ogbase.pas 97 KB

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