Merge branch 'mob' of git://repo.or.cz/tinycc into mypatch
[tinycc.git] / tccpe.c
blobdff6169b5899ea63e87cc56d053ff25ec3a65fb9
1 /*
2 * TCCPE.C - PE file output for the Tiny C Compiler
4 * Copyright (c) 2005-2007 grischka
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.
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.
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
21 #include "tcc.h"
23 #define PE_MERGE_DATA
24 /* #define PE_PRINT_SECTIONS */
26 #ifndef _WIN32
27 #define stricmp strcasecmp
28 #define strnicmp strncasecmp
29 #include <sys/stat.h> /* chmod() */
30 #endif
32 #ifdef TCC_TARGET_X86_64
33 # define ADDR3264 ULONGLONG
34 # define PE_IMAGE_REL IMAGE_REL_BASED_DIR64
35 # define REL_TYPE_DIRECT R_X86_64_64
36 # define R_XXX_THUNKFIX R_X86_64_PC32
37 # define R_XXX_RELATIVE R_X86_64_RELATIVE
38 # define IMAGE_FILE_MACHINE 0x8664
39 # define RSRC_RELTYPE 3
41 #elif defined TCC_TARGET_ARM
42 # define ADDR3264 DWORD
43 # define PE_IMAGE_REL IMAGE_REL_BASED_HIGHLOW
44 # define REL_TYPE_DIRECT R_ARM_ABS32
45 # define R_XXX_THUNKFIX R_ARM_ABS32
46 # define R_XXX_RELATIVE R_ARM_RELATIVE
47 # define IMAGE_FILE_MACHINE 0x01C0
48 # define RSRC_RELTYPE 7 /* ??? (not tested) */
50 #elif defined TCC_TARGET_I386
51 # define ADDR3264 DWORD
52 # define PE_IMAGE_REL IMAGE_REL_BASED_HIGHLOW
53 # define REL_TYPE_DIRECT R_386_32
54 # define R_XXX_THUNKFIX R_386_32
55 # define R_XXX_RELATIVE R_386_RELATIVE
56 # define IMAGE_FILE_MACHINE 0x014C
57 # define RSRC_RELTYPE 7 /* DIR32NB */
59 #endif
61 #ifndef IMAGE_NT_SIGNATURE
62 /* ----------------------------------------------------------- */
63 /* definitions below are from winnt.h */
65 typedef unsigned char BYTE;
66 typedef unsigned short WORD;
67 typedef unsigned int DWORD;
68 typedef unsigned long long ULONGLONG;
69 #pragma pack(push, 1)
71 typedef struct _IMAGE_DOS_HEADER { /* DOS .EXE header */
72 WORD e_magic; /* Magic number */
73 WORD e_cblp; /* Bytes on last page of file */
74 WORD e_cp; /* Pages in file */
75 WORD e_crlc; /* Relocations */
76 WORD e_cparhdr; /* Size of header in paragraphs */
77 WORD e_minalloc; /* Minimum extra paragraphs needed */
78 WORD e_maxalloc; /* Maximum extra paragraphs needed */
79 WORD e_ss; /* Initial (relative) SS value */
80 WORD e_sp; /* Initial SP value */
81 WORD e_csum; /* Checksum */
82 WORD e_ip; /* Initial IP value */
83 WORD e_cs; /* Initial (relative) CS value */
84 WORD e_lfarlc; /* File address of relocation table */
85 WORD e_ovno; /* Overlay number */
86 WORD e_res[4]; /* Reserved words */
87 WORD e_oemid; /* OEM identifier (for e_oeminfo) */
88 WORD e_oeminfo; /* OEM information; e_oemid specific */
89 WORD e_res2[10]; /* Reserved words */
90 DWORD e_lfanew; /* File address of new exe header */
91 } IMAGE_DOS_HEADER, *PIMAGE_DOS_HEADER;
93 #define IMAGE_NT_SIGNATURE 0x00004550 /* PE00 */
94 #define SIZE_OF_NT_SIGNATURE 4
96 typedef struct _IMAGE_FILE_HEADER {
97 WORD Machine;
98 WORD NumberOfSections;
99 DWORD TimeDateStamp;
100 DWORD PointerToSymbolTable;
101 DWORD NumberOfSymbols;
102 WORD SizeOfOptionalHeader;
103 WORD Characteristics;
104 } IMAGE_FILE_HEADER, *PIMAGE_FILE_HEADER;
107 #define IMAGE_SIZEOF_FILE_HEADER 20
109 typedef struct _IMAGE_DATA_DIRECTORY {
110 DWORD VirtualAddress;
111 DWORD Size;
112 } IMAGE_DATA_DIRECTORY, *PIMAGE_DATA_DIRECTORY;
115 typedef struct _IMAGE_OPTIONAL_HEADER {
116 /* Standard fields. */
117 WORD Magic;
118 BYTE MajorLinkerVersion;
119 BYTE MinorLinkerVersion;
120 DWORD SizeOfCode;
121 DWORD SizeOfInitializedData;
122 DWORD SizeOfUninitializedData;
123 DWORD AddressOfEntryPoint;
124 DWORD BaseOfCode;
125 #ifndef TCC_TARGET_X86_64
126 DWORD BaseOfData;
127 #endif
128 /* NT additional fields. */
129 ADDR3264 ImageBase;
130 DWORD SectionAlignment;
131 DWORD FileAlignment;
132 WORD MajorOperatingSystemVersion;
133 WORD MinorOperatingSystemVersion;
134 WORD MajorImageVersion;
135 WORD MinorImageVersion;
136 WORD MajorSubsystemVersion;
137 WORD MinorSubsystemVersion;
138 DWORD Win32VersionValue;
139 DWORD SizeOfImage;
140 DWORD SizeOfHeaders;
141 DWORD CheckSum;
142 WORD Subsystem;
143 WORD DllCharacteristics;
144 ADDR3264 SizeOfStackReserve;
145 ADDR3264 SizeOfStackCommit;
146 ADDR3264 SizeOfHeapReserve;
147 ADDR3264 SizeOfHeapCommit;
148 DWORD LoaderFlags;
149 DWORD NumberOfRvaAndSizes;
150 IMAGE_DATA_DIRECTORY DataDirectory[16];
151 } IMAGE_OPTIONAL_HEADER32, IMAGE_OPTIONAL_HEADER64, IMAGE_OPTIONAL_HEADER;
153 #define IMAGE_DIRECTORY_ENTRY_EXPORT 0 /* Export Directory */
154 #define IMAGE_DIRECTORY_ENTRY_IMPORT 1 /* Import Directory */
155 #define IMAGE_DIRECTORY_ENTRY_RESOURCE 2 /* Resource Directory */
156 #define IMAGE_DIRECTORY_ENTRY_EXCEPTION 3 /* Exception Directory */
157 #define IMAGE_DIRECTORY_ENTRY_SECURITY 4 /* Security Directory */
158 #define IMAGE_DIRECTORY_ENTRY_BASERELOC 5 /* Base Relocation Table */
159 #define IMAGE_DIRECTORY_ENTRY_DEBUG 6 /* Debug Directory */
160 /* IMAGE_DIRECTORY_ENTRY_COPYRIGHT 7 (X86 usage) */
161 #define IMAGE_DIRECTORY_ENTRY_ARCHITECTURE 7 /* Architecture Specific Data */
162 #define IMAGE_DIRECTORY_ENTRY_GLOBALPTR 8 /* RVA of GP */
163 #define IMAGE_DIRECTORY_ENTRY_TLS 9 /* TLS Directory */
164 #define IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG 10 /* Load Configuration Directory */
165 #define IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT 11 /* Bound Import Directory in headers */
166 #define IMAGE_DIRECTORY_ENTRY_IAT 12 /* Import Address Table */
167 #define IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT 13 /* Delay Load Import Descriptors */
168 #define IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR 14 /* COM Runtime descriptor */
170 /* Section header format. */
171 #define IMAGE_SIZEOF_SHORT_NAME 8
173 typedef struct _IMAGE_SECTION_HEADER {
174 BYTE Name[IMAGE_SIZEOF_SHORT_NAME];
175 union {
176 DWORD PhysicalAddress;
177 DWORD VirtualSize;
178 } Misc;
179 DWORD VirtualAddress;
180 DWORD SizeOfRawData;
181 DWORD PointerToRawData;
182 DWORD PointerToRelocations;
183 DWORD PointerToLinenumbers;
184 WORD NumberOfRelocations;
185 WORD NumberOfLinenumbers;
186 DWORD Characteristics;
187 } IMAGE_SECTION_HEADER, *PIMAGE_SECTION_HEADER;
189 #define IMAGE_SIZEOF_SECTION_HEADER 40
191 typedef struct _IMAGE_EXPORT_DIRECTORY {
192 DWORD Characteristics;
193 DWORD TimeDateStamp;
194 WORD MajorVersion;
195 WORD MinorVersion;
196 DWORD Name;
197 DWORD Base;
198 DWORD NumberOfFunctions;
199 DWORD NumberOfNames;
200 DWORD AddressOfFunctions;
201 DWORD AddressOfNames;
202 DWORD AddressOfNameOrdinals;
203 } IMAGE_EXPORT_DIRECTORY,*PIMAGE_EXPORT_DIRECTORY;
205 typedef struct _IMAGE_IMPORT_DESCRIPTOR {
206 union {
207 DWORD Characteristics;
208 DWORD OriginalFirstThunk;
210 DWORD TimeDateStamp;
211 DWORD ForwarderChain;
212 DWORD Name;
213 DWORD FirstThunk;
214 } IMAGE_IMPORT_DESCRIPTOR;
216 typedef struct _IMAGE_BASE_RELOCATION {
217 DWORD VirtualAddress;
218 DWORD SizeOfBlock;
219 // WORD TypeOffset[1];
220 } IMAGE_BASE_RELOCATION;
222 #define IMAGE_SIZEOF_BASE_RELOCATION 8
224 #define IMAGE_REL_BASED_ABSOLUTE 0
225 #define IMAGE_REL_BASED_HIGH 1
226 #define IMAGE_REL_BASED_LOW 2
227 #define IMAGE_REL_BASED_HIGHLOW 3
228 #define IMAGE_REL_BASED_HIGHADJ 4
229 #define IMAGE_REL_BASED_MIPS_JMPADDR 5
230 #define IMAGE_REL_BASED_SECTION 6
231 #define IMAGE_REL_BASED_REL32 7
232 #define IMAGE_REL_BASED_DIR64 10
234 #define IMAGE_SCN_CNT_CODE 0x00000020
235 #define IMAGE_SCN_CNT_INITIALIZED_DATA 0x00000040
236 #define IMAGE_SCN_CNT_UNINITIALIZED_DATA 0x00000080
237 #define IMAGE_SCN_MEM_DISCARDABLE 0x02000000
238 #define IMAGE_SCN_MEM_SHARED 0x10000000
239 #define IMAGE_SCN_MEM_EXECUTE 0x20000000
240 #define IMAGE_SCN_MEM_READ 0x40000000
241 #define IMAGE_SCN_MEM_WRITE 0x80000000
242 #define IMAGE_SCN_TYPE_NOLOAD 0x00000002
243 #define IMAGE_SCN_LNK_REMOVE 0x00000800
245 #pragma pack(pop)
247 /* ----------------------------------------------------------- */
248 #endif /* ndef IMAGE_NT_SIGNATURE */
249 /* ----------------------------------------------------------- */
251 #ifndef IMAGE_REL_BASED_DIR64
252 # define IMAGE_REL_BASED_DIR64 10
253 #endif
255 #pragma pack(push, 1)
256 struct pe_header
258 IMAGE_DOS_HEADER doshdr;
259 BYTE dosstub[0x40];
260 DWORD nt_sig;
261 IMAGE_FILE_HEADER filehdr;
262 #ifdef TCC_TARGET_X86_64
263 IMAGE_OPTIONAL_HEADER64 opthdr;
264 #else
265 #ifdef _WIN64
266 IMAGE_OPTIONAL_HEADER32 opthdr;
267 #else
268 IMAGE_OPTIONAL_HEADER opthdr;
269 #endif
270 #endif
273 struct pe_reloc_header {
274 DWORD offset;
275 DWORD size;
278 struct pe_rsrc_header {
279 struct _IMAGE_FILE_HEADER filehdr;
280 struct _IMAGE_SECTION_HEADER sectionhdr;
283 struct pe_rsrc_reloc {
284 DWORD offset;
285 DWORD size;
286 WORD type;
288 #pragma pack(pop)
290 /* ------------------------------------------------------------- */
291 /* internal temporary structures */
293 enum {
294 sec_text = 0,
295 sec_data ,
296 sec_bss ,
297 sec_idata ,
298 sec_pdata ,
299 sec_other ,
300 sec_rsrc ,
301 sec_stab ,
302 sec_reloc ,
303 sec_last
306 #if 0
307 static const DWORD pe_sec_flags[] = {
308 0x60000020, /* ".text" , */
309 0xC0000040, /* ".data" , */
310 0xC0000080, /* ".bss" , */
311 0x40000040, /* ".idata" , */
312 0x40000040, /* ".pdata" , */
313 0xE0000060, /* < other > , */
314 0x40000040, /* ".rsrc" , */
315 0x42000802, /* ".stab" , */
316 0x42000040, /* ".reloc" , */
318 #endif
320 struct section_info {
321 int cls, ord;
322 char name[32];
323 DWORD sh_addr;
324 DWORD sh_size;
325 DWORD pe_flags;
326 unsigned char *data;
327 DWORD data_size;
328 IMAGE_SECTION_HEADER ish;
331 struct import_symbol {
332 int sym_index;
333 int iat_index;
334 int thk_offset;
337 struct pe_import_info {
338 int dll_index;
339 int sym_count;
340 struct import_symbol **symbols;
343 struct pe_info {
344 TCCState *s1;
345 Section *reloc;
346 Section *thunk;
347 const char *filename;
348 int type;
349 DWORD sizeofheaders;
350 ADDR3264 imagebase;
351 const char *start_symbol;
352 DWORD start_addr;
353 DWORD imp_offs;
354 DWORD imp_size;
355 DWORD iat_offs;
356 DWORD iat_size;
357 DWORD exp_offs;
358 DWORD exp_size;
359 int subsystem;
360 DWORD section_align;
361 DWORD file_align;
362 struct section_info *sec_info;
363 int sec_count;
364 struct pe_import_info **imp_info;
365 int imp_count;
368 #define PE_NUL 0
369 #define PE_DLL 1
370 #define PE_GUI 2
371 #define PE_EXE 3
372 #define PE_RUN 4
374 /* --------------------------------------------*/
376 static const char *pe_export_name(TCCState *s1, ElfW(Sym) *sym)
378 const char *name = (char*)symtab_section->link->data + sym->st_name;
379 if (s1->leading_underscore && name[0] == '_' && !(sym->st_other & ST_PE_STDCALL))
380 return name + 1;
381 return name;
384 static int pe_find_import(TCCState * s1, ElfW(Sym) *sym)
386 char buffer[200];
387 const char *s, *p;
388 int sym_index = 0, n = 0;
389 int a, err = 0;
391 do {
392 s = pe_export_name(s1, sym);
393 a = 0;
394 if (n) {
395 /* second try: */
396 if (sym->st_other & ST_PE_STDCALL) {
397 /* try w/0 stdcall deco (windows API convention) */
398 p = strrchr(s, '@');
399 if (!p || s[0] != '_')
400 break;
401 strcpy(buffer, s+1)[p-s-1] = 0;
402 } else if (s[0] != '_') { /* try non-ansi function */
403 buffer[0] = '_', strcpy(buffer + 1, s);
404 } else if (0 == memcmp(s, "__imp_", 6)) { /* mingw 2.0 */
405 strcpy(buffer, s + 6), a = 1;
406 } else if (0 == memcmp(s, "_imp__", 6)) { /* mingw 3.7 */
407 strcpy(buffer, s + 6), a = 1;
408 } else {
409 continue;
411 s = buffer;
413 sym_index = find_elf_sym(s1->dynsymtab_section, s);
414 // printf("find (%d) %d %s\n", n, sym_index, s);
415 if (sym_index
416 && ELFW(ST_TYPE)(sym->st_info) == STT_OBJECT
417 && 0 == (sym->st_other & ST_PE_IMPORT)
418 && 0 == a
419 ) err = -1, sym_index = 0;
420 } while (0 == sym_index && ++n < 2);
421 return n == 2 ? err : sym_index;
424 /*----------------------------------------------------------------------------*/
426 static int dynarray_assoc(void **pp, int n, int key)
428 int i;
429 for (i = 0; i < n; ++i, ++pp)
430 if (key == **(int **) pp)
431 return i;
432 return -1;
435 #if 0
436 ST_FN DWORD umin(DWORD a, DWORD b)
438 return a < b ? a : b;
440 #endif
442 static DWORD umax(DWORD a, DWORD b)
444 return a < b ? b : a;
447 static DWORD pe_file_align(struct pe_info *pe, DWORD n)
449 return (n + (pe->file_align - 1)) & ~(pe->file_align - 1);
452 static DWORD pe_virtual_align(struct pe_info *pe, DWORD n)
454 return (n + (pe->section_align - 1)) & ~(pe->section_align - 1);
457 static void pe_align_section(Section *s, int a)
459 int i = s->data_offset & (a-1);
460 if (i)
461 section_ptr_add(s, a - i);
464 static void pe_set_datadir(struct pe_header *hdr, int dir, DWORD addr, DWORD size)
466 hdr->opthdr.DataDirectory[dir].VirtualAddress = addr;
467 hdr->opthdr.DataDirectory[dir].Size = size;
470 static int pe_fwrite(void *data, unsigned len, FILE *fp, DWORD *psum)
472 if (psum) {
473 DWORD sum = *psum;
474 WORD *p = data;
475 int i;
476 for (i = len; i > 0; i -= 2) {
477 sum += (i >= 2) ? *p++ : *(BYTE*)p;
478 sum = (sum + (sum >> 16)) & 0xFFFF;
480 *psum = sum;
482 return len == fwrite(data, 1, len, fp) ? 0 : -1;
485 static void pe_fpad(FILE *fp, DWORD new_pos)
487 DWORD pos = ftell(fp);
488 while (++pos <= new_pos)
489 fputc(0, fp);
492 /*----------------------------------------------------------------------------*/
493 static int pe_write(struct pe_info *pe)
495 static const struct pe_header pe_template = {
497 /* IMAGE_DOS_HEADER doshdr */
498 0x5A4D, /*WORD e_magic; Magic number */
499 0x0090, /*WORD e_cblp; Bytes on last page of file */
500 0x0003, /*WORD e_cp; Pages in file */
501 0x0000, /*WORD e_crlc; Relocations */
503 0x0004, /*WORD e_cparhdr; Size of header in paragraphs */
504 0x0000, /*WORD e_minalloc; Minimum extra paragraphs needed */
505 0xFFFF, /*WORD e_maxalloc; Maximum extra paragraphs needed */
506 0x0000, /*WORD e_ss; Initial (relative) SS value */
508 0x00B8, /*WORD e_sp; Initial SP value */
509 0x0000, /*WORD e_csum; Checksum */
510 0x0000, /*WORD e_ip; Initial IP value */
511 0x0000, /*WORD e_cs; Initial (relative) CS value */
512 0x0040, /*WORD e_lfarlc; File address of relocation table */
513 0x0000, /*WORD e_ovno; Overlay number */
514 {0,0,0,0}, /*WORD e_res[4]; Reserved words */
515 0x0000, /*WORD e_oemid; OEM identifier (for e_oeminfo) */
516 0x0000, /*WORD e_oeminfo; OEM information; e_oemid specific */
517 {0,0,0,0,0,0,0,0,0,0}, /*WORD e_res2[10]; Reserved words */
518 0x00000080 /*DWORD e_lfanew; File address of new exe header */
520 /* BYTE dosstub[0x40] */
521 /* 14 code bytes + "This program cannot be run in DOS mode.\r\r\n$" + 6 * 0x00 */
522 0x0e,0x1f,0xba,0x0e,0x00,0xb4,0x09,0xcd,0x21,0xb8,0x01,0x4c,0xcd,0x21,0x54,0x68,
523 0x69,0x73,0x20,0x70,0x72,0x6f,0x67,0x72,0x61,0x6d,0x20,0x63,0x61,0x6e,0x6e,0x6f,
524 0x74,0x20,0x62,0x65,0x20,0x72,0x75,0x6e,0x20,0x69,0x6e,0x20,0x44,0x4f,0x53,0x20,
525 0x6d,0x6f,0x64,0x65,0x2e,0x0d,0x0d,0x0a,0x24,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
527 0x00004550, /* DWORD nt_sig = IMAGE_NT_SIGNATURE */
529 /* IMAGE_FILE_HEADER filehdr */
530 IMAGE_FILE_MACHINE, /*WORD Machine; */
531 0x0003, /*WORD NumberOfSections; */
532 0x00000000, /*DWORD TimeDateStamp; */
533 0x00000000, /*DWORD PointerToSymbolTable; */
534 0x00000000, /*DWORD NumberOfSymbols; */
535 #if defined(TCC_TARGET_X86_64)
536 0x00F0, /*WORD SizeOfOptionalHeader; */
537 0x022F /*WORD Characteristics; */
538 #define CHARACTERISTICS_DLL 0x222E
539 #elif defined(TCC_TARGET_I386)
540 0x00E0, /*WORD SizeOfOptionalHeader; */
541 0x030F /*WORD Characteristics; */
542 #define CHARACTERISTICS_DLL 0x230E
543 #elif defined(TCC_TARGET_ARM)
544 0x00E0, /*WORD SizeOfOptionalHeader; */
545 0x010F, /*WORD Characteristics; */
546 #define CHARACTERISTICS_DLL 0x230F
547 #endif
549 /* IMAGE_OPTIONAL_HEADER opthdr */
550 /* Standard fields. */
551 #ifdef TCC_TARGET_X86_64
552 0x020B, /*WORD Magic; */
553 #else
554 0x010B, /*WORD Magic; */
555 #endif
556 0x06, /*BYTE MajorLinkerVersion; */
557 0x00, /*BYTE MinorLinkerVersion; */
558 0x00000000, /*DWORD SizeOfCode; */
559 0x00000000, /*DWORD SizeOfInitializedData; */
560 0x00000000, /*DWORD SizeOfUninitializedData; */
561 0x00000000, /*DWORD AddressOfEntryPoint; */
562 0x00000000, /*DWORD BaseOfCode; */
563 #ifndef TCC_TARGET_X86_64
564 0x00000000, /*DWORD BaseOfData; */
565 #endif
566 /* NT additional fields. */
567 #if defined(TCC_TARGET_ARM)
568 0x00100000, /*DWORD ImageBase; */
569 #else
570 0x00400000, /*DWORD ImageBase; */
571 #endif
572 0x00001000, /*DWORD SectionAlignment; */
573 0x00000200, /*DWORD FileAlignment; */
574 0x0004, /*WORD MajorOperatingSystemVersion; */
575 0x0000, /*WORD MinorOperatingSystemVersion; */
576 0x0000, /*WORD MajorImageVersion; */
577 0x0000, /*WORD MinorImageVersion; */
578 0x0004, /*WORD MajorSubsystemVersion; */
579 0x0000, /*WORD MinorSubsystemVersion; */
580 0x00000000, /*DWORD Win32VersionValue; */
581 0x00000000, /*DWORD SizeOfImage; */
582 0x00000200, /*DWORD SizeOfHeaders; */
583 0x00000000, /*DWORD CheckSum; */
584 0x0002, /*WORD Subsystem; */
585 0x0000, /*WORD DllCharacteristics; */
586 0x00100000, /*DWORD SizeOfStackReserve; */
587 0x00001000, /*DWORD SizeOfStackCommit; */
588 0x00100000, /*DWORD SizeOfHeapReserve; */
589 0x00001000, /*DWORD SizeOfHeapCommit; */
590 0x00000000, /*DWORD LoaderFlags; */
591 0x00000010, /*DWORD NumberOfRvaAndSizes; */
593 /* IMAGE_DATA_DIRECTORY DataDirectory[16]; */
594 {{0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0},
595 {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}}
598 struct pe_header pe_header = pe_template;
600 int i;
601 FILE *op;
602 DWORD file_offset, sum;
603 struct section_info *si;
604 IMAGE_SECTION_HEADER *psh;
605 TCCState *s1 = pe->s1;
607 op = fopen(pe->filename, "wb");
608 if (NULL == op) {
609 tcc_error_noabort("could not write '%s': %s", pe->filename, strerror(errno));
610 return -1;
613 pe->sizeofheaders = pe_file_align(pe,
614 sizeof (struct pe_header)
615 + pe->sec_count * sizeof (IMAGE_SECTION_HEADER)
618 file_offset = pe->sizeofheaders;
620 if (2 == pe->s1->verbose)
621 printf("-------------------------------"
622 "\n virt file size section" "\n");
623 for (i = 0; i < pe->sec_count; ++i) {
624 DWORD addr, size;
625 const char *sh_name;
627 si = pe->sec_info + i;
628 sh_name = si->name;
629 addr = si->sh_addr - pe->imagebase;
630 size = si->sh_size;
631 psh = &si->ish;
633 if (2 == pe->s1->verbose)
634 printf("%6x %6x %6x %s\n",
635 (unsigned)addr, (unsigned)file_offset, (unsigned)size, sh_name);
637 switch (si->cls) {
638 case sec_text:
639 if (!pe_header.opthdr.BaseOfCode)
640 pe_header.opthdr.BaseOfCode = addr;
641 break;
643 case sec_data:
644 #ifndef TCC_TARGET_X86_64
645 if (!pe_header.opthdr.BaseOfData)
646 pe_header.opthdr.BaseOfData = addr;
647 #endif
648 break;
650 case sec_bss:
651 break;
653 case sec_reloc:
654 pe_set_datadir(&pe_header, IMAGE_DIRECTORY_ENTRY_BASERELOC, addr, size);
655 break;
657 case sec_rsrc:
658 pe_set_datadir(&pe_header, IMAGE_DIRECTORY_ENTRY_RESOURCE, addr, size);
659 break;
661 case sec_pdata:
662 pe_set_datadir(&pe_header, IMAGE_DIRECTORY_ENTRY_EXCEPTION, addr, size);
663 break;
666 if (pe->thunk == pe->s1->sections[si->ord]) {
667 if (pe->imp_size) {
668 pe_set_datadir(&pe_header, IMAGE_DIRECTORY_ENTRY_IMPORT,
669 pe->imp_offs + addr, pe->imp_size);
670 pe_set_datadir(&pe_header, IMAGE_DIRECTORY_ENTRY_IAT,
671 pe->iat_offs + addr, pe->iat_size);
673 if (pe->exp_size) {
674 pe_set_datadir(&pe_header, IMAGE_DIRECTORY_ENTRY_EXPORT,
675 pe->exp_offs + addr, pe->exp_size);
679 strncpy((char*)psh->Name, sh_name, sizeof psh->Name);
681 psh->Characteristics = si->pe_flags;
682 psh->VirtualAddress = addr;
683 psh->Misc.VirtualSize = size;
684 pe_header.opthdr.SizeOfImage =
685 umax(pe_virtual_align(pe, size + addr), pe_header.opthdr.SizeOfImage);
687 if (si->data_size) {
688 psh->PointerToRawData = file_offset;
689 file_offset = pe_file_align(pe, file_offset + si->data_size);
690 psh->SizeOfRawData = file_offset - psh->PointerToRawData;
691 if (si->cls == sec_text)
692 pe_header.opthdr.SizeOfCode += psh->SizeOfRawData;
693 else
694 pe_header.opthdr.SizeOfInitializedData += psh->SizeOfRawData;
698 //pe_header.filehdr.TimeDateStamp = time(NULL);
699 pe_header.filehdr.NumberOfSections = pe->sec_count;
700 pe_header.opthdr.AddressOfEntryPoint = pe->start_addr;
701 pe_header.opthdr.SizeOfHeaders = pe->sizeofheaders;
702 pe_header.opthdr.ImageBase = pe->imagebase;
703 pe_header.opthdr.Subsystem = pe->subsystem;
704 if (pe->s1->pe_stack_size)
705 pe_header.opthdr.SizeOfStackReserve = pe->s1->pe_stack_size;
706 if (PE_DLL == pe->type)
707 pe_header.filehdr.Characteristics = CHARACTERISTICS_DLL;
708 pe_header.filehdr.Characteristics |= pe->s1->pe_characteristics;
710 sum = 0;
711 pe_fwrite(&pe_header, sizeof pe_header, op, &sum);
712 for (i = 0; i < pe->sec_count; ++i)
713 pe_fwrite(&pe->sec_info[i].ish, sizeof(IMAGE_SECTION_HEADER), op, &sum);
714 pe_fpad(op, pe->sizeofheaders);
715 for (i = 0; i < pe->sec_count; ++i) {
716 si = pe->sec_info + i;
717 psh = &si->ish;
718 if (si->data_size) {
719 pe_fwrite(si->data, si->data_size, op, &sum);
720 file_offset = psh->PointerToRawData + psh->SizeOfRawData;
721 pe_fpad(op, file_offset);
725 pe_header.opthdr.CheckSum = sum + file_offset;
726 fseek(op, offsetof(struct pe_header, opthdr.CheckSum), SEEK_SET);
727 pe_fwrite(&pe_header.opthdr.CheckSum, sizeof pe_header.opthdr.CheckSum, op, NULL);
728 fclose (op);
729 #ifndef _WIN32
730 chmod(pe->filename, 0777);
731 #endif
733 if (2 == pe->s1->verbose)
734 printf("-------------------------------\n");
735 if (pe->s1->verbose)
736 printf("<- %s (%u bytes)\n", pe->filename, (unsigned)file_offset);
738 return 0;
741 /*----------------------------------------------------------------------------*/
743 static struct import_symbol *pe_add_import(struct pe_info *pe, int sym_index)
745 int i;
746 int dll_index;
747 struct pe_import_info *p;
748 struct import_symbol *s;
749 ElfW(Sym) *isym;
751 isym = (ElfW(Sym) *)pe->s1->dynsymtab_section->data + sym_index;
752 dll_index = isym->st_size;
754 i = dynarray_assoc ((void**)pe->imp_info, pe->imp_count, dll_index);
755 if (-1 != i) {
756 p = pe->imp_info[i];
757 goto found_dll;
759 p = tcc_mallocz(sizeof *p);
760 p->dll_index = dll_index;
761 dynarray_add(&pe->imp_info, &pe->imp_count, p);
763 found_dll:
764 i = dynarray_assoc ((void**)p->symbols, p->sym_count, sym_index);
765 if (-1 != i)
766 return p->symbols[i];
768 s = tcc_mallocz(sizeof *s);
769 dynarray_add(&p->symbols, &p->sym_count, s);
770 s->sym_index = sym_index;
771 return s;
774 void pe_free_imports(struct pe_info *pe)
776 int i;
777 for (i = 0; i < pe->imp_count; ++i) {
778 struct pe_import_info *p = pe->imp_info[i];
779 dynarray_reset(&p->symbols, &p->sym_count);
781 dynarray_reset(&pe->imp_info, &pe->imp_count);
784 /*----------------------------------------------------------------------------*/
785 static void pe_build_imports(struct pe_info *pe)
787 int thk_ptr, ent_ptr, dll_ptr, sym_cnt, i;
788 DWORD rva_base = pe->thunk->sh_addr - pe->imagebase;
789 int ndlls = pe->imp_count;
790 TCCState *s1 = pe->s1;
792 for (sym_cnt = i = 0; i < ndlls; ++i)
793 sym_cnt += pe->imp_info[i]->sym_count;
795 if (0 == sym_cnt)
796 return;
798 pe_align_section(pe->thunk, 16);
800 pe->imp_offs = dll_ptr = pe->thunk->data_offset;
801 pe->imp_size = (ndlls + 1) * sizeof(IMAGE_IMPORT_DESCRIPTOR);
802 pe->iat_offs = dll_ptr + pe->imp_size;
803 pe->iat_size = (sym_cnt + ndlls) * sizeof(ADDR3264);
804 section_ptr_add(pe->thunk, pe->imp_size + 2*pe->iat_size);
806 thk_ptr = pe->iat_offs;
807 ent_ptr = pe->iat_offs + pe->iat_size;
809 for (i = 0; i < pe->imp_count; ++i) {
810 IMAGE_IMPORT_DESCRIPTOR *hdr;
811 int k, n, dllindex;
812 ADDR3264 v;
813 struct pe_import_info *p = pe->imp_info[i];
814 const char *name;
815 DLLReference *dllref;
817 dllindex = p->dll_index;
818 if (dllindex)
819 name = (dllref = pe->s1->loaded_dlls[dllindex-1])->name;
820 else
821 name = "", dllref = NULL;
823 /* put the dll name into the import header */
824 v = put_elf_str(pe->thunk, name);
825 hdr = (IMAGE_IMPORT_DESCRIPTOR*)(pe->thunk->data + dll_ptr);
826 hdr->FirstThunk = thk_ptr + rva_base;
827 hdr->OriginalFirstThunk = ent_ptr + rva_base;
828 hdr->Name = v + rva_base;
830 for (k = 0, n = p->sym_count; k <= n; ++k) {
831 if (k < n) {
832 int iat_index = p->symbols[k]->iat_index;
833 int sym_index = p->symbols[k]->sym_index;
834 ElfW(Sym) *imp_sym = (ElfW(Sym) *)pe->s1->dynsymtab_section->data + sym_index;
835 ElfW(Sym) *org_sym = (ElfW(Sym) *)symtab_section->data + iat_index;
836 const char *name = (char*)pe->s1->dynsymtab_section->link->data + imp_sym->st_name;
837 int ordinal;
839 org_sym->st_value = thk_ptr;
840 org_sym->st_shndx = pe->thunk->sh_num;
842 if (dllref)
843 v = 0, ordinal = imp_sym->st_value; /* ordinal from pe_load_def */
844 else
845 ordinal = 0, v = imp_sym->st_value; /* address from tcc_add_symbol() */
847 #ifdef TCC_IS_NATIVE
848 if (pe->type == PE_RUN) {
849 if (dllref) {
850 if ( !dllref->handle )
851 dllref->handle = LoadLibrary(dllref->name);
852 v = (ADDR3264)GetProcAddress(dllref->handle, ordinal?(char*)0+ordinal:name);
854 if (!v)
855 tcc_error_noabort("can't build symbol '%s'", name);
856 } else
857 #endif
858 if (ordinal) {
859 v = ordinal | (ADDR3264)1 << (sizeof(ADDR3264)*8 - 1);
860 } else {
861 v = pe->thunk->data_offset + rva_base;
862 section_ptr_add(pe->thunk, sizeof(WORD)); /* hint, not used */
863 put_elf_str(pe->thunk, name);
866 } else {
867 v = 0; /* last entry is zero */
870 *(ADDR3264*)(pe->thunk->data+thk_ptr) =
871 *(ADDR3264*)(pe->thunk->data+ent_ptr) = v;
872 thk_ptr += sizeof (ADDR3264);
873 ent_ptr += sizeof (ADDR3264);
875 dll_ptr += sizeof(IMAGE_IMPORT_DESCRIPTOR);
879 /* ------------------------------------------------------------- */
881 struct pe_sort_sym
883 int index;
884 const char *name;
887 static int sym_cmp(const void *va, const void *vb)
889 const char *ca = (*(struct pe_sort_sym**)va)->name;
890 const char *cb = (*(struct pe_sort_sym**)vb)->name;
891 return strcmp(ca, cb);
894 static void pe_build_exports(struct pe_info *pe)
896 ElfW(Sym) *sym;
897 int sym_index, sym_end;
898 DWORD rva_base, func_o, name_o, ord_o, str_o;
899 IMAGE_EXPORT_DIRECTORY *hdr;
900 int sym_count, ord;
901 struct pe_sort_sym **sorted, *p;
902 TCCState *s1 = pe->s1;
904 FILE *op;
905 char buf[260];
906 const char *dllname;
907 const char *name;
909 rva_base = pe->thunk->sh_addr - pe->imagebase;
910 sym_count = 0, sorted = NULL, op = NULL;
912 sym_end = symtab_section->data_offset / sizeof(ElfW(Sym));
913 for (sym_index = 1; sym_index < sym_end; ++sym_index) {
914 sym = (ElfW(Sym)*)symtab_section->data + sym_index;
915 name = pe_export_name(pe->s1, sym);
916 if ((sym->st_other & ST_PE_EXPORT)
917 /* export only symbols from actually written sections */
918 && pe->s1->sections[sym->st_shndx]->sh_addr) {
919 p = tcc_malloc(sizeof *p);
920 p->index = sym_index;
921 p->name = name;
922 dynarray_add(&sorted, &sym_count, p);
924 #if 0
925 if (sym->st_other & ST_PE_EXPORT)
926 printf("export: %s\n", name);
927 if (sym->st_other & ST_PE_STDCALL)
928 printf("stdcall: %s\n", name);
929 #endif
932 if (0 == sym_count)
933 return;
935 qsort (sorted, sym_count, sizeof *sorted, sym_cmp);
937 pe_align_section(pe->thunk, 16);
938 dllname = tcc_basename(pe->filename);
940 pe->exp_offs = pe->thunk->data_offset;
941 func_o = pe->exp_offs + sizeof(IMAGE_EXPORT_DIRECTORY);
942 name_o = func_o + sym_count * sizeof (DWORD);
943 ord_o = name_o + sym_count * sizeof (DWORD);
944 str_o = ord_o + sym_count * sizeof(WORD);
946 hdr = section_ptr_add(pe->thunk, str_o - pe->exp_offs);
947 hdr->Characteristics = 0;
948 hdr->Base = 1;
949 hdr->NumberOfFunctions = sym_count;
950 hdr->NumberOfNames = sym_count;
951 hdr->AddressOfFunctions = func_o + rva_base;
952 hdr->AddressOfNames = name_o + rva_base;
953 hdr->AddressOfNameOrdinals = ord_o + rva_base;
954 hdr->Name = str_o + rva_base;
955 put_elf_str(pe->thunk, dllname);
957 #if 1
958 /* automatically write exports to <output-filename>.def */
959 pstrcpy(buf, sizeof buf, pe->filename);
960 strcpy(tcc_fileextension(buf), ".def");
961 op = fopen(buf, "wb");
962 if (NULL == op) {
963 tcc_error_noabort("could not create '%s': %s", buf, strerror(errno));
964 } else {
965 fprintf(op, "LIBRARY %s\n\nEXPORTS\n", dllname);
966 if (pe->s1->verbose)
967 printf("<- %s (%d symbol%s)\n", buf, sym_count, &"s"[sym_count < 2]);
969 #endif
971 for (ord = 0; ord < sym_count; ++ord)
973 p = sorted[ord], sym_index = p->index, name = p->name;
974 /* insert actual address later in relocate_section() */
975 put_elf_reloc(symtab_section, pe->thunk,
976 func_o, R_XXX_RELATIVE, sym_index);
977 *(DWORD*)(pe->thunk->data + name_o)
978 = pe->thunk->data_offset + rva_base;
979 *(WORD*)(pe->thunk->data + ord_o)
980 = ord;
981 put_elf_str(pe->thunk, name);
982 func_o += sizeof (DWORD);
983 name_o += sizeof (DWORD);
984 ord_o += sizeof (WORD);
985 if (op)
986 fprintf(op, "%s\n", name);
988 pe->exp_size = pe->thunk->data_offset - pe->exp_offs;
989 dynarray_reset(&sorted, &sym_count);
990 if (op)
991 fclose(op);
994 /* ------------------------------------------------------------- */
995 static void pe_build_reloc (struct pe_info *pe)
997 DWORD offset, block_ptr, addr;
998 int count, i;
999 ElfW_Rel *rel, *rel_end;
1000 Section *s = NULL, *sr;
1002 offset = addr = block_ptr = count = i = 0;
1003 rel = rel_end = NULL;
1005 for(;;) {
1006 if (rel < rel_end) {
1007 int type = ELFW(R_TYPE)(rel->r_info);
1008 addr = rel->r_offset + s->sh_addr;
1009 ++ rel;
1010 if (type != REL_TYPE_DIRECT)
1011 continue;
1012 if (count == 0) { /* new block */
1013 block_ptr = pe->reloc->data_offset;
1014 section_ptr_add(pe->reloc, sizeof(struct pe_reloc_header));
1015 offset = addr & 0xFFFFFFFF<<12;
1017 if ((addr -= offset) < (1<<12)) { /* one block spans 4k addresses */
1018 WORD *wp = section_ptr_add(pe->reloc, sizeof (WORD));
1019 *wp = addr | PE_IMAGE_REL<<12;
1020 ++count;
1021 continue;
1023 -- rel;
1025 } else if (i < pe->sec_count) {
1026 sr = (s = pe->s1->sections[pe->sec_info[i++].ord])->reloc;
1027 if (sr) {
1028 rel = (ElfW_Rel *)sr->data;
1029 rel_end = (ElfW_Rel *)(sr->data + sr->data_offset);
1031 continue;
1034 if (count) {
1035 /* store the last block and ready for a new one */
1036 struct pe_reloc_header *hdr;
1037 if (count & 1) /* align for DWORDS */
1038 section_ptr_add(pe->reloc, sizeof(WORD)), ++count;
1039 hdr = (struct pe_reloc_header *)(pe->reloc->data + block_ptr);
1040 hdr -> offset = offset - pe->imagebase;
1041 hdr -> size = count * sizeof(WORD) + sizeof(struct pe_reloc_header);
1042 count = 0;
1045 if (rel >= rel_end)
1046 break;
1050 /* ------------------------------------------------------------- */
1051 static int pe_section_class(Section *s)
1053 int type, flags;
1054 const char *name;
1056 type = s->sh_type;
1057 flags = s->sh_flags;
1058 name = s->name;
1059 if (flags & SHF_ALLOC) {
1060 if (type == SHT_PROGBITS) {
1061 if (flags & SHF_EXECINSTR)
1062 return sec_text;
1063 if (flags & SHF_WRITE)
1064 return sec_data;
1065 if (0 == strcmp(name, ".rsrc"))
1066 return sec_rsrc;
1067 if (0 == strcmp(name, ".iedat"))
1068 return sec_idata;
1069 if (0 == strcmp(name, ".pdata"))
1070 return sec_pdata;
1071 } else if (type == SHT_NOBITS) {
1072 if (flags & SHF_WRITE)
1073 return sec_bss;
1075 return sec_other;
1076 } else {
1077 if (0 == strcmp(name, ".reloc"))
1078 return sec_reloc;
1079 if (0 == memcmp(name, ".stab", 5))
1080 return sec_stab;
1082 return -1;
1085 static int pe_assign_addresses (struct pe_info *pe)
1087 int i, k, o, c;
1088 DWORD addr;
1089 int *section_order;
1090 struct section_info *si;
1091 Section *s;
1093 if (PE_DLL == pe->type)
1094 pe->reloc = new_section(pe->s1, ".reloc", SHT_PROGBITS, 0);
1096 // pe->thunk = new_section(pe->s1, ".iedat", SHT_PROGBITS, SHF_ALLOC);
1098 section_order = tcc_malloc(pe->s1->nb_sections * sizeof (int));
1099 for (o = k = 0 ; k < sec_last; ++k) {
1100 for (i = 1; i < pe->s1->nb_sections; ++i) {
1101 s = pe->s1->sections[i];
1102 if (k == pe_section_class(s)) {
1103 // printf("%s %d\n", s->name, k);
1104 s->sh_addr = pe->imagebase;
1105 section_order[o++] = i;
1110 pe->sec_info = tcc_mallocz(o * sizeof (struct section_info));
1111 addr = pe->imagebase + 1;
1113 for (i = 0; i < o; ++i)
1115 k = section_order[i];
1116 s = pe->s1->sections[k];
1117 c = pe_section_class(s);
1118 si = &pe->sec_info[pe->sec_count];
1120 #ifdef PE_MERGE_DATA
1121 if (c == sec_bss && pe->sec_count && si[-1].cls == sec_data) {
1122 /* append .bss to .data */
1123 s->sh_addr = addr = ((addr-1) | (s->sh_addralign-1)) + 1;
1124 addr += s->data_offset;
1125 si[-1].sh_size = addr - si[-1].sh_addr;
1126 continue;
1128 #endif
1129 if (c == sec_stab && 0 == pe->s1->do_debug)
1130 continue;
1132 strcpy(si->name, s->name);
1133 si->cls = c;
1134 si->ord = k;
1135 si->sh_addr = s->sh_addr = addr = pe_virtual_align(pe, addr);
1137 si->pe_flags = IMAGE_SCN_MEM_READ;
1138 if (s->sh_flags & SHF_EXECINSTR)
1139 si->pe_flags |= IMAGE_SCN_MEM_EXECUTE | IMAGE_SCN_CNT_CODE;
1140 else if (s->sh_type == SHT_NOBITS)
1141 si->pe_flags |= IMAGE_SCN_CNT_UNINITIALIZED_DATA;
1142 else
1143 si->pe_flags |= IMAGE_SCN_CNT_INITIALIZED_DATA;
1144 if (s->sh_flags & SHF_WRITE)
1145 si->pe_flags |= IMAGE_SCN_MEM_WRITE;
1146 if (0 == (s->sh_flags & SHF_ALLOC)) {
1147 si->pe_flags |= IMAGE_SCN_MEM_DISCARDABLE;
1148 if (c == sec_stab)
1149 si->pe_flags |= 0x802; //IMAGE_SCN_TYPE_NOLOAD|IMAGE_SCN_LNK_REMOVE
1152 if (c == sec_data && NULL == pe->thunk)
1153 pe->thunk = s;
1155 if (s == pe->thunk) {
1156 pe_build_imports(pe);
1157 pe_build_exports(pe);
1160 if (c == sec_reloc)
1161 pe_build_reloc (pe);
1163 if (s->data_offset)
1165 if (s->sh_type != SHT_NOBITS) {
1166 si->data = s->data;
1167 si->data_size = s->data_offset;
1170 addr += s->data_offset;
1171 si->sh_size = s->data_offset;
1172 ++pe->sec_count;
1174 //printf("%08x %05x %s %08x\n", si->sh_addr, si->sh_size, si->name, si->pe_flags);
1176 #if 0
1177 for (i = 1; i < pe->s1->nb_sections; ++i) {
1178 Section *s = pe->s1->sections[i];
1179 int type = s->sh_type;
1180 int flags = s->sh_flags;
1181 printf("section %-16s %-10s %5x %s,%s,%s\n",
1182 s->name,
1183 type == SHT_PROGBITS ? "progbits" :
1184 type == SHT_NOBITS ? "nobits" :
1185 type == SHT_SYMTAB ? "symtab" :
1186 type == SHT_STRTAB ? "strtab" :
1187 type == SHT_RELX ? "rel" : "???",
1188 s->data_offset,
1189 flags & SHF_ALLOC ? "alloc" : "",
1190 flags & SHF_WRITE ? "write" : "",
1191 flags & SHF_EXECINSTR ? "exec" : ""
1194 pe->s1->verbose = 2;
1195 #endif
1197 tcc_free(section_order);
1198 return 0;
1201 /*----------------------------------------------------------------------------*/
1203 static int pe_isafunc(TCCState *s1, int sym_index)
1205 Section *sr = text_section->reloc;
1206 ElfW_Rel *rel, *rel_end;
1207 Elf32_Word info = ELF32_R_INFO(sym_index, R_386_PC32);
1208 if (!sr)
1209 return 0;
1210 rel_end = (ElfW_Rel *)(sr->data + sr->data_offset);
1211 for (rel = (ElfW_Rel *)sr->data; rel < rel_end; rel++)
1212 if (rel->r_info == info)
1213 return 1;
1214 return 0;
1217 /*----------------------------------------------------------------------------*/
1218 static int pe_check_symbols(struct pe_info *pe)
1220 ElfW(Sym) *sym;
1221 int sym_index, sym_end;
1222 int ret = 0;
1223 TCCState *s1 = pe->s1;
1225 pe_align_section(text_section, 8);
1227 sym_end = symtab_section->data_offset / sizeof(ElfW(Sym));
1228 for (sym_index = 1; sym_index < sym_end; ++sym_index) {
1230 sym = (ElfW(Sym) *)symtab_section->data + sym_index;
1231 if (sym->st_shndx == SHN_UNDEF) {
1233 const char *name = (char*)symtab_section->link->data + sym->st_name;
1234 unsigned type = ELFW(ST_TYPE)(sym->st_info);
1235 int imp_sym = pe_find_import(pe->s1, sym);
1236 struct import_symbol *is;
1238 if (imp_sym <= 0)
1239 goto not_found;
1241 if (type == STT_NOTYPE) {
1242 /* symbols from assembler have no type, find out which */
1243 if (pe_isafunc(s1, sym_index))
1244 type = STT_FUNC;
1245 else
1246 type = STT_OBJECT;
1249 is = pe_add_import(pe, imp_sym);
1251 if (type == STT_FUNC) {
1252 unsigned long offset = is->thk_offset;
1253 if (offset) {
1254 /* got aliased symbol, like stricmp and _stricmp */
1256 } else {
1257 char buffer[100];
1258 WORD *p;
1260 offset = text_section->data_offset;
1261 /* add the 'jmp IAT[x]' instruction */
1262 #ifdef TCC_TARGET_ARM
1263 p = section_ptr_add(text_section, 8+4); // room for code and address
1264 (*(DWORD*)(p)) = 0xE59FC000; // arm code ldr ip, [pc] ; PC+8+0 = 0001xxxx
1265 (*(DWORD*)(p+2)) = 0xE59CF000; // arm code ldr pc, [ip]
1266 #else
1267 p = section_ptr_add(text_section, 8);
1268 *p = 0x25FF;
1269 #ifdef TCC_TARGET_X86_64
1270 *(DWORD*)(p+1) = (DWORD)-4;
1271 #endif
1272 #endif
1273 /* add a helper symbol, will be patched later in
1274 pe_build_imports */
1275 sprintf(buffer, "IAT.%s", name);
1276 is->iat_index = put_elf_sym(
1277 symtab_section, 0, sizeof(DWORD),
1278 ELFW(ST_INFO)(STB_GLOBAL, STT_OBJECT),
1279 0, SHN_UNDEF, buffer);
1280 #ifdef TCC_TARGET_ARM
1281 put_elf_reloc(symtab_section, text_section,
1282 offset + 8, R_XXX_THUNKFIX, is->iat_index); // offset to IAT position
1283 #else
1284 put_elf_reloc(symtab_section, text_section,
1285 offset + 2, R_XXX_THUNKFIX, is->iat_index);
1286 #endif
1287 is->thk_offset = offset;
1290 /* tcc_realloc might have altered sym's address */
1291 sym = (ElfW(Sym) *)symtab_section->data + sym_index;
1293 /* patch the original symbol */
1294 sym->st_value = offset;
1295 sym->st_shndx = text_section->sh_num;
1296 sym->st_other &= ~ST_PE_EXPORT; /* do not export */
1297 continue;
1300 if (type == STT_OBJECT) { /* data, ptr to that should be */
1301 if (0 == is->iat_index) {
1302 /* original symbol will be patched later in pe_build_imports */
1303 is->iat_index = sym_index;
1304 continue;
1308 not_found:
1309 if (ELFW(ST_BIND)(sym->st_info) == STB_WEAK)
1310 /* STB_WEAK undefined symbols are accepted */
1311 continue;
1312 tcc_error_noabort("undefined symbol '%s'%s", name,
1313 imp_sym < 0 ? ", missing __declspec(dllimport)?":"");
1314 ret = -1;
1316 } else if (pe->s1->rdynamic
1317 && ELFW(ST_BIND)(sym->st_info) != STB_LOCAL) {
1318 /* if -rdynamic option, then export all non local symbols */
1319 sym->st_other |= ST_PE_EXPORT;
1322 return ret;
1325 /*----------------------------------------------------------------------------*/
1326 #ifdef PE_PRINT_SECTIONS
1327 static void pe_print_section(FILE * f, Section * s)
1329 /* just if you're curious */
1330 BYTE *p, *e, b;
1331 int i, n, l, m;
1332 p = s->data;
1333 e = s->data + s->data_offset;
1334 l = e - p;
1336 fprintf(f, "section \"%s\"", s->name);
1337 if (s->link)
1338 fprintf(f, "\nlink \"%s\"", s->link->name);
1339 if (s->reloc)
1340 fprintf(f, "\nreloc \"%s\"", s->reloc->name);
1341 fprintf(f, "\nv_addr %08X", (unsigned)s->sh_addr);
1342 fprintf(f, "\ncontents %08X", (unsigned)l);
1343 fprintf(f, "\n\n");
1345 if (s->sh_type == SHT_NOBITS)
1346 return;
1348 if (0 == l)
1349 return;
1351 if (s->sh_type == SHT_SYMTAB)
1352 m = sizeof(ElfW(Sym));
1353 else if (s->sh_type == SHT_RELX)
1354 m = sizeof(ElfW_Rel);
1355 else
1356 m = 16;
1358 fprintf(f, "%-8s", "offset");
1359 for (i = 0; i < m; ++i)
1360 fprintf(f, " %02x", i);
1361 n = 56;
1363 if (s->sh_type == SHT_SYMTAB || s->sh_type == SHT_RELX) {
1364 const char *fields1[] = {
1365 "name",
1366 "value",
1367 "size",
1368 "bind",
1369 "type",
1370 "other",
1371 "shndx",
1372 NULL
1375 const char *fields2[] = {
1376 "offs",
1377 "type",
1378 "symb",
1379 NULL
1382 const char **p;
1384 if (s->sh_type == SHT_SYMTAB)
1385 p = fields1, n = 106;
1386 else
1387 p = fields2, n = 58;
1389 for (i = 0; p[i]; ++i)
1390 fprintf(f, "%6s", p[i]);
1391 fprintf(f, " symbol");
1394 fprintf(f, "\n");
1395 for (i = 0; i < n; ++i)
1396 fprintf(f, "-");
1397 fprintf(f, "\n");
1399 for (i = 0; i < l;)
1401 fprintf(f, "%08X", i);
1402 for (n = 0; n < m; ++n) {
1403 if (n + i < l)
1404 fprintf(f, " %02X", p[i + n]);
1405 else
1406 fprintf(f, " ");
1409 if (s->sh_type == SHT_SYMTAB) {
1410 ElfW(Sym) *sym = (ElfW(Sym) *) (p + i);
1411 const char *name = s->link->data + sym->st_name;
1412 fprintf(f, " %04X %04X %04X %02X %02X %02X %04X \"%s\"",
1413 (unsigned)sym->st_name,
1414 (unsigned)sym->st_value,
1415 (unsigned)sym->st_size,
1416 (unsigned)ELFW(ST_BIND)(sym->st_info),
1417 (unsigned)ELFW(ST_TYPE)(sym->st_info),
1418 (unsigned)sym->st_other,
1419 (unsigned)sym->st_shndx,
1420 name);
1422 } else if (s->sh_type == SHT_RELX) {
1423 ElfW_Rel *rel = (ElfW_Rel *) (p + i);
1424 ElfW(Sym) *sym =
1425 (ElfW(Sym) *) s->link->data + ELFW(R_SYM)(rel->r_info);
1426 const char *name = s->link->link->data + sym->st_name;
1427 fprintf(f, " %04X %02X %04X \"%s\"",
1428 (unsigned)rel->r_offset,
1429 (unsigned)ELFW(R_TYPE)(rel->r_info),
1430 (unsigned)ELFW(R_SYM)(rel->r_info),
1431 name);
1432 } else {
1433 fprintf(f, " ");
1434 for (n = 0; n < m; ++n) {
1435 if (n + i < l) {
1436 b = p[i + n];
1437 if (b < 32 || b >= 127)
1438 b = '.';
1439 fprintf(f, "%c", b);
1443 i += m;
1444 fprintf(f, "\n");
1446 fprintf(f, "\n\n");
1449 static void pe_print_sections(TCCState *s1, const char *fname)
1451 Section *s;
1452 FILE *f;
1453 int i;
1454 f = fopen(fname, "w");
1455 for (i = 1; i < s1->nb_sections; ++i) {
1456 s = s1->sections[i];
1457 pe_print_section(f, s);
1459 pe_print_section(f, s1->dynsymtab_section);
1460 fclose(f);
1462 #endif
1464 /* ------------------------------------------------------------- */
1465 /* helper function for load/store to insert one more indirection */
1467 #if defined TCC_TARGET_I386 || defined TCC_TARGET_X86_64
1468 ST_FUNC SValue *pe_getimport(SValue *sv, SValue *v2)
1470 int r2;
1471 if ((sv->r & (VT_VALMASK|VT_SYM)) != (VT_CONST|VT_SYM) || (sv->r2 != VT_CONST))
1472 return sv;
1473 if (!sv->sym->a.dllimport)
1474 return sv;
1475 // printf("import %04x %04x %04x %s\n", sv->type.t, sv->sym->type.t, sv->r, get_tok_str(sv->sym->v, NULL));
1476 memset(v2, 0, sizeof *v2);
1477 v2->type.t = VT_PTR;
1478 v2->r = VT_CONST | VT_SYM | VT_LVAL;
1479 v2->sym = sv->sym;
1481 r2 = get_reg(RC_INT);
1482 load(r2, v2);
1483 v2->r = r2;
1484 if ((uint32_t)sv->c.i) {
1485 vpushv(v2);
1486 vpushi(sv->c.i);
1487 gen_opi('+');
1488 *v2 = *vtop--;
1490 v2->type.t = sv->type.t;
1491 v2->r |= sv->r & VT_LVAL;
1492 return v2;
1494 #endif
1496 ST_FUNC int pe_putimport(TCCState *s1, int dllindex, const char *name, addr_t value)
1498 return set_elf_sym(
1499 s1->dynsymtab_section,
1500 value,
1501 dllindex, /* st_size */
1502 ELFW(ST_INFO)(STB_GLOBAL, STT_NOTYPE),
1504 value ? SHN_ABS : SHN_UNDEF,
1505 name
1509 static int add_dllref(TCCState *s1, const char *dllname)
1511 DLLReference *dllref;
1512 int i;
1513 for (i = 0; i < s1->nb_loaded_dlls; ++i)
1514 if (0 == strcmp(s1->loaded_dlls[i]->name, dllname))
1515 return i + 1;
1516 dllref = tcc_mallocz(sizeof(DLLReference) + strlen(dllname));
1517 strcpy(dllref->name, dllname);
1518 dynarray_add(&s1->loaded_dlls, &s1->nb_loaded_dlls, dllref);
1519 return s1->nb_loaded_dlls;
1522 /* ------------------------------------------------------------- */
1524 static int read_mem(int fd, unsigned offset, void *buffer, unsigned len)
1526 lseek(fd, offset, SEEK_SET);
1527 return len == read(fd, buffer, len);
1530 /* ------------------------------------------------------------- */
1532 PUB_FUNC int tcc_get_dllexports(const char *filename, char **pp)
1534 int l, i, n, n0, ret;
1535 char *p;
1536 int fd;
1538 IMAGE_SECTION_HEADER ish;
1539 IMAGE_EXPORT_DIRECTORY ied;
1540 IMAGE_DOS_HEADER dh;
1541 IMAGE_FILE_HEADER ih;
1542 DWORD sig, ref, addr, ptr, namep;
1544 int pef_hdroffset, opt_hdroffset, sec_hdroffset;
1546 n = n0 = 0;
1547 p = NULL;
1548 ret = -1;
1550 fd = open(filename, O_RDONLY | O_BINARY);
1551 if (fd < 0)
1552 goto the_end_1;
1553 ret = 1;
1554 if (!read_mem(fd, 0, &dh, sizeof dh))
1555 goto the_end;
1556 if (!read_mem(fd, dh.e_lfanew, &sig, sizeof sig))
1557 goto the_end;
1558 if (sig != 0x00004550)
1559 goto the_end;
1560 pef_hdroffset = dh.e_lfanew + sizeof sig;
1561 if (!read_mem(fd, pef_hdroffset, &ih, sizeof ih))
1562 goto the_end;
1563 opt_hdroffset = pef_hdroffset + sizeof ih;
1564 if (ih.Machine == 0x014C) {
1565 IMAGE_OPTIONAL_HEADER32 oh;
1566 sec_hdroffset = opt_hdroffset + sizeof oh;
1567 if (!read_mem(fd, opt_hdroffset, &oh, sizeof oh))
1568 goto the_end;
1569 if (IMAGE_DIRECTORY_ENTRY_EXPORT >= oh.NumberOfRvaAndSizes)
1570 goto the_end_0;
1571 addr = oh.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress;
1572 } else if (ih.Machine == 0x8664) {
1573 IMAGE_OPTIONAL_HEADER64 oh;
1574 sec_hdroffset = opt_hdroffset + sizeof oh;
1575 if (!read_mem(fd, opt_hdroffset, &oh, sizeof oh))
1576 goto the_end;
1577 if (IMAGE_DIRECTORY_ENTRY_EXPORT >= oh.NumberOfRvaAndSizes)
1578 goto the_end_0;
1579 addr = oh.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress;
1580 } else
1581 goto the_end;
1583 //printf("addr: %08x\n", addr);
1584 for (i = 0; i < ih.NumberOfSections; ++i) {
1585 if (!read_mem(fd, sec_hdroffset + i * sizeof ish, &ish, sizeof ish))
1586 goto the_end;
1587 //printf("vaddr: %08x\n", ish.VirtualAddress);
1588 if (addr >= ish.VirtualAddress && addr < ish.VirtualAddress + ish.SizeOfRawData)
1589 goto found;
1591 goto the_end_0;
1593 found:
1594 ref = ish.VirtualAddress - ish.PointerToRawData;
1595 if (!read_mem(fd, addr - ref, &ied, sizeof ied))
1596 goto the_end;
1598 namep = ied.AddressOfNames - ref;
1599 for (i = 0; i < ied.NumberOfNames; ++i) {
1600 if (!read_mem(fd, namep, &ptr, sizeof ptr))
1601 goto the_end;
1602 namep += sizeof ptr;
1603 for (l = 0;;) {
1604 if (n+1 >= n0)
1605 p = tcc_realloc(p, n0 = n0 ? n0 * 2 : 256);
1606 if (!read_mem(fd, ptr - ref + l++, p + n, 1)) {
1607 tcc_free(p), p = NULL;
1608 goto the_end;
1610 if (p[n++] == 0)
1611 break;
1614 if (p)
1615 p[n] = 0;
1616 the_end_0:
1617 ret = 0;
1618 the_end:
1619 close(fd);
1620 the_end_1:
1621 *pp = p;
1622 return ret;
1625 /* -------------------------------------------------------------
1626 * This is for compiled windows resources in 'coff' format
1627 * as generated by 'windres.exe -O coff ...'.
1630 static int pe_load_res(TCCState *s1, int fd)
1632 struct pe_rsrc_header hdr;
1633 Section *rsrc_section;
1634 int i, ret = -1, sym_index;
1635 BYTE *ptr;
1636 unsigned offs;
1638 if (!read_mem(fd, 0, &hdr, sizeof hdr))
1639 goto quit;
1641 if (hdr.filehdr.Machine != IMAGE_FILE_MACHINE
1642 || hdr.filehdr.NumberOfSections != 1
1643 || strcmp((char*)hdr.sectionhdr.Name, ".rsrc") != 0)
1644 goto quit;
1646 rsrc_section = new_section(s1, ".rsrc", SHT_PROGBITS, SHF_ALLOC);
1647 ptr = section_ptr_add(rsrc_section, hdr.sectionhdr.SizeOfRawData);
1648 offs = hdr.sectionhdr.PointerToRawData;
1649 if (!read_mem(fd, offs, ptr, hdr.sectionhdr.SizeOfRawData))
1650 goto quit;
1651 offs = hdr.sectionhdr.PointerToRelocations;
1652 sym_index = put_elf_sym(symtab_section, 0, 0, 0, 0, rsrc_section->sh_num, ".rsrc");
1653 for (i = 0; i < hdr.sectionhdr.NumberOfRelocations; ++i) {
1654 struct pe_rsrc_reloc rel;
1655 if (!read_mem(fd, offs, &rel, sizeof rel))
1656 goto quit;
1657 // printf("rsrc_reloc: %x %x %x\n", rel.offset, rel.size, rel.type);
1658 if (rel.type != RSRC_RELTYPE)
1659 goto quit;
1660 put_elf_reloc(symtab_section, rsrc_section,
1661 rel.offset, R_XXX_RELATIVE, sym_index);
1662 offs += sizeof rel;
1664 ret = 0;
1665 quit:
1666 return ret;
1669 /* ------------------------------------------------------------- */
1671 static char *trimfront(char *p)
1673 while (*p && (unsigned char)*p <= ' ')
1674 ++p;
1675 return p;
1678 static char *trimback(char *a, char *e)
1680 while (e > a && (unsigned char)e[-1] <= ' ')
1681 --e;
1682 *e = 0;;
1683 return a;
1686 /* ------------------------------------------------------------- */
1687 static int pe_load_def(TCCState *s1, int fd)
1689 int state = 0, ret = -1, dllindex = 0, ord;
1690 char line[400], dllname[80], *p, *x;
1691 FILE *fp;
1693 fp = fdopen(dup(fd), "rb");
1694 while (fgets(line, sizeof line, fp))
1696 p = trimfront(trimback(line, strchr(line, 0)));
1697 if (0 == *p || ';' == *p)
1698 continue;
1700 switch (state) {
1701 case 0:
1702 if (0 != strnicmp(p, "LIBRARY", 7))
1703 goto quit;
1704 pstrcpy(dllname, sizeof dllname, trimfront(p+7));
1705 ++state;
1706 continue;
1708 case 1:
1709 if (0 != stricmp(p, "EXPORTS"))
1710 goto quit;
1711 ++state;
1712 continue;
1714 case 2:
1715 dllindex = add_dllref(s1, dllname);
1716 ++state;
1717 /* fall through */
1718 default:
1719 /* get ordinal and will store in sym->st_value */
1720 ord = 0;
1721 x = strchr(p, ' ');
1722 if (x) {
1723 *x = 0, x = strrchr(x + 1, '@');
1724 if (x) {
1725 char *d;
1726 ord = (int)strtol(x + 1, &d, 10);
1727 if (*d)
1728 ord = 0;
1731 pe_putimport(s1, dllindex, p, ord);
1732 continue;
1735 ret = 0;
1736 quit:
1737 fclose(fp);
1738 return ret;
1741 /* ------------------------------------------------------------- */
1742 static int pe_load_dll(TCCState *s1, const char *filename)
1744 char *p, *q;
1745 int index, ret;
1747 ret = tcc_get_dllexports(filename, &p);
1748 if (ret) {
1749 return -1;
1750 } else if (p) {
1751 index = add_dllref(s1, tcc_basename(filename));
1752 for (q = p; *q; q += 1 + strlen(q))
1753 pe_putimport(s1, index, q, 0);
1754 tcc_free(p);
1756 return 0;
1759 /* ------------------------------------------------------------- */
1760 ST_FUNC int pe_load_file(struct TCCState *s1, const char *filename, int fd)
1762 int ret = -1;
1763 char buf[10];
1764 if (0 == strcmp(tcc_fileextension(filename), ".def"))
1765 ret = pe_load_def(s1, fd);
1766 else if (pe_load_res(s1, fd) == 0)
1767 ret = 0;
1768 else if (read_mem(fd, 0, buf, 4) && 0 == memcmp(buf, "MZ", 2))
1769 ret = pe_load_dll(s1, filename);
1770 return ret;
1773 /* ------------------------------------------------------------- */
1774 #ifdef TCC_TARGET_X86_64
1775 static unsigned pe_add_uwwind_info(TCCState *s1)
1777 if (NULL == s1->uw_pdata) {
1778 s1->uw_pdata = find_section(s1, ".pdata");
1779 s1->uw_pdata->sh_addralign = 4;
1781 if (0 == s1->uw_sym)
1782 s1->uw_sym = put_elf_sym(symtab_section, 0, 0, 0, 0, text_section->sh_num, ".uw_base");
1783 if (0 == s1->uw_offs) {
1784 /* As our functions all have the same stackframe, we use one entry for all */
1785 static const unsigned char uw_info[] = {
1786 0x01, // UBYTE: 3 Version , UBYTE: 5 Flags
1787 0x04, // UBYTE Size of prolog
1788 0x02, // UBYTE Count of unwind codes
1789 0x05, // UBYTE: 4 Frame Register (rbp), UBYTE: 4 Frame Register offset (scaled)
1790 // USHORT * n Unwind codes array
1791 // 0x0b, 0x01, 0xff, 0xff, // stack size
1792 0x04, 0x03, // set frame ptr (mov rsp -> rbp)
1793 0x01, 0x50 // push reg (rbp)
1796 Section *s = text_section;
1797 unsigned char *p;
1799 section_ptr_add(s, -s->data_offset & 3); /* align */
1800 s1->uw_offs = s->data_offset;
1801 p = section_ptr_add(s, sizeof uw_info);
1802 memcpy(p, uw_info, sizeof uw_info);
1805 return s1->uw_offs;
1808 ST_FUNC void pe_add_unwind_data(unsigned start, unsigned end, unsigned stack)
1810 TCCState *s1 = tcc_state;
1811 Section *pd;
1812 unsigned o, n, d;
1813 struct /* _RUNTIME_FUNCTION */ {
1814 DWORD BeginAddress;
1815 DWORD EndAddress;
1816 DWORD UnwindData;
1817 } *p;
1819 d = pe_add_uwwind_info(s1);
1820 pd = s1->uw_pdata;
1821 o = pd->data_offset;
1822 p = section_ptr_add(pd, sizeof *p);
1824 /* record this function */
1825 p->BeginAddress = start;
1826 p->EndAddress = end;
1827 p->UnwindData = d;
1829 /* put relocations on it */
1830 for (n = o + sizeof *p; o < n; o += sizeof p->BeginAddress)
1831 put_elf_reloc(symtab_section, pd, o, R_XXX_RELATIVE, s1->uw_sym);
1833 #endif
1834 /* ------------------------------------------------------------- */
1835 #ifdef TCC_TARGET_X86_64
1836 #define PE_STDSYM(n,s) n
1837 #else
1838 #define PE_STDSYM(n,s) "_" n s
1839 #endif
1841 static void tcc_add_support(TCCState *s1, const char *filename)
1843 if (tcc_add_dll(s1, filename, 0) < 0)
1844 tcc_error_noabort("%s not found", filename);
1847 static void pe_add_runtime(TCCState *s1, struct pe_info *pe)
1849 const char *start_symbol;
1850 int pe_type = 0;
1851 int unicode_entry = 0;
1853 if (find_elf_sym(symtab_section, PE_STDSYM("WinMain","@16")))
1854 pe_type = PE_GUI;
1855 else
1856 if (find_elf_sym(symtab_section, PE_STDSYM("wWinMain","@16"))) {
1857 pe_type = PE_GUI;
1858 unicode_entry = PE_GUI;
1860 else
1861 if (TCC_OUTPUT_DLL == s1->output_type) {
1862 pe_type = PE_DLL;
1863 /* need this for 'tccelf.c:relocate_section()' */
1864 s1->output_type = TCC_OUTPUT_EXE;
1866 else {
1867 pe_type = PE_EXE;
1868 if (find_elf_sym(symtab_section, "wmain"))
1869 unicode_entry = PE_EXE;
1872 start_symbol =
1873 TCC_OUTPUT_MEMORY == s1->output_type
1874 ? PE_GUI == pe_type ? (unicode_entry ? "__runwwinmain" : "__runwinmain")
1875 : (unicode_entry ? "__runwmain" : "__runmain")
1876 : PE_DLL == pe_type ? PE_STDSYM("__dllstart","@12")
1877 : PE_GUI == pe_type ? (unicode_entry ? "__wwinstart": "__winstart")
1878 : (unicode_entry ? "__wstart" : "__start")
1881 if (!s1->leading_underscore || strchr(start_symbol, '@'))
1882 ++start_symbol;
1884 /* grab the startup code from libtcc1 */
1885 #ifdef TCC_IS_NATIVE
1886 if (TCC_OUTPUT_MEMORY != s1->output_type || s1->runtime_main)
1887 #endif
1888 set_elf_sym(symtab_section,
1889 0, 0,
1890 ELFW(ST_INFO)(STB_GLOBAL, STT_NOTYPE), 0,
1891 SHN_UNDEF, start_symbol);
1893 if (0 == s1->nostdlib) {
1894 static const char *libs[] = {
1895 "msvcrt", "kernel32", "", "user32", "gdi32", NULL
1897 const char **pp, *p;
1898 #ifdef TCC_IS_NATIVE
1899 if (s1->do_bounds_check)
1900 tcc_add_support(s1, TCC_LIBBCHECK);
1901 #endif
1902 tcc_add_support(s1, TCC_LIBTCC1);
1903 for (pp = libs; 0 != (p = *pp); ++pp) {
1904 if (*p)
1905 tcc_add_library_err(s1, p);
1906 else if (PE_DLL != pe_type && PE_GUI != pe_type)
1907 break;
1910 if (TCC_OUTPUT_MEMORY == s1->output_type)
1911 pe_type = PE_RUN;
1912 pe->type = pe_type;
1913 pe->start_symbol = start_symbol;
1916 static void pe_set_options(TCCState * s1, struct pe_info *pe)
1918 if (PE_DLL == pe->type) {
1919 /* XXX: check if is correct for arm-pe target */
1920 pe->imagebase = 0x10000000;
1921 } else {
1922 #if defined(TCC_TARGET_ARM)
1923 pe->imagebase = 0x00010000;
1924 #else
1925 pe->imagebase = 0x00400000;
1926 #endif
1929 #if defined(TCC_TARGET_ARM)
1930 /* we use "console" subsystem by default */
1931 pe->subsystem = 9;
1932 #else
1933 if (PE_DLL == pe->type || PE_GUI == pe->type)
1934 pe->subsystem = 2;
1935 else
1936 pe->subsystem = 3;
1937 #endif
1938 /* Allow override via -Wl,-subsystem=... option */
1939 if (s1->pe_subsystem != 0)
1940 pe->subsystem = s1->pe_subsystem;
1942 /* set default file/section alignment */
1943 if (pe->subsystem == 1) {
1944 pe->section_align = 0x20;
1945 pe->file_align = 0x20;
1946 } else {
1947 pe->section_align = 0x1000;
1948 pe->file_align = 0x200;
1951 if (s1->section_align != 0)
1952 pe->section_align = s1->section_align;
1953 if (s1->pe_file_align != 0)
1954 pe->file_align = s1->pe_file_align;
1956 if ((pe->subsystem >= 10) && (pe->subsystem <= 12))
1957 pe->imagebase = 0;
1959 if (s1->has_text_addr)
1960 pe->imagebase = s1->text_addr;
1963 ST_FUNC int pe_output_file(TCCState *s1, const char *filename)
1965 int ret;
1966 struct pe_info pe;
1967 int i;
1969 memset(&pe, 0, sizeof pe);
1970 pe.filename = filename;
1971 pe.s1 = s1;
1973 tcc_add_runtime(s1);
1974 pe_add_runtime(s1, &pe);
1975 resolve_common_syms(s1);
1976 pe_set_options(s1, &pe);
1978 ret = pe_check_symbols(&pe);
1979 if (ret)
1981 else if (filename) {
1982 pe_assign_addresses(&pe);
1983 relocate_syms(s1, s1->symtab, 0);
1984 s1->pe_imagebase = pe.imagebase;
1985 for (i = 1; i < s1->nb_sections; ++i) {
1986 Section *s = s1->sections[i];
1987 if (s->reloc) {
1988 relocate_section(s1, s);
1991 pe.start_addr = (DWORD)
1992 ((uintptr_t)tcc_get_symbol_err(s1, pe.start_symbol)
1993 - pe.imagebase);
1994 if (s1->nb_errors)
1995 ret = -1;
1996 else
1997 ret = pe_write(&pe);
1998 tcc_free(pe.sec_info);
1999 } else {
2000 #ifdef TCC_IS_NATIVE
2001 pe.thunk = data_section;
2002 pe_build_imports(&pe);
2003 s1->runtime_main = pe.start_symbol;
2004 #ifdef TCC_TARGET_X86_64
2005 s1->uw_pdata = find_section(s1, ".pdata");
2006 #endif
2007 #endif
2010 pe_free_imports(&pe);
2012 #ifdef PE_PRINT_SECTIONS
2013 pe_print_sections(s1, "tcc.log");
2014 #endif
2015 return ret;
2018 /* ------------------------------------------------------------- */