ogbase.pas 100 KB

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