ogbase.pas 134 KB

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