ogbase.pas 111 KB

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