ogbase.pas 128 KB

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