ogbase.pas 114 KB

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