ogbase.pas 110 KB

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