ogbase.pas 131 KB

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