ogbase.pas 117 KB

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