ogbase.pas 94 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862
  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; const aPattern:string);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_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. {$ifdef FPC_USE_TLS_DIRECTORY}
  832. ,oso_keep
  833. {$endif FPC_USE_TLS_DIRECTORY}
  834. ],
  835. {pdata} [oso_data,oso_load,oso_readonly {$ifndef x86_64},oso_keep{$endif}],
  836. {stub} [oso_Data,oso_load,oso_readonly,oso_executable],
  837. {data_nonlazy} [oso_Data,oso_load,oso_write],
  838. {data_lazy} [oso_Data,oso_load,oso_write],
  839. {init_func} [oso_Data,oso_load],
  840. {term_func} [oso_Data,oso_load],
  841. {stab} [oso_Data,oso_noload,oso_debug],
  842. {stabstr} [oso_Data,oso_noload,oso_strings,oso_debug],
  843. {iData2} [oso_Data,oso_load,oso_write],
  844. {iData4} [oso_Data,oso_load,oso_write],
  845. {iData5} [oso_Data,oso_load,oso_write],
  846. {iData6} [oso_Data,oso_load,oso_write],
  847. {iData7} [oso_Data,oso_load,oso_write],
  848. {eData} [oso_Data,oso_load,oso_readonly],
  849. {eh_frame} [oso_Data,oso_load,oso_readonly],
  850. {debug_frame} [oso_Data,oso_noload,oso_debug],
  851. {debug_info} [oso_Data,oso_noload,oso_debug],
  852. {debug_line} [oso_Data,oso_noload,oso_debug],
  853. {debug_abbrev} [oso_Data,oso_noload,oso_debug],
  854. {fpc} [oso_Data,oso_load,oso_write,oso_keep],
  855. {toc} [oso_Data,oso_load,oso_readonly],
  856. {init} [oso_Data,oso_load,oso_readonly,oso_executable,oso_keep],
  857. {fini} [oso_Data,oso_load,oso_readonly,oso_executable,oso_keep],
  858. {objc_class} [oso_data,oso_load],
  859. {objc_meta_class} [oso_data,oso_load],
  860. {objc_cat_cls_meth} [oso_data,oso_load],
  861. {objc_cat_inst_meth} [oso_data,oso_load],
  862. {objc_protocol} [oso_data,oso_load],
  863. {objc_string_object} [oso_data,oso_load],
  864. {objc_cls_meth} [oso_data,oso_load],
  865. {objc_inst_meth} [oso_data,oso_load],
  866. {objc_cls_refs} [oso_data,oso_load],
  867. {objc_message_refs} [oso_data,oso_load],
  868. {objc_symbols} [oso_data,oso_load],
  869. {objc_category} [oso_data,oso_load],
  870. {objc_class_vars} [oso_data,oso_load],
  871. {objc_instance_vars} [oso_data,oso_load],
  872. {objc_module_info} [oso_data,oso_load],
  873. {objc_class_names} [oso_data,oso_load],
  874. {objc_meth_var_types} [oso_data,oso_load],
  875. {objc_meth_var_names} [oso_data,oso_load],
  876. {objc_selector_strs} [oso_data,oso_load],
  877. {objc_protocol_ext} [oso_data,oso_load],
  878. {objc_class_ext} [oso_data,oso_load],
  879. {objc_property} [oso_data,oso_load],
  880. {objc_image_info} [oso_data,oso_load],
  881. {objc_cstring_object} [oso_data,oso_load],
  882. {objc_sel_fixup} [oso_data,oso_load],
  883. {sec_objc_data} [oso_data,oso_load],
  884. {sec_objc_const} [oso_data,oso_load],
  885. {sec_objc_sup_refs} [oso_data,oso_load],
  886. {sec_data_coalesced} [oso_data,oso_load],
  887. {sec_objc_classlist} [oso_data,oso_load],
  888. {sec_objc_nlclasslist} [oso_data,oso_load],
  889. {sec_objc_catlist} [oso_data,oso_load],
  890. {sec_objc_nlcatlist} [oso_data,oso_load],
  891. {sec_objc_protolist'} [oso_data,oso_load]
  892. );
  893. begin
  894. result:=secoptions[atype];
  895. end;
  896. function TObjData.sectiontype2align(atype:TAsmSectiontype):shortint;
  897. begin
  898. case atype of
  899. sec_stabstr,sec_debug_info,sec_debug_line,sec_debug_abbrev:
  900. result:=1;
  901. sec_code,
  902. sec_bss,
  903. sec_data:
  904. result:=16;
  905. { For idata (at least idata2) it must be 4 bytes, because
  906. an entry is always (also in win64) 20 bytes and aligning
  907. on 8 bytes will insert 4 bytes between the entries resulting
  908. in a corrupt idata section.
  909. Same story with .pdata, it has 4-byte elements which should
  910. be packed without gaps. }
  911. sec_idata2,sec_idata4,sec_idata5,sec_idata6,sec_idata7,sec_pdata:
  912. result:=4;
  913. else
  914. result:=sizeof(pint);
  915. end;
  916. end;
  917. function TObjData.createsection(atype:TAsmSectionType;const aname:string;aorder:TAsmSectionOrder):TObjSection;
  918. begin
  919. result:=createsection(sectionname(atype,aname,aorder),sectiontype2align(atype),sectiontype2options(atype));
  920. end;
  921. function TObjData.createsection(const aname:string;aalign:shortint;aoptions:TObjSectionOptions;DiscardDuplicate:boolean):TObjSection;
  922. begin
  923. if DiscardDuplicate then
  924. result:=TObjSection(FObjSectionList.Find(aname))
  925. else
  926. result:=nil;
  927. if not assigned(result) then
  928. begin
  929. result:=CObjSection.create(FObjSectionList,aname,aalign,aoptions);
  930. result.ObjData:=self;
  931. end;
  932. FCurrObjSec:=result;
  933. end;
  934. procedure TObjData.CreateDebugSections;
  935. begin
  936. end;
  937. function TObjData.FindSection(const aname:string):TObjSection;
  938. begin
  939. result:=TObjSection(FObjSectionList.Find(aname));
  940. end;
  941. procedure TObjData.setsection(asec:TObjSection);
  942. begin
  943. if asec.ObjData<>self then
  944. internalerror(200403041);
  945. FCurrObjSec:=asec;
  946. end;
  947. function TObjData.createsymbol(const aname:string):TObjSymbol;
  948. begin
  949. result:=TObjSymbol(FObjSymbolList.Find(aname));
  950. if not assigned(result) then
  951. result:=TObjSymbol.Create(FObjSymbolList,aname);
  952. end;
  953. function TObjData.symboldefine(asmsym:TAsmSymbol):TObjSymbol;
  954. begin
  955. if assigned(asmsym) then
  956. begin
  957. if not assigned(asmsym.cachedObjSymbol) then
  958. begin
  959. result:=symboldefine(asmsym.name,asmsym.bind,asmsym.typ);
  960. asmsym.cachedObjSymbol:=result;
  961. FCachedAsmSymbolList.add(asmsym);
  962. end
  963. else
  964. begin
  965. result:=TObjSymbol(asmsym.cachedObjSymbol);
  966. result.SetAddress(CurrPass,CurrObjSec,asmsym.bind,asmsym.typ);
  967. { Register also in TObjSection }
  968. CurrObjSec.AddSymbolDefine(result);
  969. end;
  970. end
  971. else
  972. result:=nil;
  973. end;
  974. function TObjData.symboldefine(const aname:string;abind:TAsmsymbind;atyp:Tasmsymtype):TObjSymbol;
  975. begin
  976. if not assigned(CurrObjSec) then
  977. internalerror(200603051);
  978. result:=CreateSymbol(aname);
  979. { Register also in TObjSection }
  980. CurrObjSec.AddSymbolDefine(result);
  981. result.SetAddress(CurrPass,CurrObjSec,abind,atyp);
  982. end;
  983. function TObjData.symbolref(asmsym:TAsmSymbol):TObjSymbol;
  984. begin
  985. if assigned(asmsym) then
  986. begin
  987. if not assigned(asmsym.cachedObjSymbol) then
  988. begin
  989. result:=symbolref(asmsym.name);
  990. asmsym.cachedObjSymbol:=result;
  991. FCachedAsmSymbolList.add(asmsym);
  992. end
  993. else
  994. result:=TObjSymbol(asmsym.cachedObjSymbol);
  995. end
  996. else
  997. result:=nil;
  998. end;
  999. function TObjData.symbolref(const aname:string):TObjSymbol;
  1000. begin
  1001. if not assigned(CurrObjSec) then
  1002. internalerror(200603052);
  1003. result:=CreateSymbol(aname);
  1004. end;
  1005. procedure TObjData.ResetCachedAsmSymbols;
  1006. var
  1007. i : longint;
  1008. begin
  1009. for i:=0 to FCachedAsmSymbolList.Count-1 do
  1010. tasmsymbol(FCachedAsmSymbolList[i]).cachedObjSymbol:=nil;
  1011. FCachedAsmSymbolList.Clear;
  1012. end;
  1013. procedure TObjData.writebytes(const Data;len:aword);
  1014. begin
  1015. if not assigned(CurrObjSec) then
  1016. internalerror(200402251);
  1017. CurrObjSec.write(Data,len);
  1018. end;
  1019. procedure TObjData.alloc(len:aword);
  1020. begin
  1021. if not assigned(CurrObjSec) then
  1022. internalerror(200402252);
  1023. CurrObjSec.alloc(len);
  1024. end;
  1025. procedure TObjData.allocalign(len:shortint);
  1026. begin
  1027. if not assigned(CurrObjSec) then
  1028. internalerror(200402253);
  1029. CurrObjSec.alloc(align(CurrObjSec.size,len)-CurrObjSec.size);
  1030. end;
  1031. procedure TObjData.section_afteralloc(p:TObject;arg:pointer);
  1032. begin
  1033. with TObjSection(p) do
  1034. alloc(align(size,secalign)-size);
  1035. end;
  1036. procedure TObjData.section_afterwrite(p:TObject;arg:pointer);
  1037. begin
  1038. with TObjSection(p) do
  1039. begin
  1040. if assigned(Data) then
  1041. writezeros(align(size,secalign)-size);
  1042. end;
  1043. end;
  1044. procedure TObjData.section_reset(p:TObject;arg:pointer);
  1045. begin
  1046. with TObjSection(p) do
  1047. begin
  1048. Size:=0;
  1049. Datapos:=0;
  1050. mempos:=0;
  1051. end;
  1052. end;
  1053. procedure TObjData.beforealloc;
  1054. begin
  1055. { create stabs sections if debugging }
  1056. if assigned(StabsSec) then
  1057. begin
  1058. StabsSec.Alloc(sizeof(TObjStabEntry));
  1059. StabStrSec.Alloc(1);
  1060. end;
  1061. end;
  1062. procedure TObjData.beforewrite;
  1063. var
  1064. s : string[1];
  1065. hstab : TObjStabEntry;
  1066. begin
  1067. { create stabs sections if debugging }
  1068. if assigned(StabsSec) then
  1069. begin
  1070. { Create dummy HdrSym stab, it will be overwritten in AfterWrite }
  1071. fillchar(hstab,sizeof(hstab),0);
  1072. StabsSec.Write(hstab,sizeof(hstab));
  1073. { start of stabstr }
  1074. s:=#0;
  1075. StabStrSec.write(s[1],length(s));
  1076. end;
  1077. end;
  1078. procedure TObjData.afteralloc;
  1079. begin
  1080. FObjSectionList.ForEachCall(@section_afteralloc,nil);
  1081. end;
  1082. procedure TObjData.afterwrite;
  1083. var
  1084. s : string[1];
  1085. hstab : TObjStabEntry;
  1086. begin
  1087. FObjSectionList.ForEachCall(@section_afterwrite,nil);
  1088. { For the stab section we need an HdrSym which can now be
  1089. calculated more easily }
  1090. if assigned(StabsSec) then
  1091. begin
  1092. { end of stabstr }
  1093. s:=#0;
  1094. StabStrSec.write(s[1],length(s));
  1095. { header stab }
  1096. hstab.strpos:=1;
  1097. hstab.ntype:=0;
  1098. hstab.nother:=0;
  1099. hstab.ndesc:=(StabsSec.Size div sizeof(TObjStabEntry))-1;
  1100. hstab.nvalue:=StabStrSec.Size;
  1101. StabsSec.Data.seek(0);
  1102. StabsSec.Data.write(hstab,sizeof(hstab));
  1103. end;
  1104. end;
  1105. procedure TObjData.resetsections;
  1106. begin
  1107. FObjSectionList.ForEachCall(@section_reset,nil);
  1108. end;
  1109. {****************************************************************************
  1110. TObjOutput
  1111. ****************************************************************************}
  1112. constructor TObjOutput.create(AWriter:TObjectWriter);
  1113. begin
  1114. FWriter:=AWriter;
  1115. CObjData:=TObjData;
  1116. end;
  1117. destructor TObjOutput.destroy;
  1118. begin
  1119. inherited destroy;
  1120. end;
  1121. function TObjOutput.newObjData(const n:string):TObjData;
  1122. begin
  1123. result:=CObjData.create(n);
  1124. if (cs_use_lineinfo in current_settings.globalswitches) or
  1125. (cs_debuginfo in current_settings.moduleswitches) then
  1126. result.CreateDebugSections;
  1127. end;
  1128. function TObjOutput.startObjectfile(const fn:string):boolean;
  1129. begin
  1130. result:=false;
  1131. { start the writer already, so the .a generation can initialize
  1132. the position of the current objectfile }
  1133. if not FWriter.createfile(fn) then
  1134. Comment(V_Fatal,'Can''t create object '+fn);
  1135. result:=true;
  1136. end;
  1137. function TObjOutput.writeobjectfile(Data:TObjData):boolean;
  1138. begin
  1139. if errorcount=0 then
  1140. result:=writeData(Data)
  1141. else
  1142. result:=true;
  1143. { close the writer }
  1144. FWriter.closefile;
  1145. end;
  1146. procedure TObjOutput.exportsymbol(p:TObjSymbol);
  1147. begin
  1148. { export globals and common symbols, this is needed
  1149. for .a files }
  1150. if p.bind in [AB_GLOBAL,AB_COMMON] then
  1151. FWriter.writesym(p.name);
  1152. end;
  1153. {****************************************************************************
  1154. TExeVTable
  1155. ****************************************************************************}
  1156. constructor TExeVTable.Create(AExeSymbol:TExeSymbol);
  1157. begin
  1158. ExeSymbol:=AExeSymbol;
  1159. if ExeSymbol.State=symstate_undefined then
  1160. internalerror(200604012);
  1161. ChildList:=TFPObjectList.Create(false);
  1162. end;
  1163. destructor TExeVTable.Destroy;
  1164. begin
  1165. ChildList.Free;
  1166. if assigned(EntryArray) then
  1167. Freemem(EntryArray);
  1168. end;
  1169. procedure TExeVTable.CheckIdx(VTableIdx:longint);
  1170. var
  1171. OldEntryCnt : longint;
  1172. begin
  1173. if VTableIdx>=EntryCnt then
  1174. begin
  1175. OldEntryCnt:=EntryCnt;
  1176. EntryCnt:=VTableIdx+1;
  1177. ReAllocMem(EntryArray,EntryCnt*sizeof(TVTableEntry));
  1178. FillChar(EntryArray[OldEntryCnt],(EntryCnt-OldEntryCnt)*sizeof(TVTableEntry),0);
  1179. end;
  1180. end;
  1181. procedure TExeVTable.AddChild(vt:TExeVTable);
  1182. begin
  1183. ChildList.Add(vt);
  1184. end;
  1185. procedure TExeVTable.AddEntry(VTableIdx:Longint);
  1186. var
  1187. i : longint;
  1188. objreloc : TObjRelocation;
  1189. vtblentryoffset : aword;
  1190. begin
  1191. CheckIdx(VTableIdx);
  1192. vtblentryoffset:=ExeSymbol.ObjSymbol.Offset+longword(VTableIdx)*sizeof(pint);
  1193. { Find and disable relocation }
  1194. for i:=0 to ExeSymbol.ObjSymbol.ObjSection.ObjRelocations.Count-1 do
  1195. begin
  1196. objreloc:=TObjRelocation(ExeSymbol.ObjSymbol.ObjSection.ObjRelocations[i]);
  1197. if objreloc.dataoffset=vtblentryoffset then
  1198. begin
  1199. EntryArray[VTableIdx].ObjRelocation:=objreloc;
  1200. EntryArray[VTableIdx].OrgRelocType:=objreloc.typ;
  1201. objreloc.typ:=RELOC_ZERO;
  1202. break;
  1203. end;
  1204. end;
  1205. if not assigned(EntryArray[VTableIdx].ObjRelocation) then
  1206. internalerror(200604011);
  1207. end;
  1208. procedure TExeVTable.SetVTableSize(ASize:longint);
  1209. begin
  1210. if EntryCnt<>0 then
  1211. internalerror(200603313);
  1212. EntryCnt:=ASize div sizeof(pint);
  1213. EntryArray:=AllocMem(EntryCnt*sizeof(TVTableEntry));
  1214. end;
  1215. function TExeVTable.VTableRef(VTableIdx:Longint):TObjRelocation;
  1216. begin
  1217. result:=nil;
  1218. CheckIdx(VTableIdx);
  1219. if EntryArray[VTableIdx].Used then
  1220. exit;
  1221. { Restore relocation if available }
  1222. if assigned(EntryArray[VTableIdx].ObjRelocation) then
  1223. begin
  1224. EntryArray[VTableIdx].ObjRelocation.typ:=EntryArray[VTableIdx].OrgRelocType;
  1225. result:=EntryArray[VTableIdx].ObjRelocation;
  1226. end;
  1227. EntryArray[VTableIdx].Used:=true;
  1228. end;
  1229. {****************************************************************************
  1230. TExeSection
  1231. ****************************************************************************}
  1232. constructor TExeSection.create(AList:TFPHashObjectList;const AName:string);
  1233. begin
  1234. inherited create(AList,AName);
  1235. Size:=0;
  1236. MemPos:=0;
  1237. DataPos:=0;
  1238. FSecSymIdx:=0;
  1239. FObjSectionList:=TFPObjectList.Create(false);
  1240. end;
  1241. destructor TExeSection.destroy;
  1242. begin
  1243. ObjSectionList.Free;
  1244. inherited destroy;
  1245. end;
  1246. procedure TExeSection.AddObjSection(objsec:TObjSection);
  1247. begin
  1248. ObjSectionList.Add(objsec);
  1249. if (SecOptions<>[]) then
  1250. begin
  1251. { Only if the section contains (un)initialized data the
  1252. data flag must match. This check is not needed if the
  1253. section is empty for a symbol allocation }
  1254. if (objsec.size>0) and
  1255. ((oso_Data in SecOptions)<>(oso_Data in objsec.SecOptions)) then
  1256. Comment(V_Error,'Incompatible section options');
  1257. end
  1258. else
  1259. begin
  1260. { inherit section options }
  1261. SecAlign:=objsec.SecAlign;
  1262. SecOptions:=SecOptions+objsec.SecOptions;
  1263. end;
  1264. { relate ObjSection to ExeSection, and mark it Used by default }
  1265. objsec.ExeSection:=self;
  1266. objsec.Used:=true;
  1267. end;
  1268. {****************************************************************************
  1269. TStaticLibrary
  1270. ****************************************************************************}
  1271. constructor TStaticLibrary.create(AList:TFPHashObjectList;const AName:string;AReader:TObjectReader;AObjInputClass:TObjInputClass);
  1272. begin
  1273. inherited create(AList,AName);
  1274. FArReader:=AReader;
  1275. FObjInputClass:=AObjInputClass;
  1276. end;
  1277. destructor TStaticLibrary.destroy;
  1278. begin
  1279. ArReader.Free;
  1280. inherited destroy;
  1281. end;
  1282. {****************************************************************************
  1283. TImportLibrary
  1284. ****************************************************************************}
  1285. constructor TImportLibrary.create(AList:TFPHashObjectList;const AName:string);
  1286. begin
  1287. inherited create(AList,AName);
  1288. FImportSymbolList:=TFPHashObjectList.Create(true);
  1289. end;
  1290. destructor TImportLibrary.destroy;
  1291. begin
  1292. ImportSymbolList.Free;
  1293. inherited destroy;
  1294. end;
  1295. {****************************************************************************
  1296. TImportSymbol
  1297. ****************************************************************************}
  1298. constructor TImportSymbol.create(AList:TFPHashObjectList;
  1299. const AName,AMangledName:string;AOrdNr:longint;AIsVar:boolean);
  1300. begin
  1301. inherited Create(AList, AName);
  1302. FOrdNr:=AOrdNr;
  1303. FIsVar:=AIsVar;
  1304. FMangledName:=AMangledName;
  1305. { Replace ? and @ in import name, since GNU AS does not allow these characters in symbol names. }
  1306. { This allows to import VC++ mangled names from DLLs. }
  1307. if target_info.system in systems_all_windows then
  1308. begin
  1309. Replace(FMangledName,'?','__q$$');
  1310. {$ifdef arm}
  1311. { @ symbol is not allowed in ARM assembler only }
  1312. Replace(FMangledName,'@','__a$$');
  1313. {$endif arm}
  1314. end;
  1315. end;
  1316. {****************************************************************************
  1317. TExeOutput
  1318. ****************************************************************************}
  1319. constructor TExeOutput.create;
  1320. begin
  1321. { init writer }
  1322. FWriter:=TObjectwriter.create;
  1323. FExeWriteMode:=ewm_exefull;
  1324. { object files }
  1325. FObjDataList:=TFPObjectList.Create(true);
  1326. { symbols }
  1327. FExeSymbolList:=TFPHashObjectList.Create(true);
  1328. FUnresolvedExeSymbols:=TFPObjectList.Create(false);
  1329. FExternalObjSymbols:=TFPObjectList.Create(false);
  1330. FCommonObjSymbols:=TFPObjectList.Create(false);
  1331. FExeVTableList:=TFPObjectList.Create(false);
  1332. FEntryName:='start';
  1333. { sections }
  1334. FExeSectionList:=TFPHashObjectList.Create(true);
  1335. FImageBase:=0;
  1336. {$ifdef cpu16bitaddr}
  1337. SectionMemAlign:=$10;
  1338. SectionDataAlign:=$10;
  1339. {$else cpu16bitaddr}
  1340. SectionMemAlign:=$1000;
  1341. SectionDataAlign:=$200;
  1342. {$endif cpu16bitaddr}
  1343. FCExeSection:=TExeSection;
  1344. FCObjData:=TObjData;
  1345. end;
  1346. destructor TExeOutput.destroy;
  1347. begin
  1348. FExeSymbolList.free;
  1349. UnresolvedExeSymbols.free;
  1350. ExternalObjSymbols.free;
  1351. CommonObjSymbols.free;
  1352. ExeVTableList.free;
  1353. FExeSectionList.free;
  1354. ObjDatalist.free;
  1355. FWriter.free;
  1356. inherited destroy;
  1357. end;
  1358. function TExeOutput.WriteExeFile(const fn:string):boolean;
  1359. begin
  1360. result:=false;
  1361. if FWriter.createfile(fn) then
  1362. begin
  1363. { Only write the .o if there are no errors }
  1364. if errorcount=0 then
  1365. result:=writedata
  1366. else
  1367. result:=true;
  1368. { close the writer }
  1369. FWriter.closefile;
  1370. end
  1371. else
  1372. Comment(V_Fatal,'Can''t create executable '+fn);
  1373. end;
  1374. procedure TExeOutput.ParseScript (linkscript:TCmdStrList);
  1375. begin
  1376. end;
  1377. function TExeOutput.FindExeSection(const aname:string):TExeSection;
  1378. begin
  1379. result:=TExeSection(ExeSectionList.Find(aname));
  1380. end;
  1381. procedure TExeOutput.AddObjData(ObjData:TObjData);
  1382. begin
  1383. if ObjData.classtype<>FCObjData then
  1384. Comment(V_Error,'Invalid input object format for '+ObjData.name+' got '+ObjData.classname+' expected '+FCObjData.classname);
  1385. ObjDataList.Add(ObjData);
  1386. end;
  1387. procedure TExeOutput.Load_Start;
  1388. begin
  1389. ObjDataList.Clear;
  1390. { Globals defined in the linker script }
  1391. if not assigned(internalObjData) then
  1392. internalObjData:=CObjData.create('*Internal*');
  1393. AddObjData(internalObjData);
  1394. { Common Data section }
  1395. commonObjSection:=internalObjData.createsection(sec_bss,'');
  1396. end;
  1397. procedure TExeOutput.Load_EntryName(const aname:string);
  1398. begin
  1399. FEntryName:=aname;
  1400. end;
  1401. procedure TExeOutput.Load_IsSharedLibrary;
  1402. begin
  1403. IsSharedLibrary:=true;
  1404. end;
  1405. procedure TExeOutput.Load_ImageBase(const avalue:string);
  1406. var
  1407. code : integer;
  1408. objsec : TObjSection;
  1409. objsym : TObjSymbol;
  1410. exesym : TExeSymbol;
  1411. begin
  1412. val(avalue,ImageBase,code);
  1413. if code<>0 then
  1414. Comment(V_Error,'Invalid number '+avalue);
  1415. { Create __image_base__ symbol, create the symbol
  1416. in a section with adress 0 and at offset 0 }
  1417. objsec:=internalObjData.createsection('*__image_base__',0,[]);
  1418. internalObjData.setsection(objsec);
  1419. objsym:=internalObjData.SymbolDefine('__image_base__',AB_GLOBAL,AT_FUNCTION);
  1420. exesym:=texesymbol.Create(FExeSymbolList,objsym.name);
  1421. exesym.ObjSymbol:=objsym;
  1422. end;
  1423. procedure TExeOutput.Load_Symbol(const aname:string);
  1424. begin
  1425. internalObjData.createsection('*'+aname,0,[]);
  1426. internalObjData.SymbolDefine(aname,AB_GLOBAL,AT_FUNCTION);
  1427. end;
  1428. procedure TExeOutput.Load_ProvideSymbol(const aname:string);
  1429. begin
  1430. if assigned(ExeSymbolList.Find(aname)) then
  1431. exit;
  1432. internalObjData.createsection('*'+aname,0,[]);
  1433. // Use AB_COMMON to avoid muliple defined complaints
  1434. internalObjData.SymbolDefine(aname,AB_COMMON,AT_DATA);
  1435. end;
  1436. procedure TExeOutput.Order_Start;
  1437. begin
  1438. end;
  1439. procedure TExeOutput.Order_End;
  1440. begin
  1441. internalObjData.afterwrite;
  1442. end;
  1443. procedure TExeOutput.Order_ExeSection(const aname:string);
  1444. var
  1445. sec : TExeSection;
  1446. begin
  1447. sec:=FindExeSection(aname);
  1448. if not assigned(sec) then
  1449. sec:=CExeSection.create(ExeSectionList,aname);
  1450. { Clear ExeSection contents }
  1451. FCurrExeSec:=sec;
  1452. end;
  1453. procedure TExeOutput.Order_EndExeSection;
  1454. begin
  1455. if not assigned(CurrExeSec) then
  1456. internalerror(200602184);
  1457. FCurrExeSec:=nil;
  1458. end;
  1459. procedure TExeOutput.Order_ObjSection(const aname:string);
  1460. var
  1461. i,j : longint;
  1462. ObjData : TObjData;
  1463. objsec : TObjSection;
  1464. TmpObjSectionList : TFPObjectList;
  1465. begin
  1466. if not assigned(CurrExeSec) then
  1467. internalerror(200602181);
  1468. TmpObjSectionList:=TFPObjectList.Create(false);
  1469. for i:=0 to ObjDataList.Count-1 do
  1470. begin
  1471. ObjData:=TObjData(ObjDataList[i]);
  1472. for j:=0 to ObjData.ObjSectionList.Count-1 do
  1473. begin
  1474. objsec:=TObjSection(ObjData.ObjSectionList[j]);
  1475. if (not objsec.Used) and
  1476. MatchPattern(aname,objsec.name) then
  1477. TmpObjSectionList.Add(objsec);
  1478. end;
  1479. end;
  1480. { Order list if needed }
  1481. Order_ObjSectionList(TmpObjSectionList,aname);
  1482. { Add the (ordered) list to the current ExeSection }
  1483. for i:=0 to TmpObjSectionList.Count-1 do
  1484. begin
  1485. objsec:=TObjSection(TmpObjSectionList[i]);
  1486. CurrExeSec.AddObjSection(objsec);
  1487. end;
  1488. TmpObjSectionList.Free;
  1489. end;
  1490. procedure TExeOutput.Order_ObjSectionList(ObjSectionList : TFPObjectList; const aPattern:string);
  1491. begin
  1492. end;
  1493. procedure TExeOutput.Order_Symbol(const aname:string);
  1494. var
  1495. ObjSection : TObjSection;
  1496. begin
  1497. ObjSection:=internalObjData.findsection('*'+aname);
  1498. if not assigned(ObjSection) then
  1499. internalerror(200603041);
  1500. CurrExeSec.AddObjSection(ObjSection);
  1501. end;
  1502. procedure TExeOutput.Order_ProvideSymbol(const aname:string);
  1503. var
  1504. ObjSection : TObjSection;
  1505. begin
  1506. ObjSection:=internalObjData.findsection('*'+aname);
  1507. if not assigned(ObjSection) then
  1508. internalerror(200603041);
  1509. { Only include this section if the symbol doesn't
  1510. exist otherwisee }
  1511. if not assigned(ExeSymbolList.Find(aname)) then
  1512. CurrExeSec.AddObjSection(ObjSection);
  1513. end;
  1514. procedure TExeOutput.Order_Align(const avalue:string);
  1515. var
  1516. code : integer;
  1517. alignval : shortint;
  1518. objsec : TObjSection;
  1519. begin
  1520. val(avalue,alignval,code);
  1521. if code<>0 then
  1522. Comment(V_Error,'Invalid number '+avalue);
  1523. if alignval<=0 then
  1524. exit;
  1525. { Create an empty section with the required aligning }
  1526. inc(Fzeronr);
  1527. objsec:=internalObjData.createsection('*align'+tostr(Fzeronr),alignval,CurrExeSec.SecOptions+[oso_Data,oso_keep]);
  1528. CurrExeSec.AddObjSection(objsec);
  1529. end;
  1530. procedure TExeOutput.Order_Zeros(const avalue:string);
  1531. var
  1532. zeros : array[0..1023] of byte;
  1533. code : integer;
  1534. len : longint;
  1535. objsec : TObjSection;
  1536. begin
  1537. val(avalue,len,code);
  1538. if code<>0 then
  1539. Comment(V_Error,'Invalid number '+avalue);
  1540. if len<=0 then
  1541. exit;
  1542. if len>sizeof(zeros) then
  1543. internalerror(200602254);
  1544. fillchar(zeros,len,0);
  1545. inc(Fzeronr);
  1546. objsec:=internalObjData.createsection('*zeros'+tostr(Fzeronr),0,CurrExeSec.SecOptions+[oso_Data,oso_keep]);
  1547. internalObjData.writebytes(zeros,len);
  1548. CurrExeSec.AddObjSection(objsec);
  1549. end;
  1550. procedure TExeOutput.Order_Values(bytesize : aword; const avalue:string);
  1551. const
  1552. MAXVAL = 128;
  1553. var
  1554. bytevalues : array[0..MAXVAL-1] of byte;
  1555. twobytevalues : array[0..MAXVAL-1] of word;
  1556. fourbytevalues : array[0..MAXVAL-1] of dword;
  1557. eightbytevalues : array[0..MAXVAL-1] of qword;
  1558. allvals, oneval : string;
  1559. len, commapos : longint;
  1560. indexpos, code : integer;
  1561. anumval : qword;
  1562. signedval : int64;
  1563. objsec : TObjSection;
  1564. begin
  1565. indexpos:=0;
  1566. allvals:=avalue;
  1567. repeat
  1568. commapos:=pos(',',allvals);
  1569. if commapos>0 then
  1570. begin
  1571. oneval:=trim(copy(allvals,1,commapos-1));
  1572. allvals:=copy(allvals,commapos+1,length(allvals));
  1573. end
  1574. else
  1575. begin
  1576. oneval:=trim(allvals);
  1577. allvals:='';
  1578. end;
  1579. if oneval<>'' then
  1580. begin
  1581. if oneval[1]='-' then
  1582. begin
  1583. val(oneval,signedval,code);
  1584. anumval:=qword(signedval);
  1585. end
  1586. else
  1587. val(oneval,anumval,code);
  1588. if code<>0 then
  1589. Comment(V_Error,'Invalid number '+avalue)
  1590. else
  1591. begin
  1592. if (indexpos<MAXVAL) then
  1593. begin
  1594. if source_info.endian<>target_info.endian then
  1595. swapendian(anumval);
  1596. { No range checking here }
  1597. if bytesize=1 then
  1598. bytevalues[indexpos]:=byte(anumval)
  1599. else if bytesize=2 then
  1600. twobytevalues[indexpos]:=word(anumval)
  1601. else if bytesize=4 then
  1602. fourbytevalues[indexpos]:=dword(anumval)
  1603. else if bytesize=8 then
  1604. eightbytevalues[indexpos]:=anumval;
  1605. inc(indexpos);
  1606. end
  1607. else
  1608. Comment(V_Error,'Buffer overrun in Order_values');
  1609. end;
  1610. end;
  1611. until allvals='';
  1612. if indexpos=0 then
  1613. begin
  1614. Comment(V_Error,'Invalid number '+avalue);
  1615. exit;
  1616. end;
  1617. if indexpos=MAXVAL then
  1618. begin
  1619. Comment(V_Error,'Too many values '+avalue);
  1620. internalerror(200602254);
  1621. end;
  1622. len:=bytesize*indexpos;
  1623. inc(Fvaluesnr);
  1624. objsec:=internalObjData.createsection('*values'+tostr(Fvaluesnr),0,CurrExeSec.SecOptions+[oso_Data,oso_keep]);
  1625. if bytesize=1 then
  1626. internalObjData.writebytes(bytevalues,len)
  1627. else if bytesize=2 then
  1628. internalObjData.writebytes(twobytevalues,len)
  1629. else if bytesize=4 then
  1630. internalObjData.writebytes(fourbytevalues,len)
  1631. else if bytesize=8 then
  1632. internalObjData.writebytes(eightbytevalues,len);
  1633. CurrExeSec.AddObjSection(objsec);
  1634. end;
  1635. procedure TExeOutput.MemPos_Start;
  1636. begin
  1637. CurrMemPos:=0;
  1638. end;
  1639. procedure TExeOutput.MemPos_Header;
  1640. begin
  1641. end;
  1642. procedure TExeOutput.MemPos_ExeSection(const aname:string);
  1643. var
  1644. i : longint;
  1645. objsec : TObjSection;
  1646. begin
  1647. { Section can be removed }
  1648. FCurrExeSec:=FindExeSection(aname);
  1649. if not assigned(CurrExeSec) then
  1650. exit;
  1651. { Alignment of ExeSection }
  1652. CurrMemPos:=align(CurrMemPos,SectionMemAlign);
  1653. CurrExeSec.MemPos:=CurrMemPos;
  1654. { set position of object ObjSections }
  1655. for i:=0 to CurrExeSec.ObjSectionList.Count-1 do
  1656. begin
  1657. objsec:=TObjSection(CurrExeSec.ObjSectionList[i]);
  1658. CurrMemPos:=objsec.setmempos(CurrMemPos);
  1659. end;
  1660. { calculate size of the section }
  1661. CurrExeSec.Size:=CurrMemPos-CurrExeSec.MemPos;
  1662. end;
  1663. procedure TExeOutput.MemPos_EndExeSection;
  1664. begin
  1665. if not assigned(CurrExeSec) then
  1666. exit;
  1667. FCurrExeSec:=nil;
  1668. end;
  1669. procedure TExeOutput.DataPos_Start;
  1670. begin
  1671. end;
  1672. procedure TExeOutput.DataPos_Header;
  1673. begin
  1674. end;
  1675. procedure TExeOutput.DataPos_ExeSection(const aname:string);
  1676. var
  1677. i : longint;
  1678. objsec : TObjSection;
  1679. begin
  1680. { Section can be removed }
  1681. FCurrExeSec:=FindExeSection(aname);
  1682. if not assigned(CurrExeSec) then
  1683. exit;
  1684. { don't write normal section if writing only debug info }
  1685. if (ExeWriteMode=ewm_dbgonly) and
  1686. not(oso_debug in CurrExeSec.SecOptions) then
  1687. exit;
  1688. if (oso_Data in currexesec.SecOptions) then
  1689. begin
  1690. CurrDataPos:=align(CurrDataPos,SectionDataAlign);
  1691. CurrExeSec.DataPos:=CurrDataPos;
  1692. end;
  1693. { set position of object ObjSections }
  1694. for i:=0 to CurrExeSec.ObjSectionList.Count-1 do
  1695. begin
  1696. objsec:=TObjSection(CurrExeSec.ObjSectionList[i]);
  1697. if (oso_Data in objsec.SecOptions) then
  1698. begin
  1699. if not(oso_Data in currexesec.SecOptions) then
  1700. internalerror(200603043);
  1701. if not assigned(objsec.Data) then
  1702. internalerror(200603044);
  1703. objsec.setDatapos(CurrDataPos);
  1704. end;
  1705. end;
  1706. end;
  1707. procedure TExeOutput.DataPos_EndExeSection;
  1708. begin
  1709. if not assigned(CurrExeSec) then
  1710. exit;
  1711. FCurrExeSec:=nil;
  1712. end;
  1713. procedure TExeOutput.DataPos_Symbols;
  1714. var
  1715. i : longint;
  1716. sym : TExeSymbol;
  1717. begin
  1718. { Removing unused symbols }
  1719. for i:=0 to ExeSymbolList.Count-1 do
  1720. begin
  1721. sym:=TExeSymbol(ExeSymbolList[i]);
  1722. if not sym.ObjSymbol.objsection.Used then
  1723. ExeSymbolList[i]:=nil;
  1724. end;
  1725. ExeSymbolList.Pack;
  1726. end;
  1727. procedure TExeOutput.BuildVTableTree(VTInheritList,VTEntryList:TFPObjectList);
  1728. var
  1729. hs : string;
  1730. code : integer;
  1731. i,k,
  1732. vtableidx : longint;
  1733. vtableexesym,
  1734. childexesym,
  1735. parentexesym : TExeSymbol;
  1736. objsym : TObjSymbol;
  1737. begin
  1738. { Build inheritance tree from VTINHERIT }
  1739. for i:=0 to VTInheritList.Count-1 do
  1740. begin
  1741. objsym:=TObjSymbol(VTInheritList[i]);
  1742. hs:=objsym.name;
  1743. { VTINHERIT_<ChildVMTName>$$<ParentVMTName> }
  1744. Delete(hs,1,Pos('_',hs));
  1745. k:=Pos('$$',hs);
  1746. if k=0 then
  1747. internalerror(200603311);
  1748. childexesym:=texesymbol(FExeSymbolList.Find(Copy(hs,1,k-1)));
  1749. parentexesym:=texesymbol(FExeSymbolList.Find(Copy(hs,k+2,length(hs)-k-1)));
  1750. if not assigned(childexesym) or
  1751. not assigned(parentexesym)then
  1752. internalerror(200603312);
  1753. if not assigned(childexesym.vtable) then
  1754. begin
  1755. childexesym.vtable:=TExeVTable.Create(childexesym);
  1756. ExeVTableList.Add(childexesym.vtable);
  1757. end;
  1758. if not assigned(parentexesym.vtable) then
  1759. begin
  1760. parentexesym.vtable:=TExeVTable.Create(parentexesym);
  1761. ExeVTableList.Add(parentexesym.vtable);
  1762. end;
  1763. childexesym.vtable.SetVTableSize(childexesym.ObjSymbol.Size);
  1764. if parentexesym<>childexesym then
  1765. parentexesym.vtable.AddChild(childexesym.vtable);
  1766. end;
  1767. { Find VTable entries from VTENTRY }
  1768. for i:=0 to VTEntryList.Count-1 do
  1769. begin
  1770. objsym:=TObjSymbol(VTEntryList[i]);
  1771. hs:=objsym.name;
  1772. { VTENTRY_<VTableName>$$<Index> }
  1773. Delete(hs,1,Pos('_',hs));
  1774. k:=Pos('$$',hs);
  1775. if k=0 then
  1776. internalerror(200603319);
  1777. vtableexesym:=texesymbol(FExeSymbolList.Find(Copy(hs,1,k-1)));
  1778. val(Copy(hs,k+2,length(hs)-k-1),vtableidx,code);
  1779. if (code<>0) then
  1780. internalerror(200603318);
  1781. if not assigned(vtableexesym) then
  1782. internalerror(2006033110);
  1783. vtableexesym.vtable.AddEntry(vtableidx);
  1784. end;
  1785. end;
  1786. procedure TExeOutput.PackUnresolvedExeSymbols(const s:string);
  1787. var
  1788. i : longint;
  1789. exesym : TExeSymbol;
  1790. begin
  1791. { Generate a list of Unresolved External symbols }
  1792. for i:=0 to UnresolvedExeSymbols.count-1 do
  1793. begin
  1794. exesym:=TExeSymbol(UnresolvedExeSymbols[i]);
  1795. if exesym.State<>symstate_undefined then
  1796. UnresolvedExeSymbols[i]:=nil;
  1797. end;
  1798. UnresolvedExeSymbols.Pack;
  1799. Comment(V_Debug,'Number of unresolved externals '+s+' '+tostr(UnresolvedExeSymbols.Count));
  1800. end;
  1801. procedure TExeOutput.ResolveSymbols(StaticLibraryList:TFPHashObjectList);
  1802. var
  1803. ObjData : TObjData;
  1804. exesym : TExeSymbol;
  1805. objsym,
  1806. commonsym : TObjSymbol;
  1807. objinput : TObjInput;
  1808. StaticLibrary : TStaticLibrary;
  1809. firstarchive,
  1810. firstcommon : boolean;
  1811. i,j : longint;
  1812. VTEntryList,
  1813. VTInheritList : TFPObjectList;
  1814. procedure LoadObjDataSymbols(ObjData:TObjData);
  1815. var
  1816. j : longint;
  1817. hs : string;
  1818. exesym : TExeSymbol;
  1819. objsym : TObjSymbol;
  1820. begin
  1821. for j:=0 to ObjData.ObjSymbolList.Count-1 do
  1822. begin
  1823. objsym:=TObjSymbol(ObjData.ObjSymbolList[j]);
  1824. { From the local symbols we are only interressed in the
  1825. VTENTRY and VTINHERIT symbols }
  1826. if objsym.bind=AB_LOCAL then
  1827. begin
  1828. if cs_link_opt_vtable in current_settings.globalswitches then
  1829. begin
  1830. hs:=objsym.name;
  1831. if (hs[1]='V') then
  1832. begin
  1833. if Copy(hs,1,5)='VTREF' then
  1834. begin
  1835. if not assigned(objsym.ObjSection.VTRefList) then
  1836. objsym.ObjSection.VTRefList:=TFPObjectList.Create(false);
  1837. objsym.ObjSection.VTRefList.Add(objsym);
  1838. end
  1839. else if Copy(hs,1,7)='VTENTRY' then
  1840. VTEntryList.Add(objsym)
  1841. else if Copy(hs,1,9)='VTINHERIT' then
  1842. VTInheritList.Add(objsym);
  1843. end;
  1844. end;
  1845. continue;
  1846. end;
  1847. { Search for existing exesymbol }
  1848. exesym:=texesymbol(FExeSymbolList.Find(objsym.name));
  1849. if not assigned(exesym) then
  1850. begin
  1851. exesym:=texesymbol.Create(FExeSymbolList,objsym.name);
  1852. exesym.ObjSymbol:=objsym;
  1853. end;
  1854. objsym.ExeSymbol:=exesym;
  1855. case objsym.bind of
  1856. AB_GLOBAL :
  1857. begin
  1858. if exesym.State<>symstate_defined then
  1859. begin
  1860. exesym.ObjSymbol:=objsym;
  1861. exesym.State:=symstate_defined;
  1862. end
  1863. else
  1864. Comment(V_Error,'Multiple defined symbol '+objsym.name);
  1865. end;
  1866. AB_EXTERNAL :
  1867. begin
  1868. ExternalObjSymbols.add(objsym);
  1869. { Register unresolved symbols only the first time they
  1870. are registered }
  1871. if exesym.ObjSymbol=objsym then
  1872. UnresolvedExeSymbols.Add(exesym);
  1873. end;
  1874. AB_COMMON :
  1875. begin
  1876. if exesym.State=symstate_undefined then
  1877. begin
  1878. exesym.ObjSymbol:=objsym;
  1879. exesym.State:=symstate_common;
  1880. end;
  1881. CommonObjSymbols.add(objsym);
  1882. end;
  1883. end;
  1884. end;
  1885. end;
  1886. begin
  1887. VTEntryList:=TFPObjectList.Create(false);
  1888. VTInheritList:=TFPObjectList.Create(false);
  1889. {
  1890. The symbol resolving is done in 3 steps:
  1891. 1. Register symbols from objects
  1892. 2. Find symbols in static libraries
  1893. 3. Define stil undefined common symbols
  1894. }
  1895. { Step 1, Register symbols from objects }
  1896. for i:=0 to ObjDataList.Count-1 do
  1897. begin
  1898. ObjData:=TObjData(ObjDataList[i]);
  1899. LoadObjDataSymbols(ObjData);
  1900. end;
  1901. PackUnresolvedExeSymbols('in objects');
  1902. { Step 2, Find unresolved symbols in the libraries }
  1903. firstarchive:=true;
  1904. for i:=0 to StaticLibraryList.Count-1 do
  1905. begin
  1906. StaticLibrary:=TStaticLibrary(StaticLibraryList[i]);
  1907. { Process list of Unresolved External symbols, we need
  1908. to use a while loop because the list can be extended when
  1909. we load members from the library. }
  1910. j:=0;
  1911. while (j<UnresolvedExeSymbols.count) do
  1912. begin
  1913. exesym:=TExeSymbol(UnresolvedExeSymbols[j]);
  1914. { Check first if the symbol is still undefined }
  1915. if exesym.State=symstate_undefined then
  1916. begin
  1917. if StaticLibrary.ArReader.OpenFile(exesym.name) then
  1918. begin
  1919. if assigned(exemap) then
  1920. begin
  1921. if firstarchive then
  1922. begin
  1923. exemap.Add('');
  1924. exemap.Add('Archive member included because of file (symbol)');
  1925. exemap.Add('');
  1926. firstarchive:=false;
  1927. end;
  1928. exemap.Add(StaticLibrary.ArReader.FileName+' - '+
  1929. {exesym.ObjSymbol.ObjSection.FullName+}
  1930. '('+exesym.Name+')');
  1931. end;
  1932. objinput:=StaticLibrary.ObjInputClass.Create;
  1933. objdata:=objinput.newObjData(StaticLibrary.ArReader.FileName);
  1934. objinput.ReadObjData(StaticLibrary.ArReader,objdata);
  1935. objinput.free;
  1936. AddObjData(objdata);
  1937. LoadObjDataSymbols(objdata);
  1938. StaticLibrary.ArReader.CloseFile;
  1939. end;
  1940. end;
  1941. inc(j);
  1942. end;
  1943. end;
  1944. PackUnresolvedExeSymbols('after static libraries');
  1945. { Step 3, Match common symbols or add to the globals }
  1946. firstcommon:=true;
  1947. for i:=0 to CommonObjSymbols.count-1 do
  1948. begin
  1949. objsym:=TObjSymbol(CommonObjSymbols[i]);
  1950. if objsym.exesymbol.State=symstate_defined then
  1951. begin
  1952. if objsym.exesymbol.ObjSymbol.size<>objsym.size then
  1953. Comment(V_Debug,'Size of common symbol '+objsym.name+' is different, expected '+tostr(objsym.size)+' got '+tostr(objsym.exesymbol.ObjSymbol.size));
  1954. end
  1955. else
  1956. begin
  1957. { allocate new objsymbol in .bss of *COMMON* and assign
  1958. it to the exesymbol }
  1959. if firstcommon then
  1960. begin
  1961. if assigned(exemap) then
  1962. exemap.AddCommonSymbolsHeader;
  1963. firstcommon:=false;
  1964. end;
  1965. internalObjData.setsection(commonObjSection);
  1966. internalObjData.allocalign(var_align(objsym.size));
  1967. commonsym:=internalObjData.symboldefine(objsym.name,AB_GLOBAL,AT_FUNCTION);
  1968. commonsym.size:=objsym.size;
  1969. internalObjData.alloc(objsym.size);
  1970. if assigned(exemap) then
  1971. exemap.AddCommonSymbol(commonsym);
  1972. { Assign to the exesymbol }
  1973. objsym.exesymbol.objsymbol:=commonsym;
  1974. objsym.exesymbol.state:=symstate_defined;
  1975. end;
  1976. end;
  1977. PackUnresolvedExeSymbols('after defining COMMON symbols');
  1978. { Find entry symbol and print in map }
  1979. exesym:=texesymbol(ExeSymbolList.Find(EntryName));
  1980. if assigned(exesym) then
  1981. begin
  1982. EntrySym:=exesym.ObjSymbol;
  1983. if assigned(exemap) then
  1984. begin
  1985. exemap.Add('');
  1986. exemap.Add('Entry symbol '+EntryName);
  1987. end;
  1988. end
  1989. else
  1990. Comment(V_Error,'Entrypoint '+EntryName+' not defined');
  1991. { Generate VTable tree }
  1992. if cs_link_opt_vtable in current_settings.globalswitches then
  1993. BuildVTableTree(VTInheritList,VTEntryList);
  1994. VTInheritList.Free;
  1995. VTEntryList.Free;
  1996. end;
  1997. procedure TExeOutput.GenerateDebugLink(const dbgname:string;dbgcrc:cardinal);
  1998. var
  1999. debuglink : array[0..1023] of byte;
  2000. len : longint;
  2001. objsec : TObjSection;
  2002. exesec : TExeSection;
  2003. begin
  2004. { From the gdb manual chapter 15. GDB Files:
  2005. * A filename, with any leading directory components removed, followed by a zero byte,
  2006. * zero to three bytes of padding, as needed to reach the next four-byte boundary within the section, and
  2007. * a four-byte CRC checksum, stored in the same endianness used for the executable file itself. The checksum is computed
  2008. on the debugging information file's full contents by the function given below, passing zero as the crc argument.
  2009. }
  2010. fillchar(debuglink,sizeof(debuglink),0);
  2011. len:=0;
  2012. move(dbgname[1],debuglink[len],length(dbgname));
  2013. inc(len,length(dbgname)+1);
  2014. len:=align(len,4);
  2015. if source_info.endian<>target_info.endian then
  2016. SwapEndian(dbgcrc);
  2017. move(dbgcrc,debuglink[len],sizeof(cardinal));
  2018. inc(len,4);
  2019. { Add section }
  2020. exesec:=FindExeSection(debuglinkname);
  2021. if not assigned(exesec) then
  2022. exesec:=CExeSection.create(ExeSectionList,debuglinkname);
  2023. exesec.SecOptions:=[oso_data,oso_keep];
  2024. exesec.SecAlign:=4;
  2025. objsec:=internalObjData.createsection(exesec.name,0,exesec.SecOptions);
  2026. internalObjData.writebytes(debuglink,len);
  2027. exesec.AddObjSection(objsec);
  2028. end;
  2029. procedure TExeOutput.GenerateLibraryImports(ImportLibraryList:TFPHashObjectList);
  2030. begin
  2031. end;
  2032. procedure TExeOutput.PrintMemoryMap;
  2033. var
  2034. exesec : TExeSection;
  2035. objsec : TObjSection;
  2036. objsym : TObjSymbol;
  2037. i,j,k : longint;
  2038. begin
  2039. if not assigned(exemap) then
  2040. exit;
  2041. exemap.AddMemoryMapHeader(ImageBase);
  2042. for i:=0 to ExeSectionList.Count-1 do
  2043. begin
  2044. exesec:=TExeSection(ExeSectionList[i]);
  2045. exemap.AddMemoryMapExeSection(exesec);
  2046. for j:=0 to exesec.ObjSectionList.count-1 do
  2047. begin
  2048. objsec:=TObjSection(exesec.ObjSectionList[j]);
  2049. exemap.AddMemoryMapObjectSection(objsec);
  2050. for k:=0 to objsec.ObjSymbolDefines.Count-1 do
  2051. begin
  2052. objsym:=TObjSymbol(objsec.ObjSymbolDefines[k]);
  2053. exemap.AddMemoryMapSymbol(objsym);
  2054. end;
  2055. end;
  2056. end;
  2057. end;
  2058. procedure TExeOutput.FixupSymbols;
  2059. procedure UpdateSymbol(objsym:TObjSymbol);
  2060. begin
  2061. objsym.bind:=objsym.ExeSymbol.ObjSymbol.bind;
  2062. objsym.offset:=objsym.ExeSymbol.ObjSymbol.offset;
  2063. objsym.size:=objsym.ExeSymbol.ObjSymbol.size;
  2064. objsym.typ:=objsym.ExeSymbol.ObjSymbol.typ;
  2065. objsym.ObjSection:=objsym.ExeSymbol.ObjSymbol.ObjSection;
  2066. end;
  2067. var
  2068. i : longint;
  2069. objsym : TObjSymbol;
  2070. exesym : TExeSymbol;
  2071. begin
  2072. { Print list of Unresolved External symbols }
  2073. for i:=0 to UnresolvedExeSymbols.count-1 do
  2074. begin
  2075. exesym:=TExeSymbol(UnresolvedExeSymbols[i]);
  2076. if exesym.State<>symstate_defined then
  2077. Comment(V_Error,'Undefined symbol: '+exesym.name);
  2078. end;
  2079. { Update ImageBase to ObjData so it can access from ObjSymbols }
  2080. for i:=0 to ObjDataList.Count-1 do
  2081. TObjData(ObjDataList[i]).imagebase:=imagebase;
  2082. {
  2083. Fixing up symbols is done in the following steps:
  2084. 1. Update common references
  2085. 2. Update external references
  2086. }
  2087. { Step 1, Update commons }
  2088. for i:=0 to CommonObjSymbols.count-1 do
  2089. begin
  2090. objsym:=TObjSymbol(CommonObjSymbols[i]);
  2091. if objsym.bind<>AB_COMMON then
  2092. internalerror(200606241);
  2093. UpdateSymbol(objsym);
  2094. end;
  2095. { Step 2, Update externals }
  2096. for i:=0 to ExternalObjSymbols.count-1 do
  2097. begin
  2098. objsym:=TObjSymbol(ExternalObjSymbols[i]);
  2099. if objsym.bind<>AB_EXTERNAL then
  2100. internalerror(200606242);
  2101. UpdateSymbol(objsym);
  2102. end;
  2103. end;
  2104. procedure TExeOutput.MergeStabs;
  2105. var
  2106. stabexesec,
  2107. stabstrexesec : TExeSection;
  2108. relocsec,
  2109. currstabsec,
  2110. currstabstrsec,
  2111. mergedstabsec,
  2112. mergedstabstrsec : TObjSection;
  2113. hstabreloc,
  2114. currstabreloc : TObjRelocation;
  2115. i,j : longint;
  2116. currstabrelocidx,
  2117. mergestabcnt,
  2118. stabcnt : longword;
  2119. skipstab : boolean;
  2120. skipfun : boolean;
  2121. hstab : TObjStabEntry;
  2122. stabrelocofs : longword;
  2123. buf : array[0..1023] of byte;
  2124. bufend,
  2125. bufsize : longint;
  2126. begin
  2127. stabexesec:=FindExeSection('.stab');
  2128. stabstrexesec:=FindExeSection('.stabstr');
  2129. if (stabexesec=nil) or
  2130. (stabstrexesec=nil) or
  2131. (stabexesec.ObjSectionlist.count=0) then
  2132. exit;
  2133. { Create new stabsection }
  2134. stabRelocofs:=pbyte(@hstab.nvalue)-pbyte(@hstab);
  2135. mergedstabsec:=internalObjData.CreateSection(sec_stab,'');
  2136. mergedstabstrsec:=internalObjData.CreateSection(sec_stabstr,'');
  2137. { write stab for hdrsym }
  2138. fillchar(hstab,sizeof(TObjStabEntry),0);
  2139. mergedstabsec.write(hstab,sizeof(TObjStabEntry));
  2140. mergestabcnt:=1;
  2141. { .stabstr starts with a #0 }
  2142. buf[0]:=0;
  2143. mergedstabstrsec.write(buf[0],1);
  2144. skipfun:=false;
  2145. { Copy stabs and corresponding Relocations }
  2146. for i:=0 to stabexesec.ObjSectionList.Count-1 do
  2147. begin
  2148. currstabsec:=TObjSection(stabexesec.ObjSectionList[i]);
  2149. currstabstrsec:=currstabsec.ObjData.findsection('.stabstr');
  2150. if assigned(currstabstrsec) then
  2151. begin
  2152. stabcnt:=currstabsec.Data.size div sizeof(TObjStabEntry);
  2153. currstabsec.Data.seek(0);
  2154. currstabrelocidx:=0;
  2155. for j:=0 to stabcnt-1 do
  2156. begin
  2157. hstabreloc:=nil;
  2158. skipstab:=false;
  2159. currstabsec.Data.read(hstab,sizeof(TObjStabEntry));
  2160. { Only include first hdrsym stab }
  2161. if hstab.ntype=0 then
  2162. skipstab:=true;
  2163. if skipfun then
  2164. begin
  2165. { Skip all stabs for function body until N_RBRAC }
  2166. skipfun:=hstab.ntype<>N_RBRAC;
  2167. skipstab:=true;
  2168. end;
  2169. if not skipstab then
  2170. begin
  2171. { Find corresponding Relocation }
  2172. currstabreloc:=nil;
  2173. while (currstabrelocidx<longword(currstabsec.ObjRelocations.Count)) do
  2174. begin
  2175. currstabreloc:=TObjRelocation(currstabsec.ObjRelocations[currstabrelocidx]);
  2176. if assigned(currstabreloc) and
  2177. (currstabreloc.dataoffset>=longword(j)*sizeof(TObjStabEntry)+stabrelocofs) then
  2178. break;
  2179. inc(currstabrelocidx);
  2180. end;
  2181. if assigned(currstabreloc) and
  2182. (currstabreloc.dataoffset=longword(j)*sizeof(TObjStabEntry)+stabrelocofs) then
  2183. begin
  2184. hstabReloc:=currstabReloc;
  2185. inc(currstabrelocidx);
  2186. end;
  2187. { Check if the stab is refering to a removed section }
  2188. if assigned(hstabreloc) then
  2189. begin
  2190. if assigned(hstabreloc.Symbol) then
  2191. relocsec:=hstabreloc.Symbol.ObjSection
  2192. else
  2193. relocsec:=hstabreloc.ObjSection;
  2194. if not assigned(relocsec) then
  2195. internalerror(200603302);
  2196. if not relocsec.Used then
  2197. begin
  2198. skipstab:=true;
  2199. if (hstab.ntype=N_Function) and (hstab.strpos<>0) then
  2200. begin
  2201. currstabstrsec.Data.seek(hstab.strpos);
  2202. bufsize:=currstabstrsec.Data.read(buf,sizeof(buf));
  2203. bufend:=indexbyte(buf,bufsize,Ord(':'));
  2204. if (bufend<>-1) and (bufend<bufsize-1) and (buf[bufend+1]=Ord('F')) then
  2205. skipfun:=true;
  2206. end;
  2207. end;
  2208. end;
  2209. end;
  2210. if not skipstab then
  2211. begin
  2212. { Copy string in stabstr }
  2213. if hstab.strpos<>0 then
  2214. begin
  2215. currstabstrsec.Data.seek(hstab.strpos);
  2216. hstab.strpos:=mergedstabstrsec.Size;
  2217. repeat
  2218. bufsize:=currstabstrsec.Data.read(buf,sizeof(buf));
  2219. bufend:=indexbyte(buf,bufsize,0);
  2220. if bufend=-1 then
  2221. bufend:=bufsize
  2222. else
  2223. begin
  2224. { include the #0 }
  2225. inc(bufend);
  2226. end;
  2227. mergedstabstrsec.write(buf,bufend);
  2228. until (buf[bufend-1]=0) or (bufsize<sizeof(buf));
  2229. end;
  2230. { Copy and Update the relocation }
  2231. if assigned(hstabreloc) then
  2232. begin
  2233. hstabreloc.Dataoffset:=mergestabcnt*sizeof(TObjStabEntry)+stabRelocofs;
  2234. { Remove from List without freeing the object }
  2235. currstabsec.ObjRelocations.List[currstabrelocidx-1]:=nil;
  2236. mergedstabsec.ObjRelocations.Add(hstabreloc);
  2237. end;
  2238. { Write updated stab }
  2239. mergedstabsec.write(hstab,sizeof(hstab));
  2240. inc(mergestabcnt);
  2241. end;
  2242. end;
  2243. end;
  2244. { Unload stabs }
  2245. if assigned(currstabstrsec) then
  2246. begin
  2247. currstabstrsec.Used:=False;
  2248. currstabstrsec.ReleaseData;
  2249. end;
  2250. currstabsec.Used:=false;
  2251. currstabsec.ReleaseData;
  2252. end;
  2253. { Generate new HdrSym }
  2254. if mergedstabsec.Size>0 then
  2255. begin
  2256. hstab.strpos:=1;
  2257. hstab.ntype:=0;
  2258. hstab.nother:=0;
  2259. hstab.ndesc:=word(mergestabcnt-1);
  2260. hstab.nvalue:=mergedstabstrsec.Size;
  2261. mergedstabsec.Data.seek(0);
  2262. mergedstabsec.Data.write(hstab,sizeof(hstab));
  2263. end;
  2264. { Replace all sections with our combined stabsec }
  2265. stabexesec.ObjSectionList.Clear;
  2266. stabstrexesec.ObjSectionList.Clear;
  2267. stabexesec.AddObjSection(mergedstabsec);
  2268. stabstrexesec.AddObjSection(mergedstabstrsec);
  2269. end;
  2270. procedure TExeOutput.RemoveEmptySections;
  2271. var
  2272. i, j : longint;
  2273. exesec : TExeSection;
  2274. doremove : boolean;
  2275. begin
  2276. for i:=0 to ExeSectionList.Count-1 do
  2277. begin
  2278. exesec:=TExeSection(ExeSectionList[i]);
  2279. doremove:=not(oso_keep in exesec.SecOptions) and
  2280. (
  2281. (exesec.ObjSectionlist.count=0) or
  2282. (
  2283. (cs_link_strip in current_settings.globalswitches) and
  2284. not(cs_link_separate_dbg_file in current_settings.globalswitches) and
  2285. (oso_debug in exesec.SecOptions)
  2286. )
  2287. );
  2288. if not doremove then
  2289. begin
  2290. { Check if section has no actual data }
  2291. doremove:=true;
  2292. for j:=0 to exesec.ObjSectionList.Count-1 do
  2293. if TObjSection(exesec.ObjSectionList[j]).Size<>0 then
  2294. begin
  2295. doremove:=false;
  2296. break;
  2297. end;
  2298. end;
  2299. if doremove and not (RelocSection and (exesec.Name='.reloc')) then
  2300. begin
  2301. Comment(V_Debug,'Deleting empty section '+exesec.name);
  2302. ExeSectionList[i]:=nil;
  2303. end;
  2304. end;
  2305. ExeSectionList.Pack;
  2306. end;
  2307. procedure TExeOutput.RemoveDebugInfo;
  2308. var
  2309. i : longint;
  2310. exesec : TExeSection;
  2311. begin
  2312. for i:=0 to ExeSectionList.Count-1 do
  2313. begin
  2314. exesec:=TExeSection(ExeSectionList[i]);
  2315. if (oso_debug in exesec.SecOptions) then
  2316. ExeSectionList[i]:=nil;
  2317. end;
  2318. ExeSectionList.Pack;
  2319. end;
  2320. procedure TExeOutput.RemoveUnreferencedSections;
  2321. var
  2322. ObjSectionWorkList : TFPObjectList;
  2323. procedure AddToObjSectionWorkList(aobjsec:TObjSection);
  2324. begin
  2325. if not aobjsec.Used then
  2326. begin
  2327. aobjsec.Used:=true;
  2328. ObjSectionWorkList.Add(aobjsec);
  2329. end;
  2330. end;
  2331. procedure DoReloc(objreloc:TObjRelocation);
  2332. var
  2333. objsym : TObjSymbol;
  2334. refobjsec : TObjSection;
  2335. begin
  2336. { Disabled Relocation to 0 }
  2337. if objreloc.typ=RELOC_ZERO then
  2338. exit;
  2339. if assigned(objreloc.symbol) then
  2340. begin
  2341. objsym:=objreloc.symbol;
  2342. if objsym.bind<>AB_LOCAL then
  2343. begin
  2344. if not(assigned(objsym.exesymbol) and
  2345. (objsym.exesymbol.State=symstate_defined)) then
  2346. internalerror(200603063);
  2347. objsym:=objsym.exesymbol.objsymbol;
  2348. end;
  2349. if not assigned(objsym.objsection) then
  2350. internalerror(200603062);
  2351. refobjsec:=objsym.objsection;
  2352. end
  2353. else
  2354. if assigned(objreloc.objsection) then
  2355. refobjsec:=objreloc.objsection
  2356. else
  2357. internalerror(200603316);
  2358. if assigned(exemap) then
  2359. begin
  2360. objsym:=objreloc.symbol;
  2361. if assigned(objsym) then
  2362. exemap.Add(' References '+objsym.name+' in '
  2363. +refobjsec.fullname)
  2364. else
  2365. exemap.Add(' References '+refobjsec.fullname);
  2366. end;
  2367. AddToObjSectionWorkList(refobjsec);
  2368. end;
  2369. procedure DoVTableRef(vtable:TExeVTable;VTableIdx:longint);
  2370. var
  2371. i : longint;
  2372. objreloc : TObjRelocation;
  2373. begin
  2374. objreloc:=vtable.VTableRef(VTableIdx);
  2375. if assigned(objreloc) then
  2376. begin
  2377. { Process the relocation now if the ObjSection is
  2378. already processed and marked as used. Otherwise we leave it
  2379. unprocessed. It'll then be resolved when the ObjSection is
  2380. changed to Used }
  2381. if vtable.ExeSymbol.ObjSymbol.ObjSection.Used then
  2382. DoReloc(objreloc);
  2383. end;
  2384. { This recursive walking is done here instead of
  2385. in TExeVTable.VTableRef because we can now process
  2386. all needed relocations }
  2387. for i:=0 to vtable.ChildList.Count-1 do
  2388. DoVTableRef(TExeVTable(vtable.ChildList[i]),VTableIdx);
  2389. end;
  2390. var
  2391. hs : string;
  2392. i,j,k : longint;
  2393. exesec : TExeSection;
  2394. objdata : TObjData;
  2395. objsec : TObjSection;
  2396. objsym : TObjSymbol;
  2397. code : integer;
  2398. vtableidx : longint;
  2399. vtableexesym : TExeSymbol;
  2400. begin
  2401. ObjSectionWorkList:=TFPObjectList.Create(false);
  2402. if assigned(exemap) then
  2403. exemap.AddHeader('Removing unreferenced sections');
  2404. { Initialize by marking all sections unused and
  2405. adding the sections with oso_keep flags to the ObjSectionWorkList }
  2406. for i:=0 to ObjDataList.Count-1 do
  2407. begin
  2408. ObjData:=TObjData(ObjDataList[i]);
  2409. for j:=0 to ObjData.ObjSectionList.Count-1 do
  2410. begin
  2411. objsec:=TObjSection(ObjData.ObjSectionList[j]);
  2412. objsec.Used:=false;
  2413. { TODO: remove debug section always keep}
  2414. if oso_debug in objsec.secoptions then
  2415. objsec.Used:=true;
  2416. if (oso_keep in objsec.secoptions) then
  2417. begin
  2418. AddToObjSectionWorkList(objsec);
  2419. if objsec.name='.fpc.n_links' then
  2420. objsec.Used:=false;
  2421. end;
  2422. end;
  2423. end;
  2424. AddToObjSectionWorkList(entrysym.exesymbol.objsymbol.objsection);
  2425. { Process all sections, add new sections to process based
  2426. on the symbol references }
  2427. while ObjSectionWorkList.Count>0 do
  2428. begin
  2429. objsec:=TObjSection(ObjSectionWorkList.Last);
  2430. if assigned(exemap) then
  2431. exemap.Add('Keeping '+objsec.FullName+' '+ToStr(objsec.ObjRelocations.Count)+' references');
  2432. ObjSectionWorkList.Delete(ObjSectionWorkList.Count-1);
  2433. { Process Relocations }
  2434. for i:=0 to objsec.ObjRelocations.count-1 do
  2435. DoReloc(TObjRelocation(objsec.ObjRelocations[i]));
  2436. { Process Virtual Entry calls }
  2437. if cs_link_opt_vtable in current_settings.globalswitches then
  2438. begin
  2439. for i:=0 to objsec.VTRefList.count-1 do
  2440. begin
  2441. objsym:=TObjSymbol(objsec.VTRefList[i]);
  2442. hs:=objsym.name;
  2443. Delete(hs,1,Pos('_',hs));
  2444. k:=Pos('$$',hs);
  2445. if k=0 then
  2446. internalerror(200603314);
  2447. vtableexesym:=texesymbol(FExeSymbolList.Find(Copy(hs,1,k-1)));
  2448. val(Copy(hs,k+2,length(hs)-k-1),vtableidx,code);
  2449. if (code<>0) then
  2450. internalerror(200603317);
  2451. if not assigned(vtableexesym) then
  2452. internalerror(200603315);
  2453. if not assigned(vtableexesym.vtable) then
  2454. internalerror(200603316);
  2455. DoVTableRef(vtableexesym.vtable,vtableidx);
  2456. end;
  2457. end;
  2458. end;
  2459. ObjSectionWorkList.Free;
  2460. ObjSectionWorkList:=nil;
  2461. { Remove unused objsections from ExeSectionList }
  2462. for i:=0 to ExeSectionList.Count-1 do
  2463. begin
  2464. exesec:=TExeSection(ExeSectionList[i]);
  2465. for j:=0 to exesec.ObjSectionlist.count-1 do
  2466. begin
  2467. objsec:=TObjSection(exesec.ObjSectionlist[j]);
  2468. if not objsec.used then
  2469. begin
  2470. if assigned(exemap) then
  2471. exemap.Add('Removing '+objsec.FullName);
  2472. exesec.ObjSectionlist[j]:=nil;
  2473. objsec.ReleaseData;
  2474. end;
  2475. end;
  2476. exesec.ObjSectionlist.Pack;
  2477. end;
  2478. end;
  2479. procedure TExeOutput.FixupRelocations;
  2480. var
  2481. i,j : longint;
  2482. exesec : TExeSection;
  2483. objsec : TObjSection;
  2484. begin
  2485. for i:=0 to ExeSectionList.Count-1 do
  2486. begin
  2487. exesec:=TExeSection(ExeSectionList[i]);
  2488. if not assigned(exesec) then
  2489. continue;
  2490. for j:=0 to exesec.ObjSectionlist.count-1 do
  2491. begin
  2492. objsec:=TObjSection(exesec.ObjSectionlist[j]);
  2493. if not objsec.Used then
  2494. internalerror(200603301);
  2495. objsec.FixupRelocs;
  2496. end;
  2497. end;
  2498. end;
  2499. procedure TExeOutput.SetCurrMemPos(const AValue: qword);
  2500. begin
  2501. if AValue>MaxMemPos then
  2502. Message1(link_f_executable_too_big, target_os_string);
  2503. FCurrMemPos:=AValue;
  2504. end;
  2505. {****************************************************************************
  2506. TObjInput
  2507. ****************************************************************************}
  2508. constructor TObjInput.create;
  2509. begin
  2510. end;
  2511. destructor TObjInput.destroy;
  2512. begin
  2513. inherited destroy;
  2514. end;
  2515. function TObjInput.newObjData(const n:string):TObjData;
  2516. begin
  2517. result:=CObjData.create(n);
  2518. end;
  2519. procedure TObjInput.inputerror(const s : string);
  2520. begin
  2521. Comment(V_Error,s+' while reading '+InputFileName);
  2522. end;
  2523. {$ifdef MEMDEBUG}
  2524. initialization
  2525. memobjsymbols:=TMemDebug.create('ObjSymbols');
  2526. memobjsymbols.stop;
  2527. memobjsections:=TMemDebug.create('ObjSections');
  2528. memobjsections.stop;
  2529. finalization
  2530. memobjsymbols.free;
  2531. memobjsections.free;
  2532. {$endif MEMDEBUG}
  2533. end.