ogbase.pas 116 KB

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