ogbase.pas 122 KB

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