ogbase.pas 89 KB

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