ogbase.pas 113 KB

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