ogbase.pas 122 KB

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