ogbase.pas 113 KB

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