ogbase.pas 135 KB

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