ogbase.pas 98 KB

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