ogbase.pas 120 KB

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