ogbase.pas 112 KB

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