ogbase.pas 101 KB

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