ogbase.pas 100 KB

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