ogbase.pas 117 KB

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