ogbase.pas 128 KB

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