ogbase.pas 114 KB

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