ogbase.pas 115 KB

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