ogbase.pas 115 KB

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