ogbase.pas 118 KB

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