ogbase.pas 114 KB

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