ogbase.pas 113 KB

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