ogbase.pas 117 KB

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