ogbase.pas 93 KB

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