ogbase.pas 118 KB

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