ogbase.pas 122 KB

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