ogbase.pas 121 KB

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