ogbase.pas 113 KB

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