ogbase.pas 89 KB

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