ogbase.pas 117 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520
  1. {
  2. Copyright (c) 1998-2006 by Peter Vreman
  3. Contains the base stuff for binary object file writers
  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 ogbase;
  18. {$i fpcdefs.inc}
  19. interface
  20. uses
  21. { common }
  22. cutils,
  23. cclasses,
  24. { targets }
  25. systems,globtype,
  26. { outputwriters }
  27. owbase,
  28. { assembler }
  29. aasmbase;
  30. type
  31. TObjSection = class;
  32. TObjData = class;
  33. TExeSection = class;
  34. TExeSymbol = class;
  35. TExeOutput = class;
  36. TObjRelocationType = (
  37. { Relocation to absolute address }
  38. RELOC_ABSOLUTE,
  39. {$ifdef x86_64}
  40. { 32bit Relocation to absolute address }
  41. RELOC_ABSOLUTE32,
  42. { 64 bit coff only }
  43. RELOC_RELATIVE_1,
  44. RELOC_RELATIVE_2,
  45. RELOC_RELATIVE_3,
  46. RELOC_RELATIVE_4,
  47. RELOC_RELATIVE_5,
  48. { PIC }
  49. RELOC_GOTPCREL,
  50. RELOC_PLT32,
  51. {$endif x86_64}
  52. {$ifdef i386}
  53. { PIC }
  54. RELOC_GOTPC,
  55. RELOC_GOT32,
  56. RELOC_PLT32,
  57. {$endif i386}
  58. {$ifdef i8086}
  59. RELOC_ABSOLUTE32,
  60. RELOC_RELATIVE32,
  61. RELOC_FARPTR,
  62. RELOC_FARPTR_RELATIVEOFFSET,
  63. RELOC_SEG,
  64. RELOC_SEGREL,
  65. RELOC_DGROUP,
  66. RELOC_DGROUPREL,
  67. RELOC_FARDATASEG,
  68. RELOC_FARDATASEGREL,
  69. {$endif i8086}
  70. {$ifdef arm}
  71. RELOC_RELATIVE_24,
  72. RELOC_RELATIVE_CALL,
  73. RELOC_RELATIVE_24_THUMB,
  74. RELOC_RELATIVE_CALL_THUMB,
  75. RELOC_GOT32,
  76. {$endif arm}
  77. { Relative relocation }
  78. RELOC_RELATIVE,
  79. { PECoff (Windows) RVA relocation }
  80. RELOC_RVA,
  81. { PECoff (Windows) section relocation, required by DWARF2 debug info }
  82. RELOC_SECREL32,
  83. { Generate a 0 value at the place of the relocation,
  84. this is used to remove unused vtable entries }
  85. RELOC_ZERO,
  86. { No relocation is needed. It is used in ARM object files.
  87. Also internal linker use this reloc to make virtual (not real)
  88. links to some sections }
  89. RELOC_NONE,
  90. { Darwin relocation, using PAIR }
  91. RELOC_PIC_PAIR,
  92. { Relative to GOT/gp }
  93. RELOC_GOTOFF,
  94. { Untranslated target-specific value }
  95. RELOC_RAW
  96. );
  97. {$if defined(x86_64)}
  98. { no special aliases for x86_64 }
  99. {$elseif defined(i8086)}
  100. const
  101. RELOC_ABSOLUTE16 = RELOC_ABSOLUTE;
  102. RELOC_RELATIVE16 = RELOC_RELATIVE;
  103. {$else}
  104. const
  105. RELOC_ABSOLUTE32 = RELOC_ABSOLUTE;
  106. {$endif}
  107. const
  108. { stab types }
  109. N_GSYM = $20;
  110. N_STSYM = 38; { initialized const }
  111. N_LCSYM = 40; { non initialized variable}
  112. N_Function = $24; { function or const }
  113. N_TextLine = $44;
  114. N_DataLine = $46;
  115. N_BssLine = $48;
  116. N_RSYM = $40; { register variable }
  117. N_LSYM = $80;
  118. N_tsym = 160;
  119. N_SourceFile = $64;
  120. N_IncludeFile = $84;
  121. N_BINCL = $82;
  122. N_EINCL = $A2;
  123. N_LBRAC = $C0;
  124. N_EXCL = $C2;
  125. N_RBRAC = $E0;
  126. { GNU extensions }
  127. debuglinkname='.gnu_debuglink';
  128. { TObjRelocation.flags }
  129. { 'ftype' field contains platform-specific value }
  130. rf_raw = 1;
  131. { relocation must be added to dynamic list }
  132. rf_dynamic = 2;
  133. { relocation target is absent/irrelevant (e.g. R_ARM_V4BX) }
  134. rf_nosymbol = 4;
  135. type
  136. TObjSectionOption = (
  137. { Has Data available in the file }
  138. oso_Data,
  139. { Is loaded into memory }
  140. oso_load,
  141. { Writable }
  142. oso_write,
  143. { Contains executable instructions }
  144. oso_executable,
  145. { Never discard section }
  146. oso_keep,
  147. { Procedure Linkage Table specific treatment }
  148. oso_plt,
  149. { Contains debug info and can be stripped }
  150. oso_debug,
  151. { Contains only strings }
  152. oso_strings,
  153. { Must be cloned when writing separate debug file }
  154. oso_debug_copy,
  155. { Has relocations with explicit addends (ELF-specific) }
  156. oso_rela_relocs,
  157. { Supports bss-like allocation of data, even though it is written in file (i.e. also has oso_Data) }
  158. oso_sparse_data
  159. );
  160. TObjSectionOptions = set of TObjSectionOption;
  161. TObjSectionGroup = class;
  162. TObjSymbol = class(TFPHashObject)
  163. public
  164. bind : TAsmsymbind;
  165. typ : TAsmsymtype;
  166. { Current assemble pass, used to detect duplicate labels }
  167. pass : byte;
  168. { how the symbol is referenced (target-specific bitfield) }
  169. refs : byte;
  170. symidx : longint;
  171. objsection : TObjSection;
  172. offset,
  173. size : aword;
  174. { Used for external and common solving during linking }
  175. exesymbol : TExeSymbol;
  176. { Darwin asm is using indirect symbols resolving }
  177. indsymbol : TObjSymbol;
  178. { Used by the OMF object format and its complicated relocation records }
  179. group: TObjSectionGroup;
  180. {$ifdef ARM}
  181. ThumbFunc : boolean;
  182. {$endif ARM}
  183. constructor create(AList:TFPHashObjectList;const AName:string);
  184. function address:qword;
  185. procedure SetAddress(apass:byte;aobjsec:TObjSection;abind:TAsmsymbind;atyp:Tasmsymtype);
  186. function ObjData: TObjData;
  187. { string representation for the linker map file }
  188. function AddressStr(AImageBase: qword): string;virtual;
  189. end;
  190. TObjSymbolClass = class of TObjSymbol;
  191. { Stabs is common for all targets }
  192. TObjStabEntry=packed record
  193. strpos : longint;
  194. ntype : byte;
  195. nother : byte;
  196. ndesc : word;
  197. nvalue : longint;
  198. end;
  199. PObjStabEntry=^TObjStabEntry;
  200. TObjRelocation = class
  201. private
  202. function GetType:TObjRelocationType;
  203. procedure SetType(v:TObjRelocationType);
  204. public
  205. DataOffset,
  206. orgsize : aword; { COFF: original size of the symbol to relocate }
  207. { ELF: explicit addend }
  208. symbol : TObjSymbol;
  209. objsection : TObjSection; { only used if symbol=nil }
  210. group : TObjSectionGroup; { only used if symbol=nil and objsection=nil }
  211. ftype : byte;
  212. size : byte;
  213. flags : byte;
  214. constructor CreateSymbol(ADataOffset:aword;s:TObjSymbol;Atyp:TObjRelocationType);
  215. constructor CreateSection(ADataOffset:aword;aobjsec:TObjSection;Atyp:TObjRelocationType);
  216. constructor CreateGroup(ADataOffset:aword;grp:TObjSectionGroup;Atyp:TObjRelocationType);
  217. constructor CreateRaw(ADataOffset:aword;s:TObjSymbol;ARawType:byte);
  218. function TargetName:TSymStr;
  219. property typ: TObjRelocationType read GetType write SetType;
  220. end;
  221. TObjSection = class(TFPHashObject)
  222. private
  223. FData : TDynamicArray;
  224. FSecOptions : TObjSectionOptions;
  225. FCachedFullName : pshortstring;
  226. procedure SetSecOptions(Aoptions:TObjSectionOptions);
  227. procedure SectionTooLargeError;
  228. public
  229. ObjData : TObjData;
  230. index : longword; { index of section in section headers }
  231. SecSymIdx : longint; { index for the section in symtab }
  232. SecAlign : shortint; { alignment of the section }
  233. { section Data }
  234. Size,
  235. DataPos : aword;
  236. MemPos : qword;
  237. Group : TObjSectionGroup;
  238. DataAlignBytes : shortint;
  239. { Relocations (=references) to other sections }
  240. ObjRelocations : TFPObjectList;
  241. { executable linking }
  242. ExeSection : TExeSection;
  243. USed : Boolean;
  244. VTRefList : TFPObjectList;
  245. constructor create(AList:TFPHashObjectList;const Aname:string;Aalign:shortint;Aoptions:TObjSectionOptions);virtual;
  246. destructor destroy;override;
  247. function write(const d;l:aword):aword;
  248. { writes string plus zero byte }
  249. function writestr(const s:string):aword;
  250. function WriteZeros(l:longword):aword;
  251. { writes content of s without null termination }
  252. function WriteBytes(const s:string):aword;
  253. procedure writeReloc_internal(aTarget:TObjSection;offset:aword;len:byte;reltype:TObjRelocationType);virtual;
  254. function setmempos(mpos:qword):qword;
  255. procedure setDatapos(var dpos:aword);
  256. procedure alloc(l:aword);
  257. procedure addsymReloc(ofs:aword;p:TObjSymbol;Reloctype:TObjRelocationType);
  258. procedure addsectionReloc(ofs:aword;aobjsec:TObjSection;Reloctype:TObjRelocationType);
  259. procedure addrawReloc(ofs:aword;p:TObjSymbol;RawReloctype:byte);
  260. procedure ReleaseData;
  261. function FullName:string;
  262. { string representation for the linker map file }
  263. function MemPosStr(AImageBase: qword): string;virtual;
  264. property Data:TDynamicArray read FData;
  265. property SecOptions:TObjSectionOptions read FSecOptions write SetSecOptions;
  266. end;
  267. TObjSectionClass = class of TObjSection;
  268. TObjSectionGroup = class(TFPHashObject)
  269. public
  270. members: array of TObjSection;
  271. iscomdat: boolean;
  272. end;
  273. TObjSectionGroupClass = class of TObjSectionGroup;
  274. TString80 = string[80];
  275. TObjSymbolList = class(TFPHashObjectList)
  276. public
  277. Owner: TObjData;
  278. end;
  279. TObjData = class(TLinkedListItem)
  280. private
  281. FCurrObjSec : TObjSection;
  282. FObjSectionList : TFPHashObjectList;
  283. FCObjSymbol : TObjSymbolClass;
  284. FCObjSection : TObjSectionClass;
  285. FCObjSectionGroup: TObjSectionGroupClass;
  286. { Symbols that will be defined in this object file }
  287. FObjSymbolList : TObjSymbolList;
  288. FCachedAsmSymbolList : TFPObjectList;
  289. { Special info sections that are written to during object generation }
  290. FStabsObjSec,
  291. FStabStrObjSec : TObjSection;
  292. FGroupsList : TFPHashObjectList;
  293. procedure section_reset(p:TObject;arg:pointer);
  294. procedure section_afteralloc(p:TObject;arg:pointer);
  295. procedure section_afterwrite(p:TObject;arg:pointer);
  296. protected
  297. FName : TString80;
  298. property CObjSection:TObjSectionClass read FCObjSection write FCObjSection;
  299. property CObjSectionGroup: TObjSectionGroupClass read FCObjSectionGroup write FCObjSectionGroup;
  300. public
  301. CurrPass : byte;
  302. ExecStack : boolean;
  303. {$ifdef ARM}
  304. ThumbFunc : boolean;
  305. {$endif ARM}
  306. constructor create(const n:string);virtual;
  307. destructor destroy;override;
  308. { Sections }
  309. function sectionname(atype:TAsmSectiontype;const aname:string;aorder:TAsmSectionOrder):string;virtual;abstract;
  310. function sectiontype2options(atype:TAsmSectiontype):TObjSectionOptions;virtual;
  311. function sectiontype2align(atype:TAsmSectiontype):shortint;virtual;
  312. function createsection(atype:TAsmSectionType;const aname:string='';aorder:TAsmSectionOrder=secorder_default):TObjSection;virtual;
  313. function createsection(const aname:string;aalign:shortint;aoptions:TObjSectionOptions;DiscardDuplicate:boolean=true):TObjSection;virtual;
  314. function createsectiongroup(const aname:string):TObjSectionGroup;
  315. procedure CreateDebugSections;virtual;
  316. function findsection(const aname:string):TObjSection;
  317. procedure setsection(asec:TObjSection);
  318. { Symbols }
  319. function createsymbol(const aname:string):TObjSymbol;
  320. function symboldefine(asmsym:TAsmSymbol):TObjSymbol;
  321. function symboldefine(const aname:string;abind:TAsmsymbind;atyp:Tasmsymtype):TObjSymbol;
  322. function symbolref(asmsym:TAsmSymbol):TObjSymbol;
  323. function symbolref(const aname:string):TObjSymbol;
  324. procedure ResetCachedAsmSymbols;
  325. { Allocation }
  326. procedure alloc(len:aword);
  327. procedure allocalign(len:shortint);
  328. procedure writebytes(const Data;len:aword);
  329. procedure writeReloc(Data:aint;len:aword;p:TObjSymbol;Reloctype:TObjRelocationType);virtual;abstract;
  330. procedure beforealloc;virtual;
  331. procedure beforewrite;virtual;
  332. procedure afteralloc;virtual;
  333. procedure afterwrite;virtual;
  334. procedure resetsections;
  335. procedure layoutsections(var datapos:aword);
  336. property Name:TString80 read FName;
  337. property CurrObjSec:TObjSection read FCurrObjSec;
  338. property ObjSymbolList:TObjSymbolList read FObjSymbolList;
  339. property ObjSectionList:TFPHashObjectList read FObjSectionList;
  340. property GroupsList:TFPHashObjectList read FGroupsList;
  341. property StabsSec:TObjSection read FStabsObjSec write FStabsObjSec;
  342. property StabStrSec:TObjSection read FStabStrObjSec write FStabStrObjSec;
  343. property CObjSymbol: TObjSymbolClass read FCObjSymbol write FCObjSymbol;
  344. end;
  345. TObjDataClass = class of TObjData;
  346. TObjOutput = class
  347. private
  348. FCObjData : TObjDataClass;
  349. protected
  350. { writer }
  351. FWriter : TObjectwriter;
  352. function writeData(Data:TObjData):boolean;virtual;abstract;
  353. property CObjData : TObjDataClass read FCObjData write FCObjData;
  354. procedure WriteSectionContent(Data:TObjData);
  355. public
  356. constructor create(AWriter:TObjectWriter);virtual;
  357. destructor destroy;override;
  358. function newObjData(const n:string):TObjData;
  359. function startObjectfile(const fn:string):boolean;
  360. function writeobjectfile(Data:TObjData):boolean;
  361. procedure exportsymbol(p:TObjSymbol);
  362. property Writer:TObjectWriter read FWriter;
  363. end;
  364. TObjOutputClass=class of TObjOutput;
  365. TObjInput = class
  366. private
  367. FCObjData : TObjDataClass;
  368. protected
  369. { reader }
  370. FReader : TObjectReader;
  371. InputFileName : string;
  372. property CObjData : TObjDataClass read FCObjData write FCObjData;
  373. procedure ReadSectionContent(Data:TObjData);
  374. public
  375. constructor create;virtual;
  376. function ReadObjData(AReader:TObjectreader;out Data:TObjData):boolean;virtual;abstract;
  377. class function CanReadObjData(AReader:TObjectreader):boolean;virtual;
  378. procedure inputerror(const s : string);
  379. end;
  380. TObjInputClass=class of TObjInput;
  381. TVTableEntry=record
  382. ObjRelocation : TObjRelocation;
  383. orgreloctype,
  384. orgrelocflags : byte;
  385. Enabled,
  386. Used : Boolean;
  387. end;
  388. PVTableEntry=^TVTableEntry;
  389. TExeVTable = class
  390. private
  391. procedure CheckIdx(VTableIdx:longint);
  392. public
  393. ExeSymbol : TExeSymbol;
  394. EntryCnt : Longint;
  395. EntryArray : PVTableEntry;
  396. Consolidated : Boolean;
  397. ChildList : TFPObjectList;
  398. constructor Create(AExeSymbol:TExeSymbol);
  399. destructor Destroy;override;
  400. procedure AddChild(vt:TExeVTable);
  401. procedure AddEntry(VTableIdx:Longint);
  402. procedure SetVTableSize(ASize:longint);
  403. function VTableRef(VTableIdx:Longint):TObjRelocation;
  404. end;
  405. TSymbolState = (
  406. symstate_undefined,
  407. symstate_undefweak, // undefined but has only weak refs - don't complain
  408. symstate_defined,
  409. symstate_defweak,
  410. symstate_common,
  411. symstate_dynamic // a matching symbol has been seen in .so
  412. );
  413. TExeSymbol = class(TFPHashObject)
  414. ObjSymbol : TObjSymbol;
  415. State : TSymbolState;
  416. used : boolean;
  417. { Used for vmt references optimization }
  418. VTable : TExeVTable;
  419. { fields for ELF linking }
  420. gotoffset : aword;
  421. dynindex : aword;
  422. { A thunk used to redirect some references to symbol (like absolute
  423. jumps/calls to PIC code).
  424. This probably is also needed for ARM/Thumb interworking and alike.
  425. TODO: consider reusing objsymbol.indsymbol for this purpose }
  426. {$ifdef mips}
  427. stubsymbol : TObjSymbol;
  428. {$endif mips}
  429. end;
  430. TExeSection = class(TFPHashObject)
  431. private
  432. FSecSymIdx : longint;
  433. FObjSectionList : TFPObjectList;
  434. public
  435. Size,
  436. DataPos,
  437. MemPos : qword;
  438. SecAlign : shortint;
  439. Disabled : boolean;
  440. SecOptions : TObjSectionOptions;
  441. constructor create(AList:TFPHashObjectList;const AName:string);virtual;
  442. destructor destroy;override;
  443. procedure AddObjSection(objsec:TObjSection;ignoreprops:boolean=false);virtual;
  444. property ObjSectionList:TFPObjectList read FObjSectionList;
  445. property SecSymIdx:longint read FSecSymIdx write FSecSymIdx;
  446. end;
  447. TExeSectionClass=class of TExeSection;
  448. TlibKind = (lkArchive,lkObject,lkGroup);
  449. TStaticLibrary = class(TObject)
  450. private
  451. FName : TCmdStr;
  452. FPayload : TObject; { lkArchive: TObjectReader }
  453. { lkObject: TObjData }
  454. { lkGroup: TFPObjectList }
  455. FObjInputClass : TObjInputClass;
  456. FKind: TlibKind;
  457. FAsNeeded : Boolean;
  458. function GetArReader:TObjectReader;
  459. function GetGroupMembers:TFPObjectList;
  460. function GetObjData:TObjData;
  461. public
  462. constructor create(const AName:TCmdStr;AReader:TObjectReader;AObjInputClass:TObjInputClass);
  463. constructor create_object(AObjData:TObjData);
  464. constructor create_group;
  465. destructor destroy;override;
  466. property ArReader:TObjectReader read GetArReader;
  467. property ObjInputClass:TObjInputClass read FObjInputClass;
  468. property GroupMembers:TFPObjectList read GetGroupMembers;
  469. property ObjData:TObjData read GetObjData;
  470. property AsNeeded:Boolean read FAsNeeded write FAsNeeded;
  471. property Kind:TLibKind read FKind;
  472. end;
  473. TImportLibrary = class(TFPHashObject)
  474. private
  475. FImportSymbolList : TFPHashObjectList;
  476. public
  477. constructor create(AList:TFPHashObjectList;const AName:string);
  478. destructor destroy;override;
  479. property ImportSymbolList:TFPHashObjectList read FImportSymbolList;
  480. end;
  481. TImportSymbol = class(TFPHashObject)
  482. private
  483. FOrdNr : longint;
  484. FIsVar : boolean;
  485. FMangledName : string;
  486. FCachedExeSymbol: TExeSymbol;
  487. public
  488. constructor create(AList:TFPHashObjectList;const AName,AMangledName:string;AOrdNr:longint;AIsVar:boolean);
  489. property OrdNr: longint read FOrdNr;
  490. property MangledName: string read FMangledName;
  491. property IsVar: boolean read FIsVar;
  492. property CachedExeSymbol: TExeSymbol read FCachedExeSymbol write FCachedExeSymbol;
  493. end;
  494. TExeWriteMode = (ewm_exefull,ewm_dbgonly,ewm_exeonly);
  495. TExeOutput = class
  496. private
  497. { ExeSectionList }
  498. FCObjSymbol : TObjSymbolClass;
  499. FCObjData : TObjDataClass;
  500. FCExeSection : TExeSectionClass;
  501. FCurrExeSec : TExeSection;
  502. FExeSectionList : TFPHashObjectList;
  503. Fzeronr : longint;
  504. Fvaluesnr : longint;
  505. { Symbols }
  506. FExeSymbolList : TFPHashObjectList;
  507. FUnresolvedExeSymbols : TFPObjectList;
  508. FExternalObjSymbols,
  509. FCommonObjSymbols : TFPObjectList;
  510. FProvidedObjSymbols : TFPObjectList;
  511. FIndirectObjSymbols : TFPObjectList;
  512. FEntryName : string;
  513. FExeVTableList : TFPObjectList;
  514. { Objects }
  515. FObjDataList : TFPObjectList;
  516. { Position calculation }
  517. FImageBase : aword;
  518. FCurrMemPos : qword;
  519. procedure SetCurrMemPos(const AValue: qword);
  520. protected
  521. { writer }
  522. FExeWriteMode : TExeWriteMode;
  523. FWriter : TObjectwriter;
  524. commonObjSection : TObjSection;
  525. internalObjData : TObjData;
  526. EntrySym : TObjSymbol;
  527. SectionDataAlign,
  528. SectionMemAlign : aword;
  529. ComdatGroups : TFPHashList;
  530. FixedSectionAlign : boolean;
  531. AllowUndefinedSymbols : boolean;
  532. function writeData:boolean;virtual;abstract;
  533. property CExeSection:TExeSectionClass read FCExeSection write FCExeSection;
  534. property CObjData:TObjDataClass read FCObjData write FCObjData;
  535. property CObjSymbol:TObjSymbolClass read FCObjSymbol write FCObjSymbol;
  536. procedure Order_ObjSectionList(ObjSectionList : TFPObjectList; const aPattern:string);virtual;
  537. procedure WriteExeSectionContent;
  538. procedure DoRelocationFixup(objsec:TObjSection);virtual;abstract;
  539. function MemAlign(exesec: TExeSection): longword;
  540. function DataAlign(exesec: TExeSection): longword;
  541. procedure ReplaceExeSectionList(newlist: TFPList);
  542. public
  543. CurrDataPos : aword;
  544. MaxMemPos : qword;
  545. IsSharedLibrary : boolean;
  546. ExecStack : boolean;
  547. constructor create;virtual;
  548. destructor destroy;override;
  549. function FindExeSection(const aname:string):TExeSection;
  550. procedure AddObjData(ObjData:TObjData);
  551. procedure Load_Start;virtual;
  552. procedure Load_EntryName(const aname:string);virtual;
  553. procedure Load_Symbol(const aname:string);virtual;
  554. procedure Load_ProvideSymbol(const aname:string);virtual;
  555. procedure Load_IsSharedLibrary;
  556. procedure Load_ImageBase(const avalue:string);
  557. procedure Load_DynamicObject(ObjData:TObjData;asneeded:boolean);virtual;
  558. procedure Order_Start;virtual;
  559. procedure Order_End;virtual;
  560. procedure Order_ExeSection(const aname:string);virtual;
  561. procedure Order_Align(const avalue:string);virtual;
  562. procedure Order_Zeros(const avalue:string);virtual;
  563. procedure Order_Values(bytesize : aword; const avalue:string);virtual;
  564. procedure Order_Symbol(const aname:string);virtual;
  565. procedure Order_ProvideSymbol(const aname:string);virtual;
  566. procedure Order_EndExeSection;virtual;
  567. procedure Order_ObjSection(const aname:string);virtual;
  568. procedure MemPos_Start;virtual;
  569. procedure MemPos_Header;virtual;
  570. procedure MemPos_ExeSection(exesec:TExeSection);
  571. procedure MemPos_ExeSection(const aname:string);virtual;
  572. procedure MemPos_EndExeSection;virtual;
  573. procedure DataPos_Start;virtual;
  574. procedure DataPos_Header;virtual;
  575. procedure DataPos_ExeSection(exesec:TExeSection);
  576. procedure DataPos_ExeSection(const aname:string);virtual;
  577. procedure DataPos_EndExeSection;virtual;
  578. procedure DataPos_Symbols;virtual;
  579. procedure BuildVTableTree(VTInheritList,VTEntryList:TFPObjectList);
  580. procedure PackUnresolvedExeSymbols(const s:string);
  581. procedure ResolveSymbols(StaticLibraryList:TFPObjectList);
  582. procedure PrintMemoryMap;
  583. procedure FixupSymbols;
  584. procedure FixupRelocations;virtual;
  585. procedure RemoveUnusedExeSymbols;
  586. procedure MergeStabs;
  587. procedure MarkEmptySections;
  588. procedure RemoveUnreferencedSections;
  589. procedure RemoveDisabledSections;
  590. procedure RemoveDebugInfo;
  591. procedure MarkTargetSpecificSections(WorkList:TFPObjectList);virtual;
  592. procedure AfterUnusedSectionRemoval;virtual;
  593. procedure GenerateLibraryImports(ImportLibraryList:TFPHashObjectList);virtual;
  594. procedure GenerateDebugLink(const dbgname:string;dbgcrc:cardinal);
  595. function WriteExeFile(const fn:string):boolean;
  596. procedure ParseScript (linkscript:TCmdStrList); virtual;
  597. property Writer:TObjectWriter read FWriter;
  598. property ExeSectionList:TFPHashObjectList read FExeSectionList;
  599. property ObjDataList:TFPObjectList read FObjDataList;
  600. property ExeSymbolList:TFPHashObjectList read FExeSymbolList;
  601. property UnresolvedExeSymbols:TFPObjectList read FUnresolvedExeSymbols;
  602. property ExternalObjSymbols:TFPObjectList read FExternalObjSymbols;
  603. property CommonObjSymbols:TFPObjectList read FCommonObjSymbols;
  604. property IndirectObjSymbols:TFPObjectList read FIndirectObjSymbols;
  605. property ExeVTableList:TFPObjectList read FExeVTableList;
  606. property EntryName:string read FEntryName write FEntryName;
  607. property ImageBase:aword read FImageBase write FImageBase;
  608. property CurrExeSec:TExeSection read FCurrExeSec;
  609. property ExeWriteMode:TExeWriteMode read FExeWriteMode write FExeWriteMode;
  610. property CurrMemPos:qword read FCurrMemPos write SetCurrMemPos;
  611. end;
  612. TExeOutputClass=class of TExeOutput;
  613. var
  614. exeoutput : TExeOutput;
  615. function align_aword(v:aword;a:longword):aword;
  616. function align_qword(v:qword;a:longword):qword;
  617. implementation
  618. uses
  619. SysUtils,
  620. globals,verbose,fmodule,ogmap;
  621. const
  622. SectionDataMaxGrow = 4096;
  623. {$ifdef MEMDEBUG}
  624. var
  625. memobjsymbols,
  626. memobjsections : TMemDebug;
  627. {$endif MEMDEBUG}
  628. {*****************************************************************************
  629. Helpers
  630. *****************************************************************************}
  631. function align_aword(v:aword;a:longword):aword;
  632. begin
  633. if a<=1 then
  634. result:=v
  635. else
  636. result:=((v+a-1) div a) * a;
  637. end;
  638. function align_qword(v:qword;a:longword):qword;
  639. begin
  640. if a<=1 then
  641. result:=v
  642. else
  643. result:=((v+a-1) div a) * a;
  644. end;
  645. procedure MaybeSwapStab(var v:TObjStabEntry);
  646. begin
  647. if source_info.endian<>target_info.endian then
  648. begin
  649. v.strpos:=SwapEndian(v.strpos);
  650. v.nvalue:=SwapEndian(v.nvalue);
  651. v.ndesc:=SwapEndian(v.ndesc);
  652. end;
  653. end;
  654. {*****************************************************************************
  655. TObjSymbol
  656. *****************************************************************************}
  657. constructor TObjSymbol.create(AList:TFPHashObjectList;const AName:string);
  658. begin
  659. inherited create(AList,AName);
  660. bind:=AB_EXTERNAL;
  661. typ:=AT_NONE;
  662. symidx:=-1;
  663. size:=0;
  664. offset:=0;
  665. objsection:=nil;
  666. end;
  667. function TObjSymbol.address:qword;
  668. begin
  669. if assigned(objsection) then
  670. result:=offset+objsection.mempos
  671. else
  672. result:=0;
  673. end;
  674. procedure TObjSymbol.SetAddress(apass:byte;aobjsec:TObjSection;abind:TAsmsymbind;atyp:Tasmsymtype);
  675. begin
  676. if not(abind in [AB_GLOBAL,AB_LOCAL,AB_COMMON,AB_IMPORT]) then
  677. internalerror(200603016);
  678. if not assigned(aobjsec) then
  679. internalerror(200603017);
  680. if (bind in [AB_EXTERNAL,AB_LAZY]) or
  681. { Put all COMMON to GLOBAL in step 3 of
  682. TExeOutput.ResolveSymbols }
  683. ((abind=AB_GLOBAL) and (bind=AB_COMMON)) then
  684. begin
  685. { Do not change the AB_TYPE of common symbols yet }
  686. { This will be done in FixupSymbols }
  687. if (pass<>0) or (bind<>AB_COMMON) then
  688. bind:=abind;
  689. typ:=atyp;
  690. end
  691. else
  692. begin
  693. if pass=apass then
  694. begin
  695. Message1(asmw_e_duplicate_label,name);
  696. exit;
  697. end;
  698. end;
  699. pass:=apass;
  700. { Code can never grow after a pass }
  701. if assigned(objsection) and
  702. (objsection=aobjsec) and
  703. (aobjsec.size>offset) then
  704. internalerror(200603014);
  705. objsection:=aobjsec;
  706. offset:=aobjsec.size;
  707. end;
  708. function TObjSymbol.ObjData: TObjData;
  709. begin
  710. result:=(OwnerList as TObjSymbolList).Owner;
  711. end;
  712. function TObjSymbol.AddressStr(AImageBase: qword): string;
  713. begin
  714. Result:='0x'+HexStr(address+Aimagebase,sizeof(pint)*2);
  715. end;
  716. {****************************************************************************
  717. TObjRelocation
  718. ****************************************************************************}
  719. constructor TObjRelocation.CreateSymbol(ADataOffset:aword;s:TObjSymbol;Atyp:TObjRelocationType);
  720. begin
  721. if not assigned(s) then
  722. internalerror(200603034);
  723. DataOffset:=ADataOffset;
  724. Symbol:=s;
  725. OrgSize:=0;
  726. Group:=nil;
  727. ObjSection:=nil;
  728. ftype:=ord(Atyp);
  729. end;
  730. constructor TObjRelocation.CreateSection(ADataOffset:aword;aobjsec:TObjSection;Atyp:TObjRelocationType);
  731. begin
  732. if not assigned(aobjsec) then
  733. internalerror(200603036);
  734. DataOffset:=ADataOffset;
  735. Symbol:=nil;
  736. OrgSize:=0;
  737. Group:=nil;
  738. ObjSection:=aobjsec;
  739. ftype:=ord(Atyp);
  740. end;
  741. constructor TObjRelocation.CreateGroup(ADataOffset:aword;grp:TObjSectionGroup;Atyp:TObjRelocationType);
  742. begin
  743. if not assigned(grp) then
  744. internalerror(2015111201);
  745. DataOffset:=ADataOffset;
  746. Symbol:=nil;
  747. ObjSection:=nil;
  748. OrgSize:=0;
  749. Group:=grp;
  750. ftype:=ord(Atyp);
  751. end;
  752. constructor TObjRelocation.CreateRaw(ADataOffset:aword;s:TObjSymbol;ARawType:byte);
  753. begin
  754. { nil symbol is allowed here }
  755. DataOffset:=ADataOffset;
  756. Symbol:=s;
  757. ObjSection:=nil;
  758. Group:=nil;
  759. orgsize:=0;
  760. ftype:=ARawType;
  761. flags:=rf_raw;
  762. end;
  763. function TObjRelocation.GetType:TObjRelocationType;
  764. begin
  765. if (flags and rf_raw)=0 then
  766. result:=TObjRelocationType(ftype)
  767. else
  768. result:=RELOC_RAW;
  769. end;
  770. procedure TObjRelocation.SetType(v:TObjRelocationType);
  771. begin
  772. ftype:=ord(v);
  773. flags:=flags and (not rf_raw);
  774. end;
  775. function TObjRelocation.TargetName:TSymStr;
  776. begin
  777. if assigned(symbol) then
  778. if symbol.typ=AT_SECTION then
  779. result:=symbol.objsection.name
  780. else
  781. result:=symbol.Name
  782. else
  783. result:=objsection.Name;
  784. end;
  785. {****************************************************************************
  786. TObjSection
  787. ****************************************************************************}
  788. constructor TObjSection.create(AList:TFPHashObjectList;const Aname:string;Aalign:shortint;Aoptions:TObjSectionOptions);
  789. begin
  790. inherited Create(AList,Aname);
  791. { Data }
  792. Size:=0;
  793. Datapos:=0;
  794. mempos:=0;
  795. FData:=Nil;
  796. { Setting the secoptions allocates Data if needed }
  797. secoptions:=Aoptions;
  798. secalign:=Aalign;
  799. secsymidx:=0;
  800. { relocation }
  801. ObjRelocations:=TFPObjectList.Create(true);
  802. VTRefList:=TFPObjectList.Create(false);
  803. end;
  804. destructor TObjSection.destroy;
  805. begin
  806. if assigned(Data) then
  807. Data.Free;
  808. stringdispose(FCachedFullName);
  809. ObjRelocations.Free;
  810. VTRefList.Free;
  811. inherited destroy;
  812. end;
  813. procedure TObjSection.SetSecOptions(Aoptions:TObjSectionOptions);
  814. begin
  815. FSecOptions:=FSecOptions+AOptions;
  816. if (oso_Data in secoptions) and
  817. not assigned(FData) then
  818. FData:=TDynamicArray.Create(SectionDataMaxGrow);
  819. end;
  820. procedure TObjSection.SectionTooLargeError;
  821. begin
  822. if oso_executable in SecOptions then
  823. Message(asmw_f_code_segment_too_large)
  824. else
  825. Message(asmw_f_data_segment_too_large);
  826. end;
  827. function TObjSection.write(const d;l:aword):aword;
  828. begin
  829. result:=size;
  830. if assigned(Data) then
  831. begin
  832. if Size<>Data.size then
  833. internalerror(200602281);
  834. {$ifndef cpu64bitalu}
  835. if (qword(size)+l)>high(size) then
  836. SectionTooLargeError;
  837. {$endif}
  838. Data.write(d,l);
  839. inc(Size,l);
  840. end
  841. else
  842. internalerror(200602289);
  843. end;
  844. function TObjSection.writestr(const s:string):aword;
  845. var
  846. b: byte;
  847. begin
  848. result:=Write(s[1],length(s));
  849. b:=0;
  850. Write(b,1);
  851. end;
  852. function TObjSection.WriteBytes(const s:string):aword;
  853. begin
  854. result:=Write(s[1],length(s));
  855. end;
  856. function TObjSection.WriteZeros(l:longword):aword;
  857. var
  858. empty : array[0..1023] of byte;
  859. begin
  860. result:=Size;
  861. if l>sizeof(empty) then
  862. begin
  863. fillchar(empty,sizeof(empty),0);
  864. while l>sizeof(empty) do
  865. begin
  866. Write(empty,sizeof(empty));
  867. Dec(l,sizeof(empty));
  868. end;
  869. if l>0 then
  870. Write(empty,l);
  871. end
  872. else if l>0 then
  873. begin
  874. fillchar(empty,l,0);
  875. Write(empty,l);
  876. end;
  877. end;
  878. { Writes relocation to (section+offset) without need to have a symbol at that location.
  879. Not an abstract method because not every backend needs this functionality. }
  880. procedure TObjSection.writeReloc_internal(aTarget:TObjSection;offset:aword;len:byte;reltype:TObjRelocationType);
  881. begin
  882. InternalError(2012081501);
  883. end;
  884. procedure TObjSection.setDatapos(var dpos:aword);
  885. begin
  886. if oso_Data in secoptions then
  887. begin
  888. { get aligned Datapos }
  889. Datapos:=align_aword(dpos,secalign);
  890. Dataalignbytes:=Datapos-dpos;
  891. { return updated Datapos }
  892. dpos:=Datapos+size;
  893. end
  894. else
  895. Datapos:=dpos;
  896. end;
  897. function TObjSection.setmempos(mpos:qword):qword;
  898. begin
  899. mempos:=align_qword(mpos,secalign);
  900. { return updated mempos }
  901. result:=mempos+size;
  902. end;
  903. procedure TObjSection.alloc(l:aword);
  904. begin
  905. {$ifndef cpu64bitalu}
  906. if (qword(size)+l)>high(size) then
  907. SectionTooLargeError;
  908. {$endif}
  909. if oso_sparse_data in SecOptions then
  910. WriteZeros(l)
  911. else
  912. inc(size,l);
  913. end;
  914. procedure TObjSection.addsymReloc(ofs:aword;p:TObjSymbol;Reloctype:TObjRelocationType);
  915. begin
  916. ObjRelocations.Add(TObjRelocation.CreateSymbol(ofs,p,reloctype));
  917. end;
  918. procedure TObjSection.addsectionReloc(ofs:aword;aobjsec:TObjSection;Reloctype:TObjRelocationType);
  919. begin
  920. ObjRelocations.Add(TObjRelocation.CreateSection(ofs,aobjsec,reloctype));
  921. end;
  922. procedure TObjSection.addrawReloc(ofs:aword;p:TObjSymbol;RawReloctype:byte);
  923. begin
  924. ObjRelocations.Add(TObjRelocation.CreateRaw(ofs,p,RawReloctype));
  925. end;
  926. procedure TObjSection.ReleaseData;
  927. begin
  928. if assigned(FData) then
  929. begin
  930. FData.free;
  931. FData:=nil;
  932. end;
  933. ObjRelocations.free;
  934. ObjRelocations:=nil;
  935. if assigned(FCachedFullName) then
  936. begin
  937. stringdispose(FCachedFullName);
  938. FCachedFullName:=nil;
  939. end;
  940. end;
  941. function TObjSection.FullName:string;
  942. begin
  943. if not assigned(FCachedFullName) then
  944. begin
  945. if assigned(ObjData) then
  946. FCachedFullName:=stringdup(ObjData.Name+'('+Name+')')
  947. else
  948. FCachedFullName:=stringdup(Name);
  949. end;
  950. result:=FCachedFullName^;
  951. end;
  952. function TObjSection.MemPosStr(AImageBase: qword): string;
  953. begin
  954. result:='0x'+HexStr(mempos+AImageBase,sizeof(pint)*2);
  955. end;
  956. {****************************************************************************
  957. TObjData
  958. ****************************************************************************}
  959. constructor TObjData.create(const n:string);
  960. begin
  961. inherited create;
  962. FName:=ExtractFileName(n);
  963. FObjSectionList:=TFPHashObjectList.Create(true);
  964. FStabsObjSec:=nil;
  965. FStabStrObjSec:=nil;
  966. { symbols }
  967. FCObjSymbol:=TObjSymbol;
  968. FObjSymbolList:=TObjSymbolList.Create(true);
  969. FObjSymbolList.Owner:=Self;
  970. FCachedAsmSymbolList:=TFPObjectList.Create(false);
  971. { section class type for creating of new sections }
  972. FCObjSection:=TObjSection;
  973. FCObjSectionGroup:=TObjSectionGroup;
  974. {$ifdef ARM}
  975. ThumbFunc:=false;
  976. {$endif ARM}
  977. end;
  978. destructor TObjData.destroy;
  979. begin
  980. { Symbols }
  981. {$ifdef MEMDEBUG}
  982. MemObjSymbols.Start;
  983. {$endif}
  984. ResetCachedAsmSymbols;
  985. FCachedAsmSymbolList.free;
  986. FObjSymbolList.free;
  987. {$ifdef MEMDEBUG}
  988. MemObjSymbols.Stop;
  989. {$endif}
  990. GroupsList.free;
  991. { Sections }
  992. {$ifdef MEMDEBUG}
  993. MemObjSections.Start;
  994. {$endif}
  995. FObjSectionList.free;
  996. {$ifdef MEMDEBUG}
  997. MemObjSections.Stop;
  998. {$endif}
  999. inherited destroy;
  1000. end;
  1001. function TObjData.sectiontype2options(atype:TAsmSectiontype):TObjSectionOptions;
  1002. const
  1003. secoptions : array[TAsmSectiontype] of TObjSectionOptions = ([],
  1004. {user} [oso_Data,oso_load,oso_write],
  1005. {code} [oso_Data,oso_load,oso_executable],
  1006. {Data} [oso_Data,oso_load,oso_write],
  1007. { Readonly data with relocations must be initially writable for some targets.
  1008. Moreover, e.g. for ELF it depends on whether the executable is linked statically or
  1009. dynamically. Here we declare it writable, target-specific descendants must provide
  1010. further handling. }
  1011. {roData} [oso_Data,oso_load,oso_write],
  1012. {roData_norel} [oso_Data,oso_load],
  1013. {bss} [oso_load,oso_write],
  1014. {threadvar} [oso_load,oso_write],
  1015. {pdata} [oso_data,oso_load],
  1016. {stub} [oso_Data,oso_load,oso_executable],
  1017. {data_nonlazy} [oso_Data,oso_load,oso_write],
  1018. {data_lazy} [oso_Data,oso_load,oso_write],
  1019. {init_func} [oso_Data,oso_load],
  1020. {term_func} [oso_Data,oso_load],
  1021. {stab} [oso_Data,oso_debug],
  1022. {stabstr} [oso_Data,oso_strings,oso_debug],
  1023. {iData2} [oso_Data,oso_load,oso_write],
  1024. {iData4} [oso_Data,oso_load,oso_write],
  1025. {iData5} [oso_Data,oso_load,oso_write],
  1026. {iData6} [oso_Data,oso_load,oso_write],
  1027. {iData7} [oso_Data,oso_load,oso_write],
  1028. {eData} [oso_Data,oso_load],
  1029. {eh_frame} [oso_Data,oso_load],
  1030. {debug_frame} [oso_Data,oso_debug],
  1031. {debug_info} [oso_Data,oso_debug],
  1032. {debug_line} [oso_Data,oso_debug],
  1033. {debug_abbrev} [oso_Data,oso_debug],
  1034. {fpc} [oso_Data,oso_load,oso_write],
  1035. {toc} [oso_Data,oso_load],
  1036. {init} [oso_Data,oso_load,oso_executable],
  1037. {fini} [oso_Data,oso_load,oso_executable],
  1038. {objc_class} [oso_data,oso_load],
  1039. {objc_meta_class} [oso_data,oso_load],
  1040. {objc_cat_cls_meth} [oso_data,oso_load],
  1041. {objc_cat_inst_meth} [oso_data,oso_load],
  1042. {objc_protocol} [oso_data,oso_load],
  1043. {objc_string_object} [oso_data,oso_load],
  1044. {objc_cls_meth} [oso_data,oso_load],
  1045. {objc_inst_meth} [oso_data,oso_load],
  1046. {objc_cls_refs} [oso_data,oso_load],
  1047. {objc_message_refs} [oso_data,oso_load],
  1048. {objc_symbols} [oso_data,oso_load],
  1049. {objc_category} [oso_data,oso_load],
  1050. {objc_class_vars} [oso_data,oso_load],
  1051. {objc_instance_vars} [oso_data,oso_load],
  1052. {objc_module_info} [oso_data,oso_load],
  1053. {objc_class_names} [oso_data,oso_load],
  1054. {objc_meth_var_types} [oso_data,oso_load],
  1055. {objc_meth_var_names} [oso_data,oso_load],
  1056. {objc_selector_strs} [oso_data,oso_load],
  1057. {objc_protocol_ext} [oso_data,oso_load],
  1058. {objc_class_ext} [oso_data,oso_load],
  1059. {objc_property} [oso_data,oso_load],
  1060. {objc_image_info} [oso_data,oso_load],
  1061. {objc_cstring_object} [oso_data,oso_load],
  1062. {objc_sel_fixup} [oso_data,oso_load],
  1063. {sec_objc_data} [oso_data,oso_load],
  1064. {sec_objc_const} [oso_data,oso_load],
  1065. {sec_objc_sup_refs} [oso_data,oso_load],
  1066. {sec_data_coalesced} [oso_data,oso_load],
  1067. {sec_objc_classlist} [oso_data,oso_load],
  1068. {sec_objc_nlclasslist} [oso_data,oso_load],
  1069. {sec_objc_catlist} [oso_data,oso_load],
  1070. {sec_objc_nlcatlist} [oso_data,oso_load],
  1071. {sec_objc_protolist'} [oso_data,oso_load],
  1072. {stack} [oso_load,oso_write],
  1073. {heap} [oso_load,oso_write]
  1074. );
  1075. begin
  1076. result:=secoptions[atype];
  1077. end;
  1078. function TObjData.sectiontype2align(atype:TAsmSectiontype):shortint;
  1079. begin
  1080. case atype of
  1081. sec_stabstr,sec_debug_info,sec_debug_line,sec_debug_abbrev:
  1082. result:=1;
  1083. sec_code,
  1084. sec_bss,
  1085. sec_data:
  1086. result:=16;
  1087. { For idata (at least idata2) it must be 4 bytes, because
  1088. an entry is always (also in win64) 20 bytes and aligning
  1089. on 8 bytes will insert 4 bytes between the entries resulting
  1090. in a corrupt idata section.
  1091. Same story with .pdata, it has 4-byte elements which should
  1092. be packed without gaps. }
  1093. sec_idata2,sec_idata4,sec_idata5,sec_idata6,sec_idata7,sec_pdata:
  1094. result:=4;
  1095. else
  1096. result:=sizeof(pint);
  1097. end;
  1098. end;
  1099. function TObjData.createsection(atype:TAsmSectionType;const aname:string;aorder:TAsmSectionOrder):TObjSection;
  1100. begin
  1101. result:=createsection(sectionname(atype,aname,aorder),sectiontype2align(atype),sectiontype2options(atype));
  1102. end;
  1103. function TObjData.createsection(const aname:string;aalign:shortint;aoptions:TObjSectionOptions;DiscardDuplicate:boolean):TObjSection;
  1104. begin
  1105. if DiscardDuplicate then
  1106. result:=TObjSection(FObjSectionList.Find(aname))
  1107. else
  1108. result:=nil;
  1109. if not assigned(result) then
  1110. begin
  1111. result:=CObjSection.create(FObjSectionList,aname,aalign,aoptions);
  1112. result.ObjData:=self;
  1113. end;
  1114. FCurrObjSec:=result;
  1115. end;
  1116. function TObjData.CreateSectionGroup(const aname:string):TObjSectionGroup;
  1117. begin
  1118. if FGroupsList=nil then
  1119. FGroupsList:=TFPHashObjectList.Create(true);
  1120. result:=CObjSectionGroup.Create(FGroupsList,aname);
  1121. end;
  1122. procedure TObjData.CreateDebugSections;
  1123. begin
  1124. end;
  1125. function TObjData.FindSection(const aname:string):TObjSection;
  1126. begin
  1127. result:=TObjSection(FObjSectionList.Find(aname));
  1128. end;
  1129. procedure TObjData.setsection(asec:TObjSection);
  1130. begin
  1131. if asec.ObjData<>self then
  1132. internalerror(200403041);
  1133. FCurrObjSec:=asec;
  1134. end;
  1135. function TObjData.createsymbol(const aname:string):TObjSymbol;
  1136. begin
  1137. result:=TObjSymbol(FObjSymbolList.Find(aname));
  1138. if not assigned(result) then
  1139. result:=CObjSymbol.Create(FObjSymbolList,aname);
  1140. {$ifdef ARM}
  1141. result.ThumbFunc:=ThumbFunc;
  1142. ThumbFunc:=false;
  1143. {$endif ARM}
  1144. end;
  1145. function TObjData.symboldefine(asmsym:TAsmSymbol):TObjSymbol;
  1146. begin
  1147. if assigned(asmsym) then
  1148. begin
  1149. if not assigned(asmsym.cachedObjSymbol) then
  1150. begin
  1151. result:=symboldefine(asmsym.name,asmsym.bind,asmsym.typ);
  1152. asmsym.cachedObjSymbol:=result;
  1153. FCachedAsmSymbolList.add(asmsym);
  1154. end
  1155. else
  1156. begin
  1157. result:=TObjSymbol(asmsym.cachedObjSymbol);
  1158. result.SetAddress(CurrPass,CurrObjSec,asmsym.bind,asmsym.typ);
  1159. end;
  1160. end
  1161. else
  1162. result:=nil;
  1163. end;
  1164. function TObjData.symboldefine(const aname:string;abind:TAsmsymbind;atyp:Tasmsymtype):TObjSymbol;
  1165. begin
  1166. if not assigned(CurrObjSec) then
  1167. internalerror(200603051);
  1168. result:=CreateSymbol(aname);
  1169. result.SetAddress(CurrPass,CurrObjSec,abind,atyp);
  1170. end;
  1171. function TObjData.symbolref(asmsym:TAsmSymbol):TObjSymbol;
  1172. var
  1173. s:string;
  1174. begin
  1175. if assigned(asmsym) then
  1176. begin
  1177. if not assigned(asmsym.cachedObjSymbol) then
  1178. begin
  1179. s:=asmsym.name;
  1180. result:=TObjSymbol(FObjSymbolList.Find(s));
  1181. if result=nil then
  1182. begin
  1183. result:=CObjSymbol.Create(FObjSymbolList,s);
  1184. if asmsym.bind=AB_WEAK_EXTERNAL then
  1185. result.bind:=AB_WEAK_EXTERNAL;
  1186. end;
  1187. asmsym.cachedObjSymbol:=result;
  1188. FCachedAsmSymbolList.add(asmsym);
  1189. end
  1190. else
  1191. result:=TObjSymbol(asmsym.cachedObjSymbol);
  1192. { The weak bit could have been removed from asmsym. }
  1193. if (asmsym.bind=AB_EXTERNAL) and (result.bind=AB_WEAK_EXTERNAL) then
  1194. result.bind:=AB_EXTERNAL;
  1195. end
  1196. else
  1197. result:=nil;
  1198. end;
  1199. function TObjData.symbolref(const aname:string):TObjSymbol;
  1200. begin
  1201. if not assigned(CurrObjSec) then
  1202. internalerror(200603052);
  1203. result:=CreateSymbol(aname);
  1204. end;
  1205. procedure TObjData.ResetCachedAsmSymbols;
  1206. var
  1207. i : longint;
  1208. begin
  1209. for i:=0 to FCachedAsmSymbolList.Count-1 do
  1210. tasmsymbol(FCachedAsmSymbolList[i]).cachedObjSymbol:=nil;
  1211. FCachedAsmSymbolList.Clear;
  1212. end;
  1213. procedure TObjData.writebytes(const Data;len:aword);
  1214. begin
  1215. if not assigned(CurrObjSec) then
  1216. internalerror(200402251);
  1217. CurrObjSec.write(Data,len);
  1218. end;
  1219. procedure TObjData.alloc(len:aword);
  1220. begin
  1221. if not assigned(CurrObjSec) then
  1222. internalerror(200402252);
  1223. CurrObjSec.alloc(len);
  1224. end;
  1225. procedure TObjData.allocalign(len:shortint);
  1226. begin
  1227. if not assigned(CurrObjSec) then
  1228. internalerror(200402253);
  1229. CurrObjSec.alloc(align_aword(CurrObjSec.size,len)-CurrObjSec.size);
  1230. end;
  1231. procedure TObjData.section_afteralloc(p:TObject;arg:pointer);
  1232. begin
  1233. with TObjSection(p) do
  1234. alloc(align_aword(size,secalign)-size);
  1235. end;
  1236. procedure TObjData.section_afterwrite(p:TObject;arg:pointer);
  1237. begin
  1238. with TObjSection(p) do
  1239. begin
  1240. if assigned(Data) then
  1241. writezeros(align_aword(size,secalign)-size);
  1242. end;
  1243. end;
  1244. procedure TObjData.section_reset(p:TObject;arg:pointer);
  1245. begin
  1246. with TObjSection(p) do
  1247. begin
  1248. Size:=0;
  1249. Datapos:=0;
  1250. mempos:=0;
  1251. if assigned(Data) then
  1252. Data.reset;
  1253. end;
  1254. end;
  1255. procedure TObjData.beforealloc;
  1256. begin
  1257. { create stabs sections if debugging }
  1258. if assigned(StabsSec) then
  1259. begin
  1260. StabsSec.Alloc(sizeof(TObjStabEntry));
  1261. StabStrSec.Alloc(1);
  1262. end;
  1263. end;
  1264. procedure TObjData.beforewrite;
  1265. begin
  1266. { create stabs sections if debugging }
  1267. if assigned(StabsSec) then
  1268. begin
  1269. { Create dummy HdrSym stab, it will be overwritten in AfterWrite }
  1270. StabsSec.WriteZeros(sizeof(TObjStabEntry));
  1271. { start of stabstr }
  1272. StabStrSec.writeZeros(1);
  1273. end;
  1274. end;
  1275. procedure TObjData.afteralloc;
  1276. begin
  1277. FObjSectionList.ForEachCall(@section_afteralloc,nil);
  1278. end;
  1279. procedure TObjData.afterwrite;
  1280. var
  1281. hstab : TObjStabEntry;
  1282. begin
  1283. FObjSectionList.ForEachCall(@section_afterwrite,nil);
  1284. { For the stab section we need an HdrSym which can now be
  1285. calculated more easily }
  1286. if assigned(StabsSec) then
  1287. begin
  1288. { end of stabstr }
  1289. StabStrSec.writeZeros(1);
  1290. { header stab }
  1291. hstab.strpos:=1;
  1292. hstab.ntype:=0;
  1293. hstab.nother:=0;
  1294. {$push}{$R-}
  1295. { for jwawindows.pas, this causes an range check error, it contains too much stab symbols }
  1296. hstab.ndesc:=(StabsSec.Size div sizeof(TObjStabEntry))-1;
  1297. {$pop}
  1298. hstab.nvalue:=StabStrSec.Size;
  1299. MaybeSwapStab(hstab);
  1300. StabsSec.Data.seek(0);
  1301. StabsSec.Data.write(hstab,sizeof(hstab));
  1302. end;
  1303. end;
  1304. procedure TObjData.resetsections;
  1305. begin
  1306. FObjSectionList.ForEachCall(@section_reset,nil);
  1307. end;
  1308. procedure TObjData.layoutsections(var DataPos:aword);
  1309. var
  1310. i: longint;
  1311. begin
  1312. for i:=0 to FObjSectionList.Count-1 do
  1313. TObjSection(FObjSectionList[i]).setDatapos(DataPos);
  1314. end;
  1315. {****************************************************************************
  1316. TObjOutput
  1317. ****************************************************************************}
  1318. constructor TObjOutput.create(AWriter:TObjectWriter);
  1319. begin
  1320. FWriter:=AWriter;
  1321. CObjData:=TObjData;
  1322. end;
  1323. destructor TObjOutput.destroy;
  1324. begin
  1325. inherited destroy;
  1326. end;
  1327. function TObjOutput.newObjData(const n:string):TObjData;
  1328. begin
  1329. result:=CObjData.create(n);
  1330. if (cs_use_lineinfo in current_settings.globalswitches) or
  1331. (cs_debuginfo in current_settings.moduleswitches) then
  1332. result.CreateDebugSections;
  1333. end;
  1334. function TObjOutput.startObjectfile(const fn:string):boolean;
  1335. begin
  1336. result:=false;
  1337. { start the writer already, so the .a generation can initialize
  1338. the position of the current objectfile }
  1339. if not FWriter.createfile(fn) then
  1340. Comment(V_Fatal,'Can''t create object '+fn);
  1341. result:=true;
  1342. end;
  1343. function TObjOutput.writeobjectfile(Data:TObjData):boolean;
  1344. begin
  1345. if errorcount=0 then
  1346. result:=writeData(Data)
  1347. else
  1348. result:=true;
  1349. { close the writer }
  1350. FWriter.closefile;
  1351. end;
  1352. procedure TObjOutput.exportsymbol(p:TObjSymbol);
  1353. begin
  1354. { export globals and common symbols, this is needed
  1355. for .a files }
  1356. if p.bind in [AB_GLOBAL,AB_COMMON] then
  1357. FWriter.writesym(p.name);
  1358. end;
  1359. procedure TObjOutput.WriteSectionContent(Data:TObjData);
  1360. var
  1361. i:longint;
  1362. sec:TObjSection;
  1363. begin
  1364. for i:=0 to Data.ObjSectionList.Count-1 do
  1365. begin
  1366. sec:=TObjSection(Data.ObjSectionList[i]);
  1367. if (oso_data in sec.SecOptions) then
  1368. begin
  1369. if sec.Data=nil then
  1370. internalerror(200403073);
  1371. FWriter.writezeros(sec.dataalignbytes);
  1372. if sec.Datapos<>FWriter.ObjSize then
  1373. internalerror(200604031);
  1374. FWriter.writearray(sec.data);
  1375. end;
  1376. end;
  1377. end;
  1378. {****************************************************************************
  1379. TExeVTable
  1380. ****************************************************************************}
  1381. constructor TExeVTable.Create(AExeSymbol:TExeSymbol);
  1382. begin
  1383. ExeSymbol:=AExeSymbol;
  1384. if ExeSymbol.State=symstate_undefined then
  1385. internalerror(200604012);
  1386. ChildList:=TFPObjectList.Create(false);
  1387. end;
  1388. destructor TExeVTable.Destroy;
  1389. begin
  1390. ChildList.Free;
  1391. if assigned(EntryArray) then
  1392. Freemem(EntryArray);
  1393. end;
  1394. procedure TExeVTable.CheckIdx(VTableIdx:longint);
  1395. var
  1396. OldEntryCnt : longint;
  1397. begin
  1398. if VTableIdx>=EntryCnt then
  1399. begin
  1400. OldEntryCnt:=EntryCnt;
  1401. EntryCnt:=VTableIdx+1;
  1402. ReAllocMem(EntryArray,EntryCnt*sizeof(TVTableEntry));
  1403. FillChar(EntryArray[OldEntryCnt],(EntryCnt-OldEntryCnt)*sizeof(TVTableEntry),0);
  1404. end;
  1405. end;
  1406. procedure TExeVTable.AddChild(vt:TExeVTable);
  1407. begin
  1408. ChildList.Add(vt);
  1409. end;
  1410. procedure TExeVTable.AddEntry(VTableIdx:Longint);
  1411. var
  1412. i : longint;
  1413. objreloc : TObjRelocation;
  1414. vtblentryoffset : aword;
  1415. begin
  1416. CheckIdx(VTableIdx);
  1417. vtblentryoffset:=ExeSymbol.ObjSymbol.Offset+longword(VTableIdx)*sizeof(pint);
  1418. { Find and disable relocation }
  1419. for i:=0 to ExeSymbol.ObjSymbol.ObjSection.ObjRelocations.Count-1 do
  1420. begin
  1421. objreloc:=TObjRelocation(ExeSymbol.ObjSymbol.ObjSection.ObjRelocations[i]);
  1422. if objreloc.dataoffset=vtblentryoffset then
  1423. begin
  1424. EntryArray[VTableIdx].ObjRelocation:=objreloc;
  1425. EntryArray[VTableIdx].OrgRelocType:=objreloc.ftype;
  1426. EntryArray[VTableIdx].OrgRelocFlags:=objreloc.flags;
  1427. objreloc.typ:=RELOC_ZERO;
  1428. objreloc.flags:=objreloc.flags or rf_nosymbol;
  1429. break;
  1430. end;
  1431. end;
  1432. if not assigned(EntryArray[VTableIdx].ObjRelocation) then
  1433. internalerror(200604011);
  1434. end;
  1435. procedure TExeVTable.SetVTableSize(ASize:longint);
  1436. begin
  1437. if EntryCnt<>0 then
  1438. internalerror(200603313);
  1439. EntryCnt:=ASize div sizeof(pint);
  1440. EntryArray:=AllocMem(EntryCnt*sizeof(TVTableEntry));
  1441. end;
  1442. function TExeVTable.VTableRef(VTableIdx:Longint):TObjRelocation;
  1443. begin
  1444. result:=nil;
  1445. CheckIdx(VTableIdx);
  1446. if EntryArray[VTableIdx].Used then
  1447. exit;
  1448. { Restore relocation if available }
  1449. if assigned(EntryArray[VTableIdx].ObjRelocation) then
  1450. begin
  1451. EntryArray[VTableIdx].ObjRelocation.ftype:=EntryArray[VTableIdx].OrgRelocType;
  1452. EntryArray[VTableIdx].ObjRelocation.flags:=EntryArray[VTableIdx].OrgRelocFlags;
  1453. result:=EntryArray[VTableIdx].ObjRelocation;
  1454. end;
  1455. EntryArray[VTableIdx].Used:=true;
  1456. end;
  1457. {****************************************************************************
  1458. TExeSection
  1459. ****************************************************************************}
  1460. constructor TExeSection.create(AList:TFPHashObjectList;const AName:string);
  1461. begin
  1462. inherited create(AList,AName);
  1463. Size:=0;
  1464. MemPos:=0;
  1465. DataPos:=0;
  1466. FSecSymIdx:=0;
  1467. FObjSectionList:=TFPObjectList.Create(false);
  1468. end;
  1469. destructor TExeSection.destroy;
  1470. begin
  1471. ObjSectionList.Free;
  1472. inherited destroy;
  1473. end;
  1474. procedure TExeSection.AddObjSection(objsec:TObjSection;ignoreprops:boolean);
  1475. begin
  1476. ObjSectionList.Add(objsec);
  1477. { relate ObjSection to ExeSection, and mark it Used by default }
  1478. objsec.ExeSection:=self;
  1479. objsec.Used:=true;
  1480. if ignoreprops then
  1481. exit;
  1482. if (SecOptions<>[]) then
  1483. begin
  1484. { Only if the section contains (un)initialized data the
  1485. data flag must match. }
  1486. if ((oso_Data in SecOptions)<>(oso_Data in objsec.SecOptions)) then
  1487. Comment(V_Error,'Incompatible section options');
  1488. end
  1489. else
  1490. begin
  1491. { inherit section options }
  1492. SecOptions:=SecOptions+objsec.SecOptions;
  1493. end;
  1494. SecAlign:=max(objsec.SecAlign,SecAlign);
  1495. end;
  1496. {****************************************************************************
  1497. TStaticLibrary
  1498. ****************************************************************************}
  1499. constructor TStaticLibrary.create(const AName:TCmdStr;AReader:TObjectReader;AObjInputClass:TObjInputClass);
  1500. begin
  1501. FName:=AName;
  1502. FPayload:=AReader;
  1503. FObjInputClass:=AObjInputClass;
  1504. FKind:=lkArchive;
  1505. end;
  1506. constructor TStaticLibrary.create_object(AObjData:TObjData);
  1507. begin
  1508. FPayload:=AObjData;
  1509. FKind:=lkObject;
  1510. end;
  1511. constructor TStaticLibrary.create_group;
  1512. begin
  1513. FPayload:=TFPObjectList.Create(true);
  1514. FKind:=lkGroup;
  1515. end;
  1516. destructor TStaticLibrary.destroy;
  1517. begin
  1518. FPayload.Free;
  1519. inherited destroy;
  1520. end;
  1521. function TStaticLibrary.GetArReader: TObjectReader;
  1522. begin
  1523. if (FKind<>lkArchive) then
  1524. InternalError(2012071501);
  1525. result:=TObjectReader(FPayload);
  1526. end;
  1527. function TStaticLibrary.GetGroupMembers: TFPObjectList;
  1528. begin
  1529. if (FKind<>lkGroup) then
  1530. InternalError(2012071502);
  1531. result:=TFPObjectList(FPayload);
  1532. end;
  1533. function TStaticLibrary.GetObjData: TObjData;
  1534. begin
  1535. if (FKind<>lkObject) then
  1536. InternalError(2012071503);
  1537. result:=TObjData(FPayload);
  1538. end;
  1539. {****************************************************************************
  1540. TImportLibrary
  1541. ****************************************************************************}
  1542. constructor TImportLibrary.create(AList:TFPHashObjectList;const AName:string);
  1543. begin
  1544. inherited create(AList,AName);
  1545. FImportSymbolList:=TFPHashObjectList.Create(true);
  1546. end;
  1547. destructor TImportLibrary.destroy;
  1548. begin
  1549. ImportSymbolList.Free;
  1550. inherited destroy;
  1551. end;
  1552. {****************************************************************************
  1553. TImportSymbol
  1554. ****************************************************************************}
  1555. constructor TImportSymbol.create(AList:TFPHashObjectList;
  1556. const AName,AMangledName:string;AOrdNr:longint;AIsVar:boolean);
  1557. begin
  1558. inherited Create(AList, AName);
  1559. FOrdNr:=AOrdNr;
  1560. FIsVar:=AIsVar;
  1561. FMangledName:=AMangledName;
  1562. { Replace ? and @ in import name, since GNU AS does not allow these characters in symbol names. }
  1563. { This allows to import VC++ mangled names from DLLs. }
  1564. if target_info.system in systems_all_windows then
  1565. begin
  1566. Replace(FMangledName,'?','__q$$');
  1567. {$ifdef arm}
  1568. { @ symbol is not allowed in ARM assembler only }
  1569. Replace(FMangledName,'@','__a$$');
  1570. {$endif arm}
  1571. end;
  1572. end;
  1573. {****************************************************************************
  1574. TExeOutput
  1575. ****************************************************************************}
  1576. constructor TExeOutput.create;
  1577. begin
  1578. { init writer }
  1579. FWriter:=TObjectwriter.create;
  1580. FExeWriteMode:=ewm_exefull;
  1581. { object files }
  1582. FObjDataList:=TFPObjectList.Create(true);
  1583. { symbols }
  1584. FExeSymbolList:=TFPHashObjectList.Create(true);
  1585. FUnresolvedExeSymbols:=TFPObjectList.Create(false);
  1586. FExternalObjSymbols:=TFPObjectList.Create(false);
  1587. FCommonObjSymbols:=TFPObjectList.Create(false);
  1588. FProvidedObjSymbols:=TFPObjectList.Create(false);
  1589. FIndirectObjSymbols:=TFPObjectList.Create(false);
  1590. FExeVTableList:=TFPObjectList.Create(false);
  1591. ComdatGroups:=TFPHashList.Create;
  1592. { sections }
  1593. FExeSectionList:=TFPHashObjectList.Create(true);
  1594. FImageBase:=0;
  1595. {$ifdef cpu16bitaddr}
  1596. SectionMemAlign:=$10;
  1597. SectionDataAlign:=$10;
  1598. {$else cpu16bitaddr}
  1599. SectionMemAlign:=$1000;
  1600. SectionDataAlign:=$200;
  1601. {$endif cpu16bitaddr}
  1602. FixedSectionAlign:=True;
  1603. FCExeSection:=TExeSection;
  1604. FCObjData:=TObjData;
  1605. FCObjSymbol:=TObjSymbol;
  1606. end;
  1607. destructor TExeOutput.destroy;
  1608. begin
  1609. FExeSymbolList.free;
  1610. UnresolvedExeSymbols.free;
  1611. ExternalObjSymbols.free;
  1612. FProvidedObjSymbols.free;
  1613. FIndirectObjSymbols.free;
  1614. CommonObjSymbols.free;
  1615. ExeVTableList.free;
  1616. FExeSectionList.free;
  1617. ComdatGroups.free;
  1618. ObjDatalist.free;
  1619. FWriter.free;
  1620. inherited destroy;
  1621. end;
  1622. function TExeOutput.MemAlign(exesec:TExeSection):longword;
  1623. begin
  1624. if FixedSectionAlign then
  1625. result:=SectionMemAlign
  1626. else
  1627. result:=exesec.SecAlign;
  1628. end;
  1629. function TExeOutput.DataAlign(exesec:TExeSection):longword;
  1630. begin
  1631. if FixedSectionAlign then
  1632. result:=SectionDataAlign
  1633. else
  1634. result:=exesec.SecAlign;
  1635. end;
  1636. function TExeOutput.WriteExeFile(const fn:string):boolean;
  1637. begin
  1638. result:=false;
  1639. if FWriter.createfile(fn) then
  1640. begin
  1641. { Only write the .o if there are no errors }
  1642. if errorcount=0 then
  1643. result:=writedata
  1644. else
  1645. result:=true;
  1646. { close the writer }
  1647. FWriter.closefile;
  1648. end
  1649. else
  1650. Comment(V_Fatal,'Can''t create executable '+fn);
  1651. end;
  1652. procedure TExeOutput.ParseScript (linkscript:TCmdStrList);
  1653. begin
  1654. end;
  1655. function TExeOutput.FindExeSection(const aname:string):TExeSection;
  1656. begin
  1657. result:=TExeSection(ExeSectionList.Find(aname));
  1658. end;
  1659. procedure TExeOutput.AddObjData(ObjData:TObjData);
  1660. begin
  1661. if ObjData.classtype<>FCObjData then
  1662. Comment(V_Error,'Invalid input object format for '+ObjData.name+' got '+ObjData.classname+' expected '+FCObjData.classname);
  1663. ObjDataList.Add(ObjData);
  1664. ExecStack:=ExecStack or ObjData.ExecStack;
  1665. end;
  1666. procedure TExeOutput.Load_Start;
  1667. begin
  1668. ObjDataList.Clear;
  1669. { Globals defined in the linker script }
  1670. if not assigned(internalObjData) then
  1671. internalObjData:=CObjData.create('*Internal*');
  1672. AddObjData(internalObjData);
  1673. { Common Data section }
  1674. commonObjSection:=internalObjData.createsection(sec_bss,'');
  1675. end;
  1676. procedure TExeOutput.Load_EntryName(const aname:string);
  1677. begin
  1678. FEntryName:=aname;
  1679. end;
  1680. procedure TExeOutput.Load_IsSharedLibrary;
  1681. begin
  1682. IsSharedLibrary:=true;
  1683. end;
  1684. procedure TExeOutput.Load_ImageBase(const avalue:string);
  1685. var
  1686. code : integer;
  1687. objsec : TObjSection;
  1688. objsym : TObjSymbol;
  1689. exesym : TExeSymbol;
  1690. begin
  1691. val(avalue,FImageBase,code);
  1692. if code<>0 then
  1693. Comment(V_Error,'Invalid number '+avalue);
  1694. { Create __image_base__ symbol, create the symbol
  1695. in a section with adress 0 and at offset 0 }
  1696. objsec:=internalObjData.createsection('*__image_base__',0,[]);
  1697. internalObjData.setsection(objsec);
  1698. objsym:=internalObjData.SymbolDefine('__image_base__',AB_GLOBAL,AT_DATA);
  1699. exesym:=texesymbol.Create(FExeSymbolList,objsym.name);
  1700. exesym.ObjSymbol:=objsym;
  1701. end;
  1702. procedure TExeOutput.Load_Symbol(const aname:string);
  1703. begin
  1704. internalObjData.createsection('*'+aname,0,[]);
  1705. internalObjData.SymbolDefine(aname,AB_GLOBAL,AT_DATA);
  1706. end;
  1707. procedure TExeOutput.Load_ProvideSymbol(const aname:string);
  1708. begin
  1709. if assigned(ExeSymbolList.Find(aname)) then
  1710. exit;
  1711. internalObjData.createsection('*'+aname,0,[]);
  1712. // Use AB_COMMON to avoid muliple defined complaints
  1713. internalObjData.SymbolDefine(aname,AB_COMMON,AT_DATA);
  1714. end;
  1715. procedure TExeOutput.Load_DynamicObject(ObjData:TObjData;asneeded:boolean);
  1716. begin
  1717. end;
  1718. procedure TExeOutput.Order_Start;
  1719. begin
  1720. end;
  1721. procedure TExeOutput.Order_End;
  1722. begin
  1723. internalObjData.afterwrite;
  1724. end;
  1725. procedure TExeOutput.Order_ExeSection(const aname:string);
  1726. var
  1727. sec : TExeSection;
  1728. begin
  1729. sec:=FindExeSection(aname);
  1730. if not assigned(sec) then
  1731. sec:=CExeSection.create(ExeSectionList,aname);
  1732. { Clear ExeSection contents }
  1733. FCurrExeSec:=sec;
  1734. end;
  1735. procedure TExeOutput.Order_EndExeSection;
  1736. begin
  1737. if not assigned(CurrExeSec) then
  1738. internalerror(200602184);
  1739. FCurrExeSec:=nil;
  1740. end;
  1741. procedure TExeOutput.Order_ObjSection(const aname:string);
  1742. var
  1743. i,j : longint;
  1744. ObjData : TObjData;
  1745. objsec : TObjSection;
  1746. TmpObjSectionList : TFPObjectList;
  1747. begin
  1748. if not assigned(CurrExeSec) then
  1749. internalerror(200602181);
  1750. TmpObjSectionList:=TFPObjectList.Create(false);
  1751. for i:=0 to ObjDataList.Count-1 do
  1752. begin
  1753. ObjData:=TObjData(ObjDataList[i]);
  1754. for j:=0 to ObjData.ObjSectionList.Count-1 do
  1755. begin
  1756. objsec:=TObjSection(ObjData.ObjSectionList[j]);
  1757. if (not objsec.Used) and
  1758. MatchPattern(aname,objsec.name) then
  1759. TmpObjSectionList.Add(objsec);
  1760. end;
  1761. end;
  1762. { Order list if needed }
  1763. Order_ObjSectionList(TmpObjSectionList,aname);
  1764. { Add the (ordered) list to the current ExeSection }
  1765. for i:=0 to TmpObjSectionList.Count-1 do
  1766. begin
  1767. objsec:=TObjSection(TmpObjSectionList[i]);
  1768. CurrExeSec.AddObjSection(objsec);
  1769. end;
  1770. TmpObjSectionList.Free;
  1771. end;
  1772. procedure TExeOutput.Order_ObjSectionList(ObjSectionList : TFPObjectList; const aPattern:string);
  1773. begin
  1774. end;
  1775. procedure TExeOutput.Order_Symbol(const aname:string);
  1776. var
  1777. objsym: TObjSymbol;
  1778. begin
  1779. objsym:=TObjSymbol(internalObjData.ObjSymbolList.Find(aname));
  1780. if (objsym=nil) or (objsym.ObjSection.ObjData<>internalObjData) then
  1781. internalerror(200603041);
  1782. CurrExeSec.AddObjSection(objsym.ObjSection,True);
  1783. end;
  1784. procedure TExeOutput.Order_ProvideSymbol(const aname:string);
  1785. var
  1786. objsym : TObjSymbol;
  1787. exesym : TExeSymbol;
  1788. begin
  1789. objsym:=TObjSymbol(internalObjData.ObjSymbolList.Find(aname));
  1790. if (objsym=nil) or (objsym.ObjSection.ObjData<>internalObjData) then
  1791. internalerror(200603041);
  1792. exesym:=TExeSymbol(ExeSymbolList.Find(aname));
  1793. if not assigned(exesym) then
  1794. internalerror(201206301);
  1795. { Only include this section if it actually resolves
  1796. the symbol }
  1797. if exesym.objsymbol=objsym then
  1798. CurrExeSec.AddObjSection(objsym.ObjSection,True);
  1799. end;
  1800. procedure TExeOutput.Order_Align(const avalue:string);
  1801. var
  1802. code : integer;
  1803. alignval : shortint;
  1804. objsec : TObjSection;
  1805. begin
  1806. val(avalue,alignval,code);
  1807. if code<>0 then
  1808. Comment(V_Error,'Invalid number '+avalue);
  1809. if alignval<=0 then
  1810. exit;
  1811. { Create an empty section with the required aligning }
  1812. inc(Fzeronr);
  1813. objsec:=internalObjData.createsection('*align'+tostr(Fzeronr),alignval,CurrExeSec.SecOptions+[oso_Data,oso_keep]);
  1814. CurrExeSec.AddObjSection(objsec);
  1815. end;
  1816. procedure TExeOutput.Order_Zeros(const avalue:string);
  1817. var
  1818. zeros : array[0..1023] of byte;
  1819. code : integer;
  1820. len : longint;
  1821. objsec : TObjSection;
  1822. begin
  1823. val(avalue,len,code);
  1824. if code<>0 then
  1825. Comment(V_Error,'Invalid number '+avalue);
  1826. if len<=0 then
  1827. exit;
  1828. if len>sizeof(zeros) then
  1829. internalerror(200602254);
  1830. fillchar(zeros,len,0);
  1831. inc(Fzeronr);
  1832. objsec:=internalObjData.createsection('*zeros'+tostr(Fzeronr),0,CurrExeSec.SecOptions+[oso_Data,oso_keep]);
  1833. internalObjData.writebytes(zeros,len);
  1834. CurrExeSec.AddObjSection(objsec);
  1835. end;
  1836. procedure TExeOutput.Order_Values(bytesize : aword; const avalue:string);
  1837. const
  1838. MAXVAL = 128;
  1839. var
  1840. bytevalues : array[0..MAXVAL-1] of byte;
  1841. twobytevalues : array[0..MAXVAL-1] of word;
  1842. fourbytevalues : array[0..MAXVAL-1] of dword;
  1843. eightbytevalues : array[0..MAXVAL-1] of qword;
  1844. allvals, oneval : string;
  1845. len, commapos : longint;
  1846. indexpos, code : integer;
  1847. anumval : qword;
  1848. signedval : int64;
  1849. objsec : TObjSection;
  1850. begin
  1851. indexpos:=0;
  1852. allvals:=avalue;
  1853. { avoid warnings }
  1854. bytevalues[0]:=0;
  1855. twobytevalues[0]:=0;
  1856. fourbytevalues[0]:=0;
  1857. eightbytevalues[0]:=0;
  1858. repeat
  1859. commapos:=pos(',',allvals);
  1860. if commapos>0 then
  1861. begin
  1862. oneval:=trim(copy(allvals,1,commapos-1));
  1863. allvals:=copy(allvals,commapos+1,length(allvals));
  1864. end
  1865. else
  1866. begin
  1867. oneval:=trim(allvals);
  1868. allvals:='';
  1869. end;
  1870. if oneval<>'' then
  1871. begin
  1872. if oneval[1]='-' then
  1873. begin
  1874. val(oneval,signedval,code);
  1875. anumval:=qword(signedval);
  1876. end
  1877. else
  1878. val(oneval,anumval,code);
  1879. if code<>0 then
  1880. Comment(V_Error,'Invalid number '+avalue)
  1881. else
  1882. begin
  1883. if (indexpos<MAXVAL) then
  1884. begin
  1885. if source_info.endian<>target_info.endian then
  1886. swapendian(anumval);
  1887. { No range checking here }
  1888. if bytesize=1 then
  1889. bytevalues[indexpos]:=byte(anumval)
  1890. else if bytesize=2 then
  1891. twobytevalues[indexpos]:=word(anumval)
  1892. else if bytesize=4 then
  1893. fourbytevalues[indexpos]:=dword(anumval)
  1894. else if bytesize=8 then
  1895. eightbytevalues[indexpos]:=anumval;
  1896. inc(indexpos);
  1897. end
  1898. else
  1899. Comment(V_Error,'Buffer overrun in Order_values');
  1900. end;
  1901. end;
  1902. until allvals='';
  1903. if indexpos=0 then
  1904. begin
  1905. Comment(V_Error,'Invalid number '+avalue);
  1906. exit;
  1907. end;
  1908. if indexpos=MAXVAL then
  1909. begin
  1910. Comment(V_Error,'Too many values '+avalue);
  1911. internalerror(200602254);
  1912. end;
  1913. len:=bytesize*indexpos;
  1914. inc(Fvaluesnr);
  1915. objsec:=internalObjData.createsection('*values'+tostr(Fvaluesnr),0,CurrExeSec.SecOptions+[oso_Data,oso_keep]);
  1916. if bytesize=1 then
  1917. internalObjData.writebytes(bytevalues,len)
  1918. else if bytesize=2 then
  1919. internalObjData.writebytes(twobytevalues,len)
  1920. else if bytesize=4 then
  1921. internalObjData.writebytes(fourbytevalues,len)
  1922. else if bytesize=8 then
  1923. internalObjData.writebytes(eightbytevalues,len);
  1924. CurrExeSec.AddObjSection(objsec);
  1925. end;
  1926. procedure TExeOutput.MemPos_Start;
  1927. begin
  1928. CurrMemPos:=0;
  1929. RemoveDisabledSections;
  1930. end;
  1931. procedure TExeOutput.MemPos_Header;
  1932. begin
  1933. end;
  1934. procedure TExeOutput.MemPos_ExeSection(exesec:TExeSection);
  1935. var
  1936. i : longint;
  1937. objsec : TObjSection;
  1938. begin
  1939. { Alignment of ExeSection }
  1940. CurrMemPos:=align_qword(CurrMemPos,MemAlign(exesec));
  1941. exesec.MemPos:=CurrMemPos;
  1942. { set position of object ObjSections }
  1943. for i:=0 to exesec.ObjSectionList.Count-1 do
  1944. begin
  1945. objsec:=TObjSection(exesec.ObjSectionList[i]);
  1946. CurrMemPos:=objsec.setmempos(CurrMemPos);
  1947. end;
  1948. { calculate size of the section }
  1949. exesec.Size:=CurrMemPos-exesec.MemPos;
  1950. end;
  1951. procedure TExeOutput.MemPos_ExeSection(const aname:string);
  1952. begin
  1953. { Section can be removed }
  1954. FCurrExeSec:=FindExeSection(aname);
  1955. if not assigned(CurrExeSec) then
  1956. exit;
  1957. MemPos_ExeSection(CurrExeSec);
  1958. end;
  1959. procedure TExeOutput.MemPos_EndExeSection;
  1960. begin
  1961. if not assigned(CurrExeSec) then
  1962. exit;
  1963. FCurrExeSec:=nil;
  1964. end;
  1965. procedure TExeOutput.DataPos_Start;
  1966. begin
  1967. end;
  1968. procedure TExeOutput.DataPos_Header;
  1969. begin
  1970. end;
  1971. procedure TExeOutput.DataPos_ExeSection(exesec:TExeSection);
  1972. begin
  1973. { don't write normal section if writing only debug info }
  1974. if (ExeWriteMode=ewm_dbgonly) and
  1975. (exesec.SecOptions*[oso_debug,oso_debug_copy]=[]) then
  1976. exit;
  1977. if (oso_Data in exesec.SecOptions) then
  1978. begin
  1979. CurrDataPos:=align_aword(CurrDataPos,DataAlign(exesec));
  1980. exesec.DataPos:=CurrDataPos;
  1981. CurrDataPos:=CurrDataPos+exesec.Size;
  1982. end;
  1983. end;
  1984. procedure TExeOutput.DataPos_ExeSection(const aname:string);
  1985. begin
  1986. { Section can be removed }
  1987. FCurrExeSec:=FindExeSection(aname);
  1988. if not assigned(CurrExeSec) then
  1989. exit;
  1990. DataPos_ExeSection(CurrExeSec);
  1991. end;
  1992. procedure TExeOutput.DataPos_EndExeSection;
  1993. begin
  1994. if not assigned(CurrExeSec) then
  1995. exit;
  1996. FCurrExeSec:=nil;
  1997. end;
  1998. procedure TExeOutput.DataPos_Symbols;
  1999. begin
  2000. end;
  2001. procedure TExeOutput.BuildVTableTree(VTInheritList,VTEntryList:TFPObjectList);
  2002. var
  2003. hs : string;
  2004. code : integer;
  2005. i,k,
  2006. vtableidx : longint;
  2007. vtableexesym,
  2008. childexesym,
  2009. parentexesym : TExeSymbol;
  2010. objsym : TObjSymbol;
  2011. begin
  2012. { Build inheritance tree from VTINHERIT }
  2013. for i:=0 to VTInheritList.Count-1 do
  2014. begin
  2015. objsym:=TObjSymbol(VTInheritList[i]);
  2016. hs:=objsym.name;
  2017. { VTINHERIT_<ChildVMTName>$$<ParentVMTName> }
  2018. Delete(hs,1,Pos('_',hs));
  2019. k:=Pos('$$',hs);
  2020. if k=0 then
  2021. internalerror(200603311);
  2022. childexesym:=texesymbol(FExeSymbolList.Find(Copy(hs,1,k-1)));
  2023. parentexesym:=texesymbol(FExeSymbolList.Find(Copy(hs,k+2,length(hs)-k-1)));
  2024. if not assigned(childexesym) or
  2025. not assigned(parentexesym)then
  2026. internalerror(200603312);
  2027. if not assigned(childexesym.vtable) then
  2028. begin
  2029. childexesym.vtable:=TExeVTable.Create(childexesym);
  2030. ExeVTableList.Add(childexesym.vtable);
  2031. end;
  2032. if not assigned(parentexesym.vtable) then
  2033. begin
  2034. parentexesym.vtable:=TExeVTable.Create(parentexesym);
  2035. ExeVTableList.Add(parentexesym.vtable);
  2036. end;
  2037. childexesym.vtable.SetVTableSize(childexesym.ObjSymbol.Size);
  2038. if parentexesym<>childexesym then
  2039. parentexesym.vtable.AddChild(childexesym.vtable);
  2040. end;
  2041. { Find VTable entries from VTENTRY }
  2042. for i:=0 to VTEntryList.Count-1 do
  2043. begin
  2044. objsym:=TObjSymbol(VTEntryList[i]);
  2045. hs:=objsym.name;
  2046. { VTENTRY_<VTableName>$$<Index> }
  2047. Delete(hs,1,Pos('_',hs));
  2048. k:=Pos('$$',hs);
  2049. if k=0 then
  2050. internalerror(200603319);
  2051. vtableexesym:=texesymbol(FExeSymbolList.Find(Copy(hs,1,k-1)));
  2052. val(Copy(hs,k+2,length(hs)-k-1),vtableidx,code);
  2053. if (code<>0) then
  2054. internalerror(200603318);
  2055. if not assigned(vtableexesym) then
  2056. internalerror(2006033110);
  2057. vtableexesym.vtable.AddEntry(vtableidx);
  2058. end;
  2059. end;
  2060. procedure TExeOutput.PackUnresolvedExeSymbols(const s:string);
  2061. var
  2062. i : longint;
  2063. exesym : TExeSymbol;
  2064. begin
  2065. { Generate a list of Unresolved External symbols }
  2066. for i:=0 to UnresolvedExeSymbols.count-1 do
  2067. begin
  2068. exesym:=TExeSymbol(UnresolvedExeSymbols[i]);
  2069. if not (exesym.State in [symstate_undefined,symstate_undefweak]) then
  2070. UnresolvedExeSymbols[i]:=nil;
  2071. end;
  2072. UnresolvedExeSymbols.Pack;
  2073. Comment(V_Debug,'Number of unresolved externals '+s+' '+tostr(UnresolvedExeSymbols.Count));
  2074. end;
  2075. procedure TExeOutput.ResolveSymbols(StaticLibraryList:TFPObjectList);
  2076. var
  2077. ObjData : TObjData;
  2078. exesym : TExeSymbol;
  2079. objsym,
  2080. commonsym : TObjSymbol;
  2081. firstarchive,
  2082. firstcommon : boolean;
  2083. i : longint;
  2084. VTEntryList,
  2085. VTInheritList : TFPObjectList;
  2086. procedure LoadObjDataSymbols(ObjData:TObjData);
  2087. var
  2088. j : longint;
  2089. hs : string;
  2090. exesym : TExeSymbol;
  2091. objsym : TObjSymbol;
  2092. grp : TObjSectionGroup;
  2093. begin
  2094. for j:=0 to ObjData.ObjSymbolList.Count-1 do
  2095. begin
  2096. objsym:=TObjSymbol(ObjData.ObjSymbolList[j]);
  2097. { From the local symbols we are only interressed in the
  2098. VTENTRY and VTINHERIT symbols }
  2099. if objsym.bind=AB_LOCAL then
  2100. begin
  2101. if cs_link_opt_vtable in current_settings.globalswitches then
  2102. begin
  2103. hs:=objsym.name;
  2104. if (hs[1]='V') then
  2105. begin
  2106. if Copy(hs,1,5)='VTREF' then
  2107. begin
  2108. if not assigned(objsym.ObjSection.VTRefList) then
  2109. objsym.ObjSection.VTRefList:=TFPObjectList.Create(false);
  2110. objsym.ObjSection.VTRefList.Add(objsym);
  2111. end
  2112. else if Copy(hs,1,7)='VTENTRY' then
  2113. VTEntryList.Add(objsym)
  2114. else if Copy(hs,1,9)='VTINHERIT' then
  2115. VTInheritList.Add(objsym);
  2116. end;
  2117. end;
  2118. continue;
  2119. end;
  2120. { If this symbol comes from COMDAT group, see if a group with
  2121. matching signature is already included. }
  2122. if assigned(objsym.objsection) and
  2123. assigned(objsym.objsection.group) then
  2124. begin
  2125. grp:=objsym.objsection.group;
  2126. if grp.IsComdat then
  2127. begin
  2128. if ComdatGroups.Find(grp.name)=nil then
  2129. ComdatGroups.Add(grp.name,grp)
  2130. else
  2131. begin
  2132. { Undefine the symbol, causing relocations to it from same
  2133. objdata to be redirected to the symbol in the actually
  2134. linked group. }
  2135. if objsym.bind=AB_GLOBAL then
  2136. objsym.bind:=AB_EXTERNAL;
  2137. { AB_WEAK_EXTERNAL remains unchanged }
  2138. objsym.objsection:=nil;
  2139. end;
  2140. end;
  2141. end;
  2142. { Search for existing exesymbol }
  2143. exesym:=texesymbol(FExeSymbolList.Find(objsym.name));
  2144. if not assigned(exesym) then
  2145. begin
  2146. exesym:=texesymbol.Create(FExeSymbolList,objsym.name);
  2147. exesym.ObjSymbol:=objsym;
  2148. end;
  2149. objsym.ExeSymbol:=exesym;
  2150. case objsym.bind of
  2151. AB_GLOBAL :
  2152. begin
  2153. if exesym.State<>symstate_defined then
  2154. begin
  2155. exesym.ObjSymbol:=objsym;
  2156. exesym.State:=symstate_defined;
  2157. end
  2158. else
  2159. Comment(V_Error,'Multiple defined symbol '+objsym.name);
  2160. end;
  2161. AB_EXTERNAL :
  2162. begin
  2163. ExternalObjSymbols.add(objsym);
  2164. { Register unresolved symbols only the first time they
  2165. are registered }
  2166. if exesym.ObjSymbol=objsym then
  2167. UnresolvedExeSymbols.Add(exesym)
  2168. { Normal reference removes any existing "weakness" }
  2169. else if exesym.state=symstate_undefweak then
  2170. begin
  2171. exesym.state:=symstate_undefined;
  2172. exesym.ObjSymbol:=objsym;
  2173. end;
  2174. end;
  2175. AB_COMMON :
  2176. begin
  2177. { A COMMON definition overrides weak one.
  2178. Also select the symbol with largest size. }
  2179. if (exesym.State in [symstate_undefined,symstate_undefweak,symstate_defweak]) or
  2180. ((exesym.State=symstate_common) and (objsym.size>exesym.ObjSymbol.size)) then
  2181. begin
  2182. exesym.ObjSymbol:=objsym;
  2183. exesym.State:=symstate_common;
  2184. end;
  2185. if assigned(objsym.objsection) and
  2186. (objsym.objsection.objdata=internalObjData) then
  2187. FProvidedObjSymbols.add(objsym)
  2188. else
  2189. CommonObjSymbols.add(objsym);
  2190. end;
  2191. AB_WEAK_EXTERNAL :
  2192. begin
  2193. if objsym.objsection=nil then { a weak reference }
  2194. begin
  2195. ExternalObjSymbols.add(objsym);
  2196. if exesym.ObjSymbol=objsym then
  2197. begin
  2198. UnresolvedExeSymbols.Add(exesym);
  2199. exesym.state:=symstate_undefweak;
  2200. end;
  2201. end
  2202. else { a weak definition }
  2203. begin
  2204. if exesym.State in [symstate_undefined,symstate_undefweak] then
  2205. begin
  2206. exesym.ObjSymbol:=objsym;
  2207. exesym.state:=symstate_defweak;
  2208. end;
  2209. end;
  2210. end;
  2211. end;
  2212. end;
  2213. end;
  2214. procedure LoadLibrary(lib:TStaticLibrary);
  2215. var
  2216. j,k,oldcount: longint;
  2217. members: TFPObjectList;
  2218. exesym: TExeSymbol;
  2219. objinput: TObjInput;
  2220. begin
  2221. case lib.Kind of
  2222. lkArchive:
  2223. begin
  2224. { Process list of Unresolved External symbols, we need
  2225. to use a while loop because the list can be extended when
  2226. we load members from the library. }
  2227. j:=0;
  2228. while (j<UnresolvedExeSymbols.count) do
  2229. begin
  2230. exesym:=TExeSymbol(UnresolvedExeSymbols[j]);
  2231. { Check first if the symbol is still undefined }
  2232. if (exesym.State=symstate_undefined) then
  2233. begin
  2234. if lib.ArReader.OpenFile(exesym.name) then
  2235. begin
  2236. if assigned(exemap) then
  2237. begin
  2238. if firstarchive then
  2239. begin
  2240. exemap.Add('');
  2241. exemap.Add('Archive member included because of file (symbol)');
  2242. exemap.Add('');
  2243. firstarchive:=false;
  2244. end;
  2245. exemap.Add(lib.ArReader.FileName+' - '+
  2246. {exesym.ObjSymbol.ObjSection.FullName+}
  2247. '('+exesym.Name+')');
  2248. end;
  2249. objinput:=lib.ObjInputClass.Create;
  2250. objinput.ReadObjData(lib.ArReader,objdata);
  2251. objinput.free;
  2252. AddObjData(objdata);
  2253. LoadObjDataSymbols(objdata);
  2254. lib.ArReader.CloseFile;
  2255. end;
  2256. end;
  2257. inc(j);
  2258. end;
  2259. end;
  2260. lkGroup:
  2261. begin
  2262. { repeatedly process members of the group until no new
  2263. unresolved symbols appear }
  2264. members:=lib.GroupMembers;
  2265. repeat
  2266. oldcount:=UnresolvedExeSymbols.count;
  2267. for k:=0 to members.Count-1 do
  2268. LoadLibrary(TStaticLibrary(members[k]));
  2269. until UnresolvedExeSymbols.count=oldcount;
  2270. end;
  2271. lkObject:
  2272. { TODO: ownership of objdata }
  2273. //if lib.objdata.is_dynamic then
  2274. Load_DynamicObject(lib.objdata,lib.AsNeeded);
  2275. {else
  2276. begin
  2277. AddObjData(lib.objdata);
  2278. LoadObjDataSymbols(lib.objdata);
  2279. end;}
  2280. end;
  2281. end;
  2282. begin
  2283. VTEntryList:=TFPObjectList.Create(false);
  2284. VTInheritList:=TFPObjectList.Create(false);
  2285. {
  2286. The symbol resolving is done in 4 steps:
  2287. 1. Register symbols from objects
  2288. 2. Find symbols in static libraries
  2289. 3. Define symbols PROVIDEd by the link script
  2290. 4. Define still undefined common symbols
  2291. }
  2292. { Step 1, Register symbols from objects }
  2293. for i:=0 to ObjDataList.Count-1 do
  2294. begin
  2295. ObjData:=TObjData(ObjDataList[i]);
  2296. LoadObjDataSymbols(ObjData);
  2297. end;
  2298. PackUnresolvedExeSymbols('in objects');
  2299. { Step 2, Find unresolved symbols in the libraries }
  2300. firstarchive:=true;
  2301. for i:=0 to StaticLibraryList.Count-1 do
  2302. LoadLibrary(TStaticLibrary(StaticLibraryList[i]));
  2303. PackUnresolvedExeSymbols('after static libraries');
  2304. { Step 3, handle symbols provided in script }
  2305. for i:=0 to FProvidedObjSymbols.count-1 do
  2306. begin
  2307. objsym:=TObjSymbol(FProvidedObjSymbols[i]);
  2308. if objsym.exesymbol.State=symstate_defined then
  2309. continue;
  2310. objsym.exesymbol.objsymbol:=objsym;
  2311. objsym.bind:=AB_GLOBAL;
  2312. objsym.exesymbol.State:=symstate_defined;
  2313. end;
  2314. PackUnresolvedExeSymbols('after defining symbols provided by link script');
  2315. { Step 4, Match common symbols or add to the globals }
  2316. firstcommon:=true;
  2317. for i:=0 to CommonObjSymbols.count-1 do
  2318. begin
  2319. objsym:=TObjSymbol(CommonObjSymbols[i]);
  2320. if objsym.exesymbol.State=symstate_defined then
  2321. begin
  2322. if objsym.exesymbol.ObjSymbol.size<>objsym.size then
  2323. Comment(V_Debug,'Size of common symbol '+objsym.name+' is different, expected '+tostr(objsym.size)+' got '+tostr(objsym.exesymbol.ObjSymbol.size));
  2324. end
  2325. else
  2326. begin
  2327. { allocate new objsymbol in .bss of *COMMON* and assign
  2328. it to the exesymbol }
  2329. if firstcommon then
  2330. begin
  2331. if assigned(exemap) then
  2332. exemap.AddCommonSymbolsHeader;
  2333. firstcommon:=false;
  2334. end;
  2335. internalObjData.setsection(commonObjSection);
  2336. { TODO: support alignment of common symbols (ELF targets at least),
  2337. increase commonObjSection.SecAlign if necessary here. }
  2338. internalObjData.allocalign(used_align(size_2_align(objsym.size),0,commonObjSection.SecAlign));
  2339. commonsym:=internalObjData.symboldefine(objsym.name,AB_GLOBAL,AT_DATA);
  2340. commonsym.size:=objsym.size;
  2341. internalObjData.alloc(objsym.size);
  2342. if assigned(exemap) then
  2343. exemap.AddCommonSymbol(objsym);
  2344. { Assign to the exesymbol }
  2345. objsym.exesymbol.objsymbol:=commonsym;
  2346. objsym.exesymbol.state:=symstate_defined;
  2347. end;
  2348. end;
  2349. PackUnresolvedExeSymbols('after defining COMMON symbols');
  2350. { Find entry symbol and print in map }
  2351. if (EntryName<>'') then
  2352. begin
  2353. exesym:=texesymbol(ExeSymbolList.Find(EntryName));
  2354. if assigned(exesym) then
  2355. begin
  2356. EntrySym:=exesym.ObjSymbol;
  2357. if assigned(exemap) then
  2358. begin
  2359. exemap.Add('');
  2360. exemap.Add('Entry symbol '+EntryName);
  2361. end;
  2362. end
  2363. else
  2364. Comment(V_Error,'Entrypoint '+EntryName+' not defined');
  2365. end;
  2366. { Generate VTable tree }
  2367. if cs_link_opt_vtable in current_settings.globalswitches then
  2368. BuildVTableTree(VTInheritList,VTEntryList);
  2369. VTInheritList.Free;
  2370. VTEntryList.Free;
  2371. end;
  2372. procedure TExeOutput.GenerateDebugLink(const dbgname:string;dbgcrc:cardinal);
  2373. var
  2374. debuglink : array[0..1023] of byte;
  2375. len : longint;
  2376. objsec : TObjSection;
  2377. exesec : TExeSection;
  2378. begin
  2379. { From the gdb manual chapter 15. GDB Files:
  2380. * A filename, with any leading directory components removed, followed by a zero byte,
  2381. * zero to three bytes of padding, as needed to reach the next four-byte boundary within the section, and
  2382. * a four-byte CRC checksum, stored in the same endianness used for the executable file itself. The checksum is computed
  2383. on the debugging information file's full contents by the function given below, passing zero as the crc argument.
  2384. }
  2385. fillchar(debuglink,sizeof(debuglink),0);
  2386. len:=0;
  2387. move(dbgname[1],debuglink[len],length(dbgname));
  2388. inc(len,length(dbgname)+1);
  2389. len:=align(len,4);
  2390. if source_info.endian<>target_info.endian then
  2391. SwapEndian(dbgcrc);
  2392. move(dbgcrc,debuglink[len],sizeof(cardinal));
  2393. inc(len,4);
  2394. { Add section }
  2395. exesec:=FindExeSection(debuglinkname);
  2396. if not assigned(exesec) then
  2397. exesec:=CExeSection.create(ExeSectionList,debuglinkname);
  2398. exesec.SecOptions:=[oso_data,oso_keep];
  2399. exesec.SecAlign:=4;
  2400. objsec:=internalObjData.createsection(exesec.name,1,exesec.SecOptions);
  2401. internalObjData.writebytes(debuglink,len);
  2402. exesec.AddObjSection(objsec);
  2403. end;
  2404. procedure TExeOutput.GenerateLibraryImports(ImportLibraryList:TFPHashObjectList);
  2405. begin
  2406. end;
  2407. procedure TExeOutput.MarkTargetSpecificSections(WorkList:TFPObjectList);
  2408. begin
  2409. end;
  2410. procedure TExeOutput.AfterUnusedSectionRemoval;
  2411. begin
  2412. end;
  2413. function ByAddress(item1,item2:pointer):longint;
  2414. var
  2415. sym1:TObjSymbol absolute item1;
  2416. sym2:TObjSymbol absolute item2;
  2417. begin
  2418. if sym1.address>sym2.address then
  2419. result:=1
  2420. else if sym1.address<sym2.address then
  2421. result:=-1
  2422. else
  2423. result:=0;
  2424. end;
  2425. procedure TExeOutput.PrintMemoryMap;
  2426. var
  2427. exesec : TExeSection;
  2428. objsec : TObjSection;
  2429. objsym : TObjSymbol;
  2430. i,j,k,m: longint;
  2431. list : TFPList;
  2432. flag : boolean;
  2433. begin
  2434. if not assigned(exemap) then
  2435. exit;
  2436. { create a list of symbols sorted by address }
  2437. list:=TFPList.Create;
  2438. for i:=0 to ExeSymbolList.Count-1 do
  2439. list.Add(TExeSymbol(ExeSymbolList[i]).ObjSymbol);
  2440. list.Sort(@ByAddress);
  2441. exemap.AddMemoryMapHeader(ImageBase);
  2442. k:=0;
  2443. for i:=0 to ExeSectionList.Count-1 do
  2444. begin
  2445. exesec:=TExeSection(ExeSectionList[i]);
  2446. exemap.AddMemoryMapExeSection(exesec);
  2447. for j:=0 to exesec.ObjSectionList.count-1 do
  2448. begin
  2449. objsec:=TObjSection(exesec.ObjSectionList[j]);
  2450. exemap.AddMemoryMapObjectSection(objsec);
  2451. while (k<list.Count) and (TObjSymbol(list[k]).Address<objsec.MemPos) do
  2452. inc(k);
  2453. while (k<list.Count) do
  2454. begin
  2455. objsym:=TObjSymbol(list[k]);
  2456. if objsym.address>objsec.MemPos+objsec.Size then
  2457. break;
  2458. if objsym.objsection=objsec then
  2459. exemap.AddMemoryMapSymbol(objsym)
  2460. else
  2461. begin
  2462. { Got a symbol with address falling into current section, but
  2463. belonging to a different section. This may happen for zero-length
  2464. sections because symbol list is sorted by address but not by section.
  2465. Do some look-ahead in this case. }
  2466. m:=k+1;
  2467. flag:=false;
  2468. while (m<list.Count) and (TObjSymbol(list[m]).Address=objsym.address) do
  2469. begin
  2470. if TObjSymbol(list[m]).objsection=objsec then
  2471. begin
  2472. flag:=true;
  2473. list.Exchange(k,m);
  2474. exemap.AddMemoryMapSymbol(TObjSymbol(list[k]));
  2475. break;
  2476. end;
  2477. inc(m);
  2478. end;
  2479. if not flag then
  2480. break;
  2481. end;
  2482. inc(k);
  2483. end;
  2484. end;
  2485. end;
  2486. list.Free;
  2487. end;
  2488. procedure TExeOutput.FixupSymbols;
  2489. procedure UpdateSymbol(objsym:TObjSymbol);
  2490. begin
  2491. objsym.bind:=objsym.ExeSymbol.ObjSymbol.bind;
  2492. objsym.offset:=objsym.ExeSymbol.ObjSymbol.offset;
  2493. objsym.size:=objsym.ExeSymbol.ObjSymbol.size;
  2494. objsym.typ:=objsym.ExeSymbol.ObjSymbol.typ;
  2495. objsym.ObjSection:=objsym.ExeSymbol.ObjSymbol.ObjSection;
  2496. objsym.group:=objsym.ExeSymbol.ObjSymbol.group;
  2497. end;
  2498. var
  2499. i : longint;
  2500. objsym : TObjSymbol;
  2501. exesym : TExeSymbol;
  2502. begin
  2503. { Print list of Unresolved External symbols }
  2504. if not AllowUndefinedSymbols then
  2505. for i:=0 to UnresolvedExeSymbols.count-1 do
  2506. begin
  2507. exesym:=TExeSymbol(UnresolvedExeSymbols[i]);
  2508. if (exesym.State=symstate_undefined) then
  2509. Comment(V_Error,'Undefined symbol: '+exesym.name);
  2510. end;
  2511. {
  2512. Fixing up symbols is done in the following steps:
  2513. 1. Update common references
  2514. 2. Update external references
  2515. Symbols with objsection<>nil are removed from the lists,
  2516. remaining ones can be processed later by calling this method again.
  2517. }
  2518. { Step 1, Update commons. Preserve the original symbol size and bind,
  2519. this is needed for correct relocation of DJCOFF files. }
  2520. for i:=0 to CommonObjSymbols.count-1 do
  2521. begin
  2522. objsym:=TObjSymbol(CommonObjSymbols[i]);
  2523. if objsym.bind<>AB_COMMON then
  2524. internalerror(200606241);
  2525. objsym.ObjSection:=objsym.ExeSymbol.ObjSymbol.ObjSection;
  2526. objsym.offset:=objsym.ExeSymbol.ObjSymbol.offset;
  2527. objsym.typ:=objsym.ExeSymbol.ObjSymbol.typ;
  2528. end;
  2529. { Step 2, Update externals }
  2530. for i:=0 to ExternalObjSymbols.count-1 do
  2531. begin
  2532. objsym:=TObjSymbol(ExternalObjSymbols[i]);
  2533. if not (objsym.bind in [AB_EXTERNAL,AB_WEAK_EXTERNAL]) then
  2534. internalerror(200606242);
  2535. UpdateSymbol(objsym);
  2536. { Collect symbols that resolve to indirect functions,
  2537. they will need additional target-specific processing. }
  2538. if objsym.typ=AT_GNU_IFUNC then
  2539. IndirectObjSymbols.Add(objsym)
  2540. else if assigned(objsym.objsection) then
  2541. ExternalObjSymbols[i]:=nil;
  2542. end;
  2543. CommonObjSymbols.Clear;
  2544. ExternalObjSymbols.Pack;
  2545. end;
  2546. procedure TExeOutput.MergeStabs;
  2547. var
  2548. stabexesec,
  2549. stabstrexesec : TExeSection;
  2550. relocsec,
  2551. currstabsec,
  2552. currstabstrsec,
  2553. mergedstabsec,
  2554. mergedstabstrsec : TObjSection;
  2555. hstabreloc,
  2556. currstabreloc : TObjRelocation;
  2557. i,j : longint;
  2558. currstabrelocidx,
  2559. mergestabcnt,
  2560. stabcnt : longword;
  2561. skipstab : boolean;
  2562. skipfun : boolean;
  2563. hstab : TObjStabEntry;
  2564. stabrelocofs : longword;
  2565. buf : array[0..1023] of byte;
  2566. bufend,
  2567. bufsize : longint;
  2568. begin
  2569. stabexesec:=FindExeSection('.stab');
  2570. stabstrexesec:=FindExeSection('.stabstr');
  2571. if (stabexesec=nil) or
  2572. (stabstrexesec=nil) or
  2573. (stabexesec.ObjSectionlist.count=0) then
  2574. exit;
  2575. { Create new stabsection }
  2576. stabRelocofs:=pbyte(@hstab.nvalue)-pbyte(@hstab);
  2577. mergedstabsec:=internalObjData.CreateSection(sec_stab,'');
  2578. mergedstabstrsec:=internalObjData.CreateSection(sec_stabstr,'');
  2579. { write stab for hdrsym }
  2580. mergedstabsec.writeZeros(sizeof(TObjStabEntry));
  2581. mergestabcnt:=1;
  2582. { .stabstr starts with a #0 }
  2583. buf[0]:=0;
  2584. mergedstabstrsec.write(buf[0],1);
  2585. skipfun:=false;
  2586. { Copy stabs and corresponding Relocations }
  2587. for i:=0 to stabexesec.ObjSectionList.Count-1 do
  2588. begin
  2589. currstabsec:=TObjSection(stabexesec.ObjSectionList[i]);
  2590. currstabstrsec:=currstabsec.ObjData.findsection('.stabstr');
  2591. if assigned(currstabstrsec) then
  2592. begin
  2593. stabcnt:=currstabsec.Data.size div sizeof(TObjStabEntry);
  2594. currstabsec.Data.seek(0);
  2595. currstabrelocidx:=0;
  2596. for j:=0 to stabcnt-1 do
  2597. begin
  2598. hstabreloc:=nil;
  2599. skipstab:=false;
  2600. currstabsec.Data.read(hstab,sizeof(TObjStabEntry));
  2601. MaybeSwapStab(hstab);
  2602. { Only include first hdrsym stab }
  2603. if hstab.ntype=0 then
  2604. skipstab:=true;
  2605. if skipfun then
  2606. begin
  2607. { Skip all stabs for function body until N_RBRAC }
  2608. skipfun:=hstab.ntype<>N_RBRAC;
  2609. skipstab:=true;
  2610. end;
  2611. if not skipstab then
  2612. begin
  2613. { Find corresponding Relocation }
  2614. currstabreloc:=nil;
  2615. while (currstabrelocidx<longword(currstabsec.ObjRelocations.Count)) do
  2616. begin
  2617. currstabreloc:=TObjRelocation(currstabsec.ObjRelocations[currstabrelocidx]);
  2618. if assigned(currstabreloc) and
  2619. (currstabreloc.dataoffset>=longword(j)*sizeof(TObjStabEntry)+stabrelocofs) then
  2620. break;
  2621. inc(currstabrelocidx);
  2622. end;
  2623. if assigned(currstabreloc) and
  2624. (currstabreloc.dataoffset=longword(j)*sizeof(TObjStabEntry)+stabrelocofs) then
  2625. begin
  2626. hstabReloc:=currstabReloc;
  2627. inc(currstabrelocidx);
  2628. end;
  2629. { Check if the stab is refering to a removed section }
  2630. if assigned(hstabreloc) then
  2631. begin
  2632. if assigned(hstabreloc.Symbol) then
  2633. relocsec:=hstabreloc.Symbol.ObjSection
  2634. else
  2635. relocsec:=hstabreloc.ObjSection;
  2636. if not assigned(relocsec) then
  2637. internalerror(200603302);
  2638. if not relocsec.Used then
  2639. begin
  2640. skipstab:=true;
  2641. if (hstab.ntype=N_Function) and (hstab.strpos<>0) then
  2642. begin
  2643. currstabstrsec.Data.seek(hstab.strpos);
  2644. bufsize:=currstabstrsec.Data.read(buf,sizeof(buf));
  2645. bufend:=indexbyte(buf,bufsize,Ord(':'));
  2646. if (bufend<>-1) and (bufend<bufsize-1) and (buf[bufend+1]=Ord('F')) then
  2647. skipfun:=true;
  2648. end;
  2649. end;
  2650. end;
  2651. end;
  2652. if not skipstab then
  2653. begin
  2654. { Copy string in stabstr }
  2655. if hstab.strpos<>0 then
  2656. begin
  2657. currstabstrsec.Data.seek(hstab.strpos);
  2658. hstab.strpos:=mergedstabstrsec.Size;
  2659. repeat
  2660. bufsize:=currstabstrsec.Data.read(buf,sizeof(buf));
  2661. bufend:=indexbyte(buf,bufsize,0);
  2662. if bufend=-1 then
  2663. bufend:=bufsize
  2664. else
  2665. begin
  2666. { include the #0 }
  2667. inc(bufend);
  2668. end;
  2669. mergedstabstrsec.write(buf,bufend);
  2670. until (buf[bufend-1]=0) or (bufsize<sizeof(buf));
  2671. end;
  2672. { Copy and Update the relocation }
  2673. if assigned(hstabreloc) then
  2674. begin
  2675. hstabreloc.Dataoffset:=mergestabcnt*sizeof(TObjStabEntry)+stabRelocofs;
  2676. { Remove from List without freeing the object }
  2677. currstabsec.ObjRelocations.List[currstabrelocidx-1]:=nil;
  2678. mergedstabsec.ObjRelocations.Add(hstabreloc);
  2679. end;
  2680. { Write updated stab }
  2681. MaybeSwapStab(hstab);
  2682. mergedstabsec.write(hstab,sizeof(hstab));
  2683. inc(mergestabcnt);
  2684. end;
  2685. end;
  2686. end;
  2687. { Unload stabs }
  2688. if assigned(currstabstrsec) then
  2689. begin
  2690. currstabstrsec.Used:=False;
  2691. currstabstrsec.ReleaseData;
  2692. end;
  2693. currstabsec.Used:=false;
  2694. currstabsec.ReleaseData;
  2695. end;
  2696. { Generate new HdrSym }
  2697. if mergedstabsec.Size>0 then
  2698. begin
  2699. hstab.strpos:=1;
  2700. hstab.ntype:=0;
  2701. hstab.nother:=0;
  2702. hstab.ndesc:=word(mergestabcnt-1);
  2703. hstab.nvalue:=mergedstabstrsec.Size;
  2704. MaybeSwapStab(hstab);
  2705. mergedstabsec.Data.seek(0);
  2706. mergedstabsec.Data.write(hstab,sizeof(hstab));
  2707. end;
  2708. { Replace all sections with our combined stabsec }
  2709. stabexesec.ObjSectionList.Clear;
  2710. stabstrexesec.ObjSectionList.Clear;
  2711. stabexesec.AddObjSection(mergedstabsec);
  2712. stabstrexesec.AddObjSection(mergedstabstrsec);
  2713. end;
  2714. procedure TExeOutput.MarkEmptySections;
  2715. var
  2716. i, j : longint;
  2717. exesec : TExeSection;
  2718. doremove : boolean;
  2719. begin
  2720. for i:=0 to ExeSectionList.Count-1 do
  2721. begin
  2722. exesec:=TExeSection(ExeSectionList[i]);
  2723. doremove:=not(oso_keep in exesec.SecOptions) and
  2724. (
  2725. (exesec.ObjSectionlist.count=0) or
  2726. (
  2727. (cs_link_strip in current_settings.globalswitches) and
  2728. not(cs_link_separate_dbg_file in current_settings.globalswitches) and
  2729. (oso_debug in exesec.SecOptions)
  2730. )
  2731. );
  2732. if not doremove then
  2733. begin
  2734. { Check if section has no actual data }
  2735. doremove:=true;
  2736. for j:=0 to exesec.ObjSectionList.Count-1 do
  2737. if TObjSection(exesec.ObjSectionList[j]).Size<>0 then
  2738. begin
  2739. doremove:=false;
  2740. break;
  2741. end;
  2742. end;
  2743. if doremove then
  2744. begin
  2745. Comment(V_Debug,'Disabling empty section '+exesec.name);
  2746. exesec.Disabled:=true;
  2747. end;
  2748. end;
  2749. end;
  2750. procedure TExeOutput.RemoveDisabledSections;
  2751. var
  2752. i: longint;
  2753. exesec: TExeSection;
  2754. begin
  2755. for i:=0 to ExeSectionList.Count-1 do
  2756. begin
  2757. exesec:=TExeSection(ExeSectionList[i]);
  2758. if exesec.Disabled then
  2759. ExeSectionList[i]:=nil;
  2760. end;
  2761. ExeSectionList.Pack;
  2762. end;
  2763. procedure TExeOutput.RemoveDebugInfo;
  2764. var
  2765. i : longint;
  2766. exesec : TExeSection;
  2767. begin
  2768. for i:=0 to ExeSectionList.Count-1 do
  2769. begin
  2770. exesec:=TExeSection(ExeSectionList[i]);
  2771. if (oso_debug in exesec.SecOptions) then
  2772. ExeSectionList[i]:=nil;
  2773. end;
  2774. ExeSectionList.Pack;
  2775. end;
  2776. procedure TExeOutput.RemoveUnreferencedSections;
  2777. var
  2778. ObjSectionWorkList : TFPObjectList;
  2779. procedure AddToObjSectionWorkList(aobjsec:TObjSection);
  2780. begin
  2781. if not aobjsec.Used then
  2782. begin
  2783. aobjsec.Used:=true;
  2784. ObjSectionWorkList.Add(aobjsec);
  2785. end;
  2786. end;
  2787. procedure DoReloc(objreloc:TObjRelocation);
  2788. var
  2789. objsym : TObjSymbol;
  2790. refobjsec : TObjSection;
  2791. refgrp : TObjSectionGroup;
  2792. begin
  2793. { Disabled Relocation to 0 }
  2794. if (objreloc.flags and rf_nosymbol)<>0 then
  2795. exit;
  2796. refobjsec:=nil;
  2797. refgrp:=nil;
  2798. if assigned(objreloc.symbol) then
  2799. begin
  2800. objsym:=objreloc.symbol;
  2801. if objsym.bind<>AB_LOCAL then
  2802. begin
  2803. if not assigned(objsym.exesymbol) then
  2804. internalerror(200603063);
  2805. objsym.exesymbol.used:=true;
  2806. objsym:=objsym.exesymbol.objsymbol;
  2807. end;
  2808. if not assigned(objsym.objsection) then
  2809. exit
  2810. else
  2811. refobjsec:=objsym.objsection;
  2812. end
  2813. else if assigned(objreloc.objsection) then
  2814. refobjsec:=objreloc.objsection
  2815. else if assigned(objreloc.group) then
  2816. refgrp:=objreloc.group
  2817. else
  2818. internalerror(200603316);
  2819. if assigned(exemap) then
  2820. begin
  2821. objsym:=objreloc.symbol;
  2822. if assigned(objsym) and (objsym.typ<>AT_SECTION) then
  2823. exemap.Add(' References '+objsym.name+' in '
  2824. +refobjsec.fullname)
  2825. else if assigned(refobjsec) then
  2826. exemap.Add(' References '+refobjsec.fullname)
  2827. else if assigned(refgrp) then
  2828. exemap.Add(' References '+refgrp.Name)
  2829. else
  2830. internalerror(200603316);
  2831. end;
  2832. if assigned(refobjsec) then
  2833. AddToObjSectionWorkList(refobjsec);
  2834. end;
  2835. procedure DoVTableRef(vtable:TExeVTable;VTableIdx:longint);
  2836. var
  2837. i : longint;
  2838. objreloc : TObjRelocation;
  2839. begin
  2840. objreloc:=vtable.VTableRef(VTableIdx);
  2841. if assigned(objreloc) then
  2842. begin
  2843. { Process the relocation now if the ObjSection is
  2844. already processed and marked as used. Otherwise we leave it
  2845. unprocessed. It'll then be resolved when the ObjSection is
  2846. changed to Used }
  2847. if vtable.ExeSymbol.ObjSymbol.ObjSection.Used then
  2848. DoReloc(objreloc);
  2849. end;
  2850. { This recursive walking is done here instead of
  2851. in TExeVTable.VTableRef because we can now process
  2852. all needed relocations }
  2853. for i:=0 to vtable.ChildList.Count-1 do
  2854. DoVTableRef(TExeVTable(vtable.ChildList[i]),VTableIdx);
  2855. end;
  2856. procedure ProcessWorkList;
  2857. var
  2858. hs : string;
  2859. i,k : longint;
  2860. objsec : TObjSection;
  2861. objsym : TObjSymbol;
  2862. code : integer;
  2863. vtableidx : longint;
  2864. vtableexesym : TExeSymbol;
  2865. begin
  2866. while ObjSectionWorkList.Count>0 do
  2867. begin
  2868. objsec:=TObjSection(ObjSectionWorkList.Last);
  2869. if assigned(exemap) then
  2870. exemap.Add('Keeping '+objsec.FullName+' '+ToStr(objsec.ObjRelocations.Count)+' references');
  2871. ObjSectionWorkList.Delete(ObjSectionWorkList.Count-1);
  2872. { Process Relocations }
  2873. for i:=0 to objsec.ObjRelocations.count-1 do
  2874. DoReloc(TObjRelocation(objsec.ObjRelocations[i]));
  2875. { Process Virtual Entry calls }
  2876. if cs_link_opt_vtable in current_settings.globalswitches then
  2877. begin
  2878. for i:=0 to objsec.VTRefList.count-1 do
  2879. begin
  2880. objsym:=TObjSymbol(objsec.VTRefList[i]);
  2881. hs:=objsym.name;
  2882. Delete(hs,1,Pos('_',hs));
  2883. k:=Pos('$$',hs);
  2884. if k=0 then
  2885. internalerror(200603314);
  2886. vtableexesym:=texesymbol(FExeSymbolList.Find(Copy(hs,1,k-1)));
  2887. val(Copy(hs,k+2,length(hs)-k-1),vtableidx,code);
  2888. if (code<>0) then
  2889. internalerror(200603317);
  2890. if not assigned(vtableexesym) then
  2891. internalerror(200603315);
  2892. if not assigned(vtableexesym.vtable) then
  2893. internalerror(200603316);
  2894. DoVTableRef(vtableexesym.vtable,vtableidx);
  2895. end;
  2896. end;
  2897. end;
  2898. end;
  2899. var
  2900. i,j : longint;
  2901. exesec : TExeSection;
  2902. objdata : TObjData;
  2903. objsec : TObjSection;
  2904. begin
  2905. ObjSectionWorkList:=TFPObjectList.Create(false);
  2906. if assigned(exemap) then
  2907. exemap.AddHeader('Removing unreferenced sections');
  2908. { Initialize by marking all sections unused and
  2909. adding the sections with oso_keep flags to the ObjSectionWorkList }
  2910. for i:=0 to ObjDataList.Count-1 do
  2911. begin
  2912. ObjData:=TObjData(ObjDataList[i]);
  2913. for j:=0 to ObjData.ObjSectionList.Count-1 do
  2914. begin
  2915. objsec:=TObjSection(ObjData.ObjSectionList[j]);
  2916. objsec.Used:=false;
  2917. { TODO: remove debug section always keep}
  2918. if oso_debug in objsec.secoptions then
  2919. objsec.Used:=true;
  2920. if (oso_keep in objsec.secoptions) then
  2921. begin
  2922. AddToObjSectionWorkList(objsec);
  2923. if objsec.name='.fpc.n_links' then
  2924. objsec.Used:=false;
  2925. end;
  2926. end;
  2927. end;
  2928. if assigned(entrysym) then
  2929. AddToObjSectionWorkList(entrysym.exesymbol.objsymbol.objsection);
  2930. { Process all sections, add new sections to process based
  2931. on the symbol references }
  2932. ProcessWorkList;
  2933. { Handle stuff like .pdata, i.e. sections that are not referenced
  2934. but must be included if sections they reference are included.
  2935. Loop is necessary because .pdata can reference (via .xdata)
  2936. more text sections, VMTs of exception classes, etc. }
  2937. repeat
  2938. MarkTargetSpecificSections(ObjSectionWorkList);
  2939. if (ObjSectionWorkList.Count=0) then
  2940. break;
  2941. ProcessWorkList;
  2942. until False;
  2943. ObjSectionWorkList.Free;
  2944. ObjSectionWorkList:=nil;
  2945. { Remove unused objsections from ExeSectionList }
  2946. for i:=0 to ExeSectionList.Count-1 do
  2947. begin
  2948. exesec:=TExeSection(ExeSectionList[i]);
  2949. for j:=0 to exesec.ObjSectionlist.count-1 do
  2950. begin
  2951. objsec:=TObjSection(exesec.ObjSectionlist[j]);
  2952. if not objsec.used then
  2953. begin
  2954. if assigned(exemap) then
  2955. exemap.Add('Removing '+objsec.FullName);
  2956. exesec.ObjSectionlist[j]:=nil;
  2957. objsec.ReleaseData;
  2958. end;
  2959. end;
  2960. exesec.ObjSectionlist.Pack;
  2961. end;
  2962. end;
  2963. procedure TExeOutput.FixupRelocations;
  2964. var
  2965. i,j : longint;
  2966. exesec : TExeSection;
  2967. objsec : TObjSection;
  2968. begin
  2969. for i:=0 to ExeSectionList.Count-1 do
  2970. begin
  2971. exesec:=TExeSection(ExeSectionList[i]);
  2972. if not assigned(exesec) then
  2973. continue;
  2974. for j:=0 to exesec.ObjSectionlist.count-1 do
  2975. begin
  2976. objsec:=TObjSection(exesec.ObjSectionlist[j]);
  2977. if not objsec.Used then
  2978. internalerror(200603301);
  2979. if (objsec.ObjRelocations.Count>0) and
  2980. not assigned(objsec.data) then
  2981. internalerror(200205183);
  2982. DoRelocationFixup(objsec);
  2983. {for size = 0 data is not valid PM }
  2984. if assigned(objsec.data) and (objsec.data.size<>objsec.size) then
  2985. internalerror(2010092801);
  2986. end;
  2987. end;
  2988. end;
  2989. procedure TExeOutput.RemoveUnusedExeSymbols;
  2990. var
  2991. i : longint;
  2992. sym : TExeSymbol;
  2993. begin
  2994. { Removing unused symbols }
  2995. for i:=0 to ExeSymbolList.Count-1 do
  2996. begin
  2997. sym:=TExeSymbol(ExeSymbolList[i]);
  2998. { an unresolved weak symbol has objsection=nil }
  2999. if assigned(sym.ObjSymbol.objsection) and
  3000. (not sym.ObjSymbol.objsection.Used) then
  3001. ExeSymbolList[i]:=nil;
  3002. end;
  3003. ExeSymbolList.Pack;
  3004. end;
  3005. procedure TExeOutput.SetCurrMemPos(const AValue: qword);
  3006. begin
  3007. if AValue>MaxMemPos then
  3008. Message1(link_f_executable_too_big, target_os_string);
  3009. FCurrMemPos:=AValue;
  3010. end;
  3011. procedure TExeOutput.WriteExeSectionContent;
  3012. var
  3013. exesec : TExeSection;
  3014. objsec : TObjSection;
  3015. i,j : longint;
  3016. dpos,pad: aword;
  3017. begin
  3018. for j:=0 to ExeSectionList.Count-1 do
  3019. begin
  3020. exesec:=TExeSection(ExeSectionList[j]);
  3021. { don't write normal section if writing only debug info }
  3022. if (ExeWriteMode=ewm_dbgonly) and
  3023. (exesec.SecOptions*[oso_debug,oso_debug_copy]=[]) then
  3024. continue;
  3025. if oso_data in exesec.SecOptions then
  3026. begin
  3027. if exesec.DataPos<FWriter.Size then
  3028. InternalError(2012103001);
  3029. FWriter.Writezeros(exesec.DataPos-FWriter.Size);
  3030. for i:=0 to exesec.ObjSectionList.Count-1 do
  3031. begin
  3032. objsec:=TObjSection(exesec.ObjSectionList[i]);
  3033. if oso_data in objsec.secoptions then
  3034. begin
  3035. if not assigned(objsec.data) then
  3036. internalerror(200603042);
  3037. dpos:=objsec.MemPos-exesec.MemPos+exesec.DataPos;
  3038. pad:=dpos-FWriter.Size;
  3039. { objsection must be within SecAlign bytes from the previous one }
  3040. if (dpos<FWriter.Size) or
  3041. (pad>=max(objsec.SecAlign,1)) then
  3042. internalerror(200602251);
  3043. FWriter.writeZeros(pad);
  3044. FWriter.writearray(objsec.data);
  3045. end;
  3046. end;
  3047. end;
  3048. end;
  3049. end;
  3050. procedure TExeOutput.ReplaceExeSectionList(newlist: TFPList);
  3051. var
  3052. tmp: TFPHashObjectList;
  3053. i: longint;
  3054. begin
  3055. tmp:=TFPHashObjectList.Create(true);
  3056. for i:=0 to newlist.count-1 do
  3057. TFPHashObject(newlist[i]).ChangeOwner(tmp);
  3058. { prevent destruction of existing sections }
  3059. for i:=0 to ExeSectionList.count-1 do
  3060. ExeSectionList.List[i]:=nil;
  3061. FExeSectionList.Free;
  3062. FExeSectionList:=tmp;
  3063. end;
  3064. {****************************************************************************
  3065. TObjInput
  3066. ****************************************************************************}
  3067. constructor TObjInput.create;
  3068. begin
  3069. end;
  3070. procedure TObjInput.inputerror(const s : string);
  3071. begin
  3072. Comment(V_Error,s+' while reading '+InputFileName);
  3073. end;
  3074. class function TObjInput.CanReadObjData(AReader:TObjectReader):boolean;
  3075. begin
  3076. result:=false;
  3077. end;
  3078. procedure TObjInput.ReadSectionContent(Data:TObjData);
  3079. var
  3080. i: longint;
  3081. sec: TObjSection;
  3082. begin
  3083. for i:=0 to Data.ObjSectionList.Count-1 do
  3084. begin
  3085. sec:=TObjSection(Data.ObjSectionList[i]);
  3086. { Skip debug sections }
  3087. if (oso_debug in sec.SecOptions) and
  3088. (cs_link_strip in current_settings.globalswitches) and
  3089. not(cs_link_separate_dbg_file in current_settings.globalswitches) then
  3090. continue;
  3091. if assigned(sec.Data) then
  3092. begin
  3093. FReader.Seek(sec.datapos);
  3094. if not FReader.ReadArray(sec.data,sec.Size) then
  3095. begin
  3096. InputError('Can''t read object data');
  3097. exit;
  3098. end;
  3099. end;
  3100. end;
  3101. end;
  3102. {$ifdef MEMDEBUG}
  3103. initialization
  3104. memobjsymbols:=TMemDebug.create('ObjSymbols');
  3105. memobjsymbols.stop;
  3106. memobjsections:=TMemDebug.create('ObjSections');
  3107. memobjsections.stop;
  3108. finalization
  3109. memobjsymbols.free;
  3110. memobjsections.free;
  3111. {$endif MEMDEBUG}
  3112. end.