ogbase.pas 116 KB

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