ogbase.pas 134 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045
  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. {fpc} [oso_Data,oso_load,oso_write],
  1265. {toc} [oso_Data,oso_load],
  1266. {init} [oso_Data,oso_load,oso_executable],
  1267. {fini} [oso_Data,oso_load,oso_executable],
  1268. {objc_class} [oso_data,oso_load],
  1269. {objc_meta_class} [oso_data,oso_load],
  1270. {objc_cat_cls_meth} [oso_data,oso_load],
  1271. {objc_cat_inst_meth} [oso_data,oso_load],
  1272. {objc_protocol} [oso_data,oso_load],
  1273. {objc_string_object} [oso_data,oso_load],
  1274. {objc_cls_meth} [oso_data,oso_load],
  1275. {objc_inst_meth} [oso_data,oso_load],
  1276. {objc_cls_refs} [oso_data,oso_load],
  1277. {objc_message_refs} [oso_data,oso_load],
  1278. {objc_symbols} [oso_data,oso_load],
  1279. {objc_category} [oso_data,oso_load],
  1280. {objc_class_vars} [oso_data,oso_load],
  1281. {objc_instance_vars} [oso_data,oso_load],
  1282. {objc_module_info} [oso_data,oso_load],
  1283. {objc_class_names} [oso_data,oso_load],
  1284. {objc_meth_var_types} [oso_data,oso_load],
  1285. {objc_meth_var_names} [oso_data,oso_load],
  1286. {objc_selector_strs} [oso_data,oso_load],
  1287. {objc_protocol_ext} [oso_data,oso_load],
  1288. {objc_class_ext} [oso_data,oso_load],
  1289. {objc_property} [oso_data,oso_load],
  1290. {objc_image_info} [oso_data,oso_load],
  1291. {objc_cstring_object} [oso_data,oso_load],
  1292. {objc_sel_fixup} [oso_data,oso_load],
  1293. {sec_objc_data} [oso_data,oso_load],
  1294. {sec_objc_const} [oso_data,oso_load],
  1295. {sec_objc_sup_refs} [oso_data,oso_load],
  1296. {sec_data_coalesced} [oso_data,oso_load],
  1297. {sec_objc_classlist} [oso_data,oso_load],
  1298. {sec_objc_nlclasslist} [oso_data,oso_load],
  1299. {sec_objc_catlist} [oso_data,oso_load],
  1300. {sec_objc_nlcatlist} [oso_data,oso_load],
  1301. {sec_objc_protolist'} [oso_data,oso_load],
  1302. {stack} [oso_load,oso_write],
  1303. {heap} [oso_load,oso_write],
  1304. {gcc_except_table} [oso_data,oso_load],
  1305. {arm_attribute} [oso_data]
  1306. );
  1307. begin
  1308. if target_asm.id in asms_int_coff then
  1309. begin
  1310. if (aType in [sec_rodata,sec_rodata_norel]) then
  1311. begin
  1312. if (target_info.system in systems_all_windows) then
  1313. aType:=sec_rodata_norel
  1314. else
  1315. aType:=sec_data;
  1316. end;
  1317. end;
  1318. result:=secoptions[atype];
  1319. {$ifdef OMFOBJSUPPORT}
  1320. { in the huge memory model, BSS data is actually written in the regular
  1321. FAR_DATA segment of the module }
  1322. if omf_segclass(atype)='FAR_DATA' then
  1323. Result:=Result+[oso_data,oso_sparse_data];
  1324. {$endif OMFOBJSUPPORT}
  1325. end;
  1326. function TObjData.sectiontype2align(atype:TAsmSectiontype):longint;
  1327. begin
  1328. case atype of
  1329. sec_stabstr,sec_debug_info,sec_debug_line,sec_debug_abbrev,sec_debug_aranges,sec_debug_ranges,
  1330. sec_arm_attribute:
  1331. result:=1;
  1332. sec_code,
  1333. sec_bss,
  1334. sec_data:
  1335. result:=16;
  1336. { For idata (at least idata2) it must be 4 bytes, because
  1337. an entry is always (also in win64) 20 bytes and aligning
  1338. on 8 bytes will insert 4 bytes between the entries resulting
  1339. in a corrupt idata section.
  1340. Same story with .pdata, it has 4-byte elements which should
  1341. be packed without gaps. }
  1342. sec_idata2,sec_idata4,sec_idata5,sec_idata6,sec_idata7,sec_pdata:
  1343. result:=4;
  1344. else
  1345. result:=sizeof(pint);
  1346. end;
  1347. end;
  1348. class procedure TObjData.sectiontype2progbitsandflags(atype:TAsmSectiontype;out progbits:TSectionProgbits;out flags:TSectionFlags);
  1349. var
  1350. options : TObjSectionOptions;
  1351. begin
  1352. { this is essentially the inverse of the createsection overload that takes
  1353. both progbits and flags as parameters }
  1354. options:=sectiontype2options(atype);
  1355. flags:=[];
  1356. progbits:=SPB_None;
  1357. if oso_load in options then
  1358. include(flags,SF_A);
  1359. if oso_write in options then
  1360. include(flags,SF_W);
  1361. if oso_executable in options then
  1362. include(flags,SF_X);
  1363. if not (oso_data in options) then
  1364. progbits:=SPB_NOBITS
  1365. else if oso_note in options then
  1366. progbits:=SPB_NOTE
  1367. else if oso_arm_attributes in options then
  1368. progbits:=SPB_ARM_ATTRIBUTES;
  1369. end;
  1370. function TObjData.createsection(atype:TAsmSectionType;const aname:string;aorder:TAsmSectionOrder):TObjSection;
  1371. begin
  1372. result:=createsection(sectionname(atype,aname,aorder),sectiontype2align(atype),sectiontype2options(atype));
  1373. end;
  1374. function TObjData.createsection(atype: TAsmSectionType; secflags: TSectionFlags; aprogbits: TSectionProgbits; const aname: string; aorder: TAsmSectionOrder): TObjSection;
  1375. var
  1376. flags : TObjSectionOptions;
  1377. begin
  1378. flags:=[oso_data];
  1379. if SF_A in secflags then
  1380. Include(flags,oso_load);
  1381. if SF_W in secflags then
  1382. Include(flags,oso_write);
  1383. if SF_X in secflags then
  1384. Include(flags,oso_executable);
  1385. if aprogbits=SPB_NOBITS then
  1386. Exclude(flags,oso_data);
  1387. if aprogbits=SPB_NOTE then
  1388. Include(flags,oso_note);
  1389. if aprogbits=SPB_ARM_ATTRIBUTES then
  1390. Include(flags,oso_arm_attributes);
  1391. result:=createsection(sectionname(atype,aname,aorder),sectiontype2align(atype),flags);
  1392. end;
  1393. function TObjData.createsection(const aname:string;aalign:longint;aoptions:TObjSectionOptions;DiscardDuplicate:boolean):TObjSection;
  1394. begin
  1395. if DiscardDuplicate then
  1396. result:=TObjSection(FObjSectionList.Find(aname))
  1397. else
  1398. result:=nil;
  1399. if not assigned(result) then
  1400. begin
  1401. result:=CObjSection.create(FObjSectionList,aname,aalign,aoptions);
  1402. result.ObjData:=self;
  1403. end;
  1404. FCurrObjSec:=result;
  1405. end;
  1406. function TObjData.CreateSectionGroup(const aname:string):TObjSectionGroup;
  1407. begin
  1408. if FGroupsList=nil then
  1409. FGroupsList:=TFPHashObjectList.Create(true);
  1410. result:=CObjSectionGroup.Create(FGroupsList,aname);
  1411. end;
  1412. procedure TObjData.CreateDebugSections;
  1413. begin
  1414. end;
  1415. function TObjData.FindSection(const aname:string):TObjSection;
  1416. begin
  1417. result:=TObjSection(FObjSectionList.Find(aname));
  1418. end;
  1419. procedure TObjData.setsection(asec:TObjSection);
  1420. begin
  1421. if asec.ObjData<>self then
  1422. internalerror(200403041);
  1423. FCurrObjSec:=asec;
  1424. end;
  1425. function TObjData.createsymbol(const aname:string):TObjSymbol;
  1426. begin
  1427. result:=TObjSymbol(FObjSymbolList.Find(aname));
  1428. if not assigned(result) then
  1429. result:=CObjSymbol.Create(FObjSymbolList,aname);
  1430. {$ifdef ARM}
  1431. result.ThumbFunc:=ThumbFunc;
  1432. ThumbFunc:=false;
  1433. {$endif ARM}
  1434. end;
  1435. function TObjData.symboldefine(asmsym:TAsmSymbol):TObjSymbol;
  1436. begin
  1437. if assigned(asmsym) then
  1438. begin
  1439. if asmsym.typ = AT_NONE then
  1440. InternalError(2018062800);
  1441. if not assigned(asmsym.cachedObjSymbol) then
  1442. begin
  1443. result:=symboldefine(asmsym.name,asmsym.bind,asmsym.typ);
  1444. asmsym.cachedObjSymbol:=result;
  1445. FCachedAsmSymbolList.add(asmsym);
  1446. end
  1447. else
  1448. begin
  1449. result:=TObjSymbol(asmsym.cachedObjSymbol);
  1450. result.SetAddress(CurrPass,CurrObjSec,asmsym.bind,asmsym.typ);
  1451. end;
  1452. end
  1453. else
  1454. result:=nil;
  1455. end;
  1456. function TObjData.symboldefine(const aname:string;abind:TAsmsymbind;atyp:Tasmsymtype):TObjSymbol;
  1457. begin
  1458. if not assigned(CurrObjSec) then
  1459. internalerror(2006030504);
  1460. result:=CreateSymbol(aname);
  1461. result.SetAddress(CurrPass,CurrObjSec,abind,atyp);
  1462. end;
  1463. function TObjData.symbolref(asmsym:TAsmSymbol):TObjSymbol;
  1464. var
  1465. s:string;
  1466. begin
  1467. if assigned(asmsym) then
  1468. begin
  1469. if not assigned(asmsym.cachedObjSymbol) then
  1470. begin
  1471. s:=asmsym.name;
  1472. result:=TObjSymbol(FObjSymbolList.Find(s));
  1473. if result=nil then
  1474. begin
  1475. result:=CObjSymbol.Create(FObjSymbolList,s);
  1476. if asmsym.bind=AB_WEAK_EXTERNAL then
  1477. result.bind:=AB_WEAK_EXTERNAL;
  1478. end;
  1479. asmsym.cachedObjSymbol:=result;
  1480. FCachedAsmSymbolList.add(asmsym);
  1481. end
  1482. else
  1483. result:=TObjSymbol(asmsym.cachedObjSymbol);
  1484. { The weak bit could have been removed from asmsym. }
  1485. if (asmsym.bind=AB_EXTERNAL) and (result.bind=AB_WEAK_EXTERNAL) then
  1486. result.bind:=AB_EXTERNAL;
  1487. { the TLS type needs to be inherited }
  1488. if asmsym.typ=AT_TLS then
  1489. result.typ:=AT_TLS;
  1490. end
  1491. else
  1492. result:=nil;
  1493. end;
  1494. function TObjData.symbolref(const aname:string):TObjSymbol;
  1495. begin
  1496. if not assigned(CurrObjSec) then
  1497. internalerror(200603052);
  1498. result:=CreateSymbol(aname);
  1499. end;
  1500. procedure TObjData.symbolpairdefine(akind: TSymbolPairKind; const asym, avalue: string);
  1501. begin
  1502. end;
  1503. procedure TObjData.ResetCachedAsmSymbols;
  1504. var
  1505. i : longint;
  1506. begin
  1507. for i:=0 to FCachedAsmSymbolList.Count-1 do
  1508. tasmsymbol(FCachedAsmSymbolList[i]).cachedObjSymbol:=nil;
  1509. FCachedAsmSymbolList.Clear;
  1510. end;
  1511. procedure TObjData.writebytes(const Data;len:TObjSectionOfs);
  1512. begin
  1513. if not assigned(CurrObjSec) then
  1514. internalerror(200402251);
  1515. CurrObjSec.write(Data,len);
  1516. end;
  1517. procedure TObjData.writeInt16LE(v: int16);
  1518. begin
  1519. {$ifdef FPC_BIG_ENDIAN}
  1520. v:=SwapEndian(v);
  1521. {$endif FPC_BIG_ENDIAN}
  1522. writebytes(v,2);
  1523. end;
  1524. procedure TObjData.writeInt16BE(v: int16);
  1525. begin
  1526. {$ifdef FPC_LITTLE_ENDIAN}
  1527. v:=SwapEndian(v);
  1528. {$endif FPC_LITTLE_ENDIAN}
  1529. writebytes(v,2);
  1530. end;
  1531. procedure TObjData.writeInt32LE(v: int32);
  1532. begin
  1533. {$ifdef FPC_BIG_ENDIAN}
  1534. v:=SwapEndian(v);
  1535. {$endif FPC_BIG_ENDIAN}
  1536. writebytes(v,4);
  1537. end;
  1538. procedure TObjData.writeInt32BE(v: int32);
  1539. begin
  1540. {$ifdef FPC_LITTLE_ENDIAN}
  1541. v:=SwapEndian(v);
  1542. {$endif FPC_LITTLE_ENDIAN}
  1543. writebytes(v,4);
  1544. end;
  1545. procedure TObjData.writeInt64LE(v: int64);
  1546. begin
  1547. {$ifdef FPC_BIG_ENDIAN}
  1548. v:=SwapEndian(v);
  1549. {$endif FPC_BIG_ENDIAN}
  1550. writebytes(v,8);
  1551. end;
  1552. procedure TObjData.writeInt64BE(v: int64);
  1553. begin
  1554. {$ifdef FPC_LITTLE_ENDIAN}
  1555. v:=SwapEndian(v);
  1556. {$endif FPC_LITTLE_ENDIAN}
  1557. writebytes(v,8);
  1558. end;
  1559. procedure TObjData.writeUInt16LE(v: uint16);
  1560. begin
  1561. {$ifdef FPC_BIG_ENDIAN}
  1562. v:=SwapEndian(v);
  1563. {$endif FPC_BIG_ENDIAN}
  1564. writebytes(v,2);
  1565. end;
  1566. procedure TObjData.writeUInt16BE(v: uint16);
  1567. begin
  1568. {$ifdef FPC_LITTLE_ENDIAN}
  1569. v:=SwapEndian(v);
  1570. {$endif FPC_LITTLE_ENDIAN}
  1571. writebytes(v,2);
  1572. end;
  1573. procedure TObjData.writeUInt32LE(v: uint32);
  1574. begin
  1575. {$ifdef FPC_BIG_ENDIAN}
  1576. v:=SwapEndian(v);
  1577. {$endif FPC_BIG_ENDIAN}
  1578. writebytes(v,4);
  1579. end;
  1580. procedure TObjData.writeUInt32BE(v: uint32);
  1581. begin
  1582. {$ifdef FPC_LITTLE_ENDIAN}
  1583. v:=SwapEndian(v);
  1584. {$endif FPC_LITTLE_ENDIAN}
  1585. writebytes(v,4);
  1586. end;
  1587. procedure TObjData.writeUInt64LE(v: uint64);
  1588. begin
  1589. {$ifdef FPC_BIG_ENDIAN}
  1590. v:=SwapEndian(v);
  1591. {$endif FPC_BIG_ENDIAN}
  1592. writebytes(v,8);
  1593. end;
  1594. procedure TObjData.writeUInt64BE(v: uint64);
  1595. begin
  1596. {$ifdef FPC_LITTLE_ENDIAN}
  1597. v:=SwapEndian(v);
  1598. {$endif FPC_LITTLE_ENDIAN}
  1599. writebytes(v,8);
  1600. end;
  1601. procedure TObjData.alloc(len:TObjSectionOfs);
  1602. begin
  1603. if not assigned(CurrObjSec) then
  1604. internalerror(200402252);
  1605. CurrObjSec.alloc(len);
  1606. end;
  1607. procedure TObjData.allocalign(len:longint);
  1608. begin
  1609. if not assigned(CurrObjSec) then
  1610. internalerror(200402253);
  1611. CurrObjSec.alloc(align_objsecofs(CurrObjSec.size,len)-CurrObjSec.size);
  1612. end;
  1613. procedure TObjData.section_afteralloc(p:TObject;arg:pointer);
  1614. begin
  1615. with TObjSection(p) do
  1616. alloc(align_objsecofs(size,secalign)-size);
  1617. end;
  1618. procedure TObjData.section_afterwrite(p:TObject;arg:pointer);
  1619. begin
  1620. with TObjSection(p) do
  1621. begin
  1622. if assigned(Data) then
  1623. writezeros(align_objsecofs(size,secalign)-size);
  1624. end;
  1625. end;
  1626. procedure TObjData.section_reset(p:TObject;arg:pointer);
  1627. begin
  1628. with TObjSection(p) do
  1629. begin
  1630. Size:=0;
  1631. Datapos:=0;
  1632. mempos:=0;
  1633. if assigned(Data) then
  1634. Data.reset;
  1635. end;
  1636. end;
  1637. procedure TObjData.beforealloc;
  1638. begin
  1639. FCPUType:=current_settings.cputype;
  1640. { create stabs sections if debugging }
  1641. if assigned(StabsSec) then
  1642. begin
  1643. StabsSec.Alloc(sizeof(TObjStabEntry));
  1644. StabStrSec.Alloc(1);
  1645. end;
  1646. end;
  1647. procedure TObjData.beforewrite;
  1648. begin
  1649. FCPUType:=current_settings.cputype;
  1650. { create stabs sections if debugging }
  1651. if assigned(StabsSec) then
  1652. begin
  1653. { Create dummy HdrSym stab, it will be overwritten in AfterWrite }
  1654. StabsSec.WriteZeros(sizeof(TObjStabEntry));
  1655. { start of stabstr }
  1656. StabStrSec.writeZeros(1);
  1657. end;
  1658. end;
  1659. procedure TObjData.afteralloc;
  1660. begin
  1661. FObjSectionList.ForEachCall(@section_afteralloc,nil);
  1662. end;
  1663. procedure TObjData.afterwrite;
  1664. var
  1665. hstab : TObjStabEntry;
  1666. begin
  1667. FObjSectionList.ForEachCall(@section_afterwrite,nil);
  1668. { For the stab section we need an HdrSym which can now be
  1669. calculated more easily }
  1670. if assigned(StabsSec) then
  1671. begin
  1672. { end of stabstr }
  1673. StabStrSec.writeZeros(1);
  1674. { header stab }
  1675. hstab.strpos:=1;
  1676. hstab.ntype:=0;
  1677. hstab.nother:=0;
  1678. {$push}{$R-}
  1679. { for jwawindows.pas, this causes an range check error, it contains too much stab symbols }
  1680. hstab.ndesc:=(StabsSec.Size div sizeof(TObjStabEntry))-1;
  1681. {$pop}
  1682. hstab.nvalue:=StabStrSec.Size;
  1683. MaybeSwapStab(hstab);
  1684. StabsSec.Data.seek(0);
  1685. StabsSec.Data.write(hstab,sizeof(hstab));
  1686. end;
  1687. end;
  1688. procedure TObjData.resetsections;
  1689. begin
  1690. FObjSectionList.ForEachCall(@section_reset,nil);
  1691. end;
  1692. procedure TObjData.layoutsections(var datapos: TObjSectionOfs);
  1693. var
  1694. i: longint;
  1695. begin
  1696. for i:=0 to FObjSectionList.Count-1 do
  1697. TObjSection(FObjSectionList[i]).setDatapos(DataPos);
  1698. end;
  1699. {****************************************************************************
  1700. TObjOutput
  1701. ****************************************************************************}
  1702. constructor TObjOutput.create(AWriter:TObjectWriter);
  1703. begin
  1704. FWriter:=AWriter;
  1705. CObjData:=TObjData;
  1706. end;
  1707. destructor TObjOutput.destroy;
  1708. begin
  1709. inherited destroy;
  1710. end;
  1711. function TObjOutput.newObjData(const n:string):TObjData;
  1712. begin
  1713. result:=CObjData.create(n);
  1714. if (cs_use_lineinfo in current_settings.globalswitches) or
  1715. (cs_debuginfo in current_settings.moduleswitches) then
  1716. result.CreateDebugSections;
  1717. end;
  1718. function TObjOutput.startObjectfile(const fn:string):boolean;
  1719. begin
  1720. result:=false;
  1721. { start the writer already, so the .a generation can initialize
  1722. the position of the current objectfile }
  1723. if not FWriter.createfile(fn) then
  1724. Comment(V_Fatal,'Can''t create object '+fn);
  1725. result:=true;
  1726. end;
  1727. function TObjOutput.writeobjectfile(Data:TObjData):boolean;
  1728. begin
  1729. if errorcount=0 then
  1730. result:=writeData(Data)
  1731. else
  1732. result:=true;
  1733. { close the writer }
  1734. FWriter.closefile;
  1735. end;
  1736. procedure TObjOutput.exportsymbol(p:TObjSymbol);
  1737. begin
  1738. { export globals and common symbols, this is needed
  1739. for .a files }
  1740. if p.bind in [AB_GLOBAL,AB_PRIVATE_EXTERN,AB_COMMON] then
  1741. FWriter.writesym(ApplyAsmSymbolRestrictions(p.name));
  1742. end;
  1743. procedure TObjOutput.WriteSectionContent(Data:TObjData);
  1744. var
  1745. i:longint;
  1746. sec:TObjSection;
  1747. begin
  1748. for i:=0 to Data.ObjSectionList.Count-1 do
  1749. begin
  1750. sec:=TObjSection(Data.ObjSectionList[i]);
  1751. if (oso_data in sec.SecOptions) then
  1752. begin
  1753. if sec.Data=nil then
  1754. internalerror(2004030707);
  1755. FWriter.writezeros(sec.dataalignbytes);
  1756. if sec.Datapos<>FWriter.ObjSize then
  1757. internalerror(200604031);
  1758. FWriter.writearray(sec.data);
  1759. end;
  1760. end;
  1761. end;
  1762. {****************************************************************************
  1763. TExeVTable
  1764. ****************************************************************************}
  1765. constructor TExeVTable.Create(AExeSymbol:TExeSymbol);
  1766. begin
  1767. ExeSymbol:=AExeSymbol;
  1768. if ExeSymbol.State=symstate_undefined then
  1769. internalerror(200604012);
  1770. ChildList:=TFPObjectList.Create(false);
  1771. end;
  1772. destructor TExeVTable.Destroy;
  1773. begin
  1774. ChildList.Free;
  1775. if assigned(EntryArray) then
  1776. Freemem(EntryArray);
  1777. end;
  1778. procedure TExeVTable.CheckIdx(VTableIdx:longint);
  1779. var
  1780. OldEntryCnt : longint;
  1781. begin
  1782. if VTableIdx>=EntryCnt then
  1783. begin
  1784. OldEntryCnt:=EntryCnt;
  1785. EntryCnt:=VTableIdx+1;
  1786. ReAllocMem(EntryArray,EntryCnt*sizeof(TVTableEntry));
  1787. FillChar(EntryArray[OldEntryCnt],(EntryCnt-OldEntryCnt)*sizeof(TVTableEntry),0);
  1788. end;
  1789. end;
  1790. procedure TExeVTable.AddChild(vt:TExeVTable);
  1791. begin
  1792. ChildList.Add(vt);
  1793. end;
  1794. procedure TExeVTable.AddEntry(VTableIdx:Longint);
  1795. var
  1796. i : longint;
  1797. objreloc : TObjRelocation;
  1798. vtblentryoffset : aword;
  1799. begin
  1800. CheckIdx(VTableIdx);
  1801. vtblentryoffset:=ExeSymbol.ObjSymbol.Offset+longword(VTableIdx)*sizeof(pint);
  1802. { Find and disable relocation }
  1803. for i:=0 to ExeSymbol.ObjSymbol.ObjSection.ObjRelocations.Count-1 do
  1804. begin
  1805. objreloc:=TObjRelocation(ExeSymbol.ObjSymbol.ObjSection.ObjRelocations[i]);
  1806. if objreloc.dataoffset=vtblentryoffset then
  1807. begin
  1808. EntryArray[VTableIdx].ObjRelocation:=objreloc;
  1809. EntryArray[VTableIdx].OrgRelocType:=objreloc.ftype;
  1810. EntryArray[VTableIdx].OrgRelocFlags:=objreloc.flags;
  1811. objreloc.typ:=RELOC_ZERO;
  1812. objreloc.flags:=objreloc.flags or rf_nosymbol;
  1813. break;
  1814. end;
  1815. end;
  1816. if not assigned(EntryArray[VTableIdx].ObjRelocation) then
  1817. internalerror(200604011);
  1818. end;
  1819. procedure TExeVTable.SetVTableSize(ASize:longint);
  1820. begin
  1821. if EntryCnt<>0 then
  1822. internalerror(200603313);
  1823. EntryCnt:=ASize div sizeof(pint);
  1824. EntryArray:=AllocMem(EntryCnt*sizeof(TVTableEntry));
  1825. end;
  1826. function TExeVTable.VTableRef(VTableIdx:Longint):TObjRelocation;
  1827. begin
  1828. result:=nil;
  1829. CheckIdx(VTableIdx);
  1830. if EntryArray[VTableIdx].Used then
  1831. exit;
  1832. { Restore relocation if available }
  1833. if assigned(EntryArray[VTableIdx].ObjRelocation) then
  1834. begin
  1835. EntryArray[VTableIdx].ObjRelocation.ftype:=EntryArray[VTableIdx].OrgRelocType;
  1836. EntryArray[VTableIdx].ObjRelocation.flags:=EntryArray[VTableIdx].OrgRelocFlags;
  1837. result:=EntryArray[VTableIdx].ObjRelocation;
  1838. end;
  1839. EntryArray[VTableIdx].Used:=true;
  1840. end;
  1841. {****************************************************************************
  1842. TExeSection
  1843. ****************************************************************************}
  1844. constructor TExeSection.create(AList:TFPHashObjectList;const AName:string);
  1845. begin
  1846. inherited create(AList,AName);
  1847. Size:=0;
  1848. MemPos:=0;
  1849. DataPos:=0;
  1850. FSecSymIdx:=0;
  1851. FObjSectionList:=TFPObjectList.Create(false);
  1852. end;
  1853. destructor TExeSection.destroy;
  1854. begin
  1855. ObjSectionList.Free;
  1856. inherited destroy;
  1857. end;
  1858. procedure TExeSection.AddObjSection(objsec:TObjSection;ignoreprops:boolean);
  1859. begin
  1860. ObjSectionList.Add(objsec);
  1861. { relate ObjSection to ExeSection, and mark it Used by default }
  1862. objsec.ExeSection:=self;
  1863. objsec.Used:=true;
  1864. if ignoreprops then
  1865. exit;
  1866. if (SecOptions<>[]) then
  1867. begin
  1868. { Only if the section contains (un)initialized data the
  1869. data flag must match. }
  1870. if ((oso_Data in SecOptions)<>(oso_Data in objsec.SecOptions)) then
  1871. Comment(V_Error,'Incompatible section options');
  1872. end
  1873. else
  1874. begin
  1875. { inherit section options }
  1876. SecOptions:=SecOptions+objsec.SecOptions;
  1877. end;
  1878. SecAlign:=max(objsec.SecAlign,SecAlign);
  1879. end;
  1880. function TExeSection.MemPosStr(AImageBase: qword): string;
  1881. begin
  1882. result:='0x'+HexStr(mempos+AImageBase,sizeof(pint)*2);
  1883. end;
  1884. {****************************************************************************
  1885. TStaticLibrary
  1886. ****************************************************************************}
  1887. constructor TStaticLibrary.create(const AName:TCmdStr;AReader:TObjectReader;AObjInputClass:TObjInputClass);
  1888. begin
  1889. FName:=AName;
  1890. FPayload:=AReader;
  1891. FObjInputClass:=AObjInputClass;
  1892. FKind:=lkArchive;
  1893. end;
  1894. constructor TStaticLibrary.create_object(AObjData:TObjData);
  1895. begin
  1896. FPayload:=AObjData;
  1897. FKind:=lkObject;
  1898. end;
  1899. constructor TStaticLibrary.create_group;
  1900. begin
  1901. FPayload:=TFPObjectList.Create(true);
  1902. FKind:=lkGroup;
  1903. end;
  1904. destructor TStaticLibrary.destroy;
  1905. begin
  1906. FPayload.Free;
  1907. inherited destroy;
  1908. end;
  1909. function TStaticLibrary.GetArReader: TObjectReader;
  1910. begin
  1911. if (FKind<>lkArchive) then
  1912. InternalError(2012071501);
  1913. result:=TObjectReader(FPayload);
  1914. end;
  1915. function TStaticLibrary.GetGroupMembers: TFPObjectList;
  1916. begin
  1917. if (FKind<>lkGroup) then
  1918. InternalError(2012071502);
  1919. result:=TFPObjectList(FPayload);
  1920. end;
  1921. function TStaticLibrary.GetObjData: TObjData;
  1922. begin
  1923. if (FKind<>lkObject) then
  1924. InternalError(2012071503);
  1925. result:=TObjData(FPayload);
  1926. end;
  1927. {****************************************************************************
  1928. TImportLibrary
  1929. ****************************************************************************}
  1930. constructor TImportLibrary.create(AList:TFPHashObjectList;const AName:string);
  1931. begin
  1932. inherited create(AList,AName);
  1933. FImportSymbolList:=TFPHashObjectList.Create(true);
  1934. end;
  1935. destructor TImportLibrary.destroy;
  1936. begin
  1937. ImportSymbolList.Free;
  1938. inherited destroy;
  1939. end;
  1940. {****************************************************************************
  1941. TImportSymbol
  1942. ****************************************************************************}
  1943. constructor TImportSymbol.create(AList:TFPHashObjectList;
  1944. const AName,AMangledName:string;AOrdNr:longint;AIsVar:boolean);
  1945. begin
  1946. inherited Create(AList, AName);
  1947. FOrdNr:=AOrdNr;
  1948. FIsVar:=AIsVar;
  1949. FMangledName:=AMangledName;
  1950. { Replace ? and @ in import name, since GNU AS does not allow these characters in symbol names. }
  1951. { This allows to import VC++ mangled names from DLLs. }
  1952. if target_info.system in systems_all_windows then
  1953. begin
  1954. Replace(FMangledName,'?','__q$$');
  1955. {$ifdef arm}
  1956. { @ symbol is not allowed in ARM assembler only }
  1957. Replace(FMangledName,'@','__a$$');
  1958. {$endif arm}
  1959. end;
  1960. end;
  1961. {****************************************************************************
  1962. TExeOutput
  1963. ****************************************************************************}
  1964. constructor TExeOutput.create;
  1965. begin
  1966. { init writer }
  1967. FWriter:=TObjectwriter.create;
  1968. FExeWriteMode:=ewm_exefull;
  1969. { object files }
  1970. FObjDataList:=TFPObjectList.Create(true);
  1971. { symbols }
  1972. FExeSymbolList:=TFPHashObjectList.Create(true);
  1973. FUnresolvedExeSymbols:=TFPObjectList.Create(false);
  1974. FExternalObjSymbols:=TFPObjectList.Create(false);
  1975. FCommonObjSymbols:=TFPObjectList.Create(false);
  1976. FProvidedObjSymbols:=TFPObjectList.Create(false);
  1977. FIndirectObjSymbols:=TFPObjectList.Create(false);
  1978. FExeVTableList:=TFPObjectList.Create(false);
  1979. ComdatGroups:=TFPHashList.Create;
  1980. { sections }
  1981. FExeSectionList:=TFPHashObjectList.Create(true);
  1982. FImageBase:=0;
  1983. {$ifdef cpu16bitaddr}
  1984. SectionMemAlign:=$10;
  1985. SectionDataAlign:=$10;
  1986. {$else cpu16bitaddr}
  1987. SectionMemAlign:=$1000;
  1988. SectionDataAlign:=$200;
  1989. {$endif cpu16bitaddr}
  1990. FixedSectionAlign:=True;
  1991. FCExeSection:=TExeSection;
  1992. FCObjData:=TObjData;
  1993. FCObjSymbol:=TObjSymbol;
  1994. end;
  1995. destructor TExeOutput.destroy;
  1996. begin
  1997. FExeSymbolList.free;
  1998. UnresolvedExeSymbols.free;
  1999. ExternalObjSymbols.free;
  2000. FProvidedObjSymbols.free;
  2001. FIndirectObjSymbols.free;
  2002. CommonObjSymbols.free;
  2003. ExeVTableList.free;
  2004. FExeSectionList.free;
  2005. ComdatGroups.free;
  2006. ObjDatalist.free;
  2007. FWriter.free;
  2008. inherited destroy;
  2009. end;
  2010. function TExeOutput.MemAlign(exesec:TExeSection):longword;
  2011. begin
  2012. if FixedSectionAlign then
  2013. result:=SectionMemAlign
  2014. else
  2015. result:=exesec.SecAlign;
  2016. end;
  2017. function TExeOutput.DataAlign(exesec:TExeSection):longword;
  2018. begin
  2019. if FixedSectionAlign then
  2020. result:=SectionDataAlign
  2021. else
  2022. result:=exesec.SecAlign;
  2023. end;
  2024. function TExeOutput.WriteExeFile(const fn:string):boolean;
  2025. begin
  2026. result:=false;
  2027. if FWriter.createfile(fn) then
  2028. begin
  2029. { Only write the .o if there are no errors }
  2030. if errorcount=0 then
  2031. result:=writedata
  2032. else
  2033. result:=true;
  2034. { close the writer }
  2035. FWriter.closefile;
  2036. end
  2037. else
  2038. Comment(V_Fatal,'Can''t create executable '+fn);
  2039. end;
  2040. procedure TExeOutput.ParseScript (linkscript:TCmdStrList);
  2041. begin
  2042. end;
  2043. function TExeOutput.FindExeSection(const aname:string):TExeSection;
  2044. begin
  2045. result:=TExeSection(ExeSectionList.Find(aname));
  2046. end;
  2047. procedure TExeOutput.AddObjData(ObjData:TObjData);
  2048. begin
  2049. if ObjData.classtype<>FCObjData then
  2050. Comment(V_Error,'Invalid input object format for '+ObjData.name+' got '+ObjData.classname+' expected '+FCObjData.classname);
  2051. ObjDataList.Add(ObjData);
  2052. ExecStack:=ExecStack or ObjData.ExecStack;
  2053. end;
  2054. procedure TExeOutput.Load_Start;
  2055. begin
  2056. ObjDataList.Clear;
  2057. { Globals defined in the linker script }
  2058. if not assigned(internalObjData) then
  2059. internalObjData:=CObjData.create('*Internal*');
  2060. AddObjData(internalObjData);
  2061. { Common Data section }
  2062. commonObjSection:=internalObjData.createsection(sec_bss,'');
  2063. end;
  2064. procedure TExeOutput.Load_EntryName(const aname:string);
  2065. begin
  2066. FEntryName:=aname;
  2067. end;
  2068. procedure TExeOutput.Load_IsSharedLibrary;
  2069. begin
  2070. IsSharedLibrary:=true;
  2071. end;
  2072. procedure TExeOutput.Load_ImageBase(const avalue:string);
  2073. var
  2074. code : integer;
  2075. objsec : TObjSection;
  2076. objsym : TObjSymbol;
  2077. exesym : TExeSymbol;
  2078. begin
  2079. val(avalue,FImageBase,code);
  2080. if code<>0 then
  2081. Comment(V_Error,'Invalid number '+avalue);
  2082. { Create __image_base__ symbol, create the symbol
  2083. in a section with adress 0 and at offset 0 }
  2084. objsec:=internalObjData.createsection('*__image_base__',0,[]);
  2085. internalObjData.setsection(objsec);
  2086. objsym:=internalObjData.SymbolDefine('__image_base__',AB_GLOBAL,AT_DATA);
  2087. exesym:=texesymbol.Create(FExeSymbolList,objsym.name);
  2088. exesym.ObjSymbol:=objsym;
  2089. end;
  2090. procedure TExeOutput.Load_Symbol(const aname:string);
  2091. begin
  2092. internalObjData.createsection('*'+aname,0,[]);
  2093. internalObjData.SymbolDefine(aname,AB_GLOBAL,AT_DATA);
  2094. end;
  2095. procedure TExeOutput.Load_ProvideSymbol(const aname:string);
  2096. begin
  2097. if assigned(ExeSymbolList.Find(aname)) then
  2098. exit;
  2099. internalObjData.createsection('*'+aname,0,[]);
  2100. // Use AB_COMMON to avoid muliple defined complaints
  2101. internalObjData.SymbolDefine(aname,AB_COMMON,AT_DATA);
  2102. end;
  2103. procedure TExeOutput.Load_DynamicObject(ObjData:TObjData;asneeded:boolean);
  2104. begin
  2105. end;
  2106. procedure TExeOutput.Order_Start;
  2107. begin
  2108. end;
  2109. procedure TExeOutput.Order_End;
  2110. begin
  2111. internalObjData.afterwrite;
  2112. end;
  2113. procedure TExeOutput.Order_ExeSection(const aname:string);
  2114. var
  2115. sec : TExeSection;
  2116. begin
  2117. sec:=FindExeSection(aname);
  2118. if not assigned(sec) then
  2119. sec:=CExeSection.create(ExeSectionList,aname);
  2120. { Clear ExeSection contents }
  2121. FCurrExeSec:=sec;
  2122. end;
  2123. procedure TExeOutput.Order_EndExeSection;
  2124. begin
  2125. if not assigned(CurrExeSec) then
  2126. internalerror(200602184);
  2127. FCurrExeSec:=nil;
  2128. end;
  2129. procedure TExeOutput.Order_ObjSection(const aname:string);
  2130. var
  2131. i,j : longint;
  2132. ObjData : TObjData;
  2133. objsec : TObjSection;
  2134. TmpObjSectionList : TFPObjectList;
  2135. begin
  2136. if not assigned(CurrExeSec) then
  2137. internalerror(200602181);
  2138. TmpObjSectionList:=TFPObjectList.Create(false);
  2139. for i:=0 to ObjDataList.Count-1 do
  2140. begin
  2141. ObjData:=TObjData(ObjDataList[i]);
  2142. for j:=0 to ObjData.ObjSectionList.Count-1 do
  2143. begin
  2144. objsec:=TObjSection(ObjData.ObjSectionList[j]);
  2145. if (not objsec.Used) and
  2146. MatchPattern(aname,objsec.name) then
  2147. TmpObjSectionList.Add(objsec);
  2148. end;
  2149. end;
  2150. { Order list if needed }
  2151. Order_ObjSectionList(TmpObjSectionList,aname);
  2152. { Add the (ordered) list to the current ExeSection }
  2153. for i:=0 to TmpObjSectionList.Count-1 do
  2154. begin
  2155. objsec:=TObjSection(TmpObjSectionList[i]);
  2156. CurrExeSec.AddObjSection(objsec);
  2157. end;
  2158. TmpObjSectionList.Free;
  2159. end;
  2160. procedure TExeOutput.Order_ObjSectionList(ObjSectionList : TFPObjectList; const aPattern:string);
  2161. begin
  2162. end;
  2163. procedure TExeOutput.Order_Symbol(const aname:string);
  2164. var
  2165. objsym: TObjSymbol;
  2166. begin
  2167. objsym:=TObjSymbol(internalObjData.ObjSymbolList.Find(aname));
  2168. if (objsym=nil) or (objsym.ObjSection.ObjData<>internalObjData) then
  2169. internalerror(200603041);
  2170. CurrExeSec.AddObjSection(objsym.ObjSection,True);
  2171. end;
  2172. procedure TExeOutput.Order_ProvideSymbol(const aname:string);
  2173. var
  2174. objsym : TObjSymbol;
  2175. exesym : TExeSymbol;
  2176. begin
  2177. objsym:=TObjSymbol(internalObjData.ObjSymbolList.Find(aname));
  2178. if (objsym=nil) or (objsym.ObjSection.ObjData<>internalObjData) then
  2179. internalerror(2006030403);
  2180. exesym:=TExeSymbol(ExeSymbolList.Find(aname));
  2181. if not assigned(exesym) then
  2182. internalerror(201206301);
  2183. { Only include this section if it actually resolves
  2184. the symbol }
  2185. if exesym.objsymbol=objsym then
  2186. CurrExeSec.AddObjSection(objsym.ObjSection,True);
  2187. end;
  2188. procedure TExeOutput.Order_Align(const avalue:string);
  2189. var
  2190. code : integer;
  2191. alignval : shortint;
  2192. objsec : TObjSection;
  2193. begin
  2194. val(avalue,alignval,code);
  2195. if code<>0 then
  2196. Comment(V_Error,'Invalid number '+avalue);
  2197. if alignval<=0 then
  2198. exit;
  2199. { Create an empty section with the required aligning }
  2200. inc(Fzeronr);
  2201. objsec:=internalObjData.createsection('*align'+tostr(Fzeronr),alignval,CurrExeSec.SecOptions+[oso_Data,oso_keep]);
  2202. CurrExeSec.AddObjSection(objsec);
  2203. end;
  2204. procedure TExeOutput.Order_Zeros(const avalue:string);
  2205. var
  2206. zeros : array[0..1023] of byte;
  2207. code : integer;
  2208. len : longint;
  2209. objsec : TObjSection;
  2210. begin
  2211. val(avalue,len,code);
  2212. if code<>0 then
  2213. Comment(V_Error,'Invalid number '+avalue);
  2214. if len<=0 then
  2215. exit;
  2216. if len>sizeof(zeros) then
  2217. internalerror(200602254);
  2218. fillchar(zeros,len,0);
  2219. inc(Fzeronr);
  2220. objsec:=internalObjData.createsection('*zeros'+tostr(Fzeronr),0,CurrExeSec.SecOptions+[oso_Data,oso_keep]);
  2221. internalObjData.writebytes(zeros,len);
  2222. CurrExeSec.AddObjSection(objsec);
  2223. end;
  2224. procedure TExeOutput.Order_Values(bytesize : aword; const avalue:string);
  2225. const
  2226. MAXVAL = 128;
  2227. var
  2228. bytevalues : array[0..MAXVAL-1] of byte;
  2229. twobytevalues : array[0..MAXVAL-1] of word;
  2230. fourbytevalues : array[0..MAXVAL-1] of dword;
  2231. eightbytevalues : array[0..MAXVAL-1] of qword;
  2232. allvals, oneval : string;
  2233. len, commapos : longint;
  2234. indexpos, code : integer;
  2235. anumval : qword;
  2236. signedval : int64;
  2237. objsec : TObjSection;
  2238. begin
  2239. indexpos:=0;
  2240. allvals:=avalue;
  2241. { avoid warnings }
  2242. bytevalues[0]:=0;
  2243. twobytevalues[0]:=0;
  2244. fourbytevalues[0]:=0;
  2245. eightbytevalues[0]:=0;
  2246. repeat
  2247. commapos:=pos(',',allvals);
  2248. if commapos>0 then
  2249. begin
  2250. oneval:=trim(copy(allvals,1,commapos-1));
  2251. allvals:=copy(allvals,commapos+1,length(allvals));
  2252. end
  2253. else
  2254. begin
  2255. oneval:=trim(allvals);
  2256. allvals:='';
  2257. end;
  2258. if oneval<>'' then
  2259. begin
  2260. if oneval[1]='-' then
  2261. begin
  2262. val(oneval,signedval,code);
  2263. anumval:=qword(signedval);
  2264. end
  2265. else
  2266. val(oneval,anumval,code);
  2267. if code<>0 then
  2268. Comment(V_Error,'Invalid number '+avalue)
  2269. else
  2270. begin
  2271. if (indexpos<MAXVAL) then
  2272. begin
  2273. if source_info.endian<>target_info.endian then
  2274. swapendian(anumval);
  2275. { No range checking here }
  2276. if bytesize=1 then
  2277. bytevalues[indexpos]:=byte(anumval)
  2278. else if bytesize=2 then
  2279. twobytevalues[indexpos]:=word(anumval)
  2280. else if bytesize=4 then
  2281. fourbytevalues[indexpos]:=dword(anumval)
  2282. else if bytesize=8 then
  2283. eightbytevalues[indexpos]:=anumval;
  2284. inc(indexpos);
  2285. end
  2286. else
  2287. Comment(V_Error,'Buffer overrun in Order_values');
  2288. end;
  2289. end;
  2290. until allvals='';
  2291. if indexpos=0 then
  2292. begin
  2293. Comment(V_Error,'Invalid number '+avalue);
  2294. exit;
  2295. end;
  2296. if indexpos=MAXVAL then
  2297. begin
  2298. Comment(V_Error,'Too many values '+avalue);
  2299. internalerror(2006022505);
  2300. end;
  2301. len:=bytesize*indexpos;
  2302. inc(Fvaluesnr);
  2303. objsec:=internalObjData.createsection('*values'+tostr(Fvaluesnr),0,CurrExeSec.SecOptions+[oso_Data,oso_keep]);
  2304. if bytesize=1 then
  2305. internalObjData.writebytes(bytevalues,len)
  2306. else if bytesize=2 then
  2307. internalObjData.writebytes(twobytevalues,len)
  2308. else if bytesize=4 then
  2309. internalObjData.writebytes(fourbytevalues,len)
  2310. else if bytesize=8 then
  2311. internalObjData.writebytes(eightbytevalues,len);
  2312. CurrExeSec.AddObjSection(objsec);
  2313. end;
  2314. procedure TExeOutput.MemPos_Start;
  2315. begin
  2316. CurrMemPos:=0;
  2317. RemoveDisabledSections;
  2318. end;
  2319. procedure TExeOutput.MemPos_Header;
  2320. begin
  2321. end;
  2322. procedure TExeOutput.MemPos_ExeSection(exesec:TExeSection);
  2323. var
  2324. i : longint;
  2325. objsec : TObjSection;
  2326. begin
  2327. { Alignment of ExeSection }
  2328. CurrMemPos:=align_qword(CurrMemPos,MemAlign(exesec));
  2329. exesec.MemPos:=CurrMemPos;
  2330. { set position of object ObjSections }
  2331. for i:=0 to exesec.ObjSectionList.Count-1 do
  2332. begin
  2333. objsec:=TObjSection(exesec.ObjSectionList[i]);
  2334. CurrMemPos:=objsec.setmempos(CurrMemPos);
  2335. end;
  2336. { calculate size of the section }
  2337. exesec.Size:=CurrMemPos-exesec.MemPos;
  2338. end;
  2339. procedure TExeOutput.MemPos_ExeSection(const aname:string);
  2340. begin
  2341. { Section can be removed }
  2342. FCurrExeSec:=FindExeSection(aname);
  2343. if not assigned(CurrExeSec) then
  2344. exit;
  2345. MemPos_ExeSection(CurrExeSec);
  2346. end;
  2347. procedure TExeOutput.MemPos_EndExeSection;
  2348. begin
  2349. if not assigned(CurrExeSec) then
  2350. exit;
  2351. FCurrExeSec:=nil;
  2352. end;
  2353. procedure TExeOutput.DataPos_Start;
  2354. begin
  2355. end;
  2356. procedure TExeOutput.DataPos_Header;
  2357. begin
  2358. end;
  2359. procedure TExeOutput.DataPos_ExeSection(exesec:TExeSection);
  2360. begin
  2361. { don't write normal section if writing only debug info }
  2362. if (ExeWriteMode=ewm_dbgonly) and
  2363. (exesec.SecOptions*[oso_debug,oso_debug_copy]=[]) then
  2364. exit;
  2365. if (oso_Data in exesec.SecOptions) then
  2366. begin
  2367. CurrDataPos:=align_aword(CurrDataPos,DataAlign(exesec));
  2368. exesec.DataPos:=CurrDataPos;
  2369. CurrDataPos:=CurrDataPos+exesec.Size;
  2370. end;
  2371. end;
  2372. procedure TExeOutput.DataPos_ExeSection(const aname:string);
  2373. begin
  2374. { Section can be removed }
  2375. FCurrExeSec:=FindExeSection(aname);
  2376. if not assigned(CurrExeSec) then
  2377. exit;
  2378. DataPos_ExeSection(CurrExeSec);
  2379. end;
  2380. procedure TExeOutput.DataPos_EndExeSection;
  2381. begin
  2382. if not assigned(CurrExeSec) then
  2383. exit;
  2384. FCurrExeSec:=nil;
  2385. end;
  2386. procedure TExeOutput.DataPos_Symbols;
  2387. begin
  2388. end;
  2389. procedure TExeOutput.BuildVTableTree(VTInheritList,VTEntryList:TFPObjectList);
  2390. var
  2391. hs : string;
  2392. code : integer;
  2393. i,k,
  2394. vtableidx : longint;
  2395. vtableexesym,
  2396. childexesym,
  2397. parentexesym : TExeSymbol;
  2398. objsym : TObjSymbol;
  2399. begin
  2400. { Build inheritance tree from VTINHERIT }
  2401. for i:=0 to VTInheritList.Count-1 do
  2402. begin
  2403. objsym:=TObjSymbol(VTInheritList[i]);
  2404. hs:=objsym.name;
  2405. { VTINHERIT_<ChildVMTName>$$<ParentVMTName> }
  2406. Delete(hs,1,Pos('_',hs));
  2407. k:=Pos('$$',hs);
  2408. if k=0 then
  2409. internalerror(200603311);
  2410. childexesym:=texesymbol(FExeSymbolList.Find(Copy(hs,1,k-1)));
  2411. parentexesym:=texesymbol(FExeSymbolList.Find(Copy(hs,k+2,length(hs)-k-1)));
  2412. if not assigned(childexesym) or
  2413. not assigned(parentexesym)then
  2414. internalerror(200603312);
  2415. if not assigned(childexesym.vtable) then
  2416. begin
  2417. childexesym.vtable:=TExeVTable.Create(childexesym);
  2418. ExeVTableList.Add(childexesym.vtable);
  2419. end;
  2420. if not assigned(parentexesym.vtable) then
  2421. begin
  2422. parentexesym.vtable:=TExeVTable.Create(parentexesym);
  2423. ExeVTableList.Add(parentexesym.vtable);
  2424. end;
  2425. childexesym.vtable.SetVTableSize(childexesym.ObjSymbol.Size);
  2426. if parentexesym<>childexesym then
  2427. parentexesym.vtable.AddChild(childexesym.vtable);
  2428. end;
  2429. { Find VTable entries from VTENTRY }
  2430. for i:=0 to VTEntryList.Count-1 do
  2431. begin
  2432. objsym:=TObjSymbol(VTEntryList[i]);
  2433. hs:=objsym.name;
  2434. { VTENTRY_<VTableName>$$<Index> }
  2435. Delete(hs,1,Pos('_',hs));
  2436. k:=Pos('$$',hs);
  2437. if k=0 then
  2438. internalerror(200603319);
  2439. vtableexesym:=texesymbol(FExeSymbolList.Find(Copy(hs,1,k-1)));
  2440. val(Copy(hs,k+2,length(hs)-k-1),vtableidx,code);
  2441. if (code<>0) then
  2442. internalerror(200603318);
  2443. if not assigned(vtableexesym) then
  2444. internalerror(2006033110);
  2445. vtableexesym.vtable.AddEntry(vtableidx);
  2446. end;
  2447. end;
  2448. procedure TExeOutput.PackUnresolvedExeSymbols(const s:string);
  2449. var
  2450. i : longint;
  2451. exesym : TExeSymbol;
  2452. begin
  2453. { Generate a list of Unresolved External symbols }
  2454. for i:=0 to UnresolvedExeSymbols.count-1 do
  2455. begin
  2456. exesym:=TExeSymbol(UnresolvedExeSymbols[i]);
  2457. if not (exesym.State in [symstate_undefined,symstate_undefweak]) then
  2458. UnresolvedExeSymbols[i]:=nil;
  2459. end;
  2460. UnresolvedExeSymbols.Pack;
  2461. Comment(V_Debug,'Number of unresolved externals '+s+' '+tostr(UnresolvedExeSymbols.Count));
  2462. end;
  2463. procedure TExeOutput.ResolveSymbols(StaticLibraryList:TFPObjectList);
  2464. var
  2465. ObjData : TObjData;
  2466. exesym : TExeSymbol;
  2467. objsym,
  2468. commonsym : TObjSymbol;
  2469. firstarchive,
  2470. firstcommon : boolean;
  2471. i : longint;
  2472. VTEntryList,
  2473. VTInheritList : TFPObjectList;
  2474. procedure LoadObjDataSymbols(ObjData:TObjData);
  2475. var
  2476. j : longint;
  2477. hs : string;
  2478. exesym : TExeSymbol;
  2479. tmpsym,
  2480. objsym : TObjSymbol;
  2481. grp : TObjSectionGroup;
  2482. makeexternal : boolean;
  2483. begin
  2484. for j:=0 to ObjData.ObjSymbolList.Count-1 do
  2485. begin
  2486. objsym:=TObjSymbol(ObjData.ObjSymbolList[j]);
  2487. { From the local symbols we are only interessed in the
  2488. VTENTRY and VTINHERIT symbols }
  2489. if objsym.bind=AB_LOCAL then
  2490. begin
  2491. if cs_link_opt_vtable in current_settings.globalswitches then
  2492. begin
  2493. hs:=objsym.name;
  2494. if (hs[1]='V') then
  2495. begin
  2496. if Copy(hs,1,5)='VTREF' then
  2497. begin
  2498. if not assigned(objsym.ObjSection.VTRefList) then
  2499. objsym.ObjSection.VTRefList:=TFPObjectList.Create(false);
  2500. objsym.ObjSection.VTRefList.Add(objsym);
  2501. end
  2502. else if Copy(hs,1,7)='VTENTRY' then
  2503. VTEntryList.Add(objsym)
  2504. else if Copy(hs,1,9)='VTINHERIT' then
  2505. VTInheritList.Add(objsym);
  2506. end;
  2507. end;
  2508. continue;
  2509. end;
  2510. { If this symbol comes from COMDAT group, see if a group with
  2511. matching signature is already included. }
  2512. if assigned(objsym.objsection) and
  2513. assigned(objsym.objsection.group) then
  2514. begin
  2515. grp:=objsym.objsection.group;
  2516. if grp.IsComdat then
  2517. begin
  2518. if ComdatGroups.Find(grp.name)=nil then
  2519. ComdatGroups.Add(grp.name,grp)
  2520. else
  2521. begin
  2522. { Undefine the symbol, causing relocations to it from same
  2523. objdata to be redirected to the symbol in the actually
  2524. linked group. }
  2525. if objsym.bind=AB_GLOBAL then
  2526. objsym.bind:=AB_EXTERNAL;
  2527. { AB_WEAK_EXTERNAL remains unchanged }
  2528. objsym.objsection:=nil;
  2529. end;
  2530. end;
  2531. end;
  2532. { Search for existing exesymbol }
  2533. exesym:=texesymbol(FExeSymbolList.Find(objsym.name));
  2534. if not assigned(exesym) then
  2535. begin
  2536. exesym:=texesymbol.Create(FExeSymbolList,objsym.name);
  2537. exesym.ObjSymbol:=objsym;
  2538. end
  2539. else
  2540. begin
  2541. if assigned(objsym.objsection) and assigned(exesym.objsymbol.objsection) then
  2542. begin
  2543. if (oso_comdat in exesym.ObjSymbol.objsection.SecOptions) and
  2544. (oso_comdat in objsym.objsection.SecOptions) then
  2545. begin
  2546. if exesym.ObjSymbol.objsection.ComdatSelection=objsym.objsection.ComdatSelection then
  2547. begin
  2548. makeexternal:=true;
  2549. case objsym.objsection.ComdatSelection of
  2550. oscs_none:
  2551. makeexternal:=false;
  2552. oscs_any:
  2553. Message1(link_d_comdat_discard_any,objsym.name);
  2554. oscs_same_size:
  2555. if exesym.ObjSymbol.size<>objsym.size then
  2556. Message1(link_e_comdat_size_differs,objsym.name)
  2557. else
  2558. Message1(link_d_comdat_discard_size,objsym.name);
  2559. oscs_exact_match:
  2560. if (exesym.ObjSymbol.size<>objsym.size) and not exesym.ObjSymbol.objsection.Data.equal(objsym.objsection.Data) then
  2561. Message1(link_e_comdat_content_differs,objsym.name)
  2562. else
  2563. Message1(link_d_comdat_discard_content,objsym.name);
  2564. oscs_associative:
  2565. { this is handled in a different way }
  2566. makeexternal:=false;
  2567. oscs_largest:
  2568. if objsym.size>exesym.ObjSymbol.size then
  2569. begin
  2570. Message1(link_d_comdat_replace_size,objsym.name);
  2571. { we swap the symbols and turn the smaller one to an external
  2572. symbol }
  2573. tmpsym:=exesym.objsymbol;
  2574. exesym.objsymbol:=objsym;
  2575. objsym.exesymbol:=exesym;
  2576. objsym:=tmpsym;
  2577. end;
  2578. end;
  2579. if makeexternal then
  2580. begin
  2581. { Undefine the symbol, causing relocations to it from same
  2582. objdata to be redirected to the symbol that is actually
  2583. used }
  2584. if objsym.bind=AB_GLOBAL then
  2585. objsym.bind:=AB_EXTERNAL;
  2586. { AB_WEAK_EXTERNAL remains unchanged }
  2587. objsym.objsection:=nil;
  2588. end;
  2589. end
  2590. else
  2591. Message1(link_e_comdat_selection_differs,objsym.name);
  2592. end;
  2593. end;
  2594. end;
  2595. objsym.ExeSymbol:=exesym;
  2596. case objsym.bind of
  2597. AB_GLOBAL,
  2598. AB_PRIVATE_EXTERN:
  2599. begin
  2600. if exesym.State<>symstate_defined then
  2601. begin
  2602. exesym.ObjSymbol:=objsym;
  2603. exesym.State:=symstate_defined;
  2604. end
  2605. else
  2606. Message1(link_e_duplicate_symbol,objsym.name);
  2607. { hidden symbols must become local symbols in the executable }
  2608. if objsym.bind=AB_PRIVATE_EXTERN then
  2609. objsym.bind:=AB_LOCAL;
  2610. end;
  2611. AB_EXTERNAL :
  2612. begin
  2613. ExternalObjSymbols.add(objsym);
  2614. { Register unresolved symbols only the first time they
  2615. are registered }
  2616. if exesym.ObjSymbol=objsym then
  2617. UnresolvedExeSymbols.Add(exesym)
  2618. { Normal reference removes any existing "weakness" }
  2619. else if exesym.state=symstate_undefweak then
  2620. begin
  2621. exesym.state:=symstate_undefined;
  2622. exesym.ObjSymbol:=objsym;
  2623. end;
  2624. end;
  2625. AB_COMMON :
  2626. begin
  2627. { A COMMON definition overrides weak one.
  2628. Also select the symbol with largest size. }
  2629. if (exesym.State in [symstate_undefined,symstate_undefweak,symstate_defweak]) or
  2630. ((exesym.State=symstate_common) and (objsym.size>exesym.ObjSymbol.size)) then
  2631. begin
  2632. exesym.ObjSymbol:=objsym;
  2633. exesym.State:=symstate_common;
  2634. end;
  2635. if assigned(objsym.objsection) and
  2636. (objsym.objsection.objdata=internalObjData) then
  2637. FProvidedObjSymbols.add(objsym)
  2638. else
  2639. CommonObjSymbols.add(objsym);
  2640. end;
  2641. AB_WEAK_EXTERNAL :
  2642. begin
  2643. if objsym.objsection=nil then { a weak reference }
  2644. begin
  2645. ExternalObjSymbols.add(objsym);
  2646. if exesym.ObjSymbol=objsym then
  2647. begin
  2648. UnresolvedExeSymbols.Add(exesym);
  2649. exesym.state:=symstate_undefweak;
  2650. end;
  2651. end
  2652. else { a weak definition }
  2653. begin
  2654. if exesym.State in [symstate_undefined,symstate_undefweak] then
  2655. begin
  2656. exesym.ObjSymbol:=objsym;
  2657. exesym.state:=symstate_defweak;
  2658. end;
  2659. end;
  2660. end;
  2661. else
  2662. internalerror(2019050510);
  2663. end;
  2664. end;
  2665. end;
  2666. procedure LoadLibrary(lib:TStaticLibrary);
  2667. var
  2668. j,k,oldcount: longint;
  2669. members: TFPObjectList;
  2670. exesym: TExeSymbol;
  2671. objinput: TObjInput;
  2672. begin
  2673. case lib.Kind of
  2674. lkArchive:
  2675. begin
  2676. { Process list of Unresolved External symbols, we need
  2677. to use a while loop because the list can be extended when
  2678. we load members from the library. }
  2679. j:=0;
  2680. while (j<UnresolvedExeSymbols.count) do
  2681. begin
  2682. exesym:=TExeSymbol(UnresolvedExeSymbols[j]);
  2683. { Check first if the symbol is still undefined }
  2684. if (exesym.State=symstate_undefined) then
  2685. begin
  2686. if lib.ArReader.OpenFile(exesym.name) then
  2687. begin
  2688. if assigned(exemap) then
  2689. begin
  2690. if firstarchive then
  2691. begin
  2692. exemap.Add('');
  2693. exemap.Add('Archive member included because of file (symbol)');
  2694. exemap.Add('');
  2695. firstarchive:=false;
  2696. end;
  2697. exemap.Add(lib.ArReader.FileName+' - '+
  2698. {exesym.ObjSymbol.ObjSection.FullName+}
  2699. '('+exesym.Name+')');
  2700. end;
  2701. objinput:=lib.ObjInputClass.Create;
  2702. objinput.ReadObjData(lib.ArReader,objdata);
  2703. objinput.free;
  2704. AddObjData(objdata);
  2705. LoadObjDataSymbols(objdata);
  2706. lib.ArReader.CloseFile;
  2707. end;
  2708. end;
  2709. inc(j);
  2710. end;
  2711. end;
  2712. lkGroup:
  2713. begin
  2714. { repeatedly process members of the group until no new
  2715. unresolved symbols appear }
  2716. members:=lib.GroupMembers;
  2717. repeat
  2718. oldcount:=UnresolvedExeSymbols.count;
  2719. for k:=0 to members.Count-1 do
  2720. LoadLibrary(TStaticLibrary(members[k]));
  2721. until UnresolvedExeSymbols.count=oldcount;
  2722. end;
  2723. lkObject:
  2724. { TODO: ownership of objdata }
  2725. //if lib.objdata.is_dynamic then
  2726. Load_DynamicObject(lib.objdata,lib.AsNeeded);
  2727. {else
  2728. begin
  2729. AddObjData(lib.objdata);
  2730. LoadObjDataSymbols(lib.objdata);
  2731. end;}
  2732. end;
  2733. end;
  2734. begin
  2735. VTEntryList:=TFPObjectList.Create(false);
  2736. VTInheritList:=TFPObjectList.Create(false);
  2737. {
  2738. The symbol resolving is done in 4 steps:
  2739. 1. Register symbols from objects
  2740. 2. Find symbols in static libraries
  2741. 3. Define symbols PROVIDEd by the link script
  2742. 4. Define still undefined common symbols
  2743. }
  2744. { Step 1, Register symbols from objects }
  2745. for i:=0 to ObjDataList.Count-1 do
  2746. begin
  2747. ObjData:=TObjData(ObjDataList[i]);
  2748. LoadObjDataSymbols(ObjData);
  2749. end;
  2750. PackUnresolvedExeSymbols('in objects');
  2751. { Step 2, Find unresolved symbols in the libraries }
  2752. firstarchive:=true;
  2753. for i:=0 to StaticLibraryList.Count-1 do
  2754. LoadLibrary(TStaticLibrary(StaticLibraryList[i]));
  2755. PackUnresolvedExeSymbols('after static libraries');
  2756. { Step 3, handle symbols provided in script }
  2757. for i:=0 to FProvidedObjSymbols.count-1 do
  2758. begin
  2759. objsym:=TObjSymbol(FProvidedObjSymbols[i]);
  2760. if objsym.exesymbol.State=symstate_defined then
  2761. continue;
  2762. objsym.exesymbol.objsymbol:=objsym;
  2763. objsym.bind:=AB_GLOBAL;
  2764. objsym.exesymbol.State:=symstate_defined;
  2765. end;
  2766. PackUnresolvedExeSymbols('after defining symbols provided by link script');
  2767. { Step 4, Match common symbols or add to the globals }
  2768. firstcommon:=true;
  2769. for i:=0 to CommonObjSymbols.count-1 do
  2770. begin
  2771. objsym:=TObjSymbol(CommonObjSymbols[i]);
  2772. if objsym.exesymbol.State=symstate_defined then
  2773. begin
  2774. if objsym.exesymbol.ObjSymbol.size<>objsym.size then
  2775. Comment(V_Debug,'Size of common symbol '+objsym.name+' is different, expected '+tostr(objsym.size)+' got '+tostr(objsym.exesymbol.ObjSymbol.size));
  2776. end
  2777. else
  2778. begin
  2779. { allocate new objsymbol in .bss of *COMMON* and assign
  2780. it to the exesymbol }
  2781. if firstcommon then
  2782. begin
  2783. if assigned(exemap) then
  2784. exemap.AddCommonSymbolsHeader;
  2785. firstcommon:=false;
  2786. end;
  2787. internalObjData.setsection(commonObjSection);
  2788. { TODO: support alignment of common symbols (ELF targets at least),
  2789. increase commonObjSection.SecAlign if necessary here. }
  2790. internalObjData.allocalign(used_align(size_2_align(objsym.size),0,commonObjSection.SecAlign));
  2791. commonsym:=internalObjData.symboldefine(objsym.name,AB_GLOBAL,AT_DATA);
  2792. commonsym.size:=objsym.size;
  2793. internalObjData.alloc(objsym.size);
  2794. if assigned(exemap) then
  2795. exemap.AddCommonSymbol(objsym);
  2796. { Assign to the exesymbol }
  2797. objsym.exesymbol.objsymbol:=commonsym;
  2798. objsym.exesymbol.state:=symstate_defined;
  2799. end;
  2800. end;
  2801. PackUnresolvedExeSymbols('after defining COMMON symbols');
  2802. { Find entry symbol and print in map }
  2803. if (EntryName<>'') then
  2804. begin
  2805. exesym:=texesymbol(ExeSymbolList.Find(EntryName));
  2806. if assigned(exesym) then
  2807. begin
  2808. EntrySym:=exesym.ObjSymbol;
  2809. if assigned(exemap) then
  2810. begin
  2811. exemap.Add('');
  2812. exemap.Add('Entry symbol '+EntryName);
  2813. end;
  2814. end
  2815. else
  2816. Comment(V_Error,'Entrypoint '+EntryName+' not defined');
  2817. end;
  2818. { Generate VTable tree }
  2819. if cs_link_opt_vtable in current_settings.globalswitches then
  2820. BuildVTableTree(VTInheritList,VTEntryList);
  2821. VTInheritList.Free;
  2822. VTEntryList.Free;
  2823. end;
  2824. procedure TExeOutput.GenerateDebugLink(const dbgname:string;dbgcrc:cardinal);
  2825. var
  2826. debuglink : array[0..1023] of byte;
  2827. len : longint;
  2828. objsec : TObjSection;
  2829. exesec : TExeSection;
  2830. begin
  2831. { From the gdb manual chapter 15. GDB Files:
  2832. * A filename, with any leading directory components removed, followed by a zero byte,
  2833. * zero to three bytes of padding, as needed to reach the next four-byte boundary within the section, and
  2834. * a four-byte CRC checksum, stored in the same endianness used for the executable file itself. The checksum is computed
  2835. on the debugging information file's full contents by the function given below, passing zero as the crc argument.
  2836. }
  2837. fillchar(debuglink,sizeof(debuglink),0);
  2838. len:=0;
  2839. move(dbgname[1],debuglink[len],length(dbgname));
  2840. inc(len,length(dbgname)+1);
  2841. len:=align(len,4);
  2842. if source_info.endian<>target_info.endian then
  2843. SwapEndian(dbgcrc);
  2844. move(dbgcrc,debuglink[len],sizeof(cardinal));
  2845. inc(len,4);
  2846. { Add section }
  2847. exesec:=FindExeSection(debuglinkname);
  2848. if not assigned(exesec) then
  2849. exesec:=CExeSection.create(ExeSectionList,debuglinkname);
  2850. exesec.SecOptions:=[oso_data,oso_keep];
  2851. exesec.SecAlign:=4;
  2852. objsec:=internalObjData.createsection(exesec.name,1,exesec.SecOptions);
  2853. internalObjData.writebytes(debuglink,len);
  2854. exesec.AddObjSection(objsec);
  2855. end;
  2856. procedure TExeOutput.GenerateLibraryImports(ImportLibraryList:TFPHashObjectList);
  2857. begin
  2858. end;
  2859. procedure TExeOutput.MarkTargetSpecificSections(WorkList:TFPObjectList);
  2860. begin
  2861. end;
  2862. procedure TExeOutput.AfterUnusedSectionRemoval;
  2863. begin
  2864. end;
  2865. function ByAddress(item1,item2:pointer):longint;
  2866. var
  2867. sym1:TObjSymbol absolute item1;
  2868. sym2:TObjSymbol absolute item2;
  2869. begin
  2870. if sym1.address>sym2.address then
  2871. result:=1
  2872. else if sym1.address<sym2.address then
  2873. result:=-1
  2874. else
  2875. result:=0;
  2876. end;
  2877. procedure TExeOutput.PrintMemoryMap;
  2878. var
  2879. exesec : TExeSection;
  2880. objsec : TObjSection;
  2881. objsym : TObjSymbol;
  2882. i,j,k,m: longint;
  2883. list : TFPList;
  2884. flag : boolean;
  2885. begin
  2886. if not assigned(exemap) then
  2887. exit;
  2888. { create a list of symbols sorted by address }
  2889. list:=TFPList.Create;
  2890. for i:=0 to ExeSymbolList.Count-1 do
  2891. list.Add(TExeSymbol(ExeSymbolList[i]).ObjSymbol);
  2892. list.Sort(@ByAddress);
  2893. exemap.AddMemoryMapHeader(ImageBase);
  2894. k:=0;
  2895. for i:=0 to ExeSectionList.Count-1 do
  2896. begin
  2897. exesec:=TExeSection(ExeSectionList[i]);
  2898. exemap.AddMemoryMapExeSection(exesec);
  2899. for j:=0 to exesec.ObjSectionList.count-1 do
  2900. begin
  2901. objsec:=TObjSection(exesec.ObjSectionList[j]);
  2902. exemap.AddMemoryMapObjectSection(objsec);
  2903. while (k<list.Count) and (TObjSymbol(list[k]).Address<objsec.MemPos) do
  2904. inc(k);
  2905. while (k<list.Count) do
  2906. begin
  2907. objsym:=TObjSymbol(list[k]);
  2908. if objsym.address>objsec.MemPos+objsec.Size then
  2909. break;
  2910. if objsym.objsection=objsec then
  2911. exemap.AddMemoryMapSymbol(objsym)
  2912. else
  2913. begin
  2914. { Got a symbol with address falling into current section, but
  2915. belonging to a different section. This may happen for zero-length
  2916. sections because symbol list is sorted by address but not by section.
  2917. Do some look-ahead in this case. }
  2918. m:=k+1;
  2919. flag:=false;
  2920. while (m<list.Count) and (TObjSymbol(list[m]).Address=objsym.address) do
  2921. begin
  2922. if TObjSymbol(list[m]).objsection=objsec then
  2923. begin
  2924. flag:=true;
  2925. list.Exchange(k,m);
  2926. exemap.AddMemoryMapSymbol(TObjSymbol(list[k]));
  2927. break;
  2928. end;
  2929. inc(m);
  2930. end;
  2931. if not flag then
  2932. break;
  2933. end;
  2934. inc(k);
  2935. end;
  2936. end;
  2937. end;
  2938. list.Free;
  2939. end;
  2940. procedure TExeOutput.FixupSymbols;
  2941. procedure UpdateSymbol(objsym:TObjSymbol);
  2942. begin
  2943. objsym.bind:=objsym.ExeSymbol.ObjSymbol.bind;
  2944. objsym.offset:=objsym.ExeSymbol.ObjSymbol.offset;
  2945. objsym.size:=objsym.ExeSymbol.ObjSymbol.size;
  2946. objsym.typ:=objsym.ExeSymbol.ObjSymbol.typ;
  2947. objsym.ObjSection:=objsym.ExeSymbol.ObjSymbol.ObjSection;
  2948. objsym.group:=objsym.ExeSymbol.ObjSymbol.group;
  2949. end;
  2950. var
  2951. i : longint;
  2952. objsym : TObjSymbol;
  2953. exesym : TExeSymbol;
  2954. begin
  2955. { Print list of Unresolved External symbols }
  2956. if not AllowUndefinedSymbols then
  2957. for i:=0 to UnresolvedExeSymbols.count-1 do
  2958. begin
  2959. exesym:=TExeSymbol(UnresolvedExeSymbols[i]);
  2960. if (exesym.State=symstate_undefined) then
  2961. begin
  2962. if assigned(exesym.ObjSymbol) and assigned(exesym.ObjSymbol.ObjData) then
  2963. Message2(link_e_undefined_symbol_in_obj,exesym.name,exesym.objsymbol.ObjData.Name)
  2964. else
  2965. Message1(link_e_undefined_symbol,exesym.name);
  2966. end;
  2967. end;
  2968. {
  2969. Fixing up symbols is done in the following steps:
  2970. 1. Update common references
  2971. 2. Update external references
  2972. Symbols with objsection<>nil are removed from the lists,
  2973. remaining ones can be processed later by calling this method again.
  2974. }
  2975. { Step 1, Update commons. Preserve the original symbol size and bind,
  2976. this is needed for correct relocation of DJCOFF files. }
  2977. for i:=0 to CommonObjSymbols.count-1 do
  2978. begin
  2979. objsym:=TObjSymbol(CommonObjSymbols[i]);
  2980. if objsym.bind<>AB_COMMON then
  2981. internalerror(200606241);
  2982. objsym.ObjSection:=objsym.ExeSymbol.ObjSymbol.ObjSection;
  2983. objsym.offset:=objsym.ExeSymbol.ObjSymbol.offset;
  2984. objsym.typ:=objsym.ExeSymbol.ObjSymbol.typ;
  2985. end;
  2986. { Step 2, Update externals }
  2987. for i:=0 to ExternalObjSymbols.count-1 do
  2988. begin
  2989. objsym:=TObjSymbol(ExternalObjSymbols[i]);
  2990. if not (objsym.bind in [AB_EXTERNAL,AB_WEAK_EXTERNAL]) then
  2991. internalerror(200606242);
  2992. UpdateSymbol(objsym);
  2993. { Collect symbols that resolve to indirect functions,
  2994. they will need additional target-specific processing. }
  2995. if objsym.typ=AT_GNU_IFUNC then
  2996. IndirectObjSymbols.Add(objsym)
  2997. else if assigned(objsym.objsection) then
  2998. ExternalObjSymbols[i]:=nil;
  2999. end;
  3000. CommonObjSymbols.Clear;
  3001. ExternalObjSymbols.Pack;
  3002. end;
  3003. procedure TExeOutput.MergeStabs;
  3004. var
  3005. stabexesec,
  3006. stabstrexesec : TExeSection;
  3007. relocsec,
  3008. currstabsec,
  3009. currstabstrsec,
  3010. mergedstabsec,
  3011. mergedstabstrsec : TObjSection;
  3012. hstabreloc,
  3013. currstabreloc : TObjRelocation;
  3014. i,j : longint;
  3015. currstabrelocidx,
  3016. mergestabcnt,
  3017. stabcnt : longword;
  3018. skipstab : boolean;
  3019. skipfun : boolean;
  3020. hstab : TObjStabEntry;
  3021. stabrelocofs : longword;
  3022. buf : array[0..1023] of byte;
  3023. bufend,
  3024. bufsize : longint;
  3025. begin
  3026. stabexesec:=FindExeSection('.stab');
  3027. stabstrexesec:=FindExeSection('.stabstr');
  3028. if (stabexesec=nil) or
  3029. (stabstrexesec=nil) or
  3030. (stabexesec.ObjSectionlist.count=0) then
  3031. exit;
  3032. { Create new stabsection }
  3033. stabRelocofs:=pbyte(@hstab.nvalue)-pbyte(@hstab);
  3034. mergedstabsec:=internalObjData.CreateSection(sec_stab,'');
  3035. mergedstabstrsec:=internalObjData.CreateSection(sec_stabstr,'');
  3036. { write stab for hdrsym }
  3037. mergedstabsec.writeZeros(sizeof(TObjStabEntry));
  3038. mergestabcnt:=1;
  3039. { .stabstr starts with a #0 }
  3040. buf[0]:=0;
  3041. mergedstabstrsec.write(buf[0],1);
  3042. skipfun:=false;
  3043. { Copy stabs and corresponding Relocations }
  3044. for i:=0 to stabexesec.ObjSectionList.Count-1 do
  3045. begin
  3046. currstabsec:=TObjSection(stabexesec.ObjSectionList[i]);
  3047. currstabstrsec:=currstabsec.ObjData.findsection('.stabstr');
  3048. if assigned(currstabstrsec) then
  3049. begin
  3050. stabcnt:=currstabsec.Data.size div sizeof(TObjStabEntry);
  3051. currstabsec.Data.seek(0);
  3052. currstabrelocidx:=0;
  3053. for j:=0 to stabcnt-1 do
  3054. begin
  3055. hstabreloc:=nil;
  3056. skipstab:=false;
  3057. currstabsec.Data.read(hstab,sizeof(TObjStabEntry));
  3058. MaybeSwapStab(hstab);
  3059. { Only include first hdrsym stab }
  3060. if hstab.ntype=0 then
  3061. skipstab:=true;
  3062. if skipfun then
  3063. begin
  3064. { Skip all stabs for function body until N_RBRAC }
  3065. skipfun:=hstab.ntype<>N_RBRAC;
  3066. skipstab:=true;
  3067. end;
  3068. if not skipstab then
  3069. begin
  3070. { Find corresponding Relocation }
  3071. currstabreloc:=nil;
  3072. while (currstabrelocidx<longword(currstabsec.ObjRelocations.Count)) do
  3073. begin
  3074. currstabreloc:=TObjRelocation(currstabsec.ObjRelocations[currstabrelocidx]);
  3075. if assigned(currstabreloc) and
  3076. (currstabreloc.dataoffset>=longword(j)*sizeof(TObjStabEntry)+stabrelocofs) then
  3077. break;
  3078. inc(currstabrelocidx);
  3079. end;
  3080. if assigned(currstabreloc) and
  3081. (currstabreloc.dataoffset=longword(j)*sizeof(TObjStabEntry)+stabrelocofs) then
  3082. begin
  3083. hstabReloc:=currstabReloc;
  3084. inc(currstabrelocidx);
  3085. end;
  3086. { Check if the stab is refering to a removed section }
  3087. if assigned(hstabreloc) then
  3088. begin
  3089. if assigned(hstabreloc.Symbol) then
  3090. relocsec:=hstabreloc.Symbol.ObjSection
  3091. else
  3092. relocsec:=hstabreloc.ObjSection;
  3093. if not assigned(relocsec) then
  3094. internalerror(200603302);
  3095. if not relocsec.Used then
  3096. begin
  3097. skipstab:=true;
  3098. if (hstab.ntype=N_Function) and (hstab.strpos<>0) then
  3099. begin
  3100. currstabstrsec.Data.seek(hstab.strpos);
  3101. bufsize:=currstabstrsec.Data.read(buf,sizeof(buf));
  3102. bufend:=indexbyte(buf,bufsize,Ord(':'));
  3103. if (bufend<>-1) and (bufend<bufsize-1) and (buf[bufend+1]=Ord('F')) then
  3104. skipfun:=true;
  3105. end;
  3106. end;
  3107. end;
  3108. end;
  3109. if not skipstab then
  3110. begin
  3111. { Copy string in stabstr }
  3112. if hstab.strpos<>0 then
  3113. begin
  3114. currstabstrsec.Data.seek(hstab.strpos);
  3115. hstab.strpos:=mergedstabstrsec.Size;
  3116. repeat
  3117. bufsize:=currstabstrsec.Data.read(buf,sizeof(buf));
  3118. bufend:=indexbyte(buf,bufsize,0);
  3119. if bufend=-1 then
  3120. bufend:=bufsize
  3121. else
  3122. begin
  3123. { include the #0 }
  3124. inc(bufend);
  3125. end;
  3126. mergedstabstrsec.write(buf,bufend);
  3127. until (buf[bufend-1]=0) or (bufsize<sizeof(buf));
  3128. end;
  3129. { Copy and Update the relocation }
  3130. if assigned(hstabreloc) then
  3131. begin
  3132. hstabreloc.Dataoffset:=mergestabcnt*sizeof(TObjStabEntry)+stabRelocofs;
  3133. { Remove from List without freeing the object }
  3134. currstabsec.ObjRelocations.List[currstabrelocidx-1]:=nil;
  3135. mergedstabsec.ObjRelocations.Add(hstabreloc);
  3136. end;
  3137. { Write updated stab }
  3138. MaybeSwapStab(hstab);
  3139. mergedstabsec.write(hstab,sizeof(hstab));
  3140. inc(mergestabcnt);
  3141. end;
  3142. end;
  3143. end;
  3144. { Unload stabs }
  3145. if assigned(currstabstrsec) then
  3146. begin
  3147. currstabstrsec.Used:=False;
  3148. currstabstrsec.ReleaseData;
  3149. end;
  3150. currstabsec.Used:=false;
  3151. currstabsec.ReleaseData;
  3152. end;
  3153. { Generate new HdrSym }
  3154. if mergedstabsec.Size>0 then
  3155. begin
  3156. hstab.strpos:=1;
  3157. hstab.ntype:=0;
  3158. hstab.nother:=0;
  3159. hstab.ndesc:=word(mergestabcnt-1);
  3160. hstab.nvalue:=mergedstabstrsec.Size;
  3161. MaybeSwapStab(hstab);
  3162. mergedstabsec.Data.seek(0);
  3163. mergedstabsec.Data.write(hstab,sizeof(hstab));
  3164. end;
  3165. { Replace all sections with our combined stabsec }
  3166. stabexesec.ObjSectionList.Clear;
  3167. stabstrexesec.ObjSectionList.Clear;
  3168. stabexesec.AddObjSection(mergedstabsec);
  3169. stabstrexesec.AddObjSection(mergedstabstrsec);
  3170. end;
  3171. procedure TExeOutput.MarkEmptySections;
  3172. var
  3173. i, j : longint;
  3174. exesec : TExeSection;
  3175. doremove : boolean;
  3176. begin
  3177. for i:=0 to ExeSectionList.Count-1 do
  3178. begin
  3179. exesec:=TExeSection(ExeSectionList[i]);
  3180. doremove:=not(oso_keep in exesec.SecOptions) and
  3181. (
  3182. (exesec.ObjSectionlist.count=0) or
  3183. (
  3184. (cs_link_strip in current_settings.globalswitches) and
  3185. not(cs_link_separate_dbg_file in current_settings.globalswitches) and
  3186. (oso_debug in exesec.SecOptions)
  3187. )
  3188. );
  3189. if not doremove then
  3190. begin
  3191. { Check if section has no actual data }
  3192. doremove:=true;
  3193. for j:=0 to exesec.ObjSectionList.Count-1 do
  3194. if TObjSection(exesec.ObjSectionList[j]).Size<>0 then
  3195. begin
  3196. doremove:=false;
  3197. break;
  3198. end;
  3199. end;
  3200. if doremove then
  3201. begin
  3202. Comment(V_Debug,'Disabling empty section '+exesec.name);
  3203. exesec.Disabled:=true;
  3204. end;
  3205. end;
  3206. end;
  3207. procedure TExeOutput.RemoveDisabledSections;
  3208. var
  3209. i: longint;
  3210. exesec: TExeSection;
  3211. begin
  3212. for i:=0 to ExeSectionList.Count-1 do
  3213. begin
  3214. exesec:=TExeSection(ExeSectionList[i]);
  3215. if exesec.Disabled then
  3216. ExeSectionList[i]:=nil;
  3217. end;
  3218. ExeSectionList.Pack;
  3219. end;
  3220. procedure TExeOutput.RemoveDebugInfo;
  3221. var
  3222. i : longint;
  3223. exesec : TExeSection;
  3224. begin
  3225. for i:=0 to ExeSectionList.Count-1 do
  3226. begin
  3227. exesec:=TExeSection(ExeSectionList[i]);
  3228. if (oso_debug in exesec.SecOptions) then
  3229. ExeSectionList[i]:=nil;
  3230. end;
  3231. ExeSectionList.Pack;
  3232. end;
  3233. procedure TExeOutput.RemoveUnreferencedSections;
  3234. var
  3235. ObjSectionWorkList : TFPObjectList;
  3236. procedure AddToObjSectionWorkList(aobjsec:TObjSection);
  3237. begin
  3238. if not aobjsec.Used then
  3239. begin
  3240. aobjsec.Used:=true;
  3241. ObjSectionWorkList.Add(aobjsec);
  3242. end;
  3243. end;
  3244. procedure DoReloc(objreloc:TObjRelocation);
  3245. var
  3246. objsym : TObjSymbol;
  3247. refobjsec : TObjSection;
  3248. refgrp : TObjSectionGroup;
  3249. begin
  3250. { Disabled Relocation to 0 }
  3251. if (objreloc.flags and rf_nosymbol)<>0 then
  3252. exit;
  3253. refobjsec:=nil;
  3254. refgrp:=nil;
  3255. if assigned(objreloc.symbol) then
  3256. begin
  3257. objsym:=objreloc.symbol;
  3258. if objsym.bind<>AB_LOCAL then
  3259. begin
  3260. if not assigned(objsym.exesymbol) then
  3261. internalerror(200603063);
  3262. objsym.exesymbol.used:=true;
  3263. objsym:=objsym.exesymbol.objsymbol;
  3264. end;
  3265. if not assigned(objsym.objsection) then
  3266. exit
  3267. else
  3268. refobjsec:=objsym.objsection;
  3269. end
  3270. else if assigned(objreloc.objsection) then
  3271. refobjsec:=objreloc.objsection
  3272. else if assigned(objreloc.group) then
  3273. refgrp:=objreloc.group
  3274. else
  3275. internalerror(200603316);
  3276. if assigned(exemap) then
  3277. begin
  3278. objsym:=objreloc.symbol;
  3279. if assigned(objsym) and (objsym.typ<>AT_SECTION) then
  3280. exemap.Add(' References '+objsym.name+' in '
  3281. +refobjsec.fullname)
  3282. else if assigned(refobjsec) then
  3283. exemap.Add(' References '+refobjsec.fullname)
  3284. else if assigned(refgrp) then
  3285. exemap.Add(' References '+refgrp.Name)
  3286. else
  3287. internalerror(2006033111);
  3288. end;
  3289. if assigned(refobjsec) then
  3290. AddToObjSectionWorkList(refobjsec);
  3291. end;
  3292. procedure DoVTableRef(vtable:TExeVTable;VTableIdx:longint);
  3293. var
  3294. i : longint;
  3295. objreloc : TObjRelocation;
  3296. begin
  3297. objreloc:=vtable.VTableRef(VTableIdx);
  3298. if assigned(objreloc) then
  3299. begin
  3300. { Process the relocation now if the ObjSection is
  3301. already processed and marked as used. Otherwise we leave it
  3302. unprocessed. It'll then be resolved when the ObjSection is
  3303. changed to Used }
  3304. if vtable.ExeSymbol.ObjSymbol.ObjSection.Used then
  3305. DoReloc(objreloc);
  3306. end;
  3307. { This recursive walking is done here instead of
  3308. in TExeVTable.VTableRef because we can now process
  3309. all needed relocations }
  3310. for i:=0 to vtable.ChildList.Count-1 do
  3311. DoVTableRef(TExeVTable(vtable.ChildList[i]),VTableIdx);
  3312. end;
  3313. procedure ProcessWorkList;
  3314. var
  3315. hs : string;
  3316. i,k : longint;
  3317. objsec : TObjSection;
  3318. objsym : TObjSymbol;
  3319. code : integer;
  3320. vtableidx : longint;
  3321. vtableexesym : TExeSymbol;
  3322. begin
  3323. while ObjSectionWorkList.Count>0 do
  3324. begin
  3325. objsec:=TObjSection(ObjSectionWorkList.Last);
  3326. if not assigned(objsec.exesection) then
  3327. internalerror(202102001);
  3328. if assigned(exemap) then
  3329. exemap.Add('Keeping '+objsec.FullName+' '+ToStr(objsec.ObjRelocations.Count)+' references');
  3330. ObjSectionWorkList.Delete(ObjSectionWorkList.Count-1);
  3331. { Process Relocations }
  3332. for i:=0 to objsec.ObjRelocations.count-1 do
  3333. DoReloc(TObjRelocation(objsec.ObjRelocations[i]));
  3334. { Process Virtual Entry calls }
  3335. if cs_link_opt_vtable in current_settings.globalswitches then
  3336. begin
  3337. for i:=0 to objsec.VTRefList.count-1 do
  3338. begin
  3339. objsym:=TObjSymbol(objsec.VTRefList[i]);
  3340. hs:=objsym.name;
  3341. Delete(hs,1,Pos('_',hs));
  3342. k:=Pos('$$',hs);
  3343. if k=0 then
  3344. internalerror(200603314);
  3345. vtableexesym:=texesymbol(FExeSymbolList.Find(Copy(hs,1,k-1)));
  3346. val(Copy(hs,k+2,length(hs)-k-1),vtableidx,code);
  3347. if (code<>0) then
  3348. internalerror(200603317);
  3349. if not assigned(vtableexesym) then
  3350. internalerror(200603315);
  3351. if not assigned(vtableexesym.vtable) then
  3352. internalerror(2006033112);
  3353. DoVTableRef(vtableexesym.vtable,vtableidx);
  3354. end;
  3355. end;
  3356. end;
  3357. end;
  3358. var
  3359. i,j : longint;
  3360. exesec : TExeSection;
  3361. objdata : TObjData;
  3362. objsec : TObjSection;
  3363. begin
  3364. ObjSectionWorkList:=TFPObjectList.Create(false);
  3365. if assigned(exemap) then
  3366. exemap.AddHeader('Removing unreferenced sections');
  3367. { Initialize by marking all sections unused and
  3368. adding the sections with oso_keep flags to the ObjSectionWorkList }
  3369. for i:=0 to ObjDataList.Count-1 do
  3370. begin
  3371. ObjData:=TObjData(ObjDataList[i]);
  3372. for j:=0 to ObjData.ObjSectionList.Count-1 do
  3373. begin
  3374. objsec:=TObjSection(ObjData.ObjSectionList[j]);
  3375. objsec.Used:=false;
  3376. { TODO: remove debug section always keep}
  3377. if oso_debug in objsec.secoptions then
  3378. objsec.Used:=true;
  3379. if (oso_keep in objsec.secoptions) then
  3380. begin
  3381. AddToObjSectionWorkList(objsec);
  3382. if objsec.name='.fpc.n_links' then
  3383. objsec.Used:=false;
  3384. end;
  3385. end;
  3386. end;
  3387. if assigned(entrysym) then
  3388. AddToObjSectionWorkList(entrysym.exesymbol.objsymbol.objsection);
  3389. { Process all sections, add new sections to process based
  3390. on the symbol references }
  3391. ProcessWorkList;
  3392. { Handle stuff like .pdata, i.e. sections that are not referenced
  3393. but must be included if sections they reference are included.
  3394. Loop is necessary because .pdata can reference (via .xdata)
  3395. more text sections, VMTs of exception classes, etc. }
  3396. repeat
  3397. MarkTargetSpecificSections(ObjSectionWorkList);
  3398. if (ObjSectionWorkList.Count=0) then
  3399. break;
  3400. ProcessWorkList;
  3401. until False;
  3402. ObjSectionWorkList.Free;
  3403. ObjSectionWorkList:=nil;
  3404. { Remove unused objsections from ExeSectionList }
  3405. for i:=0 to ExeSectionList.Count-1 do
  3406. begin
  3407. exesec:=TExeSection(ExeSectionList[i]);
  3408. for j:=0 to exesec.ObjSectionlist.count-1 do
  3409. begin
  3410. objsec:=TObjSection(exesec.ObjSectionlist[j]);
  3411. if not objsec.used then
  3412. begin
  3413. if assigned(exemap) then
  3414. exemap.Add('Removing '+objsec.FullName);
  3415. exesec.ObjSectionlist[j]:=nil;
  3416. objsec.ReleaseData;
  3417. end;
  3418. end;
  3419. exesec.ObjSectionlist.Pack;
  3420. end;
  3421. end;
  3422. procedure TExeOutput.FixupRelocations;
  3423. var
  3424. i,j : longint;
  3425. exesec : TExeSection;
  3426. objsec : TObjSection;
  3427. begin
  3428. for i:=0 to ExeSectionList.Count-1 do
  3429. begin
  3430. exesec:=TExeSection(ExeSectionList[i]);
  3431. if not assigned(exesec) then
  3432. continue;
  3433. for j:=0 to exesec.ObjSectionlist.count-1 do
  3434. begin
  3435. objsec:=TObjSection(exesec.ObjSectionlist[j]);
  3436. if not objsec.Used then
  3437. internalerror(200603301);
  3438. if (objsec.ObjRelocations.Count>0) and
  3439. not assigned(objsec.data) then
  3440. internalerror(2002051801);
  3441. DoRelocationFixup(objsec);
  3442. {for size = 0 data is not valid PM }
  3443. if assigned(objsec.data) and (objsec.data.size<>objsec.size) then
  3444. internalerror(2010092801);
  3445. end;
  3446. end;
  3447. end;
  3448. procedure TExeOutput.RemoveUnusedExeSymbols;
  3449. var
  3450. i : longint;
  3451. sym : TExeSymbol;
  3452. begin
  3453. { Removing unused symbols }
  3454. for i:=0 to ExeSymbolList.Count-1 do
  3455. begin
  3456. sym:=TExeSymbol(ExeSymbolList[i]);
  3457. { an unresolved weak symbol has objsection=nil }
  3458. if assigned(sym.ObjSymbol.objsection) and
  3459. (not sym.ObjSymbol.objsection.Used) then
  3460. ExeSymbolList[i]:=nil;
  3461. end;
  3462. ExeSymbolList.Pack;
  3463. end;
  3464. procedure TExeOutput.SetCurrMemPos(const AValue: qword);
  3465. begin
  3466. if AValue>MaxMemPos then
  3467. Message1(link_f_executable_too_big, target_os_string);
  3468. FCurrMemPos:=AValue;
  3469. end;
  3470. procedure TExeOutput.WriteExeSectionContent;
  3471. var
  3472. exesec : TExeSection;
  3473. objsec : TObjSection;
  3474. i,j : longint;
  3475. dpos,pad: aword;
  3476. begin
  3477. for j:=0 to ExeSectionList.Count-1 do
  3478. begin
  3479. exesec:=TExeSection(ExeSectionList[j]);
  3480. { don't write normal section if writing only debug info }
  3481. if (ExeWriteMode=ewm_dbgonly) and
  3482. (exesec.SecOptions*[oso_debug,oso_debug_copy]=[]) then
  3483. continue;
  3484. if oso_data in exesec.SecOptions then
  3485. begin
  3486. if exesec.DataPos<FWriter.Size then
  3487. InternalError(2012103002);
  3488. FWriter.Writezeros(exesec.DataPos-FWriter.Size);
  3489. for i:=0 to exesec.ObjSectionList.Count-1 do
  3490. begin
  3491. objsec:=TObjSection(exesec.ObjSectionList[i]);
  3492. if oso_data in objsec.secoptions then
  3493. begin
  3494. if not assigned(objsec.data) then
  3495. internalerror(2006030404);
  3496. dpos:=objsec.MemPos-exesec.MemPos+exesec.DataPos;
  3497. pad:=dpos-FWriter.Size;
  3498. { objsection must be within SecAlign bytes from the previous one }
  3499. if (dpos<FWriter.Size) or
  3500. (pad>=max(objsec.SecAlign,1)) then
  3501. internalerror(2006022503);
  3502. FWriter.writeZeros(pad);
  3503. FWriter.writearray(objsec.data);
  3504. end;
  3505. end;
  3506. end;
  3507. end;
  3508. end;
  3509. procedure TExeOutput.ReplaceExeSectionList(newlist: TFPList);
  3510. var
  3511. tmp: TFPHashObjectList;
  3512. i: longint;
  3513. begin
  3514. tmp:=TFPHashObjectList.Create(true);
  3515. for i:=0 to newlist.count-1 do
  3516. TFPHashObject(newlist[i]).ChangeOwner(tmp);
  3517. { prevent destruction of existing sections }
  3518. for i:=0 to ExeSectionList.count-1 do
  3519. ExeSectionList.List[i]:=nil;
  3520. FExeSectionList.Free;
  3521. FExeSectionList:=tmp;
  3522. end;
  3523. {****************************************************************************
  3524. TObjInput
  3525. ****************************************************************************}
  3526. constructor TObjInput.create;
  3527. begin
  3528. end;
  3529. procedure TObjInput.inputerror(const s : string);
  3530. begin
  3531. Comment(V_Error,s+' while reading '+InputFileName);
  3532. end;
  3533. class function TObjInput.CanReadObjData(AReader:TObjectReader):boolean;
  3534. begin
  3535. result:=false;
  3536. end;
  3537. procedure TObjInput.ReadSectionContent(Data:TObjData);
  3538. var
  3539. i: longint;
  3540. sec: TObjSection;
  3541. begin
  3542. for i:=0 to Data.ObjSectionList.Count-1 do
  3543. begin
  3544. sec:=TObjSection(Data.ObjSectionList[i]);
  3545. { Skip debug sections }
  3546. if (oso_debug in sec.SecOptions) and
  3547. (cs_link_strip in current_settings.globalswitches) and
  3548. not(cs_link_separate_dbg_file in current_settings.globalswitches) then
  3549. continue;
  3550. if assigned(sec.Data) then
  3551. begin
  3552. FReader.Seek(sec.datapos);
  3553. if not FReader.ReadArray(sec.data,sec.Size) then
  3554. begin
  3555. InputError('Can''t read object data');
  3556. exit;
  3557. end;
  3558. end;
  3559. end;
  3560. end;
  3561. {$ifdef MEMDEBUG}
  3562. initialization
  3563. memobjsymbols:=TMemDebug.create('ObjSymbols');
  3564. memobjsymbols.stop;
  3565. memobjsections:=TMemDebug.create('ObjSections');
  3566. memobjsections.stop;
  3567. finalization
  3568. memobjsymbols.free;
  3569. memobjsections.free;
  3570. {$endif MEMDEBUG}
  3571. end.