2
0

ogbase.pas 135 KB

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