ogbase.pas 113 KB

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