ogbase.pas 138 KB

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