ogbase.pas 113 KB

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