ogbase.pas 134 KB

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