ogbase.pas 114 KB

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