ogbase.pas 97 KB

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