ogbase.pas 121 KB

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