ogbase.pas 100 KB

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