ogbase.pas 100 KB

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