ogbase.pas 94 KB

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