riscv: fp parameters
[tinycc.git] / tccpe.c
bloba1f73b0d7f794f18c36bd4cfc784bf05ccb58d49
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;
606 op = fopen(pe->filename, "wb");
607 if (NULL == op) {
608 tcc_error_noabort("could not write '%s': %s", pe->filename, strerror(errno));
609 return -1;
612 pe->sizeofheaders = pe_file_align(pe,
613 sizeof (struct pe_header)
614 + pe->sec_count * sizeof (IMAGE_SECTION_HEADER)
617 file_offset = pe->sizeofheaders;
619 if (2 == pe->s1->verbose)
620 printf("-------------------------------"
621 "\n virt file size section" "\n");
622 for (i = 0; i < pe->sec_count; ++i) {
623 DWORD addr, size;
624 const char *sh_name;
626 si = pe->sec_info + i;
627 sh_name = si->name;
628 addr = si->sh_addr - pe->imagebase;
629 size = si->sh_size;
630 psh = &si->ish;
632 if (2 == pe->s1->verbose)
633 printf("%6x %6x %6x %s\n",
634 (unsigned)addr, (unsigned)file_offset, (unsigned)size, sh_name);
636 switch (si->cls) {
637 case sec_text:
638 pe_header.opthdr.BaseOfCode = addr;
639 break;
641 case sec_data:
642 #ifndef TCC_TARGET_X86_64
643 pe_header.opthdr.BaseOfData = addr;
644 #endif
645 break;
647 case sec_bss:
648 break;
650 case sec_reloc:
651 pe_set_datadir(&pe_header, IMAGE_DIRECTORY_ENTRY_BASERELOC, addr, size);
652 break;
654 case sec_rsrc:
655 pe_set_datadir(&pe_header, IMAGE_DIRECTORY_ENTRY_RESOURCE, addr, size);
656 break;
658 case sec_pdata:
659 pe_set_datadir(&pe_header, IMAGE_DIRECTORY_ENTRY_EXCEPTION, addr, size);
660 break;
663 if (pe->thunk == pe->s1->sections[si->ord]) {
664 if (pe->imp_size) {
665 pe_set_datadir(&pe_header, IMAGE_DIRECTORY_ENTRY_IMPORT,
666 pe->imp_offs + addr, pe->imp_size);
667 pe_set_datadir(&pe_header, IMAGE_DIRECTORY_ENTRY_IAT,
668 pe->iat_offs + addr, pe->iat_size);
670 if (pe->exp_size) {
671 pe_set_datadir(&pe_header, IMAGE_DIRECTORY_ENTRY_EXPORT,
672 pe->exp_offs + addr, pe->exp_size);
676 strncpy((char*)psh->Name, sh_name, sizeof psh->Name);
678 psh->Characteristics = si->pe_flags;
679 psh->VirtualAddress = addr;
680 psh->Misc.VirtualSize = size;
681 pe_header.opthdr.SizeOfImage =
682 umax(pe_virtual_align(pe, size + addr), pe_header.opthdr.SizeOfImage);
684 if (si->data_size) {
685 psh->PointerToRawData = file_offset;
686 file_offset = pe_file_align(pe, file_offset + si->data_size);
687 psh->SizeOfRawData = file_offset - psh->PointerToRawData;
688 if (si->cls == sec_text)
689 pe_header.opthdr.SizeOfCode += psh->SizeOfRawData;
690 else
691 pe_header.opthdr.SizeOfInitializedData += psh->SizeOfRawData;
695 //pe_header.filehdr.TimeDateStamp = time(NULL);
696 pe_header.filehdr.NumberOfSections = pe->sec_count;
697 pe_header.opthdr.AddressOfEntryPoint = pe->start_addr;
698 pe_header.opthdr.SizeOfHeaders = pe->sizeofheaders;
699 pe_header.opthdr.ImageBase = pe->imagebase;
700 pe_header.opthdr.Subsystem = pe->subsystem;
701 if (pe->s1->pe_stack_size)
702 pe_header.opthdr.SizeOfStackReserve = pe->s1->pe_stack_size;
703 if (PE_DLL == pe->type)
704 pe_header.filehdr.Characteristics = CHARACTERISTICS_DLL;
705 pe_header.filehdr.Characteristics |= pe->s1->pe_characteristics;
707 sum = 0;
708 pe_fwrite(&pe_header, sizeof pe_header, op, &sum);
709 for (i = 0; i < pe->sec_count; ++i)
710 pe_fwrite(&pe->sec_info[i].ish, sizeof(IMAGE_SECTION_HEADER), op, &sum);
711 pe_fpad(op, pe->sizeofheaders);
712 for (i = 0; i < pe->sec_count; ++i) {
713 si = pe->sec_info + i;
714 psh = &si->ish;
715 if (si->data_size) {
716 pe_fwrite(si->data, si->data_size, op, &sum);
717 file_offset = psh->PointerToRawData + psh->SizeOfRawData;
718 pe_fpad(op, file_offset);
722 pe_header.opthdr.CheckSum = sum + file_offset;
723 fseek(op, offsetof(struct pe_header, opthdr.CheckSum), SEEK_SET);
724 pe_fwrite(&pe_header.opthdr.CheckSum, sizeof pe_header.opthdr.CheckSum, op, NULL);
725 fclose (op);
726 #ifndef _WIN32
727 chmod(pe->filename, 0777);
728 #endif
730 if (2 == pe->s1->verbose)
731 printf("-------------------------------\n");
732 if (pe->s1->verbose)
733 printf("<- %s (%u bytes)\n", pe->filename, (unsigned)file_offset);
735 return 0;
738 /*----------------------------------------------------------------------------*/
740 static struct import_symbol *pe_add_import(struct pe_info *pe, int sym_index)
742 int i;
743 int dll_index;
744 struct pe_import_info *p;
745 struct import_symbol *s;
746 ElfW(Sym) *isym;
748 isym = (ElfW(Sym) *)pe->s1->dynsymtab_section->data + sym_index;
749 dll_index = isym->st_size;
751 i = dynarray_assoc ((void**)pe->imp_info, pe->imp_count, dll_index);
752 if (-1 != i) {
753 p = pe->imp_info[i];
754 goto found_dll;
756 p = tcc_mallocz(sizeof *p);
757 p->dll_index = dll_index;
758 dynarray_add(&pe->imp_info, &pe->imp_count, p);
760 found_dll:
761 i = dynarray_assoc ((void**)p->symbols, p->sym_count, sym_index);
762 if (-1 != i)
763 return p->symbols[i];
765 s = tcc_mallocz(sizeof *s);
766 dynarray_add(&p->symbols, &p->sym_count, s);
767 s->sym_index = sym_index;
768 return s;
771 void pe_free_imports(struct pe_info *pe)
773 int i;
774 for (i = 0; i < pe->imp_count; ++i) {
775 struct pe_import_info *p = pe->imp_info[i];
776 dynarray_reset(&p->symbols, &p->sym_count);
778 dynarray_reset(&pe->imp_info, &pe->imp_count);
781 /*----------------------------------------------------------------------------*/
782 static void pe_build_imports(struct pe_info *pe)
784 int thk_ptr, ent_ptr, dll_ptr, sym_cnt, i;
785 DWORD rva_base = pe->thunk->sh_addr - pe->imagebase;
786 int ndlls = pe->imp_count;
788 for (sym_cnt = i = 0; i < ndlls; ++i)
789 sym_cnt += pe->imp_info[i]->sym_count;
791 if (0 == sym_cnt)
792 return;
794 pe_align_section(pe->thunk, 16);
796 pe->imp_offs = dll_ptr = pe->thunk->data_offset;
797 pe->imp_size = (ndlls + 1) * sizeof(IMAGE_IMPORT_DESCRIPTOR);
798 pe->iat_offs = dll_ptr + pe->imp_size;
799 pe->iat_size = (sym_cnt + ndlls) * sizeof(ADDR3264);
800 section_ptr_add(pe->thunk, pe->imp_size + 2*pe->iat_size);
802 thk_ptr = pe->iat_offs;
803 ent_ptr = pe->iat_offs + pe->iat_size;
805 for (i = 0; i < pe->imp_count; ++i) {
806 IMAGE_IMPORT_DESCRIPTOR *hdr;
807 int k, n, dllindex;
808 ADDR3264 v;
809 struct pe_import_info *p = pe->imp_info[i];
810 const char *name;
811 DLLReference *dllref;
813 dllindex = p->dll_index;
814 if (dllindex)
815 name = (dllref = pe->s1->loaded_dlls[dllindex-1])->name;
816 else
817 name = "", dllref = NULL;
819 /* put the dll name into the import header */
820 v = put_elf_str(pe->thunk, name);
821 hdr = (IMAGE_IMPORT_DESCRIPTOR*)(pe->thunk->data + dll_ptr);
822 hdr->FirstThunk = thk_ptr + rva_base;
823 hdr->OriginalFirstThunk = ent_ptr + rva_base;
824 hdr->Name = v + rva_base;
826 for (k = 0, n = p->sym_count; k <= n; ++k) {
827 if (k < n) {
828 int iat_index = p->symbols[k]->iat_index;
829 int sym_index = p->symbols[k]->sym_index;
830 ElfW(Sym) *imp_sym = (ElfW(Sym) *)pe->s1->dynsymtab_section->data + sym_index;
831 ElfW(Sym) *org_sym = (ElfW(Sym) *)symtab_section->data + iat_index;
832 const char *name = (char*)pe->s1->dynsymtab_section->link->data + imp_sym->st_name;
833 int ordinal;
835 org_sym->st_value = thk_ptr;
836 org_sym->st_shndx = pe->thunk->sh_num;
838 if (dllref)
839 v = 0, ordinal = imp_sym->st_value; /* ordinal from pe_load_def */
840 else
841 ordinal = 0, v = imp_sym->st_value; /* address from tcc_add_symbol() */
843 #ifdef TCC_IS_NATIVE
844 if (pe->type == PE_RUN) {
845 if (dllref) {
846 if ( !dllref->handle )
847 dllref->handle = LoadLibrary(dllref->name);
848 v = (ADDR3264)GetProcAddress(dllref->handle, ordinal?(char*)0+ordinal:name);
850 if (!v)
851 tcc_error_noabort("can't build symbol '%s'", name);
852 } else
853 #endif
854 if (ordinal) {
855 v = ordinal | (ADDR3264)1 << (sizeof(ADDR3264)*8 - 1);
856 } else {
857 v = pe->thunk->data_offset + rva_base;
858 section_ptr_add(pe->thunk, sizeof(WORD)); /* hint, not used */
859 put_elf_str(pe->thunk, name);
862 } else {
863 v = 0; /* last entry is zero */
866 *(ADDR3264*)(pe->thunk->data+thk_ptr) =
867 *(ADDR3264*)(pe->thunk->data+ent_ptr) = v;
868 thk_ptr += sizeof (ADDR3264);
869 ent_ptr += sizeof (ADDR3264);
871 dll_ptr += sizeof(IMAGE_IMPORT_DESCRIPTOR);
875 /* ------------------------------------------------------------- */
877 struct pe_sort_sym
879 int index;
880 const char *name;
883 static int sym_cmp(const void *va, const void *vb)
885 const char *ca = (*(struct pe_sort_sym**)va)->name;
886 const char *cb = (*(struct pe_sort_sym**)vb)->name;
887 return strcmp(ca, cb);
890 static void pe_build_exports(struct pe_info *pe)
892 ElfW(Sym) *sym;
893 int sym_index, sym_end;
894 DWORD rva_base, func_o, name_o, ord_o, str_o;
895 IMAGE_EXPORT_DIRECTORY *hdr;
896 int sym_count, ord;
897 struct pe_sort_sym **sorted, *p;
899 FILE *op;
900 char buf[260];
901 const char *dllname;
902 const char *name;
904 rva_base = pe->thunk->sh_addr - pe->imagebase;
905 sym_count = 0, sorted = NULL, op = NULL;
907 sym_end = symtab_section->data_offset / sizeof(ElfW(Sym));
908 for (sym_index = 1; sym_index < sym_end; ++sym_index) {
909 sym = (ElfW(Sym)*)symtab_section->data + sym_index;
910 name = pe_export_name(pe->s1, sym);
911 if ((sym->st_other & ST_PE_EXPORT)
912 /* export only symbols from actually written sections */
913 && pe->s1->sections[sym->st_shndx]->sh_addr) {
914 p = tcc_malloc(sizeof *p);
915 p->index = sym_index;
916 p->name = name;
917 dynarray_add(&sorted, &sym_count, p);
919 #if 0
920 if (sym->st_other & ST_PE_EXPORT)
921 printf("export: %s\n", name);
922 if (sym->st_other & ST_PE_STDCALL)
923 printf("stdcall: %s\n", name);
924 #endif
927 if (0 == sym_count)
928 return;
930 qsort (sorted, sym_count, sizeof *sorted, sym_cmp);
932 pe_align_section(pe->thunk, 16);
933 dllname = tcc_basename(pe->filename);
935 pe->exp_offs = pe->thunk->data_offset;
936 func_o = pe->exp_offs + sizeof(IMAGE_EXPORT_DIRECTORY);
937 name_o = func_o + sym_count * sizeof (DWORD);
938 ord_o = name_o + sym_count * sizeof (DWORD);
939 str_o = ord_o + sym_count * sizeof(WORD);
941 hdr = section_ptr_add(pe->thunk, str_o - pe->exp_offs);
942 hdr->Characteristics = 0;
943 hdr->Base = 1;
944 hdr->NumberOfFunctions = sym_count;
945 hdr->NumberOfNames = sym_count;
946 hdr->AddressOfFunctions = func_o + rva_base;
947 hdr->AddressOfNames = name_o + rva_base;
948 hdr->AddressOfNameOrdinals = ord_o + rva_base;
949 hdr->Name = str_o + rva_base;
950 put_elf_str(pe->thunk, dllname);
952 #if 1
953 /* automatically write exports to <output-filename>.def */
954 pstrcpy(buf, sizeof buf, pe->filename);
955 strcpy(tcc_fileextension(buf), ".def");
956 op = fopen(buf, "wb");
957 if (NULL == op) {
958 tcc_error_noabort("could not create '%s': %s", buf, strerror(errno));
959 } else {
960 fprintf(op, "LIBRARY %s\n\nEXPORTS\n", dllname);
961 if (pe->s1->verbose)
962 printf("<- %s (%d symbol%s)\n", buf, sym_count, &"s"[sym_count < 2]);
964 #endif
966 for (ord = 0; ord < sym_count; ++ord)
968 p = sorted[ord], sym_index = p->index, name = p->name;
969 /* insert actual address later in relocate_section() */
970 put_elf_reloc(symtab_section, pe->thunk,
971 func_o, R_XXX_RELATIVE, sym_index);
972 *(DWORD*)(pe->thunk->data + name_o)
973 = pe->thunk->data_offset + rva_base;
974 *(WORD*)(pe->thunk->data + ord_o)
975 = ord;
976 put_elf_str(pe->thunk, name);
977 func_o += sizeof (DWORD);
978 name_o += sizeof (DWORD);
979 ord_o += sizeof (WORD);
980 if (op)
981 fprintf(op, "%s\n", name);
983 pe->exp_size = pe->thunk->data_offset - pe->exp_offs;
984 dynarray_reset(&sorted, &sym_count);
985 if (op)
986 fclose(op);
989 /* ------------------------------------------------------------- */
990 static void pe_build_reloc (struct pe_info *pe)
992 DWORD offset, block_ptr, addr;
993 int count, i;
994 ElfW_Rel *rel, *rel_end;
995 Section *s = NULL, *sr;
997 offset = addr = block_ptr = count = i = 0;
998 rel = rel_end = NULL;
1000 for(;;) {
1001 if (rel < rel_end) {
1002 int type = ELFW(R_TYPE)(rel->r_info);
1003 addr = rel->r_offset + s->sh_addr;
1004 ++ rel;
1005 if (type != REL_TYPE_DIRECT)
1006 continue;
1007 if (count == 0) { /* new block */
1008 block_ptr = pe->reloc->data_offset;
1009 section_ptr_add(pe->reloc, sizeof(struct pe_reloc_header));
1010 offset = addr & 0xFFFFFFFF<<12;
1012 if ((addr -= offset) < (1<<12)) { /* one block spans 4k addresses */
1013 WORD *wp = section_ptr_add(pe->reloc, sizeof (WORD));
1014 *wp = addr | PE_IMAGE_REL<<12;
1015 ++count;
1016 continue;
1018 -- rel;
1020 } else if (i < pe->sec_count) {
1021 sr = (s = pe->s1->sections[pe->sec_info[i++].ord])->reloc;
1022 if (sr) {
1023 rel = (ElfW_Rel *)sr->data;
1024 rel_end = (ElfW_Rel *)(sr->data + sr->data_offset);
1026 continue;
1029 if (count) {
1030 /* store the last block and ready for a new one */
1031 struct pe_reloc_header *hdr;
1032 if (count & 1) /* align for DWORDS */
1033 section_ptr_add(pe->reloc, sizeof(WORD)), ++count;
1034 hdr = (struct pe_reloc_header *)(pe->reloc->data + block_ptr);
1035 hdr -> offset = offset - pe->imagebase;
1036 hdr -> size = count * sizeof(WORD) + sizeof(struct pe_reloc_header);
1037 count = 0;
1040 if (rel >= rel_end)
1041 break;
1045 /* ------------------------------------------------------------- */
1046 static int pe_section_class(Section *s)
1048 int type, flags;
1049 const char *name;
1051 type = s->sh_type;
1052 flags = s->sh_flags;
1053 name = s->name;
1054 if (flags & SHF_ALLOC) {
1055 if (type == SHT_PROGBITS) {
1056 if (flags & SHF_EXECINSTR)
1057 return sec_text;
1058 if (flags & SHF_WRITE)
1059 return sec_data;
1060 if (0 == strcmp(name, ".rsrc"))
1061 return sec_rsrc;
1062 if (0 == strcmp(name, ".iedat"))
1063 return sec_idata;
1064 if (0 == strcmp(name, ".pdata"))
1065 return sec_pdata;
1066 } else if (type == SHT_NOBITS) {
1067 if (flags & SHF_WRITE)
1068 return sec_bss;
1070 return sec_other;
1071 } else {
1072 if (0 == strcmp(name, ".reloc"))
1073 return sec_reloc;
1074 if (0 == memcmp(name, ".stab", 5))
1075 return sec_stab;
1077 return -1;
1080 static int pe_assign_addresses (struct pe_info *pe)
1082 int i, k, o, c;
1083 DWORD addr;
1084 int *section_order;
1085 struct section_info *si;
1086 Section *s;
1088 if (PE_DLL == pe->type)
1089 pe->reloc = new_section(pe->s1, ".reloc", SHT_PROGBITS, 0);
1091 // pe->thunk = new_section(pe->s1, ".iedat", SHT_PROGBITS, SHF_ALLOC);
1093 section_order = tcc_malloc(pe->s1->nb_sections * sizeof (int));
1094 for (o = k = 0 ; k < sec_last; ++k) {
1095 for (i = 1; i < pe->s1->nb_sections; ++i) {
1096 s = pe->s1->sections[i];
1097 if (k == pe_section_class(s)) {
1098 // printf("%s %d\n", s->name, k);
1099 s->sh_addr = pe->imagebase;
1100 section_order[o++] = i;
1105 pe->sec_info = tcc_mallocz(o * sizeof (struct section_info));
1106 addr = pe->imagebase + 1;
1108 for (i = 0; i < o; ++i)
1110 k = section_order[i];
1111 s = pe->s1->sections[k];
1112 c = pe_section_class(s);
1113 si = &pe->sec_info[pe->sec_count];
1115 #ifdef PE_MERGE_DATA
1116 if (c == sec_bss && pe->sec_count && si[-1].cls == sec_data) {
1117 /* append .bss to .data */
1118 s->sh_addr = addr = ((addr-1) | (s->sh_addralign-1)) + 1;
1119 addr += s->data_offset;
1120 si[-1].sh_size = addr - si[-1].sh_addr;
1121 continue;
1123 #endif
1124 if (c == sec_stab && 0 == pe->s1->do_debug)
1125 continue;
1127 strcpy(si->name, s->name);
1128 si->cls = c;
1129 si->ord = k;
1130 si->sh_addr = s->sh_addr = addr = pe_virtual_align(pe, addr);
1132 si->pe_flags = IMAGE_SCN_MEM_READ;
1133 if (s->sh_flags & SHF_EXECINSTR)
1134 si->pe_flags |= IMAGE_SCN_MEM_EXECUTE | IMAGE_SCN_CNT_CODE;
1135 else if (s->sh_type == SHT_NOBITS)
1136 si->pe_flags |= IMAGE_SCN_CNT_UNINITIALIZED_DATA;
1137 else
1138 si->pe_flags |= IMAGE_SCN_CNT_INITIALIZED_DATA;
1139 if (s->sh_flags & SHF_WRITE)
1140 si->pe_flags |= IMAGE_SCN_MEM_WRITE;
1141 if (0 == (s->sh_flags & SHF_ALLOC)) {
1142 si->pe_flags |= IMAGE_SCN_MEM_DISCARDABLE;
1143 if (c == sec_stab)
1144 si->pe_flags |= 0x802; //IMAGE_SCN_TYPE_NOLOAD|IMAGE_SCN_LNK_REMOVE
1147 if (c == sec_data && NULL == pe->thunk)
1148 pe->thunk = s;
1150 if (s == pe->thunk) {
1151 pe_build_imports(pe);
1152 pe_build_exports(pe);
1155 if (c == sec_reloc)
1156 pe_build_reloc (pe);
1158 if (s->data_offset)
1160 if (s->sh_type != SHT_NOBITS) {
1161 si->data = s->data;
1162 si->data_size = s->data_offset;
1165 addr += s->data_offset;
1166 si->sh_size = s->data_offset;
1167 ++pe->sec_count;
1169 //printf("%08x %05x %s %08x\n", si->sh_addr, si->sh_size, si->name, si->pe_flags);
1171 #if 0
1172 for (i = 1; i < pe->s1->nb_sections; ++i) {
1173 Section *s = pe->s1->sections[i];
1174 int type = s->sh_type;
1175 int flags = s->sh_flags;
1176 printf("section %-16s %-10s %5x %s,%s,%s\n",
1177 s->name,
1178 type == SHT_PROGBITS ? "progbits" :
1179 type == SHT_NOBITS ? "nobits" :
1180 type == SHT_SYMTAB ? "symtab" :
1181 type == SHT_STRTAB ? "strtab" :
1182 type == SHT_RELX ? "rel" : "???",
1183 s->data_offset,
1184 flags & SHF_ALLOC ? "alloc" : "",
1185 flags & SHF_WRITE ? "write" : "",
1186 flags & SHF_EXECINSTR ? "exec" : ""
1189 pe->s1->verbose = 2;
1190 #endif
1192 tcc_free(section_order);
1193 return 0;
1196 /*----------------------------------------------------------------------------*/
1198 static int pe_isafunc(int sym_index)
1200 Section *sr = text_section->reloc;
1201 ElfW_Rel *rel, *rel_end;
1202 Elf32_Word info = ELF32_R_INFO(sym_index, R_386_PC32);
1203 if (!sr)
1204 return 0;
1205 rel_end = (ElfW_Rel *)(sr->data + sr->data_offset);
1206 for (rel = (ElfW_Rel *)sr->data; rel < rel_end; rel++)
1207 if (rel->r_info == info)
1208 return 1;
1209 return 0;
1212 /*----------------------------------------------------------------------------*/
1213 static int pe_check_symbols(struct pe_info *pe)
1215 ElfW(Sym) *sym;
1216 int sym_index, sym_end;
1217 int ret = 0;
1219 pe_align_section(text_section, 8);
1221 sym_end = symtab_section->data_offset / sizeof(ElfW(Sym));
1222 for (sym_index = 1; sym_index < sym_end; ++sym_index) {
1224 sym = (ElfW(Sym) *)symtab_section->data + sym_index;
1225 if (sym->st_shndx == SHN_UNDEF) {
1227 const char *name = (char*)symtab_section->link->data + sym->st_name;
1228 unsigned type = ELFW(ST_TYPE)(sym->st_info);
1229 int imp_sym = pe_find_import(pe->s1, sym);
1230 struct import_symbol *is;
1232 if (imp_sym <= 0)
1233 goto not_found;
1235 if (type == STT_NOTYPE) {
1236 /* symbols from assembler have no type, find out which */
1237 if (pe_isafunc(sym_index))
1238 type = STT_FUNC;
1239 else
1240 type = STT_OBJECT;
1243 is = pe_add_import(pe, imp_sym);
1245 if (type == STT_FUNC) {
1246 unsigned long offset = is->thk_offset;
1247 if (offset) {
1248 /* got aliased symbol, like stricmp and _stricmp */
1250 } else {
1251 char buffer[100];
1252 WORD *p;
1254 offset = text_section->data_offset;
1255 /* add the 'jmp IAT[x]' instruction */
1256 #ifdef TCC_TARGET_ARM
1257 p = section_ptr_add(text_section, 8+4); // room for code and address
1258 (*(DWORD*)(p)) = 0xE59FC000; // arm code ldr ip, [pc] ; PC+8+0 = 0001xxxx
1259 (*(DWORD*)(p+2)) = 0xE59CF000; // arm code ldr pc, [ip]
1260 #else
1261 p = section_ptr_add(text_section, 8);
1262 *p = 0x25FF;
1263 #ifdef TCC_TARGET_X86_64
1264 *(DWORD*)(p+1) = (DWORD)-4;
1265 #endif
1266 #endif
1267 /* add a helper symbol, will be patched later in
1268 pe_build_imports */
1269 sprintf(buffer, "IAT.%s", name);
1270 is->iat_index = put_elf_sym(
1271 symtab_section, 0, sizeof(DWORD),
1272 ELFW(ST_INFO)(STB_GLOBAL, STT_OBJECT),
1273 0, SHN_UNDEF, buffer);
1274 #ifdef TCC_TARGET_ARM
1275 put_elf_reloc(symtab_section, text_section,
1276 offset + 8, R_XXX_THUNKFIX, is->iat_index); // offset to IAT position
1277 #else
1278 put_elf_reloc(symtab_section, text_section,
1279 offset + 2, R_XXX_THUNKFIX, is->iat_index);
1280 #endif
1281 is->thk_offset = offset;
1284 /* tcc_realloc might have altered sym's address */
1285 sym = (ElfW(Sym) *)symtab_section->data + sym_index;
1287 /* patch the original symbol */
1288 sym->st_value = offset;
1289 sym->st_shndx = text_section->sh_num;
1290 sym->st_other &= ~ST_PE_EXPORT; /* do not export */
1291 continue;
1294 if (type == STT_OBJECT) { /* data, ptr to that should be */
1295 if (0 == is->iat_index) {
1296 /* original symbol will be patched later in pe_build_imports */
1297 is->iat_index = sym_index;
1298 continue;
1302 not_found:
1303 if (ELFW(ST_BIND)(sym->st_info) == STB_WEAK)
1304 /* STB_WEAK undefined symbols are accepted */
1305 continue;
1306 tcc_error_noabort("undefined symbol '%s'%s", name,
1307 imp_sym < 0 ? ", missing __declspec(dllimport)?":"");
1308 ret = -1;
1310 } else if (pe->s1->rdynamic
1311 && ELFW(ST_BIND)(sym->st_info) != STB_LOCAL) {
1312 /* if -rdynamic option, then export all non local symbols */
1313 sym->st_other |= ST_PE_EXPORT;
1316 return ret;
1319 /*----------------------------------------------------------------------------*/
1320 #ifdef PE_PRINT_SECTIONS
1321 static void pe_print_section(FILE * f, Section * s)
1323 /* just if you're curious */
1324 BYTE *p, *e, b;
1325 int i, n, l, m;
1326 p = s->data;
1327 e = s->data + s->data_offset;
1328 l = e - p;
1330 fprintf(f, "section \"%s\"", s->name);
1331 if (s->link)
1332 fprintf(f, "\nlink \"%s\"", s->link->name);
1333 if (s->reloc)
1334 fprintf(f, "\nreloc \"%s\"", s->reloc->name);
1335 fprintf(f, "\nv_addr %08X", (unsigned)s->sh_addr);
1336 fprintf(f, "\ncontents %08X", (unsigned)l);
1337 fprintf(f, "\n\n");
1339 if (s->sh_type == SHT_NOBITS)
1340 return;
1342 if (0 == l)
1343 return;
1345 if (s->sh_type == SHT_SYMTAB)
1346 m = sizeof(ElfW(Sym));
1347 else if (s->sh_type == SHT_RELX)
1348 m = sizeof(ElfW_Rel);
1349 else
1350 m = 16;
1352 fprintf(f, "%-8s", "offset");
1353 for (i = 0; i < m; ++i)
1354 fprintf(f, " %02x", i);
1355 n = 56;
1357 if (s->sh_type == SHT_SYMTAB || s->sh_type == SHT_RELX) {
1358 const char *fields1[] = {
1359 "name",
1360 "value",
1361 "size",
1362 "bind",
1363 "type",
1364 "other",
1365 "shndx",
1366 NULL
1369 const char *fields2[] = {
1370 "offs",
1371 "type",
1372 "symb",
1373 NULL
1376 const char **p;
1378 if (s->sh_type == SHT_SYMTAB)
1379 p = fields1, n = 106;
1380 else
1381 p = fields2, n = 58;
1383 for (i = 0; p[i]; ++i)
1384 fprintf(f, "%6s", p[i]);
1385 fprintf(f, " symbol");
1388 fprintf(f, "\n");
1389 for (i = 0; i < n; ++i)
1390 fprintf(f, "-");
1391 fprintf(f, "\n");
1393 for (i = 0; i < l;)
1395 fprintf(f, "%08X", i);
1396 for (n = 0; n < m; ++n) {
1397 if (n + i < l)
1398 fprintf(f, " %02X", p[i + n]);
1399 else
1400 fprintf(f, " ");
1403 if (s->sh_type == SHT_SYMTAB) {
1404 ElfW(Sym) *sym = (ElfW(Sym) *) (p + i);
1405 const char *name = s->link->data + sym->st_name;
1406 fprintf(f, " %04X %04X %04X %02X %02X %02X %04X \"%s\"",
1407 (unsigned)sym->st_name,
1408 (unsigned)sym->st_value,
1409 (unsigned)sym->st_size,
1410 (unsigned)ELFW(ST_BIND)(sym->st_info),
1411 (unsigned)ELFW(ST_TYPE)(sym->st_info),
1412 (unsigned)sym->st_other,
1413 (unsigned)sym->st_shndx,
1414 name);
1416 } else if (s->sh_type == SHT_RELX) {
1417 ElfW_Rel *rel = (ElfW_Rel *) (p + i);
1418 ElfW(Sym) *sym =
1419 (ElfW(Sym) *) s->link->data + ELFW(R_SYM)(rel->r_info);
1420 const char *name = s->link->link->data + sym->st_name;
1421 fprintf(f, " %04X %02X %04X \"%s\"",
1422 (unsigned)rel->r_offset,
1423 (unsigned)ELFW(R_TYPE)(rel->r_info),
1424 (unsigned)ELFW(R_SYM)(rel->r_info),
1425 name);
1426 } else {
1427 fprintf(f, " ");
1428 for (n = 0; n < m; ++n) {
1429 if (n + i < l) {
1430 b = p[i + n];
1431 if (b < 32 || b >= 127)
1432 b = '.';
1433 fprintf(f, "%c", b);
1437 i += m;
1438 fprintf(f, "\n");
1440 fprintf(f, "\n\n");
1443 static void pe_print_sections(TCCState *s1, const char *fname)
1445 Section *s;
1446 FILE *f;
1447 int i;
1448 f = fopen(fname, "w");
1449 for (i = 1; i < s1->nb_sections; ++i) {
1450 s = s1->sections[i];
1451 pe_print_section(f, s);
1453 pe_print_section(f, s1->dynsymtab_section);
1454 fclose(f);
1456 #endif
1458 /* ------------------------------------------------------------- */
1459 /* helper function for load/store to insert one more indirection */
1461 #if defined TCC_TARGET_I386 || defined TCC_TARGET_X86_64
1462 ST_FUNC SValue *pe_getimport(SValue *sv, SValue *v2)
1464 int r2;
1465 if ((sv->r & (VT_VALMASK|VT_SYM)) != (VT_CONST|VT_SYM) || (sv->r2 != VT_CONST))
1466 return sv;
1467 if (!sv->sym->a.dllimport)
1468 return sv;
1469 // printf("import %04x %04x %04x %s\n", sv->type.t, sv->sym->type.t, sv->r, get_tok_str(sv->sym->v, NULL));
1470 memset(v2, 0, sizeof *v2);
1471 v2->type.t = VT_PTR;
1472 v2->r = VT_CONST | VT_SYM | VT_LVAL;
1473 v2->sym = sv->sym;
1475 r2 = get_reg(RC_INT);
1476 load(r2, v2);
1477 v2->r = r2;
1478 if ((uint32_t)sv->c.i) {
1479 vpushv(v2);
1480 vpushi(sv->c.i);
1481 gen_opi('+');
1482 *v2 = *vtop--;
1484 v2->type.t = sv->type.t;
1485 v2->r |= sv->r & VT_LVAL;
1486 return v2;
1488 #endif
1490 ST_FUNC int pe_putimport(TCCState *s1, int dllindex, const char *name, addr_t value)
1492 return set_elf_sym(
1493 s1->dynsymtab_section,
1494 value,
1495 dllindex, /* st_size */
1496 ELFW(ST_INFO)(STB_GLOBAL, STT_NOTYPE),
1498 value ? SHN_ABS : SHN_UNDEF,
1499 name
1503 static int add_dllref(TCCState *s1, const char *dllname)
1505 DLLReference *dllref;
1506 int i;
1507 for (i = 0; i < s1->nb_loaded_dlls; ++i)
1508 if (0 == strcmp(s1->loaded_dlls[i]->name, dllname))
1509 return i + 1;
1510 dllref = tcc_mallocz(sizeof(DLLReference) + strlen(dllname));
1511 strcpy(dllref->name, dllname);
1512 dynarray_add(&s1->loaded_dlls, &s1->nb_loaded_dlls, dllref);
1513 return s1->nb_loaded_dlls;
1516 /* ------------------------------------------------------------- */
1518 static int read_mem(int fd, unsigned offset, void *buffer, unsigned len)
1520 lseek(fd, offset, SEEK_SET);
1521 return len == read(fd, buffer, len);
1524 /* ------------------------------------------------------------- */
1526 PUB_FUNC int tcc_get_dllexports(const char *filename, char **pp)
1528 int l, i, n, n0, ret;
1529 char *p;
1530 int fd;
1532 IMAGE_SECTION_HEADER ish;
1533 IMAGE_EXPORT_DIRECTORY ied;
1534 IMAGE_DOS_HEADER dh;
1535 IMAGE_FILE_HEADER ih;
1536 DWORD sig, ref, addr, ptr, namep;
1538 int pef_hdroffset, opt_hdroffset, sec_hdroffset;
1540 n = n0 = 0;
1541 p = NULL;
1542 ret = -1;
1544 fd = open(filename, O_RDONLY | O_BINARY);
1545 if (fd < 0)
1546 goto the_end_1;
1547 ret = 1;
1548 if (!read_mem(fd, 0, &dh, sizeof dh))
1549 goto the_end;
1550 if (!read_mem(fd, dh.e_lfanew, &sig, sizeof sig))
1551 goto the_end;
1552 if (sig != 0x00004550)
1553 goto the_end;
1554 pef_hdroffset = dh.e_lfanew + sizeof sig;
1555 if (!read_mem(fd, pef_hdroffset, &ih, sizeof ih))
1556 goto the_end;
1557 opt_hdroffset = pef_hdroffset + sizeof ih;
1558 if (ih.Machine == 0x014C) {
1559 IMAGE_OPTIONAL_HEADER32 oh;
1560 sec_hdroffset = opt_hdroffset + sizeof oh;
1561 if (!read_mem(fd, opt_hdroffset, &oh, sizeof oh))
1562 goto the_end;
1563 if (IMAGE_DIRECTORY_ENTRY_EXPORT >= oh.NumberOfRvaAndSizes)
1564 goto the_end_0;
1565 addr = oh.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress;
1566 } else if (ih.Machine == 0x8664) {
1567 IMAGE_OPTIONAL_HEADER64 oh;
1568 sec_hdroffset = opt_hdroffset + sizeof oh;
1569 if (!read_mem(fd, opt_hdroffset, &oh, sizeof oh))
1570 goto the_end;
1571 if (IMAGE_DIRECTORY_ENTRY_EXPORT >= oh.NumberOfRvaAndSizes)
1572 goto the_end_0;
1573 addr = oh.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress;
1574 } else
1575 goto the_end;
1577 //printf("addr: %08x\n", addr);
1578 for (i = 0; i < ih.NumberOfSections; ++i) {
1579 if (!read_mem(fd, sec_hdroffset + i * sizeof ish, &ish, sizeof ish))
1580 goto the_end;
1581 //printf("vaddr: %08x\n", ish.VirtualAddress);
1582 if (addr >= ish.VirtualAddress && addr < ish.VirtualAddress + ish.SizeOfRawData)
1583 goto found;
1585 goto the_end_0;
1587 found:
1588 ref = ish.VirtualAddress - ish.PointerToRawData;
1589 if (!read_mem(fd, addr - ref, &ied, sizeof ied))
1590 goto the_end;
1592 namep = ied.AddressOfNames - ref;
1593 for (i = 0; i < ied.NumberOfNames; ++i) {
1594 if (!read_mem(fd, namep, &ptr, sizeof ptr))
1595 goto the_end;
1596 namep += sizeof ptr;
1597 for (l = 0;;) {
1598 if (n+1 >= n0)
1599 p = tcc_realloc(p, n0 = n0 ? n0 * 2 : 256);
1600 if (!read_mem(fd, ptr - ref + l++, p + n, 1)) {
1601 tcc_free(p), p = NULL;
1602 goto the_end;
1604 if (p[n++] == 0)
1605 break;
1608 if (p)
1609 p[n] = 0;
1610 the_end_0:
1611 ret = 0;
1612 the_end:
1613 close(fd);
1614 the_end_1:
1615 *pp = p;
1616 return ret;
1619 /* -------------------------------------------------------------
1620 * This is for compiled windows resources in 'coff' format
1621 * as generated by 'windres.exe -O coff ...'.
1624 static int pe_load_res(TCCState *s1, int fd)
1626 struct pe_rsrc_header hdr;
1627 Section *rsrc_section;
1628 int i, ret = -1, sym_index;
1629 BYTE *ptr;
1630 unsigned offs;
1632 if (!read_mem(fd, 0, &hdr, sizeof hdr))
1633 goto quit;
1635 if (hdr.filehdr.Machine != IMAGE_FILE_MACHINE
1636 || hdr.filehdr.NumberOfSections != 1
1637 || strcmp((char*)hdr.sectionhdr.Name, ".rsrc") != 0)
1638 goto quit;
1640 rsrc_section = new_section(s1, ".rsrc", SHT_PROGBITS, SHF_ALLOC);
1641 ptr = section_ptr_add(rsrc_section, hdr.sectionhdr.SizeOfRawData);
1642 offs = hdr.sectionhdr.PointerToRawData;
1643 if (!read_mem(fd, offs, ptr, hdr.sectionhdr.SizeOfRawData))
1644 goto quit;
1645 offs = hdr.sectionhdr.PointerToRelocations;
1646 sym_index = put_elf_sym(symtab_section, 0, 0, 0, 0, rsrc_section->sh_num, ".rsrc");
1647 for (i = 0; i < hdr.sectionhdr.NumberOfRelocations; ++i) {
1648 struct pe_rsrc_reloc rel;
1649 if (!read_mem(fd, offs, &rel, sizeof rel))
1650 goto quit;
1651 // printf("rsrc_reloc: %x %x %x\n", rel.offset, rel.size, rel.type);
1652 if (rel.type != RSRC_RELTYPE)
1653 goto quit;
1654 put_elf_reloc(symtab_section, rsrc_section,
1655 rel.offset, R_XXX_RELATIVE, sym_index);
1656 offs += sizeof rel;
1658 ret = 0;
1659 quit:
1660 return ret;
1663 /* ------------------------------------------------------------- */
1665 static char *trimfront(char *p)
1667 while (*p && (unsigned char)*p <= ' ')
1668 ++p;
1669 return p;
1672 static char *trimback(char *a, char *e)
1674 while (e > a && (unsigned char)e[-1] <= ' ')
1675 --e;
1676 *e = 0;;
1677 return a;
1680 /* ------------------------------------------------------------- */
1681 static int pe_load_def(TCCState *s1, int fd)
1683 int state = 0, ret = -1, dllindex = 0, ord;
1684 char line[400], dllname[80], *p, *x;
1685 FILE *fp;
1687 fp = fdopen(dup(fd), "rb");
1688 while (fgets(line, sizeof line, fp))
1690 p = trimfront(trimback(line, strchr(line, 0)));
1691 if (0 == *p || ';' == *p)
1692 continue;
1694 switch (state) {
1695 case 0:
1696 if (0 != strnicmp(p, "LIBRARY", 7))
1697 goto quit;
1698 pstrcpy(dllname, sizeof dllname, trimfront(p+7));
1699 ++state;
1700 continue;
1702 case 1:
1703 if (0 != stricmp(p, "EXPORTS"))
1704 goto quit;
1705 ++state;
1706 continue;
1708 case 2:
1709 dllindex = add_dllref(s1, dllname);
1710 ++state;
1711 /* fall through */
1712 default:
1713 /* get ordinal and will store in sym->st_value */
1714 ord = 0;
1715 x = strchr(p, ' ');
1716 if (x) {
1717 *x = 0, x = strrchr(x + 1, '@');
1718 if (x) {
1719 char *d;
1720 ord = (int)strtol(x + 1, &d, 10);
1721 if (*d)
1722 ord = 0;
1725 pe_putimport(s1, dllindex, p, ord);
1726 continue;
1729 ret = 0;
1730 quit:
1731 fclose(fp);
1732 return ret;
1735 /* ------------------------------------------------------------- */
1736 static int pe_load_dll(TCCState *s1, const char *filename)
1738 char *p, *q;
1739 int index, ret;
1741 ret = tcc_get_dllexports(filename, &p);
1742 if (ret) {
1743 return -1;
1744 } else if (p) {
1745 index = add_dllref(s1, tcc_basename(filename));
1746 for (q = p; *q; q += 1 + strlen(q))
1747 pe_putimport(s1, index, q, 0);
1748 tcc_free(p);
1750 return 0;
1753 /* ------------------------------------------------------------- */
1754 ST_FUNC int pe_load_file(struct TCCState *s1, const char *filename, int fd)
1756 int ret = -1;
1757 char buf[10];
1758 if (0 == strcmp(tcc_fileextension(filename), ".def"))
1759 ret = pe_load_def(s1, fd);
1760 else if (pe_load_res(s1, fd) == 0)
1761 ret = 0;
1762 else if (read_mem(fd, 0, buf, 4) && 0 == memcmp(buf, "MZ", 2))
1763 ret = pe_load_dll(s1, filename);
1764 return ret;
1767 /* ------------------------------------------------------------- */
1768 #ifdef TCC_TARGET_X86_64
1769 static unsigned pe_add_uwwind_info(TCCState *s1)
1771 if (NULL == s1->uw_pdata) {
1772 s1->uw_pdata = find_section(tcc_state, ".pdata");
1773 s1->uw_pdata->sh_addralign = 4;
1775 if (0 == s1->uw_sym)
1776 s1->uw_sym = put_elf_sym(symtab_section, 0, 0, 0, 0, text_section->sh_num, ".uw_base");
1777 if (0 == s1->uw_offs) {
1778 /* As our functions all have the same stackframe, we use one entry for all */
1779 static const unsigned char uw_info[] = {
1780 0x01, // UBYTE: 3 Version , UBYTE: 5 Flags
1781 0x04, // UBYTE Size of prolog
1782 0x02, // UBYTE Count of unwind codes
1783 0x05, // UBYTE: 4 Frame Register (rbp), UBYTE: 4 Frame Register offset (scaled)
1784 // USHORT * n Unwind codes array
1785 // 0x0b, 0x01, 0xff, 0xff, // stack size
1786 0x04, 0x03, // set frame ptr (mov rsp -> rbp)
1787 0x01, 0x50 // push reg (rbp)
1790 Section *s = text_section;
1791 unsigned char *p;
1793 section_ptr_add(s, -s->data_offset & 3); /* align */
1794 s1->uw_offs = s->data_offset;
1795 p = section_ptr_add(s, sizeof uw_info);
1796 memcpy(p, uw_info, sizeof uw_info);
1799 return s1->uw_offs;
1802 ST_FUNC void pe_add_unwind_data(unsigned start, unsigned end, unsigned stack)
1804 TCCState *s1 = tcc_state;
1805 Section *pd;
1806 unsigned o, n, d;
1807 struct /* _RUNTIME_FUNCTION */ {
1808 DWORD BeginAddress;
1809 DWORD EndAddress;
1810 DWORD UnwindData;
1811 } *p;
1813 d = pe_add_uwwind_info(s1);
1814 pd = s1->uw_pdata;
1815 o = pd->data_offset;
1816 p = section_ptr_add(pd, sizeof *p);
1818 /* record this function */
1819 p->BeginAddress = start;
1820 p->EndAddress = end;
1821 p->UnwindData = d;
1823 /* put relocations on it */
1824 for (n = o + sizeof *p; o < n; o += sizeof p->BeginAddress)
1825 put_elf_reloc(symtab_section, pd, o, R_XXX_RELATIVE, s1->uw_sym);
1827 #endif
1828 /* ------------------------------------------------------------- */
1829 #ifdef TCC_TARGET_X86_64
1830 #define PE_STDSYM(n,s) n
1831 #else
1832 #define PE_STDSYM(n,s) "_" n s
1833 #endif
1835 static void pe_add_runtime(TCCState *s1, struct pe_info *pe)
1837 const char *start_symbol;
1838 int pe_type = 0;
1839 int unicode_entry = 0;
1841 if (find_elf_sym(symtab_section, PE_STDSYM("WinMain","@16")))
1842 pe_type = PE_GUI;
1843 else
1844 if (find_elf_sym(symtab_section, PE_STDSYM("wWinMain","@16"))) {
1845 pe_type = PE_GUI;
1846 unicode_entry = PE_GUI;
1848 else
1849 if (TCC_OUTPUT_DLL == s1->output_type) {
1850 pe_type = PE_DLL;
1851 /* need this for 'tccelf.c:relocate_section()' */
1852 s1->output_type = TCC_OUTPUT_EXE;
1854 else {
1855 pe_type = PE_EXE;
1856 if (find_elf_sym(symtab_section, "wmain"))
1857 unicode_entry = PE_EXE;
1860 start_symbol =
1861 TCC_OUTPUT_MEMORY == s1->output_type
1862 ? PE_GUI == pe_type ? (unicode_entry ? "__runwwinmain" : "__runwinmain")
1863 : (unicode_entry ? "__runwmain" : "__runmain")
1864 : PE_DLL == pe_type ? PE_STDSYM("__dllstart","@12")
1865 : PE_GUI == pe_type ? (unicode_entry ? "__wwinstart": "__winstart")
1866 : (unicode_entry ? "__wstart" : "__start")
1869 if (!s1->leading_underscore || strchr(start_symbol, '@'))
1870 ++start_symbol;
1872 /* grab the startup code from libtcc1 */
1873 #ifdef TCC_IS_NATIVE
1874 if (TCC_OUTPUT_MEMORY != s1->output_type || s1->runtime_main)
1875 #endif
1876 set_elf_sym(symtab_section,
1877 0, 0,
1878 ELFW(ST_INFO)(STB_GLOBAL, STT_NOTYPE), 0,
1879 SHN_UNDEF, start_symbol);
1881 if (0 == s1->nostdlib) {
1882 static const char *libs[] = {
1883 TCC_LIBTCC1, "msvcrt", "kernel32", "", "user32", "gdi32", NULL
1885 const char **pp, *p;
1886 for (pp = libs; 0 != (p = *pp); ++pp) {
1887 if (0 == *p) {
1888 if (PE_DLL != pe_type && PE_GUI != pe_type)
1889 break;
1890 } else if (pp == libs && tcc_add_dll(s1, p, 0) >= 0) {
1891 continue;
1892 } else {
1893 tcc_add_library_err(s1, p);
1898 if (TCC_OUTPUT_MEMORY == s1->output_type)
1899 pe_type = PE_RUN;
1900 pe->type = pe_type;
1901 pe->start_symbol = start_symbol;
1904 static void pe_set_options(TCCState * s1, struct pe_info *pe)
1906 if (PE_DLL == pe->type) {
1907 /* XXX: check if is correct for arm-pe target */
1908 pe->imagebase = 0x10000000;
1909 } else {
1910 #if defined(TCC_TARGET_ARM)
1911 pe->imagebase = 0x00010000;
1912 #else
1913 pe->imagebase = 0x00400000;
1914 #endif
1917 #if defined(TCC_TARGET_ARM)
1918 /* we use "console" subsystem by default */
1919 pe->subsystem = 9;
1920 #else
1921 if (PE_DLL == pe->type || PE_GUI == pe->type)
1922 pe->subsystem = 2;
1923 else
1924 pe->subsystem = 3;
1925 #endif
1926 /* Allow override via -Wl,-subsystem=... option */
1927 if (s1->pe_subsystem != 0)
1928 pe->subsystem = s1->pe_subsystem;
1930 /* set default file/section alignment */
1931 if (pe->subsystem == 1) {
1932 pe->section_align = 0x20;
1933 pe->file_align = 0x20;
1934 } else {
1935 pe->section_align = 0x1000;
1936 pe->file_align = 0x200;
1939 if (s1->section_align != 0)
1940 pe->section_align = s1->section_align;
1941 if (s1->pe_file_align != 0)
1942 pe->file_align = s1->pe_file_align;
1944 if ((pe->subsystem >= 10) && (pe->subsystem <= 12))
1945 pe->imagebase = 0;
1947 if (s1->has_text_addr)
1948 pe->imagebase = s1->text_addr;
1951 ST_FUNC int pe_output_file(TCCState *s1, const char *filename)
1953 int ret;
1954 struct pe_info pe;
1955 int i;
1957 memset(&pe, 0, sizeof pe);
1958 pe.filename = filename;
1959 pe.s1 = s1;
1961 tcc_add_runtime(s1);
1962 pe_add_runtime(s1, &pe);
1963 resolve_common_syms(s1);
1964 pe_set_options(s1, &pe);
1966 ret = pe_check_symbols(&pe);
1967 if (ret)
1969 else if (filename) {
1970 pe_assign_addresses(&pe);
1971 relocate_syms(s1, s1->symtab, 0);
1972 s1->pe_imagebase = pe.imagebase;
1973 for (i = 1; i < s1->nb_sections; ++i) {
1974 Section *s = s1->sections[i];
1975 if (s->reloc) {
1976 relocate_section(s1, s);
1979 pe.start_addr = (DWORD)
1980 ((uintptr_t)tcc_get_symbol_err(s1, pe.start_symbol)
1981 - pe.imagebase);
1982 if (s1->nb_errors)
1983 ret = -1;
1984 else
1985 ret = pe_write(&pe);
1986 tcc_free(pe.sec_info);
1987 } else {
1988 #ifdef TCC_IS_NATIVE
1989 pe.thunk = data_section;
1990 pe_build_imports(&pe);
1991 s1->runtime_main = pe.start_symbol;
1992 #ifdef TCC_TARGET_X86_64
1993 s1->uw_pdata = find_section(s1, ".pdata");
1994 #endif
1995 #endif
1998 pe_free_imports(&pe);
2000 #ifdef PE_PRINT_SECTIONS
2001 pe_print_sections(s1, "tcc.log");
2002 #endif
2003 return ret;
2006 /* ------------------------------------------------------------- */