ogbase.pas 100 KB

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