ogbase.pas 117 KB

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