ogbase.pas 122 KB

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