ogbase.pas 101 KB

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