ogbase.pas 122 KB

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