tccpe.c 60 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015
  1. /*
  2. * TCCPE.C - PE file output for the Tiny C Compiler
  3. *
  4. * Copyright (c) 2005-2007 grischka
  5. *
  6. * This library is free software; you can redistribute it and/or
  7. * modify it under the terms of the GNU Lesser General Public
  8. * License as published by the Free Software Foundation; either
  9. * version 2 of the License, or (at your option) any later version.
  10. *
  11. * This library is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  14. * Lesser General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU Lesser General Public
  17. * License along with this library; if not, write to the Free Software
  18. * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  19. */
  20. #include "tcc.h"
  21. #define PE_MERGE_DATA
  22. /* #define PE_PRINT_SECTIONS */
  23. #ifndef _WIN32
  24. #define stricmp strcasecmp
  25. #define strnicmp strncasecmp
  26. #include <sys/stat.h> /* chmod() */
  27. #endif
  28. #ifdef TCC_TARGET_X86_64
  29. # define ADDR3264 ULONGLONG
  30. # define PE_IMAGE_REL IMAGE_REL_BASED_DIR64
  31. # define REL_TYPE_DIRECT R_X86_64_64
  32. # define R_XXX_THUNKFIX R_X86_64_PC32
  33. # define R_XXX_RELATIVE R_X86_64_RELATIVE
  34. # define IMAGE_FILE_MACHINE 0x8664
  35. # define RSRC_RELTYPE 3
  36. #elif defined TCC_TARGET_ARM
  37. # define ADDR3264 DWORD
  38. # define PE_IMAGE_REL IMAGE_REL_BASED_HIGHLOW
  39. # define REL_TYPE_DIRECT R_ARM_ABS32
  40. # define R_XXX_THUNKFIX R_ARM_ABS32
  41. # define R_XXX_RELATIVE R_ARM_RELATIVE
  42. # define IMAGE_FILE_MACHINE 0x01C0
  43. # define RSRC_RELTYPE 7 /* ??? (not tested) */
  44. #elif defined TCC_TARGET_I386
  45. # define ADDR3264 DWORD
  46. # define PE_IMAGE_REL IMAGE_REL_BASED_HIGHLOW
  47. # define REL_TYPE_DIRECT R_386_32
  48. # define R_XXX_THUNKFIX R_386_32
  49. # define R_XXX_RELATIVE R_386_RELATIVE
  50. # define IMAGE_FILE_MACHINE 0x014C
  51. # define RSRC_RELTYPE 7 /* DIR32NB */
  52. #endif
  53. #ifndef IMAGE_NT_SIGNATURE
  54. /* ----------------------------------------------------------- */
  55. /* definitions below are from winnt.h */
  56. typedef unsigned char BYTE;
  57. typedef unsigned short WORD;
  58. typedef unsigned int DWORD;
  59. typedef unsigned long long ULONGLONG;
  60. #pragma pack(push, 1)
  61. typedef struct _IMAGE_DOS_HEADER { /* DOS .EXE header */
  62. WORD e_magic; /* Magic number */
  63. WORD e_cblp; /* Bytes on last page of file */
  64. WORD e_cp; /* Pages in file */
  65. WORD e_crlc; /* Relocations */
  66. WORD e_cparhdr; /* Size of header in paragraphs */
  67. WORD e_minalloc; /* Minimum extra paragraphs needed */
  68. WORD e_maxalloc; /* Maximum extra paragraphs needed */
  69. WORD e_ss; /* Initial (relative) SS value */
  70. WORD e_sp; /* Initial SP value */
  71. WORD e_csum; /* Checksum */
  72. WORD e_ip; /* Initial IP value */
  73. WORD e_cs; /* Initial (relative) CS value */
  74. WORD e_lfarlc; /* File address of relocation table */
  75. WORD e_ovno; /* Overlay number */
  76. WORD e_res[4]; /* Reserved words */
  77. WORD e_oemid; /* OEM identifier (for e_oeminfo) */
  78. WORD e_oeminfo; /* OEM information; e_oemid specific */
  79. WORD e_res2[10]; /* Reserved words */
  80. DWORD e_lfanew; /* File address of new exe header */
  81. } IMAGE_DOS_HEADER, *PIMAGE_DOS_HEADER;
  82. #define IMAGE_NT_SIGNATURE 0x00004550 /* PE00 */
  83. #define SIZE_OF_NT_SIGNATURE 4
  84. typedef struct _IMAGE_FILE_HEADER {
  85. WORD Machine;
  86. WORD NumberOfSections;
  87. DWORD TimeDateStamp;
  88. DWORD PointerToSymbolTable;
  89. DWORD NumberOfSymbols;
  90. WORD SizeOfOptionalHeader;
  91. WORD Characteristics;
  92. } IMAGE_FILE_HEADER, *PIMAGE_FILE_HEADER;
  93. #define IMAGE_SIZEOF_FILE_HEADER 20
  94. typedef struct _IMAGE_DATA_DIRECTORY {
  95. DWORD VirtualAddress;
  96. DWORD Size;
  97. } IMAGE_DATA_DIRECTORY, *PIMAGE_DATA_DIRECTORY;
  98. typedef struct _IMAGE_OPTIONAL_HEADER {
  99. /* Standard fields. */
  100. WORD Magic;
  101. BYTE MajorLinkerVersion;
  102. BYTE MinorLinkerVersion;
  103. DWORD SizeOfCode;
  104. DWORD SizeOfInitializedData;
  105. DWORD SizeOfUninitializedData;
  106. DWORD AddressOfEntryPoint;
  107. DWORD BaseOfCode;
  108. #ifndef TCC_TARGET_X86_64
  109. DWORD BaseOfData;
  110. #endif
  111. /* NT additional fields. */
  112. ADDR3264 ImageBase;
  113. DWORD SectionAlignment;
  114. DWORD FileAlignment;
  115. WORD MajorOperatingSystemVersion;
  116. WORD MinorOperatingSystemVersion;
  117. WORD MajorImageVersion;
  118. WORD MinorImageVersion;
  119. WORD MajorSubsystemVersion;
  120. WORD MinorSubsystemVersion;
  121. DWORD Win32VersionValue;
  122. DWORD SizeOfImage;
  123. DWORD SizeOfHeaders;
  124. DWORD CheckSum;
  125. WORD Subsystem;
  126. WORD DllCharacteristics;
  127. ADDR3264 SizeOfStackReserve;
  128. ADDR3264 SizeOfStackCommit;
  129. ADDR3264 SizeOfHeapReserve;
  130. ADDR3264 SizeOfHeapCommit;
  131. DWORD LoaderFlags;
  132. DWORD NumberOfRvaAndSizes;
  133. IMAGE_DATA_DIRECTORY DataDirectory[16];
  134. } IMAGE_OPTIONAL_HEADER32, IMAGE_OPTIONAL_HEADER64, IMAGE_OPTIONAL_HEADER;
  135. #define IMAGE_DIRECTORY_ENTRY_EXPORT 0 /* Export Directory */
  136. #define IMAGE_DIRECTORY_ENTRY_IMPORT 1 /* Import Directory */
  137. #define IMAGE_DIRECTORY_ENTRY_RESOURCE 2 /* Resource Directory */
  138. #define IMAGE_DIRECTORY_ENTRY_EXCEPTION 3 /* Exception Directory */
  139. #define IMAGE_DIRECTORY_ENTRY_SECURITY 4 /* Security Directory */
  140. #define IMAGE_DIRECTORY_ENTRY_BASERELOC 5 /* Base Relocation Table */
  141. #define IMAGE_DIRECTORY_ENTRY_DEBUG 6 /* Debug Directory */
  142. /* IMAGE_DIRECTORY_ENTRY_COPYRIGHT 7 (X86 usage) */
  143. #define IMAGE_DIRECTORY_ENTRY_ARCHITECTURE 7 /* Architecture Specific Data */
  144. #define IMAGE_DIRECTORY_ENTRY_GLOBALPTR 8 /* RVA of GP */
  145. #define IMAGE_DIRECTORY_ENTRY_TLS 9 /* TLS Directory */
  146. #define IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG 10 /* Load Configuration Directory */
  147. #define IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT 11 /* Bound Import Directory in headers */
  148. #define IMAGE_DIRECTORY_ENTRY_IAT 12 /* Import Address Table */
  149. #define IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT 13 /* Delay Load Import Descriptors */
  150. #define IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR 14 /* COM Runtime descriptor */
  151. /* Section header format. */
  152. #define IMAGE_SIZEOF_SHORT_NAME 8
  153. typedef struct _IMAGE_SECTION_HEADER {
  154. BYTE Name[IMAGE_SIZEOF_SHORT_NAME];
  155. union {
  156. DWORD PhysicalAddress;
  157. DWORD VirtualSize;
  158. } Misc;
  159. DWORD VirtualAddress;
  160. DWORD SizeOfRawData;
  161. DWORD PointerToRawData;
  162. DWORD PointerToRelocations;
  163. DWORD PointerToLinenumbers;
  164. WORD NumberOfRelocations;
  165. WORD NumberOfLinenumbers;
  166. DWORD Characteristics;
  167. } IMAGE_SECTION_HEADER, *PIMAGE_SECTION_HEADER;
  168. #define IMAGE_SIZEOF_SECTION_HEADER 40
  169. typedef struct _IMAGE_EXPORT_DIRECTORY {
  170. DWORD Characteristics;
  171. DWORD TimeDateStamp;
  172. WORD MajorVersion;
  173. WORD MinorVersion;
  174. DWORD Name;
  175. DWORD Base;
  176. DWORD NumberOfFunctions;
  177. DWORD NumberOfNames;
  178. DWORD AddressOfFunctions;
  179. DWORD AddressOfNames;
  180. DWORD AddressOfNameOrdinals;
  181. } IMAGE_EXPORT_DIRECTORY,*PIMAGE_EXPORT_DIRECTORY;
  182. typedef struct _IMAGE_IMPORT_DESCRIPTOR {
  183. union {
  184. DWORD Characteristics;
  185. DWORD OriginalFirstThunk;
  186. };
  187. DWORD TimeDateStamp;
  188. DWORD ForwarderChain;
  189. DWORD Name;
  190. DWORD FirstThunk;
  191. } IMAGE_IMPORT_DESCRIPTOR;
  192. typedef struct _IMAGE_BASE_RELOCATION {
  193. DWORD VirtualAddress;
  194. DWORD SizeOfBlock;
  195. // WORD TypeOffset[1];
  196. } IMAGE_BASE_RELOCATION;
  197. #define IMAGE_SIZEOF_BASE_RELOCATION 8
  198. #define IMAGE_REL_BASED_ABSOLUTE 0
  199. #define IMAGE_REL_BASED_HIGH 1
  200. #define IMAGE_REL_BASED_LOW 2
  201. #define IMAGE_REL_BASED_HIGHLOW 3
  202. #define IMAGE_REL_BASED_HIGHADJ 4
  203. #define IMAGE_REL_BASED_MIPS_JMPADDR 5
  204. #define IMAGE_REL_BASED_SECTION 6
  205. #define IMAGE_REL_BASED_REL32 7
  206. #define IMAGE_REL_BASED_DIR64 10
  207. #pragma pack(pop)
  208. /* ----------------------------------------------------------- */
  209. #endif /* ndef IMAGE_NT_SIGNATURE */
  210. /* ----------------------------------------------------------- */
  211. #ifndef IMAGE_REL_BASED_DIR64
  212. # define IMAGE_REL_BASED_DIR64 10
  213. #endif
  214. #pragma pack(push, 1)
  215. struct pe_header
  216. {
  217. IMAGE_DOS_HEADER doshdr;
  218. BYTE dosstub[0x40];
  219. DWORD nt_sig;
  220. IMAGE_FILE_HEADER filehdr;
  221. #ifdef TCC_TARGET_X86_64
  222. IMAGE_OPTIONAL_HEADER64 opthdr;
  223. #else
  224. #ifdef _WIN64
  225. IMAGE_OPTIONAL_HEADER32 opthdr;
  226. #else
  227. IMAGE_OPTIONAL_HEADER opthdr;
  228. #endif
  229. #endif
  230. };
  231. struct pe_reloc_header {
  232. DWORD offset;
  233. DWORD size;
  234. };
  235. struct pe_rsrc_header {
  236. struct _IMAGE_FILE_HEADER filehdr;
  237. struct _IMAGE_SECTION_HEADER sectionhdr;
  238. };
  239. struct pe_rsrc_reloc {
  240. DWORD offset;
  241. DWORD size;
  242. WORD type;
  243. };
  244. #pragma pack(pop)
  245. /* ------------------------------------------------------------- */
  246. /* internal temporary structures */
  247. /*
  248. #define IMAGE_SCN_CNT_CODE 0x00000020
  249. #define IMAGE_SCN_CNT_INITIALIZED_DATA 0x00000040
  250. #define IMAGE_SCN_CNT_UNINITIALIZED_DATA 0x00000080
  251. #define IMAGE_SCN_MEM_DISCARDABLE 0x02000000
  252. #define IMAGE_SCN_MEM_SHARED 0x10000000
  253. #define IMAGE_SCN_MEM_EXECUTE 0x20000000
  254. #define IMAGE_SCN_MEM_READ 0x40000000
  255. #define IMAGE_SCN_MEM_WRITE 0x80000000
  256. */
  257. enum {
  258. sec_text = 0,
  259. sec_data ,
  260. sec_bss ,
  261. sec_idata ,
  262. sec_pdata ,
  263. sec_other ,
  264. sec_rsrc ,
  265. sec_stab ,
  266. sec_reloc ,
  267. sec_last
  268. };
  269. static const DWORD pe_sec_flags[] = {
  270. 0x60000020, /* ".text" , */
  271. 0xC0000040, /* ".data" , */
  272. 0xC0000080, /* ".bss" , */
  273. 0x40000040, /* ".idata" , */
  274. 0x40000040, /* ".pdata" , */
  275. 0xE0000060, /* < other > , */
  276. 0x40000040, /* ".rsrc" , */
  277. 0x42000802, /* ".stab" , */
  278. 0x42000040, /* ".reloc" , */
  279. };
  280. struct section_info {
  281. int cls, ord;
  282. char name[32];
  283. DWORD sh_addr;
  284. DWORD sh_size;
  285. DWORD sh_flags;
  286. unsigned char *data;
  287. DWORD data_size;
  288. IMAGE_SECTION_HEADER ish;
  289. };
  290. struct import_symbol {
  291. int sym_index;
  292. int iat_index;
  293. int thk_offset;
  294. };
  295. struct pe_import_info {
  296. int dll_index;
  297. int sym_count;
  298. struct import_symbol **symbols;
  299. };
  300. struct pe_info {
  301. TCCState *s1;
  302. Section *reloc;
  303. Section *thunk;
  304. const char *filename;
  305. int type;
  306. DWORD sizeofheaders;
  307. ADDR3264 imagebase;
  308. const char *start_symbol;
  309. DWORD start_addr;
  310. DWORD imp_offs;
  311. DWORD imp_size;
  312. DWORD iat_offs;
  313. DWORD iat_size;
  314. DWORD exp_offs;
  315. DWORD exp_size;
  316. int subsystem;
  317. DWORD section_align;
  318. DWORD file_align;
  319. struct section_info *sec_info;
  320. int sec_count;
  321. struct pe_import_info **imp_info;
  322. int imp_count;
  323. };
  324. #define PE_NUL 0
  325. #define PE_DLL 1
  326. #define PE_GUI 2
  327. #define PE_EXE 3
  328. #define PE_RUN 4
  329. /* --------------------------------------------*/
  330. static const char *pe_export_name(TCCState *s1, ElfW(Sym) *sym)
  331. {
  332. const char *name = (char*)symtab_section->link->data + sym->st_name;
  333. if (s1->leading_underscore && name[0] == '_' && !(sym->st_other & ST_PE_STDCALL))
  334. return name + 1;
  335. return name;
  336. }
  337. static int pe_find_import(TCCState * s1, ElfW(Sym) *sym)
  338. {
  339. char buffer[200];
  340. const char *s, *p;
  341. int sym_index = 0, n = 0;
  342. int a, err = 0;
  343. do {
  344. s = pe_export_name(s1, sym);
  345. a = 0;
  346. if (n) {
  347. /* second try: */
  348. if (sym->st_other & ST_PE_STDCALL) {
  349. /* try w/0 stdcall deco (windows API convention) */
  350. p = strrchr(s, '@');
  351. if (!p || s[0] != '_')
  352. break;
  353. strcpy(buffer, s+1)[p-s-1] = 0;
  354. } else if (s[0] != '_') { /* try non-ansi function */
  355. buffer[0] = '_', strcpy(buffer + 1, s);
  356. } else if (0 == memcmp(s, "__imp_", 6)) { /* mingw 2.0 */
  357. strcpy(buffer, s + 6), a = 1;
  358. } else if (0 == memcmp(s, "_imp__", 6)) { /* mingw 3.7 */
  359. strcpy(buffer, s + 6), a = 1;
  360. } else {
  361. continue;
  362. }
  363. s = buffer;
  364. }
  365. sym_index = find_elf_sym(s1->dynsymtab_section, s);
  366. // printf("find (%d) %d %s\n", n, sym_index, s);
  367. if (sym_index
  368. && ELFW(ST_TYPE)(sym->st_info) == STT_OBJECT
  369. && 0 == (sym->st_other & ST_PE_IMPORT)
  370. && 0 == a
  371. ) err = -1, sym_index = 0;
  372. } while (0 == sym_index && ++n < 2);
  373. return n == 2 ? err : sym_index;
  374. }
  375. /*----------------------------------------------------------------------------*/
  376. static int dynarray_assoc(void **pp, int n, int key)
  377. {
  378. int i;
  379. for (i = 0; i < n; ++i, ++pp)
  380. if (key == **(int **) pp)
  381. return i;
  382. return -1;
  383. }
  384. #if 0
  385. ST_FN DWORD umin(DWORD a, DWORD b)
  386. {
  387. return a < b ? a : b;
  388. }
  389. #endif
  390. static DWORD umax(DWORD a, DWORD b)
  391. {
  392. return a < b ? b : a;
  393. }
  394. static DWORD pe_file_align(struct pe_info *pe, DWORD n)
  395. {
  396. return (n + (pe->file_align - 1)) & ~(pe->file_align - 1);
  397. }
  398. static DWORD pe_virtual_align(struct pe_info *pe, DWORD n)
  399. {
  400. return (n + (pe->section_align - 1)) & ~(pe->section_align - 1);
  401. }
  402. static void pe_align_section(Section *s, int a)
  403. {
  404. int i = s->data_offset & (a-1);
  405. if (i)
  406. section_ptr_add(s, a - i);
  407. }
  408. static void pe_set_datadir(struct pe_header *hdr, int dir, DWORD addr, DWORD size)
  409. {
  410. hdr->opthdr.DataDirectory[dir].VirtualAddress = addr;
  411. hdr->opthdr.DataDirectory[dir].Size = size;
  412. }
  413. static int pe_fwrite(void *data, unsigned len, FILE *fp, DWORD *psum)
  414. {
  415. if (psum) {
  416. DWORD sum = *psum;
  417. WORD *p = data;
  418. int i;
  419. for (i = len; i > 0; i -= 2) {
  420. sum += (i >= 2) ? *p++ : *(BYTE*)p;
  421. sum = (sum + (sum >> 16)) & 0xFFFF;
  422. }
  423. *psum = sum;
  424. }
  425. return len == fwrite(data, 1, len, fp) ? 0 : -1;
  426. }
  427. static void pe_fpad(FILE *fp, DWORD new_pos)
  428. {
  429. DWORD pos = ftell(fp);
  430. while (++pos <= new_pos)
  431. fputc(0, fp);
  432. }
  433. /*----------------------------------------------------------------------------*/
  434. static int pe_write(struct pe_info *pe)
  435. {
  436. static const struct pe_header pe_template = {
  437. {
  438. /* IMAGE_DOS_HEADER doshdr */
  439. 0x5A4D, /*WORD e_magic; Magic number */
  440. 0x0090, /*WORD e_cblp; Bytes on last page of file */
  441. 0x0003, /*WORD e_cp; Pages in file */
  442. 0x0000, /*WORD e_crlc; Relocations */
  443. 0x0004, /*WORD e_cparhdr; Size of header in paragraphs */
  444. 0x0000, /*WORD e_minalloc; Minimum extra paragraphs needed */
  445. 0xFFFF, /*WORD e_maxalloc; Maximum extra paragraphs needed */
  446. 0x0000, /*WORD e_ss; Initial (relative) SS value */
  447. 0x00B8, /*WORD e_sp; Initial SP value */
  448. 0x0000, /*WORD e_csum; Checksum */
  449. 0x0000, /*WORD e_ip; Initial IP value */
  450. 0x0000, /*WORD e_cs; Initial (relative) CS value */
  451. 0x0040, /*WORD e_lfarlc; File address of relocation table */
  452. 0x0000, /*WORD e_ovno; Overlay number */
  453. {0,0,0,0}, /*WORD e_res[4]; Reserved words */
  454. 0x0000, /*WORD e_oemid; OEM identifier (for e_oeminfo) */
  455. 0x0000, /*WORD e_oeminfo; OEM information; e_oemid specific */
  456. {0,0,0,0,0,0,0,0,0,0}, /*WORD e_res2[10]; Reserved words */
  457. 0x00000080 /*DWORD e_lfanew; File address of new exe header */
  458. },{
  459. /* BYTE dosstub[0x40] */
  460. /* 14 code bytes + "This program cannot be run in DOS mode.\r\r\n$" + 6 * 0x00 */
  461. 0x0e,0x1f,0xba,0x0e,0x00,0xb4,0x09,0xcd,0x21,0xb8,0x01,0x4c,0xcd,0x21,0x54,0x68,
  462. 0x69,0x73,0x20,0x70,0x72,0x6f,0x67,0x72,0x61,0x6d,0x20,0x63,0x61,0x6e,0x6e,0x6f,
  463. 0x74,0x20,0x62,0x65,0x20,0x72,0x75,0x6e,0x20,0x69,0x6e,0x20,0x44,0x4f,0x53,0x20,
  464. 0x6d,0x6f,0x64,0x65,0x2e,0x0d,0x0d,0x0a,0x24,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  465. },
  466. 0x00004550, /* DWORD nt_sig = IMAGE_NT_SIGNATURE */
  467. {
  468. /* IMAGE_FILE_HEADER filehdr */
  469. IMAGE_FILE_MACHINE, /*WORD Machine; */
  470. 0x0003, /*WORD NumberOfSections; */
  471. 0x00000000, /*DWORD TimeDateStamp; */
  472. 0x00000000, /*DWORD PointerToSymbolTable; */
  473. 0x00000000, /*DWORD NumberOfSymbols; */
  474. #if defined(TCC_TARGET_X86_64)
  475. 0x00F0, /*WORD SizeOfOptionalHeader; */
  476. 0x022F /*WORD Characteristics; */
  477. #define CHARACTERISTICS_DLL 0x222E
  478. #elif defined(TCC_TARGET_I386)
  479. 0x00E0, /*WORD SizeOfOptionalHeader; */
  480. 0x030F /*WORD Characteristics; */
  481. #define CHARACTERISTICS_DLL 0x230E
  482. #elif defined(TCC_TARGET_ARM)
  483. 0x00E0, /*WORD SizeOfOptionalHeader; */
  484. 0x010F, /*WORD Characteristics; */
  485. #define CHARACTERISTICS_DLL 0x230F
  486. #endif
  487. },{
  488. /* IMAGE_OPTIONAL_HEADER opthdr */
  489. /* Standard fields. */
  490. #ifdef TCC_TARGET_X86_64
  491. 0x020B, /*WORD Magic; */
  492. #else
  493. 0x010B, /*WORD Magic; */
  494. #endif
  495. 0x06, /*BYTE MajorLinkerVersion; */
  496. 0x00, /*BYTE MinorLinkerVersion; */
  497. 0x00000000, /*DWORD SizeOfCode; */
  498. 0x00000000, /*DWORD SizeOfInitializedData; */
  499. 0x00000000, /*DWORD SizeOfUninitializedData; */
  500. 0x00000000, /*DWORD AddressOfEntryPoint; */
  501. 0x00000000, /*DWORD BaseOfCode; */
  502. #ifndef TCC_TARGET_X86_64
  503. 0x00000000, /*DWORD BaseOfData; */
  504. #endif
  505. /* NT additional fields. */
  506. #if defined(TCC_TARGET_ARM)
  507. 0x00100000, /*DWORD ImageBase; */
  508. #else
  509. 0x00400000, /*DWORD ImageBase; */
  510. #endif
  511. 0x00001000, /*DWORD SectionAlignment; */
  512. 0x00000200, /*DWORD FileAlignment; */
  513. 0x0004, /*WORD MajorOperatingSystemVersion; */
  514. 0x0000, /*WORD MinorOperatingSystemVersion; */
  515. 0x0000, /*WORD MajorImageVersion; */
  516. 0x0000, /*WORD MinorImageVersion; */
  517. 0x0004, /*WORD MajorSubsystemVersion; */
  518. 0x0000, /*WORD MinorSubsystemVersion; */
  519. 0x00000000, /*DWORD Win32VersionValue; */
  520. 0x00000000, /*DWORD SizeOfImage; */
  521. 0x00000200, /*DWORD SizeOfHeaders; */
  522. 0x00000000, /*DWORD CheckSum; */
  523. 0x0002, /*WORD Subsystem; */
  524. 0x0000, /*WORD DllCharacteristics; */
  525. 0x00100000, /*DWORD SizeOfStackReserve; */
  526. 0x00001000, /*DWORD SizeOfStackCommit; */
  527. 0x00100000, /*DWORD SizeOfHeapReserve; */
  528. 0x00001000, /*DWORD SizeOfHeapCommit; */
  529. 0x00000000, /*DWORD LoaderFlags; */
  530. 0x00000010, /*DWORD NumberOfRvaAndSizes; */
  531. /* IMAGE_DATA_DIRECTORY DataDirectory[16]; */
  532. {{0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0},
  533. {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}}
  534. }};
  535. struct pe_header pe_header = pe_template;
  536. int i;
  537. FILE *op;
  538. DWORD file_offset, sum;
  539. struct section_info *si;
  540. IMAGE_SECTION_HEADER *psh;
  541. op = fopen(pe->filename, "wb");
  542. if (NULL == op) {
  543. tcc_error_noabort("could not write '%s': %s", pe->filename, strerror(errno));
  544. return -1;
  545. }
  546. pe->sizeofheaders = pe_file_align(pe,
  547. sizeof (struct pe_header)
  548. + pe->sec_count * sizeof (IMAGE_SECTION_HEADER)
  549. );
  550. file_offset = pe->sizeofheaders;
  551. if (2 == pe->s1->verbose)
  552. printf("-------------------------------"
  553. "\n virt file size section" "\n");
  554. for (i = 0; i < pe->sec_count; ++i) {
  555. DWORD addr, size;
  556. const char *sh_name;
  557. si = pe->sec_info + i;
  558. sh_name = si->name;
  559. addr = si->sh_addr - pe->imagebase;
  560. size = si->sh_size;
  561. psh = &si->ish;
  562. if (2 == pe->s1->verbose)
  563. printf("%6x %6x %6x %s\n",
  564. (unsigned)addr, (unsigned)file_offset, (unsigned)size, sh_name);
  565. switch (si->cls) {
  566. case sec_text:
  567. pe_header.opthdr.BaseOfCode = addr;
  568. break;
  569. case sec_data:
  570. #ifndef TCC_TARGET_X86_64
  571. pe_header.opthdr.BaseOfData = addr;
  572. #endif
  573. break;
  574. case sec_bss:
  575. break;
  576. case sec_reloc:
  577. pe_set_datadir(&pe_header, IMAGE_DIRECTORY_ENTRY_BASERELOC, addr, size);
  578. break;
  579. case sec_rsrc:
  580. pe_set_datadir(&pe_header, IMAGE_DIRECTORY_ENTRY_RESOURCE, addr, size);
  581. break;
  582. case sec_pdata:
  583. pe_set_datadir(&pe_header, IMAGE_DIRECTORY_ENTRY_EXCEPTION, addr, size);
  584. break;
  585. case sec_stab:
  586. break;
  587. }
  588. if (pe->thunk == pe->s1->sections[si->ord]) {
  589. if (pe->imp_size) {
  590. pe_set_datadir(&pe_header, IMAGE_DIRECTORY_ENTRY_IMPORT,
  591. pe->imp_offs + addr, pe->imp_size);
  592. pe_set_datadir(&pe_header, IMAGE_DIRECTORY_ENTRY_IAT,
  593. pe->iat_offs + addr, pe->iat_size);
  594. }
  595. if (pe->exp_size) {
  596. pe_set_datadir(&pe_header, IMAGE_DIRECTORY_ENTRY_EXPORT,
  597. pe->exp_offs + addr, pe->exp_size);
  598. }
  599. }
  600. strncpy((char*)psh->Name, sh_name, sizeof psh->Name);
  601. psh->Characteristics = pe_sec_flags[si->cls];
  602. psh->VirtualAddress = addr;
  603. psh->Misc.VirtualSize = size;
  604. pe_header.opthdr.SizeOfImage =
  605. umax(pe_virtual_align(pe, size + addr), pe_header.opthdr.SizeOfImage);
  606. if (si->data_size) {
  607. psh->PointerToRawData = file_offset;
  608. file_offset = pe_file_align(pe, file_offset + si->data_size);
  609. psh->SizeOfRawData = file_offset - psh->PointerToRawData;
  610. if (si->cls == sec_text)
  611. pe_header.opthdr.SizeOfCode += psh->SizeOfRawData;
  612. else
  613. pe_header.opthdr.SizeOfInitializedData += psh->SizeOfRawData;
  614. }
  615. }
  616. //pe_header.filehdr.TimeDateStamp = time(NULL);
  617. pe_header.filehdr.NumberOfSections = pe->sec_count;
  618. pe_header.opthdr.AddressOfEntryPoint = pe->start_addr;
  619. pe_header.opthdr.SizeOfHeaders = pe->sizeofheaders;
  620. pe_header.opthdr.ImageBase = pe->imagebase;
  621. pe_header.opthdr.Subsystem = pe->subsystem;
  622. if (pe->s1->pe_stack_size)
  623. pe_header.opthdr.SizeOfStackReserve = pe->s1->pe_stack_size;
  624. if (PE_DLL == pe->type)
  625. pe_header.filehdr.Characteristics = CHARACTERISTICS_DLL;
  626. pe_header.filehdr.Characteristics |= pe->s1->pe_characteristics;
  627. sum = 0;
  628. pe_fwrite(&pe_header, sizeof pe_header, op, &sum);
  629. for (i = 0; i < pe->sec_count; ++i)
  630. pe_fwrite(&pe->sec_info[i].ish, sizeof(IMAGE_SECTION_HEADER), op, &sum);
  631. pe_fpad(op, pe->sizeofheaders);
  632. for (i = 0; i < pe->sec_count; ++i) {
  633. si = pe->sec_info + i;
  634. psh = &si->ish;
  635. if (si->data_size) {
  636. pe_fwrite(si->data, si->data_size, op, &sum);
  637. file_offset = psh->PointerToRawData + psh->SizeOfRawData;
  638. pe_fpad(op, file_offset);
  639. }
  640. }
  641. pe_header.opthdr.CheckSum = sum + file_offset;
  642. fseek(op, offsetof(struct pe_header, opthdr.CheckSum), SEEK_SET);
  643. pe_fwrite(&pe_header.opthdr.CheckSum, sizeof pe_header.opthdr.CheckSum, op, NULL);
  644. fclose (op);
  645. #ifndef _WIN32
  646. chmod(pe->filename, 0777);
  647. #endif
  648. if (2 == pe->s1->verbose)
  649. printf("-------------------------------\n");
  650. if (pe->s1->verbose)
  651. printf("<- %s (%u bytes)\n", pe->filename, (unsigned)file_offset);
  652. return 0;
  653. }
  654. /*----------------------------------------------------------------------------*/
  655. static struct import_symbol *pe_add_import(struct pe_info *pe, int sym_index)
  656. {
  657. int i;
  658. int dll_index;
  659. struct pe_import_info *p;
  660. struct import_symbol *s;
  661. ElfW(Sym) *isym;
  662. isym = (ElfW(Sym) *)pe->s1->dynsymtab_section->data + sym_index;
  663. dll_index = isym->st_size;
  664. i = dynarray_assoc ((void**)pe->imp_info, pe->imp_count, dll_index);
  665. if (-1 != i) {
  666. p = pe->imp_info[i];
  667. goto found_dll;
  668. }
  669. p = tcc_mallocz(sizeof *p);
  670. p->dll_index = dll_index;
  671. dynarray_add(&pe->imp_info, &pe->imp_count, p);
  672. found_dll:
  673. i = dynarray_assoc ((void**)p->symbols, p->sym_count, sym_index);
  674. if (-1 != i)
  675. return p->symbols[i];
  676. s = tcc_mallocz(sizeof *s);
  677. dynarray_add(&p->symbols, &p->sym_count, s);
  678. s->sym_index = sym_index;
  679. return s;
  680. }
  681. void pe_free_imports(struct pe_info *pe)
  682. {
  683. int i;
  684. for (i = 0; i < pe->imp_count; ++i) {
  685. struct pe_import_info *p = pe->imp_info[i];
  686. dynarray_reset(&p->symbols, &p->sym_count);
  687. }
  688. dynarray_reset(&pe->imp_info, &pe->imp_count);
  689. }
  690. /*----------------------------------------------------------------------------*/
  691. static void pe_build_imports(struct pe_info *pe)
  692. {
  693. int thk_ptr, ent_ptr, dll_ptr, sym_cnt, i;
  694. DWORD rva_base = pe->thunk->sh_addr - pe->imagebase;
  695. int ndlls = pe->imp_count;
  696. for (sym_cnt = i = 0; i < ndlls; ++i)
  697. sym_cnt += pe->imp_info[i]->sym_count;
  698. if (0 == sym_cnt)
  699. return;
  700. pe_align_section(pe->thunk, 16);
  701. pe->imp_offs = dll_ptr = pe->thunk->data_offset;
  702. pe->imp_size = (ndlls + 1) * sizeof(IMAGE_IMPORT_DESCRIPTOR);
  703. pe->iat_offs = dll_ptr + pe->imp_size;
  704. pe->iat_size = (sym_cnt + ndlls) * sizeof(ADDR3264);
  705. section_ptr_add(pe->thunk, pe->imp_size + 2*pe->iat_size);
  706. thk_ptr = pe->iat_offs;
  707. ent_ptr = pe->iat_offs + pe->iat_size;
  708. for (i = 0; i < pe->imp_count; ++i) {
  709. IMAGE_IMPORT_DESCRIPTOR *hdr;
  710. int k, n, dllindex;
  711. ADDR3264 v;
  712. struct pe_import_info *p = pe->imp_info[i];
  713. const char *name;
  714. DLLReference *dllref;
  715. dllindex = p->dll_index;
  716. if (dllindex)
  717. name = (dllref = pe->s1->loaded_dlls[dllindex-1])->name;
  718. else
  719. name = "", dllref = NULL;
  720. /* put the dll name into the import header */
  721. v = put_elf_str(pe->thunk, name);
  722. hdr = (IMAGE_IMPORT_DESCRIPTOR*)(pe->thunk->data + dll_ptr);
  723. hdr->FirstThunk = thk_ptr + rva_base;
  724. hdr->OriginalFirstThunk = ent_ptr + rva_base;
  725. hdr->Name = v + rva_base;
  726. for (k = 0, n = p->sym_count; k <= n; ++k) {
  727. if (k < n) {
  728. int iat_index = p->symbols[k]->iat_index;
  729. int sym_index = p->symbols[k]->sym_index;
  730. ElfW(Sym) *imp_sym = (ElfW(Sym) *)pe->s1->dynsymtab_section->data + sym_index;
  731. ElfW(Sym) *org_sym = (ElfW(Sym) *)symtab_section->data + iat_index;
  732. const char *name = (char*)pe->s1->dynsymtab_section->link->data + imp_sym->st_name;
  733. int ordinal;
  734. org_sym->st_value = thk_ptr;
  735. org_sym->st_shndx = pe->thunk->sh_num;
  736. if (dllref)
  737. v = 0, ordinal = imp_sym->st_value; /* ordinal from pe_load_def */
  738. else
  739. ordinal = 0, v = imp_sym->st_value; /* address from tcc_add_symbol() */
  740. #ifdef TCC_IS_NATIVE
  741. if (pe->type == PE_RUN) {
  742. if (dllref) {
  743. if ( !dllref->handle )
  744. dllref->handle = LoadLibrary(dllref->name);
  745. v = (ADDR3264)GetProcAddress(dllref->handle, ordinal?(char*)0+ordinal:name);
  746. }
  747. if (!v)
  748. tcc_error_noabort("can't build symbol '%s'", name);
  749. } else
  750. #endif
  751. if (ordinal) {
  752. v = ordinal | (ADDR3264)1 << (sizeof(ADDR3264)*8 - 1);
  753. } else {
  754. v = pe->thunk->data_offset + rva_base;
  755. section_ptr_add(pe->thunk, sizeof(WORD)); /* hint, not used */
  756. put_elf_str(pe->thunk, name);
  757. }
  758. } else {
  759. v = 0; /* last entry is zero */
  760. }
  761. *(ADDR3264*)(pe->thunk->data+thk_ptr) =
  762. *(ADDR3264*)(pe->thunk->data+ent_ptr) = v;
  763. thk_ptr += sizeof (ADDR3264);
  764. ent_ptr += sizeof (ADDR3264);
  765. }
  766. dll_ptr += sizeof(IMAGE_IMPORT_DESCRIPTOR);
  767. }
  768. }
  769. /* ------------------------------------------------------------- */
  770. struct pe_sort_sym
  771. {
  772. int index;
  773. const char *name;
  774. };
  775. static int sym_cmp(const void *va, const void *vb)
  776. {
  777. const char *ca = (*(struct pe_sort_sym**)va)->name;
  778. const char *cb = (*(struct pe_sort_sym**)vb)->name;
  779. return strcmp(ca, cb);
  780. }
  781. static void pe_build_exports(struct pe_info *pe)
  782. {
  783. ElfW(Sym) *sym;
  784. int sym_index, sym_end;
  785. DWORD rva_base, func_o, name_o, ord_o, str_o;
  786. IMAGE_EXPORT_DIRECTORY *hdr;
  787. int sym_count, ord;
  788. struct pe_sort_sym **sorted, *p;
  789. FILE *op;
  790. char buf[260];
  791. const char *dllname;
  792. const char *name;
  793. rva_base = pe->thunk->sh_addr - pe->imagebase;
  794. sym_count = 0, sorted = NULL, op = NULL;
  795. sym_end = symtab_section->data_offset / sizeof(ElfW(Sym));
  796. for (sym_index = 1; sym_index < sym_end; ++sym_index) {
  797. sym = (ElfW(Sym)*)symtab_section->data + sym_index;
  798. name = pe_export_name(pe->s1, sym);
  799. if ((sym->st_other & ST_PE_EXPORT)
  800. /* export only symbols from actually written sections */
  801. && pe->s1->sections[sym->st_shndx]->sh_addr) {
  802. p = tcc_malloc(sizeof *p);
  803. p->index = sym_index;
  804. p->name = name;
  805. dynarray_add(&sorted, &sym_count, p);
  806. }
  807. #if 0
  808. if (sym->st_other & ST_PE_EXPORT)
  809. printf("export: %s\n", name);
  810. if (sym->st_other & ST_PE_STDCALL)
  811. printf("stdcall: %s\n", name);
  812. #endif
  813. }
  814. if (0 == sym_count)
  815. return;
  816. qsort (sorted, sym_count, sizeof *sorted, sym_cmp);
  817. pe_align_section(pe->thunk, 16);
  818. dllname = tcc_basename(pe->filename);
  819. pe->exp_offs = pe->thunk->data_offset;
  820. func_o = pe->exp_offs + sizeof(IMAGE_EXPORT_DIRECTORY);
  821. name_o = func_o + sym_count * sizeof (DWORD);
  822. ord_o = name_o + sym_count * sizeof (DWORD);
  823. str_o = ord_o + sym_count * sizeof(WORD);
  824. hdr = section_ptr_add(pe->thunk, str_o - pe->exp_offs);
  825. hdr->Characteristics = 0;
  826. hdr->Base = 1;
  827. hdr->NumberOfFunctions = sym_count;
  828. hdr->NumberOfNames = sym_count;
  829. hdr->AddressOfFunctions = func_o + rva_base;
  830. hdr->AddressOfNames = name_o + rva_base;
  831. hdr->AddressOfNameOrdinals = ord_o + rva_base;
  832. hdr->Name = str_o + rva_base;
  833. put_elf_str(pe->thunk, dllname);
  834. #if 1
  835. /* automatically write exports to <output-filename>.def */
  836. pstrcpy(buf, sizeof buf, pe->filename);
  837. strcpy(tcc_fileextension(buf), ".def");
  838. op = fopen(buf, "w");
  839. if (NULL == op) {
  840. tcc_error_noabort("could not create '%s': %s", buf, strerror(errno));
  841. } else {
  842. fprintf(op, "LIBRARY %s\n\nEXPORTS\n", dllname);
  843. if (pe->s1->verbose)
  844. printf("<- %s (%d symbol%s)\n", buf, sym_count, &"s"[sym_count < 2]);
  845. }
  846. #endif
  847. for (ord = 0; ord < sym_count; ++ord)
  848. {
  849. p = sorted[ord], sym_index = p->index, name = p->name;
  850. /* insert actual address later in pe_relocate_rva */
  851. put_elf_reloc(symtab_section, pe->thunk,
  852. func_o, R_XXX_RELATIVE, sym_index);
  853. *(DWORD*)(pe->thunk->data + name_o)
  854. = pe->thunk->data_offset + rva_base;
  855. *(WORD*)(pe->thunk->data + ord_o)
  856. = ord;
  857. put_elf_str(pe->thunk, name);
  858. func_o += sizeof (DWORD);
  859. name_o += sizeof (DWORD);
  860. ord_o += sizeof (WORD);
  861. if (op)
  862. fprintf(op, "%s\n", name);
  863. }
  864. pe->exp_size = pe->thunk->data_offset - pe->exp_offs;
  865. dynarray_reset(&sorted, &sym_count);
  866. if (op)
  867. fclose(op);
  868. }
  869. /* ------------------------------------------------------------- */
  870. static void pe_build_reloc (struct pe_info *pe)
  871. {
  872. DWORD offset, block_ptr, addr;
  873. int count, i;
  874. ElfW_Rel *rel, *rel_end;
  875. Section *s = NULL, *sr;
  876. offset = addr = block_ptr = count = i = 0;
  877. rel = rel_end = NULL;
  878. for(;;) {
  879. if (rel < rel_end) {
  880. int type = ELFW(R_TYPE)(rel->r_info);
  881. addr = rel->r_offset + s->sh_addr;
  882. ++ rel;
  883. if (type != REL_TYPE_DIRECT)
  884. continue;
  885. if (count == 0) { /* new block */
  886. block_ptr = pe->reloc->data_offset;
  887. section_ptr_add(pe->reloc, sizeof(struct pe_reloc_header));
  888. offset = addr & 0xFFFFFFFF<<12;
  889. }
  890. if ((addr -= offset) < (1<<12)) { /* one block spans 4k addresses */
  891. WORD *wp = section_ptr_add(pe->reloc, sizeof (WORD));
  892. *wp = addr | PE_IMAGE_REL<<12;
  893. ++count;
  894. continue;
  895. }
  896. -- rel;
  897. } else if (i < pe->sec_count) {
  898. sr = (s = pe->s1->sections[pe->sec_info[i++].ord])->reloc;
  899. if (sr) {
  900. rel = (ElfW_Rel *)sr->data;
  901. rel_end = (ElfW_Rel *)(sr->data + sr->data_offset);
  902. }
  903. continue;
  904. }
  905. if (count) {
  906. /* store the last block and ready for a new one */
  907. struct pe_reloc_header *hdr;
  908. if (count & 1) /* align for DWORDS */
  909. section_ptr_add(pe->reloc, sizeof(WORD)), ++count;
  910. hdr = (struct pe_reloc_header *)(pe->reloc->data + block_ptr);
  911. hdr -> offset = offset - pe->imagebase;
  912. hdr -> size = count * sizeof(WORD) + sizeof(struct pe_reloc_header);
  913. count = 0;
  914. }
  915. if (rel >= rel_end)
  916. break;
  917. }
  918. }
  919. /* ------------------------------------------------------------- */
  920. static int pe_section_class(Section *s)
  921. {
  922. int type, flags;
  923. const char *name;
  924. type = s->sh_type;
  925. flags = s->sh_flags;
  926. name = s->name;
  927. if (flags & SHF_ALLOC) {
  928. if (type == SHT_PROGBITS) {
  929. if (flags & SHF_EXECINSTR)
  930. return sec_text;
  931. if (flags & SHF_WRITE)
  932. return sec_data;
  933. if (0 == strcmp(name, ".rsrc"))
  934. return sec_rsrc;
  935. if (0 == strcmp(name, ".iedat"))
  936. return sec_idata;
  937. if (0 == strcmp(name, ".pdata"))
  938. return sec_pdata;
  939. return sec_other;
  940. } else if (type == SHT_NOBITS) {
  941. if (flags & SHF_WRITE)
  942. return sec_bss;
  943. }
  944. } else {
  945. if (0 == strcmp(name, ".reloc"))
  946. return sec_reloc;
  947. if (0 == strncmp(name, ".stab", 5)) /* .stab and .stabstr */
  948. return sec_stab;
  949. }
  950. return -1;
  951. }
  952. static int pe_assign_addresses (struct pe_info *pe)
  953. {
  954. int i, k, o, c;
  955. DWORD addr;
  956. int *section_order;
  957. struct section_info *si;
  958. Section *s;
  959. if (PE_DLL == pe->type)
  960. pe->reloc = new_section(pe->s1, ".reloc", SHT_PROGBITS, 0);
  961. // pe->thunk = new_section(pe->s1, ".iedat", SHT_PROGBITS, SHF_ALLOC);
  962. section_order = tcc_malloc(pe->s1->nb_sections * sizeof (int));
  963. for (o = k = 0 ; k < sec_last; ++k) {
  964. for (i = 1; i < pe->s1->nb_sections; ++i) {
  965. s = pe->s1->sections[i];
  966. if (k == pe_section_class(s)) {
  967. // printf("%s %d\n", s->name, k);
  968. s->sh_addr = pe->imagebase;
  969. section_order[o++] = i;
  970. }
  971. }
  972. }
  973. pe->sec_info = tcc_mallocz(o * sizeof (struct section_info));
  974. addr = pe->imagebase + 1;
  975. for (i = 0; i < o; ++i)
  976. {
  977. k = section_order[i];
  978. s = pe->s1->sections[k];
  979. c = pe_section_class(s);
  980. si = &pe->sec_info[pe->sec_count];
  981. #ifdef PE_MERGE_DATA
  982. if (c == sec_bss && pe->sec_count && si[-1].cls == sec_data) {
  983. /* append .bss to .data */
  984. s->sh_addr = addr = ((addr-1) | (s->sh_addralign-1)) + 1;
  985. addr += s->data_offset;
  986. si[-1].sh_size = addr - si[-1].sh_addr;
  987. continue;
  988. }
  989. #endif
  990. if (c == sec_stab && 0 == pe->s1->do_debug)
  991. continue;
  992. strcpy(si->name, s->name);
  993. si->cls = c;
  994. si->ord = k;
  995. si->sh_addr = s->sh_addr = addr = pe_virtual_align(pe, addr);
  996. si->sh_flags = s->sh_flags;
  997. if (c == sec_data && NULL == pe->thunk)
  998. pe->thunk = s;
  999. if (s == pe->thunk) {
  1000. pe_build_imports(pe);
  1001. pe_build_exports(pe);
  1002. }
  1003. if (c == sec_reloc)
  1004. pe_build_reloc (pe);
  1005. if (s->data_offset)
  1006. {
  1007. if (s->sh_type != SHT_NOBITS) {
  1008. si->data = s->data;
  1009. si->data_size = s->data_offset;
  1010. }
  1011. addr += s->data_offset;
  1012. si->sh_size = s->data_offset;
  1013. ++pe->sec_count;
  1014. }
  1015. // printf("%08x %05x %s\n", si->sh_addr, si->sh_size, si->name);
  1016. }
  1017. #if 0
  1018. for (i = 1; i < pe->s1->nb_sections; ++i) {
  1019. Section *s = pe->s1->sections[i];
  1020. int type = s->sh_type;
  1021. int flags = s->sh_flags;
  1022. printf("section %-16s %-10s %5x %s,%s,%s\n",
  1023. s->name,
  1024. type == SHT_PROGBITS ? "progbits" :
  1025. type == SHT_NOBITS ? "nobits" :
  1026. type == SHT_SYMTAB ? "symtab" :
  1027. type == SHT_STRTAB ? "strtab" :
  1028. type == SHT_RELX ? "rel" : "???",
  1029. s->data_offset,
  1030. flags & SHF_ALLOC ? "alloc" : "",
  1031. flags & SHF_WRITE ? "write" : "",
  1032. flags & SHF_EXECINSTR ? "exec" : ""
  1033. );
  1034. }
  1035. pe->s1->verbose = 2;
  1036. #endif
  1037. tcc_free(section_order);
  1038. return 0;
  1039. }
  1040. /* ------------------------------------------------------------- */
  1041. static void pe_relocate_rva (struct pe_info *pe, Section *s)
  1042. {
  1043. Section *sr = s->reloc;
  1044. ElfW_Rel *rel, *rel_end;
  1045. rel_end = (ElfW_Rel *)(sr->data + sr->data_offset);
  1046. for(rel = (ElfW_Rel *)sr->data; rel < rel_end; rel++) {
  1047. if (ELFW(R_TYPE)(rel->r_info) == R_XXX_RELATIVE) {
  1048. int sym_index = ELFW(R_SYM)(rel->r_info);
  1049. DWORD addr = s->sh_addr;
  1050. if (sym_index) {
  1051. ElfW(Sym) *sym = (ElfW(Sym) *)symtab_section->data + sym_index;
  1052. addr = sym->st_value;
  1053. }
  1054. // printf("reloc rva %08x %08x %s\n", (DWORD)rel->r_offset, addr, s->name);
  1055. *(DWORD*)(s->data + rel->r_offset) += addr - pe->imagebase;
  1056. }
  1057. }
  1058. }
  1059. /*----------------------------------------------------------------------------*/
  1060. static int pe_isafunc(int sym_index)
  1061. {
  1062. Section *sr = text_section->reloc;
  1063. ElfW_Rel *rel, *rel_end;
  1064. Elf32_Word info = ELF32_R_INFO(sym_index, R_386_PC32);
  1065. if (!sr)
  1066. return 0;
  1067. rel_end = (ElfW_Rel *)(sr->data + sr->data_offset);
  1068. for (rel = (ElfW_Rel *)sr->data; rel < rel_end; rel++)
  1069. if (rel->r_info == info)
  1070. return 1;
  1071. return 0;
  1072. }
  1073. /*----------------------------------------------------------------------------*/
  1074. static int pe_check_symbols(struct pe_info *pe)
  1075. {
  1076. ElfW(Sym) *sym;
  1077. int sym_index, sym_end;
  1078. int ret = 0;
  1079. pe_align_section(text_section, 8);
  1080. sym_end = symtab_section->data_offset / sizeof(ElfW(Sym));
  1081. for (sym_index = 1; sym_index < sym_end; ++sym_index) {
  1082. sym = (ElfW(Sym) *)symtab_section->data + sym_index;
  1083. if (sym->st_shndx == SHN_UNDEF) {
  1084. const char *name = (char*)symtab_section->link->data + sym->st_name;
  1085. unsigned type = ELFW(ST_TYPE)(sym->st_info);
  1086. int imp_sym = pe_find_import(pe->s1, sym);
  1087. struct import_symbol *is;
  1088. if (imp_sym <= 0)
  1089. goto not_found;
  1090. if (type == STT_NOTYPE) {
  1091. /* symbols from assembler have no type, find out which */
  1092. if (pe_isafunc(sym_index))
  1093. type = STT_FUNC;
  1094. else
  1095. type = STT_OBJECT;
  1096. }
  1097. is = pe_add_import(pe, imp_sym);
  1098. if (type == STT_FUNC) {
  1099. unsigned long offset = is->thk_offset;
  1100. if (offset) {
  1101. /* got aliased symbol, like stricmp and _stricmp */
  1102. } else {
  1103. char buffer[100];
  1104. WORD *p;
  1105. offset = text_section->data_offset;
  1106. /* add the 'jmp IAT[x]' instruction */
  1107. #ifdef TCC_TARGET_ARM
  1108. p = section_ptr_add(text_section, 8+4); // room for code and address
  1109. (*(DWORD*)(p)) = 0xE59FC000; // arm code ldr ip, [pc] ; PC+8+0 = 0001xxxx
  1110. (*(DWORD*)(p+2)) = 0xE59CF000; // arm code ldr pc, [ip]
  1111. #else
  1112. p = section_ptr_add(text_section, 8);
  1113. *p = 0x25FF;
  1114. #ifdef TCC_TARGET_X86_64
  1115. *(DWORD*)(p+1) = (DWORD)-4;
  1116. #endif
  1117. #endif
  1118. /* add a helper symbol, will be patched later in
  1119. pe_build_imports */
  1120. sprintf(buffer, "IAT.%s", name);
  1121. is->iat_index = put_elf_sym(
  1122. symtab_section, 0, sizeof(DWORD),
  1123. ELFW(ST_INFO)(STB_GLOBAL, STT_OBJECT),
  1124. 0, SHN_UNDEF, buffer);
  1125. #ifdef TCC_TARGET_ARM
  1126. put_elf_reloc(symtab_section, text_section,
  1127. offset + 8, R_XXX_THUNKFIX, is->iat_index); // offset to IAT position
  1128. #else
  1129. put_elf_reloc(symtab_section, text_section,
  1130. offset + 2, R_XXX_THUNKFIX, is->iat_index);
  1131. #endif
  1132. is->thk_offset = offset;
  1133. }
  1134. /* tcc_realloc might have altered sym's address */
  1135. sym = (ElfW(Sym) *)symtab_section->data + sym_index;
  1136. /* patch the original symbol */
  1137. sym->st_value = offset;
  1138. sym->st_shndx = text_section->sh_num;
  1139. sym->st_other &= ~ST_PE_EXPORT; /* do not export */
  1140. continue;
  1141. }
  1142. if (type == STT_OBJECT) { /* data, ptr to that should be */
  1143. if (0 == is->iat_index) {
  1144. /* original symbol will be patched later in pe_build_imports */
  1145. is->iat_index = sym_index;
  1146. continue;
  1147. }
  1148. }
  1149. not_found:
  1150. if (ELFW(ST_BIND)(sym->st_info) == STB_WEAK)
  1151. /* STB_WEAK undefined symbols are accepted */
  1152. continue;
  1153. tcc_error_noabort("undefined symbol '%s'%s", name,
  1154. imp_sym < 0 ? ", missing __declspec(dllimport)?":"");
  1155. ret = -1;
  1156. } else if (pe->s1->rdynamic
  1157. && ELFW(ST_BIND)(sym->st_info) != STB_LOCAL) {
  1158. /* if -rdynamic option, then export all non local symbols */
  1159. sym->st_other |= ST_PE_EXPORT;
  1160. }
  1161. }
  1162. return ret;
  1163. }
  1164. /*----------------------------------------------------------------------------*/
  1165. #ifdef PE_PRINT_SECTIONS
  1166. static void pe_print_section(FILE * f, Section * s)
  1167. {
  1168. /* just if you're curious */
  1169. BYTE *p, *e, b;
  1170. int i, n, l, m;
  1171. p = s->data;
  1172. e = s->data + s->data_offset;
  1173. l = e - p;
  1174. fprintf(f, "section \"%s\"", s->name);
  1175. if (s->link)
  1176. fprintf(f, "\nlink \"%s\"", s->link->name);
  1177. if (s->reloc)
  1178. fprintf(f, "\nreloc \"%s\"", s->reloc->name);
  1179. fprintf(f, "\nv_addr %08X", (unsigned)s->sh_addr);
  1180. fprintf(f, "\ncontents %08X", (unsigned)l);
  1181. fprintf(f, "\n\n");
  1182. if (s->sh_type == SHT_NOBITS)
  1183. return;
  1184. if (0 == l)
  1185. return;
  1186. if (s->sh_type == SHT_SYMTAB)
  1187. m = sizeof(ElfW(Sym));
  1188. else if (s->sh_type == SHT_RELX)
  1189. m = sizeof(ElfW_Rel);
  1190. else
  1191. m = 16;
  1192. fprintf(f, "%-8s", "offset");
  1193. for (i = 0; i < m; ++i)
  1194. fprintf(f, " %02x", i);
  1195. n = 56;
  1196. if (s->sh_type == SHT_SYMTAB || s->sh_type == SHT_RELX) {
  1197. const char *fields1[] = {
  1198. "name",
  1199. "value",
  1200. "size",
  1201. "bind",
  1202. "type",
  1203. "other",
  1204. "shndx",
  1205. NULL
  1206. };
  1207. const char *fields2[] = {
  1208. "offs",
  1209. "type",
  1210. "symb",
  1211. NULL
  1212. };
  1213. const char **p;
  1214. if (s->sh_type == SHT_SYMTAB)
  1215. p = fields1, n = 106;
  1216. else
  1217. p = fields2, n = 58;
  1218. for (i = 0; p[i]; ++i)
  1219. fprintf(f, "%6s", p[i]);
  1220. fprintf(f, " symbol");
  1221. }
  1222. fprintf(f, "\n");
  1223. for (i = 0; i < n; ++i)
  1224. fprintf(f, "-");
  1225. fprintf(f, "\n");
  1226. for (i = 0; i < l;)
  1227. {
  1228. fprintf(f, "%08X", i);
  1229. for (n = 0; n < m; ++n) {
  1230. if (n + i < l)
  1231. fprintf(f, " %02X", p[i + n]);
  1232. else
  1233. fprintf(f, " ");
  1234. }
  1235. if (s->sh_type == SHT_SYMTAB) {
  1236. ElfW(Sym) *sym = (ElfW(Sym) *) (p + i);
  1237. const char *name = s->link->data + sym->st_name;
  1238. fprintf(f, " %04X %04X %04X %02X %02X %02X %04X \"%s\"",
  1239. (unsigned)sym->st_name,
  1240. (unsigned)sym->st_value,
  1241. (unsigned)sym->st_size,
  1242. (unsigned)ELFW(ST_BIND)(sym->st_info),
  1243. (unsigned)ELFW(ST_TYPE)(sym->st_info),
  1244. (unsigned)sym->st_other,
  1245. (unsigned)sym->st_shndx,
  1246. name);
  1247. } else if (s->sh_type == SHT_RELX) {
  1248. ElfW_Rel *rel = (ElfW_Rel *) (p + i);
  1249. ElfW(Sym) *sym =
  1250. (ElfW(Sym) *) s->link->data + ELFW(R_SYM)(rel->r_info);
  1251. const char *name = s->link->link->data + sym->st_name;
  1252. fprintf(f, " %04X %02X %04X \"%s\"",
  1253. (unsigned)rel->r_offset,
  1254. (unsigned)ELFW(R_TYPE)(rel->r_info),
  1255. (unsigned)ELFW(R_SYM)(rel->r_info),
  1256. name);
  1257. } else {
  1258. fprintf(f, " ");
  1259. for (n = 0; n < m; ++n) {
  1260. if (n + i < l) {
  1261. b = p[i + n];
  1262. if (b < 32 || b >= 127)
  1263. b = '.';
  1264. fprintf(f, "%c", b);
  1265. }
  1266. }
  1267. }
  1268. i += m;
  1269. fprintf(f, "\n");
  1270. }
  1271. fprintf(f, "\n\n");
  1272. }
  1273. static void pe_print_sections(TCCState *s1, const char *fname)
  1274. {
  1275. Section *s;
  1276. FILE *f;
  1277. int i;
  1278. f = fopen(fname, "w");
  1279. for (i = 1; i < s1->nb_sections; ++i) {
  1280. s = s1->sections[i];
  1281. pe_print_section(f, s);
  1282. }
  1283. pe_print_section(f, s1->dynsymtab_section);
  1284. fclose(f);
  1285. }
  1286. #endif
  1287. /* ------------------------------------------------------------- */
  1288. /* helper function for load/store to insert one more indirection */
  1289. #if defined TCC_TARGET_I386 || defined TCC_TARGET_X86_64
  1290. ST_FUNC SValue *pe_getimport(SValue *sv, SValue *v2)
  1291. {
  1292. int r2;
  1293. if ((sv->r & (VT_VALMASK|VT_SYM)) != (VT_CONST|VT_SYM) || (sv->r2 != VT_CONST))
  1294. return sv;
  1295. if (!sv->sym->a.dllimport)
  1296. return sv;
  1297. // printf("import %04x %04x %04x %s\n", sv->type.t, sv->sym->type.t, sv->r, get_tok_str(sv->sym->v, NULL));
  1298. memset(v2, 0, sizeof *v2);
  1299. v2->type.t = VT_PTR;
  1300. v2->r = VT_CONST | VT_SYM | VT_LVAL;
  1301. v2->sym = sv->sym;
  1302. r2 = get_reg(RC_INT);
  1303. load(r2, v2);
  1304. v2->r = r2;
  1305. if ((uint32_t)sv->c.i) {
  1306. vpushv(v2);
  1307. vpushi(sv->c.i);
  1308. gen_opi('+');
  1309. *v2 = *vtop--;
  1310. }
  1311. v2->type.t = sv->type.t;
  1312. v2->r |= sv->r & VT_LVAL;
  1313. return v2;
  1314. }
  1315. #endif
  1316. ST_FUNC int pe_putimport(TCCState *s1, int dllindex, const char *name, addr_t value)
  1317. {
  1318. return set_elf_sym(
  1319. s1->dynsymtab_section,
  1320. value,
  1321. dllindex, /* st_size */
  1322. ELFW(ST_INFO)(STB_GLOBAL, STT_NOTYPE),
  1323. 0,
  1324. value ? SHN_ABS : SHN_UNDEF,
  1325. name
  1326. );
  1327. }
  1328. static int add_dllref(TCCState *s1, const char *dllname)
  1329. {
  1330. DLLReference *dllref;
  1331. int i;
  1332. for (i = 0; i < s1->nb_loaded_dlls; ++i)
  1333. if (0 == strcmp(s1->loaded_dlls[i]->name, dllname))
  1334. return i + 1;
  1335. dllref = tcc_mallocz(sizeof(DLLReference) + strlen(dllname));
  1336. strcpy(dllref->name, dllname);
  1337. dynarray_add(&s1->loaded_dlls, &s1->nb_loaded_dlls, dllref);
  1338. return s1->nb_loaded_dlls;
  1339. }
  1340. /* ------------------------------------------------------------- */
  1341. static int read_mem(int fd, unsigned offset, void *buffer, unsigned len)
  1342. {
  1343. lseek(fd, offset, SEEK_SET);
  1344. return len == read(fd, buffer, len);
  1345. }
  1346. /* ------------------------------------------------------------- */
  1347. PUB_FUNC int tcc_get_dllexports(const char *filename, char **pp)
  1348. {
  1349. int l, i, n, n0, ret;
  1350. char *p;
  1351. int fd;
  1352. IMAGE_SECTION_HEADER ish;
  1353. IMAGE_EXPORT_DIRECTORY ied;
  1354. IMAGE_DOS_HEADER dh;
  1355. IMAGE_FILE_HEADER ih;
  1356. DWORD sig, ref, addr, ptr, namep;
  1357. int pef_hdroffset, opt_hdroffset, sec_hdroffset;
  1358. n = n0 = 0;
  1359. p = NULL;
  1360. ret = -1;
  1361. fd = open(filename, O_RDONLY | O_BINARY);
  1362. if (fd < 0)
  1363. goto the_end_1;
  1364. ret = 1;
  1365. if (!read_mem(fd, 0, &dh, sizeof dh))
  1366. goto the_end;
  1367. if (!read_mem(fd, dh.e_lfanew, &sig, sizeof sig))
  1368. goto the_end;
  1369. if (sig != 0x00004550)
  1370. goto the_end;
  1371. pef_hdroffset = dh.e_lfanew + sizeof sig;
  1372. if (!read_mem(fd, pef_hdroffset, &ih, sizeof ih))
  1373. goto the_end;
  1374. opt_hdroffset = pef_hdroffset + sizeof ih;
  1375. if (ih.Machine == 0x014C) {
  1376. IMAGE_OPTIONAL_HEADER32 oh;
  1377. sec_hdroffset = opt_hdroffset + sizeof oh;
  1378. if (!read_mem(fd, opt_hdroffset, &oh, sizeof oh))
  1379. goto the_end;
  1380. if (IMAGE_DIRECTORY_ENTRY_EXPORT >= oh.NumberOfRvaAndSizes)
  1381. goto the_end_0;
  1382. addr = oh.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress;
  1383. } else if (ih.Machine == 0x8664) {
  1384. IMAGE_OPTIONAL_HEADER64 oh;
  1385. sec_hdroffset = opt_hdroffset + sizeof oh;
  1386. if (!read_mem(fd, opt_hdroffset, &oh, sizeof oh))
  1387. goto the_end;
  1388. if (IMAGE_DIRECTORY_ENTRY_EXPORT >= oh.NumberOfRvaAndSizes)
  1389. goto the_end_0;
  1390. addr = oh.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress;
  1391. } else
  1392. goto the_end;
  1393. //printf("addr: %08x\n", addr);
  1394. for (i = 0; i < ih.NumberOfSections; ++i) {
  1395. if (!read_mem(fd, sec_hdroffset + i * sizeof ish, &ish, sizeof ish))
  1396. goto the_end;
  1397. //printf("vaddr: %08x\n", ish.VirtualAddress);
  1398. if (addr >= ish.VirtualAddress && addr < ish.VirtualAddress + ish.SizeOfRawData)
  1399. goto found;
  1400. }
  1401. goto the_end_0;
  1402. found:
  1403. ref = ish.VirtualAddress - ish.PointerToRawData;
  1404. if (!read_mem(fd, addr - ref, &ied, sizeof ied))
  1405. goto the_end;
  1406. namep = ied.AddressOfNames - ref;
  1407. for (i = 0; i < ied.NumberOfNames; ++i) {
  1408. if (!read_mem(fd, namep, &ptr, sizeof ptr))
  1409. goto the_end;
  1410. namep += sizeof ptr;
  1411. for (l = 0;;) {
  1412. if (n+1 >= n0)
  1413. p = tcc_realloc(p, n0 = n0 ? n0 * 2 : 256);
  1414. if (!read_mem(fd, ptr - ref + l++, p + n, 1)) {
  1415. tcc_free(p), p = NULL;
  1416. goto the_end;
  1417. }
  1418. if (p[n++] == 0)
  1419. break;
  1420. }
  1421. }
  1422. if (p)
  1423. p[n] = 0;
  1424. the_end_0:
  1425. ret = 0;
  1426. the_end:
  1427. close(fd);
  1428. the_end_1:
  1429. *pp = p;
  1430. return ret;
  1431. }
  1432. /* -------------------------------------------------------------
  1433. * This is for compiled windows resources in 'coff' format
  1434. * as generated by 'windres.exe -O coff ...'.
  1435. */
  1436. static int pe_load_res(TCCState *s1, int fd)
  1437. {
  1438. struct pe_rsrc_header hdr;
  1439. Section *rsrc_section;
  1440. int i, ret = -1;
  1441. BYTE *ptr;
  1442. unsigned offs;
  1443. if (!read_mem(fd, 0, &hdr, sizeof hdr))
  1444. goto quit;
  1445. if (hdr.filehdr.Machine != IMAGE_FILE_MACHINE
  1446. || hdr.filehdr.NumberOfSections != 1
  1447. || strcmp((char*)hdr.sectionhdr.Name, ".rsrc") != 0)
  1448. goto quit;
  1449. rsrc_section = new_section(s1, ".rsrc", SHT_PROGBITS, SHF_ALLOC);
  1450. ptr = section_ptr_add(rsrc_section, hdr.sectionhdr.SizeOfRawData);
  1451. offs = hdr.sectionhdr.PointerToRawData;
  1452. if (!read_mem(fd, offs, ptr, hdr.sectionhdr.SizeOfRawData))
  1453. goto quit;
  1454. offs = hdr.sectionhdr.PointerToRelocations;
  1455. for (i = 0; i < hdr.sectionhdr.NumberOfRelocations; ++i)
  1456. {
  1457. struct pe_rsrc_reloc rel;
  1458. if (!read_mem(fd, offs, &rel, sizeof rel))
  1459. goto quit;
  1460. // printf("rsrc_reloc: %x %x %x\n", rel.offset, rel.size, rel.type);
  1461. if (rel.type != RSRC_RELTYPE)
  1462. goto quit;
  1463. put_elf_reloc(symtab_section, rsrc_section,
  1464. rel.offset, R_XXX_RELATIVE, 0);
  1465. offs += sizeof rel;
  1466. }
  1467. ret = 0;
  1468. quit:
  1469. return ret;
  1470. }
  1471. /* ------------------------------------------------------------- */
  1472. static char *trimfront(char *p)
  1473. {
  1474. while (*p && (unsigned char)*p <= ' ')
  1475. ++p;
  1476. return p;
  1477. }
  1478. static char *trimback(char *a, char *e)
  1479. {
  1480. while (e > a && (unsigned char)e[-1] <= ' ')
  1481. --e;
  1482. *e = 0;;
  1483. return a;
  1484. }
  1485. /* ------------------------------------------------------------- */
  1486. static int pe_load_def(TCCState *s1, int fd)
  1487. {
  1488. int state = 0, ret = -1, dllindex = 0, ord;
  1489. char line[400], dllname[80], *p, *x;
  1490. FILE *fp;
  1491. fp = fdopen(dup(fd), "rb");
  1492. while (fgets(line, sizeof line, fp))
  1493. {
  1494. p = trimfront(trimback(line, strchr(line, 0)));
  1495. if (0 == *p || ';' == *p)
  1496. continue;
  1497. switch (state) {
  1498. case 0:
  1499. if (0 != strnicmp(p, "LIBRARY", 7))
  1500. goto quit;
  1501. pstrcpy(dllname, sizeof dllname, trimfront(p+7));
  1502. ++state;
  1503. continue;
  1504. case 1:
  1505. if (0 != stricmp(p, "EXPORTS"))
  1506. goto quit;
  1507. ++state;
  1508. continue;
  1509. case 2:
  1510. dllindex = add_dllref(s1, dllname);
  1511. ++state;
  1512. /* fall through */
  1513. default:
  1514. /* get ordinal and will store in sym->st_value */
  1515. ord = 0;
  1516. x = strchr(p, ' ');
  1517. if (x) {
  1518. *x = 0, x = strrchr(x + 1, '@');
  1519. if (x) {
  1520. char *d;
  1521. ord = (int)strtol(x + 1, &d, 10);
  1522. if (*d)
  1523. ord = 0;
  1524. }
  1525. }
  1526. pe_putimport(s1, dllindex, p, ord);
  1527. continue;
  1528. }
  1529. }
  1530. ret = 0;
  1531. quit:
  1532. fclose(fp);
  1533. return ret;
  1534. }
  1535. /* ------------------------------------------------------------- */
  1536. static int pe_load_dll(TCCState *s1, const char *filename)
  1537. {
  1538. char *p, *q;
  1539. int index, ret;
  1540. ret = tcc_get_dllexports(filename, &p);
  1541. if (ret) {
  1542. return -1;
  1543. } else if (p) {
  1544. index = add_dllref(s1, tcc_basename(filename));
  1545. for (q = p; *q; q += 1 + strlen(q))
  1546. pe_putimport(s1, index, q, 0);
  1547. tcc_free(p);
  1548. }
  1549. return 0;
  1550. }
  1551. /* ------------------------------------------------------------- */
  1552. ST_FUNC int pe_load_file(struct TCCState *s1, const char *filename, int fd)
  1553. {
  1554. int ret = -1;
  1555. char buf[10];
  1556. if (0 == strcmp(tcc_fileextension(filename), ".def"))
  1557. ret = pe_load_def(s1, fd);
  1558. else if (pe_load_res(s1, fd) == 0)
  1559. ret = 0;
  1560. else if (read_mem(fd, 0, buf, 4) && 0 == memcmp(buf, "MZ\220", 4))
  1561. ret = pe_load_dll(s1, filename);
  1562. return ret;
  1563. }
  1564. /* ------------------------------------------------------------- */
  1565. #ifdef TCC_TARGET_X86_64
  1566. static unsigned pe_add_uwwind_info(TCCState *s1)
  1567. {
  1568. if (NULL == s1->uw_pdata) {
  1569. s1->uw_pdata = find_section(tcc_state, ".pdata");
  1570. s1->uw_pdata->sh_addralign = 4;
  1571. s1->uw_sym = put_elf_sym(symtab_section, 0, 0, 0, 0, text_section->sh_num, NULL);
  1572. }
  1573. if (0 == s1->uw_offs) {
  1574. /* As our functions all have the same stackframe, we use one entry for all */
  1575. static const unsigned char uw_info[] = {
  1576. 0x01, // UBYTE: 3 Version , UBYTE: 5 Flags
  1577. 0x04, // UBYTE Size of prolog
  1578. 0x02, // UBYTE Count of unwind codes
  1579. 0x05, // UBYTE: 4 Frame Register (rbp), UBYTE: 4 Frame Register offset (scaled)
  1580. // USHORT * n Unwind codes array
  1581. // 0x0b, 0x01, 0xff, 0xff, // stack size
  1582. 0x04, 0x03, // set frame ptr (mov rsp -> rbp)
  1583. 0x01, 0x50 // push reg (rbp)
  1584. };
  1585. Section *s = text_section;
  1586. unsigned char *p;
  1587. section_ptr_add(s, -s->data_offset & 3); /* align */
  1588. s1->uw_offs = s->data_offset;
  1589. p = section_ptr_add(s, sizeof uw_info);
  1590. memcpy(p, uw_info, sizeof uw_info);
  1591. }
  1592. return s1->uw_offs;
  1593. }
  1594. ST_FUNC void pe_add_unwind_data(unsigned start, unsigned end, unsigned stack)
  1595. {
  1596. TCCState *s1 = tcc_state;
  1597. Section *pd;
  1598. unsigned o, n, d;
  1599. struct /* _RUNTIME_FUNCTION */ {
  1600. DWORD BeginAddress;
  1601. DWORD EndAddress;
  1602. DWORD UnwindData;
  1603. } *p;
  1604. d = pe_add_uwwind_info(s1);
  1605. pd = s1->uw_pdata;
  1606. o = pd->data_offset;
  1607. p = section_ptr_add(pd, sizeof *p);
  1608. /* record this function */
  1609. p->BeginAddress = start;
  1610. p->EndAddress = end;
  1611. p->UnwindData = d;
  1612. /* put relocations on it */
  1613. for (n = o + sizeof *p; o < n; o += sizeof p->BeginAddress)
  1614. put_elf_reloc(symtab_section, pd, o, R_X86_64_RELATIVE, s1->uw_sym);
  1615. }
  1616. #endif
  1617. /* ------------------------------------------------------------- */
  1618. #ifdef TCC_TARGET_X86_64
  1619. #define PE_STDSYM(n,s) n
  1620. #else
  1621. #define PE_STDSYM(n,s) "_" n s
  1622. #endif
  1623. static void pe_add_runtime(TCCState *s1, struct pe_info *pe)
  1624. {
  1625. const char *start_symbol;
  1626. int pe_type = 0;
  1627. int unicode_entry = 0;
  1628. if (find_elf_sym(symtab_section, PE_STDSYM("WinMain","@16")))
  1629. pe_type = PE_GUI;
  1630. else
  1631. if (find_elf_sym(symtab_section, PE_STDSYM("wWinMain","@16"))) {
  1632. pe_type = PE_GUI;
  1633. unicode_entry = PE_GUI;
  1634. }
  1635. else
  1636. if (TCC_OUTPUT_DLL == s1->output_type) {
  1637. pe_type = PE_DLL;
  1638. /* need this for 'tccelf.c:relocate_section()' */
  1639. s1->output_type = TCC_OUTPUT_EXE;
  1640. }
  1641. else {
  1642. pe_type = PE_EXE;
  1643. if (find_elf_sym(symtab_section, "wmain"))
  1644. unicode_entry = PE_EXE;
  1645. }
  1646. start_symbol =
  1647. TCC_OUTPUT_MEMORY == s1->output_type
  1648. ? PE_GUI == pe_type ? (unicode_entry ? "__runwwinmain" : "__runwinmain")
  1649. : (unicode_entry ? "__runwmain" : "__runmain")
  1650. : PE_DLL == pe_type ? PE_STDSYM("__dllstart","@12")
  1651. : PE_GUI == pe_type ? (unicode_entry ? "__wwinstart": "__winstart")
  1652. : (unicode_entry ? "__wstart" : "__start")
  1653. ;
  1654. if (!s1->leading_underscore || strchr(start_symbol, '@'))
  1655. ++start_symbol;
  1656. /* grab the startup code from libtcc1 */
  1657. #ifdef TCC_IS_NATIVE
  1658. if (TCC_OUTPUT_MEMORY != s1->output_type || s1->runtime_main)
  1659. #endif
  1660. set_elf_sym(symtab_section,
  1661. 0, 0,
  1662. ELFW(ST_INFO)(STB_GLOBAL, STT_NOTYPE), 0,
  1663. SHN_UNDEF, start_symbol);
  1664. tcc_add_pragma_libs(s1);
  1665. if (0 == s1->nostdlib) {
  1666. static const char *libs[] = {
  1667. TCC_LIBTCC1, "msvcrt", "kernel32", "", "user32", "gdi32", NULL
  1668. };
  1669. const char **pp, *p;
  1670. for (pp = libs; 0 != (p = *pp); ++pp) {
  1671. if (0 == *p) {
  1672. if (PE_DLL != pe_type && PE_GUI != pe_type)
  1673. break;
  1674. } else if (pp == libs && tcc_add_dll(s1, p, 0) >= 0) {
  1675. continue;
  1676. } else {
  1677. tcc_add_library_err(s1, p);
  1678. }
  1679. }
  1680. }
  1681. if (TCC_OUTPUT_MEMORY == s1->output_type)
  1682. pe_type = PE_RUN;
  1683. pe->type = pe_type;
  1684. pe->start_symbol = start_symbol;
  1685. }
  1686. static void pe_set_options(TCCState * s1, struct pe_info *pe)
  1687. {
  1688. if (PE_DLL == pe->type) {
  1689. /* XXX: check if is correct for arm-pe target */
  1690. pe->imagebase = 0x10000000;
  1691. } else {
  1692. #if defined(TCC_TARGET_ARM)
  1693. pe->imagebase = 0x00010000;
  1694. #else
  1695. pe->imagebase = 0x00400000;
  1696. #endif
  1697. }
  1698. #if defined(TCC_TARGET_ARM)
  1699. /* we use "console" subsystem by default */
  1700. pe->subsystem = 9;
  1701. #else
  1702. if (PE_DLL == pe->type || PE_GUI == pe->type)
  1703. pe->subsystem = 2;
  1704. else
  1705. pe->subsystem = 3;
  1706. #endif
  1707. /* Allow override via -Wl,-subsystem=... option */
  1708. if (s1->pe_subsystem != 0)
  1709. pe->subsystem = s1->pe_subsystem;
  1710. /* set default file/section alignment */
  1711. if (pe->subsystem == 1) {
  1712. pe->section_align = 0x20;
  1713. pe->file_align = 0x20;
  1714. } else {
  1715. pe->section_align = 0x1000;
  1716. pe->file_align = 0x200;
  1717. }
  1718. if (s1->section_align != 0)
  1719. pe->section_align = s1->section_align;
  1720. if (s1->pe_file_align != 0)
  1721. pe->file_align = s1->pe_file_align;
  1722. if ((pe->subsystem >= 10) && (pe->subsystem <= 12))
  1723. pe->imagebase = 0;
  1724. if (s1->has_text_addr)
  1725. pe->imagebase = s1->text_addr;
  1726. }
  1727. ST_FUNC int pe_output_file(TCCState *s1, const char *filename)
  1728. {
  1729. int ret;
  1730. struct pe_info pe;
  1731. int i;
  1732. memset(&pe, 0, sizeof pe);
  1733. pe.filename = filename;
  1734. pe.s1 = s1;
  1735. tcc_add_bcheck(s1);
  1736. pe_add_runtime(s1, &pe);
  1737. relocate_common_syms(); /* assign bss addresses */
  1738. tcc_add_linker_symbols(s1);
  1739. pe_set_options(s1, &pe);
  1740. ret = pe_check_symbols(&pe);
  1741. if (ret)
  1742. ;
  1743. else if (filename) {
  1744. pe_assign_addresses(&pe);
  1745. relocate_syms(s1, s1->symtab, 0);
  1746. for (i = 1; i < s1->nb_sections; ++i) {
  1747. Section *s = s1->sections[i];
  1748. if (s->reloc) {
  1749. relocate_section(s1, s);
  1750. pe_relocate_rva(&pe, s);
  1751. }
  1752. }
  1753. pe.start_addr = (DWORD)
  1754. ((uintptr_t)tcc_get_symbol_err(s1, pe.start_symbol)
  1755. - pe.imagebase);
  1756. if (s1->nb_errors)
  1757. ret = -1;
  1758. else
  1759. ret = pe_write(&pe);
  1760. tcc_free(pe.sec_info);
  1761. } else {
  1762. #ifdef TCC_IS_NATIVE
  1763. pe.thunk = data_section;
  1764. pe_build_imports(&pe);
  1765. s1->runtime_main = pe.start_symbol;
  1766. #endif
  1767. }
  1768. pe_free_imports(&pe);
  1769. #ifdef PE_PRINT_SECTIONS
  1770. pe_print_sections(s1, "tcc.log");
  1771. #endif
  1772. return ret;
  1773. }
  1774. /* ------------------------------------------------------------- */