ogcoff.pas 109 KB

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