ogbase.pas 79 KB

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