ogbase.pas 129 KB

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