ogbase.pas 113 KB

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