ogbase.pas 114 KB

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