ogcoff.pas 111 KB

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