ogbase.pas 135 KB

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