ogbase.pas 118 KB

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