ogbase.pas 137 KB

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