ogbase.pas 122 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623
  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 not assigned(asmsym.cachedObjSymbol) then
  1209. begin
  1210. result:=symboldefine(asmsym.name,asmsym.bind,asmsym.typ);
  1211. asmsym.cachedObjSymbol:=result;
  1212. FCachedAsmSymbolList.add(asmsym);
  1213. end
  1214. else
  1215. begin
  1216. result:=TObjSymbol(asmsym.cachedObjSymbol);
  1217. result.SetAddress(CurrPass,CurrObjSec,asmsym.bind,asmsym.typ);
  1218. end;
  1219. end
  1220. else
  1221. result:=nil;
  1222. end;
  1223. function TObjData.symboldefine(const aname:string;abind:TAsmsymbind;atyp:Tasmsymtype):TObjSymbol;
  1224. begin
  1225. if not assigned(CurrObjSec) then
  1226. internalerror(200603051);
  1227. result:=CreateSymbol(aname);
  1228. result.SetAddress(CurrPass,CurrObjSec,abind,atyp);
  1229. end;
  1230. function TObjData.symbolref(asmsym:TAsmSymbol):TObjSymbol;
  1231. var
  1232. s:string;
  1233. begin
  1234. if assigned(asmsym) then
  1235. begin
  1236. if not assigned(asmsym.cachedObjSymbol) then
  1237. begin
  1238. s:=asmsym.name;
  1239. result:=TObjSymbol(FObjSymbolList.Find(s));
  1240. if result=nil then
  1241. begin
  1242. result:=CObjSymbol.Create(FObjSymbolList,s);
  1243. if asmsym.bind=AB_WEAK_EXTERNAL then
  1244. result.bind:=AB_WEAK_EXTERNAL;
  1245. end;
  1246. asmsym.cachedObjSymbol:=result;
  1247. FCachedAsmSymbolList.add(asmsym);
  1248. end
  1249. else
  1250. result:=TObjSymbol(asmsym.cachedObjSymbol);
  1251. { The weak bit could have been removed from asmsym. }
  1252. if (asmsym.bind=AB_EXTERNAL) and (result.bind=AB_WEAK_EXTERNAL) then
  1253. result.bind:=AB_EXTERNAL;
  1254. end
  1255. else
  1256. result:=nil;
  1257. end;
  1258. function TObjData.symbolref(const aname:string):TObjSymbol;
  1259. begin
  1260. if not assigned(CurrObjSec) then
  1261. internalerror(200603052);
  1262. result:=CreateSymbol(aname);
  1263. end;
  1264. procedure TObjData.ResetCachedAsmSymbols;
  1265. var
  1266. i : longint;
  1267. begin
  1268. for i:=0 to FCachedAsmSymbolList.Count-1 do
  1269. tasmsymbol(FCachedAsmSymbolList[i]).cachedObjSymbol:=nil;
  1270. FCachedAsmSymbolList.Clear;
  1271. end;
  1272. procedure TObjData.writebytes(const Data;len:aword);
  1273. begin
  1274. if not assigned(CurrObjSec) then
  1275. internalerror(200402251);
  1276. CurrObjSec.write(Data,len);
  1277. end;
  1278. procedure TObjData.alloc(len:aword);
  1279. begin
  1280. if not assigned(CurrObjSec) then
  1281. internalerror(200402252);
  1282. CurrObjSec.alloc(len);
  1283. end;
  1284. procedure TObjData.allocalign(len:longint);
  1285. begin
  1286. if not assigned(CurrObjSec) then
  1287. internalerror(200402253);
  1288. CurrObjSec.alloc(align_objsecofs(CurrObjSec.size,len)-CurrObjSec.size);
  1289. end;
  1290. procedure TObjData.section_afteralloc(p:TObject;arg:pointer);
  1291. begin
  1292. with TObjSection(p) do
  1293. alloc(align_objsecofs(size,secalign)-size);
  1294. end;
  1295. procedure TObjData.section_afterwrite(p:TObject;arg:pointer);
  1296. begin
  1297. with TObjSection(p) do
  1298. begin
  1299. if assigned(Data) then
  1300. writezeros(align_objsecofs(size,secalign)-size);
  1301. end;
  1302. end;
  1303. procedure TObjData.section_reset(p:TObject;arg:pointer);
  1304. begin
  1305. with TObjSection(p) do
  1306. begin
  1307. Size:=0;
  1308. Datapos:=0;
  1309. mempos:=0;
  1310. if assigned(Data) then
  1311. Data.reset;
  1312. end;
  1313. end;
  1314. procedure TObjData.beforealloc;
  1315. begin
  1316. FCPUType:=current_settings.cputype;
  1317. { create stabs sections if debugging }
  1318. if assigned(StabsSec) then
  1319. begin
  1320. StabsSec.Alloc(sizeof(TObjStabEntry));
  1321. StabStrSec.Alloc(1);
  1322. end;
  1323. end;
  1324. procedure TObjData.beforewrite;
  1325. begin
  1326. FCPUType:=current_settings.cputype;
  1327. { create stabs sections if debugging }
  1328. if assigned(StabsSec) then
  1329. begin
  1330. { Create dummy HdrSym stab, it will be overwritten in AfterWrite }
  1331. StabsSec.WriteZeros(sizeof(TObjStabEntry));
  1332. { start of stabstr }
  1333. StabStrSec.writeZeros(1);
  1334. end;
  1335. end;
  1336. procedure TObjData.afteralloc;
  1337. begin
  1338. FObjSectionList.ForEachCall(@section_afteralloc,nil);
  1339. end;
  1340. procedure TObjData.afterwrite;
  1341. var
  1342. hstab : TObjStabEntry;
  1343. begin
  1344. FObjSectionList.ForEachCall(@section_afterwrite,nil);
  1345. { For the stab section we need an HdrSym which can now be
  1346. calculated more easily }
  1347. if assigned(StabsSec) then
  1348. begin
  1349. { end of stabstr }
  1350. StabStrSec.writeZeros(1);
  1351. { header stab }
  1352. hstab.strpos:=1;
  1353. hstab.ntype:=0;
  1354. hstab.nother:=0;
  1355. {$push}{$R-}
  1356. { for jwawindows.pas, this causes an range check error, it contains too much stab symbols }
  1357. hstab.ndesc:=(StabsSec.Size div sizeof(TObjStabEntry))-1;
  1358. {$pop}
  1359. hstab.nvalue:=StabStrSec.Size;
  1360. MaybeSwapStab(hstab);
  1361. StabsSec.Data.seek(0);
  1362. StabsSec.Data.write(hstab,sizeof(hstab));
  1363. end;
  1364. end;
  1365. procedure TObjData.resetsections;
  1366. begin
  1367. FObjSectionList.ForEachCall(@section_reset,nil);
  1368. end;
  1369. procedure TObjData.layoutsections(var DataPos:TObjSectionOfs);
  1370. var
  1371. i: longint;
  1372. begin
  1373. for i:=0 to FObjSectionList.Count-1 do
  1374. TObjSection(FObjSectionList[i]).setDatapos(DataPos);
  1375. end;
  1376. {****************************************************************************
  1377. TObjOutput
  1378. ****************************************************************************}
  1379. constructor TObjOutput.create(AWriter:TObjectWriter);
  1380. begin
  1381. FWriter:=AWriter;
  1382. CObjData:=TObjData;
  1383. end;
  1384. destructor TObjOutput.destroy;
  1385. begin
  1386. inherited destroy;
  1387. end;
  1388. function TObjOutput.newObjData(const n:string):TObjData;
  1389. begin
  1390. result:=CObjData.create(n);
  1391. if (cs_use_lineinfo in current_settings.globalswitches) or
  1392. (cs_debuginfo in current_settings.moduleswitches) then
  1393. result.CreateDebugSections;
  1394. end;
  1395. function TObjOutput.startObjectfile(const fn:string):boolean;
  1396. begin
  1397. result:=false;
  1398. { start the writer already, so the .a generation can initialize
  1399. the position of the current objectfile }
  1400. if not FWriter.createfile(fn) then
  1401. Comment(V_Fatal,'Can''t create object '+fn);
  1402. result:=true;
  1403. end;
  1404. function TObjOutput.writeobjectfile(Data:TObjData):boolean;
  1405. begin
  1406. if errorcount=0 then
  1407. result:=writeData(Data)
  1408. else
  1409. result:=true;
  1410. { close the writer }
  1411. FWriter.closefile;
  1412. end;
  1413. procedure TObjOutput.exportsymbol(p:TObjSymbol);
  1414. begin
  1415. { export globals and common symbols, this is needed
  1416. for .a files }
  1417. if p.bind in [AB_GLOBAL,AB_COMMON] then
  1418. FWriter.writesym(p.name);
  1419. end;
  1420. procedure TObjOutput.WriteSectionContent(Data:TObjData);
  1421. var
  1422. i:longint;
  1423. sec:TObjSection;
  1424. begin
  1425. for i:=0 to Data.ObjSectionList.Count-1 do
  1426. begin
  1427. sec:=TObjSection(Data.ObjSectionList[i]);
  1428. if (oso_data in sec.SecOptions) then
  1429. begin
  1430. if sec.Data=nil then
  1431. internalerror(200403073);
  1432. FWriter.writezeros(sec.dataalignbytes);
  1433. if sec.Datapos<>FWriter.ObjSize then
  1434. internalerror(200604031);
  1435. FWriter.writearray(sec.data);
  1436. end;
  1437. end;
  1438. end;
  1439. {****************************************************************************
  1440. TExeVTable
  1441. ****************************************************************************}
  1442. constructor TExeVTable.Create(AExeSymbol:TExeSymbol);
  1443. begin
  1444. ExeSymbol:=AExeSymbol;
  1445. if ExeSymbol.State=symstate_undefined then
  1446. internalerror(200604012);
  1447. ChildList:=TFPObjectList.Create(false);
  1448. end;
  1449. destructor TExeVTable.Destroy;
  1450. begin
  1451. ChildList.Free;
  1452. if assigned(EntryArray) then
  1453. Freemem(EntryArray);
  1454. end;
  1455. procedure TExeVTable.CheckIdx(VTableIdx:longint);
  1456. var
  1457. OldEntryCnt : longint;
  1458. begin
  1459. if VTableIdx>=EntryCnt then
  1460. begin
  1461. OldEntryCnt:=EntryCnt;
  1462. EntryCnt:=VTableIdx+1;
  1463. ReAllocMem(EntryArray,EntryCnt*sizeof(TVTableEntry));
  1464. FillChar(EntryArray[OldEntryCnt],(EntryCnt-OldEntryCnt)*sizeof(TVTableEntry),0);
  1465. end;
  1466. end;
  1467. procedure TExeVTable.AddChild(vt:TExeVTable);
  1468. begin
  1469. ChildList.Add(vt);
  1470. end;
  1471. procedure TExeVTable.AddEntry(VTableIdx:Longint);
  1472. var
  1473. i : longint;
  1474. objreloc : TObjRelocation;
  1475. vtblentryoffset : aword;
  1476. begin
  1477. CheckIdx(VTableIdx);
  1478. vtblentryoffset:=ExeSymbol.ObjSymbol.Offset+longword(VTableIdx)*sizeof(pint);
  1479. { Find and disable relocation }
  1480. for i:=0 to ExeSymbol.ObjSymbol.ObjSection.ObjRelocations.Count-1 do
  1481. begin
  1482. objreloc:=TObjRelocation(ExeSymbol.ObjSymbol.ObjSection.ObjRelocations[i]);
  1483. if objreloc.dataoffset=vtblentryoffset then
  1484. begin
  1485. EntryArray[VTableIdx].ObjRelocation:=objreloc;
  1486. EntryArray[VTableIdx].OrgRelocType:=objreloc.ftype;
  1487. EntryArray[VTableIdx].OrgRelocFlags:=objreloc.flags;
  1488. objreloc.typ:=RELOC_ZERO;
  1489. objreloc.flags:=objreloc.flags or rf_nosymbol;
  1490. break;
  1491. end;
  1492. end;
  1493. if not assigned(EntryArray[VTableIdx].ObjRelocation) then
  1494. internalerror(200604011);
  1495. end;
  1496. procedure TExeVTable.SetVTableSize(ASize:longint);
  1497. begin
  1498. if EntryCnt<>0 then
  1499. internalerror(200603313);
  1500. EntryCnt:=ASize div sizeof(pint);
  1501. EntryArray:=AllocMem(EntryCnt*sizeof(TVTableEntry));
  1502. end;
  1503. function TExeVTable.VTableRef(VTableIdx:Longint):TObjRelocation;
  1504. begin
  1505. result:=nil;
  1506. CheckIdx(VTableIdx);
  1507. if EntryArray[VTableIdx].Used then
  1508. exit;
  1509. { Restore relocation if available }
  1510. if assigned(EntryArray[VTableIdx].ObjRelocation) then
  1511. begin
  1512. EntryArray[VTableIdx].ObjRelocation.ftype:=EntryArray[VTableIdx].OrgRelocType;
  1513. EntryArray[VTableIdx].ObjRelocation.flags:=EntryArray[VTableIdx].OrgRelocFlags;
  1514. result:=EntryArray[VTableIdx].ObjRelocation;
  1515. end;
  1516. EntryArray[VTableIdx].Used:=true;
  1517. end;
  1518. {****************************************************************************
  1519. TExeSection
  1520. ****************************************************************************}
  1521. constructor TExeSection.create(AList:TFPHashObjectList;const AName:string);
  1522. begin
  1523. inherited create(AList,AName);
  1524. Size:=0;
  1525. MemPos:=0;
  1526. DataPos:=0;
  1527. FSecSymIdx:=0;
  1528. FObjSectionList:=TFPObjectList.Create(false);
  1529. end;
  1530. destructor TExeSection.destroy;
  1531. begin
  1532. ObjSectionList.Free;
  1533. inherited destroy;
  1534. end;
  1535. procedure TExeSection.AddObjSection(objsec:TObjSection;ignoreprops:boolean);
  1536. begin
  1537. ObjSectionList.Add(objsec);
  1538. { relate ObjSection to ExeSection, and mark it Used by default }
  1539. objsec.ExeSection:=self;
  1540. objsec.Used:=true;
  1541. if ignoreprops then
  1542. exit;
  1543. if (SecOptions<>[]) then
  1544. begin
  1545. { Only if the section contains (un)initialized data the
  1546. data flag must match. }
  1547. if ((oso_Data in SecOptions)<>(oso_Data in objsec.SecOptions)) then
  1548. Comment(V_Error,'Incompatible section options');
  1549. end
  1550. else
  1551. begin
  1552. { inherit section options }
  1553. SecOptions:=SecOptions+objsec.SecOptions;
  1554. end;
  1555. SecAlign:=max(objsec.SecAlign,SecAlign);
  1556. end;
  1557. {****************************************************************************
  1558. TStaticLibrary
  1559. ****************************************************************************}
  1560. constructor TStaticLibrary.create(const AName:TCmdStr;AReader:TObjectReader;AObjInputClass:TObjInputClass);
  1561. begin
  1562. FName:=AName;
  1563. FPayload:=AReader;
  1564. FObjInputClass:=AObjInputClass;
  1565. FKind:=lkArchive;
  1566. end;
  1567. constructor TStaticLibrary.create_object(AObjData:TObjData);
  1568. begin
  1569. FPayload:=AObjData;
  1570. FKind:=lkObject;
  1571. end;
  1572. constructor TStaticLibrary.create_group;
  1573. begin
  1574. FPayload:=TFPObjectList.Create(true);
  1575. FKind:=lkGroup;
  1576. end;
  1577. destructor TStaticLibrary.destroy;
  1578. begin
  1579. FPayload.Free;
  1580. inherited destroy;
  1581. end;
  1582. function TStaticLibrary.GetArReader: TObjectReader;
  1583. begin
  1584. if (FKind<>lkArchive) then
  1585. InternalError(2012071501);
  1586. result:=TObjectReader(FPayload);
  1587. end;
  1588. function TStaticLibrary.GetGroupMembers: TFPObjectList;
  1589. begin
  1590. if (FKind<>lkGroup) then
  1591. InternalError(2012071502);
  1592. result:=TFPObjectList(FPayload);
  1593. end;
  1594. function TStaticLibrary.GetObjData: TObjData;
  1595. begin
  1596. if (FKind<>lkObject) then
  1597. InternalError(2012071503);
  1598. result:=TObjData(FPayload);
  1599. end;
  1600. {****************************************************************************
  1601. TImportLibrary
  1602. ****************************************************************************}
  1603. constructor TImportLibrary.create(AList:TFPHashObjectList;const AName:string);
  1604. begin
  1605. inherited create(AList,AName);
  1606. FImportSymbolList:=TFPHashObjectList.Create(true);
  1607. end;
  1608. destructor TImportLibrary.destroy;
  1609. begin
  1610. ImportSymbolList.Free;
  1611. inherited destroy;
  1612. end;
  1613. {****************************************************************************
  1614. TImportSymbol
  1615. ****************************************************************************}
  1616. constructor TImportSymbol.create(AList:TFPHashObjectList;
  1617. const AName,AMangledName:string;AOrdNr:longint;AIsVar:boolean);
  1618. begin
  1619. inherited Create(AList, AName);
  1620. FOrdNr:=AOrdNr;
  1621. FIsVar:=AIsVar;
  1622. FMangledName:=AMangledName;
  1623. { Replace ? and @ in import name, since GNU AS does not allow these characters in symbol names. }
  1624. { This allows to import VC++ mangled names from DLLs. }
  1625. if target_info.system in systems_all_windows then
  1626. begin
  1627. Replace(FMangledName,'?','__q$$');
  1628. {$ifdef arm}
  1629. { @ symbol is not allowed in ARM assembler only }
  1630. Replace(FMangledName,'@','__a$$');
  1631. {$endif arm}
  1632. end;
  1633. end;
  1634. {****************************************************************************
  1635. TExeOutput
  1636. ****************************************************************************}
  1637. constructor TExeOutput.create;
  1638. begin
  1639. { init writer }
  1640. FWriter:=TObjectwriter.create;
  1641. FExeWriteMode:=ewm_exefull;
  1642. { object files }
  1643. FObjDataList:=TFPObjectList.Create(true);
  1644. { symbols }
  1645. FExeSymbolList:=TFPHashObjectList.Create(true);
  1646. FUnresolvedExeSymbols:=TFPObjectList.Create(false);
  1647. FExternalObjSymbols:=TFPObjectList.Create(false);
  1648. FCommonObjSymbols:=TFPObjectList.Create(false);
  1649. FProvidedObjSymbols:=TFPObjectList.Create(false);
  1650. FIndirectObjSymbols:=TFPObjectList.Create(false);
  1651. FExeVTableList:=TFPObjectList.Create(false);
  1652. ComdatGroups:=TFPHashList.Create;
  1653. { sections }
  1654. FExeSectionList:=TFPHashObjectList.Create(true);
  1655. FImageBase:=0;
  1656. {$ifdef cpu16bitaddr}
  1657. SectionMemAlign:=$10;
  1658. SectionDataAlign:=$10;
  1659. {$else cpu16bitaddr}
  1660. SectionMemAlign:=$1000;
  1661. SectionDataAlign:=$200;
  1662. {$endif cpu16bitaddr}
  1663. FixedSectionAlign:=True;
  1664. FCExeSection:=TExeSection;
  1665. FCObjData:=TObjData;
  1666. FCObjSymbol:=TObjSymbol;
  1667. end;
  1668. destructor TExeOutput.destroy;
  1669. begin
  1670. FExeSymbolList.free;
  1671. UnresolvedExeSymbols.free;
  1672. ExternalObjSymbols.free;
  1673. FProvidedObjSymbols.free;
  1674. FIndirectObjSymbols.free;
  1675. CommonObjSymbols.free;
  1676. ExeVTableList.free;
  1677. FExeSectionList.free;
  1678. ComdatGroups.free;
  1679. ObjDatalist.free;
  1680. FWriter.free;
  1681. inherited destroy;
  1682. end;
  1683. function TExeOutput.MemAlign(exesec:TExeSection):longword;
  1684. begin
  1685. if FixedSectionAlign then
  1686. result:=SectionMemAlign
  1687. else
  1688. result:=exesec.SecAlign;
  1689. end;
  1690. function TExeOutput.DataAlign(exesec:TExeSection):longword;
  1691. begin
  1692. if FixedSectionAlign then
  1693. result:=SectionDataAlign
  1694. else
  1695. result:=exesec.SecAlign;
  1696. end;
  1697. function TExeOutput.WriteExeFile(const fn:string):boolean;
  1698. begin
  1699. result:=false;
  1700. if FWriter.createfile(fn) then
  1701. begin
  1702. { Only write the .o if there are no errors }
  1703. if errorcount=0 then
  1704. result:=writedata
  1705. else
  1706. result:=true;
  1707. { close the writer }
  1708. FWriter.closefile;
  1709. end
  1710. else
  1711. Comment(V_Fatal,'Can''t create executable '+fn);
  1712. end;
  1713. procedure TExeOutput.ParseScript (linkscript:TCmdStrList);
  1714. begin
  1715. end;
  1716. function TExeOutput.FindExeSection(const aname:string):TExeSection;
  1717. begin
  1718. result:=TExeSection(ExeSectionList.Find(aname));
  1719. end;
  1720. procedure TExeOutput.AddObjData(ObjData:TObjData);
  1721. begin
  1722. if ObjData.classtype<>FCObjData then
  1723. Comment(V_Error,'Invalid input object format for '+ObjData.name+' got '+ObjData.classname+' expected '+FCObjData.classname);
  1724. ObjDataList.Add(ObjData);
  1725. ExecStack:=ExecStack or ObjData.ExecStack;
  1726. end;
  1727. procedure TExeOutput.Load_Start;
  1728. begin
  1729. ObjDataList.Clear;
  1730. { Globals defined in the linker script }
  1731. if not assigned(internalObjData) then
  1732. internalObjData:=CObjData.create('*Internal*');
  1733. AddObjData(internalObjData);
  1734. { Common Data section }
  1735. commonObjSection:=internalObjData.createsection(sec_bss,'');
  1736. end;
  1737. procedure TExeOutput.Load_EntryName(const aname:string);
  1738. begin
  1739. FEntryName:=aname;
  1740. end;
  1741. procedure TExeOutput.Load_IsSharedLibrary;
  1742. begin
  1743. IsSharedLibrary:=true;
  1744. end;
  1745. procedure TExeOutput.Load_ImageBase(const avalue:string);
  1746. var
  1747. code : integer;
  1748. objsec : TObjSection;
  1749. objsym : TObjSymbol;
  1750. exesym : TExeSymbol;
  1751. begin
  1752. val(avalue,FImageBase,code);
  1753. if code<>0 then
  1754. Comment(V_Error,'Invalid number '+avalue);
  1755. { Create __image_base__ symbol, create the symbol
  1756. in a section with adress 0 and at offset 0 }
  1757. objsec:=internalObjData.createsection('*__image_base__',0,[]);
  1758. internalObjData.setsection(objsec);
  1759. objsym:=internalObjData.SymbolDefine('__image_base__',AB_GLOBAL,AT_DATA);
  1760. exesym:=texesymbol.Create(FExeSymbolList,objsym.name);
  1761. exesym.ObjSymbol:=objsym;
  1762. end;
  1763. procedure TExeOutput.Load_Symbol(const aname:string);
  1764. begin
  1765. internalObjData.createsection('*'+aname,0,[]);
  1766. internalObjData.SymbolDefine(aname,AB_GLOBAL,AT_DATA);
  1767. end;
  1768. procedure TExeOutput.Load_ProvideSymbol(const aname:string);
  1769. begin
  1770. if assigned(ExeSymbolList.Find(aname)) then
  1771. exit;
  1772. internalObjData.createsection('*'+aname,0,[]);
  1773. // Use AB_COMMON to avoid muliple defined complaints
  1774. internalObjData.SymbolDefine(aname,AB_COMMON,AT_DATA);
  1775. end;
  1776. procedure TExeOutput.Load_DynamicObject(ObjData:TObjData;asneeded:boolean);
  1777. begin
  1778. end;
  1779. procedure TExeOutput.Order_Start;
  1780. begin
  1781. end;
  1782. procedure TExeOutput.Order_End;
  1783. begin
  1784. internalObjData.afterwrite;
  1785. end;
  1786. procedure TExeOutput.Order_ExeSection(const aname:string);
  1787. var
  1788. sec : TExeSection;
  1789. begin
  1790. sec:=FindExeSection(aname);
  1791. if not assigned(sec) then
  1792. sec:=CExeSection.create(ExeSectionList,aname);
  1793. { Clear ExeSection contents }
  1794. FCurrExeSec:=sec;
  1795. end;
  1796. procedure TExeOutput.Order_EndExeSection;
  1797. begin
  1798. if not assigned(CurrExeSec) then
  1799. internalerror(200602184);
  1800. FCurrExeSec:=nil;
  1801. end;
  1802. procedure TExeOutput.Order_ObjSection(const aname:string);
  1803. var
  1804. i,j : longint;
  1805. ObjData : TObjData;
  1806. objsec : TObjSection;
  1807. TmpObjSectionList : TFPObjectList;
  1808. begin
  1809. if not assigned(CurrExeSec) then
  1810. internalerror(200602181);
  1811. TmpObjSectionList:=TFPObjectList.Create(false);
  1812. for i:=0 to ObjDataList.Count-1 do
  1813. begin
  1814. ObjData:=TObjData(ObjDataList[i]);
  1815. for j:=0 to ObjData.ObjSectionList.Count-1 do
  1816. begin
  1817. objsec:=TObjSection(ObjData.ObjSectionList[j]);
  1818. if (not objsec.Used) and
  1819. MatchPattern(aname,objsec.name) then
  1820. TmpObjSectionList.Add(objsec);
  1821. end;
  1822. end;
  1823. { Order list if needed }
  1824. Order_ObjSectionList(TmpObjSectionList,aname);
  1825. { Add the (ordered) list to the current ExeSection }
  1826. for i:=0 to TmpObjSectionList.Count-1 do
  1827. begin
  1828. objsec:=TObjSection(TmpObjSectionList[i]);
  1829. CurrExeSec.AddObjSection(objsec);
  1830. end;
  1831. TmpObjSectionList.Free;
  1832. end;
  1833. procedure TExeOutput.Order_ObjSectionList(ObjSectionList : TFPObjectList; const aPattern:string);
  1834. begin
  1835. end;
  1836. procedure TExeOutput.Order_Symbol(const aname:string);
  1837. var
  1838. objsym: TObjSymbol;
  1839. begin
  1840. objsym:=TObjSymbol(internalObjData.ObjSymbolList.Find(aname));
  1841. if (objsym=nil) or (objsym.ObjSection.ObjData<>internalObjData) then
  1842. internalerror(200603041);
  1843. CurrExeSec.AddObjSection(objsym.ObjSection,True);
  1844. end;
  1845. procedure TExeOutput.Order_ProvideSymbol(const aname:string);
  1846. var
  1847. objsym : TObjSymbol;
  1848. exesym : TExeSymbol;
  1849. begin
  1850. objsym:=TObjSymbol(internalObjData.ObjSymbolList.Find(aname));
  1851. if (objsym=nil) or (objsym.ObjSection.ObjData<>internalObjData) then
  1852. internalerror(200603041);
  1853. exesym:=TExeSymbol(ExeSymbolList.Find(aname));
  1854. if not assigned(exesym) then
  1855. internalerror(201206301);
  1856. { Only include this section if it actually resolves
  1857. the symbol }
  1858. if exesym.objsymbol=objsym then
  1859. CurrExeSec.AddObjSection(objsym.ObjSection,True);
  1860. end;
  1861. procedure TExeOutput.Order_Align(const avalue:string);
  1862. var
  1863. code : integer;
  1864. alignval : shortint;
  1865. objsec : TObjSection;
  1866. begin
  1867. val(avalue,alignval,code);
  1868. if code<>0 then
  1869. Comment(V_Error,'Invalid number '+avalue);
  1870. if alignval<=0 then
  1871. exit;
  1872. { Create an empty section with the required aligning }
  1873. inc(Fzeronr);
  1874. objsec:=internalObjData.createsection('*align'+tostr(Fzeronr),alignval,CurrExeSec.SecOptions+[oso_Data,oso_keep]);
  1875. CurrExeSec.AddObjSection(objsec);
  1876. end;
  1877. procedure TExeOutput.Order_Zeros(const avalue:string);
  1878. var
  1879. zeros : array[0..1023] of byte;
  1880. code : integer;
  1881. len : longint;
  1882. objsec : TObjSection;
  1883. begin
  1884. val(avalue,len,code);
  1885. if code<>0 then
  1886. Comment(V_Error,'Invalid number '+avalue);
  1887. if len<=0 then
  1888. exit;
  1889. if len>sizeof(zeros) then
  1890. internalerror(200602254);
  1891. fillchar(zeros,len,0);
  1892. inc(Fzeronr);
  1893. objsec:=internalObjData.createsection('*zeros'+tostr(Fzeronr),0,CurrExeSec.SecOptions+[oso_Data,oso_keep]);
  1894. internalObjData.writebytes(zeros,len);
  1895. CurrExeSec.AddObjSection(objsec);
  1896. end;
  1897. procedure TExeOutput.Order_Values(bytesize : aword; const avalue:string);
  1898. const
  1899. MAXVAL = 128;
  1900. var
  1901. bytevalues : array[0..MAXVAL-1] of byte;
  1902. twobytevalues : array[0..MAXVAL-1] of word;
  1903. fourbytevalues : array[0..MAXVAL-1] of dword;
  1904. eightbytevalues : array[0..MAXVAL-1] of qword;
  1905. allvals, oneval : string;
  1906. len, commapos : longint;
  1907. indexpos, code : integer;
  1908. anumval : qword;
  1909. signedval : int64;
  1910. objsec : TObjSection;
  1911. begin
  1912. indexpos:=0;
  1913. allvals:=avalue;
  1914. { avoid warnings }
  1915. bytevalues[0]:=0;
  1916. twobytevalues[0]:=0;
  1917. fourbytevalues[0]:=0;
  1918. eightbytevalues[0]:=0;
  1919. repeat
  1920. commapos:=pos(',',allvals);
  1921. if commapos>0 then
  1922. begin
  1923. oneval:=trim(copy(allvals,1,commapos-1));
  1924. allvals:=copy(allvals,commapos+1,length(allvals));
  1925. end
  1926. else
  1927. begin
  1928. oneval:=trim(allvals);
  1929. allvals:='';
  1930. end;
  1931. if oneval<>'' then
  1932. begin
  1933. if oneval[1]='-' then
  1934. begin
  1935. val(oneval,signedval,code);
  1936. anumval:=qword(signedval);
  1937. end
  1938. else
  1939. val(oneval,anumval,code);
  1940. if code<>0 then
  1941. Comment(V_Error,'Invalid number '+avalue)
  1942. else
  1943. begin
  1944. if (indexpos<MAXVAL) then
  1945. begin
  1946. if source_info.endian<>target_info.endian then
  1947. swapendian(anumval);
  1948. { No range checking here }
  1949. if bytesize=1 then
  1950. bytevalues[indexpos]:=byte(anumval)
  1951. else if bytesize=2 then
  1952. twobytevalues[indexpos]:=word(anumval)
  1953. else if bytesize=4 then
  1954. fourbytevalues[indexpos]:=dword(anumval)
  1955. else if bytesize=8 then
  1956. eightbytevalues[indexpos]:=anumval;
  1957. inc(indexpos);
  1958. end
  1959. else
  1960. Comment(V_Error,'Buffer overrun in Order_values');
  1961. end;
  1962. end;
  1963. until allvals='';
  1964. if indexpos=0 then
  1965. begin
  1966. Comment(V_Error,'Invalid number '+avalue);
  1967. exit;
  1968. end;
  1969. if indexpos=MAXVAL then
  1970. begin
  1971. Comment(V_Error,'Too many values '+avalue);
  1972. internalerror(200602254);
  1973. end;
  1974. len:=bytesize*indexpos;
  1975. inc(Fvaluesnr);
  1976. objsec:=internalObjData.createsection('*values'+tostr(Fvaluesnr),0,CurrExeSec.SecOptions+[oso_Data,oso_keep]);
  1977. if bytesize=1 then
  1978. internalObjData.writebytes(bytevalues,len)
  1979. else if bytesize=2 then
  1980. internalObjData.writebytes(twobytevalues,len)
  1981. else if bytesize=4 then
  1982. internalObjData.writebytes(fourbytevalues,len)
  1983. else if bytesize=8 then
  1984. internalObjData.writebytes(eightbytevalues,len);
  1985. CurrExeSec.AddObjSection(objsec);
  1986. end;
  1987. procedure TExeOutput.MemPos_Start;
  1988. begin
  1989. CurrMemPos:=0;
  1990. RemoveDisabledSections;
  1991. end;
  1992. procedure TExeOutput.MemPos_Header;
  1993. begin
  1994. end;
  1995. procedure TExeOutput.MemPos_ExeSection(exesec:TExeSection);
  1996. var
  1997. i : longint;
  1998. objsec : TObjSection;
  1999. begin
  2000. { Alignment of ExeSection }
  2001. CurrMemPos:=align_qword(CurrMemPos,MemAlign(exesec));
  2002. exesec.MemPos:=CurrMemPos;
  2003. { set position of object ObjSections }
  2004. for i:=0 to exesec.ObjSectionList.Count-1 do
  2005. begin
  2006. objsec:=TObjSection(exesec.ObjSectionList[i]);
  2007. CurrMemPos:=objsec.setmempos(CurrMemPos);
  2008. end;
  2009. { calculate size of the section }
  2010. exesec.Size:=CurrMemPos-exesec.MemPos;
  2011. end;
  2012. procedure TExeOutput.MemPos_ExeSection(const aname:string);
  2013. begin
  2014. { Section can be removed }
  2015. FCurrExeSec:=FindExeSection(aname);
  2016. if not assigned(CurrExeSec) then
  2017. exit;
  2018. MemPos_ExeSection(CurrExeSec);
  2019. end;
  2020. procedure TExeOutput.MemPos_EndExeSection;
  2021. begin
  2022. if not assigned(CurrExeSec) then
  2023. exit;
  2024. FCurrExeSec:=nil;
  2025. end;
  2026. procedure TExeOutput.DataPos_Start;
  2027. begin
  2028. end;
  2029. procedure TExeOutput.DataPos_Header;
  2030. begin
  2031. end;
  2032. procedure TExeOutput.DataPos_ExeSection(exesec:TExeSection);
  2033. begin
  2034. { don't write normal section if writing only debug info }
  2035. if (ExeWriteMode=ewm_dbgonly) and
  2036. (exesec.SecOptions*[oso_debug,oso_debug_copy]=[]) then
  2037. exit;
  2038. if (oso_Data in exesec.SecOptions) then
  2039. begin
  2040. CurrDataPos:=align_aword(CurrDataPos,DataAlign(exesec));
  2041. exesec.DataPos:=CurrDataPos;
  2042. CurrDataPos:=CurrDataPos+exesec.Size;
  2043. end;
  2044. end;
  2045. procedure TExeOutput.DataPos_ExeSection(const aname:string);
  2046. begin
  2047. { Section can be removed }
  2048. FCurrExeSec:=FindExeSection(aname);
  2049. if not assigned(CurrExeSec) then
  2050. exit;
  2051. DataPos_ExeSection(CurrExeSec);
  2052. end;
  2053. procedure TExeOutput.DataPos_EndExeSection;
  2054. begin
  2055. if not assigned(CurrExeSec) then
  2056. exit;
  2057. FCurrExeSec:=nil;
  2058. end;
  2059. procedure TExeOutput.DataPos_Symbols;
  2060. begin
  2061. end;
  2062. procedure TExeOutput.BuildVTableTree(VTInheritList,VTEntryList:TFPObjectList);
  2063. var
  2064. hs : string;
  2065. code : integer;
  2066. i,k,
  2067. vtableidx : longint;
  2068. vtableexesym,
  2069. childexesym,
  2070. parentexesym : TExeSymbol;
  2071. objsym : TObjSymbol;
  2072. begin
  2073. { Build inheritance tree from VTINHERIT }
  2074. for i:=0 to VTInheritList.Count-1 do
  2075. begin
  2076. objsym:=TObjSymbol(VTInheritList[i]);
  2077. hs:=objsym.name;
  2078. { VTINHERIT_<ChildVMTName>$$<ParentVMTName> }
  2079. Delete(hs,1,Pos('_',hs));
  2080. k:=Pos('$$',hs);
  2081. if k=0 then
  2082. internalerror(200603311);
  2083. childexesym:=texesymbol(FExeSymbolList.Find(Copy(hs,1,k-1)));
  2084. parentexesym:=texesymbol(FExeSymbolList.Find(Copy(hs,k+2,length(hs)-k-1)));
  2085. if not assigned(childexesym) or
  2086. not assigned(parentexesym)then
  2087. internalerror(200603312);
  2088. if not assigned(childexesym.vtable) then
  2089. begin
  2090. childexesym.vtable:=TExeVTable.Create(childexesym);
  2091. ExeVTableList.Add(childexesym.vtable);
  2092. end;
  2093. if not assigned(parentexesym.vtable) then
  2094. begin
  2095. parentexesym.vtable:=TExeVTable.Create(parentexesym);
  2096. ExeVTableList.Add(parentexesym.vtable);
  2097. end;
  2098. childexesym.vtable.SetVTableSize(childexesym.ObjSymbol.Size);
  2099. if parentexesym<>childexesym then
  2100. parentexesym.vtable.AddChild(childexesym.vtable);
  2101. end;
  2102. { Find VTable entries from VTENTRY }
  2103. for i:=0 to VTEntryList.Count-1 do
  2104. begin
  2105. objsym:=TObjSymbol(VTEntryList[i]);
  2106. hs:=objsym.name;
  2107. { VTENTRY_<VTableName>$$<Index> }
  2108. Delete(hs,1,Pos('_',hs));
  2109. k:=Pos('$$',hs);
  2110. if k=0 then
  2111. internalerror(200603319);
  2112. vtableexesym:=texesymbol(FExeSymbolList.Find(Copy(hs,1,k-1)));
  2113. val(Copy(hs,k+2,length(hs)-k-1),vtableidx,code);
  2114. if (code<>0) then
  2115. internalerror(200603318);
  2116. if not assigned(vtableexesym) then
  2117. internalerror(2006033110);
  2118. vtableexesym.vtable.AddEntry(vtableidx);
  2119. end;
  2120. end;
  2121. procedure TExeOutput.PackUnresolvedExeSymbols(const s:string);
  2122. var
  2123. i : longint;
  2124. exesym : TExeSymbol;
  2125. begin
  2126. { Generate a list of Unresolved External symbols }
  2127. for i:=0 to UnresolvedExeSymbols.count-1 do
  2128. begin
  2129. exesym:=TExeSymbol(UnresolvedExeSymbols[i]);
  2130. if not (exesym.State in [symstate_undefined,symstate_undefweak]) then
  2131. UnresolvedExeSymbols[i]:=nil;
  2132. end;
  2133. UnresolvedExeSymbols.Pack;
  2134. Comment(V_Debug,'Number of unresolved externals '+s+' '+tostr(UnresolvedExeSymbols.Count));
  2135. end;
  2136. procedure TExeOutput.ResolveSymbols(StaticLibraryList:TFPObjectList);
  2137. var
  2138. ObjData : TObjData;
  2139. exesym : TExeSymbol;
  2140. objsym,
  2141. commonsym : TObjSymbol;
  2142. firstarchive,
  2143. firstcommon : boolean;
  2144. i : longint;
  2145. VTEntryList,
  2146. VTInheritList : TFPObjectList;
  2147. procedure LoadObjDataSymbols(ObjData:TObjData);
  2148. var
  2149. j : longint;
  2150. hs : string;
  2151. exesym : TExeSymbol;
  2152. objsym : TObjSymbol;
  2153. grp : TObjSectionGroup;
  2154. begin
  2155. for j:=0 to ObjData.ObjSymbolList.Count-1 do
  2156. begin
  2157. objsym:=TObjSymbol(ObjData.ObjSymbolList[j]);
  2158. { From the local symbols we are only interressed in the
  2159. VTENTRY and VTINHERIT symbols }
  2160. if objsym.bind=AB_LOCAL then
  2161. begin
  2162. if cs_link_opt_vtable in current_settings.globalswitches then
  2163. begin
  2164. hs:=objsym.name;
  2165. if (hs[1]='V') then
  2166. begin
  2167. if Copy(hs,1,5)='VTREF' then
  2168. begin
  2169. if not assigned(objsym.ObjSection.VTRefList) then
  2170. objsym.ObjSection.VTRefList:=TFPObjectList.Create(false);
  2171. objsym.ObjSection.VTRefList.Add(objsym);
  2172. end
  2173. else if Copy(hs,1,7)='VTENTRY' then
  2174. VTEntryList.Add(objsym)
  2175. else if Copy(hs,1,9)='VTINHERIT' then
  2176. VTInheritList.Add(objsym);
  2177. end;
  2178. end;
  2179. continue;
  2180. end;
  2181. { If this symbol comes from COMDAT group, see if a group with
  2182. matching signature is already included. }
  2183. if assigned(objsym.objsection) and
  2184. assigned(objsym.objsection.group) then
  2185. begin
  2186. grp:=objsym.objsection.group;
  2187. if grp.IsComdat then
  2188. begin
  2189. if ComdatGroups.Find(grp.name)=nil then
  2190. ComdatGroups.Add(grp.name,grp)
  2191. else
  2192. begin
  2193. { Undefine the symbol, causing relocations to it from same
  2194. objdata to be redirected to the symbol in the actually
  2195. linked group. }
  2196. if objsym.bind=AB_GLOBAL then
  2197. objsym.bind:=AB_EXTERNAL;
  2198. { AB_WEAK_EXTERNAL remains unchanged }
  2199. objsym.objsection:=nil;
  2200. end;
  2201. end;
  2202. end;
  2203. { Search for existing exesymbol }
  2204. exesym:=texesymbol(FExeSymbolList.Find(objsym.name));
  2205. if not assigned(exesym) then
  2206. begin
  2207. exesym:=texesymbol.Create(FExeSymbolList,objsym.name);
  2208. exesym.ObjSymbol:=objsym;
  2209. end;
  2210. objsym.ExeSymbol:=exesym;
  2211. case objsym.bind of
  2212. AB_GLOBAL :
  2213. begin
  2214. if exesym.State<>symstate_defined then
  2215. begin
  2216. exesym.ObjSymbol:=objsym;
  2217. exesym.State:=symstate_defined;
  2218. end
  2219. else
  2220. if (oso_comdat in exesym.ObjSymbol.objsection.SecOptions) and
  2221. (oso_comdat in objsym.objsection.SecOptions) then
  2222. begin
  2223. if exesym.ObjSymbol.objsection.ComdatSelection=objsym.objsection.ComdatSelection then
  2224. begin
  2225. case objsym.objsection.ComdatSelection of
  2226. oscs_none:
  2227. Message1(link_e_duplicate_symbol,objsym.name);
  2228. oscs_any:
  2229. Message1(link_d_comdat_discard_any,objsym.name);
  2230. oscs_same_size:
  2231. if exesym.ObjSymbol.size<>objsym.size then
  2232. Message1(link_e_comdat_size_differs,objsym.name)
  2233. else
  2234. Message1(link_d_comdat_discard_size,objsym.name);
  2235. oscs_exact_match:
  2236. if (exesym.ObjSymbol.size<>objsym.size) and not exesym.ObjSymbol.objsection.Data.equal(objsym.objsection.Data) then
  2237. Message1(link_e_comdat_content_differs,objsym.name)
  2238. else
  2239. Message1(link_d_comdat_discard_content,objsym.name);
  2240. oscs_associative:
  2241. { this is handled in a different way }
  2242. Message1(link_e_duplicate_symbol,objsym.name);
  2243. oscs_largest:
  2244. if objsym.size>exesym.ObjSymbol.size then
  2245. begin
  2246. Message1(link_d_comdat_replace_size,objsym.name);
  2247. exesym.ObjSymbol.exesymbol:=nil;
  2248. exesym.ObjSymbol:=objsym;
  2249. end;
  2250. end;
  2251. end
  2252. else
  2253. Message1(link_e_comdat_selection_differs,objsym.name);
  2254. end
  2255. else
  2256. { specific error if ComDat flags are different? }
  2257. Message1(link_e_duplicate_symbol,objsym.name);
  2258. end;
  2259. AB_EXTERNAL :
  2260. begin
  2261. ExternalObjSymbols.add(objsym);
  2262. { Register unresolved symbols only the first time they
  2263. are registered }
  2264. if exesym.ObjSymbol=objsym then
  2265. UnresolvedExeSymbols.Add(exesym)
  2266. { Normal reference removes any existing "weakness" }
  2267. else if exesym.state=symstate_undefweak then
  2268. begin
  2269. exesym.state:=symstate_undefined;
  2270. exesym.ObjSymbol:=objsym;
  2271. end;
  2272. end;
  2273. AB_COMMON :
  2274. begin
  2275. { A COMMON definition overrides weak one.
  2276. Also select the symbol with largest size. }
  2277. if (exesym.State in [symstate_undefined,symstate_undefweak,symstate_defweak]) or
  2278. ((exesym.State=symstate_common) and (objsym.size>exesym.ObjSymbol.size)) then
  2279. begin
  2280. exesym.ObjSymbol:=objsym;
  2281. exesym.State:=symstate_common;
  2282. end;
  2283. if assigned(objsym.objsection) and
  2284. (objsym.objsection.objdata=internalObjData) then
  2285. FProvidedObjSymbols.add(objsym)
  2286. else
  2287. CommonObjSymbols.add(objsym);
  2288. end;
  2289. AB_WEAK_EXTERNAL :
  2290. begin
  2291. if objsym.objsection=nil then { a weak reference }
  2292. begin
  2293. ExternalObjSymbols.add(objsym);
  2294. if exesym.ObjSymbol=objsym then
  2295. begin
  2296. UnresolvedExeSymbols.Add(exesym);
  2297. exesym.state:=symstate_undefweak;
  2298. end;
  2299. end
  2300. else { a weak definition }
  2301. begin
  2302. if exesym.State in [symstate_undefined,symstate_undefweak] then
  2303. begin
  2304. exesym.ObjSymbol:=objsym;
  2305. exesym.state:=symstate_defweak;
  2306. end;
  2307. end;
  2308. end;
  2309. end;
  2310. end;
  2311. end;
  2312. procedure LoadLibrary(lib:TStaticLibrary);
  2313. var
  2314. j,k,oldcount: longint;
  2315. members: TFPObjectList;
  2316. exesym: TExeSymbol;
  2317. objinput: TObjInput;
  2318. begin
  2319. case lib.Kind of
  2320. lkArchive:
  2321. begin
  2322. { Process list of Unresolved External symbols, we need
  2323. to use a while loop because the list can be extended when
  2324. we load members from the library. }
  2325. j:=0;
  2326. while (j<UnresolvedExeSymbols.count) do
  2327. begin
  2328. exesym:=TExeSymbol(UnresolvedExeSymbols[j]);
  2329. { Check first if the symbol is still undefined }
  2330. if (exesym.State=symstate_undefined) then
  2331. begin
  2332. if lib.ArReader.OpenFile(exesym.name) then
  2333. begin
  2334. if assigned(exemap) then
  2335. begin
  2336. if firstarchive then
  2337. begin
  2338. exemap.Add('');
  2339. exemap.Add('Archive member included because of file (symbol)');
  2340. exemap.Add('');
  2341. firstarchive:=false;
  2342. end;
  2343. exemap.Add(lib.ArReader.FileName+' - '+
  2344. {exesym.ObjSymbol.ObjSection.FullName+}
  2345. '('+exesym.Name+')');
  2346. end;
  2347. objinput:=lib.ObjInputClass.Create;
  2348. objinput.ReadObjData(lib.ArReader,objdata);
  2349. objinput.free;
  2350. AddObjData(objdata);
  2351. LoadObjDataSymbols(objdata);
  2352. lib.ArReader.CloseFile;
  2353. end;
  2354. end;
  2355. inc(j);
  2356. end;
  2357. end;
  2358. lkGroup:
  2359. begin
  2360. { repeatedly process members of the group until no new
  2361. unresolved symbols appear }
  2362. members:=lib.GroupMembers;
  2363. repeat
  2364. oldcount:=UnresolvedExeSymbols.count;
  2365. for k:=0 to members.Count-1 do
  2366. LoadLibrary(TStaticLibrary(members[k]));
  2367. until UnresolvedExeSymbols.count=oldcount;
  2368. end;
  2369. lkObject:
  2370. { TODO: ownership of objdata }
  2371. //if lib.objdata.is_dynamic then
  2372. Load_DynamicObject(lib.objdata,lib.AsNeeded);
  2373. {else
  2374. begin
  2375. AddObjData(lib.objdata);
  2376. LoadObjDataSymbols(lib.objdata);
  2377. end;}
  2378. end;
  2379. end;
  2380. begin
  2381. VTEntryList:=TFPObjectList.Create(false);
  2382. VTInheritList:=TFPObjectList.Create(false);
  2383. {
  2384. The symbol resolving is done in 4 steps:
  2385. 1. Register symbols from objects
  2386. 2. Find symbols in static libraries
  2387. 3. Define symbols PROVIDEd by the link script
  2388. 4. Define still undefined common symbols
  2389. }
  2390. { Step 1, Register symbols from objects }
  2391. for i:=0 to ObjDataList.Count-1 do
  2392. begin
  2393. ObjData:=TObjData(ObjDataList[i]);
  2394. LoadObjDataSymbols(ObjData);
  2395. end;
  2396. PackUnresolvedExeSymbols('in objects');
  2397. { Step 2, Find unresolved symbols in the libraries }
  2398. firstarchive:=true;
  2399. for i:=0 to StaticLibraryList.Count-1 do
  2400. LoadLibrary(TStaticLibrary(StaticLibraryList[i]));
  2401. PackUnresolvedExeSymbols('after static libraries');
  2402. { Step 3, handle symbols provided in script }
  2403. for i:=0 to FProvidedObjSymbols.count-1 do
  2404. begin
  2405. objsym:=TObjSymbol(FProvidedObjSymbols[i]);
  2406. if objsym.exesymbol.State=symstate_defined then
  2407. continue;
  2408. objsym.exesymbol.objsymbol:=objsym;
  2409. objsym.bind:=AB_GLOBAL;
  2410. objsym.exesymbol.State:=symstate_defined;
  2411. end;
  2412. PackUnresolvedExeSymbols('after defining symbols provided by link script');
  2413. { Step 4, Match common symbols or add to the globals }
  2414. firstcommon:=true;
  2415. for i:=0 to CommonObjSymbols.count-1 do
  2416. begin
  2417. objsym:=TObjSymbol(CommonObjSymbols[i]);
  2418. if objsym.exesymbol.State=symstate_defined then
  2419. begin
  2420. if objsym.exesymbol.ObjSymbol.size<>objsym.size then
  2421. Comment(V_Debug,'Size of common symbol '+objsym.name+' is different, expected '+tostr(objsym.size)+' got '+tostr(objsym.exesymbol.ObjSymbol.size));
  2422. end
  2423. else
  2424. begin
  2425. { allocate new objsymbol in .bss of *COMMON* and assign
  2426. it to the exesymbol }
  2427. if firstcommon then
  2428. begin
  2429. if assigned(exemap) then
  2430. exemap.AddCommonSymbolsHeader;
  2431. firstcommon:=false;
  2432. end;
  2433. internalObjData.setsection(commonObjSection);
  2434. { TODO: support alignment of common symbols (ELF targets at least),
  2435. increase commonObjSection.SecAlign if necessary here. }
  2436. internalObjData.allocalign(used_align(size_2_align(objsym.size),0,commonObjSection.SecAlign));
  2437. commonsym:=internalObjData.symboldefine(objsym.name,AB_GLOBAL,AT_DATA);
  2438. commonsym.size:=objsym.size;
  2439. internalObjData.alloc(objsym.size);
  2440. if assigned(exemap) then
  2441. exemap.AddCommonSymbol(objsym);
  2442. { Assign to the exesymbol }
  2443. objsym.exesymbol.objsymbol:=commonsym;
  2444. objsym.exesymbol.state:=symstate_defined;
  2445. end;
  2446. end;
  2447. PackUnresolvedExeSymbols('after defining COMMON symbols');
  2448. { Find entry symbol and print in map }
  2449. if (EntryName<>'') then
  2450. begin
  2451. exesym:=texesymbol(ExeSymbolList.Find(EntryName));
  2452. if assigned(exesym) then
  2453. begin
  2454. EntrySym:=exesym.ObjSymbol;
  2455. if assigned(exemap) then
  2456. begin
  2457. exemap.Add('');
  2458. exemap.Add('Entry symbol '+EntryName);
  2459. end;
  2460. end
  2461. else
  2462. Comment(V_Error,'Entrypoint '+EntryName+' not defined');
  2463. end;
  2464. { Generate VTable tree }
  2465. if cs_link_opt_vtable in current_settings.globalswitches then
  2466. BuildVTableTree(VTInheritList,VTEntryList);
  2467. VTInheritList.Free;
  2468. VTEntryList.Free;
  2469. end;
  2470. procedure TExeOutput.GenerateDebugLink(const dbgname:string;dbgcrc:cardinal);
  2471. var
  2472. debuglink : array[0..1023] of byte;
  2473. len : longint;
  2474. objsec : TObjSection;
  2475. exesec : TExeSection;
  2476. begin
  2477. { From the gdb manual chapter 15. GDB Files:
  2478. * A filename, with any leading directory components removed, followed by a zero byte,
  2479. * zero to three bytes of padding, as needed to reach the next four-byte boundary within the section, and
  2480. * a four-byte CRC checksum, stored in the same endianness used for the executable file itself. The checksum is computed
  2481. on the debugging information file's full contents by the function given below, passing zero as the crc argument.
  2482. }
  2483. fillchar(debuglink,sizeof(debuglink),0);
  2484. len:=0;
  2485. move(dbgname[1],debuglink[len],length(dbgname));
  2486. inc(len,length(dbgname)+1);
  2487. len:=align(len,4);
  2488. if source_info.endian<>target_info.endian then
  2489. SwapEndian(dbgcrc);
  2490. move(dbgcrc,debuglink[len],sizeof(cardinal));
  2491. inc(len,4);
  2492. { Add section }
  2493. exesec:=FindExeSection(debuglinkname);
  2494. if not assigned(exesec) then
  2495. exesec:=CExeSection.create(ExeSectionList,debuglinkname);
  2496. exesec.SecOptions:=[oso_data,oso_keep];
  2497. exesec.SecAlign:=4;
  2498. objsec:=internalObjData.createsection(exesec.name,1,exesec.SecOptions);
  2499. internalObjData.writebytes(debuglink,len);
  2500. exesec.AddObjSection(objsec);
  2501. end;
  2502. procedure TExeOutput.GenerateLibraryImports(ImportLibraryList:TFPHashObjectList);
  2503. begin
  2504. end;
  2505. procedure TExeOutput.MarkTargetSpecificSections(WorkList:TFPObjectList);
  2506. begin
  2507. end;
  2508. procedure TExeOutput.AfterUnusedSectionRemoval;
  2509. begin
  2510. end;
  2511. function ByAddress(item1,item2:pointer):longint;
  2512. var
  2513. sym1:TObjSymbol absolute item1;
  2514. sym2:TObjSymbol absolute item2;
  2515. begin
  2516. if sym1.address>sym2.address then
  2517. result:=1
  2518. else if sym1.address<sym2.address then
  2519. result:=-1
  2520. else
  2521. result:=0;
  2522. end;
  2523. procedure TExeOutput.PrintMemoryMap;
  2524. var
  2525. exesec : TExeSection;
  2526. objsec : TObjSection;
  2527. objsym : TObjSymbol;
  2528. i,j,k,m: longint;
  2529. list : TFPList;
  2530. flag : boolean;
  2531. begin
  2532. if not assigned(exemap) then
  2533. exit;
  2534. { create a list of symbols sorted by address }
  2535. list:=TFPList.Create;
  2536. for i:=0 to ExeSymbolList.Count-1 do
  2537. list.Add(TExeSymbol(ExeSymbolList[i]).ObjSymbol);
  2538. list.Sort(@ByAddress);
  2539. exemap.AddMemoryMapHeader(ImageBase);
  2540. k:=0;
  2541. for i:=0 to ExeSectionList.Count-1 do
  2542. begin
  2543. exesec:=TExeSection(ExeSectionList[i]);
  2544. exemap.AddMemoryMapExeSection(exesec);
  2545. for j:=0 to exesec.ObjSectionList.count-1 do
  2546. begin
  2547. objsec:=TObjSection(exesec.ObjSectionList[j]);
  2548. exemap.AddMemoryMapObjectSection(objsec);
  2549. while (k<list.Count) and (TObjSymbol(list[k]).Address<objsec.MemPos) do
  2550. inc(k);
  2551. while (k<list.Count) do
  2552. begin
  2553. objsym:=TObjSymbol(list[k]);
  2554. if objsym.address>objsec.MemPos+objsec.Size then
  2555. break;
  2556. if objsym.objsection=objsec then
  2557. exemap.AddMemoryMapSymbol(objsym)
  2558. else
  2559. begin
  2560. { Got a symbol with address falling into current section, but
  2561. belonging to a different section. This may happen for zero-length
  2562. sections because symbol list is sorted by address but not by section.
  2563. Do some look-ahead in this case. }
  2564. m:=k+1;
  2565. flag:=false;
  2566. while (m<list.Count) and (TObjSymbol(list[m]).Address=objsym.address) do
  2567. begin
  2568. if TObjSymbol(list[m]).objsection=objsec then
  2569. begin
  2570. flag:=true;
  2571. list.Exchange(k,m);
  2572. exemap.AddMemoryMapSymbol(TObjSymbol(list[k]));
  2573. break;
  2574. end;
  2575. inc(m);
  2576. end;
  2577. if not flag then
  2578. break;
  2579. end;
  2580. inc(k);
  2581. end;
  2582. end;
  2583. end;
  2584. list.Free;
  2585. end;
  2586. procedure TExeOutput.FixupSymbols;
  2587. procedure UpdateSymbol(objsym:TObjSymbol);
  2588. begin
  2589. objsym.bind:=objsym.ExeSymbol.ObjSymbol.bind;
  2590. objsym.offset:=objsym.ExeSymbol.ObjSymbol.offset;
  2591. objsym.size:=objsym.ExeSymbol.ObjSymbol.size;
  2592. objsym.typ:=objsym.ExeSymbol.ObjSymbol.typ;
  2593. objsym.ObjSection:=objsym.ExeSymbol.ObjSymbol.ObjSection;
  2594. objsym.group:=objsym.ExeSymbol.ObjSymbol.group;
  2595. end;
  2596. var
  2597. i : longint;
  2598. objsym : TObjSymbol;
  2599. exesym : TExeSymbol;
  2600. begin
  2601. { Print list of Unresolved External symbols }
  2602. if not AllowUndefinedSymbols then
  2603. for i:=0 to UnresolvedExeSymbols.count-1 do
  2604. begin
  2605. exesym:=TExeSymbol(UnresolvedExeSymbols[i]);
  2606. if (exesym.State=symstate_undefined) then
  2607. Comment(V_Error,'Undefined symbol: '+exesym.name);
  2608. end;
  2609. {
  2610. Fixing up symbols is done in the following steps:
  2611. 1. Update common references
  2612. 2. Update external references
  2613. Symbols with objsection<>nil are removed from the lists,
  2614. remaining ones can be processed later by calling this method again.
  2615. }
  2616. { Step 1, Update commons. Preserve the original symbol size and bind,
  2617. this is needed for correct relocation of DJCOFF files. }
  2618. for i:=0 to CommonObjSymbols.count-1 do
  2619. begin
  2620. objsym:=TObjSymbol(CommonObjSymbols[i]);
  2621. if objsym.bind<>AB_COMMON then
  2622. internalerror(200606241);
  2623. objsym.ObjSection:=objsym.ExeSymbol.ObjSymbol.ObjSection;
  2624. objsym.offset:=objsym.ExeSymbol.ObjSymbol.offset;
  2625. objsym.typ:=objsym.ExeSymbol.ObjSymbol.typ;
  2626. end;
  2627. { Step 2, Update externals }
  2628. for i:=0 to ExternalObjSymbols.count-1 do
  2629. begin
  2630. objsym:=TObjSymbol(ExternalObjSymbols[i]);
  2631. if not (objsym.bind in [AB_EXTERNAL,AB_WEAK_EXTERNAL]) then
  2632. internalerror(200606242);
  2633. UpdateSymbol(objsym);
  2634. { Collect symbols that resolve to indirect functions,
  2635. they will need additional target-specific processing. }
  2636. if objsym.typ=AT_GNU_IFUNC then
  2637. IndirectObjSymbols.Add(objsym)
  2638. else if assigned(objsym.objsection) then
  2639. ExternalObjSymbols[i]:=nil;
  2640. end;
  2641. CommonObjSymbols.Clear;
  2642. ExternalObjSymbols.Pack;
  2643. end;
  2644. procedure TExeOutput.MergeStabs;
  2645. var
  2646. stabexesec,
  2647. stabstrexesec : TExeSection;
  2648. relocsec,
  2649. currstabsec,
  2650. currstabstrsec,
  2651. mergedstabsec,
  2652. mergedstabstrsec : TObjSection;
  2653. hstabreloc,
  2654. currstabreloc : TObjRelocation;
  2655. i,j : longint;
  2656. currstabrelocidx,
  2657. mergestabcnt,
  2658. stabcnt : longword;
  2659. skipstab : boolean;
  2660. skipfun : boolean;
  2661. hstab : TObjStabEntry;
  2662. stabrelocofs : longword;
  2663. buf : array[0..1023] of byte;
  2664. bufend,
  2665. bufsize : longint;
  2666. begin
  2667. stabexesec:=FindExeSection('.stab');
  2668. stabstrexesec:=FindExeSection('.stabstr');
  2669. if (stabexesec=nil) or
  2670. (stabstrexesec=nil) or
  2671. (stabexesec.ObjSectionlist.count=0) then
  2672. exit;
  2673. { Create new stabsection }
  2674. stabRelocofs:=pbyte(@hstab.nvalue)-pbyte(@hstab);
  2675. mergedstabsec:=internalObjData.CreateSection(sec_stab,'');
  2676. mergedstabstrsec:=internalObjData.CreateSection(sec_stabstr,'');
  2677. { write stab for hdrsym }
  2678. mergedstabsec.writeZeros(sizeof(TObjStabEntry));
  2679. mergestabcnt:=1;
  2680. { .stabstr starts with a #0 }
  2681. buf[0]:=0;
  2682. mergedstabstrsec.write(buf[0],1);
  2683. skipfun:=false;
  2684. { Copy stabs and corresponding Relocations }
  2685. for i:=0 to stabexesec.ObjSectionList.Count-1 do
  2686. begin
  2687. currstabsec:=TObjSection(stabexesec.ObjSectionList[i]);
  2688. currstabstrsec:=currstabsec.ObjData.findsection('.stabstr');
  2689. if assigned(currstabstrsec) then
  2690. begin
  2691. stabcnt:=currstabsec.Data.size div sizeof(TObjStabEntry);
  2692. currstabsec.Data.seek(0);
  2693. currstabrelocidx:=0;
  2694. for j:=0 to stabcnt-1 do
  2695. begin
  2696. hstabreloc:=nil;
  2697. skipstab:=false;
  2698. currstabsec.Data.read(hstab,sizeof(TObjStabEntry));
  2699. MaybeSwapStab(hstab);
  2700. { Only include first hdrsym stab }
  2701. if hstab.ntype=0 then
  2702. skipstab:=true;
  2703. if skipfun then
  2704. begin
  2705. { Skip all stabs for function body until N_RBRAC }
  2706. skipfun:=hstab.ntype<>N_RBRAC;
  2707. skipstab:=true;
  2708. end;
  2709. if not skipstab then
  2710. begin
  2711. { Find corresponding Relocation }
  2712. currstabreloc:=nil;
  2713. while (currstabrelocidx<longword(currstabsec.ObjRelocations.Count)) do
  2714. begin
  2715. currstabreloc:=TObjRelocation(currstabsec.ObjRelocations[currstabrelocidx]);
  2716. if assigned(currstabreloc) and
  2717. (currstabreloc.dataoffset>=longword(j)*sizeof(TObjStabEntry)+stabrelocofs) then
  2718. break;
  2719. inc(currstabrelocidx);
  2720. end;
  2721. if assigned(currstabreloc) and
  2722. (currstabreloc.dataoffset=longword(j)*sizeof(TObjStabEntry)+stabrelocofs) then
  2723. begin
  2724. hstabReloc:=currstabReloc;
  2725. inc(currstabrelocidx);
  2726. end;
  2727. { Check if the stab is refering to a removed section }
  2728. if assigned(hstabreloc) then
  2729. begin
  2730. if assigned(hstabreloc.Symbol) then
  2731. relocsec:=hstabreloc.Symbol.ObjSection
  2732. else
  2733. relocsec:=hstabreloc.ObjSection;
  2734. if not assigned(relocsec) then
  2735. internalerror(200603302);
  2736. if not relocsec.Used then
  2737. begin
  2738. skipstab:=true;
  2739. if (hstab.ntype=N_Function) and (hstab.strpos<>0) then
  2740. begin
  2741. currstabstrsec.Data.seek(hstab.strpos);
  2742. bufsize:=currstabstrsec.Data.read(buf,sizeof(buf));
  2743. bufend:=indexbyte(buf,bufsize,Ord(':'));
  2744. if (bufend<>-1) and (bufend<bufsize-1) and (buf[bufend+1]=Ord('F')) then
  2745. skipfun:=true;
  2746. end;
  2747. end;
  2748. end;
  2749. end;
  2750. if not skipstab then
  2751. begin
  2752. { Copy string in stabstr }
  2753. if hstab.strpos<>0 then
  2754. begin
  2755. currstabstrsec.Data.seek(hstab.strpos);
  2756. hstab.strpos:=mergedstabstrsec.Size;
  2757. repeat
  2758. bufsize:=currstabstrsec.Data.read(buf,sizeof(buf));
  2759. bufend:=indexbyte(buf,bufsize,0);
  2760. if bufend=-1 then
  2761. bufend:=bufsize
  2762. else
  2763. begin
  2764. { include the #0 }
  2765. inc(bufend);
  2766. end;
  2767. mergedstabstrsec.write(buf,bufend);
  2768. until (buf[bufend-1]=0) or (bufsize<sizeof(buf));
  2769. end;
  2770. { Copy and Update the relocation }
  2771. if assigned(hstabreloc) then
  2772. begin
  2773. hstabreloc.Dataoffset:=mergestabcnt*sizeof(TObjStabEntry)+stabRelocofs;
  2774. { Remove from List without freeing the object }
  2775. currstabsec.ObjRelocations.List[currstabrelocidx-1]:=nil;
  2776. mergedstabsec.ObjRelocations.Add(hstabreloc);
  2777. end;
  2778. { Write updated stab }
  2779. MaybeSwapStab(hstab);
  2780. mergedstabsec.write(hstab,sizeof(hstab));
  2781. inc(mergestabcnt);
  2782. end;
  2783. end;
  2784. end;
  2785. { Unload stabs }
  2786. if assigned(currstabstrsec) then
  2787. begin
  2788. currstabstrsec.Used:=False;
  2789. currstabstrsec.ReleaseData;
  2790. end;
  2791. currstabsec.Used:=false;
  2792. currstabsec.ReleaseData;
  2793. end;
  2794. { Generate new HdrSym }
  2795. if mergedstabsec.Size>0 then
  2796. begin
  2797. hstab.strpos:=1;
  2798. hstab.ntype:=0;
  2799. hstab.nother:=0;
  2800. hstab.ndesc:=word(mergestabcnt-1);
  2801. hstab.nvalue:=mergedstabstrsec.Size;
  2802. MaybeSwapStab(hstab);
  2803. mergedstabsec.Data.seek(0);
  2804. mergedstabsec.Data.write(hstab,sizeof(hstab));
  2805. end;
  2806. { Replace all sections with our combined stabsec }
  2807. stabexesec.ObjSectionList.Clear;
  2808. stabstrexesec.ObjSectionList.Clear;
  2809. stabexesec.AddObjSection(mergedstabsec);
  2810. stabstrexesec.AddObjSection(mergedstabstrsec);
  2811. end;
  2812. procedure TExeOutput.MarkEmptySections;
  2813. var
  2814. i, j : longint;
  2815. exesec : TExeSection;
  2816. doremove : boolean;
  2817. begin
  2818. for i:=0 to ExeSectionList.Count-1 do
  2819. begin
  2820. exesec:=TExeSection(ExeSectionList[i]);
  2821. doremove:=not(oso_keep in exesec.SecOptions) and
  2822. (
  2823. (exesec.ObjSectionlist.count=0) or
  2824. (
  2825. (cs_link_strip in current_settings.globalswitches) and
  2826. not(cs_link_separate_dbg_file in current_settings.globalswitches) and
  2827. (oso_debug in exesec.SecOptions)
  2828. )
  2829. );
  2830. if not doremove then
  2831. begin
  2832. { Check if section has no actual data }
  2833. doremove:=true;
  2834. for j:=0 to exesec.ObjSectionList.Count-1 do
  2835. if TObjSection(exesec.ObjSectionList[j]).Size<>0 then
  2836. begin
  2837. doremove:=false;
  2838. break;
  2839. end;
  2840. end;
  2841. if doremove then
  2842. begin
  2843. Comment(V_Debug,'Disabling empty section '+exesec.name);
  2844. exesec.Disabled:=true;
  2845. end;
  2846. end;
  2847. end;
  2848. procedure TExeOutput.RemoveDisabledSections;
  2849. var
  2850. i: longint;
  2851. exesec: TExeSection;
  2852. begin
  2853. for i:=0 to ExeSectionList.Count-1 do
  2854. begin
  2855. exesec:=TExeSection(ExeSectionList[i]);
  2856. if exesec.Disabled then
  2857. ExeSectionList[i]:=nil;
  2858. end;
  2859. ExeSectionList.Pack;
  2860. end;
  2861. procedure TExeOutput.RemoveDebugInfo;
  2862. var
  2863. i : longint;
  2864. exesec : TExeSection;
  2865. begin
  2866. for i:=0 to ExeSectionList.Count-1 do
  2867. begin
  2868. exesec:=TExeSection(ExeSectionList[i]);
  2869. if (oso_debug in exesec.SecOptions) then
  2870. ExeSectionList[i]:=nil;
  2871. end;
  2872. ExeSectionList.Pack;
  2873. end;
  2874. procedure TExeOutput.RemoveUnreferencedSections;
  2875. var
  2876. ObjSectionWorkList : TFPObjectList;
  2877. procedure AddToObjSectionWorkList(aobjsec:TObjSection);
  2878. begin
  2879. if not aobjsec.Used then
  2880. begin
  2881. aobjsec.Used:=true;
  2882. ObjSectionWorkList.Add(aobjsec);
  2883. end;
  2884. end;
  2885. procedure DoReloc(objreloc:TObjRelocation);
  2886. var
  2887. objsym : TObjSymbol;
  2888. refobjsec : TObjSection;
  2889. refgrp : TObjSectionGroup;
  2890. begin
  2891. { Disabled Relocation to 0 }
  2892. if (objreloc.flags and rf_nosymbol)<>0 then
  2893. exit;
  2894. refobjsec:=nil;
  2895. refgrp:=nil;
  2896. if assigned(objreloc.symbol) then
  2897. begin
  2898. objsym:=objreloc.symbol;
  2899. if objsym.bind<>AB_LOCAL then
  2900. begin
  2901. if not assigned(objsym.exesymbol) then
  2902. internalerror(200603063);
  2903. objsym.exesymbol.used:=true;
  2904. objsym:=objsym.exesymbol.objsymbol;
  2905. end;
  2906. if not assigned(objsym.objsection) then
  2907. exit
  2908. else
  2909. refobjsec:=objsym.objsection;
  2910. end
  2911. else if assigned(objreloc.objsection) then
  2912. refobjsec:=objreloc.objsection
  2913. else if assigned(objreloc.group) then
  2914. refgrp:=objreloc.group
  2915. else
  2916. internalerror(200603316);
  2917. if assigned(exemap) then
  2918. begin
  2919. objsym:=objreloc.symbol;
  2920. if assigned(objsym) and (objsym.typ<>AT_SECTION) then
  2921. exemap.Add(' References '+objsym.name+' in '
  2922. +refobjsec.fullname)
  2923. else if assigned(refobjsec) then
  2924. exemap.Add(' References '+refobjsec.fullname)
  2925. else if assigned(refgrp) then
  2926. exemap.Add(' References '+refgrp.Name)
  2927. else
  2928. internalerror(200603316);
  2929. end;
  2930. if assigned(refobjsec) then
  2931. AddToObjSectionWorkList(refobjsec);
  2932. end;
  2933. procedure DoVTableRef(vtable:TExeVTable;VTableIdx:longint);
  2934. var
  2935. i : longint;
  2936. objreloc : TObjRelocation;
  2937. begin
  2938. objreloc:=vtable.VTableRef(VTableIdx);
  2939. if assigned(objreloc) then
  2940. begin
  2941. { Process the relocation now if the ObjSection is
  2942. already processed and marked as used. Otherwise we leave it
  2943. unprocessed. It'll then be resolved when the ObjSection is
  2944. changed to Used }
  2945. if vtable.ExeSymbol.ObjSymbol.ObjSection.Used then
  2946. DoReloc(objreloc);
  2947. end;
  2948. { This recursive walking is done here instead of
  2949. in TExeVTable.VTableRef because we can now process
  2950. all needed relocations }
  2951. for i:=0 to vtable.ChildList.Count-1 do
  2952. DoVTableRef(TExeVTable(vtable.ChildList[i]),VTableIdx);
  2953. end;
  2954. procedure ProcessWorkList;
  2955. var
  2956. hs : string;
  2957. i,k : longint;
  2958. objsec : TObjSection;
  2959. objsym : TObjSymbol;
  2960. code : integer;
  2961. vtableidx : longint;
  2962. vtableexesym : TExeSymbol;
  2963. begin
  2964. while ObjSectionWorkList.Count>0 do
  2965. begin
  2966. objsec:=TObjSection(ObjSectionWorkList.Last);
  2967. if assigned(exemap) then
  2968. exemap.Add('Keeping '+objsec.FullName+' '+ToStr(objsec.ObjRelocations.Count)+' references');
  2969. ObjSectionWorkList.Delete(ObjSectionWorkList.Count-1);
  2970. { Process Relocations }
  2971. for i:=0 to objsec.ObjRelocations.count-1 do
  2972. DoReloc(TObjRelocation(objsec.ObjRelocations[i]));
  2973. { Process Virtual Entry calls }
  2974. if cs_link_opt_vtable in current_settings.globalswitches then
  2975. begin
  2976. for i:=0 to objsec.VTRefList.count-1 do
  2977. begin
  2978. objsym:=TObjSymbol(objsec.VTRefList[i]);
  2979. hs:=objsym.name;
  2980. Delete(hs,1,Pos('_',hs));
  2981. k:=Pos('$$',hs);
  2982. if k=0 then
  2983. internalerror(200603314);
  2984. vtableexesym:=texesymbol(FExeSymbolList.Find(Copy(hs,1,k-1)));
  2985. val(Copy(hs,k+2,length(hs)-k-1),vtableidx,code);
  2986. if (code<>0) then
  2987. internalerror(200603317);
  2988. if not assigned(vtableexesym) then
  2989. internalerror(200603315);
  2990. if not assigned(vtableexesym.vtable) then
  2991. internalerror(200603316);
  2992. DoVTableRef(vtableexesym.vtable,vtableidx);
  2993. end;
  2994. end;
  2995. end;
  2996. end;
  2997. var
  2998. i,j : longint;
  2999. exesec : TExeSection;
  3000. objdata : TObjData;
  3001. objsec : TObjSection;
  3002. begin
  3003. ObjSectionWorkList:=TFPObjectList.Create(false);
  3004. if assigned(exemap) then
  3005. exemap.AddHeader('Removing unreferenced sections');
  3006. { Initialize by marking all sections unused and
  3007. adding the sections with oso_keep flags to the ObjSectionWorkList }
  3008. for i:=0 to ObjDataList.Count-1 do
  3009. begin
  3010. ObjData:=TObjData(ObjDataList[i]);
  3011. for j:=0 to ObjData.ObjSectionList.Count-1 do
  3012. begin
  3013. objsec:=TObjSection(ObjData.ObjSectionList[j]);
  3014. objsec.Used:=false;
  3015. { TODO: remove debug section always keep}
  3016. if oso_debug in objsec.secoptions then
  3017. objsec.Used:=true;
  3018. if (oso_keep in objsec.secoptions) then
  3019. begin
  3020. AddToObjSectionWorkList(objsec);
  3021. if objsec.name='.fpc.n_links' then
  3022. objsec.Used:=false;
  3023. end;
  3024. end;
  3025. end;
  3026. if assigned(entrysym) then
  3027. AddToObjSectionWorkList(entrysym.exesymbol.objsymbol.objsection);
  3028. { Process all sections, add new sections to process based
  3029. on the symbol references }
  3030. ProcessWorkList;
  3031. { Handle stuff like .pdata, i.e. sections that are not referenced
  3032. but must be included if sections they reference are included.
  3033. Loop is necessary because .pdata can reference (via .xdata)
  3034. more text sections, VMTs of exception classes, etc. }
  3035. repeat
  3036. MarkTargetSpecificSections(ObjSectionWorkList);
  3037. if (ObjSectionWorkList.Count=0) then
  3038. break;
  3039. ProcessWorkList;
  3040. until False;
  3041. ObjSectionWorkList.Free;
  3042. ObjSectionWorkList:=nil;
  3043. { Remove unused objsections from ExeSectionList }
  3044. for i:=0 to ExeSectionList.Count-1 do
  3045. begin
  3046. exesec:=TExeSection(ExeSectionList[i]);
  3047. for j:=0 to exesec.ObjSectionlist.count-1 do
  3048. begin
  3049. objsec:=TObjSection(exesec.ObjSectionlist[j]);
  3050. if not objsec.used then
  3051. begin
  3052. if assigned(exemap) then
  3053. exemap.Add('Removing '+objsec.FullName);
  3054. exesec.ObjSectionlist[j]:=nil;
  3055. objsec.ReleaseData;
  3056. end;
  3057. end;
  3058. exesec.ObjSectionlist.Pack;
  3059. end;
  3060. end;
  3061. procedure TExeOutput.FixupRelocations;
  3062. var
  3063. i,j : longint;
  3064. exesec : TExeSection;
  3065. objsec : TObjSection;
  3066. begin
  3067. for i:=0 to ExeSectionList.Count-1 do
  3068. begin
  3069. exesec:=TExeSection(ExeSectionList[i]);
  3070. if not assigned(exesec) then
  3071. continue;
  3072. for j:=0 to exesec.ObjSectionlist.count-1 do
  3073. begin
  3074. objsec:=TObjSection(exesec.ObjSectionlist[j]);
  3075. if not objsec.Used then
  3076. internalerror(200603301);
  3077. if (objsec.ObjRelocations.Count>0) and
  3078. not assigned(objsec.data) then
  3079. internalerror(200205183);
  3080. DoRelocationFixup(objsec);
  3081. {for size = 0 data is not valid PM }
  3082. if assigned(objsec.data) and (objsec.data.size<>objsec.size) then
  3083. internalerror(2010092801);
  3084. end;
  3085. end;
  3086. end;
  3087. procedure TExeOutput.RemoveUnusedExeSymbols;
  3088. var
  3089. i : longint;
  3090. sym : TExeSymbol;
  3091. begin
  3092. { Removing unused symbols }
  3093. for i:=0 to ExeSymbolList.Count-1 do
  3094. begin
  3095. sym:=TExeSymbol(ExeSymbolList[i]);
  3096. { an unresolved weak symbol has objsection=nil }
  3097. if assigned(sym.ObjSymbol.objsection) and
  3098. (not sym.ObjSymbol.objsection.Used) then
  3099. ExeSymbolList[i]:=nil;
  3100. end;
  3101. ExeSymbolList.Pack;
  3102. end;
  3103. procedure TExeOutput.SetCurrMemPos(const AValue: qword);
  3104. begin
  3105. if AValue>MaxMemPos then
  3106. Message1(link_f_executable_too_big, target_os_string);
  3107. FCurrMemPos:=AValue;
  3108. end;
  3109. procedure TExeOutput.WriteExeSectionContent;
  3110. var
  3111. exesec : TExeSection;
  3112. objsec : TObjSection;
  3113. i,j : longint;
  3114. dpos,pad: aword;
  3115. begin
  3116. for j:=0 to ExeSectionList.Count-1 do
  3117. begin
  3118. exesec:=TExeSection(ExeSectionList[j]);
  3119. { don't write normal section if writing only debug info }
  3120. if (ExeWriteMode=ewm_dbgonly) and
  3121. (exesec.SecOptions*[oso_debug,oso_debug_copy]=[]) then
  3122. continue;
  3123. if oso_data in exesec.SecOptions then
  3124. begin
  3125. if exesec.DataPos<FWriter.Size then
  3126. InternalError(2012103001);
  3127. FWriter.Writezeros(exesec.DataPos-FWriter.Size);
  3128. for i:=0 to exesec.ObjSectionList.Count-1 do
  3129. begin
  3130. objsec:=TObjSection(exesec.ObjSectionList[i]);
  3131. if oso_data in objsec.secoptions then
  3132. begin
  3133. if not assigned(objsec.data) then
  3134. internalerror(200603042);
  3135. dpos:=objsec.MemPos-exesec.MemPos+exesec.DataPos;
  3136. pad:=dpos-FWriter.Size;
  3137. { objsection must be within SecAlign bytes from the previous one }
  3138. if (dpos<FWriter.Size) or
  3139. (pad>=max(objsec.SecAlign,1)) then
  3140. internalerror(200602251);
  3141. FWriter.writeZeros(pad);
  3142. FWriter.writearray(objsec.data);
  3143. end;
  3144. end;
  3145. end;
  3146. end;
  3147. end;
  3148. procedure TExeOutput.ReplaceExeSectionList(newlist: TFPList);
  3149. var
  3150. tmp: TFPHashObjectList;
  3151. i: longint;
  3152. begin
  3153. tmp:=TFPHashObjectList.Create(true);
  3154. for i:=0 to newlist.count-1 do
  3155. TFPHashObject(newlist[i]).ChangeOwner(tmp);
  3156. { prevent destruction of existing sections }
  3157. for i:=0 to ExeSectionList.count-1 do
  3158. ExeSectionList.List[i]:=nil;
  3159. FExeSectionList.Free;
  3160. FExeSectionList:=tmp;
  3161. end;
  3162. {****************************************************************************
  3163. TObjInput
  3164. ****************************************************************************}
  3165. constructor TObjInput.create;
  3166. begin
  3167. end;
  3168. procedure TObjInput.inputerror(const s : string);
  3169. begin
  3170. Comment(V_Error,s+' while reading '+InputFileName);
  3171. end;
  3172. class function TObjInput.CanReadObjData(AReader:TObjectReader):boolean;
  3173. begin
  3174. result:=false;
  3175. end;
  3176. procedure TObjInput.ReadSectionContent(Data:TObjData);
  3177. var
  3178. i: longint;
  3179. sec: TObjSection;
  3180. begin
  3181. for i:=0 to Data.ObjSectionList.Count-1 do
  3182. begin
  3183. sec:=TObjSection(Data.ObjSectionList[i]);
  3184. { Skip debug sections }
  3185. if (oso_debug in sec.SecOptions) and
  3186. (cs_link_strip in current_settings.globalswitches) and
  3187. not(cs_link_separate_dbg_file in current_settings.globalswitches) then
  3188. continue;
  3189. if assigned(sec.Data) then
  3190. begin
  3191. FReader.Seek(sec.datapos);
  3192. if not FReader.ReadArray(sec.data,sec.Size) then
  3193. begin
  3194. InputError('Can''t read object data');
  3195. exit;
  3196. end;
  3197. end;
  3198. end;
  3199. end;
  3200. {$ifdef MEMDEBUG}
  3201. initialization
  3202. memobjsymbols:=TMemDebug.create('ObjSymbols');
  3203. memobjsymbols.stop;
  3204. memobjsections:=TMemDebug.create('ObjSections');
  3205. memobjsections.stop;
  3206. finalization
  3207. memobjsymbols.free;
  3208. memobjsections.free;
  3209. {$endif MEMDEBUG}
  3210. end.