ogbase.pas 110 KB

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