ogbase.pas 99 KB

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