ogbase.pas 117 KB

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