ogbase.pas 129 KB

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