ogbase.pas 94 KB

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