ogbase.pas 94 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860
  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. TObjRelocationType = (
  36. { Relocation to absolute address }
  37. RELOC_ABSOLUTE,
  38. {$ifdef x86_64}
  39. { 32bit Relocation to absolute address }
  40. RELOC_ABSOLUTE32,
  41. { 64 bit coff only }
  42. RELOC_RELATIVE_1,
  43. RELOC_RELATIVE_2,
  44. RELOC_RELATIVE_3,
  45. RELOC_RELATIVE_4,
  46. RELOC_RELATIVE_5,
  47. { PIC }
  48. RELOC_GOTPCREL,
  49. RELOC_PLT32,
  50. {$endif x86_64}
  51. {$ifdef i386}
  52. { PIC }
  53. RELOC_GOTPC,
  54. RELOC_GOT32,
  55. RELOC_PLT32,
  56. {$endif i386}
  57. {$ifdef arm}
  58. RELOC_RELATIVE_24,
  59. {$endif arm}
  60. { Relative relocation }
  61. RELOC_RELATIVE,
  62. { PECoff (Windows) RVA relocation }
  63. RELOC_RVA,
  64. { PECoff (Windows) section relocation, required by DWARF2 debug info }
  65. RELOC_SECREL32,
  66. { Generate a 0 value at the place of the relocation,
  67. this is used to remove unused vtable entries }
  68. RELOC_ZERO,
  69. { No relocation is needed. It is used in ARM object files.
  70. Also internal linker use this reloc to make virtual (not real)
  71. links to some sections }
  72. RELOC_NONE,
  73. { Darwin relocation, using PAIR }
  74. RELOC_PIC_PAIR
  75. );
  76. {$ifndef x86_64}
  77. const
  78. RELOC_ABSOLUTE32 = RELOC_ABSOLUTE;
  79. {$endif x86_64}
  80. const
  81. { stab types }
  82. N_GSYM = $20;
  83. N_STSYM = 38; { initialized const }
  84. N_LCSYM = 40; { non initialized variable}
  85. N_Function = $24; { function or const }
  86. N_TextLine = $44;
  87. N_DataLine = $46;
  88. N_BssLine = $48;
  89. N_RSYM = $40; { register variable }
  90. N_LSYM = $80;
  91. N_tsym = 160;
  92. N_SourceFile = $64;
  93. N_IncludeFile = $84;
  94. N_BINCL = $82;
  95. N_EINCL = $A2;
  96. N_LBRAC = $C0;
  97. N_EXCL = $C2;
  98. N_RBRAC = $E0;
  99. { GNU extensions }
  100. debuglinkname='.gnu_debuglink';
  101. type
  102. TObjSectionOption = (
  103. { Has Data available in the file }
  104. oso_Data,
  105. { Is loaded into memory }
  106. oso_load,
  107. { Not loaded into memory }
  108. oso_noload,
  109. { Read only }
  110. oso_readonly,
  111. { Read/Write }
  112. oso_write,
  113. { Contains executable instructions }
  114. oso_executable,
  115. { Never discard section }
  116. oso_keep,
  117. { Special common symbols }
  118. oso_common,
  119. { Contains debug info and can be stripped }
  120. oso_debug,
  121. { Contains only strings }
  122. oso_strings
  123. );
  124. TObjSectionOptions = set of TObjSectionOption;
  125. TObjSymbol = class(TFPHashObject)
  126. public
  127. bind : TAsmsymbind;
  128. typ : TAsmsymtype;
  129. { Current assemble pass, used to detect duplicate labels }
  130. pass : byte;
  131. objsection : TObjSection;
  132. symidx : longint;
  133. offset,
  134. size : aword;
  135. { Used for external and common solving during linking }
  136. exesymbol : TExeSymbol;
  137. { Darwin asm is using indirect symbols resolving }
  138. indsymbol : TObjSymbol;
  139. constructor create(AList:TFPHashObjectList;const AName:string);
  140. function address:aword;
  141. procedure SetAddress(apass:byte;aobjsec:TObjSection;abind:TAsmsymbind;atyp:Tasmsymtype);
  142. end;
  143. { Stabs is common for all targets }
  144. TObjStabEntry=packed record
  145. strpos : longint;
  146. ntype : byte;
  147. nother : byte;
  148. ndesc : word;
  149. nvalue : longint;
  150. end;
  151. PObjStabEntry=^TObjStabEntry;
  152. TObjRelocation = class
  153. DataOffset,
  154. orgsize : aword; { original size of the symbol to Relocate, required for COFF }
  155. symbol : TObjSymbol;
  156. objsection : TObjSection; { only used if symbol=nil }
  157. typ : TObjRelocationType;
  158. constructor CreateSymbol(ADataOffset:aword;s:TObjSymbol;Atyp:TObjRelocationType);
  159. constructor CreateSymbolSize(ADataOffset:aword;s:TObjSymbol;Aorgsize:aword;Atyp:TObjRelocationType);
  160. constructor CreateSection(ADataOffset:aword;aobjsec:TObjSection;Atyp:TObjRelocationType);
  161. end;
  162. TObjSection = class(TFPHashObject)
  163. private
  164. FData : TDynamicArray;
  165. FSecOptions : TObjSectionOptions;
  166. FCachedFullName : pshortstring;
  167. procedure SetSecOptions(Aoptions:TObjSectionOptions);
  168. public
  169. ObjData : TObjData;
  170. SecSymIdx : longint; { index for the section in symtab }
  171. SecAlign : shortint; { alignment of the section }
  172. { section Data }
  173. Size,
  174. DataPos,
  175. MemPos : aword;
  176. DataAlignBytes : shortint;
  177. { Relocations (=references) to other sections }
  178. ObjRelocations : TFPObjectList;
  179. { Symbols this defines }
  180. ObjSymbolDefines : TFPObjectList;
  181. { executable linking }
  182. ExeSection : TExeSection;
  183. USed : Boolean;
  184. VTRefList : TFPObjectList;
  185. constructor create(AList:TFPHashObjectList;const Aname:string;Aalign:shortint;Aoptions:TObjSectionOptions);virtual;
  186. destructor destroy;override;
  187. function write(const d;l:aword):aword;
  188. function writestr(const s:string):aword;
  189. function WriteZeros(l:longword):aword;
  190. function setmempos(mpos:qword):qword;
  191. procedure setDatapos(var dpos:aword);
  192. procedure alloc(l:aword);
  193. procedure addsymReloc(ofs:aword;p:TObjSymbol;Reloctype:TObjRelocationType);
  194. procedure addsectionReloc(ofs:aword;aobjsec:TObjSection;Reloctype:TObjRelocationType);
  195. procedure AddSymbolDefine(p:TObjSymbol);
  196. procedure FixupRelocs;virtual;
  197. procedure ReleaseData;
  198. function FullName:string;
  199. property Data:TDynamicArray read FData;
  200. property SecOptions:TObjSectionOptions read FSecOptions write SetSecOptions;
  201. end;
  202. TObjSectionClass = class of TObjSection;
  203. TString80 = string[80];
  204. TObjData = class(TLinkedListItem)
  205. private
  206. FName : TString80;
  207. FCurrObjSec : TObjSection;
  208. FObjSectionList : TFPHashObjectList;
  209. FCObjSection : TObjSectionClass;
  210. { Symbols that will be defined in this object file }
  211. FObjSymbolList : TFPHashObjectList;
  212. FCachedAsmSymbolList : TFPObjectList;
  213. { Special info sections that are written to during object generation }
  214. FStabsObjSec,
  215. FStabStrObjSec : TObjSection;
  216. procedure section_reset(p:TObject;arg:pointer);
  217. procedure section_afteralloc(p:TObject;arg:pointer);
  218. procedure section_afterwrite(p:TObject;arg:pointer);
  219. protected
  220. property CObjSection:TObjSectionClass read FCObjSection write FCObjSection;
  221. public
  222. CurrPass : byte;
  223. ImageBase : aword;
  224. constructor create(const n:string);virtual;
  225. destructor destroy;override;
  226. { Sections }
  227. function sectionname(atype:TAsmSectiontype;const aname:string;aorder:TAsmSectionOrder):string;virtual;
  228. function sectiontype2options(atype:TAsmSectiontype):TObjSectionOptions;virtual;
  229. function sectiontype2align(atype:TAsmSectiontype):shortint;virtual;
  230. function createsection(atype:TAsmSectionType;const aname:string='';aorder:TAsmSectionOrder=secorder_default):TObjSection;
  231. function createsection(const aname:string;aalign:shortint;aoptions:TObjSectionOptions;DiscardDuplicate:boolean=true):TObjSection;virtual;
  232. procedure CreateDebugSections;virtual;
  233. function findsection(const aname:string):TObjSection;
  234. procedure setsection(asec:TObjSection);
  235. { Symbols }
  236. function createsymbol(const aname:string):TObjSymbol;
  237. function symboldefine(asmsym:TAsmSymbol):TObjSymbol;
  238. function symboldefine(const aname:string;abind:TAsmsymbind;atyp:Tasmsymtype):TObjSymbol;
  239. function symbolref(asmsym:TAsmSymbol):TObjSymbol;
  240. function symbolref(const aname:string):TObjSymbol;
  241. procedure ResetCachedAsmSymbols;
  242. { Allocation }
  243. procedure alloc(len:aword);
  244. procedure allocalign(len:shortint);
  245. procedure writebytes(const Data;len:aword);
  246. procedure writeReloc(Data:aint;len:aword;p:TObjSymbol;Reloctype:TObjRelocationType);virtual;abstract;
  247. procedure beforealloc;virtual;
  248. procedure beforewrite;virtual;
  249. procedure afteralloc;virtual;
  250. procedure afterwrite;virtual;
  251. procedure resetsections;
  252. property Name:TString80 read FName;
  253. property CurrObjSec:TObjSection read FCurrObjSec;
  254. property ObjSymbolList:TFPHashObjectList read FObjSymbolList;
  255. property ObjSectionList:TFPHashObjectList read FObjSectionList;
  256. property StabsSec:TObjSection read FStabsObjSec write FStabsObjSec;
  257. property StabStrSec:TObjSection read FStabStrObjSec write FStabStrObjSec;
  258. end;
  259. TObjDataClass = class of TObjData;
  260. TObjOutput = class
  261. private
  262. FCObjData : TObjDataClass;
  263. protected
  264. { writer }
  265. FWriter : TObjectwriter;
  266. function writeData(Data:TObjData):boolean;virtual;abstract;
  267. property CObjData : TObjDataClass read FCObjData write FCObjData;
  268. public
  269. constructor create(AWriter:TObjectWriter);virtual;
  270. destructor destroy;override;
  271. function newObjData(const n:string):TObjData;
  272. function startObjectfile(const fn:string):boolean;
  273. function writeobjectfile(Data:TObjData):boolean;
  274. procedure exportsymbol(p:TObjSymbol);
  275. property Writer:TObjectWriter read FWriter;
  276. end;
  277. TObjOutputClass=class of TObjOutput;
  278. TObjInput = class
  279. private
  280. FCObjData : TObjDataClass;
  281. protected
  282. { reader }
  283. FReader : TObjectReader;
  284. InputFileName : string;
  285. property CObjData : TObjDataClass read FCObjData write FCObjData;
  286. public
  287. constructor create;virtual;
  288. destructor destroy;override;
  289. function newObjData(const n:string):TObjData;
  290. function ReadObjData(AReader:TObjectreader;Data:TObjData):boolean;virtual;abstract;
  291. procedure inputerror(const s : string);
  292. end;
  293. TObjInputClass=class of TObjInput;
  294. TVTableEntry=record
  295. ObjRelocation : TObjRelocation;
  296. orgreloctype : TObjRelocationType;
  297. Enabled,
  298. Used : Boolean;
  299. end;
  300. PVTableEntry=^TVTableEntry;
  301. TExeVTable = class
  302. private
  303. procedure CheckIdx(VTableIdx:longint);
  304. public
  305. ExeSymbol : TExeSymbol;
  306. EntryCnt : Longint;
  307. EntryArray : PVTableEntry;
  308. Consolidated : Boolean;
  309. ChildList : TFPObjectList;
  310. constructor Create(AExeSymbol:TExeSymbol);
  311. destructor Destroy;override;
  312. procedure AddChild(vt:TExeVTable);
  313. procedure AddEntry(VTableIdx:Longint);
  314. procedure SetVTableSize(ASize:longint);
  315. function VTableRef(VTableIdx:Longint):TObjRelocation;
  316. end;
  317. TSymbolState = (symstate_undefined,symstate_defined,symstate_common);
  318. TExeSymbol = class(TFPHashObject)
  319. ObjSymbol : TObjSymbol;
  320. ExeSection : TExeSection;
  321. State : TSymbolState;
  322. { Used for vmt references optimization }
  323. VTable : TExeVTable;
  324. end;
  325. TExeSection = class(TFPHashObject)
  326. private
  327. FSecSymIdx : longint;
  328. FObjSectionList : TFPObjectList;
  329. public
  330. Size,
  331. DataPos,
  332. MemPos : aword;
  333. SecAlign : shortint;
  334. SecOptions : TObjSectionOptions;
  335. constructor create(AList:TFPHashObjectList;const AName:string);virtual;
  336. destructor destroy;override;
  337. procedure AddObjSection(objsec:TObjSection);
  338. property ObjSectionList:TFPObjectList read FObjSectionList;
  339. property SecSymIdx:longint read FSecSymIdx write FSecSymIdx;
  340. end;
  341. TExeSectionClass=class of TExeSection;
  342. TStaticLibrary = class(TFPHashObject)
  343. private
  344. FArReader : TObjectReader;
  345. FObjInputClass : TObjInputClass;
  346. public
  347. constructor create(AList:TFPHashObjectList;const AName:string;AReader:TObjectReader;AObjInputClass:TObjInputClass);
  348. destructor destroy;override;
  349. property ArReader:TObjectReader read FArReader;
  350. property ObjInputClass:TObjInputClass read FObjInputClass;
  351. end;
  352. TImportLibrary = class(TFPHashObject)
  353. private
  354. FImportSymbolList : TFPHashObjectList;
  355. public
  356. constructor create(AList:TFPHashObjectList;const AName:string);
  357. destructor destroy;override;
  358. property ImportSymbolList:TFPHashObjectList read FImportSymbolList;
  359. end;
  360. TImportSymbol = class(TFPHashObject)
  361. private
  362. FOrdNr : longint;
  363. FIsVar : boolean;
  364. FMangledName : string;
  365. public
  366. constructor create(AList:TFPHashObjectList;const AName,AMangledName:string;AOrdNr:longint;AIsVar:boolean);
  367. property OrdNr: longint read FOrdNr;
  368. property MangledName: string read FMangledName;
  369. property IsVar: boolean read FIsVar;
  370. end;
  371. TExeWriteMode = (ewm_exefull,ewm_dbgonly,ewm_exeonly);
  372. TExeOutput = class
  373. private
  374. { ExeSectionList }
  375. FCObjData : TObjDataClass;
  376. FCExeSection : TExeSectionClass;
  377. FCurrExeSec : TExeSection;
  378. FExeSectionList : TFPHashObjectList;
  379. Fzeronr : longint;
  380. Fvaluesnr : longint;
  381. { Symbols }
  382. FExeSymbolList : TFPHashObjectList;
  383. FUnresolvedExeSymbols : TFPObjectList;
  384. FExternalObjSymbols,
  385. FCommonObjSymbols : TFPObjectList;
  386. FEntryName : string;
  387. FExeVTableList : TFPObjectList;
  388. { Objects }
  389. FObjDataList : TFPObjectList;
  390. { Position calculation }
  391. FImageBase : aword;
  392. FCurrMemPos : qword;
  393. procedure SetCurrMemPos(const AValue: qword);
  394. protected
  395. { writer }
  396. FExeWriteMode : TExeWriteMode;
  397. FWriter : TObjectwriter;
  398. commonObjSection : TObjSection;
  399. internalObjData : TObjData;
  400. EntrySym : TObjSymbol;
  401. SectionDataAlign,
  402. SectionMemAlign : aword;
  403. function writeData:boolean;virtual;abstract;
  404. property CExeSection:TExeSectionClass read FCExeSection write FCExeSection;
  405. property CObjData:TObjDataClass read FCObjData write FCObjData;
  406. procedure Order_ObjSectionList(ObjSectionList : TFPObjectList; const aPattern:string);virtual;
  407. public
  408. CurrDataPos : aword;
  409. MaxMemPos : qword;
  410. IsSharedLibrary : boolean;
  411. constructor create;virtual;
  412. destructor destroy;override;
  413. function FindExeSection(const aname:string):TExeSection;
  414. procedure AddObjData(ObjData:TObjData);
  415. procedure Load_Start;virtual;
  416. procedure Load_EntryName(const aname:string);virtual;
  417. procedure Load_Symbol(const aname:string);virtual;
  418. procedure Load_ProvideSymbol(const aname:string);virtual;
  419. procedure Load_IsSharedLibrary;
  420. procedure Load_ImageBase(const avalue:string);
  421. procedure Order_Start;virtual;
  422. procedure Order_End;virtual;
  423. procedure Order_ExeSection(const aname:string);virtual;
  424. procedure Order_Align(const avalue:string);virtual;
  425. procedure Order_Zeros(const avalue:string);virtual;
  426. procedure Order_Values(bytesize : aword; const avalue:string);virtual;
  427. procedure Order_Symbol(const aname:string);virtual;
  428. procedure Order_ProvideSymbol(const aname:string);virtual;
  429. procedure Order_EndExeSection;virtual;
  430. procedure Order_ObjSection(const aname:string);virtual;
  431. procedure MemPos_Start;virtual;
  432. procedure MemPos_Header;virtual;
  433. procedure MemPos_ExeSection(const aname:string);virtual;
  434. procedure MemPos_EndExeSection;virtual;
  435. procedure DataPos_Start;virtual;
  436. procedure DataPos_Header;virtual;
  437. procedure DataPos_ExeSection(const aname:string);virtual;
  438. procedure DataPos_EndExeSection;virtual;
  439. procedure DataPos_Symbols;virtual;
  440. procedure BuildVTableTree(VTInheritList,VTEntryList:TFPObjectList);
  441. procedure PackUnresolvedExeSymbols(const s:string);
  442. procedure ResolveSymbols(StaticLibraryList:TFPHashObjectList);
  443. procedure PrintMemoryMap;
  444. procedure FixupSymbols;
  445. procedure FixupRelocations;
  446. procedure MergeStabs;
  447. procedure RemoveUnreferencedSections;
  448. procedure RemoveEmptySections;
  449. procedure RemoveDebugInfo;
  450. procedure GenerateLibraryImports(ImportLibraryList:TFPHashObjectList);virtual;
  451. procedure GenerateDebugLink(const dbgname:string;dbgcrc:cardinal);
  452. function WriteExeFile(const fn:string):boolean;
  453. procedure ParseScript (linkscript:TCmdStrList); virtual;
  454. property Writer:TObjectWriter read FWriter;
  455. property ExeSectionList:TFPHashObjectList read FExeSectionList;
  456. property ObjDataList:TFPObjectList read FObjDataList;
  457. property ExeSymbolList:TFPHashObjectList read FExeSymbolList;
  458. property UnresolvedExeSymbols:TFPObjectList read FUnresolvedExeSymbols;
  459. property ExternalObjSymbols:TFPObjectList read FExternalObjSymbols;
  460. property CommonObjSymbols:TFPObjectList read FCommonObjSymbols;
  461. property ExeVTableList:TFPObjectList read FExeVTableList;
  462. property EntryName:string read FEntryName write FEntryName;
  463. property ImageBase:aword read FImageBase write FImageBase;
  464. property CurrExeSec:TExeSection read FCurrExeSec;
  465. property ExeWriteMode:TExeWriteMode read FExeWriteMode write FExeWriteMode;
  466. property CurrMemPos:qword read FCurrMemPos write SetCurrMemPos;
  467. end;
  468. TExeOutputClass=class of TExeOutput;
  469. var
  470. exeoutput : TExeOutput;
  471. implementation
  472. uses
  473. SysUtils,
  474. globals,verbose,fmodule,ogmap;
  475. const
  476. SectionDataMaxGrow = 4096;
  477. {$ifdef MEMDEBUG}
  478. var
  479. memobjsymbols,
  480. memobjsections : TMemDebug;
  481. {$endif MEMDEBUG}
  482. {*****************************************************************************
  483. TObjSymbol
  484. *****************************************************************************}
  485. constructor TObjSymbol.create(AList:TFPHashObjectList;const AName:string);
  486. begin;
  487. inherited create(AList,AName);
  488. bind:=AB_EXTERNAL;
  489. typ:=AT_NONE;
  490. symidx:=-1;
  491. size:=0;
  492. offset:=0;
  493. objsection:=nil;
  494. end;
  495. function TObjSymbol.address:aword;
  496. begin
  497. if assigned(objsection) then
  498. result:=offset+objsection.mempos
  499. else
  500. result:=0;
  501. end;
  502. procedure TObjSymbol.SetAddress(apass:byte;aobjsec:TObjSection;abind:TAsmsymbind;atyp:Tasmsymtype);
  503. begin
  504. if not(abind in [AB_GLOBAL,AB_LOCAL,AB_COMMON,AB_IMPORT]) then
  505. internalerror(200603016);
  506. if not assigned(aobjsec) then
  507. internalerror(200603017);
  508. if (bind in [AB_EXTERNAL,AB_LAZY]) or
  509. { Put all COMMON to GLOBAL in step 3 of
  510. TExeOutput.ResolveSymbols }
  511. ((abind=AB_GLOBAL) and (bind=AB_COMMON)) then
  512. begin
  513. { Do not change the AB_TYPE of common symbols yet }
  514. { This will be done in FixupSymbols }
  515. if (pass<>0) or (bind<>AB_COMMON) then
  516. bind:=abind;
  517. typ:=atyp;
  518. end
  519. else
  520. begin
  521. if pass=apass then
  522. begin
  523. Message1(asmw_e_duplicate_label,name);
  524. exit;
  525. end;
  526. end;
  527. pass:=apass;
  528. { Code can never grow after a pass }
  529. if assigned(objsection) and
  530. (objsection=aobjsec) and
  531. (aobjsec.size>offset) then
  532. internalerror(200603014);
  533. objsection:=aobjsec;
  534. offset:=aobjsec.size;
  535. end;
  536. {****************************************************************************
  537. TObjRelocation
  538. ****************************************************************************}
  539. constructor TObjRelocation.CreateSymbol(ADataOffset:aword;s:TObjSymbol;Atyp:TObjRelocationType);
  540. begin
  541. if not assigned(s) then
  542. internalerror(200603034);
  543. DataOffset:=ADataOffset;
  544. Symbol:=s;
  545. OrgSize:=0;
  546. ObjSection:=nil;
  547. Typ:=Atyp;
  548. end;
  549. constructor TObjRelocation.CreateSymbolSize(ADataOffset:aword;s:TObjSymbol;Aorgsize:aword;Atyp:TObjRelocationType);
  550. begin
  551. if not assigned(s) then
  552. internalerror(200603035);
  553. DataOffset:=ADataOffset;
  554. Symbol:=s;
  555. OrgSize:=Aorgsize;
  556. ObjSection:=nil;
  557. Typ:=Atyp;
  558. end;
  559. constructor TObjRelocation.CreateSection(ADataOffset:aword;aobjsec:TObjSection;Atyp:TObjRelocationType);
  560. begin
  561. if not assigned(aobjsec) then
  562. internalerror(200603036);
  563. DataOffset:=ADataOffset;
  564. Symbol:=nil;
  565. OrgSize:=0;
  566. ObjSection:=aobjsec;
  567. Typ:=Atyp;
  568. end;
  569. {****************************************************************************
  570. TObjSection
  571. ****************************************************************************}
  572. constructor TObjSection.create(AList:TFPHashObjectList;const Aname:string;Aalign:shortint;Aoptions:TObjSectionOptions);
  573. begin
  574. inherited Create(AList,Aname);
  575. { Data }
  576. Size:=0;
  577. Datapos:=0;
  578. mempos:=0;
  579. FData:=Nil;
  580. { Setting the secoptions allocates Data if needed }
  581. secoptions:=Aoptions;
  582. secalign:=Aalign;
  583. secsymidx:=0;
  584. { relocation }
  585. ObjRelocations:=TFPObjectList.Create(true);
  586. ObjSymbolDefines:=TFPObjectList.Create(false);
  587. VTRefList:=TFPObjectList.Create(false);
  588. end;
  589. destructor TObjSection.destroy;
  590. begin
  591. if assigned(Data) then
  592. Data.Free;
  593. stringdispose(FCachedFullName);
  594. ObjRelocations.Free;
  595. ObjSymbolDefines.Free;
  596. VTRefList.Free;
  597. inherited destroy;
  598. end;
  599. procedure TObjSection.SetSecOptions(Aoptions:TObjSectionOptions);
  600. begin
  601. FSecOptions:=FSecOptions+AOptions;
  602. if (oso_Data in secoptions) and
  603. not assigned(FData) then
  604. FData:=TDynamicArray.Create(SectionDataMaxGrow);
  605. end;
  606. function TObjSection.write(const d;l:aword):aword;
  607. begin
  608. result:=size;
  609. if assigned(Data) then
  610. begin
  611. if Size<>Data.size then
  612. internalerror(200602281);
  613. Data.write(d,l);
  614. inc(Size,l);
  615. end
  616. else
  617. internalerror(200602289);
  618. end;
  619. function TObjSection.writestr(const s:string):aword;
  620. begin
  621. result:=Write(s[1],length(s));
  622. end;
  623. function TObjSection.WriteZeros(l:longword):aword;
  624. var
  625. empty : array[0..1023] of byte;
  626. begin
  627. if l>sizeof(empty) then
  628. internalerror(200404082);
  629. if l>0 then
  630. begin
  631. fillchar(empty,l,0);
  632. result:=Write(empty,l);
  633. end
  634. else
  635. result:=Size;
  636. end;
  637. procedure TObjSection.setDatapos(var dpos:aword);
  638. begin
  639. if oso_Data in secoptions then
  640. begin
  641. { get aligned Datapos }
  642. Datapos:=align(dpos,secalign);
  643. Dataalignbytes:=Datapos-dpos;
  644. { return updated Datapos }
  645. dpos:=Datapos+size;
  646. end
  647. else
  648. Datapos:=dpos;
  649. end;
  650. function TObjSection.setmempos(mpos:qword):qword;
  651. begin
  652. mempos:=align(mpos,secalign);
  653. { return updated mempos }
  654. result:=mempos+size;
  655. end;
  656. procedure TObjSection.alloc(l:aword);
  657. begin
  658. inc(size,l);
  659. end;
  660. procedure TObjSection.addsymReloc(ofs:aword;p:TObjSymbol;Reloctype:TObjRelocationType);
  661. begin
  662. ObjRelocations.Add(TObjRelocation.CreateSymbol(ofs,p,reloctype));
  663. end;
  664. procedure TObjSection.addsectionReloc(ofs:aword;aobjsec:TObjSection;Reloctype:TObjRelocationType);
  665. begin
  666. ObjRelocations.Add(TObjRelocation.CreateSection(ofs,aobjsec,reloctype));
  667. end;
  668. procedure TObjSection.AddSymbolDefine(p:TObjSymbol);
  669. begin
  670. if p.bind<>AB_GLOBAL then
  671. exit;
  672. ObjSymbolDefines.Add(p);
  673. end;
  674. procedure TObjSection.FixupRelocs;
  675. begin
  676. end;
  677. procedure TObjSection.ReleaseData;
  678. begin
  679. if assigned(FData) then
  680. begin
  681. FData.free;
  682. FData:=nil;
  683. end;
  684. ObjRelocations.free;
  685. ObjRelocations:=nil;
  686. ObjSymbolDefines.Free;
  687. ObjSymbolDefines:=nil;
  688. if assigned(FCachedFullName) then
  689. begin
  690. stringdispose(FCachedFullName);
  691. FCachedFullName:=nil;
  692. end;
  693. end;
  694. function TObjSection.FullName:string;
  695. begin
  696. if not assigned(FCachedFullName) then
  697. begin
  698. if assigned(ObjData) then
  699. FCachedFullName:=stringdup(ObjData.Name+'('+Name+')')
  700. else
  701. FCachedFullName:=stringdup(Name);
  702. end;
  703. result:=FCachedFullName^;
  704. end;
  705. {****************************************************************************
  706. TObjData
  707. ****************************************************************************}
  708. constructor TObjData.create(const n:string);
  709. begin
  710. inherited create;
  711. FName:=ExtractFileName(n);
  712. FObjSectionList:=TFPHashObjectList.Create(true);
  713. FStabsObjSec:=nil;
  714. FStabStrObjSec:=nil;
  715. { symbols }
  716. FObjSymbolList:=TFPHashObjectList.Create(true);
  717. FCachedAsmSymbolList:=TFPObjectList.Create(false);
  718. { section class type for creating of new sections }
  719. FCObjSection:=TObjSection;
  720. end;
  721. destructor TObjData.destroy;
  722. begin
  723. { Symbols }
  724. {$ifdef MEMDEBUG}
  725. MemObjSymbols.Start;
  726. {$endif}
  727. ResetCachedAsmSymbols;
  728. FCachedAsmSymbolList.free;
  729. FObjSymbolList.free;
  730. {$ifdef MEMDEBUG}
  731. MemObjSymbols.Stop;
  732. {$endif}
  733. { Sections }
  734. {$ifdef MEMDEBUG}
  735. MemObjSections.Start;
  736. {$endif}
  737. FObjSectionList.free;
  738. {$ifdef MEMDEBUG}
  739. MemObjSections.Stop;
  740. {$endif}
  741. inherited destroy;
  742. end;
  743. function TObjData.sectionname(atype:TAsmSectiontype;const aname:string;aorder:TAsmSectionOrder):string;
  744. const
  745. secnames : array[TAsmSectiontype] of string[length('__DATA, __datacoal_nt,coalesced')] = ('','',
  746. 'code',
  747. 'Data',
  748. 'Data',
  749. 'roData',
  750. 'bss',
  751. 'threadvar',
  752. 'pdata',
  753. 'stub',
  754. 'data_nonlazy',
  755. 'data_lazy',
  756. 'init_func',
  757. 'term_func',
  758. 'stab','stabstr',
  759. 'iData2','iData4','iData5','iData6','iData7','eData',
  760. 'eh_frame',
  761. 'debug_frame','debug_info','debug_line','debug_abbrev',
  762. 'fpc',
  763. 'toc',
  764. 'init',
  765. 'fini',
  766. 'objc_class',
  767. 'objc_meta_class',
  768. 'objc_cat_cls_meth',
  769. 'objc_cat_inst_meth',
  770. 'objc_protocol',
  771. 'objc_string_object',
  772. 'objc_cls_meth',
  773. 'objc_inst_meth',
  774. 'objc_cls_refs',
  775. 'objc_message_refs',
  776. 'objc_symbols',
  777. 'objc_category',
  778. 'objc_class_vars',
  779. 'objc_instance_vars',
  780. 'objc_module_info',
  781. 'objc_class_names',
  782. 'objc_meth_var_types',
  783. 'objc_meth_var_names',
  784. 'objc_selector_strs',
  785. 'objc_protocol_ext',
  786. 'objc_class_ext',
  787. 'objc_property',
  788. 'objc_image_info',
  789. 'objc_cstring_object',
  790. 'objc_sel_fixup',
  791. '__DATA,__objc_data',
  792. '__DATA,__objc_const',
  793. '.objc_superrefs',
  794. '__DATA, __datacoal_nt,coalesced',
  795. '.objc_classlist',
  796. '.objc_nlclasslist',
  797. '.objc_catlist',
  798. '.obcj_nlcatlist',
  799. '.objc_protolist'
  800. );
  801. var
  802. sep : string[3];
  803. begin
  804. if aname<>'' then
  805. begin
  806. case aorder of
  807. secorder_begin :
  808. sep:='.b_';
  809. secorder_end :
  810. sep:='.z_';
  811. else
  812. sep:='.n_';
  813. end;
  814. result:=secnames[atype]+sep+aname
  815. end
  816. else
  817. result:=secnames[atype];
  818. end;
  819. function TObjData.sectiontype2options(atype:TAsmSectiontype):TObjSectionOptions;
  820. const
  821. secoptions : array[TAsmSectiontype] of TObjSectionOptions = ([],
  822. {user} [oso_Data,oso_load,oso_write,oso_keep],
  823. {code} [oso_Data,oso_load,oso_readonly,oso_executable,oso_keep],
  824. {Data} [oso_Data,oso_load,oso_write,oso_keep],
  825. { TODO: Fix sec_rodata be read-only-with-relocs}
  826. {roData} [oso_Data,oso_load,oso_write,oso_keep],
  827. { TODO: Fix sec_rodata_norel be read-only/constant}
  828. {roData_norel} [oso_Data,oso_load,oso_write,oso_keep],
  829. {bss} [oso_load,oso_write,oso_keep],
  830. {threadvar} [oso_load,oso_write
  831. {$ifdef FPC_USE_TLS_DIRECTORY}
  832. ,oso_keep
  833. {$endif FPC_USE_TLS_DIRECTORY}
  834. ],
  835. {pdata} [oso_load,oso_readonly,oso_keep],
  836. {stub} [oso_Data,oso_load,oso_readonly,oso_executable],
  837. {data_nonlazy} [oso_Data,oso_load,oso_write],
  838. {data_lazy} [oso_Data,oso_load,oso_write],
  839. {init_func} [oso_Data,oso_load],
  840. {term_func} [oso_Data,oso_load],
  841. {stab} [oso_Data,oso_noload,oso_debug],
  842. {stabstr} [oso_Data,oso_noload,oso_strings,oso_debug],
  843. {iData2} [oso_Data,oso_load,oso_write],
  844. {iData4} [oso_Data,oso_load,oso_write],
  845. {iData5} [oso_Data,oso_load,oso_write],
  846. {iData6} [oso_Data,oso_load,oso_write],
  847. {iData7} [oso_Data,oso_load,oso_write],
  848. {eData} [oso_Data,oso_load,oso_readonly],
  849. {eh_frame} [oso_Data,oso_load,oso_readonly],
  850. {debug_frame} [oso_Data,oso_noload,oso_debug],
  851. {debug_info} [oso_Data,oso_noload,oso_debug],
  852. {debug_line} [oso_Data,oso_noload,oso_debug],
  853. {debug_abbrev} [oso_Data,oso_noload,oso_debug],
  854. {fpc} [oso_Data,oso_load,oso_write,oso_keep],
  855. {toc} [oso_Data,oso_load,oso_readonly],
  856. {init} [oso_Data,oso_load,oso_readonly,oso_executable,oso_keep],
  857. {fini} [oso_Data,oso_load,oso_readonly,oso_executable,oso_keep],
  858. {objc_class} [oso_data,oso_load],
  859. {objc_meta_class} [oso_data,oso_load],
  860. {objc_cat_cls_meth} [oso_data,oso_load],
  861. {objc_cat_inst_meth} [oso_data,oso_load],
  862. {objc_protocol} [oso_data,oso_load],
  863. {objc_string_object} [oso_data,oso_load],
  864. {objc_cls_meth} [oso_data,oso_load],
  865. {objc_inst_meth} [oso_data,oso_load],
  866. {objc_cls_refs} [oso_data,oso_load],
  867. {objc_message_refs} [oso_data,oso_load],
  868. {objc_symbols} [oso_data,oso_load],
  869. {objc_category} [oso_data,oso_load],
  870. {objc_class_vars} [oso_data,oso_load],
  871. {objc_instance_vars} [oso_data,oso_load],
  872. {objc_module_info} [oso_data,oso_load],
  873. {objc_class_names} [oso_data,oso_load],
  874. {objc_meth_var_types} [oso_data,oso_load],
  875. {objc_meth_var_names} [oso_data,oso_load],
  876. {objc_selector_strs} [oso_data,oso_load],
  877. {objc_protocol_ext} [oso_data,oso_load],
  878. {objc_class_ext} [oso_data,oso_load],
  879. {objc_property} [oso_data,oso_load],
  880. {objc_image_info} [oso_data,oso_load],
  881. {objc_cstring_object} [oso_data,oso_load],
  882. {objc_sel_fixup} [oso_data,oso_load],
  883. {sec_objc_data} [oso_data,oso_load],
  884. {sec_objc_const} [oso_data,oso_load],
  885. {sec_objc_sup_refs} [oso_data,oso_load],
  886. {sec_data_coalesced} [oso_data,oso_load],
  887. {sec_objc_classlist} [oso_data,oso_load],
  888. {sec_objc_nlclasslist} [oso_data,oso_load],
  889. {sec_objc_catlist} [oso_data,oso_load],
  890. {sec_objc_nlcatlist} [oso_data,oso_load],
  891. {sec_objc_protolist'} [oso_data,oso_load]
  892. );
  893. begin
  894. result:=secoptions[atype];
  895. end;
  896. function TObjData.sectiontype2align(atype:TAsmSectiontype):shortint;
  897. begin
  898. case atype of
  899. sec_stabstr,sec_debug_info,sec_debug_line,sec_debug_abbrev:
  900. result:=1;
  901. sec_code,
  902. sec_bss,
  903. sec_data:
  904. result:=16;
  905. { For idata (at least idata2) it must be 4 bytes, because
  906. an entry is always (also in win64) 20 bytes and aligning
  907. on 8 bytes will insert 4 bytes between the entries resulting
  908. in a corrupt idata section }
  909. sec_idata2,sec_idata4,sec_idata5,sec_idata6,sec_idata7:
  910. result:=4;
  911. else
  912. result:=sizeof(pint);
  913. end;
  914. end;
  915. function TObjData.createsection(atype:TAsmSectionType;const aname:string;aorder:TAsmSectionOrder):TObjSection;
  916. begin
  917. result:=createsection(sectionname(atype,aname,aorder),sectiontype2align(atype),sectiontype2options(atype));
  918. end;
  919. function TObjData.createsection(const aname:string;aalign:shortint;aoptions:TObjSectionOptions;DiscardDuplicate:boolean):TObjSection;
  920. begin
  921. if DiscardDuplicate then
  922. result:=TObjSection(FObjSectionList.Find(aname))
  923. else
  924. result:=nil;
  925. if not assigned(result) then
  926. begin
  927. result:=CObjSection.create(FObjSectionList,aname,aalign,aoptions);
  928. result.ObjData:=self;
  929. end;
  930. FCurrObjSec:=result;
  931. end;
  932. procedure TObjData.CreateDebugSections;
  933. begin
  934. end;
  935. function TObjData.FindSection(const aname:string):TObjSection;
  936. begin
  937. result:=TObjSection(FObjSectionList.Find(aname));
  938. end;
  939. procedure TObjData.setsection(asec:TObjSection);
  940. begin
  941. if asec.ObjData<>self then
  942. internalerror(200403041);
  943. FCurrObjSec:=asec;
  944. end;
  945. function TObjData.createsymbol(const aname:string):TObjSymbol;
  946. begin
  947. result:=TObjSymbol(FObjSymbolList.Find(aname));
  948. if not assigned(result) then
  949. result:=TObjSymbol.Create(FObjSymbolList,aname);
  950. end;
  951. function TObjData.symboldefine(asmsym:TAsmSymbol):TObjSymbol;
  952. begin
  953. if assigned(asmsym) then
  954. begin
  955. if not assigned(asmsym.cachedObjSymbol) then
  956. begin
  957. result:=symboldefine(asmsym.name,asmsym.bind,asmsym.typ);
  958. asmsym.cachedObjSymbol:=result;
  959. FCachedAsmSymbolList.add(asmsym);
  960. end
  961. else
  962. begin
  963. result:=TObjSymbol(asmsym.cachedObjSymbol);
  964. result.SetAddress(CurrPass,CurrObjSec,asmsym.bind,asmsym.typ);
  965. { Register also in TObjSection }
  966. CurrObjSec.AddSymbolDefine(result);
  967. end;
  968. end
  969. else
  970. result:=nil;
  971. end;
  972. function TObjData.symboldefine(const aname:string;abind:TAsmsymbind;atyp:Tasmsymtype):TObjSymbol;
  973. begin
  974. if not assigned(CurrObjSec) then
  975. internalerror(200603051);
  976. result:=CreateSymbol(aname);
  977. { Register also in TObjSection }
  978. CurrObjSec.AddSymbolDefine(result);
  979. result.SetAddress(CurrPass,CurrObjSec,abind,atyp);
  980. end;
  981. function TObjData.symbolref(asmsym:TAsmSymbol):TObjSymbol;
  982. begin
  983. if assigned(asmsym) then
  984. begin
  985. if not assigned(asmsym.cachedObjSymbol) then
  986. begin
  987. result:=symbolref(asmsym.name);
  988. asmsym.cachedObjSymbol:=result;
  989. FCachedAsmSymbolList.add(asmsym);
  990. end
  991. else
  992. result:=TObjSymbol(asmsym.cachedObjSymbol);
  993. end
  994. else
  995. result:=nil;
  996. end;
  997. function TObjData.symbolref(const aname:string):TObjSymbol;
  998. begin
  999. if not assigned(CurrObjSec) then
  1000. internalerror(200603052);
  1001. result:=CreateSymbol(aname);
  1002. end;
  1003. procedure TObjData.ResetCachedAsmSymbols;
  1004. var
  1005. i : longint;
  1006. begin
  1007. for i:=0 to FCachedAsmSymbolList.Count-1 do
  1008. tasmsymbol(FCachedAsmSymbolList[i]).cachedObjSymbol:=nil;
  1009. FCachedAsmSymbolList.Clear;
  1010. end;
  1011. procedure TObjData.writebytes(const Data;len:aword);
  1012. begin
  1013. if not assigned(CurrObjSec) then
  1014. internalerror(200402251);
  1015. CurrObjSec.write(Data,len);
  1016. end;
  1017. procedure TObjData.alloc(len:aword);
  1018. begin
  1019. if not assigned(CurrObjSec) then
  1020. internalerror(200402252);
  1021. CurrObjSec.alloc(len);
  1022. end;
  1023. procedure TObjData.allocalign(len:shortint);
  1024. begin
  1025. if not assigned(CurrObjSec) then
  1026. internalerror(200402253);
  1027. CurrObjSec.alloc(align(CurrObjSec.size,len)-CurrObjSec.size);
  1028. end;
  1029. procedure TObjData.section_afteralloc(p:TObject;arg:pointer);
  1030. begin
  1031. with TObjSection(p) do
  1032. alloc(align(size,secalign)-size);
  1033. end;
  1034. procedure TObjData.section_afterwrite(p:TObject;arg:pointer);
  1035. begin
  1036. with TObjSection(p) do
  1037. begin
  1038. if assigned(Data) then
  1039. writezeros(align(size,secalign)-size);
  1040. end;
  1041. end;
  1042. procedure TObjData.section_reset(p:TObject;arg:pointer);
  1043. begin
  1044. with TObjSection(p) do
  1045. begin
  1046. Size:=0;
  1047. Datapos:=0;
  1048. mempos:=0;
  1049. end;
  1050. end;
  1051. procedure TObjData.beforealloc;
  1052. begin
  1053. { create stabs sections if debugging }
  1054. if assigned(StabsSec) then
  1055. begin
  1056. StabsSec.Alloc(sizeof(TObjStabEntry));
  1057. StabStrSec.Alloc(1);
  1058. end;
  1059. end;
  1060. procedure TObjData.beforewrite;
  1061. var
  1062. s : string[1];
  1063. hstab : TObjStabEntry;
  1064. begin
  1065. { create stabs sections if debugging }
  1066. if assigned(StabsSec) then
  1067. begin
  1068. { Create dummy HdrSym stab, it will be overwritten in AfterWrite }
  1069. fillchar(hstab,sizeof(hstab),0);
  1070. StabsSec.Write(hstab,sizeof(hstab));
  1071. { start of stabstr }
  1072. s:=#0;
  1073. StabStrSec.write(s[1],length(s));
  1074. end;
  1075. end;
  1076. procedure TObjData.afteralloc;
  1077. begin
  1078. FObjSectionList.ForEachCall(@section_afteralloc,nil);
  1079. end;
  1080. procedure TObjData.afterwrite;
  1081. var
  1082. s : string[1];
  1083. hstab : TObjStabEntry;
  1084. begin
  1085. FObjSectionList.ForEachCall(@section_afterwrite,nil);
  1086. { For the stab section we need an HdrSym which can now be
  1087. calculated more easily }
  1088. if assigned(StabsSec) then
  1089. begin
  1090. { end of stabstr }
  1091. s:=#0;
  1092. StabStrSec.write(s[1],length(s));
  1093. { header stab }
  1094. hstab.strpos:=1;
  1095. hstab.ntype:=0;
  1096. hstab.nother:=0;
  1097. hstab.ndesc:=(StabsSec.Size div sizeof(TObjStabEntry))-1;
  1098. hstab.nvalue:=StabStrSec.Size;
  1099. StabsSec.Data.seek(0);
  1100. StabsSec.Data.write(hstab,sizeof(hstab));
  1101. end;
  1102. end;
  1103. procedure TObjData.resetsections;
  1104. begin
  1105. FObjSectionList.ForEachCall(@section_reset,nil);
  1106. end;
  1107. {****************************************************************************
  1108. TObjOutput
  1109. ****************************************************************************}
  1110. constructor TObjOutput.create(AWriter:TObjectWriter);
  1111. begin
  1112. FWriter:=AWriter;
  1113. CObjData:=TObjData;
  1114. end;
  1115. destructor TObjOutput.destroy;
  1116. begin
  1117. inherited destroy;
  1118. end;
  1119. function TObjOutput.newObjData(const n:string):TObjData;
  1120. begin
  1121. result:=CObjData.create(n);
  1122. if (cs_use_lineinfo in current_settings.globalswitches) or
  1123. (cs_debuginfo in current_settings.moduleswitches) then
  1124. result.CreateDebugSections;
  1125. end;
  1126. function TObjOutput.startObjectfile(const fn:string):boolean;
  1127. begin
  1128. result:=false;
  1129. { start the writer already, so the .a generation can initialize
  1130. the position of the current objectfile }
  1131. if not FWriter.createfile(fn) then
  1132. Comment(V_Fatal,'Can''t create object '+fn);
  1133. result:=true;
  1134. end;
  1135. function TObjOutput.writeobjectfile(Data:TObjData):boolean;
  1136. begin
  1137. if errorcount=0 then
  1138. result:=writeData(Data)
  1139. else
  1140. result:=true;
  1141. { close the writer }
  1142. FWriter.closefile;
  1143. end;
  1144. procedure TObjOutput.exportsymbol(p:TObjSymbol);
  1145. begin
  1146. { export globals and common symbols, this is needed
  1147. for .a files }
  1148. if p.bind in [AB_GLOBAL,AB_COMMON] then
  1149. FWriter.writesym(p.name);
  1150. end;
  1151. {****************************************************************************
  1152. TExeVTable
  1153. ****************************************************************************}
  1154. constructor TExeVTable.Create(AExeSymbol:TExeSymbol);
  1155. begin
  1156. ExeSymbol:=AExeSymbol;
  1157. if ExeSymbol.State=symstate_undefined then
  1158. internalerror(200604012);
  1159. ChildList:=TFPObjectList.Create(false);
  1160. end;
  1161. destructor TExeVTable.Destroy;
  1162. begin
  1163. ChildList.Free;
  1164. if assigned(EntryArray) then
  1165. Freemem(EntryArray);
  1166. end;
  1167. procedure TExeVTable.CheckIdx(VTableIdx:longint);
  1168. var
  1169. OldEntryCnt : longint;
  1170. begin
  1171. if VTableIdx>=EntryCnt then
  1172. begin
  1173. OldEntryCnt:=EntryCnt;
  1174. EntryCnt:=VTableIdx+1;
  1175. ReAllocMem(EntryArray,EntryCnt*sizeof(TVTableEntry));
  1176. FillChar(EntryArray[OldEntryCnt],(EntryCnt-OldEntryCnt)*sizeof(TVTableEntry),0);
  1177. end;
  1178. end;
  1179. procedure TExeVTable.AddChild(vt:TExeVTable);
  1180. begin
  1181. ChildList.Add(vt);
  1182. end;
  1183. procedure TExeVTable.AddEntry(VTableIdx:Longint);
  1184. var
  1185. i : longint;
  1186. objreloc : TObjRelocation;
  1187. vtblentryoffset : aword;
  1188. begin
  1189. CheckIdx(VTableIdx);
  1190. vtblentryoffset:=ExeSymbol.ObjSymbol.Offset+longword(VTableIdx)*sizeof(pint);
  1191. { Find and disable relocation }
  1192. for i:=0 to ExeSymbol.ObjSymbol.ObjSection.ObjRelocations.Count-1 do
  1193. begin
  1194. objreloc:=TObjRelocation(ExeSymbol.ObjSymbol.ObjSection.ObjRelocations[i]);
  1195. if objreloc.dataoffset=vtblentryoffset then
  1196. begin
  1197. EntryArray[VTableIdx].ObjRelocation:=objreloc;
  1198. EntryArray[VTableIdx].OrgRelocType:=objreloc.typ;
  1199. objreloc.typ:=RELOC_ZERO;
  1200. break;
  1201. end;
  1202. end;
  1203. if not assigned(EntryArray[VTableIdx].ObjRelocation) then
  1204. internalerror(200604011);
  1205. end;
  1206. procedure TExeVTable.SetVTableSize(ASize:longint);
  1207. begin
  1208. if EntryCnt<>0 then
  1209. internalerror(200603313);
  1210. EntryCnt:=ASize div sizeof(pint);
  1211. EntryArray:=AllocMem(EntryCnt*sizeof(TVTableEntry));
  1212. end;
  1213. function TExeVTable.VTableRef(VTableIdx:Longint):TObjRelocation;
  1214. begin
  1215. result:=nil;
  1216. CheckIdx(VTableIdx);
  1217. if EntryArray[VTableIdx].Used then
  1218. exit;
  1219. { Restore relocation if available }
  1220. if assigned(EntryArray[VTableIdx].ObjRelocation) then
  1221. begin
  1222. EntryArray[VTableIdx].ObjRelocation.typ:=EntryArray[VTableIdx].OrgRelocType;
  1223. result:=EntryArray[VTableIdx].ObjRelocation;
  1224. end;
  1225. EntryArray[VTableIdx].Used:=true;
  1226. end;
  1227. {****************************************************************************
  1228. TExeSection
  1229. ****************************************************************************}
  1230. constructor TExeSection.create(AList:TFPHashObjectList;const AName:string);
  1231. begin
  1232. inherited create(AList,AName);
  1233. Size:=0;
  1234. MemPos:=0;
  1235. DataPos:=0;
  1236. FSecSymIdx:=0;
  1237. FObjSectionList:=TFPObjectList.Create(false);
  1238. end;
  1239. destructor TExeSection.destroy;
  1240. begin
  1241. ObjSectionList.Free;
  1242. inherited destroy;
  1243. end;
  1244. procedure TExeSection.AddObjSection(objsec:TObjSection);
  1245. begin
  1246. ObjSectionList.Add(objsec);
  1247. if (SecOptions<>[]) then
  1248. begin
  1249. { Only if the section contains (un)initialized data the
  1250. data flag must match. This check is not needed if the
  1251. section is empty for a symbol allocation }
  1252. if (objsec.size>0) and
  1253. ((oso_Data in SecOptions)<>(oso_Data in objsec.SecOptions)) then
  1254. Comment(V_Error,'Incompatible section options');
  1255. end
  1256. else
  1257. begin
  1258. { inherit section options }
  1259. SecAlign:=objsec.SecAlign;
  1260. SecOptions:=SecOptions+objsec.SecOptions;
  1261. end;
  1262. { relate ObjSection to ExeSection, and mark it Used by default }
  1263. objsec.ExeSection:=self;
  1264. objsec.Used:=true;
  1265. end;
  1266. {****************************************************************************
  1267. TStaticLibrary
  1268. ****************************************************************************}
  1269. constructor TStaticLibrary.create(AList:TFPHashObjectList;const AName:string;AReader:TObjectReader;AObjInputClass:TObjInputClass);
  1270. begin
  1271. inherited create(AList,AName);
  1272. FArReader:=AReader;
  1273. FObjInputClass:=AObjInputClass;
  1274. end;
  1275. destructor TStaticLibrary.destroy;
  1276. begin
  1277. ArReader.Free;
  1278. inherited destroy;
  1279. end;
  1280. {****************************************************************************
  1281. TImportLibrary
  1282. ****************************************************************************}
  1283. constructor TImportLibrary.create(AList:TFPHashObjectList;const AName:string);
  1284. begin
  1285. inherited create(AList,AName);
  1286. FImportSymbolList:=TFPHashObjectList.Create(true);
  1287. end;
  1288. destructor TImportLibrary.destroy;
  1289. begin
  1290. ImportSymbolList.Free;
  1291. inherited destroy;
  1292. end;
  1293. {****************************************************************************
  1294. TImportSymbol
  1295. ****************************************************************************}
  1296. constructor TImportSymbol.create(AList:TFPHashObjectList;
  1297. const AName,AMangledName:string;AOrdNr:longint;AIsVar:boolean);
  1298. begin
  1299. inherited Create(AList, AName);
  1300. FOrdNr:=AOrdNr;
  1301. FIsVar:=AIsVar;
  1302. FMangledName:=AMangledName;
  1303. { Replace ? and @ in import name, since GNU AS does not allow these characters in symbol names. }
  1304. { This allows to import VC++ mangled names from DLLs. }
  1305. if target_info.system in systems_all_windows+[system_i386_symobi] then
  1306. begin
  1307. Replace(FMangledName,'?','__q$$');
  1308. {$ifdef arm}
  1309. { @ symbol is not allowed in ARM assembler only }
  1310. Replace(FMangledName,'@','__a$$');
  1311. {$endif arm}
  1312. end;
  1313. end;
  1314. {****************************************************************************
  1315. TExeOutput
  1316. ****************************************************************************}
  1317. constructor TExeOutput.create;
  1318. begin
  1319. { init writer }
  1320. FWriter:=TObjectwriter.create;
  1321. FExeWriteMode:=ewm_exefull;
  1322. { object files }
  1323. FObjDataList:=TFPObjectList.Create(true);
  1324. { symbols }
  1325. FExeSymbolList:=TFPHashObjectList.Create(true);
  1326. FUnresolvedExeSymbols:=TFPObjectList.Create(false);
  1327. FExternalObjSymbols:=TFPObjectList.Create(false);
  1328. FCommonObjSymbols:=TFPObjectList.Create(false);
  1329. FExeVTableList:=TFPObjectList.Create(false);
  1330. FEntryName:='start';
  1331. { sections }
  1332. FExeSectionList:=TFPHashObjectList.Create(true);
  1333. FImageBase:=0;
  1334. {$ifdef cpu16bitaddr}
  1335. SectionMemAlign:=$10;
  1336. SectionDataAlign:=$10;
  1337. {$else cpu16bitaddr}
  1338. SectionMemAlign:=$1000;
  1339. SectionDataAlign:=$200;
  1340. {$endif cpu16bitaddr}
  1341. FCExeSection:=TExeSection;
  1342. FCObjData:=TObjData;
  1343. end;
  1344. destructor TExeOutput.destroy;
  1345. begin
  1346. FExeSymbolList.free;
  1347. UnresolvedExeSymbols.free;
  1348. ExternalObjSymbols.free;
  1349. CommonObjSymbols.free;
  1350. ExeVTableList.free;
  1351. FExeSectionList.free;
  1352. ObjDatalist.free;
  1353. FWriter.free;
  1354. inherited destroy;
  1355. end;
  1356. function TExeOutput.WriteExeFile(const fn:string):boolean;
  1357. begin
  1358. result:=false;
  1359. if FWriter.createfile(fn) then
  1360. begin
  1361. { Only write the .o if there are no errors }
  1362. if errorcount=0 then
  1363. result:=writedata
  1364. else
  1365. result:=true;
  1366. { close the writer }
  1367. FWriter.closefile;
  1368. end
  1369. else
  1370. Comment(V_Fatal,'Can''t create executable '+fn);
  1371. end;
  1372. procedure TExeOutput.ParseScript (linkscript:TCmdStrList);
  1373. begin
  1374. end;
  1375. function TExeOutput.FindExeSection(const aname:string):TExeSection;
  1376. begin
  1377. result:=TExeSection(ExeSectionList.Find(aname));
  1378. end;
  1379. procedure TExeOutput.AddObjData(ObjData:TObjData);
  1380. begin
  1381. if ObjData.classtype<>FCObjData then
  1382. Comment(V_Error,'Invalid input object format for '+ObjData.name+' got '+ObjData.classname+' expected '+FCObjData.classname);
  1383. ObjDataList.Add(ObjData);
  1384. end;
  1385. procedure TExeOutput.Load_Start;
  1386. begin
  1387. ObjDataList.Clear;
  1388. { Globals defined in the linker script }
  1389. if not assigned(internalObjData) then
  1390. internalObjData:=CObjData.create('*Internal*');
  1391. AddObjData(internalObjData);
  1392. { Common Data section }
  1393. commonObjSection:=internalObjData.createsection(sec_bss,'');
  1394. end;
  1395. procedure TExeOutput.Load_EntryName(const aname:string);
  1396. begin
  1397. FEntryName:=aname;
  1398. end;
  1399. procedure TExeOutput.Load_IsSharedLibrary;
  1400. begin
  1401. IsSharedLibrary:=true;
  1402. end;
  1403. procedure TExeOutput.Load_ImageBase(const avalue:string);
  1404. var
  1405. code : integer;
  1406. objsec : TObjSection;
  1407. objsym : TObjSymbol;
  1408. exesym : TExeSymbol;
  1409. begin
  1410. val(avalue,ImageBase,code);
  1411. if code<>0 then
  1412. Comment(V_Error,'Invalid number '+avalue);
  1413. { Create __image_base__ symbol, create the symbol
  1414. in a section with adress 0 and at offset 0 }
  1415. objsec:=internalObjData.createsection('*__image_base__',0,[]);
  1416. internalObjData.setsection(objsec);
  1417. objsym:=internalObjData.SymbolDefine('__image_base__',AB_GLOBAL,AT_FUNCTION);
  1418. exesym:=texesymbol.Create(FExeSymbolList,objsym.name);
  1419. exesym.ObjSymbol:=objsym;
  1420. end;
  1421. procedure TExeOutput.Load_Symbol(const aname:string);
  1422. begin
  1423. internalObjData.createsection('*'+aname,0,[]);
  1424. internalObjData.SymbolDefine(aname,AB_GLOBAL,AT_FUNCTION);
  1425. end;
  1426. procedure TExeOutput.Load_ProvideSymbol(const aname:string);
  1427. begin
  1428. if assigned(ExeSymbolList.Find(aname)) then
  1429. exit;
  1430. internalObjData.createsection('*'+aname,0,[]);
  1431. // Use AB_COMMON to avoid muliple defined complaints
  1432. internalObjData.SymbolDefine(aname,AB_COMMON,AT_DATA);
  1433. end;
  1434. procedure TExeOutput.Order_Start;
  1435. begin
  1436. end;
  1437. procedure TExeOutput.Order_End;
  1438. begin
  1439. internalObjData.afterwrite;
  1440. end;
  1441. procedure TExeOutput.Order_ExeSection(const aname:string);
  1442. var
  1443. sec : TExeSection;
  1444. begin
  1445. sec:=FindExeSection(aname);
  1446. if not assigned(sec) then
  1447. sec:=CExeSection.create(ExeSectionList,aname);
  1448. { Clear ExeSection contents }
  1449. FCurrExeSec:=sec;
  1450. end;
  1451. procedure TExeOutput.Order_EndExeSection;
  1452. begin
  1453. if not assigned(CurrExeSec) then
  1454. internalerror(200602184);
  1455. FCurrExeSec:=nil;
  1456. end;
  1457. procedure TExeOutput.Order_ObjSection(const aname:string);
  1458. var
  1459. i,j : longint;
  1460. ObjData : TObjData;
  1461. objsec : TObjSection;
  1462. TmpObjSectionList : TFPObjectList;
  1463. begin
  1464. if not assigned(CurrExeSec) then
  1465. internalerror(200602181);
  1466. TmpObjSectionList:=TFPObjectList.Create(false);
  1467. for i:=0 to ObjDataList.Count-1 do
  1468. begin
  1469. ObjData:=TObjData(ObjDataList[i]);
  1470. for j:=0 to ObjData.ObjSectionList.Count-1 do
  1471. begin
  1472. objsec:=TObjSection(ObjData.ObjSectionList[j]);
  1473. if (not objsec.Used) and
  1474. MatchPattern(aname,objsec.name) then
  1475. TmpObjSectionList.Add(objsec);
  1476. end;
  1477. end;
  1478. { Order list if needed }
  1479. Order_ObjSectionList(TmpObjSectionList,aname);
  1480. { Add the (ordered) list to the current ExeSection }
  1481. for i:=0 to TmpObjSectionList.Count-1 do
  1482. begin
  1483. objsec:=TObjSection(TmpObjSectionList[i]);
  1484. CurrExeSec.AddObjSection(objsec);
  1485. end;
  1486. TmpObjSectionList.Free;
  1487. end;
  1488. procedure TExeOutput.Order_ObjSectionList(ObjSectionList : TFPObjectList; const aPattern:string);
  1489. begin
  1490. end;
  1491. procedure TExeOutput.Order_Symbol(const aname:string);
  1492. var
  1493. ObjSection : TObjSection;
  1494. begin
  1495. ObjSection:=internalObjData.findsection('*'+aname);
  1496. if not assigned(ObjSection) then
  1497. internalerror(200603041);
  1498. CurrExeSec.AddObjSection(ObjSection);
  1499. end;
  1500. procedure TExeOutput.Order_ProvideSymbol(const aname:string);
  1501. var
  1502. ObjSection : TObjSection;
  1503. begin
  1504. ObjSection:=internalObjData.findsection('*'+aname);
  1505. if not assigned(ObjSection) then
  1506. internalerror(200603041);
  1507. { Only include this section if the symbol doesn't
  1508. exist otherwisee }
  1509. if not assigned(ExeSymbolList.Find(aname)) then
  1510. CurrExeSec.AddObjSection(ObjSection);
  1511. end;
  1512. procedure TExeOutput.Order_Align(const avalue:string);
  1513. var
  1514. code : integer;
  1515. alignval : shortint;
  1516. objsec : TObjSection;
  1517. begin
  1518. val(avalue,alignval,code);
  1519. if code<>0 then
  1520. Comment(V_Error,'Invalid number '+avalue);
  1521. if alignval<=0 then
  1522. exit;
  1523. { Create an empty section with the required aligning }
  1524. inc(Fzeronr);
  1525. objsec:=internalObjData.createsection('*align'+tostr(Fzeronr),alignval,CurrExeSec.SecOptions+[oso_Data,oso_keep]);
  1526. CurrExeSec.AddObjSection(objsec);
  1527. end;
  1528. procedure TExeOutput.Order_Zeros(const avalue:string);
  1529. var
  1530. zeros : array[0..1023] of byte;
  1531. code : integer;
  1532. len : longint;
  1533. objsec : TObjSection;
  1534. begin
  1535. val(avalue,len,code);
  1536. if code<>0 then
  1537. Comment(V_Error,'Invalid number '+avalue);
  1538. if len<=0 then
  1539. exit;
  1540. if len>sizeof(zeros) then
  1541. internalerror(200602254);
  1542. fillchar(zeros,len,0);
  1543. inc(Fzeronr);
  1544. objsec:=internalObjData.createsection('*zeros'+tostr(Fzeronr),0,CurrExeSec.SecOptions+[oso_Data,oso_keep]);
  1545. internalObjData.writebytes(zeros,len);
  1546. CurrExeSec.AddObjSection(objsec);
  1547. end;
  1548. procedure TExeOutput.Order_Values(bytesize : aword; const avalue:string);
  1549. const
  1550. MAXVAL = 128;
  1551. var
  1552. bytevalues : array[0..MAXVAL-1] of byte;
  1553. twobytevalues : array[0..MAXVAL-1] of word;
  1554. fourbytevalues : array[0..MAXVAL-1] of dword;
  1555. eightbytevalues : array[0..MAXVAL-1] of qword;
  1556. allvals, oneval : string;
  1557. len, commapos : longint;
  1558. indexpos, code : integer;
  1559. anumval : qword;
  1560. signedval : int64;
  1561. objsec : TObjSection;
  1562. begin
  1563. indexpos:=0;
  1564. allvals:=avalue;
  1565. repeat
  1566. commapos:=pos(',',allvals);
  1567. if commapos>0 then
  1568. begin
  1569. oneval:=trim(copy(allvals,1,commapos-1));
  1570. allvals:=copy(allvals,commapos+1,length(allvals));
  1571. end
  1572. else
  1573. begin
  1574. oneval:=trim(allvals);
  1575. allvals:='';
  1576. end;
  1577. if oneval<>'' then
  1578. begin
  1579. if oneval[1]='-' then
  1580. begin
  1581. val(oneval,signedval,code);
  1582. anumval:=qword(signedval);
  1583. end
  1584. else
  1585. val(oneval,anumval,code);
  1586. if code<>0 then
  1587. Comment(V_Error,'Invalid number '+avalue)
  1588. else
  1589. begin
  1590. if (indexpos<MAXVAL) then
  1591. begin
  1592. if source_info.endian<>target_info.endian then
  1593. swapendian(anumval);
  1594. { No range checking here }
  1595. if bytesize=1 then
  1596. bytevalues[indexpos]:=byte(anumval)
  1597. else if bytesize=2 then
  1598. twobytevalues[indexpos]:=word(anumval)
  1599. else if bytesize=4 then
  1600. fourbytevalues[indexpos]:=dword(anumval)
  1601. else if bytesize=8 then
  1602. eightbytevalues[indexpos]:=anumval;
  1603. inc(indexpos);
  1604. end
  1605. else
  1606. Comment(V_Error,'Buffer overrun in Order_values');
  1607. end;
  1608. end;
  1609. until allvals='';
  1610. if indexpos=0 then
  1611. begin
  1612. Comment(V_Error,'Invalid number '+avalue);
  1613. exit;
  1614. end;
  1615. if indexpos=MAXVAL then
  1616. begin
  1617. Comment(V_Error,'Too many values '+avalue);
  1618. internalerror(200602254);
  1619. end;
  1620. len:=bytesize*indexpos;
  1621. inc(Fvaluesnr);
  1622. objsec:=internalObjData.createsection('*values'+tostr(Fvaluesnr),0,CurrExeSec.SecOptions+[oso_Data,oso_keep]);
  1623. if bytesize=1 then
  1624. internalObjData.writebytes(bytevalues,len)
  1625. else if bytesize=2 then
  1626. internalObjData.writebytes(twobytevalues,len)
  1627. else if bytesize=4 then
  1628. internalObjData.writebytes(fourbytevalues,len)
  1629. else if bytesize=8 then
  1630. internalObjData.writebytes(eightbytevalues,len);
  1631. CurrExeSec.AddObjSection(objsec);
  1632. end;
  1633. procedure TExeOutput.MemPos_Start;
  1634. begin
  1635. CurrMemPos:=0;
  1636. end;
  1637. procedure TExeOutput.MemPos_Header;
  1638. begin
  1639. end;
  1640. procedure TExeOutput.MemPos_ExeSection(const aname:string);
  1641. var
  1642. i : longint;
  1643. objsec : TObjSection;
  1644. begin
  1645. { Section can be removed }
  1646. FCurrExeSec:=FindExeSection(aname);
  1647. if not assigned(CurrExeSec) then
  1648. exit;
  1649. { Alignment of ExeSection }
  1650. CurrMemPos:=align(CurrMemPos,SectionMemAlign);
  1651. CurrExeSec.MemPos:=CurrMemPos;
  1652. { set position of object ObjSections }
  1653. for i:=0 to CurrExeSec.ObjSectionList.Count-1 do
  1654. begin
  1655. objsec:=TObjSection(CurrExeSec.ObjSectionList[i]);
  1656. CurrMemPos:=objsec.setmempos(CurrMemPos);
  1657. end;
  1658. { calculate size of the section }
  1659. CurrExeSec.Size:=CurrMemPos-CurrExeSec.MemPos;
  1660. end;
  1661. procedure TExeOutput.MemPos_EndExeSection;
  1662. begin
  1663. if not assigned(CurrExeSec) then
  1664. exit;
  1665. FCurrExeSec:=nil;
  1666. end;
  1667. procedure TExeOutput.DataPos_Start;
  1668. begin
  1669. end;
  1670. procedure TExeOutput.DataPos_Header;
  1671. begin
  1672. end;
  1673. procedure TExeOutput.DataPos_ExeSection(const aname:string);
  1674. var
  1675. i : longint;
  1676. objsec : TObjSection;
  1677. begin
  1678. { Section can be removed }
  1679. FCurrExeSec:=FindExeSection(aname);
  1680. if not assigned(CurrExeSec) then
  1681. exit;
  1682. { don't write normal section if writing only debug info }
  1683. if (ExeWriteMode=ewm_dbgonly) and
  1684. not(oso_debug in CurrExeSec.SecOptions) then
  1685. exit;
  1686. if (oso_Data in currexesec.SecOptions) then
  1687. begin
  1688. CurrDataPos:=align(CurrDataPos,SectionDataAlign);
  1689. CurrExeSec.DataPos:=CurrDataPos;
  1690. end;
  1691. { set position of object ObjSections }
  1692. for i:=0 to CurrExeSec.ObjSectionList.Count-1 do
  1693. begin
  1694. objsec:=TObjSection(CurrExeSec.ObjSectionList[i]);
  1695. if (oso_Data in objsec.SecOptions) then
  1696. begin
  1697. if not(oso_Data in currexesec.SecOptions) then
  1698. internalerror(200603043);
  1699. if not assigned(objsec.Data) then
  1700. internalerror(200603044);
  1701. objsec.setDatapos(CurrDataPos);
  1702. end;
  1703. end;
  1704. end;
  1705. procedure TExeOutput.DataPos_EndExeSection;
  1706. begin
  1707. if not assigned(CurrExeSec) then
  1708. exit;
  1709. FCurrExeSec:=nil;
  1710. end;
  1711. procedure TExeOutput.DataPos_Symbols;
  1712. var
  1713. i : longint;
  1714. sym : TExeSymbol;
  1715. begin
  1716. { Removing unused symbols }
  1717. for i:=0 to ExeSymbolList.Count-1 do
  1718. begin
  1719. sym:=TExeSymbol(ExeSymbolList[i]);
  1720. if not sym.ObjSymbol.objsection.Used then
  1721. ExeSymbolList[i]:=nil;
  1722. end;
  1723. ExeSymbolList.Pack;
  1724. end;
  1725. procedure TExeOutput.BuildVTableTree(VTInheritList,VTEntryList:TFPObjectList);
  1726. var
  1727. hs : string;
  1728. code : integer;
  1729. i,k,
  1730. vtableidx : longint;
  1731. vtableexesym,
  1732. childexesym,
  1733. parentexesym : TExeSymbol;
  1734. objsym : TObjSymbol;
  1735. begin
  1736. { Build inheritance tree from VTINHERIT }
  1737. for i:=0 to VTInheritList.Count-1 do
  1738. begin
  1739. objsym:=TObjSymbol(VTInheritList[i]);
  1740. hs:=objsym.name;
  1741. { VTINHERIT_<ChildVMTName>$$<ParentVMTName> }
  1742. Delete(hs,1,Pos('_',hs));
  1743. k:=Pos('$$',hs);
  1744. if k=0 then
  1745. internalerror(200603311);
  1746. childexesym:=texesymbol(FExeSymbolList.Find(Copy(hs,1,k-1)));
  1747. parentexesym:=texesymbol(FExeSymbolList.Find(Copy(hs,k+2,length(hs)-k-1)));
  1748. if not assigned(childexesym) or
  1749. not assigned(parentexesym)then
  1750. internalerror(200603312);
  1751. if not assigned(childexesym.vtable) then
  1752. begin
  1753. childexesym.vtable:=TExeVTable.Create(childexesym);
  1754. ExeVTableList.Add(childexesym.vtable);
  1755. end;
  1756. if not assigned(parentexesym.vtable) then
  1757. begin
  1758. parentexesym.vtable:=TExeVTable.Create(parentexesym);
  1759. ExeVTableList.Add(parentexesym.vtable);
  1760. end;
  1761. childexesym.vtable.SetVTableSize(childexesym.ObjSymbol.Size);
  1762. if parentexesym<>childexesym then
  1763. parentexesym.vtable.AddChild(childexesym.vtable);
  1764. end;
  1765. { Find VTable entries from VTENTRY }
  1766. for i:=0 to VTEntryList.Count-1 do
  1767. begin
  1768. objsym:=TObjSymbol(VTEntryList[i]);
  1769. hs:=objsym.name;
  1770. { VTENTRY_<VTableName>$$<Index> }
  1771. Delete(hs,1,Pos('_',hs));
  1772. k:=Pos('$$',hs);
  1773. if k=0 then
  1774. internalerror(200603319);
  1775. vtableexesym:=texesymbol(FExeSymbolList.Find(Copy(hs,1,k-1)));
  1776. val(Copy(hs,k+2,length(hs)-k-1),vtableidx,code);
  1777. if (code<>0) then
  1778. internalerror(200603318);
  1779. if not assigned(vtableexesym) then
  1780. internalerror(2006033110);
  1781. vtableexesym.vtable.AddEntry(vtableidx);
  1782. end;
  1783. end;
  1784. procedure TExeOutput.PackUnresolvedExeSymbols(const s:string);
  1785. var
  1786. i : longint;
  1787. exesym : TExeSymbol;
  1788. begin
  1789. { Generate a list of Unresolved External symbols }
  1790. for i:=0 to UnresolvedExeSymbols.count-1 do
  1791. begin
  1792. exesym:=TExeSymbol(UnresolvedExeSymbols[i]);
  1793. if exesym.State<>symstate_undefined then
  1794. UnresolvedExeSymbols[i]:=nil;
  1795. end;
  1796. UnresolvedExeSymbols.Pack;
  1797. Comment(V_Debug,'Number of unresolved externals '+s+' '+tostr(UnresolvedExeSymbols.Count));
  1798. end;
  1799. procedure TExeOutput.ResolveSymbols(StaticLibraryList:TFPHashObjectList);
  1800. var
  1801. ObjData : TObjData;
  1802. exesym : TExeSymbol;
  1803. objsym,
  1804. commonsym : TObjSymbol;
  1805. objinput : TObjInput;
  1806. StaticLibrary : TStaticLibrary;
  1807. firstarchive,
  1808. firstcommon : boolean;
  1809. i,j : longint;
  1810. VTEntryList,
  1811. VTInheritList : TFPObjectList;
  1812. procedure LoadObjDataSymbols(ObjData:TObjData);
  1813. var
  1814. j : longint;
  1815. hs : string;
  1816. exesym : TExeSymbol;
  1817. objsym : TObjSymbol;
  1818. begin
  1819. for j:=0 to ObjData.ObjSymbolList.Count-1 do
  1820. begin
  1821. objsym:=TObjSymbol(ObjData.ObjSymbolList[j]);
  1822. { From the local symbols we are only interressed in the
  1823. VTENTRY and VTINHERIT symbols }
  1824. if objsym.bind=AB_LOCAL then
  1825. begin
  1826. if cs_link_opt_vtable in current_settings.globalswitches then
  1827. begin
  1828. hs:=objsym.name;
  1829. if (hs[1]='V') then
  1830. begin
  1831. if Copy(hs,1,5)='VTREF' then
  1832. begin
  1833. if not assigned(objsym.ObjSection.VTRefList) then
  1834. objsym.ObjSection.VTRefList:=TFPObjectList.Create(false);
  1835. objsym.ObjSection.VTRefList.Add(objsym);
  1836. end
  1837. else if Copy(hs,1,7)='VTENTRY' then
  1838. VTEntryList.Add(objsym)
  1839. else if Copy(hs,1,9)='VTINHERIT' then
  1840. VTInheritList.Add(objsym);
  1841. end;
  1842. end;
  1843. continue;
  1844. end;
  1845. { Search for existing exesymbol }
  1846. exesym:=texesymbol(FExeSymbolList.Find(objsym.name));
  1847. if not assigned(exesym) then
  1848. begin
  1849. exesym:=texesymbol.Create(FExeSymbolList,objsym.name);
  1850. exesym.ObjSymbol:=objsym;
  1851. end;
  1852. objsym.ExeSymbol:=exesym;
  1853. case objsym.bind of
  1854. AB_GLOBAL :
  1855. begin
  1856. if exesym.State<>symstate_defined then
  1857. begin
  1858. exesym.ObjSymbol:=objsym;
  1859. exesym.State:=symstate_defined;
  1860. end
  1861. else
  1862. Comment(V_Error,'Multiple defined symbol '+objsym.name);
  1863. end;
  1864. AB_EXTERNAL :
  1865. begin
  1866. ExternalObjSymbols.add(objsym);
  1867. { Register unresolved symbols only the first time they
  1868. are registered }
  1869. if exesym.ObjSymbol=objsym then
  1870. UnresolvedExeSymbols.Add(exesym);
  1871. end;
  1872. AB_COMMON :
  1873. begin
  1874. if exesym.State=symstate_undefined then
  1875. begin
  1876. exesym.ObjSymbol:=objsym;
  1877. exesym.State:=symstate_common;
  1878. end;
  1879. CommonObjSymbols.add(objsym);
  1880. end;
  1881. end;
  1882. end;
  1883. end;
  1884. begin
  1885. VTEntryList:=TFPObjectList.Create(false);
  1886. VTInheritList:=TFPObjectList.Create(false);
  1887. {
  1888. The symbol resolving is done in 3 steps:
  1889. 1. Register symbols from objects
  1890. 2. Find symbols in static libraries
  1891. 3. Define stil undefined common symbols
  1892. }
  1893. { Step 1, Register symbols from objects }
  1894. for i:=0 to ObjDataList.Count-1 do
  1895. begin
  1896. ObjData:=TObjData(ObjDataList[i]);
  1897. LoadObjDataSymbols(ObjData);
  1898. end;
  1899. PackUnresolvedExeSymbols('in objects');
  1900. { Step 2, Find unresolved symbols in the libraries }
  1901. firstarchive:=true;
  1902. for i:=0 to StaticLibraryList.Count-1 do
  1903. begin
  1904. StaticLibrary:=TStaticLibrary(StaticLibraryList[i]);
  1905. { Process list of Unresolved External symbols, we need
  1906. to use a while loop because the list can be extended when
  1907. we load members from the library. }
  1908. j:=0;
  1909. while (j<UnresolvedExeSymbols.count) do
  1910. begin
  1911. exesym:=TExeSymbol(UnresolvedExeSymbols[j]);
  1912. { Check first if the symbol is still undefined }
  1913. if exesym.State=symstate_undefined then
  1914. begin
  1915. if StaticLibrary.ArReader.OpenFile(exesym.name) then
  1916. begin
  1917. if assigned(exemap) then
  1918. begin
  1919. if firstarchive then
  1920. begin
  1921. exemap.Add('');
  1922. exemap.Add('Archive member included because of file (symbol)');
  1923. exemap.Add('');
  1924. firstarchive:=false;
  1925. end;
  1926. exemap.Add(StaticLibrary.ArReader.FileName+' - '+
  1927. {exesym.ObjSymbol.ObjSection.FullName+}
  1928. '('+exesym.Name+')');
  1929. end;
  1930. objinput:=StaticLibrary.ObjInputClass.Create;
  1931. objdata:=objinput.newObjData(StaticLibrary.ArReader.FileName);
  1932. objinput.ReadObjData(StaticLibrary.ArReader,objdata);
  1933. objinput.free;
  1934. AddObjData(objdata);
  1935. LoadObjDataSymbols(objdata);
  1936. StaticLibrary.ArReader.CloseFile;
  1937. end;
  1938. end;
  1939. inc(j);
  1940. end;
  1941. end;
  1942. PackUnresolvedExeSymbols('after static libraries');
  1943. { Step 3, Match common symbols or add to the globals }
  1944. firstcommon:=true;
  1945. for i:=0 to CommonObjSymbols.count-1 do
  1946. begin
  1947. objsym:=TObjSymbol(CommonObjSymbols[i]);
  1948. if objsym.exesymbol.State=symstate_defined then
  1949. begin
  1950. if objsym.exesymbol.ObjSymbol.size<>objsym.size then
  1951. Comment(V_Debug,'Size of common symbol '+objsym.name+' is different, expected '+tostr(objsym.size)+' got '+tostr(objsym.exesymbol.ObjSymbol.size));
  1952. end
  1953. else
  1954. begin
  1955. { allocate new objsymbol in .bss of *COMMON* and assign
  1956. it to the exesymbol }
  1957. if firstcommon then
  1958. begin
  1959. if assigned(exemap) then
  1960. exemap.AddCommonSymbolsHeader;
  1961. firstcommon:=false;
  1962. end;
  1963. internalObjData.setsection(commonObjSection);
  1964. internalObjData.allocalign(var_align(objsym.size));
  1965. commonsym:=internalObjData.symboldefine(objsym.name,AB_GLOBAL,AT_FUNCTION);
  1966. commonsym.size:=objsym.size;
  1967. internalObjData.alloc(objsym.size);
  1968. if assigned(exemap) then
  1969. exemap.AddCommonSymbol(commonsym);
  1970. { Assign to the exesymbol }
  1971. objsym.exesymbol.objsymbol:=commonsym;
  1972. objsym.exesymbol.state:=symstate_defined;
  1973. end;
  1974. end;
  1975. PackUnresolvedExeSymbols('after defining COMMON symbols');
  1976. { Find entry symbol and print in map }
  1977. exesym:=texesymbol(ExeSymbolList.Find(EntryName));
  1978. if assigned(exesym) then
  1979. begin
  1980. EntrySym:=exesym.ObjSymbol;
  1981. if assigned(exemap) then
  1982. begin
  1983. exemap.Add('');
  1984. exemap.Add('Entry symbol '+EntryName);
  1985. end;
  1986. end
  1987. else
  1988. Comment(V_Error,'Entrypoint '+EntryName+' not defined');
  1989. { Generate VTable tree }
  1990. if cs_link_opt_vtable in current_settings.globalswitches then
  1991. BuildVTableTree(VTInheritList,VTEntryList);
  1992. VTInheritList.Free;
  1993. VTEntryList.Free;
  1994. end;
  1995. procedure TExeOutput.GenerateDebugLink(const dbgname:string;dbgcrc:cardinal);
  1996. var
  1997. debuglink : array[0..1023] of byte;
  1998. len : longint;
  1999. objsec : TObjSection;
  2000. exesec : TExeSection;
  2001. begin
  2002. { From the gdb manual chapter 15. GDB Files:
  2003. * A filename, with any leading directory components removed, followed by a zero byte,
  2004. * zero to three bytes of padding, as needed to reach the next four-byte boundary within the section, and
  2005. * a four-byte CRC checksum, stored in the same endianness used for the executable file itself. The checksum is computed
  2006. on the debugging information file's full contents by the function given below, passing zero as the crc argument.
  2007. }
  2008. fillchar(debuglink,sizeof(debuglink),0);
  2009. len:=0;
  2010. move(dbgname[1],debuglink[len],length(dbgname));
  2011. inc(len,length(dbgname)+1);
  2012. len:=align(len,4);
  2013. if source_info.endian<>target_info.endian then
  2014. SwapEndian(dbgcrc);
  2015. move(dbgcrc,debuglink[len],sizeof(cardinal));
  2016. inc(len,4);
  2017. { Add section }
  2018. exesec:=FindExeSection(debuglinkname);
  2019. if not assigned(exesec) then
  2020. exesec:=CExeSection.create(ExeSectionList,debuglinkname);
  2021. exesec.SecOptions:=[oso_data,oso_keep];
  2022. exesec.SecAlign:=4;
  2023. objsec:=internalObjData.createsection(exesec.name,0,exesec.SecOptions);
  2024. internalObjData.writebytes(debuglink,len);
  2025. exesec.AddObjSection(objsec);
  2026. end;
  2027. procedure TExeOutput.GenerateLibraryImports(ImportLibraryList:TFPHashObjectList);
  2028. begin
  2029. end;
  2030. procedure TExeOutput.PrintMemoryMap;
  2031. var
  2032. exesec : TExeSection;
  2033. objsec : TObjSection;
  2034. objsym : TObjSymbol;
  2035. i,j,k : longint;
  2036. begin
  2037. if not assigned(exemap) then
  2038. exit;
  2039. exemap.AddMemoryMapHeader(ImageBase);
  2040. for i:=0 to ExeSectionList.Count-1 do
  2041. begin
  2042. exesec:=TExeSection(ExeSectionList[i]);
  2043. exemap.AddMemoryMapExeSection(exesec);
  2044. for j:=0 to exesec.ObjSectionList.count-1 do
  2045. begin
  2046. objsec:=TObjSection(exesec.ObjSectionList[j]);
  2047. exemap.AddMemoryMapObjectSection(objsec);
  2048. for k:=0 to objsec.ObjSymbolDefines.Count-1 do
  2049. begin
  2050. objsym:=TObjSymbol(objsec.ObjSymbolDefines[k]);
  2051. exemap.AddMemoryMapSymbol(objsym);
  2052. end;
  2053. end;
  2054. end;
  2055. end;
  2056. procedure TExeOutput.FixupSymbols;
  2057. procedure UpdateSymbol(objsym:TObjSymbol);
  2058. begin
  2059. objsym.bind:=objsym.ExeSymbol.ObjSymbol.bind;
  2060. objsym.offset:=objsym.ExeSymbol.ObjSymbol.offset;
  2061. objsym.size:=objsym.ExeSymbol.ObjSymbol.size;
  2062. objsym.typ:=objsym.ExeSymbol.ObjSymbol.typ;
  2063. objsym.ObjSection:=objsym.ExeSymbol.ObjSymbol.ObjSection;
  2064. end;
  2065. var
  2066. i : longint;
  2067. objsym : TObjSymbol;
  2068. exesym : TExeSymbol;
  2069. begin
  2070. { Print list of Unresolved External symbols }
  2071. for i:=0 to UnresolvedExeSymbols.count-1 do
  2072. begin
  2073. exesym:=TExeSymbol(UnresolvedExeSymbols[i]);
  2074. if exesym.State<>symstate_defined then
  2075. Comment(V_Error,'Undefined symbol: '+exesym.name);
  2076. end;
  2077. { Update ImageBase to ObjData so it can access from ObjSymbols }
  2078. for i:=0 to ObjDataList.Count-1 do
  2079. TObjData(ObjDataList[i]).imagebase:=imagebase;
  2080. {
  2081. Fixing up symbols is done in the following steps:
  2082. 1. Update common references
  2083. 2. Update external references
  2084. }
  2085. { Step 1, Update commons }
  2086. for i:=0 to CommonObjSymbols.count-1 do
  2087. begin
  2088. objsym:=TObjSymbol(CommonObjSymbols[i]);
  2089. if objsym.bind<>AB_COMMON then
  2090. internalerror(200606241);
  2091. UpdateSymbol(objsym);
  2092. end;
  2093. { Step 2, Update externals }
  2094. for i:=0 to ExternalObjSymbols.count-1 do
  2095. begin
  2096. objsym:=TObjSymbol(ExternalObjSymbols[i]);
  2097. if objsym.bind<>AB_EXTERNAL then
  2098. internalerror(200606242);
  2099. UpdateSymbol(objsym);
  2100. end;
  2101. end;
  2102. procedure TExeOutput.MergeStabs;
  2103. var
  2104. stabexesec,
  2105. stabstrexesec : TExeSection;
  2106. relocsec,
  2107. currstabsec,
  2108. currstabstrsec,
  2109. mergedstabsec,
  2110. mergedstabstrsec : TObjSection;
  2111. hstabreloc,
  2112. currstabreloc : TObjRelocation;
  2113. i,j : longint;
  2114. currstabrelocidx,
  2115. mergestabcnt,
  2116. stabcnt : longword;
  2117. skipstab : boolean;
  2118. skipfun : boolean;
  2119. hstab : TObjStabEntry;
  2120. stabrelocofs : longword;
  2121. buf : array[0..1023] of byte;
  2122. bufend,
  2123. bufsize : longint;
  2124. begin
  2125. stabexesec:=FindExeSection('.stab');
  2126. stabstrexesec:=FindExeSection('.stabstr');
  2127. if (stabexesec=nil) or
  2128. (stabstrexesec=nil) or
  2129. (stabexesec.ObjSectionlist.count=0) then
  2130. exit;
  2131. { Create new stabsection }
  2132. stabRelocofs:=pbyte(@hstab.nvalue)-pbyte(@hstab);
  2133. mergedstabsec:=internalObjData.CreateSection(sec_stab,'');
  2134. mergedstabstrsec:=internalObjData.CreateSection(sec_stabstr,'');
  2135. { write stab for hdrsym }
  2136. fillchar(hstab,sizeof(TObjStabEntry),0);
  2137. mergedstabsec.write(hstab,sizeof(TObjStabEntry));
  2138. mergestabcnt:=1;
  2139. { .stabstr starts with a #0 }
  2140. buf[0]:=0;
  2141. mergedstabstrsec.write(buf[0],1);
  2142. skipfun:=false;
  2143. { Copy stabs and corresponding Relocations }
  2144. for i:=0 to stabexesec.ObjSectionList.Count-1 do
  2145. begin
  2146. currstabsec:=TObjSection(stabexesec.ObjSectionList[i]);
  2147. currstabstrsec:=currstabsec.ObjData.findsection('.stabstr');
  2148. if assigned(currstabstrsec) then
  2149. begin
  2150. stabcnt:=currstabsec.Data.size div sizeof(TObjStabEntry);
  2151. currstabsec.Data.seek(0);
  2152. currstabrelocidx:=0;
  2153. for j:=0 to stabcnt-1 do
  2154. begin
  2155. hstabreloc:=nil;
  2156. skipstab:=false;
  2157. currstabsec.Data.read(hstab,sizeof(TObjStabEntry));
  2158. { Only include first hdrsym stab }
  2159. if hstab.ntype=0 then
  2160. skipstab:=true;
  2161. if skipfun then
  2162. begin
  2163. { Skip all stabs for function body until N_RBRAC }
  2164. skipfun:=hstab.ntype<>N_RBRAC;
  2165. skipstab:=true;
  2166. end;
  2167. if not skipstab then
  2168. begin
  2169. { Find corresponding Relocation }
  2170. currstabreloc:=nil;
  2171. while (currstabrelocidx<longword(currstabsec.ObjRelocations.Count)) do
  2172. begin
  2173. currstabreloc:=TObjRelocation(currstabsec.ObjRelocations[currstabrelocidx]);
  2174. if assigned(currstabreloc) and
  2175. (currstabreloc.dataoffset>=longword(j)*sizeof(TObjStabEntry)+stabrelocofs) then
  2176. break;
  2177. inc(currstabrelocidx);
  2178. end;
  2179. if assigned(currstabreloc) and
  2180. (currstabreloc.dataoffset=longword(j)*sizeof(TObjStabEntry)+stabrelocofs) then
  2181. begin
  2182. hstabReloc:=currstabReloc;
  2183. inc(currstabrelocidx);
  2184. end;
  2185. { Check if the stab is refering to a removed section }
  2186. if assigned(hstabreloc) then
  2187. begin
  2188. if assigned(hstabreloc.Symbol) then
  2189. relocsec:=hstabreloc.Symbol.ObjSection
  2190. else
  2191. relocsec:=hstabreloc.ObjSection;
  2192. if not assigned(relocsec) then
  2193. internalerror(200603302);
  2194. if not relocsec.Used then
  2195. begin
  2196. skipstab:=true;
  2197. if (hstab.ntype=N_Function) and (hstab.strpos<>0) then
  2198. begin
  2199. currstabstrsec.Data.seek(hstab.strpos);
  2200. bufsize:=currstabstrsec.Data.read(buf,sizeof(buf));
  2201. bufend:=indexbyte(buf,bufsize,Ord(':'));
  2202. if (bufend<>-1) and (bufend<bufsize-1) and (buf[bufend+1]=Ord('F')) then
  2203. skipfun:=true;
  2204. end;
  2205. end;
  2206. end;
  2207. end;
  2208. if not skipstab then
  2209. begin
  2210. { Copy string in stabstr }
  2211. if hstab.strpos<>0 then
  2212. begin
  2213. currstabstrsec.Data.seek(hstab.strpos);
  2214. hstab.strpos:=mergedstabstrsec.Size;
  2215. repeat
  2216. bufsize:=currstabstrsec.Data.read(buf,sizeof(buf));
  2217. bufend:=indexbyte(buf,bufsize,0);
  2218. if bufend=-1 then
  2219. bufend:=bufsize
  2220. else
  2221. begin
  2222. { include the #0 }
  2223. inc(bufend);
  2224. end;
  2225. mergedstabstrsec.write(buf,bufend);
  2226. until (buf[bufend-1]=0) or (bufsize<sizeof(buf));
  2227. end;
  2228. { Copy and Update the relocation }
  2229. if assigned(hstabreloc) then
  2230. begin
  2231. hstabreloc.Dataoffset:=mergestabcnt*sizeof(TObjStabEntry)+stabRelocofs;
  2232. { Remove from List without freeing the object }
  2233. currstabsec.ObjRelocations.List[currstabrelocidx-1]:=nil;
  2234. mergedstabsec.ObjRelocations.Add(hstabreloc);
  2235. end;
  2236. { Write updated stab }
  2237. mergedstabsec.write(hstab,sizeof(hstab));
  2238. inc(mergestabcnt);
  2239. end;
  2240. end;
  2241. end;
  2242. { Unload stabs }
  2243. if assigned(currstabstrsec) then
  2244. begin
  2245. currstabstrsec.Used:=False;
  2246. currstabstrsec.ReleaseData;
  2247. end;
  2248. currstabsec.Used:=false;
  2249. currstabsec.ReleaseData;
  2250. end;
  2251. { Generate new HdrSym }
  2252. if mergedstabsec.Size>0 then
  2253. begin
  2254. hstab.strpos:=1;
  2255. hstab.ntype:=0;
  2256. hstab.nother:=0;
  2257. hstab.ndesc:=word(mergestabcnt-1);
  2258. hstab.nvalue:=mergedstabstrsec.Size;
  2259. mergedstabsec.Data.seek(0);
  2260. mergedstabsec.Data.write(hstab,sizeof(hstab));
  2261. end;
  2262. { Replace all sections with our combined stabsec }
  2263. stabexesec.ObjSectionList.Clear;
  2264. stabstrexesec.ObjSectionList.Clear;
  2265. stabexesec.AddObjSection(mergedstabsec);
  2266. stabstrexesec.AddObjSection(mergedstabstrsec);
  2267. end;
  2268. procedure TExeOutput.RemoveEmptySections;
  2269. var
  2270. i, j : longint;
  2271. exesec : TExeSection;
  2272. doremove : boolean;
  2273. begin
  2274. for i:=0 to ExeSectionList.Count-1 do
  2275. begin
  2276. exesec:=TExeSection(ExeSectionList[i]);
  2277. doremove:=not(oso_keep in exesec.SecOptions) and
  2278. (
  2279. (exesec.ObjSectionlist.count=0) or
  2280. (
  2281. (cs_link_strip in current_settings.globalswitches) and
  2282. not(cs_link_separate_dbg_file in current_settings.globalswitches) and
  2283. (oso_debug in exesec.SecOptions)
  2284. )
  2285. );
  2286. if not doremove then
  2287. begin
  2288. { Check if section has no actual data }
  2289. doremove:=true;
  2290. for j:=0 to exesec.ObjSectionList.Count-1 do
  2291. if TObjSection(exesec.ObjSectionList[j]).Size<>0 then
  2292. begin
  2293. doremove:=false;
  2294. break;
  2295. end;
  2296. end;
  2297. if doremove and not (RelocSection and (exesec.Name='.reloc')) then
  2298. begin
  2299. Comment(V_Debug,'Deleting empty section '+exesec.name);
  2300. ExeSectionList[i]:=nil;
  2301. end;
  2302. end;
  2303. ExeSectionList.Pack;
  2304. end;
  2305. procedure TExeOutput.RemoveDebugInfo;
  2306. var
  2307. i : longint;
  2308. exesec : TExeSection;
  2309. begin
  2310. for i:=0 to ExeSectionList.Count-1 do
  2311. begin
  2312. exesec:=TExeSection(ExeSectionList[i]);
  2313. if (oso_debug in exesec.SecOptions) then
  2314. ExeSectionList[i]:=nil;
  2315. end;
  2316. ExeSectionList.Pack;
  2317. end;
  2318. procedure TExeOutput.RemoveUnreferencedSections;
  2319. var
  2320. ObjSectionWorkList : TFPObjectList;
  2321. procedure AddToObjSectionWorkList(aobjsec:TObjSection);
  2322. begin
  2323. if not aobjsec.Used then
  2324. begin
  2325. aobjsec.Used:=true;
  2326. ObjSectionWorkList.Add(aobjsec);
  2327. end;
  2328. end;
  2329. procedure DoReloc(objreloc:TObjRelocation);
  2330. var
  2331. objsym : TObjSymbol;
  2332. refobjsec : TObjSection;
  2333. begin
  2334. { Disabled Relocation to 0 }
  2335. if objreloc.typ=RELOC_ZERO then
  2336. exit;
  2337. if assigned(objreloc.symbol) then
  2338. begin
  2339. objsym:=objreloc.symbol;
  2340. if objsym.bind<>AB_LOCAL then
  2341. begin
  2342. if not(assigned(objsym.exesymbol) and
  2343. (objsym.exesymbol.State=symstate_defined)) then
  2344. internalerror(200603063);
  2345. objsym:=objsym.exesymbol.objsymbol;
  2346. end;
  2347. if not assigned(objsym.objsection) then
  2348. internalerror(200603062);
  2349. refobjsec:=objsym.objsection;
  2350. end
  2351. else
  2352. if assigned(objreloc.objsection) then
  2353. refobjsec:=objreloc.objsection
  2354. else
  2355. internalerror(200603316);
  2356. if assigned(exemap) then
  2357. begin
  2358. objsym:=objreloc.symbol;
  2359. if assigned(objsym) then
  2360. exemap.Add(' References '+objsym.name+' in '
  2361. +refobjsec.fullname)
  2362. else
  2363. exemap.Add(' References '+refobjsec.fullname);
  2364. end;
  2365. AddToObjSectionWorkList(refobjsec);
  2366. end;
  2367. procedure DoVTableRef(vtable:TExeVTable;VTableIdx:longint);
  2368. var
  2369. i : longint;
  2370. objreloc : TObjRelocation;
  2371. begin
  2372. objreloc:=vtable.VTableRef(VTableIdx);
  2373. if assigned(objreloc) then
  2374. begin
  2375. { Process the relocation now if the ObjSection is
  2376. already processed and marked as used. Otherwise we leave it
  2377. unprocessed. It'll then be resolved when the ObjSection is
  2378. changed to Used }
  2379. if vtable.ExeSymbol.ObjSymbol.ObjSection.Used then
  2380. DoReloc(objreloc);
  2381. end;
  2382. { This recursive walking is done here instead of
  2383. in TExeVTable.VTableRef because we can now process
  2384. all needed relocations }
  2385. for i:=0 to vtable.ChildList.Count-1 do
  2386. DoVTableRef(TExeVTable(vtable.ChildList[i]),VTableIdx);
  2387. end;
  2388. var
  2389. hs : string;
  2390. i,j,k : longint;
  2391. exesec : TExeSection;
  2392. objdata : TObjData;
  2393. objsec : TObjSection;
  2394. objsym : TObjSymbol;
  2395. code : integer;
  2396. vtableidx : longint;
  2397. vtableexesym : TExeSymbol;
  2398. begin
  2399. ObjSectionWorkList:=TFPObjectList.Create(false);
  2400. if assigned(exemap) then
  2401. exemap.AddHeader('Removing unreferenced sections');
  2402. { Initialize by marking all sections unused and
  2403. adding the sections with oso_keep flags to the ObjSectionWorkList }
  2404. for i:=0 to ObjDataList.Count-1 do
  2405. begin
  2406. ObjData:=TObjData(ObjDataList[i]);
  2407. for j:=0 to ObjData.ObjSectionList.Count-1 do
  2408. begin
  2409. objsec:=TObjSection(ObjData.ObjSectionList[j]);
  2410. objsec.Used:=false;
  2411. { TODO: remove debug section always keep}
  2412. if oso_debug in objsec.secoptions then
  2413. objsec.Used:=true;
  2414. if (oso_keep in objsec.secoptions) then
  2415. begin
  2416. AddToObjSectionWorkList(objsec);
  2417. if objsec.name='.fpc.n_links' then
  2418. objsec.Used:=false;
  2419. end;
  2420. end;
  2421. end;
  2422. AddToObjSectionWorkList(entrysym.exesymbol.objsymbol.objsection);
  2423. { Process all sections, add new sections to process based
  2424. on the symbol references }
  2425. while ObjSectionWorkList.Count>0 do
  2426. begin
  2427. objsec:=TObjSection(ObjSectionWorkList.Last);
  2428. if assigned(exemap) then
  2429. exemap.Add('Keeping '+objsec.FullName+' '+ToStr(objsec.ObjRelocations.Count)+' references');
  2430. ObjSectionWorkList.Delete(ObjSectionWorkList.Count-1);
  2431. { Process Relocations }
  2432. for i:=0 to objsec.ObjRelocations.count-1 do
  2433. DoReloc(TObjRelocation(objsec.ObjRelocations[i]));
  2434. { Process Virtual Entry calls }
  2435. if cs_link_opt_vtable in current_settings.globalswitches then
  2436. begin
  2437. for i:=0 to objsec.VTRefList.count-1 do
  2438. begin
  2439. objsym:=TObjSymbol(objsec.VTRefList[i]);
  2440. hs:=objsym.name;
  2441. Delete(hs,1,Pos('_',hs));
  2442. k:=Pos('$$',hs);
  2443. if k=0 then
  2444. internalerror(200603314);
  2445. vtableexesym:=texesymbol(FExeSymbolList.Find(Copy(hs,1,k-1)));
  2446. val(Copy(hs,k+2,length(hs)-k-1),vtableidx,code);
  2447. if (code<>0) then
  2448. internalerror(200603317);
  2449. if not assigned(vtableexesym) then
  2450. internalerror(200603315);
  2451. if not assigned(vtableexesym.vtable) then
  2452. internalerror(200603316);
  2453. DoVTableRef(vtableexesym.vtable,vtableidx);
  2454. end;
  2455. end;
  2456. end;
  2457. ObjSectionWorkList.Free;
  2458. ObjSectionWorkList:=nil;
  2459. { Remove unused objsections from ExeSectionList }
  2460. for i:=0 to ExeSectionList.Count-1 do
  2461. begin
  2462. exesec:=TExeSection(ExeSectionList[i]);
  2463. for j:=0 to exesec.ObjSectionlist.count-1 do
  2464. begin
  2465. objsec:=TObjSection(exesec.ObjSectionlist[j]);
  2466. if not objsec.used then
  2467. begin
  2468. if assigned(exemap) then
  2469. exemap.Add('Removing '+objsec.FullName);
  2470. exesec.ObjSectionlist[j]:=nil;
  2471. objsec.ReleaseData;
  2472. end;
  2473. end;
  2474. exesec.ObjSectionlist.Pack;
  2475. end;
  2476. end;
  2477. procedure TExeOutput.FixupRelocations;
  2478. var
  2479. i,j : longint;
  2480. exesec : TExeSection;
  2481. objsec : TObjSection;
  2482. begin
  2483. for i:=0 to ExeSectionList.Count-1 do
  2484. begin
  2485. exesec:=TExeSection(ExeSectionList[i]);
  2486. if not assigned(exesec) then
  2487. continue;
  2488. for j:=0 to exesec.ObjSectionlist.count-1 do
  2489. begin
  2490. objsec:=TObjSection(exesec.ObjSectionlist[j]);
  2491. if not objsec.Used then
  2492. internalerror(200603301);
  2493. objsec.FixupRelocs;
  2494. end;
  2495. end;
  2496. end;
  2497. procedure TExeOutput.SetCurrMemPos(const AValue: qword);
  2498. begin
  2499. if AValue>MaxMemPos then
  2500. Message1(link_f_executable_too_big, target_os_string);
  2501. FCurrMemPos:=AValue;
  2502. end;
  2503. {****************************************************************************
  2504. TObjInput
  2505. ****************************************************************************}
  2506. constructor TObjInput.create;
  2507. begin
  2508. end;
  2509. destructor TObjInput.destroy;
  2510. begin
  2511. inherited destroy;
  2512. end;
  2513. function TObjInput.newObjData(const n:string):TObjData;
  2514. begin
  2515. result:=CObjData.create(n);
  2516. end;
  2517. procedure TObjInput.inputerror(const s : string);
  2518. begin
  2519. Comment(V_Error,s+' while reading '+InputFileName);
  2520. end;
  2521. {$ifdef MEMDEBUG}
  2522. initialization
  2523. memobjsymbols:=TMemDebug.create('ObjSymbols');
  2524. memobjsymbols.stop;
  2525. memobjsections:=TMemDebug.create('ObjSections');
  2526. memobjsections.stop;
  2527. finalization
  2528. memobjsymbols.free;
  2529. memobjsections.free;
  2530. {$endif MEMDEBUG}
  2531. end.