ogcoff.pas 111 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090
  1. {
  2. Copyright (c) 1998-2006 by Peter Vreman
  3. Contains the binary coff/PE reader and writer
  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 ogcoff;
  18. {$i fpcdefs.inc}
  19. interface
  20. uses
  21. { common }
  22. cclasses,globtype,
  23. { target }
  24. systems,
  25. { assembler }
  26. cpuinfo,cpubase,aasmbase,assemble,link,
  27. { output }
  28. ogbase,
  29. owbase;
  30. const
  31. PE_DATADIR_ENTRIES = 16;
  32. type
  33. tcoffpedatadir = packed record
  34. vaddr : longword;
  35. size : longword;
  36. end;
  37. tcoffheader = packed record
  38. mach : word;
  39. nsects : word;
  40. time : longword;
  41. sympos : longword;
  42. syms : longword;
  43. opthdr : word;
  44. flag : word;
  45. end;
  46. tcoffpeoptheader = packed record
  47. Magic : word;
  48. MajorLinkerVersion : byte;
  49. MinorLinkerVersion : byte;
  50. tsize : longword;
  51. dsize : longword;
  52. bsize : longword;
  53. entry : longword;
  54. text_start : longword;
  55. {$ifndef cpu64bitaddr}
  56. data_start : longword;
  57. {$endif cpu64bitaddr}
  58. ImageBase : aword;
  59. SectionAlignment : longword;
  60. FileAlignment : longword;
  61. MajorOperatingSystemVersion : word;
  62. MinorOperatingSystemVersion : word;
  63. MajorImageVersion : word;
  64. MinorImageVersion : word;
  65. MajorSubsystemVersion : word;
  66. MinorSubsystemVersion : word;
  67. Win32Version : longword;
  68. SizeOfImage : longword;
  69. SizeOfHeaders : longword;
  70. CheckSum : longword;
  71. Subsystem : word;
  72. DllCharacteristics : word;
  73. SizeOfStackReserve : aword;
  74. SizeOfStackCommit : aword;
  75. SizeOfHeapReserve : aword;
  76. SizeOfHeapCommit : aword;
  77. LoaderFlags : longword; { This field is obsolete }
  78. NumberOfRvaAndSizes : longword;
  79. DataDirectory : array[0..PE_DATADIR_ENTRIES-1] of tcoffpedatadir;
  80. end;
  81. tcoffsechdr = packed record
  82. name : array[0..7] of char;
  83. vsize : longword;
  84. rvaofs : longword;
  85. datasize : longword;
  86. datapos : longword;
  87. relocpos : longword;
  88. lineno1 : longword;
  89. nrelocs : word;
  90. lineno2 : word;
  91. flags : longword;
  92. end;
  93. TCoffObjSection = class(TObjSection)
  94. private
  95. orgmempos,
  96. coffrelocs,
  97. coffrelocpos : aword;
  98. public
  99. constructor create(AList:TFPHashObjectList;const Aname:string;Aalign:shortint;Aoptions:TObjSectionOptions);override;
  100. procedure writereloc_internal(aTarget:TObjSection;offset:aword;len:byte;reltype:TObjRelocationType);override;
  101. end;
  102. TCoffObjData = class(TObjData)
  103. private
  104. win32 : boolean;
  105. {$ifdef arm}
  106. eVCobj : boolean;
  107. {$endif arm}
  108. public
  109. constructor createcoff(const n:string;awin32:boolean;acObjSection:TObjSectionClass);
  110. procedure CreateDebugSections;override;
  111. function sectionname(atype:TAsmSectiontype;const aname:string;aorder:TAsmSectionOrder):string;override;
  112. function sectiontype2options(atype:TAsmSectiontype):TObjSectionOptions;override;
  113. procedure writereloc(data:aint;len:aword;p:TObjSymbol;reloctype:TObjRelocationType);override;
  114. end;
  115. TDJCoffObjData = class(TCoffObjData)
  116. constructor create(const n:string);override;
  117. end;
  118. TPECoffObjData = class(TCoffObjData)
  119. constructor create(const n:string);override;
  120. end;
  121. TCoffObjOutput = class(tObjOutput)
  122. private
  123. win32 : boolean;
  124. symidx : longint;
  125. FCoffSyms,
  126. FCoffStrs : tdynamicarray;
  127. procedure write_symbol(const name:string;value:aword;section:smallint;typ,aux:byte);
  128. procedure section_write_symbol(p:TObject;arg:pointer);
  129. procedure section_write_relocs(p:TObject;arg:pointer);
  130. procedure create_symbols(data:TObjData);
  131. procedure section_set_reloc_datapos(p:TCoffObjSection;var datapos:aword);
  132. procedure section_write_header(p:TObject;arg:pointer);
  133. protected
  134. function writedata(data:TObjData):boolean;override;
  135. public
  136. constructor createcoff(AWriter:TObjectWriter;awin32:boolean);
  137. destructor destroy;override;
  138. end;
  139. TDJCoffObjOutput = class(TCoffObjOutput)
  140. constructor create(AWriter:TObjectWriter);override;
  141. end;
  142. TPECoffObjOutput = class(TCoffObjOutput)
  143. constructor create(AWriter:TObjectWriter);override;
  144. end;
  145. TCoffObjInput = class(tObjInput)
  146. private
  147. FCoffsyms : tdynamicarray;
  148. FCoffStrs : PChar;
  149. FCoffStrSize: longword;
  150. { Convert symidx -> TObjSymbol }
  151. FSymTbl : ^TObjSymbolArray;
  152. { Convert secidx -> TObjSection }
  153. FSecCount : smallint;
  154. FSecTbl : ^TObjSectionArray;
  155. win32 : boolean;
  156. function GetSection(secidx:longint):TObjSection;
  157. function Read_str(strpos:longword):string;
  158. procedure read_relocs(s:TCoffObjSection);
  159. procedure read_symbols(objdata:TObjData);
  160. procedure ObjSections_read_relocs(p:TObject;arg:pointer);
  161. public
  162. constructor createcoff(awin32:boolean);
  163. destructor destroy;override;
  164. function ReadObjData(AReader:TObjectreader;out objdata:TObjData):boolean;override;
  165. end;
  166. TDJCoffObjInput = class(TCoffObjInput)
  167. constructor create;override;
  168. end;
  169. TPECoffObjInput = class(TCoffObjInput)
  170. constructor create;override;
  171. end;
  172. TCoffexeoutput = class(texeoutput)
  173. private
  174. FCoffStrs : tdynamicarray;
  175. win32 : boolean;
  176. nsects : word;
  177. nsyms,
  178. sympos : aword;
  179. datapos_offset: longword;
  180. function totalheadersize:longword;
  181. procedure ExeSectionList_pass2_header(p:TObject;arg:pointer);
  182. procedure write_symbol(const name:string;value:aword;section:smallint;typ,aux:byte);
  183. procedure globalsyms_write_symbol(p:TObject;arg:pointer);
  184. procedure ExeSectionList_write_header(p:TObject;arg:pointer);
  185. protected
  186. function writedata:boolean;override;
  187. procedure Order_ObjSectionList(ObjSectionList : TFPObjectList;const aPattern:string);override;
  188. procedure DoRelocationFixup(objsec:TObjSection);override;
  189. public
  190. constructor createcoff(awin32:boolean);
  191. procedure MemPos_Header;override;
  192. procedure DataPos_Header;override;
  193. procedure DataPos_Symbols;override;
  194. end;
  195. TDJCoffexeoutput = class(TCoffexeoutput)
  196. constructor create;override;
  197. procedure MemPos_Header;override;
  198. end;
  199. TPECoffexeoutput = class(TCoffexeoutput)
  200. private
  201. FImports: TFPHashObjectList;
  202. textobjsection,
  203. idata2objsection,
  204. idata4objsection,
  205. idata5objsection,
  206. idata6objsection,
  207. idata7objsection : TObjSection;
  208. FRelocsGenerated : boolean;
  209. procedure GenerateRelocs;
  210. public
  211. constructor create;override;
  212. procedure MarkTargetSpecificSections(WorkList:TFPObjectList);override;
  213. procedure AfterUnusedSectionRemoval;override;
  214. procedure GenerateLibraryImports(ImportLibraryList:TFPHashObjectList);override;
  215. procedure MemPos_Start;override;
  216. procedure MemPos_ExeSection(const aname:string);override;
  217. end;
  218. TObjSymbolArray = array[0..high(word)] of TObjSymbol;
  219. TObjSectionArray = array[0..high(smallint)] of TObjSection;
  220. TDJCoffAssembler = class(tinternalassembler)
  221. constructor create(smart:boolean);override;
  222. end;
  223. TPECoffassembler = class(tinternalassembler)
  224. constructor create(smart:boolean);override;
  225. end;
  226. type
  227. Treaddllproc = procedure(const dllname,funcname:string) of object;
  228. const
  229. {$ifdef i386}
  230. COFF_MAGIC = $14c;
  231. COFF_OPT_MAGIC = $10b;
  232. TLSDIR_SIZE = $18;
  233. {$endif i386}
  234. {$ifdef arm}
  235. COFF_MAGIC = $1c0;
  236. COFF_OPT_MAGIC = $10b;
  237. TLSDIR_SIZE = $18;
  238. {$endif arm}
  239. {$ifdef x86_64}
  240. COFF_MAGIC = $8664;
  241. COFF_OPT_MAGIC = $20b;
  242. TLSDIR_SIZE = $28;
  243. {$endif x86_64}
  244. function ReadDLLImports(const dllname:string;readdllproc:Treaddllproc):boolean;
  245. implementation
  246. uses
  247. {$ifdef win32}
  248. Windows,
  249. {$endif win32}
  250. SysUtils,
  251. cutils,verbose,globals,
  252. fmodule,aasmtai,aasmdata,
  253. ogmap,
  254. version
  255. ;
  256. const
  257. COFF_FLAG_NORELOCS = $0001;
  258. COFF_FLAG_EXE = $0002;
  259. COFF_FLAG_NOLINES = $0004;
  260. COFF_FLAG_NOLSYMS = $0008;
  261. COFF_FLAG_AR16WR = $0080; { 16bit little endian }
  262. COFF_FLAG_AR32WR = $0100; { 32bit little endian }
  263. COFF_FLAG_AR32W = $0200; { 32bit big endian }
  264. COFF_FLAG_DLL = $2000;
  265. COFF_SYM_GLOBAL = 2;
  266. COFF_SYM_LOCAL = 3;
  267. COFF_SYM_LABEL = 6;
  268. COFF_SYM_FUNCTION = 101;
  269. COFF_SYM_FILE = 103;
  270. COFF_SYM_SECTION = 104;
  271. COFF_STYP_REG = $0000; { "regular": allocated, relocated, loaded }
  272. COFF_STYP_DSECT = $0001; { "dummy": relocated only }
  273. COFF_STYP_NOLOAD = $0002; { "noload": allocated, relocated, not loaded }
  274. COFF_STYP_GROUP = $0004; { "grouped": formed of input sections }
  275. COFF_STYP_PAD = $0008;
  276. COFF_STYP_COPY = $0010;
  277. COFF_STYP_TEXT = $0020;
  278. COFF_STYP_DATA = $0040;
  279. COFF_STYP_BSS = $0080;
  280. COFF_STYP_INFO = $0200;
  281. COFF_STYP_OVER = $0400;
  282. COFF_STYP_LIB = $0800;
  283. PE_SUBSYSTEM_NATIVE = 1;
  284. PE_SUBSYSTEM_WINDOWS_GUI = 2;
  285. PE_SUBSYSTEM_WINDOWS_CUI = 3;
  286. PE_SUBSYSTEM_WINDOWS_CE_GUI = 9;
  287. PE_FILE_RELOCS_STRIPPED = $0001;
  288. PE_FILE_EXECUTABLE_IMAGE = $0002;
  289. PE_FILE_LINE_NUMS_STRIPPED = $0004;
  290. PE_FILE_LOCAL_SYMS_STRIPPED = $0008;
  291. PE_FILE_AGGRESSIVE_WS_TRIM = $0010;
  292. PE_FILE_LARGE_ADDRESS_AWARE = $0020;
  293. PE_FILE_16BIT_MACHINE = $0040;
  294. PE_FILE_BYTES_REVERSED_LO = $0080;
  295. PE_FILE_32BIT_MACHINE = $0100;
  296. PE_FILE_DEBUG_STRIPPED = $0200;
  297. PE_FILE_REMOVABLE_RUN_FROM_SWAP = $0400;
  298. PE_FILE_NET_RUN_FROM_SWAP = $0800;
  299. PE_FILE_SYSTEM = $1000;
  300. PE_FILE_DLL = $2000;
  301. PE_FILE_UP_SYSTEM_ONLY = $4000;
  302. PE_FILE_BYTES_REVERSED_HI = $8000;
  303. PE_SCN_CNT_CODE = $00000020; { Section contains code. }
  304. PE_SCN_CNT_INITIALIZED_DATA = $00000040; { Section contains initialized data. }
  305. PE_SCN_CNT_UNINITIALIZED_DATA = $00000080; { Section contains uninitialized data. }
  306. PE_SCN_LNK_OTHER = $00000100; { Reserved. }
  307. PE_SCN_LNK_INFO = $00000200; { Section contains comments or some other type of information. }
  308. PE_SCN_LNK_REMOVE = $00000800; { Section contents will not become part of image. }
  309. PE_SCN_LNK_COMDAT = $00001000; { Section contents comdat. }
  310. PE_SCN_MEM_FARDATA = $00008000;
  311. PE_SCN_MEM_PURGEABLE = $00020000;
  312. PE_SCN_MEM_16BIT = $00020000;
  313. PE_SCN_MEM_LOCKED = $00040000;
  314. PE_SCN_MEM_PRELOAD = $00080000;
  315. PE_SCN_ALIGN_MASK = $00f00000;
  316. PE_SCN_ALIGN_1BYTES = $00100000;
  317. PE_SCN_ALIGN_2BYTES = $00200000;
  318. PE_SCN_ALIGN_4BYTES = $00300000;
  319. PE_SCN_ALIGN_8BYTES = $00400000;
  320. PE_SCN_ALIGN_16BYTES = $00500000; { Default alignment if no others are specified. }
  321. PE_SCN_ALIGN_32BYTES = $00600000;
  322. PE_SCN_ALIGN_64BYTES = $00700000;
  323. PE_SCN_LNK_NRELOC_OVFL = $01000000; { Section contains extended relocations. }
  324. PE_SCN_MEM_NOT_CACHED = $04000000; { Section is not cachable. }
  325. PE_SCN_MEM_NOT_PAGED = $08000000; { Section is not pageable. }
  326. PE_SCN_MEM_SHARED = $10000000; { Section is shareable. }
  327. PE_SCN_MEM_DISCARDABLE = $02000000;
  328. PE_SCN_MEM_EXECUTE = $20000000;
  329. PE_SCN_MEM_READ = $40000000;
  330. PE_SCN_MEM_WRITE = $80000000;
  331. PE_DATADIR_EDATA = 0;
  332. PE_DATADIR_IDATA = 1;
  333. PE_DATADIR_RSRC = 2;
  334. PE_DATADIR_PDATA = 3;
  335. PE_DATADIR_SECURITY = 4;
  336. PE_DATADIR_RELOC = 5;
  337. PE_DATADIR_DEBUG = 6;
  338. PE_DATADIR_DESCRIPTION = 7;
  339. PE_DATADIR_SPECIAL = 8;
  340. PE_DATADIR_TLS = 9;
  341. PE_DATADIR_LOADCFG = 10;
  342. PE_DATADIR_BOUNDIMPORT = 11;
  343. PE_DATADIR_IMPORTADDRESSTABLE = 12;
  344. PE_DATADIR_DELAYIMPORT = 13;
  345. {$ifdef x86_64}
  346. IMAGE_REL_AMD64_ABSOLUTE = $0000; { Reference is absolute, no relocation is necessary }
  347. IMAGE_REL_AMD64_ADDR64 = $0001; { 64-bit address (VA). }
  348. IMAGE_REL_AMD64_ADDR32 = $0002; { 32-bit address (VA). }
  349. IMAGE_REL_AMD64_ADDR32NB = $0003; { 32-bit address w/o image base (RVA). }
  350. IMAGE_REL_AMD64_REL32 = $0004; { 32-bit relative address from byte following reloc }
  351. IMAGE_REL_AMD64_REL32_1 = $0005; { 32-bit relative address from byte distance 1 from reloc }
  352. IMAGE_REL_AMD64_REL32_2 = $0006; { 32-bit relative address from byte distance 2 from reloc }
  353. IMAGE_REL_AMD64_REL32_3 = $0007; { 32-bit relative address from byte distance 3 from reloc }
  354. IMAGE_REL_AMD64_REL32_4 = $0008; { 32-bit relative address from byte distance 4 from reloc }
  355. IMAGE_REL_AMD64_REL32_5 = $0009; { 32-bit relative address from byte distance 5 from reloc }
  356. IMAGE_REL_AMD64_SECTION = $000A; { Section index }
  357. IMAGE_REL_AMD64_SECREL = $000B; { 32 bit offset from base of section containing target }
  358. IMAGE_REL_AMD64_SECREL7 = $000C; { 7 bit unsigned offset from base of section containing target }
  359. IMAGE_REL_AMD64_TOKEN = $000D; { 32 bit metadata token }
  360. IMAGE_REL_AMD64_SREL32 = $000E; { 32 bit signed span-dependent value emitted into object }
  361. IMAGE_REL_AMD64_PAIR = $000F;
  362. IMAGE_REL_AMD64_SSPAN32 = $0010; { 32 bit signed span-dependent value applied at link time }
  363. { Direct 32 bit sign extended,
  364. win64 mingw GNU compiler
  365. also generates this type
  366. inside coff objects
  367. We assume they are equivalent to
  368. IMAGE_REL_AMD64_ADDR32 PM 2010-11-27 }
  369. R_X86_64_32S = $11;
  370. {$endif x86_64}
  371. {$ifdef arm}
  372. IMAGE_REL_ARM_ABSOLUTE = $0000; { No relocation required }
  373. IMAGE_REL_ARM_ADDR32 = $0001; { 32 bit address }
  374. IMAGE_REL_ARM_ADDR32NB = $0002; { 32 bit address w/o image base }
  375. IMAGE_REL_ARM_BRANCH24 = $0003; { 24 bit offset << 2 & sign ext. }
  376. IMAGE_REL_ARM_BRANCH11 = $0004; { Thumb: 2 11 bit offsets }
  377. IMAGE_REL_ARM_TOKEN = $0005; { clr token }
  378. IMAGE_REL_ARM_GPREL12 = $0006; { GP-relative addressing (ARM) }
  379. IMAGE_REL_ARM_GPREL7 = $0007; { GP-relative addressing (Thumb) }
  380. IMAGE_REL_ARM_BLX24 = $0008;
  381. IMAGE_REL_ARM_BLX11 = $0009;
  382. IMAGE_REL_ARM_SECTION = $000E; { Section table index }
  383. IMAGE_REL_ARM_SECREL = $000F; { Offset within section }
  384. {$endif arm}
  385. {$ifdef i386}
  386. IMAGE_REL_I386_DIR32 = 6;
  387. IMAGE_REL_I386_IMAGEBASE = 7;
  388. IMAGE_REL_I386_SECREL32 = 11;
  389. IMAGE_REL_I386_PCRLONG = 20;
  390. {$endif i386}
  391. { .reloc section fixup types }
  392. IMAGE_REL_BASED_HIGHLOW = 3; { Applies the delta to the 32-bit field at Offset. }
  393. IMAGE_REL_BASED_DIR64 = 10; { Applies the delta to the 64-bit field at Offset. }
  394. { values for coffsectionrec.select }
  395. IMAGE_COMDAT_SELECT_NODUPLICATES = 1;
  396. IMAGE_COMDAT_SELECT_ANY = 2;
  397. IMAGE_COMDAT_SELECT_SAME_SIZE = 3;
  398. IMAGE_COMDAT_SELECT_EXACT_MATCH = 4;
  399. IMAGE_COMDAT_SELECT_ASSOCIATIVE = 5;
  400. IMAGE_COMDAT_SELECT_LARGEST = 6;
  401. type
  402. coffdjoptheader=packed record
  403. magic : word;
  404. vstamp : word;
  405. tsize : longint;
  406. dsize : longint;
  407. bsize : longint;
  408. entry : longint;
  409. text_start : longint;
  410. data_start : longint;
  411. end;
  412. coffsectionrec=packed record
  413. len : longword;
  414. nrelocs : word;
  415. nlines : word;
  416. checksum: longword;
  417. assoc : word;
  418. select : byte;
  419. empty : array[0..2] of char;
  420. end;
  421. coffreloc=packed record
  422. address : longword;
  423. sym : longword;
  424. reloctype : word;
  425. end;
  426. coffsymbol=packed record
  427. name : array[0..3] of char; { real is [0..7], which overlaps the strpos ! }
  428. strpos : longword;
  429. value : longword;
  430. section : smallint;
  431. empty : word; { actually type, $20: function, 0: not a function }
  432. typ : byte;
  433. aux : byte;
  434. end;
  435. { This is defined in rtl/win/sysos.inc source }
  436. tlsdirectory=packed record
  437. data_start, data_end : PUInt;
  438. index_pointer, callbacks_pointer : PUInt;
  439. zero_fill_size : dword;
  440. flags : dword;
  441. end;
  442. const
  443. SymbolMaxGrow = 200*sizeof(coffsymbol);
  444. StrsMaxGrow = 8192;
  445. coffsecnames : array[TAsmSectiontype] of string[length('__DATA, __datacoal_nt,coalesced')] = ('','',
  446. '.text','.data','.rdata','.rdata','.bss','.tls',
  447. '.pdata',{pdata}
  448. '.text', {stub}
  449. '.data',
  450. '.data',
  451. '.data',
  452. '.data',
  453. '.stab','.stabstr',
  454. '.idata$2','.idata$4','.idata$5','.idata$6','.idata$7','.edata',
  455. '.eh_frame',
  456. '.debug_frame','.debug_info','.debug_line','.debug_abbrev',
  457. '.fpc',
  458. '',
  459. '.init',
  460. '.fini',
  461. '.objc_class',
  462. '.objc_meta_class',
  463. '.objc_cat_cls_meth',
  464. '.objc_cat_inst_meth',
  465. '.objc_protocol',
  466. '.objc_string_object',
  467. '.objc_cls_meth',
  468. '.objc_inst_meth',
  469. '.objc_cls_refs',
  470. '.objc_message_refs',
  471. '.objc_symbols',
  472. '.objc_category',
  473. '.objc_class_vars',
  474. '.objc_instance_vars',
  475. '.objc_module_info',
  476. '.objc_class_names',
  477. '.objc_meth_var_types',
  478. '.objc_meth_var_names',
  479. '.objc_selector_strs',
  480. '.objc_protocol_ext',
  481. '.objc_class_ext',
  482. '.objc_property',
  483. '.objc_image_info',
  484. '.objc_cstring_object',
  485. '.objc_sel_fixup',
  486. '__DATA,__objc_data',
  487. '__DATA,__objc_const',
  488. '.objc_superrefs',
  489. '__DATA, __datacoal_nt,coalesced',
  490. '.objc_classlist',
  491. '.objc_nlclasslist',
  492. '.objc_catlist',
  493. '.obcj_nlcatlist',
  494. '.objc_protolist',
  495. '.stack',
  496. '.heap'
  497. );
  498. const go32v2stub : array[0..2047] of byte=(
  499. $4D,$5A,$00,$00,$04,$00,$00,$00,$20,$00,$27,$00,$FF,$FF,$00,
  500. $00,$60,$07,$00,$00,$54,$00,$00,$00,$00,$00,$00,$00,$0D,$0A,
  501. $73,$74,$75,$62,$2E,$68,$20,$67,$65,$6E,$65,$72,$61,$74,$65,
  502. $64,$20,$66,$72,$6F,$6D,$20,$73,$74,$75,$62,$2E,$61,$73,$6D,
  503. $20,$62,$79,$20,$64,$6A,$61,$73,$6D,$2C,$20,$6F,$6E,$20,$54,
  504. $68,$75,$20,$44,$65,$63,$20,$20,$39,$20,$31,$30,$3A,$35,$39,
  505. $3A,$33,$31,$20,$31,$39,$39,$39,$0D,$0A,$54,$68,$65,$20,$53,
  506. $54,$55,$42,$2E,$45,$58,$45,$20,$73,$74,$75,$62,$20,$6C,$6F,
  507. $61,$64,$65,$72,$20,$69,$73,$20,$43,$6F,$70,$79,$72,$69,$67,
  508. $68,$74,$20,$28,$43,$29,$20,$31,$39,$39,$33,$2D,$31,$39,$39,
  509. $35,$20,$44,$4A,$20,$44,$65,$6C,$6F,$72,$69,$65,$2E,$20,$0D,
  510. $0A,$50,$65,$72,$6D,$69,$73,$73,$69,$6F,$6E,$20,$67,$72,$61,
  511. $6E,$74,$65,$64,$20,$74,$6F,$20,$75,$73,$65,$20,$66,$6F,$72,
  512. $20,$61,$6E,$79,$20,$70,$75,$72,$70,$6F,$73,$65,$20,$70,$72,
  513. $6F,$76,$69,$64,$65,$64,$20,$74,$68,$69,$73,$20,$63,$6F,$70,
  514. $79,$72,$69,$67,$68,$74,$20,$0D,$0A,$72,$65,$6D,$61,$69,$6E,
  515. $73,$20,$70,$72,$65,$73,$65,$6E,$74,$20,$61,$6E,$64,$20,$75,
  516. $6E,$6D,$6F,$64,$69,$66,$69,$65,$64,$2E,$20,$0D,$0A,$54,$68,
  517. $69,$73,$20,$6F,$6E,$6C,$79,$20,$61,$70,$70,$6C,$69,$65,$73,
  518. $20,$74,$6F,$20,$74,$68,$65,$20,$73,$74,$75,$62,$2C,$20,$61,
  519. $6E,$64,$20,$6E,$6F,$74,$20,$6E,$65,$63,$65,$73,$73,$61,$72,
  520. $69,$6C,$79,$20,$74,$68,$65,$20,$77,$68,$6F,$6C,$65,$20,$70,
  521. $72,$6F,$67,$72,$61,$6D,$2E,$0A,$0D,$0A,$24,$49,$64,$3A,$20,
  522. $73,$74,$75,$62,$2E,$61,$73,$6D,$20,$62,$75,$69,$6C,$74,$20,
  523. $31,$32,$2F,$30,$39,$2F,$39,$39,$20,$31,$30,$3A,$35,$39,$3A,
  524. $33,$31,$20,$62,$79,$20,$64,$6A,$61,$73,$6D,$20,$24,$0A,$0D,
  525. $0A,$40,$28,$23,$29,$20,$73,$74,$75,$62,$2E,$61,$73,$6D,$20,
  526. $62,$75,$69,$6C,$74,$20,$31,$32,$2F,$30,$39,$2F,$39,$39,$20,
  527. $31,$30,$3A,$35,$39,$3A,$33,$31,$20,$62,$79,$20,$64,$6A,$61,
  528. $73,$6D,$0A,$0D,$0A,$1A,$00,$00,$00,$00,$00,$00,$00,$00,$00,
  529. $00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,
  530. $00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,
  531. $00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,
  532. $00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,
  533. $00,$00,$67,$6F,$33,$32,$73,$74,$75,$62,$2C,$20,$76,$20,$32,
  534. $2E,$30,$32,$54,$00,$00,$00,$00,$00,$08,$00,$00,$00,$00,$00,
  535. $00,$00,$00,$00,$00,$40,$00,$00,$00,$00,$00,$00,$00,$00,$00,
  536. $00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,
  537. $00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$43,$57,$53,$44,$50,
  538. $4D,$49,$2E,$45,$58,$45,$00,$00,$00,$00,$00,$0E,$1F,$8C,$1E,
  539. $24,$00,$8C,$06,$60,$07,$FC,$B4,$30,$CD,$21,$3C,$03,$73,$08,
  540. $B0,$6D,$BA,$A7,$05,$E9,$D4,$03,$A2,$69,$08,$BE,$20,$00,$8B,
  541. $04,$09,$C0,$75,$02,$B4,$FE,$BB,$70,$08,$39,$C3,$73,$02,$89,
  542. $C3,$89,$1C,$FE,$C7,$B9,$04,$FF,$D3,$EB,$B4,$4A,$CD,$21,$73,
  543. $08,$D3,$E3,$FE,$CF,$89,$1C,$EB,$D8,$26,$8E,$06,$2C,$00,$31,
  544. $FF,$30,$C0,$A9,$F2,$AE,$26,$81,$3D,$50,$41,$75,$15,$AF,$26,
  545. $81,$3D,$54,$48,$75,$0D,$AF,$26,$80,$3D,$3D,$75,$06,$47,$89,
  546. $3E,$8C,$04,$4F,$AE,$75,$DF,$AF,$B4,$3E,$BB,$13,$00,$CD,$21,
  547. $B4,$3E,$BB,$12,$00,$CD,$21,$06,$57,$31,$C9,$74,$12,$B0,$6E,
  548. $BA,$7E,$05,$E9,$5E,$03,$09,$C9,$75,$F4,$41,$E8,$A1,$03,$72,
  549. $EE,$B8,$87,$16,$CD,$2F,$09,$C0,$75,$ED,$80,$E3,$01,$74,$E8,
  550. $89,$3E,$00,$06,$8C,$06,$02,$06,$89,$36,$04,$06,$5F,$07,$E8,
  551. $D3,$02,$89,$3E,$2A,$00,$89,$36,$62,$07,$80,$3E,$2C,$00,$00,
  552. $74,$23,$B9,$08,$00,$BF,$2C,$00,$8A,$05,$47,$08,$C0,$74,$05,
  553. $88,$07,$43,$E2,$F4,$66,$C7,$07,$2E,$45,$58,$45,$83,$C3,$04,
  554. $C6,$07,$00,$89,$1E,$62,$07,$B8,$00,$3D,$BA,$64,$07,$CD,$21,
  555. $0F,$82,$B3,$02,$A3,$06,$06,$89,$C3,$B9,$06,$00,$BA,$B5,$07,
  556. $B4,$3F,$CD,$21,$31,$D2,$31,$C9,$A1,$B5,$07,$3D,$4C,$01,$74,
  557. $1B,$3D,$4D,$5A,$0F,$85,$98,$02,$8B,$16,$B9,$07,$C1,$E2,$09,
  558. $8B,$1E,$B7,$07,$09,$DB,$74,$05,$80,$EE,$02,$01,$DA,$89,$16,
  559. $BB,$07,$89,$0E,$BD,$07,$B8,$00,$42,$8B,$1E,$06,$06,$CD,$21,
  560. $B9,$A8,$00,$BA,$BF,$07,$B4,$3F,$CD,$21,$3D,$A8,$00,$75,$06,
  561. $81,$3E,$BF,$07,$4C,$01,$0F,$85,$61,$02,$66,$A1,$E3,$07,$66,
  562. $A3,$10,$06,$66,$8B,$0E,$BB,$07,$66,$A1,$03,$08,$66,$01,$C8,
  563. $66,$A3,$08,$06,$66,$A1,$2B,$08,$66,$01,$C8,$66,$A3,$0C,$06,
  564. $66,$8B,$1E,$4B,$08,$66,$A1,$4F,$08,$66,$01,$C3,$66,$B8,$01,
  565. $00,$01,$00,$66,$39,$C3,$73,$03,$66,$89,$C3,$66,$81,$C3,$FF,
  566. $FF,$00,$00,$31,$DB,$66,$89,$1E,$1C,$00,$E8,$F5,$02,$8B,$1E,
  567. $04,$06,$09,$DB,$74,$0A,$B4,$48,$CD,$21,$0F,$82,$15,$02,$8E,
  568. $C0,$E8,$08,$03,$B8,$01,$00,$FF,$1E,$00,$06,$0F,$82,$0F,$02,
  569. $8C,$06,$26,$00,$8C,$0E,$28,$00,$8C,$D8,$A3,$22,$00,$8E,$C0,
  570. $31,$C0,$B9,$01,$00,$CD,$31,$72,$07,$A3,$14,$06,$31,$C0,$CD,
  571. $31,$0F,$82,$F3,$01,$A3,$16,$06,$66,$8B,$0E,$1C,$00,$B8,$01,
  572. $05,$8B,$1E,$1E,$00,$CD,$31,$0F,$82,$E5,$01,$89,$1E,$1A,$06,
  573. $89,$0E,$18,$06,$89,$36,$1A,$00,$89,$3E,$18,$00,$B8,$07,$00,
  574. $8B,$1E,$14,$06,$8B,$0E,$1A,$06,$8B,$16,$18,$06,$CD,$31,$B8,
  575. $09,$00,$8C,$C9,$83,$E1,$03,$C1,$E1,$05,$51,$81,$C9,$9B,$C0,
  576. $CD,$31,$B8,$08,$00,$8B,$0E,$1E,$00,$49,$BA,$FF,$FF,$CD,$31,
  577. $B8,$07,$00,$8B,$1E,$16,$06,$8B,$0E,$1A,$06,$8B,$16,$18,$06,
  578. $CD,$31,$B8,$09,$00,$59,$81,$C9,$93,$C0,$CD,$31,$B8,$08,$00,
  579. $8B,$0E,$1E,$00,$49,$BA,$FF,$FF,$CD,$31,$B8,$00,$01,$BB,$00,
  580. $0F,$CD,$31,$73,$10,$3D,$08,$00,$0F,$85,$73,$01,$B8,$00,$01,
  581. $CD,$31,$0F,$82,$6A,$01,$A3,$1C,$06,$89,$16,$1E,$06,$C1,$E3,
  582. $04,$89,$1E,$20,$06,$66,$8B,$36,$08,$06,$66,$8B,$3E,$FB,$07,
  583. $66,$8B,$0E,$FF,$07,$E8,$49,$00,$66,$8B,$36,$0C,$06,$66,$8B,
  584. $3E,$23,$08,$66,$8B,$0E,$27,$08,$E8,$37,$00,$8E,$06,$16,$06,
  585. $66,$8B,$3E,$4B,$08,$66,$8B,$0E,$4F,$08,$66,$31,$C0,$66,$C1,
  586. $E9,$02,$67,$F3,$66,$AB,$B4,$3E,$8B,$1E,$06,$06,$CD,$21,$B8,
  587. $01,$01,$8B,$16,$1E,$06,$CD,$31,$1E,$0F,$A1,$8E,$1E,$16,$06,
  588. $66,$64,$FF,$2E,$10,$06,$66,$89,$F0,$66,$25,$FF,$01,$00,$00,
  589. $66,$01,$C1,$29,$C6,$66,$29,$C7,$66,$89,$0E,$26,$06,$66,$89,
  590. $3E,$22,$06,$E8,$0F,$01,$89,$36,$3E,$06,$66,$C1,$EE,$10,$89,
  591. $36,$42,$06,$8B,$1E,$06,$06,$89,$1E,$3A,$06,$C7,$06,$46,$06,
  592. $00,$42,$E8,$03,$01,$A1,$1C,$06,$A3,$4E,$06,$C7,$06,$3E,$06,
  593. $00,$00,$C6,$06,$47,$06,$3F,$A1,$28,$06,$09,$C0,$75,$09,$A1,
  594. $26,$06,$3B,$06,$20,$06,$76,$03,$A1,$20,$06,$A3,$42,$06,$E8,
  595. $D9,$00,$66,$31,$C9,$8B,$0E,$46,$06,$66,$8B,$3E,$22,$06,$66,
  596. $01,$0E,$22,$06,$66,$29,$0E,$26,$06,$66,$31,$F6,$C1,$E9,$02,
  597. $1E,$06,$8E,$06,$16,$06,$8E,$1E,$1E,$06,$67,$F3,$66,$A5,$07,
  598. $1F,$66,$03,$0E,$26,$06,$75,$AF,$C3,$3C,$3A,$74,$06,$3C,$2F,
  599. $74,$02,$3C,$5C,$C3,$BE,$64,$07,$89,$F3,$26,$8A,$05,$47,$88,
  600. $04,$38,$E0,$74,$0E,$08,$C0,$74,$0A,$46,$E8,$DE,$FF,$75,$EC,
  601. $89,$F3,$74,$E8,$C3,$B0,$66,$BA,$48,$05,$EB,$0C,$B0,$67,$BA,
  602. $55,$05,$EB,$05,$B0,$68,$BA,$5F,$05,$52,$8B,$1E,$62,$07,$C6,
  603. $07,$24,$BB,$64,$07,$EB,$28,$E8,$F5,$00,$B0,$69,$BA,$99,$05,
  604. $EB,$1A,$B0,$6A,$BA,$B2,$05,$EB,$13,$B0,$6B,$BA,$C4,$05,$EB,
  605. $0C,$B0,$6C,$BA,$D6,$05,$EB,$05,$B0,$69,$BA,$99,$05,$52,$BB,
  606. $3B,$05,$E8,$15,$00,$5B,$E8,$11,$00,$BB,$67,$04,$E8,$0B,$00,
  607. $B4,$4C,$CD,$21,$43,$50,$B4,$02,$CD,$21,$58,$8A,$17,$80,$FA,
  608. $24,$75,$F2,$C3,$0D,$0A,$24,$50,$51,$57,$31,$C0,$BF,$2A,$06,
  609. $B9,$19,$00,$F3,$AB,$5F,$59,$58,$C3,$B8,$00,$03,$BB,$21,$00,
  610. $31,$C9,$66,$BF,$2A,$06,$00,$00,$CD,$31,$C3,$00,$00,$30,$E4,
  611. $E8,$4E,$FF,$89,$DE,$8B,$3E,$8C,$04,$EB,$17,$B4,$3B,$E8,$41,
  612. $FF,$81,$FE,$64,$07,$74,$12,$8A,$44,$FF,$E8,$2A,$FF,$74,$04,
  613. $C6,$04,$5C,$46,$E8,$03,$00,$72,$E4,$C3,$E8,$34,$00,$BB,$44,
  614. $00,$8A,$07,$88,$04,$43,$46,$08,$C0,$75,$F6,$06,$57,$1E,$07,
  615. $E8,$9B,$FF,$BB,$2A,$06,$8C,$5F,$04,$89,$5F,$02,$BA,$64,$07,
  616. $B8,$00,$4B,$CD,$21,$5F,$07,$72,$09,$B4,$4D,$CD,$21,$2D,$00,
  617. $03,$F7,$D8,$EB,$28,$80,$3E,$69,$08,$05,$72,$20,$B8,$00,$58,
  618. $CD,$21,$A2,$67,$08,$B8,$02,$58,$CD,$21,$A2,$68,$08,$B8,$01,
  619. $58,$BB,$80,$00,$CD,$21,$B8,$03,$58,$BB,$01,$00,$CD,$21,$C3,
  620. $9C,$80,$3E,$69,$08,$05,$72,$1A,$50,$53,$B8,$03,$58,$8A,$1E,
  621. $68,$08,$30,$FF,$CD,$21,$B8,$01,$58,$8A,$1E,$67,$08,$30,$FF,
  622. $CD,$21,$5B,$58,$9D,$C3,$4C,$6F,$61,$64,$20,$65,$72,$72,$6F,
  623. $72,$3A,$20,$24,$3A,$20,$63,$61,$6E,$27,$74,$20,$6F,$70,$65,
  624. $6E,$24,$3A,$20,$6E,$6F,$74,$20,$45,$58,$45,$24,$3A,$20,$6E,
  625. $6F,$74,$20,$43,$4F,$46,$46,$20,$28,$43,$68,$65,$63,$6B,$20,
  626. $66,$6F,$72,$20,$76,$69,$72,$75,$73,$65,$73,$29,$24,$6E,$6F,
  627. $20,$44,$50,$4D,$49,$20,$2D,$20,$47,$65,$74,$20,$63,$73,$64,
  628. $70,$6D,$69,$2A,$62,$2E,$7A,$69,$70,$24,$6E,$6F,$20,$44,$4F,
  629. $53,$20,$6D,$65,$6D,$6F,$72,$79,$24,$6E,$65,$65,$64,$20,$44,
  630. $4F,$53,$20,$33,$24,$63,$61,$6E,$27,$74,$20,$73,$77,$69,$74,
  631. $63,$68,$20,$6D,$6F,$64,$65,$24,$6E,$6F,$20,$44,$50,$4D,$49,
  632. $20,$73,$65,$6C,$65,$63,$74,$6F,$72,$73,$24,$6E,$6F,$20,$44,
  633. $50,$4D,$49,$20,$6D,$65,$6D,$6F,$72,$79,$24,$90,$90,$90,$90,
  634. $90,$90,$90,$90,$90,$90,$90,$90,$90,$90,$90,$90,$90,$90,$90,
  635. $90,$90,$90,$90,$90,$90,$90,$90);
  636. const win32stub : array[0..127] of byte=(
  637. $4D,$5A,$90,$00,$03,$00,$00,$00,$04,$00,$00,$00,$FF,$FF,$00,$00,
  638. $B8,$00,$00,$00,$00,$00,$00,$00,$40,$00,$00,$00,$00,$00,$00,$00,
  639. $00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,
  640. $00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$80,$00,$00,$00,
  641. $0E,$1F,$BA,$0E,$00,$B4,$09,$CD,$21,$B8,$01,$4C,$CD,$21,$54,$68,
  642. $69,$73,$20,$70,$72,$6F,$67,$72,$61,$6D,$20,$63,$61,$6E,$6E,$6F,
  643. $74,$20,$62,$65,$20,$72,$75,$6E,$20,$69,$6E,$20,$44,$4F,$53,$20,
  644. $6D,$6F,$64,$65,$2E,$0D,$0D,$0A,$24,$00,$00,$00,$00,$00,$00,$00);
  645. const pemagic : array[0..3] of byte = (
  646. $50,$45,$00,$00);
  647. {****************************************************************************
  648. Helpers
  649. ****************************************************************************}
  650. function djencodesechdrflags(aoptions:TObjSectionOptions):longword;
  651. begin
  652. if (oso_load in aoptions) then
  653. begin
  654. if oso_executable in aoptions then
  655. result:=COFF_STYP_TEXT
  656. else if not(oso_data in aoptions) then
  657. result:=COFF_STYP_BSS
  658. else
  659. result:=COFF_STYP_DATA;
  660. end
  661. else if oso_debug in aoptions then
  662. result:=COFF_STYP_INFO
  663. else
  664. result:=COFF_STYP_REG;
  665. end;
  666. function djdecodesechdrflags(const aname:string;flags:longword):TObjSectionOptions;
  667. begin
  668. result:=[];
  669. if flags and COFF_STYP_TEXT<>0 then
  670. result:=[oso_data,oso_load,oso_executable]
  671. else if flags and COFF_STYP_BSS<>0 then
  672. result:=[oso_load]
  673. else if flags and COFF_STYP_DATA<>0 then
  674. result:=[oso_data,oso_load]
  675. else if flags and COFF_STYP_INFO<>0 then
  676. result:=[oso_data,oso_debug]
  677. else
  678. result:=[oso_data]
  679. end;
  680. function peencodesechdrflags(aoptions:TObjSectionOptions;aalign:shortint):longword;
  681. begin
  682. if oso_executable in aoptions then
  683. result:=PE_SCN_CNT_CODE or PE_SCN_MEM_EXECUTE
  684. else
  685. begin
  686. if (oso_data in aoptions) then
  687. result:=PE_SCN_CNT_INITIALIZED_DATA
  688. else
  689. result:=PE_SCN_CNT_UNINITIALIZED_DATA;
  690. end;
  691. if oso_write in aoptions then
  692. result:=result or PE_SCN_MEM_WRITE or PE_SCN_MEM_READ
  693. else
  694. result:=result or PE_SCN_MEM_READ;
  695. if not (oso_load in aoptions) then
  696. result:=result or PE_SCN_MEM_DISCARDABLE;
  697. case aalign of
  698. 1 : result:=result or PE_SCN_ALIGN_1BYTES;
  699. 2 : result:=result or PE_SCN_ALIGN_2BYTES;
  700. 4 : result:=result or PE_SCN_ALIGN_4BYTES;
  701. 8 : result:=result or PE_SCN_ALIGN_8BYTES;
  702. 16 : result:=result or PE_SCN_ALIGN_16BYTES;
  703. 32 : result:=result or PE_SCN_ALIGN_32BYTES;
  704. 64 : result:=result or PE_SCN_ALIGN_64BYTES;
  705. else result:=result or PE_SCN_ALIGN_16BYTES;
  706. end;
  707. end;
  708. procedure pedecodesechdrflags(const aname:string;flags:longword;out aoptions:TObjSectionOptions;out aalign:shortint);
  709. var
  710. alignflag : longword;
  711. begin
  712. aoptions:=[];
  713. if flags and PE_SCN_CNT_CODE<>0 then
  714. include(aoptions,oso_executable);
  715. if flags and PE_SCN_MEM_DISCARDABLE<>0 then
  716. include(aoptions,oso_debug);
  717. if flags and PE_SCN_CNT_UNINITIALIZED_DATA=0 then
  718. include(aoptions,oso_data);
  719. if (flags and (PE_SCN_LNK_REMOVE or PE_SCN_MEM_DISCARDABLE)=0) then
  720. include(aoptions,oso_load);
  721. { read/write }
  722. if flags and PE_SCN_MEM_WRITE<>0 then
  723. include(aoptions,oso_write);
  724. { alignment }
  725. alignflag:=flags and PE_SCN_ALIGN_MASK;
  726. if alignflag=PE_SCN_ALIGN_64BYTES then
  727. aalign:=64
  728. else if alignflag=PE_SCN_ALIGN_32BYTES then
  729. aalign:=32
  730. else if alignflag=PE_SCN_ALIGN_16BYTES then
  731. aalign:=16
  732. else if alignflag=PE_SCN_ALIGN_8BYTES then
  733. aalign:=8
  734. else if alignflag=PE_SCN_ALIGN_4BYTES then
  735. aalign:=4
  736. else if alignflag=PE_SCN_ALIGN_2BYTES then
  737. aalign:=2
  738. else if alignflag=PE_SCN_ALIGN_1BYTES then
  739. aalign:=1
  740. else if alignflag=0 then
  741. aalign:=0
  742. else
  743. Internalerror(2009050401);
  744. end;
  745. {****************************************************************************
  746. TCoffObjSection
  747. ****************************************************************************}
  748. constructor TCoffObjSection.create(AList:TFPHashObjectList;const aname:string;aalign:shortint;aoptions:TObjSectionOptions);
  749. begin
  750. inherited create(AList,aname,aalign,aoptions);
  751. end;
  752. procedure TCoffObjSection.writereloc_internal(aTarget:TObjSection;offset:aword;len:byte;reltype:TObjRelocationType);
  753. begin
  754. AddSectionReloc(size,aTarget,reltype);
  755. write(offset,len);
  756. end;
  757. { We don't want overflow nor range checks here,
  758. wrapping is accepted in the address computation below }
  759. {$r-}
  760. {$q-}
  761. procedure TCoffExeOutput.DoRelocationFixup(objsec:TObjSection);
  762. var
  763. i,zero,address_size : longint;
  764. objreloc : TObjRelocation;
  765. address,
  766. relocval : aint;
  767. relocsec : TObjSection;
  768. {$ifdef cpu64bitaddr}
  769. s : string;
  770. {$endif cpu64bitaddr}
  771. data : TDynamicArray;
  772. begin
  773. data:=objsec.data;
  774. for i:=0 to objsec.ObjRelocations.Count-1 do
  775. begin
  776. objreloc:=TObjRelocation(objsec.ObjRelocations[i]);
  777. address_size:=4;
  778. case objreloc.typ of
  779. RELOC_NONE:
  780. continue;
  781. RELOC_ZERO:
  782. begin
  783. data.Seek(objreloc.dataoffset);
  784. zero:=0;
  785. data.Write(zero,4);
  786. continue;
  787. end;
  788. {$ifdef cpu64bitaddr}
  789. RELOC_ABSOLUTE:
  790. address_size:=8;
  791. {$endif cpu64bitaddr}
  792. end;
  793. address:=0;
  794. data.Seek(objreloc.dataoffset);
  795. data.Read(address,address_size);
  796. if assigned(objreloc.symbol) then
  797. begin
  798. relocsec:=objreloc.symbol.objsection;
  799. relocval:=objreloc.symbol.address;
  800. end
  801. else
  802. if assigned(objreloc.objsection) then
  803. begin
  804. relocsec:=objreloc.objsection;
  805. relocval:=objreloc.objsection.mempos
  806. end
  807. else
  808. internalerror(200205183);
  809. { Only debug sections are allowed to have relocs pointing to unused sections }
  810. if not relocsec.used and not (oso_debug in objsec.secoptions) then
  811. internalerror(200603061);
  812. if relocsec.used then
  813. case objreloc.typ of
  814. RELOC_RELATIVE :
  815. begin
  816. address:=address-objsec.mempos+relocval;
  817. if win32 then
  818. dec(address,objreloc.dataoffset+4);
  819. end;
  820. RELOC_RVA:
  821. begin
  822. { fixup address when the symbol was known in defined object }
  823. if (relocsec.objdata=objsec.objdata) then
  824. dec(address,TCoffObjSection(relocsec).orgmempos);
  825. {$ifdef arm}
  826. if (relocsec.objdata=objsec.objdata) and not TCoffObjData(objsec.objdata).eVCobj then
  827. inc(address, relocsec.MemPos)
  828. else
  829. {$endif arm}
  830. inc(address,relocval);
  831. end;
  832. RELOC_SECREL32 :
  833. begin
  834. { fixup address when the symbol was known in defined object }
  835. if (relocsec.objdata=objsec.objdata) then
  836. dec(address,relocsec.ExeSection.MemPos);
  837. inc(address,relocval);
  838. end;
  839. {$ifdef arm}
  840. RELOC_RELATIVE_24:
  841. begin
  842. relocval:=longint(relocval - objsec.mempos - objreloc.dataoffset) shr 2 - 2;
  843. address:=address or (relocval and $ffffff);
  844. relocval:=relocval shr 24;
  845. if (relocval<>$3f) and (relocval<>0) then
  846. internalerror(200606085); { offset overflow }
  847. end;
  848. {$endif arm}
  849. {$ifdef x86_64}
  850. { 64 bit coff only }
  851. RELOC_RELATIVE_1:
  852. begin
  853. address:=address-objsec.mempos+relocval;
  854. dec(address,objreloc.dataoffset+5);
  855. end;
  856. RELOC_RELATIVE_2:
  857. begin
  858. address:=address-objsec.mempos+relocval;
  859. dec(address,objreloc.dataoffset+6);
  860. end;
  861. RELOC_RELATIVE_3:
  862. begin
  863. address:=address-objsec.mempos+relocval;
  864. dec(address,objreloc.dataoffset+7);
  865. end;
  866. RELOC_RELATIVE_4:
  867. begin
  868. address:=address-objsec.mempos+relocval;
  869. dec(address,objreloc.dataoffset+8);
  870. end;
  871. RELOC_RELATIVE_5:
  872. begin
  873. address:=address-objsec.mempos+relocval;
  874. dec(address,objreloc.dataoffset+9);
  875. end;
  876. RELOC_ABSOLUTE32,
  877. {$endif x86_64}
  878. RELOC_ABSOLUTE :
  879. begin
  880. if (not win32) and assigned(objreloc.symbol) and
  881. (objreloc.symbol.bind=AB_COMMON) then
  882. begin
  883. dec(address,objreloc.symbol.size);
  884. end
  885. else
  886. begin
  887. { fixup address when the symbol was known in defined object }
  888. if (relocsec.objdata=objsec.objdata) then
  889. dec(address,TCoffObjSection(relocsec).orgmempos);
  890. end;
  891. {$ifdef arm}
  892. if (relocsec.objdata=objsec.objdata) and not TCoffObjData(objsec.objdata).eVCobj then
  893. inc(address, relocsec.MemPos)
  894. else
  895. {$endif arm}
  896. inc(address,relocval);
  897. inc(address,imagebase);
  898. end;
  899. else
  900. internalerror(200604014);
  901. end
  902. else
  903. address:=0; { Relocation in debug section points to unused section, which is eliminated by linker }
  904. data.Seek(objreloc.dataoffset);
  905. data.Write(address,address_size);
  906. {$ifdef cpu64bitaddr}
  907. if (objreloc.typ = RELOC_ABSOLUTE32) and (objsec.name <> '.stab') then
  908. begin
  909. if assigned(objreloc.symbol) then
  910. s:=objreloc.symbol.Name
  911. else
  912. s:=objreloc.objsection.Name;
  913. Message2(link_w_32bit_absolute_reloc, objsec.ObjData.Name, s);
  914. end;
  915. {$endif cpu64bitaddr}
  916. end;
  917. end;
  918. {****************************************************************************
  919. TCoffObjData
  920. ****************************************************************************}
  921. constructor TCoffObjData.createcoff(const n:string;awin32:boolean;acObjSection:TObjSectionClass);
  922. begin
  923. inherited create(n);
  924. CObjSection:=ACObjSection;
  925. win32:=awin32;
  926. end;
  927. function TCoffObjData.sectionname(atype:TAsmSectiontype;const aname:string;aorder:TAsmSectionOrder):string;
  928. var
  929. sep : string[3];
  930. secname : string;
  931. begin
  932. { section type user gives the user full controll on the section name }
  933. if atype=sec_user then
  934. result:=aname
  935. else
  936. begin
  937. { non-PECOFF targets lack rodata support.
  938. TODO: WinCE likely supports it, but needs testing. }
  939. if (atype in [sec_rodata,sec_rodata_norel]) and
  940. not (target_info.system in systems_windows) then
  941. atype:=sec_data;
  942. secname:=coffsecnames[atype];
  943. if create_smartlink_sections and
  944. (aname<>'') then
  945. begin
  946. case aorder of
  947. secorder_begin :
  948. sep:='.b_';
  949. secorder_end :
  950. sep:='.z_';
  951. else
  952. sep:='.n_';
  953. end;
  954. result:=secname+sep+aname
  955. end
  956. else
  957. result:=secname;
  958. end;
  959. end;
  960. function TCoffObjData.sectiontype2options(aType:TAsmSectionType): TObjSectionOptions;
  961. begin
  962. if (aType in [sec_rodata,sec_rodata_norel]) then
  963. begin
  964. { TODO: WinCE needs testing }
  965. if (target_info.system in systems_windows) then
  966. aType:=sec_rodata_norel
  967. else
  968. aType:=sec_data;
  969. end;
  970. result:=inherited sectiontype2options(aType);
  971. end;
  972. procedure TCoffObjData.CreateDebugSections;
  973. begin
  974. if target_dbg.id=dbg_stabs then
  975. begin
  976. stabssec:=createsection(sec_stab);
  977. stabstrsec:=createsection(sec_stabstr);
  978. end;
  979. end;
  980. procedure TCoffObjData.writereloc(data:aint;len:aword;p:TObjSymbol;reloctype:TObjRelocationType);
  981. var
  982. curraddr,
  983. symaddr : aword;
  984. begin
  985. if CurrObjSec=nil then
  986. internalerror(200403072);
  987. if assigned(p) then
  988. begin
  989. { current address }
  990. curraddr:=CurrObjSec.mempos+CurrObjSec.Size;
  991. { external/common symbols don't have a fixed memory position yet }
  992. if (p.bind=AB_COMMON) then
  993. begin
  994. { For go32v2 we need to use the size as address }
  995. if not win32 then
  996. symaddr:=p.size
  997. else
  998. symaddr:=0;
  999. end
  1000. else
  1001. symaddr:=p.address;
  1002. { no symbol relocation need inside a section }
  1003. if (p.objsection=CurrObjSec) and
  1004. (p.bind<>AB_COMMON) then
  1005. begin
  1006. case reloctype of
  1007. RELOC_ABSOLUTE :
  1008. begin
  1009. CurrObjSec.addsectionreloc(curraddr,CurrObjSec,RELOC_ABSOLUTE);
  1010. inc(data,symaddr);
  1011. end;
  1012. {$ifdef cpu64bitaddr}
  1013. RELOC_ABSOLUTE32 :
  1014. begin
  1015. CurrObjSec.addsectionreloc(curraddr,CurrObjSec,RELOC_ABSOLUTE32);
  1016. inc(data,symaddr);
  1017. end;
  1018. {$endif cpu64bitaddr}
  1019. RELOC_RELATIVE :
  1020. begin
  1021. //inc(data,symaddr-len-CurrObjSec.Size);
  1022. data:=data+symaddr-len-CurrObjSec.Size;
  1023. end;
  1024. RELOC_RVA,
  1025. RELOC_SECREL32 :
  1026. begin
  1027. CurrObjSec.addsectionreloc(curraddr,CurrObjSec,reloctype);
  1028. inc(data,symaddr);
  1029. end;
  1030. else
  1031. internalerror(200604013);
  1032. end;
  1033. end
  1034. else
  1035. begin
  1036. if (p.objsection<>nil) and
  1037. (p.bind<>AB_COMMON) then
  1038. CurrObjSec.addsectionreloc(curraddr,p.objsection,reloctype)
  1039. else
  1040. CurrObjSec.addsymreloc(curraddr,p,reloctype);
  1041. if (not win32) or
  1042. (p.objsection<>nil) then
  1043. inc(data,symaddr);
  1044. if reloctype=RELOC_RELATIVE then
  1045. begin
  1046. if win32 then
  1047. dec(data,len-4)
  1048. else
  1049. dec(data,len+CurrObjSec.Size);
  1050. end;
  1051. end;
  1052. end
  1053. else
  1054. begin
  1055. if reloctype=RELOC_RVA then
  1056. internalerror(200603033);
  1057. end;
  1058. CurrObjSec.write(data,len);
  1059. end;
  1060. {****************************************************************************
  1061. TDJCoffObjData
  1062. ****************************************************************************}
  1063. constructor TDJCoffObjData.create(const n:string);
  1064. begin
  1065. inherited createcoff(n,false,TCoffObjSection);
  1066. end;
  1067. {****************************************************************************
  1068. TPECoffObjData
  1069. ****************************************************************************}
  1070. constructor TPECoffObjData.create(const n:string);
  1071. begin
  1072. inherited createcoff(n,true,TCoffObjSection);
  1073. end;
  1074. {****************************************************************************
  1075. TCoffObjOutput
  1076. ****************************************************************************}
  1077. constructor TCoffObjOutput.createcoff(AWriter:TObjectWriter;awin32:boolean);
  1078. begin
  1079. inherited create(AWriter);
  1080. win32:=awin32;
  1081. end;
  1082. destructor TCoffObjOutput.destroy;
  1083. begin
  1084. FCoffSyms.free;
  1085. FCoffStrs.free;
  1086. inherited destroy;
  1087. end;
  1088. procedure TCoffObjOutput.write_symbol(const name:string;value:aword;section:smallint;typ,aux:byte);
  1089. var
  1090. sym : coffsymbol;
  1091. begin
  1092. FillChar(sym,sizeof(sym),0);
  1093. { symbolname }
  1094. if length(name)>8 then
  1095. begin
  1096. sym.strpos:=FCoffStrs.size+4;
  1097. FCoffStrs.writestr(name);
  1098. FCoffStrs.writestr(#0);
  1099. end
  1100. else
  1101. move(name[1],sym.name,length(name));
  1102. sym.value:=value;
  1103. sym.section:=section;
  1104. sym.typ:=typ;
  1105. sym.aux:=aux;
  1106. inc(symidx);
  1107. FCoffSyms.write(sym,sizeof(sym));
  1108. end;
  1109. procedure TCoffObjOutput.section_write_symbol(p:TObject;arg:pointer);
  1110. var
  1111. secrec : coffsectionrec;
  1112. begin
  1113. with TCoffObjSection(p) do
  1114. begin
  1115. Inc(plongword(arg)^);
  1116. index:=plongword(arg)^;
  1117. secsymidx:=symidx;
  1118. { Both GNU and Microsoft toolchains write section symbols using
  1119. storage class 3 (STATIC).
  1120. No reason to use COFF_SYM_SECTION, it is silently converted to 3 by
  1121. PE binutils and causes warnings with DJGPP binutils. }
  1122. write_symbol(name,mempos,index,COFF_SYM_LOCAL,1);
  1123. { AUX }
  1124. fillchar(secrec,sizeof(secrec),0);
  1125. secrec.len:=Size;
  1126. if ObjRelocations.count<65535 then
  1127. secrec.nrelocs:=ObjRelocations.count
  1128. else
  1129. secrec.nrelocs:=65535;
  1130. inc(symidx);
  1131. FCoffSyms.write(secrec,sizeof(secrec));
  1132. end;
  1133. end;
  1134. procedure TCoffObjOutput.section_write_relocs(p:TObject;arg:pointer);
  1135. var
  1136. i : longint;
  1137. rel : coffreloc;
  1138. objreloc : TObjRelocation;
  1139. begin
  1140. if (TObjSection(p).ObjRelocations.Count>65535) then
  1141. begin
  1142. rel.address:=TObjSection(p).ObjRelocations.Count+1;
  1143. rel.sym:=0;
  1144. rel.reloctype:=0;
  1145. FWriter.Write(rel,sizeof(rel));
  1146. end;
  1147. for i:=0 to TObjSection(p).ObjRelocations.Count-1 do
  1148. begin
  1149. objreloc:=TObjRelocation(TObjSection(p).ObjRelocations[i]);
  1150. rel.address:=objreloc.dataoffset;
  1151. if assigned(objreloc.symbol) then
  1152. begin
  1153. if (objreloc.symbol.bind=AB_LOCAL) then
  1154. rel.sym:=objreloc.symbol.objsection.secsymidx
  1155. else
  1156. begin
  1157. if objreloc.symbol.symidx=-1 then
  1158. internalerror(200602233);
  1159. rel.sym:=objreloc.symbol.symidx;
  1160. end;
  1161. end
  1162. else
  1163. begin
  1164. if objreloc.objsection<>nil then
  1165. rel.sym:=objreloc.objsection.secsymidx
  1166. else
  1167. rel.sym:=0;
  1168. end;
  1169. case objreloc.typ of
  1170. {$ifdef arm}
  1171. RELOC_ABSOLUTE :
  1172. rel.reloctype:=IMAGE_REL_ARM_ADDR32;
  1173. { I've no idea if this is correct (FK):
  1174. RELOC_RELATIVE :
  1175. rel.reloctype:=IMAGE_REL_ARM_GPREL12;
  1176. }
  1177. RELOC_RVA :
  1178. rel.reloctype:=IMAGE_REL_ARM_ADDR32NB;
  1179. RELOC_SECREL32 :
  1180. rel.reloctype:=IMAGE_REL_ARM_SECREL;
  1181. {$endif arm}
  1182. {$ifdef i386}
  1183. RELOC_RELATIVE :
  1184. rel.reloctype:=IMAGE_REL_I386_PCRLONG;
  1185. RELOC_ABSOLUTE :
  1186. rel.reloctype:=IMAGE_REL_I386_DIR32;
  1187. RELOC_RVA :
  1188. rel.reloctype:=IMAGE_REL_I386_IMAGEBASE;
  1189. RELOC_SECREL32 :
  1190. rel.reloctype:=IMAGE_REL_I386_SECREL32;
  1191. {$endif i386}
  1192. {$ifdef x86_64}
  1193. RELOC_NONE :
  1194. rel.reloctype:=IMAGE_REL_AMD64_ABSOLUTE;
  1195. RELOC_RELATIVE :
  1196. rel.reloctype:=IMAGE_REL_AMD64_REL32;
  1197. RELOC_ABSOLUTE32 :
  1198. rel.reloctype:=IMAGE_REL_AMD64_ADDR32;
  1199. RELOC_ABSOLUTE :
  1200. rel.reloctype:=IMAGE_REL_AMD64_ADDR64;
  1201. RELOC_RVA :
  1202. rel.reloctype:=IMAGE_REL_AMD64_ADDR32NB;
  1203. RELOC_RELATIVE_1 :
  1204. rel.reloctype:=IMAGE_REL_AMD64_REL32_1;
  1205. RELOC_RELATIVE_2 :
  1206. rel.reloctype:=IMAGE_REL_AMD64_REL32_2;
  1207. RELOC_RELATIVE_3 :
  1208. rel.reloctype:=IMAGE_REL_AMD64_REL32_3;
  1209. RELOC_RELATIVE_4 :
  1210. rel.reloctype:=IMAGE_REL_AMD64_REL32_4;
  1211. RELOC_RELATIVE_5 :
  1212. rel.reloctype:=IMAGE_REL_AMD64_REL32_5;
  1213. RELOC_SECREL32 :
  1214. rel.reloctype:=IMAGE_REL_AMD64_SECREL;
  1215. {$endif x86_64}
  1216. else
  1217. internalerror(200905071);
  1218. end;
  1219. FWriter.write(rel,sizeof(rel));
  1220. end;
  1221. end;
  1222. procedure TCoffObjOutput.create_symbols(data:TObjData);
  1223. var
  1224. filename : string[18];
  1225. sectionval : word;
  1226. globalval : byte;
  1227. i : longint;
  1228. value : aword;
  1229. objsym : TObjSymbol;
  1230. secidx : longword;
  1231. begin
  1232. with TCoffObjData(data) do
  1233. begin
  1234. symidx:=0;
  1235. { The `.file' record, and the file name auxiliary record }
  1236. write_symbol('.file', 0, -2, COFF_SYM_FILE, 1);
  1237. fillchar(filename,sizeof(filename),0);
  1238. filename:=ExtractFileName(current_module.mainsource);
  1239. inc(symidx);
  1240. FCoffSyms.write(filename[1],sizeof(filename)-1);
  1241. { Sections }
  1242. secidx:=0;
  1243. ObjSectionList.ForEachCall(@section_write_symbol,@secidx);
  1244. { ObjSymbols }
  1245. for i:=0 to ObjSymbolList.Count-1 do
  1246. begin
  1247. objsym:=TObjSymbol(ObjSymbolList[i]);
  1248. if (objsym.bind=AB_LOCAL) then
  1249. continue;
  1250. case objsym.bind of
  1251. AB_GLOBAL :
  1252. begin
  1253. globalval:=COFF_SYM_GLOBAL;
  1254. sectionval:=objsym.objsection.index;
  1255. value:=objsym.address;
  1256. end;
  1257. AB_LOCAL :
  1258. begin
  1259. globalval:=COFF_SYM_LOCAL;
  1260. sectionval:=objsym.objsection.index;
  1261. value:=objsym.address;
  1262. end;
  1263. else
  1264. begin
  1265. globalval:=COFF_SYM_GLOBAL;
  1266. sectionval:=0;
  1267. value:=objsym.size;
  1268. end;
  1269. end;
  1270. { symbolname }
  1271. objsym.symidx:=symidx;
  1272. write_symbol(objsym.name,value,sectionval,globalval,0);
  1273. end;
  1274. end;
  1275. end;
  1276. procedure TCoffObjOutput.section_set_reloc_datapos(p:TCoffObjSection;var datapos:aword);
  1277. begin
  1278. p.coffrelocpos:=datapos;
  1279. inc(datapos,sizeof(coffreloc)*p.ObjRelocations.count);
  1280. if p.ObjRelocations.count>65535 then
  1281. begin
  1282. if win32 then
  1283. inc(datapos,sizeof(coffreloc))
  1284. else
  1285. Message1(asmw_f_too_many_relocations,p.fullname);
  1286. end;
  1287. end;
  1288. procedure TCoffObjOutput.section_write_header(p:TObject;arg:pointer);
  1289. var
  1290. sechdr : tcoffsechdr;
  1291. s : string;
  1292. strpos : aword;
  1293. begin
  1294. with TCoffObjSection(p) do
  1295. begin
  1296. fillchar(sechdr,sizeof(sechdr),0);
  1297. s:=name;
  1298. if length(s)>8 then
  1299. begin
  1300. strpos:=FCoffStrs.size+4;
  1301. FCoffStrs.writestr(s);
  1302. FCoffStrs.writestr(#0);
  1303. s:='/'+ToStr(strpos);
  1304. end;
  1305. move(s[1],sechdr.name,length(s));
  1306. if not win32 then
  1307. begin
  1308. sechdr.rvaofs:=mempos;
  1309. sechdr.vsize:=mempos;
  1310. end
  1311. else
  1312. begin
  1313. if not(oso_data in secoptions) then
  1314. sechdr.vsize:=Size;
  1315. end;
  1316. sechdr.DataSize:=size;
  1317. if (Size>0) and
  1318. (oso_data in secoptions) then
  1319. sechdr.datapos:=datapos;
  1320. if ObjRelocations.count<65535 then
  1321. sechdr.nrelocs:=ObjRelocations.count
  1322. else
  1323. sechdr.nrelocs:=65535;
  1324. sechdr.relocpos:=coffrelocpos;
  1325. if win32 then
  1326. begin
  1327. sechdr.flags:=peencodesechdrflags(secoptions,secalign);
  1328. if ObjRelocations.count>65535 then
  1329. sechdr.flags:=sechdr.flags or PE_SCN_LNK_NRELOC_OVFL;
  1330. end
  1331. else
  1332. sechdr.flags:=djencodesechdrflags(secoptions);
  1333. FWriter.write(sechdr,sizeof(sechdr));
  1334. end;
  1335. end;
  1336. function TCoffObjOutput.writedata(data:TObjData):boolean;
  1337. var
  1338. datapos,
  1339. sympos : aword;
  1340. i : longint;
  1341. header : tcoffheader;
  1342. begin
  1343. result:=false;
  1344. FCoffSyms:=TDynamicArray.Create(SymbolMaxGrow);
  1345. FCoffStrs:=TDynamicArray.Create(StrsMaxGrow);
  1346. with TCoffObjData(data) do
  1347. begin
  1348. { Create Symbol Table }
  1349. create_symbols(data);
  1350. { Calculate the filepositions }
  1351. datapos:=sizeof(tcoffheader)+sizeof(tcoffsechdr)*ObjSectionList.Count;
  1352. { Sections first }
  1353. layoutsections(datapos);
  1354. { relocs }
  1355. for i:=0 to ObjSectionList.Count-1 do
  1356. section_set_reloc_datapos(TCoffObjSection(ObjSectionList[i]),datapos);
  1357. { Symbols }
  1358. sympos:=datapos;
  1359. { Generate COFF header }
  1360. fillchar(header,sizeof(tcoffheader),0);
  1361. header.mach:=COFF_MAGIC;
  1362. header.nsects:=ObjSectionList.Count;
  1363. header.sympos:=sympos;
  1364. header.syms:=symidx;
  1365. if win32 then
  1366. begin
  1367. {$ifndef x86_64}
  1368. header.flag:=PE_FILE_32BIT_MACHINE or
  1369. PE_FILE_LINE_NUMS_STRIPPED or PE_FILE_LOCAL_SYMS_STRIPPED;
  1370. {$else x86_64}
  1371. header.flag:=PE_FILE_LINE_NUMS_STRIPPED or PE_FILE_LOCAL_SYMS_STRIPPED;
  1372. {$endif x86_64}
  1373. end
  1374. else
  1375. header.flag:=COFF_FLAG_AR32WR or COFF_FLAG_NOLINES or COFF_FLAG_NOLSYMS;
  1376. FWriter.write(header,sizeof(header));
  1377. { Section headers }
  1378. ObjSectionList.ForEachCall(@section_write_header,nil);
  1379. { ObjSections }
  1380. WriteSectionContent(data);
  1381. { Relocs }
  1382. ObjSectionList.ForEachCall(@section_write_relocs,nil);
  1383. { ObjSymbols }
  1384. if Sympos<>FWriter.ObjSize then
  1385. internalerror(200603051);
  1386. FWriter.writearray(FCoffSyms);
  1387. { Strings }
  1388. i:=FCoffStrs.size+4;
  1389. FWriter.write(i,4);
  1390. FWriter.writearray(FCoffStrs);
  1391. end;
  1392. FCoffStrs.Free;
  1393. FCoffStrs:=nil;
  1394. FCoffSyms.Free;
  1395. FCoffSyms:=nil;
  1396. end;
  1397. constructor TDJCoffObjOutput.create(AWriter:TObjectWriter);
  1398. begin
  1399. inherited createcoff(AWriter,false);
  1400. cobjdata:=TDJCoffObjData;
  1401. end;
  1402. constructor TPECoffObjOutput.create(AWriter:TObjectWriter);
  1403. begin
  1404. inherited createcoff(AWriter,true);
  1405. cobjdata:=TPECoffObjData;
  1406. end;
  1407. {****************************************************************************
  1408. TCoffObjInput
  1409. ****************************************************************************}
  1410. constructor TCoffObjInput.createcoff(awin32:boolean);
  1411. begin
  1412. inherited create;
  1413. win32:=awin32;
  1414. FSymTbl:=nil;
  1415. end;
  1416. destructor TCoffObjInput.destroy;
  1417. begin
  1418. FCoffSyms.free;
  1419. if assigned(FCoffStrs) then
  1420. freemem(FCoffStrs);
  1421. if assigned(FSymTbl) then
  1422. freemem(FSymTbl);
  1423. if assigned(FSecTbl) then
  1424. freemem(FSecTbl);
  1425. inherited destroy;
  1426. end;
  1427. function TCoffObjInput.GetSection(secidx:longint):TObjSection;
  1428. begin
  1429. result:=nil;
  1430. if (secidx<1) or (secidx>FSecCount) then
  1431. begin
  1432. InputError('Failed reading coff file, invalid section index');
  1433. exit;
  1434. end;
  1435. result:=FSecTbl^[secidx];
  1436. end;
  1437. function TCoffObjInput.Read_str(strpos:longword):string;
  1438. begin
  1439. if (FCoffStrs=nil) or (strpos>=FCoffStrSize) or (FCoffStrs[strpos]=#0) then
  1440. Internalerror(200205172);
  1441. result:=string(PChar(@FCoffStrs[strpos]));
  1442. end;
  1443. procedure TCoffObjInput.read_relocs(s:TCoffObjSection);
  1444. var
  1445. rel : coffreloc;
  1446. rel_type : TObjRelocationType;
  1447. i : longint;
  1448. p : TObjSymbol;
  1449. begin
  1450. if s.coffrelocs=high(aword) then
  1451. begin
  1452. { If number of relocations exceeds 65535, it is stored in address field
  1453. of the first record, and includes this first fake relocation. }
  1454. FReader.read(rel,sizeof(rel));
  1455. s.coffrelocs:=rel.address-1;
  1456. if s.coffrelocs<=65535 then
  1457. InternalError(2013012503);
  1458. end;
  1459. for i:=1 to s.coffrelocs do
  1460. begin
  1461. FReader.read(rel,sizeof(rel));
  1462. case rel.reloctype of
  1463. {$ifdef arm}
  1464. IMAGE_REL_ARM_ABSOLUTE:
  1465. rel_type:=RELOC_NONE;
  1466. IMAGE_REL_ARM_ADDR32:
  1467. rel_type:=RELOC_ABSOLUTE;
  1468. IMAGE_REL_ARM_ADDR32NB:
  1469. rel_type:=RELOC_RVA;
  1470. IMAGE_REL_ARM_BRANCH24:
  1471. rel_type:=RELOC_RELATIVE_24;
  1472. IMAGE_REL_ARM_SECREL:
  1473. rel_type:=RELOC_SECREL32;
  1474. {$endif arm}
  1475. {$ifdef i386}
  1476. IMAGE_REL_I386_PCRLONG :
  1477. rel_type:=RELOC_RELATIVE;
  1478. IMAGE_REL_I386_DIR32 :
  1479. rel_type:=RELOC_ABSOLUTE;
  1480. IMAGE_REL_I386_IMAGEBASE :
  1481. rel_type:=RELOC_RVA;
  1482. IMAGE_REL_I386_SECREL32 :
  1483. rel_type:=RELOC_SECREL32;
  1484. {$endif i386}
  1485. {$ifdef x86_64}
  1486. IMAGE_REL_AMD64_ABSOLUTE:
  1487. rel_type:=RELOC_NONE;
  1488. IMAGE_REL_AMD64_REL32:
  1489. rel_type:=RELOC_RELATIVE;
  1490. IMAGE_REL_AMD64_ADDR32,
  1491. R_X86_64_32S:
  1492. rel_type:=RELOC_ABSOLUTE32;
  1493. IMAGE_REL_AMD64_ADDR64:
  1494. rel_type:=RELOC_ABSOLUTE;
  1495. IMAGE_REL_AMD64_ADDR32NB:
  1496. rel_type:=RELOC_RVA;
  1497. IMAGE_REL_AMD64_REL32_1:
  1498. rel_type:=RELOC_RELATIVE_1;
  1499. IMAGE_REL_AMD64_REL32_2:
  1500. rel_type:=RELOC_RELATIVE_2;
  1501. IMAGE_REL_AMD64_REL32_3:
  1502. rel_type:=RELOC_RELATIVE_3;
  1503. IMAGE_REL_AMD64_REL32_4:
  1504. rel_type:=RELOC_RELATIVE_4;
  1505. IMAGE_REL_AMD64_REL32_5:
  1506. rel_type:=RELOC_RELATIVE_5;
  1507. IMAGE_REL_AMD64_SECREL:
  1508. rel_type:=RELOC_SECREL32;
  1509. {$endif x86_64}
  1510. else
  1511. begin
  1512. InputError('Failed reading coff file, illegal reloctype $'+system.hexstr(rel.reloctype,4));
  1513. exit;
  1514. end;
  1515. end;
  1516. p:=FSymTbl^[rel.sym];
  1517. if assigned(p) then
  1518. s.addsymreloc(rel.address-s.mempos,p,rel_type)
  1519. else
  1520. begin
  1521. InputError('Failed reading coff file, can''t resolve symbol of relocation');
  1522. exit;
  1523. end;
  1524. end;
  1525. end;
  1526. procedure TCoffObjInput.read_symbols(objdata:TObjData);
  1527. var
  1528. size,
  1529. address,
  1530. nsyms,
  1531. symidx : aint;
  1532. i : longint;
  1533. sym : coffsymbol;
  1534. objsym : TObjSymbol;
  1535. bind : Tasmsymbind;
  1536. strname : string;
  1537. auxrec : array[0..17] of byte;
  1538. objsec : TObjSection;
  1539. { keeps string manipulations out of main routine }
  1540. procedure UnsupportedSymbolType;
  1541. begin
  1542. Comment(V_Fatal,'Unsupported COFF symbol type '+tostr(sym.typ)+' at index '+tostr(symidx)+' while reading '+InputFileName);
  1543. end;
  1544. begin
  1545. with TCoffObjData(objdata) do
  1546. begin
  1547. nsyms:=FCoffSyms.Size div sizeof(CoffSymbol);
  1548. { Allocate memory for symidx -> TObjSymbol table }
  1549. FSymTbl:=AllocMem(nsyms*sizeof(TObjSymbol));
  1550. { Load the Symbols }
  1551. FCoffSyms.Seek(0);
  1552. symidx:=0;
  1553. while (symidx<nsyms) do
  1554. begin
  1555. FCoffSyms.Read(sym,sizeof(sym));
  1556. if plongint(@sym.name)^<>0 then
  1557. begin
  1558. move(sym.name,strname[1],8);
  1559. strname[9]:=#0;
  1560. strname[0]:=chr(strlen(@strname[1]));
  1561. if strname='' then
  1562. Internalerror(200205171);
  1563. end
  1564. else
  1565. strname:=Read_str(sym.strpos);
  1566. bind:=AB_EXTERNAL;
  1567. size:=0;
  1568. address:=0;
  1569. objsym:=nil;
  1570. objsec:=nil;
  1571. case sym.typ of
  1572. COFF_SYM_GLOBAL :
  1573. begin
  1574. if sym.section=0 then
  1575. begin
  1576. if sym.value=0 then
  1577. bind:=AB_EXTERNAL
  1578. else
  1579. begin
  1580. bind:=AB_COMMON;
  1581. size:=sym.value;
  1582. end;
  1583. end
  1584. else
  1585. begin
  1586. bind:=AB_GLOBAL;
  1587. objsec:=GetSection(sym.section);
  1588. if sym.value>=objsec.mempos then
  1589. address:=sym.value-objsec.mempos;
  1590. end;
  1591. objsym:=CreateSymbol(strname);
  1592. objsym.bind:=bind;
  1593. objsym.typ:=AT_FUNCTION;
  1594. objsym.objsection:=objsec;
  1595. objsym.offset:=address;
  1596. objsym.size:=size;
  1597. end;
  1598. COFF_SYM_LABEL,
  1599. COFF_SYM_LOCAL :
  1600. begin
  1601. { do not add constants (section=-1) }
  1602. if sym.section<>-1 then
  1603. begin
  1604. objsec:=GetSection(sym.section);
  1605. if sym.value>=objsec.mempos then
  1606. address:=sym.value-objsec.mempos;
  1607. objsym:=CreateSymbol(strname);
  1608. objsym.bind:=AB_LOCAL;
  1609. objsym.typ:=AT_FUNCTION;
  1610. objsym.objsection:=objsec;
  1611. objsym.offset:=address;
  1612. objsym.size:=size;
  1613. end;
  1614. end;
  1615. COFF_SYM_SECTION :
  1616. begin
  1617. { GetSection checks that index is in range }
  1618. objsec:=GetSection(sym.section);
  1619. if assigned(objsec) then
  1620. begin
  1621. if sym.value>=objsec.mempos then
  1622. address:=sym.value-objsec.mempos;
  1623. objsym:=CreateSymbol(strname);
  1624. objsym.bind:=AB_LOCAL;
  1625. objsym.typ:=AT_FUNCTION;
  1626. objsym.objsection:=objsec;
  1627. objsym.offset:=address;
  1628. objsym.size:=size;
  1629. end;
  1630. end;
  1631. COFF_SYM_FUNCTION,
  1632. COFF_SYM_FILE :
  1633. ;
  1634. else
  1635. UnsupportedSymbolType;
  1636. end;
  1637. FSymTbl^[symidx]:=objsym;
  1638. { read aux records }
  1639. for i:=1 to sym.aux do
  1640. begin
  1641. FCoffSyms.Read(auxrec,sizeof(auxrec));
  1642. inc(symidx);
  1643. end;
  1644. inc(symidx);
  1645. end;
  1646. end;
  1647. end;
  1648. procedure TCoffObjInput.ObjSections_read_relocs(p:TObject;arg:pointer);
  1649. begin
  1650. with TCoffObjSection(p) do
  1651. begin
  1652. { Skip debug sections }
  1653. if (oso_debug in secoptions) and
  1654. (cs_link_strip in current_settings.globalswitches) and
  1655. not(cs_link_separate_dbg_file in current_settings.globalswitches) then
  1656. exit;
  1657. if coffrelocs>0 then
  1658. begin
  1659. FReader.Seek(coffrelocpos);
  1660. read_relocs(TCoffObjSection(p));
  1661. end;
  1662. end;
  1663. end;
  1664. function TCoffObjInput.ReadObjData(AReader:TObjectreader;out objdata:TObjData):boolean;
  1665. var
  1666. secalign : shortint;
  1667. strpos,
  1668. i : longint;
  1669. code : longint;
  1670. objsec : TCoffObjSection;
  1671. secoptions : TObjSectionOptions;
  1672. header : tcoffheader;
  1673. sechdr : tcoffsechdr;
  1674. secname : string;
  1675. secnamebuf : array[0..15] of char;
  1676. begin
  1677. FReader:=AReader;
  1678. InputFileName:=AReader.FileName;
  1679. objdata:=CObjData.Create(InputFileName);
  1680. result:=false;
  1681. FCoffSyms:=TDynamicArray.Create(SymbolMaxGrow);
  1682. with TCoffObjData(objdata) do
  1683. begin
  1684. { Read COFF header }
  1685. if not AReader.read(header,sizeof(tcoffheader)) then
  1686. begin
  1687. InputError('Can''t read COFF Header');
  1688. exit;
  1689. end;
  1690. if header.mach<>COFF_MAGIC then
  1691. begin
  1692. InputError('Illegal COFF Magic');
  1693. exit;
  1694. end;
  1695. {$ifdef arm}
  1696. eVCobj:=header.flag=$100;
  1697. {$endif arm}
  1698. { ObjSymbols }
  1699. AReader.Seek(header.sympos);
  1700. if not AReader.ReadArray(FCoffSyms,header.syms*sizeof(CoffSymbol)) then
  1701. begin
  1702. InputError('Error reading coff symbol table');
  1703. exit;
  1704. end;
  1705. { Strings }
  1706. if not AReader.Read(FCoffStrSize,4) then
  1707. begin
  1708. InputError('Error reading COFF string table');
  1709. exit;
  1710. end;
  1711. if (FCoffStrSize>4) then
  1712. begin
  1713. { allocate an extra byte and null-terminate }
  1714. GetMem(FCoffStrs,FCoffStrSize+1);
  1715. FCoffStrs[FCoffStrSize]:=#0;
  1716. for i:=0 to 3 do
  1717. FCoffStrs[i]:=#0;
  1718. if not AReader.Read(FCoffStrs[4],FCoffStrSize-4) then
  1719. begin
  1720. InputError('Error reading COFF string table');
  1721. exit;
  1722. end;
  1723. end;
  1724. { Section headers }
  1725. { Allocate SecIdx -> TObjSection table, secidx is 1-based }
  1726. FSecCount:=header.nsects;
  1727. FSecTbl:=AllocMem((header.nsects+1)*sizeof(TObjSection));
  1728. AReader.Seek(sizeof(tcoffheader)+header.opthdr);
  1729. for i:=1 to header.nsects do
  1730. begin
  1731. if not AReader.read(sechdr,sizeof(sechdr)) then
  1732. begin
  1733. InputError('Error reading COFF Section Headers');
  1734. exit;
  1735. end;
  1736. move(sechdr.name,secnamebuf,8);
  1737. secnamebuf[8]:=#0;
  1738. secname:=strpas(secnamebuf);
  1739. if secname[1]='/' then
  1740. begin
  1741. Val(Copy(secname,2,8),strpos,code);
  1742. if code=0 then
  1743. secname:=Read_str(strpos)
  1744. else
  1745. begin
  1746. InputError('Error reading COFF Section Headers');
  1747. secname:='error';
  1748. end;
  1749. end;
  1750. if win32 then
  1751. pedecodesechdrflags(secname,sechdr.flags,secoptions,secalign)
  1752. else
  1753. begin
  1754. secoptions:=djdecodesechdrflags(secname,sechdr.flags);
  1755. secalign:=sizeof(pint);
  1756. end;
  1757. if (Length(secname)>3) and (secname[2] in ['e','f','i','p','r']) then
  1758. begin
  1759. if (Pos('.edata',secname)=1) or
  1760. (Pos('.rsrc',secname)=1) or
  1761. {$ifndef x86_64}
  1762. (Pos('.pdata',secname)=1) or
  1763. {$endif}
  1764. (Pos('.fpc',secname)=1) then
  1765. include(secoptions,oso_keep);
  1766. if (Pos('.idata',secname)=1) then
  1767. begin
  1768. { TODO: idata keep can maybe replaced with grouping of text and idata}
  1769. include(secoptions,oso_keep);
  1770. secname:=secname + '.' + ExtractFileName(InputFileName);
  1771. end;
  1772. end;
  1773. objsec:=TCoffObjSection(createsection(secname,secalign,secoptions,false));
  1774. FSecTbl^[i]:=objsec;
  1775. if not win32 then
  1776. objsec.mempos:=sechdr.rvaofs;
  1777. objsec.orgmempos:=sechdr.rvaofs;
  1778. objsec.coffrelocs:=sechdr.nrelocs;
  1779. if win32 then
  1780. begin
  1781. if (sechdr.flags and PE_SCN_LNK_NRELOC_OVFL)<>0 then
  1782. objsec.coffrelocs:=high(aword);
  1783. end;
  1784. objsec.coffrelocpos:=sechdr.relocpos;
  1785. objsec.datapos:=sechdr.datapos;
  1786. objsec.Size:=sechdr.dataSize;
  1787. end;
  1788. { Insert all ObjSymbols }
  1789. read_symbols(objdata);
  1790. { Section Data }
  1791. ReadSectionContent(objdata);
  1792. { Relocs }
  1793. ObjSectionList.ForEachCall(@objsections_read_relocs,nil);
  1794. end;
  1795. if assigned(FCoffStrs) then
  1796. freemem(FCoffStrs);
  1797. FCoffStrs:=nil;
  1798. FCoffSyms.Free;
  1799. FCoffSyms:=nil;
  1800. result:=true;
  1801. end;
  1802. constructor TDJCoffObjInput.create;
  1803. begin
  1804. inherited createcoff(false);
  1805. cobjdata:=TDJCoffObjData;
  1806. end;
  1807. constructor TPECoffObjInput.create;
  1808. begin
  1809. inherited createcoff(true);
  1810. cobjdata:=TPECoffObjData;
  1811. end;
  1812. {****************************************************************************
  1813. TCoffexeoutput
  1814. ****************************************************************************}
  1815. constructor TCoffexeoutput.createcoff(awin32:boolean);
  1816. begin
  1817. inherited create;
  1818. win32:=awin32;
  1819. if target_info.system in [system_x86_64_win64] then
  1820. MaxMemPos:=$FFFFFFFF
  1821. else
  1822. if target_info.system in systems_wince then
  1823. MaxMemPos:=$1FFFFFF
  1824. else
  1825. MaxMemPos:=$7FFFFFFF;
  1826. end;
  1827. procedure TCoffexeoutput.write_symbol(const name:string;value:aword;section:smallint;typ,aux:byte);
  1828. var
  1829. sym : coffsymbol;
  1830. begin
  1831. FillChar(sym,sizeof(sym),0);
  1832. if length(name)>8 then
  1833. begin
  1834. sym.strpos:=FCoffStrs.size+4;
  1835. FCoffStrs.writestr(name);
  1836. FCoffStrs.writestr(#0);
  1837. end
  1838. else
  1839. move(name[1],sym.name,length(name));
  1840. sym.value:=value;
  1841. sym.section:=section;
  1842. sym.typ:=typ;
  1843. sym.aux:=aux;
  1844. FWriter.write(sym,sizeof(sym));
  1845. end;
  1846. procedure TCoffexeoutput.globalsyms_write_symbol(p:TObject;arg:pointer);
  1847. var
  1848. secval,
  1849. value : aint;
  1850. globalval : byte;
  1851. exesec : TExeSection;
  1852. begin
  1853. if not assigned(texesymbol(p).objsymbol) then
  1854. internalerror(200603053);
  1855. with texesymbol(p).objsymbol do
  1856. begin
  1857. if assigned(objsection) then
  1858. exesec:=TExeSection(objsection.exesection)
  1859. else
  1860. exesec:=nil;
  1861. { There is no exesection defined for special internal symbols
  1862. like __image_base__ }
  1863. if assigned(exesec) then
  1864. begin
  1865. secval:=exesec.secsymidx;
  1866. if win32 then
  1867. value:=address-exesec.mempos
  1868. else
  1869. value:=address;
  1870. end
  1871. else
  1872. begin
  1873. secval:=-1;
  1874. value:=address;
  1875. end;
  1876. if bind=AB_LOCAL then
  1877. globalval:=COFF_SYM_LOCAL
  1878. else
  1879. globalval:=COFF_SYM_GLOBAL;
  1880. { reloctype address to the section in the executable }
  1881. write_symbol(name,value,secval,globalval,0);
  1882. end;
  1883. end;
  1884. procedure TCoffexeoutput.ExeSectionList_write_header(p:TObject;arg:pointer);
  1885. var
  1886. sechdr : tcoffsechdr;
  1887. s : string;
  1888. strpos : aword;
  1889. begin
  1890. with tExeSection(p) do
  1891. begin
  1892. fillchar(sechdr,sizeof(sechdr),0);
  1893. s:=name;
  1894. if length(s)>8 then
  1895. begin
  1896. strpos:=FCoffStrs.size+4;
  1897. FCoffStrs.writestr(s);
  1898. FCoffStrs.writestr(#0);
  1899. s:='/'+ToStr(strpos);
  1900. end;
  1901. move(s[1],sechdr.name,length(s));
  1902. if win32 then
  1903. begin
  1904. sechdr.rvaofs:=mempos;
  1905. sechdr.vsize:=Size;
  1906. { sechdr.dataSize is size of initialized data, rounded up to FileAlignment
  1907. (so it can be greater than VirtualSize). Must be zero for sections that
  1908. do not contain initialized data. }
  1909. if (oso_data in SecOptions) then
  1910. sechdr.datasize:=Align(Size,SectionDataAlign);
  1911. end
  1912. else
  1913. begin
  1914. if not (oso_debug in SecOptions) then
  1915. begin
  1916. sechdr.rvaofs:=mempos;
  1917. sechdr.vsize:=mempos;
  1918. end;
  1919. sechdr.datasize:=Size;
  1920. end;
  1921. if (Size>0) then
  1922. sechdr.datapos:=datapos-datapos_offset;
  1923. sechdr.nrelocs:=0;
  1924. sechdr.relocpos:=0;
  1925. if win32 then
  1926. begin
  1927. if (target_info.system in systems_nativent) and
  1928. (apptype = app_native) then
  1929. sechdr.flags:=peencodesechdrflags(SecOptions,SecAlign) or PE_SCN_MEM_NOT_PAGED
  1930. else
  1931. sechdr.flags:=peencodesechdrflags(SecOptions,SecAlign);
  1932. { some flags are invalid in executables, reset them }
  1933. sechdr.flags:=sechdr.flags and
  1934. not(PE_SCN_LNK_INFO or PE_SCN_LNK_REMOVE or
  1935. PE_SCN_LNK_COMDAT or PE_SCN_ALIGN_MASK);
  1936. end
  1937. else
  1938. sechdr.flags:=djencodesechdrflags(SecOptions);
  1939. FWriter.write(sechdr,sizeof(sechdr));
  1940. end;
  1941. end;
  1942. procedure TCoffexeoutput.ExeSectionList_pass2_header(p:TObject;arg:pointer);
  1943. begin
  1944. with TExeSection(p) do
  1945. begin
  1946. { The debuginfo sections should already be stripped }
  1947. { if (ExeWriteMode=ewm_exeonly) and
  1948. (oso_debug in SecOptions) then
  1949. internalerror(200801161); }
  1950. inc(plongint(arg)^);
  1951. secsymidx:=plongint(arg)^;
  1952. end;
  1953. end;
  1954. function tcoffexeoutput.totalheadersize:longword;
  1955. var
  1956. stubsize,
  1957. optheadersize : longword;
  1958. begin
  1959. if win32 then
  1960. begin
  1961. stubsize:=sizeof(win32stub)+sizeof(pemagic);
  1962. optheadersize:=sizeof(tcoffpeoptheader);
  1963. end
  1964. else
  1965. begin
  1966. stubsize:=sizeof(go32v2stub);
  1967. optheadersize:=sizeof(coffdjoptheader);
  1968. end;
  1969. result:=stubsize+sizeof(tcoffheader)+optheadersize;
  1970. end;
  1971. procedure tcoffexeoutput.MemPos_Header;
  1972. begin
  1973. { calculate start positions after the headers }
  1974. currmempos:=totalheadersize+sizeof(tcoffsechdr)*longword(ExeSectionList.Count-2);
  1975. end;
  1976. procedure tcoffexeoutput.DataPos_Header;
  1977. begin
  1978. { retrieve amount of sections }
  1979. nsects:=0;
  1980. ExeSectionList.ForEachCall(@ExeSectionList_pass2_header,@nsects);
  1981. { calculate start positions after the headers }
  1982. currdatapos:=totalheadersize+longword(nsects)*sizeof(tcoffsechdr);
  1983. end;
  1984. procedure tcoffexeoutput.DataPos_Symbols;
  1985. begin
  1986. inherited DataPos_Symbols;
  1987. { Calculating symbols position and size }
  1988. nsyms:=ExeSymbolList.Count;
  1989. sympos:=Align(CurrDataPos,SectionDataAlign);
  1990. inc(CurrDataPos,sizeof(coffsymbol)*nsyms);
  1991. end;
  1992. function TCoffexeoutput.writedata:boolean;
  1993. var
  1994. i : longword;
  1995. header : tcoffheader;
  1996. djoptheader : coffdjoptheader;
  1997. peoptheader : tcoffpeoptheader;
  1998. textExeSec,
  1999. dataExeSec,
  2000. bssExeSec,
  2001. idataExeSec,
  2002. tlsExeSec : TExeSection;
  2003. tlsdir : TlsDirectory;
  2004. hassymbols,
  2005. writeDbgStrings : boolean;
  2006. procedure UpdateDataDir(const secname:string;idx:longint);
  2007. var
  2008. exesec : TExeSection;
  2009. begin
  2010. exesec:=FindExeSection(secname);
  2011. if assigned(exesec) then
  2012. begin
  2013. peoptheader.DataDirectory[idx].vaddr:=exesec.mempos;
  2014. peoptheader.DataDirectory[idx].size:=exesec.Size;
  2015. end;
  2016. end;
  2017. procedure UpdateImports;
  2018. var
  2019. exesec: TExeSection;
  2020. objsec, iat_start, iat_end, ilt_start: TObjSection;
  2021. i: longint;
  2022. begin
  2023. exesec:=FindExeSection('.idata');
  2024. if exesec=nil then
  2025. exit;
  2026. iat_start:=nil;
  2027. iat_end:=nil;
  2028. ilt_start:=nil;
  2029. for i:=0 to exesec.ObjSectionList.Count-1 do
  2030. begin
  2031. objsec:=TObjSection(exesec.ObjSectionList[i]);
  2032. if (ilt_start=nil) and (Pos('.idata$4',objsec.Name)=1) then
  2033. ilt_start:=objsec;
  2034. if Pos('.idata$5',objsec.Name)=1 then
  2035. begin
  2036. if iat_start=nil then
  2037. iat_start:=objsec;
  2038. end
  2039. else
  2040. if Assigned(iat_start) then
  2041. begin
  2042. iat_end:=objsec;
  2043. Break;
  2044. end;
  2045. end;
  2046. peoptheader.DataDirectory[PE_DATADIR_IDATA].vaddr:=exesec.mempos;
  2047. if Assigned(ilt_start) then
  2048. peoptheader.DataDirectory[PE_DATADIR_IDATA].size:=ilt_start.mempos-exesec.mempos
  2049. else { should not happen }
  2050. peoptheader.DataDirectory[PE_DATADIR_IDATA].size:=exesec.Size;
  2051. if Assigned(iat_start) and Assigned(iat_end) then
  2052. begin
  2053. peoptheader.DataDirectory[PE_DATADIR_IMPORTADDRESSTABLE].vaddr:=iat_start.mempos;
  2054. peoptheader.DataDirectory[PE_DATADIR_IMPORTADDRESSTABLE].size:=iat_end.mempos-iat_start.mempos;
  2055. end;
  2056. end;
  2057. procedure UpdateTlsDataDir;
  2058. var
  2059. {callbacksection : TExeSection;}
  2060. tlsexesymbol: TExeSymbol;
  2061. tlssymbol: TObjSymbol;
  2062. callbackexesymbol: TExeSymbol;
  2063. callbacksymbol: TObjSymbol;
  2064. begin
  2065. { according to GNU ld,
  2066. the callback routines should be placed into .CRT$XL*
  2067. sections, and the thread local variables in .tls
  2068. __tls_start__ and __tls_end__ symbols
  2069. should be used for the initialized part,
  2070. which we do not support yet. }
  2071. { For now, we only pass the address of the __tls_used
  2072. asm symbol into PE_DATADIR_TLS with the correct
  2073. size of this table (different for win32/win64 }
  2074. tlsexesymbol:=texesymbol(ExeSymbolList.Find(
  2075. target_info.Cprefix+'_tls_used'));
  2076. if assigned(tlsexesymbol) then
  2077. begin
  2078. tlssymbol:=tlsexesymbol.ObjSymbol;
  2079. peoptheader.DataDirectory[PE_DATADIR_TLS].vaddr:=tlssymbol.address;
  2080. { sizeof(TlsDirectory) is different on host and target when cross-compiling }
  2081. peoptheader.DataDirectory[PE_DATADIR_TLS].size:=TLSDIR_SIZE;
  2082. if IsSharedLibrary then
  2083. begin
  2084. { Here we should reset __FPC_tls_callbacks value to nil }
  2085. callbackexesymbol:=texesymbol(ExeSymbolList.Find(
  2086. '__FPC_tls_callbacks'));
  2087. if assigned (callbackexesymbol) then
  2088. begin
  2089. callbacksymbol:=callbackexesymbol.ObjSymbol;
  2090. end;
  2091. end;
  2092. end;
  2093. end;
  2094. begin
  2095. result:=false;
  2096. FCoffStrs:=TDynamicArray.Create(StrsMaxGrow);
  2097. textExeSec:=FindExeSection('.text');
  2098. dataExeSec:=FindExeSection('.data');
  2099. bssExeSec:=FindExeSection('.bss');
  2100. tlsExeSec:=FindExeSection('.tls');
  2101. if not assigned(TextExeSec) or
  2102. not assigned(DataExeSec) then
  2103. internalerror(200602231);
  2104. { do we need to write symbols? }
  2105. hassymbols:=(ExeWriteMode=ewm_dbgonly) or
  2106. (
  2107. (ExeWriteMode=ewm_exefull) and
  2108. not(cs_link_strip in current_settings.globalswitches)
  2109. );
  2110. writeDbgStrings:=hassymbols or ((ExeWriteMode=ewm_exeonly) and (cs_link_separate_dbg_file in current_settings.globalswitches));
  2111. { Stub }
  2112. if win32 then
  2113. begin
  2114. FWriter.write(win32stub,sizeof(win32stub));
  2115. FWriter.write(pemagic,sizeof(pemagic));
  2116. end
  2117. else
  2118. FWriter.write(go32v2stub,sizeof(go32v2stub));
  2119. { Initial header, will be updated later }
  2120. fillchar(header,sizeof(header),0);
  2121. header.mach:=COFF_MAGIC;
  2122. header.nsects:=nsects;
  2123. if writeDbgStrings then
  2124. header.sympos:=sympos-datapos_offset;
  2125. if hassymbols then
  2126. header.syms:=nsyms;
  2127. if win32 then
  2128. header.opthdr:=sizeof(tcoffpeoptheader)
  2129. else
  2130. header.opthdr:=sizeof(coffdjoptheader);
  2131. if win32 then
  2132. begin
  2133. header.flag:=PE_FILE_EXECUTABLE_IMAGE or PE_FILE_LINE_NUMS_STRIPPED;
  2134. if target_info.system in [system_x86_64_win64] then
  2135. header.flag:=header.flag or PE_FILE_LARGE_ADDRESS_AWARE
  2136. else
  2137. header.flag:=header.flag or PE_FILE_32BIT_MACHINE;
  2138. if IsSharedLibrary then
  2139. header.flag:=header.flag or PE_FILE_DLL;
  2140. if FindExeSection('.reloc')=nil then
  2141. header.flag:=header.flag or PE_FILE_RELOCS_STRIPPED;
  2142. if (FindExeSection('.stab')=nil) and
  2143. (FindExeSection('.debug_info')=nil) and
  2144. (FindExeSection('.gnu_debuglink')=nil) then
  2145. header.flag:=header.flag or PE_FILE_DEBUG_STRIPPED;
  2146. if not hassymbols then
  2147. header.flag:=header.flag or PE_FILE_LOCAL_SYMS_STRIPPED;
  2148. if SetPEFlagsSetExplicity then
  2149. header.flag:=header.flag or peflags;
  2150. end
  2151. else
  2152. header.flag:=COFF_FLAG_AR32WR or COFF_FLAG_EXE or COFF_FLAG_NORELOCS or COFF_FLAG_NOLINES;
  2153. FWriter.write(header,sizeof(header));
  2154. { Optional COFF Header }
  2155. if win32 then
  2156. begin
  2157. fillchar(peoptheader,sizeof(peoptheader),0);
  2158. peoptheader.magic:=COFF_OPT_MAGIC;
  2159. peoptheader.MajorLinkerVersion:=ord(version_nr)-ord('0');
  2160. peoptheader.MinorLinkerVersion:=(ord(release_nr)-ord('0'))*10 + (ord(patch_nr)-ord('0'));
  2161. peoptheader.tsize:=TextExeSec.Size;
  2162. peoptheader.dsize:=DataExeSec.Size;
  2163. if assigned(BSSExeSec) then
  2164. peoptheader.bsize:=BSSExeSec.Size;
  2165. peoptheader.text_start:=TextExeSec.mempos;
  2166. {$ifndef cpu64bitaddr}
  2167. peoptheader.data_start:=DataExeSec.mempos;
  2168. {$endif cpu64bitaddr}
  2169. peoptheader.entry:=EntrySym.Address;
  2170. peoptheader.ImageBase:=ImageBase;
  2171. peoptheader.SectionAlignment:=SectionMemAlign;
  2172. peoptheader.FileAlignment:=SectionDataAlign;
  2173. peoptheader.MajorOperatingSystemVersion:=4;
  2174. peoptheader.MinorOperatingSystemVersion:=0;
  2175. peoptheader.MajorImageVersion:=dllmajor;
  2176. peoptheader.MinorImageVersion:=dllminor;
  2177. if target_info.system in systems_wince then
  2178. peoptheader.MajorSubsystemVersion:=3
  2179. else
  2180. peoptheader.MajorSubsystemVersion:=4;
  2181. peoptheader.MinorSubsystemVersion:=0;
  2182. peoptheader.Win32Version:=0;
  2183. peoptheader.SizeOfImage:=Align(CurrMemPos,SectionMemAlign);
  2184. peoptheader.SizeOfHeaders:=textExeSec.DataPos;
  2185. peoptheader.CheckSum:=0;
  2186. if (target_info.system in systems_nativent) and (not IsSharedLibrary or (apptype = app_native)) then
  2187. { Although I did not really test this, it seems that Subsystem is
  2188. not checked in DLLs except for maybe drivers}
  2189. peoptheader.Subsystem:=PE_SUBSYSTEM_NATIVE
  2190. else
  2191. if target_info.system in systems_wince then
  2192. peoptheader.Subsystem:=PE_SUBSYSTEM_WINDOWS_CE_GUI
  2193. else
  2194. if apptype=app_gui then
  2195. peoptheader.Subsystem:=PE_SUBSYSTEM_WINDOWS_GUI
  2196. else
  2197. peoptheader.Subsystem:=PE_SUBSYSTEM_WINDOWS_CUI;
  2198. if SetPEOptFlagsSetExplicity then
  2199. peoptheader.DllCharacteristics:=peoptflags
  2200. else
  2201. peoptheader.DllCharacteristics:=0;
  2202. peoptheader.SizeOfStackReserve:=stacksize;
  2203. peoptheader.SizeOfStackCommit:=$1000;
  2204. if MinStackSizeSetExplicity then
  2205. peoptheader.SizeOfStackCommit:=minstacksize;
  2206. if MaxStackSizeSetExplicity then
  2207. peoptheader.SizeOfStackReserve:=maxstacksize;
  2208. peoptheader.SizeOfHeapReserve:=$100000;
  2209. peoptheader.SizeOfHeapCommit:=$1000;
  2210. peoptheader.NumberOfRvaAndSizes:=PE_DATADIR_ENTRIES;
  2211. UpdateImports;
  2212. UpdateTlsDataDir;
  2213. UpdateDataDir('.edata',PE_DATADIR_EDATA);
  2214. UpdateDataDir('.rsrc',PE_DATADIR_RSRC);
  2215. UpdateDataDir('.pdata',PE_DATADIR_PDATA);
  2216. UpdateDataDir('.reloc',PE_DATADIR_RELOC);
  2217. FWriter.write(peoptheader,sizeof(peoptheader));
  2218. end
  2219. else
  2220. begin
  2221. fillchar(djoptheader,sizeof(djoptheader),0);
  2222. djoptheader.magic:=COFF_OPT_MAGIC;
  2223. djoptheader.tsize:=TextExeSec.Size;
  2224. djoptheader.dsize:=DataExeSec.Size;
  2225. if assigned(BSSExeSec) then
  2226. djoptheader.bsize:=BSSExeSec.Size;
  2227. djoptheader.text_start:=TextExeSec.mempos;
  2228. djoptheader.data_start:=DataExeSec.mempos;
  2229. djoptheader.entry:=EntrySym.Address;
  2230. FWriter.write(djoptheader,sizeof(djoptheader));
  2231. end;
  2232. { For some unknown reason WM 6.1 requires .idata section to be read only.
  2233. Otherwise it refuses to load DLLs greater than 64KB.
  2234. Earlier versions of WinCE load DLLs regardless of .idata flags. }
  2235. if target_info.system in systems_wince then
  2236. begin
  2237. idataExeSec:=FindExeSection('.idata');
  2238. if idataExeSec<>nil then
  2239. idataExeSec.SecOptions:=idataExeSec.SecOptions - [oso_write];
  2240. end;
  2241. { Section headers }
  2242. ExeSectionList.ForEachCall(@ExeSectionList_write_header,nil);
  2243. { Section data }
  2244. WriteExeSectionContent;
  2245. { Align after the last section }
  2246. FWriter.Writezeros(Align(FWriter.Size,SectionDataAlign)-FWriter.Size);
  2247. { Optional Symbols }
  2248. if SymPos<>FWriter.Size then
  2249. internalerror(200602252);
  2250. if hassymbols then
  2251. ExeSymbolList.ForEachCall(@globalsyms_write_symbol,nil);
  2252. if writeDbgStrings then
  2253. begin
  2254. { Strings }
  2255. i:=FCoffStrs.size+4;
  2256. FWriter.write(i,4);
  2257. FWriter.writearray(FCoffStrs);
  2258. end;
  2259. { Release }
  2260. FCoffStrs.Free;
  2261. result:=true;
  2262. end;
  2263. function IdataObjSectionCompare(Item1, Item2: Pointer): Integer;
  2264. var
  2265. I1 : TObjSection absolute Item1;
  2266. I2 : TObjSection absolute Item2;
  2267. begin
  2268. Result:=CompareStr(I1.Name,I2.Name);
  2269. end;
  2270. procedure TCoffexeoutput.Order_ObjSectionList(ObjSectionList: TFPObjectList;const aPattern:string);
  2271. begin
  2272. { Sort sections having '$' in the name, that's how PECOFF documentation
  2273. tells to handle them. However, look for '$' in the pattern, not in section
  2274. names, because the latter often get superfluous '$' due to mangling. }
  2275. if Pos('$',aPattern)>0 then
  2276. ObjSectionList.Sort(@IdataObjSectionCompare);
  2277. end;
  2278. constructor TDJCoffexeoutput.create;
  2279. begin
  2280. inherited createcoff(false);
  2281. datapos_offset:=sizeof(go32v2stub);
  2282. CExeSection:=TExeSection;
  2283. CObjData:=TDJCoffObjData;
  2284. end;
  2285. procedure TDJCoffexeoutput.MemPos_Header;
  2286. begin
  2287. { Headers are not loaded, first 4K page is reserved }
  2288. CurrMemPos:=$1000;
  2289. end;
  2290. constructor TPECoffexeoutput.create;
  2291. begin
  2292. inherited createcoff(true);
  2293. CExeSection:=TExeSection;
  2294. CObjData:=TPECoffObjData;
  2295. end;
  2296. procedure TPECoffexeoutput.MarkTargetSpecificSections(WorkList:TFPObjectList);
  2297. var
  2298. exesec:TExeSection;
  2299. objsec,textsec:TObjSection;
  2300. objsym:TObjSymbol;
  2301. objreloc:TObjRelocation;
  2302. i,j:longint;
  2303. begin
  2304. if target_info.system<>system_x86_64_win64 then
  2305. exit;
  2306. exesec:=FindExeSection('.pdata');
  2307. if exesec=nil then
  2308. exit;
  2309. for i:=0 to exesec.ObjSectionList.Count-1 do
  2310. begin
  2311. objsec:=TObjSection(exesec.ObjSectionList[i]);
  2312. if objsec.Used then
  2313. continue;
  2314. j:=0;
  2315. while j<objsec.ObjRelocations.Count do
  2316. begin
  2317. objreloc:=TObjRelocation(objsec.ObjRelocations[j]);
  2318. if objreloc.symbol=nil then
  2319. InternalError(2013041201);
  2320. textsec:=objreloc.symbol.objsection;
  2321. if textsec.used then
  2322. begin
  2323. WorkList.Add(objsec);
  2324. objsec.used:=true;
  2325. { The exact algorithm for non-smartlinked .pdata sections
  2326. is subject for refinement. Extreme cases are:
  2327. - several disjoint .pdata entries for a function, if function
  2328. is complex or if compiler splits it into chunks,
  2329. - single .pdata section referencing several .text sections,
  2330. may need to remove irrelevant parts like BFD does for
  2331. .eh_frame sections. }
  2332. break;
  2333. end;
  2334. inc(j,3);
  2335. end;
  2336. end;
  2337. end;
  2338. procedure TPECoffexeoutput.AfterUnusedSectionRemoval;
  2339. var
  2340. basedllname : string;
  2341. procedure StartImport(const dllname:string);
  2342. begin
  2343. if assigned(exemap) then
  2344. begin
  2345. exemap.Add('');
  2346. exemap.Add('Importing from DLL '+dllname);
  2347. end;
  2348. basedllname:=ExtractFileName(dllname);
  2349. { idata2 }
  2350. idata2objsection.writereloc_internal(idata4objsection,idata4objsection.size,sizeof(longint),RELOC_RVA);
  2351. idata2objsection.writezeros(2*sizeof(longint));
  2352. idata2objsection.writereloc_internal(idata7objsection,idata7objsection.size,sizeof(longint),RELOC_RVA);
  2353. idata2objsection.writereloc_internal(idata5objsection,idata5objsection.size,sizeof(longint),RELOC_RVA);
  2354. { idata7 }
  2355. idata7objsection.writestr(basedllname);
  2356. end;
  2357. procedure EndImport;
  2358. begin
  2359. { idata4 }
  2360. idata4objsection.writezeros(sizeof(longint));
  2361. if target_info.system=system_x86_64_win64 then
  2362. idata4objsection.writezeros(sizeof(longint));
  2363. { idata5 }
  2364. idata5objsection.writezeros(sizeof(longint));
  2365. if target_info.system=system_x86_64_win64 then
  2366. idata5objsection.writezeros(sizeof(longint));
  2367. end;
  2368. function AddImport(const afuncname,amangledname:string; AOrdNr:longint;isvar:boolean):TObjSymbol;
  2369. const
  2370. {$ifdef arm}
  2371. jmpopcode : array[0..7] of byte = (
  2372. $00,$c0,$9f,$e5, // ldr ip, [pc, #0]
  2373. $00,$f0,$9c,$e5 // ldr pc, [ip]
  2374. );
  2375. {$else arm}
  2376. jmpopcode : array[0..1] of byte = (
  2377. $ff,$25
  2378. );
  2379. {$endif arm}
  2380. nopopcodes : array[0..1] of byte = (
  2381. $90,$90
  2382. );
  2383. var
  2384. ordint: dword;
  2385. procedure WriteTableEntry(objsec:TObjSection);
  2386. begin
  2387. if AOrdNr <= 0 then
  2388. begin
  2389. objsec.writereloc_internal(idata6objsection,idata6objsection.size,sizeof(longint),RELOC_RVA);
  2390. if target_info.system=system_x86_64_win64 then
  2391. objsec.writezeros(sizeof(longint));
  2392. end
  2393. else
  2394. begin
  2395. { import by ordinal }
  2396. ordint:=AOrdNr;
  2397. if target_info.system=system_x86_64_win64 then
  2398. begin
  2399. objsec.write(ordint,sizeof(ordint));
  2400. ordint:=$80000000;
  2401. objsec.write(ordint,sizeof(ordint));
  2402. end
  2403. else
  2404. begin
  2405. ordint:=ordint or $80000000;
  2406. objsec.write(ordint,sizeof(ordint));
  2407. end;
  2408. end;
  2409. end;
  2410. begin
  2411. result:=nil;
  2412. if assigned(exemap) then
  2413. begin
  2414. if AOrdNr <= 0 then
  2415. exemap.Add(' Importing Function '+afuncname)
  2416. else
  2417. exemap.Add(' Importing Function '+afuncname+' (OrdNr='+tostr(AOrdNr)+')');
  2418. end;
  2419. { idata4, import lookup table }
  2420. WriteTableEntry(idata4objsection);
  2421. { idata5, import address table }
  2422. internalobjdata.SetSection(idata5objsection);
  2423. if isvar then
  2424. result:=internalobjdata.SymbolDefine(amangledname,AB_GLOBAL,AT_DATA)
  2425. else
  2426. begin
  2427. internalobjdata.SetSection(textobjsection);
  2428. textobjsection.writezeros(align_aword(textobjsection.size,16)-textobjsection.size);
  2429. result:=internalobjdata.SymbolDefine('_'+amangledname,AB_GLOBAL,AT_FUNCTION);
  2430. textobjsection.write(jmpopcode,sizeof(jmpopcode));
  2431. {$ifdef x86_64}
  2432. textobjsection.writereloc_internal(idata5objsection,idata5objsection.size,4,RELOC_RELATIVE);
  2433. {$else}
  2434. textobjsection.writereloc_internal(idata5objsection,idata5objsection.size,4,RELOC_ABSOLUTE32);
  2435. {$endif x86_64}
  2436. textobjsection.write(nopopcodes,align(textobjsection.size,sizeof(nopopcodes))-textobjsection.size);
  2437. end;
  2438. { idata5 section data }
  2439. WriteTableEntry(idata5objsection);
  2440. if (AOrdNr<=0) then
  2441. begin
  2442. { index hint, function name, null terminator and align }
  2443. ordint:=abs(AOrdNr);
  2444. idata6objsection.write(ordint,2);
  2445. idata6objsection.writestr(afuncname);
  2446. idata6objsection.writezeros(align(idata6objsection.size,2)-idata6objsection.size);
  2447. end;
  2448. end;
  2449. var
  2450. i,j : longint;
  2451. ImportLibrary : TImportLibrary;
  2452. ImportSymbol : TImportSymbol;
  2453. exesym : TExeSymbol;
  2454. newdll : boolean;
  2455. begin
  2456. for i:=0 to FImports.Count-1 do
  2457. begin
  2458. ImportLibrary:=TImportLibrary(FImports[i]);
  2459. newdll:=False;
  2460. for j:=0 to ImportLibrary.ImportSymbolList.Count-1 do
  2461. begin
  2462. ImportSymbol:=TImportSymbol(ImportLibrary.ImportSymbolList[j]);
  2463. exesym:=ImportSymbol.CachedExeSymbol;
  2464. if assigned(exesym) and
  2465. exesym.Used then
  2466. begin
  2467. if (not newdll) then
  2468. StartImport(ImportLibrary.Name);
  2469. newdll:=True;
  2470. exesym.objsymbol:=AddImport(ImportSymbol.Name,ImportSymbol.MangledName,ImportSymbol.OrdNr,ImportSymbol.IsVar);
  2471. end;
  2472. end;
  2473. if newdll then
  2474. EndImport;
  2475. end;
  2476. FixupSymbols;
  2477. end;
  2478. procedure TPECoffexeoutput.GenerateLibraryImports(ImportLibraryList:TFPHashObjectList);
  2479. var
  2480. i,j: longint;
  2481. ImportLibrary: TImportLibrary;
  2482. ImportSymbol: TImportSymbol;
  2483. exesym: TExeSymbol;
  2484. begin
  2485. { Here map import symbols to exe symbols and create necessary sections.
  2486. Actual import generation is done after unused sections (and symbols) are removed. }
  2487. FImports:=ImportLibraryList;
  2488. textobjsection:=internalObjData.CreateSection(sec_code);
  2489. textobjsection.SecOptions:=[oso_keep];
  2490. idata2objsection:=internalObjData.CreateSection(sec_idata2);
  2491. idata2objsection.SecOptions:=[oso_keep];
  2492. idata4objsection:=internalObjData.CreateSection(sec_idata4);
  2493. idata4objsection.SecOptions:=[oso_keep];
  2494. idata5objsection:=internalObjData.CreateSection(sec_idata5);
  2495. idata5objsection.SecOptions:=[oso_keep];
  2496. idata6objsection:=internalObjData.CreateSection(sec_idata6);
  2497. idata6objsection.SecOptions:=[oso_keep];
  2498. idata7objsection:=internalObjData.CreateSection(sec_idata7);
  2499. idata7objsection.SecOptions:=[oso_keep];
  2500. for i:=0 to ImportLibraryList.Count-1 do
  2501. begin
  2502. ImportLibrary:=TImportLibrary(ImportLibraryList[i]);
  2503. for j:=0 to ImportLibrary.ImportSymbolList.Count-1 do
  2504. begin
  2505. ImportSymbol:=TImportSymbol(ImportLibrary.ImportSymbolList[j]);
  2506. exesym:=TExeSymbol(ExeSymbolList.Find(ImportSymbol.MangledName));
  2507. if assigned(exesym) and
  2508. (exesym.State<>symstate_defined) then
  2509. begin
  2510. ImportSymbol.CachedExeSymbol:=exesym;
  2511. exesym.State:=symstate_defined;
  2512. end;
  2513. end;
  2514. end;
  2515. PackUnresolvedExeSymbols('after DLL imports');
  2516. end;
  2517. procedure TPECoffexeoutput.GenerateRelocs;
  2518. var
  2519. pgaddr, hdrpos : longword;
  2520. procedure FinishBlock;
  2521. var
  2522. p,len : longint;
  2523. begin
  2524. if hdrpos = longword(-1) then
  2525. exit;
  2526. p:=0;
  2527. internalobjdata.writebytes(p,align(internalobjdata.CurrObjSec.size,4)-internalobjdata.CurrObjSec.size);
  2528. p:=internalObjData.CurrObjSec.Data.Pos;
  2529. internalObjData.CurrObjSec.Data.seek(hdrpos+4);
  2530. len:=p-hdrpos;
  2531. internalObjData.CurrObjSec.Data.write(len,4);
  2532. internalObjData.CurrObjSec.Data.seek(p);
  2533. hdrpos:=longword(-1);
  2534. end;
  2535. var
  2536. exesec : TExeSection;
  2537. objsec : TObjSection;
  2538. objreloc : TObjRelocation;
  2539. i,j,k : longint;
  2540. offset : longword;
  2541. w: word;
  2542. begin
  2543. if not RelocSection or FRelocsGenerated then
  2544. exit;
  2545. exesec:=FindExeSection('.reloc');
  2546. if exesec=nil then
  2547. exit;
  2548. objsec:=internalObjData.createsection('.reloc',0,[oso_data,oso_keep]);
  2549. exesec.AddObjSection(objsec);
  2550. pgaddr:=longword(-1);
  2551. hdrpos:=longword(-1);
  2552. for i:=0 to ExeSectionList.Count-1 do
  2553. begin
  2554. exesec:=TExeSection(ExeSectionList[i]);
  2555. for j:=0 to exesec.ObjSectionList.count-1 do
  2556. begin
  2557. objsec:=TObjSection(exesec.ObjSectionList[j]);
  2558. { create relocs only for sections which are loaded in memory }
  2559. if not (oso_load in objsec.SecOptions) then
  2560. continue;
  2561. for k:=0 to objsec.ObjRelocations.Count-1 do
  2562. begin
  2563. objreloc:=TObjRelocation(objsec.ObjRelocations[k]);
  2564. if not (objreloc.typ in [{$ifdef cpu64bitaddr}RELOC_ABSOLUTE32,{$endif cpu64bitaddr}RELOC_ABSOLUTE]) then
  2565. continue;
  2566. offset:=objsec.MemPos+objreloc.dataoffset;
  2567. if (offset<pgaddr) and (pgaddr<>longword(-1)) then
  2568. Internalerror(2007062701);
  2569. if (offset-pgaddr>=4096) or (pgaddr=longword(-1)) then
  2570. begin
  2571. FinishBlock;
  2572. pgaddr:=(offset div 4096)*4096;
  2573. hdrpos:=internalObjData.CurrObjSec.Data.Pos;
  2574. internalObjData.writebytes(pgaddr,4);
  2575. { Reserving space for block size. The size will be written later in FinishBlock }
  2576. internalObjData.writebytes(k,4);
  2577. end;
  2578. {$ifdef cpu64bitaddr}
  2579. if objreloc.typ = RELOC_ABSOLUTE then
  2580. w:=IMAGE_REL_BASED_DIR64
  2581. else
  2582. {$endif cpu64bitaddr}
  2583. w:=IMAGE_REL_BASED_HIGHLOW;
  2584. w:=(w shl 12) or (offset-pgaddr);
  2585. internalObjData.writebytes(w,2);
  2586. end;
  2587. end;
  2588. end;
  2589. FinishBlock;
  2590. FRelocsGenerated:=true;
  2591. end;
  2592. procedure TPECoffexeoutput.MemPos_Start;
  2593. var
  2594. exesec : TExeSection;
  2595. begin
  2596. if RelocSection then
  2597. begin
  2598. exesec:=FindExeSection('.reloc');
  2599. if exesec=nil then
  2600. InternalError(2012072401);
  2601. exesec.Disabled:=false;
  2602. end;
  2603. inherited;
  2604. end;
  2605. procedure TPECoffexeoutput.MemPos_ExeSection(const aname:string);
  2606. begin
  2607. if aname='.reloc' then
  2608. GenerateRelocs;
  2609. inherited;
  2610. end;
  2611. {****************************************************************************
  2612. TDJCoffAssembler
  2613. ****************************************************************************}
  2614. constructor TDJCoffAssembler.Create(smart:boolean);
  2615. begin
  2616. inherited Create(smart);
  2617. CObjOutput:=TDJCoffObjOutput;
  2618. end;
  2619. {****************************************************************************
  2620. TPECoffAssembler
  2621. ****************************************************************************}
  2622. constructor TPECoffAssembler.Create(smart:boolean);
  2623. begin
  2624. inherited Create(smart);
  2625. CObjOutput:=TPECoffObjOutput;
  2626. end;
  2627. {*****************************************************************************
  2628. DLLReader
  2629. *****************************************************************************}
  2630. {$ifdef win32}
  2631. var
  2632. Wow64DisableWow64FsRedirection : function (var OldValue : pointer) : boolean;stdcall;
  2633. Wow64RevertWow64FsRedirection : function (OldValue : pointer) : boolean;stdcall;
  2634. {$endif win32}
  2635. function ReadDLLImports(const dllname:string;readdllproc:Treaddllproc):boolean;
  2636. type
  2637. TPECoffExpDir=packed record
  2638. flag,
  2639. stamp : cardinal;
  2640. Major,
  2641. Minor : word;
  2642. Name,
  2643. Base,
  2644. NumFuncs,
  2645. NumNames,
  2646. AddrFuncs,
  2647. AddrNames,
  2648. AddrOrds : cardinal;
  2649. end;
  2650. var
  2651. DLLReader : TObjectReader;
  2652. DosHeader : array[0..$7f] of byte;
  2653. PEMagic : array[0..3] of byte;
  2654. Header : TCoffHeader;
  2655. peheader : tcoffpeoptheader;
  2656. NameOfs,
  2657. newheaderofs : longword;
  2658. FuncName : string;
  2659. expdir : TPECoffExpDir;
  2660. i : longint;
  2661. found : boolean;
  2662. sechdr : tCoffSecHdr;
  2663. {$ifdef win32}
  2664. p : pointer;
  2665. {$endif win32}
  2666. begin
  2667. result:=false;
  2668. fillchar(sechdr,sizeof(sechdr),0);
  2669. {$ifdef win32}
  2670. if (target_info.system=system_x86_64_win64) and
  2671. assigned(Wow64DisableWow64FsRedirection) then
  2672. Wow64DisableWow64FsRedirection(p);
  2673. {$endif win32}
  2674. DLLReader:=TObjectReader.Create;
  2675. DLLReader.OpenFile(dllname);
  2676. {$ifdef win32}
  2677. if (target_info.system=system_x86_64_win64) and
  2678. assigned(Wow64RevertWow64FsRedirection) then
  2679. Wow64RevertWow64FsRedirection(p);
  2680. {$endif win32}
  2681. if not DLLReader.Read(DosHeader,sizeof(DosHeader)) or
  2682. (DosHeader[0]<>$4d) or (DosHeader[1]<>$5a) then
  2683. begin
  2684. Comment(V_Error,'Invalid DLL '+dllname+', Dos Header invalid');
  2685. exit;
  2686. end;
  2687. newheaderofs:=cardinal(DosHeader[$3c]) or (DosHeader[$3d] shl 8) or (DosHeader[$3e] shl 16) or (DosHeader[$3f] shl 24);
  2688. DLLReader.Seek(newheaderofs);
  2689. if not DLLReader.Read(PEMagic,sizeof(PEMagic)) or
  2690. (PEMagic[0]<>$50) or (PEMagic[1]<>$45) or (PEMagic[2]<>$00) or (PEMagic[3]<>$00) then
  2691. begin
  2692. Comment(V_Error,'Invalid DLL '+dllname+': invalid magic code');
  2693. exit;
  2694. end;
  2695. if not DLLReader.Read(Header,sizeof(TCoffHeader)) or
  2696. (Header.mach<>COFF_MAGIC) or
  2697. (Header.opthdr<>sizeof(tcoffpeoptheader)) then
  2698. begin
  2699. Comment(V_Error,'Invalid DLL '+dllname+', invalid header size');
  2700. exit;
  2701. end;
  2702. { Read optheader }
  2703. DLLreader.Read(peheader,sizeof(tcoffpeoptheader));
  2704. { Section headers }
  2705. found:=false;
  2706. for i:=1 to header.nsects do
  2707. begin
  2708. if not DLLreader.read(sechdr,sizeof(sechdr)) then
  2709. begin
  2710. Comment(V_Error,'Error reading coff file '+DLLName);
  2711. exit;
  2712. end;
  2713. if (sechdr.rvaofs<=peheader.DataDirectory[PE_DATADIR_EDATA].vaddr) and
  2714. (peheader.DataDirectory[PE_DATADIR_EDATA].vaddr<sechdr.rvaofs+sechdr.vsize) then
  2715. begin
  2716. found:=true;
  2717. break;
  2718. end;
  2719. end;
  2720. if not found then
  2721. begin
  2722. Comment(V_Warning,'DLL '+DLLName+' does not contain any exports');
  2723. exit;
  2724. end;
  2725. { Process edata }
  2726. DLLReader.Seek(sechdr.datapos+peheader.DataDirectory[PE_DATADIR_EDATA].vaddr-sechdr.rvaofs);
  2727. DLLReader.Read(expdir,sizeof(expdir));
  2728. for i:=0 to expdir.NumNames-1 do
  2729. begin
  2730. DLLReader.Seek(sechdr.datapos+expdir.AddrNames-sechdr.rvaofs+i*4);
  2731. DLLReader.Read(NameOfs,4);
  2732. Dec(NameOfs,sechdr.rvaofs);
  2733. if {(NameOfs<0) or}
  2734. (NameOfs>sechdr.vsize) then
  2735. begin
  2736. Comment(V_Error,'DLL does contains invalid exports');
  2737. break;
  2738. end;
  2739. { Read Function name from DLL, prepend _ and terminate with #0 }
  2740. DLLReader.Seek(sechdr.datapos+NameOfs);
  2741. DLLReader.Read((@FuncName[1])^,sizeof(FuncName)-3);
  2742. FuncName[sizeof(FuncName)-1]:=#0;
  2743. FuncName[0]:=chr(Strlen(@FuncName[1]));
  2744. readdllproc(DLLName,FuncName);
  2745. end;
  2746. DLLReader.Free;
  2747. end;
  2748. {*****************************************************************************
  2749. Initialize
  2750. *****************************************************************************}
  2751. {$ifdef i386}
  2752. const
  2753. as_i386_coff_info : tasminfo =
  2754. (
  2755. id : as_i386_coff;
  2756. idtxt : 'COFF';
  2757. asmbin : '';
  2758. asmcmd : '';
  2759. supported_targets : [system_i386_go32v2];
  2760. flags : [af_outputbinary,af_smartlink_sections];
  2761. labelprefix : '.L';
  2762. comment : '';
  2763. dollarsign: '$';
  2764. );
  2765. as_i386_pecoff_info : tasminfo =
  2766. (
  2767. id : as_i386_pecoff;
  2768. idtxt : 'PECOFF';
  2769. asmbin : '';
  2770. asmcmd : '';
  2771. supported_targets : [system_i386_win32,system_i386_nativent];
  2772. flags : [af_outputbinary,af_smartlink_sections];
  2773. labelprefix : '.L';
  2774. comment : '';
  2775. dollarsign: '$';
  2776. );
  2777. as_i386_pecoffwdosx_info : tasminfo =
  2778. (
  2779. id : as_i386_pecoffwdosx;
  2780. idtxt : 'PEWDOSX';
  2781. asmbin : '';
  2782. asmcmd : '';
  2783. supported_targets : [system_i386_wdosx];
  2784. flags : [af_outputbinary];
  2785. labelprefix : '.L';
  2786. comment : '';
  2787. dollarsign: '$';
  2788. );
  2789. as_i386_pecoffwince_info : tasminfo =
  2790. (
  2791. id : as_i386_pecoffwince;
  2792. idtxt : 'PECOFFWINCE';
  2793. asmbin : '';
  2794. asmcmd : '';
  2795. supported_targets : [system_i386_wince];
  2796. flags : [af_outputbinary,af_smartlink_sections];
  2797. labelprefix : '.L';
  2798. comment : '';
  2799. dollarsign: '$';
  2800. );
  2801. {$endif i386}
  2802. {$ifdef x86_64}
  2803. const
  2804. as_x86_64_pecoff_info : tasminfo =
  2805. (
  2806. id : as_x86_64_pecoff;
  2807. idtxt : 'PECOFF';
  2808. asmbin : '';
  2809. asmcmd : '';
  2810. supported_targets : [system_x86_64_win64];
  2811. flags : [af_outputbinary,af_smartlink_sections];
  2812. labelprefix : '.L';
  2813. comment : '';
  2814. dollarsign: '$';
  2815. );
  2816. {$endif x86_64}
  2817. {$ifdef arm}
  2818. const
  2819. as_arm_pecoffwince_info : tasminfo =
  2820. (
  2821. id : as_arm_pecoffwince;
  2822. idtxt : 'PECOFFWINCE';
  2823. asmbin : '';
  2824. asmcmd : '';
  2825. supported_targets : [system_arm_wince];
  2826. flags : [af_outputbinary];
  2827. labelprefix : '.L';
  2828. comment : '';
  2829. dollarsign: '$';
  2830. );
  2831. {$endif arm}
  2832. {$ifdef win32}
  2833. procedure SetupProcVars;
  2834. var
  2835. hinstLib : THandle;
  2836. begin
  2837. Wow64DisableWow64FsRedirection:=nil;
  2838. Wow64RevertWow64FsRedirection:=nil;
  2839. hinstLib:=LoadLibrary('kernel32.dll');
  2840. if hinstLib<>0 then
  2841. begin
  2842. pointer(Wow64DisableWow64FsRedirection):=GetProcAddress(hinstLib,'Wow64DisableWow64FsRedirection');
  2843. pointer(Wow64RevertWow64FsRedirection):=GetProcAddress(hinstLib,'Wow64RevertWow64FsRedirection');
  2844. FreeLibrary(hinstLib);
  2845. end;
  2846. end;
  2847. {$endif win32}
  2848. initialization
  2849. {$ifdef i386}
  2850. RegisterAssembler(as_i386_coff_info,TDJCoffAssembler);
  2851. RegisterAssembler(as_i386_pecoff_info,TPECoffAssembler);
  2852. RegisterAssembler(as_i386_pecoffwdosx_info,TPECoffAssembler);
  2853. RegisterAssembler(as_i386_pecoffwince_info,TPECoffAssembler);
  2854. {$endif i386}
  2855. {$ifdef x86_64}
  2856. RegisterAssembler(as_x86_64_pecoff_info,TPECoffAssembler);
  2857. {$endif x86_64}
  2858. {$ifdef arm}
  2859. RegisterAssembler(as_arm_pecoffwince_info,TPECoffAssembler);
  2860. {$endif arm}
  2861. {$ifdef win32}
  2862. SetupProcVars;
  2863. {$endif win32}
  2864. end.