ogbase.pas 114 KB

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