tccpp: Fix corner case of fnlike macro invocation
[tinycc.git] / tccpe.c
blob2b0ea9ab13d0962c8ad145a548588f78d5e3382b
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 #endif
31 #ifndef MAX_PATH
32 #define MAX_PATH 260
33 #endif
35 #ifdef TCC_TARGET_X86_64
36 # define ADDR3264 ULONGLONG
37 # define REL_TYPE_DIRECT R_X86_64_64
38 # define R_XXX_THUNKFIX R_X86_64_PC32
39 # define R_XXX_RELATIVE R_X86_64_RELATIVE
40 # define IMAGE_FILE_MACHINE 0x8664
41 # define RSRC_RELTYPE 3
43 #elif defined TCC_TARGET_ARM
44 # define ADDR3264 DWORD
45 # define REL_TYPE_DIRECT R_ARM_ABS32
46 # define R_XXX_THUNKFIX R_ARM_ABS32
47 # define R_XXX_RELATIVE R_ARM_RELATIVE
48 # define IMAGE_FILE_MACHINE 0x01C0
49 # define RSRC_RELTYPE 7 /* ??? (not tested) */
51 #elif defined TCC_TARGET_I386
52 # define ADDR3264 DWORD
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 #if 0
62 #ifdef _WIN32
63 void dbg_printf (const char *fmt, ...)
65 char buffer[4000];
66 va_list arg;
67 int x;
68 va_start(arg, fmt);
69 x = vsprintf (buffer, fmt, arg);
70 strcpy(buffer+x, "\n");
71 OutputDebugString(buffer);
73 #endif
74 #endif
76 /* ----------------------------------------------------------- */
77 #ifndef IMAGE_NT_SIGNATURE
78 /* ----------------------------------------------------------- */
79 /* definitions below are from winnt.h */
81 typedef unsigned char BYTE;
82 typedef unsigned short WORD;
83 typedef unsigned int DWORD;
84 typedef unsigned long long ULONGLONG;
85 #pragma pack(push, 1)
87 typedef struct _IMAGE_DOS_HEADER { /* DOS .EXE header */
88 WORD e_magic; /* Magic number */
89 WORD e_cblp; /* Bytes on last page of file */
90 WORD e_cp; /* Pages in file */
91 WORD e_crlc; /* Relocations */
92 WORD e_cparhdr; /* Size of header in paragraphs */
93 WORD e_minalloc; /* Minimum extra paragraphs needed */
94 WORD e_maxalloc; /* Maximum extra paragraphs needed */
95 WORD e_ss; /* Initial (relative) SS value */
96 WORD e_sp; /* Initial SP value */
97 WORD e_csum; /* Checksum */
98 WORD e_ip; /* Initial IP value */
99 WORD e_cs; /* Initial (relative) CS value */
100 WORD e_lfarlc; /* File address of relocation table */
101 WORD e_ovno; /* Overlay number */
102 WORD e_res[4]; /* Reserved words */
103 WORD e_oemid; /* OEM identifier (for e_oeminfo) */
104 WORD e_oeminfo; /* OEM information; e_oemid specific */
105 WORD e_res2[10]; /* Reserved words */
106 DWORD e_lfanew; /* File address of new exe header */
107 } IMAGE_DOS_HEADER, *PIMAGE_DOS_HEADER;
109 #define IMAGE_NT_SIGNATURE 0x00004550 /* PE00 */
110 #define SIZE_OF_NT_SIGNATURE 4
112 typedef struct _IMAGE_FILE_HEADER {
113 WORD Machine;
114 WORD NumberOfSections;
115 DWORD TimeDateStamp;
116 DWORD PointerToSymbolTable;
117 DWORD NumberOfSymbols;
118 WORD SizeOfOptionalHeader;
119 WORD Characteristics;
120 } IMAGE_FILE_HEADER, *PIMAGE_FILE_HEADER;
123 #define IMAGE_SIZEOF_FILE_HEADER 20
125 typedef struct _IMAGE_DATA_DIRECTORY {
126 DWORD VirtualAddress;
127 DWORD Size;
128 } IMAGE_DATA_DIRECTORY, *PIMAGE_DATA_DIRECTORY;
131 typedef struct _IMAGE_OPTIONAL_HEADER {
132 /* Standard fields. */
133 WORD Magic;
134 BYTE MajorLinkerVersion;
135 BYTE MinorLinkerVersion;
136 DWORD SizeOfCode;
137 DWORD SizeOfInitializedData;
138 DWORD SizeOfUninitializedData;
139 DWORD AddressOfEntryPoint;
140 DWORD BaseOfCode;
141 #ifndef TCC_TARGET_X86_64
142 DWORD BaseOfData;
143 #endif
144 /* NT additional fields. */
145 ADDR3264 ImageBase;
146 DWORD SectionAlignment;
147 DWORD FileAlignment;
148 WORD MajorOperatingSystemVersion;
149 WORD MinorOperatingSystemVersion;
150 WORD MajorImageVersion;
151 WORD MinorImageVersion;
152 WORD MajorSubsystemVersion;
153 WORD MinorSubsystemVersion;
154 DWORD Win32VersionValue;
155 DWORD SizeOfImage;
156 DWORD SizeOfHeaders;
157 DWORD CheckSum;
158 WORD Subsystem;
159 WORD DllCharacteristics;
160 ADDR3264 SizeOfStackReserve;
161 ADDR3264 SizeOfStackCommit;
162 ADDR3264 SizeOfHeapReserve;
163 ADDR3264 SizeOfHeapCommit;
164 DWORD LoaderFlags;
165 DWORD NumberOfRvaAndSizes;
166 IMAGE_DATA_DIRECTORY DataDirectory[16];
167 } IMAGE_OPTIONAL_HEADER32, IMAGE_OPTIONAL_HEADER64, IMAGE_OPTIONAL_HEADER;
169 #define IMAGE_DIRECTORY_ENTRY_EXPORT 0 /* Export Directory */
170 #define IMAGE_DIRECTORY_ENTRY_IMPORT 1 /* Import Directory */
171 #define IMAGE_DIRECTORY_ENTRY_RESOURCE 2 /* Resource Directory */
172 #define IMAGE_DIRECTORY_ENTRY_EXCEPTION 3 /* Exception Directory */
173 #define IMAGE_DIRECTORY_ENTRY_SECURITY 4 /* Security Directory */
174 #define IMAGE_DIRECTORY_ENTRY_BASERELOC 5 /* Base Relocation Table */
175 #define IMAGE_DIRECTORY_ENTRY_DEBUG 6 /* Debug Directory */
176 /* IMAGE_DIRECTORY_ENTRY_COPYRIGHT 7 (X86 usage) */
177 #define IMAGE_DIRECTORY_ENTRY_ARCHITECTURE 7 /* Architecture Specific Data */
178 #define IMAGE_DIRECTORY_ENTRY_GLOBALPTR 8 /* RVA of GP */
179 #define IMAGE_DIRECTORY_ENTRY_TLS 9 /* TLS Directory */
180 #define IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG 10 /* Load Configuration Directory */
181 #define IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT 11 /* Bound Import Directory in headers */
182 #define IMAGE_DIRECTORY_ENTRY_IAT 12 /* Import Address Table */
183 #define IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT 13 /* Delay Load Import Descriptors */
184 #define IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR 14 /* COM Runtime descriptor */
186 /* Section header format. */
187 #define IMAGE_SIZEOF_SHORT_NAME 8
189 typedef struct _IMAGE_SECTION_HEADER {
190 BYTE Name[IMAGE_SIZEOF_SHORT_NAME];
191 union {
192 DWORD PhysicalAddress;
193 DWORD VirtualSize;
194 } Misc;
195 DWORD VirtualAddress;
196 DWORD SizeOfRawData;
197 DWORD PointerToRawData;
198 DWORD PointerToRelocations;
199 DWORD PointerToLinenumbers;
200 WORD NumberOfRelocations;
201 WORD NumberOfLinenumbers;
202 DWORD Characteristics;
203 } IMAGE_SECTION_HEADER, *PIMAGE_SECTION_HEADER;
205 #define IMAGE_SIZEOF_SECTION_HEADER 40
207 typedef struct _IMAGE_EXPORT_DIRECTORY {
208 DWORD Characteristics;
209 DWORD TimeDateStamp;
210 WORD MajorVersion;
211 WORD MinorVersion;
212 DWORD Name;
213 DWORD Base;
214 DWORD NumberOfFunctions;
215 DWORD NumberOfNames;
216 DWORD AddressOfFunctions;
217 DWORD AddressOfNames;
218 DWORD AddressOfNameOrdinals;
219 } IMAGE_EXPORT_DIRECTORY,*PIMAGE_EXPORT_DIRECTORY;
221 typedef struct _IMAGE_IMPORT_DESCRIPTOR {
222 union {
223 DWORD Characteristics;
224 DWORD OriginalFirstThunk;
226 DWORD TimeDateStamp;
227 DWORD ForwarderChain;
228 DWORD Name;
229 DWORD FirstThunk;
230 } IMAGE_IMPORT_DESCRIPTOR;
232 typedef struct _IMAGE_BASE_RELOCATION {
233 DWORD VirtualAddress;
234 DWORD SizeOfBlock;
235 // WORD TypeOffset[1];
236 } IMAGE_BASE_RELOCATION;
238 #define IMAGE_SIZEOF_BASE_RELOCATION 8
240 #define IMAGE_REL_BASED_ABSOLUTE 0
241 #define IMAGE_REL_BASED_HIGH 1
242 #define IMAGE_REL_BASED_LOW 2
243 #define IMAGE_REL_BASED_HIGHLOW 3
244 #define IMAGE_REL_BASED_HIGHADJ 4
245 #define IMAGE_REL_BASED_MIPS_JMPADDR 5
246 #define IMAGE_REL_BASED_SECTION 6
247 #define IMAGE_REL_BASED_REL32 7
249 #pragma pack(pop)
251 /* ----------------------------------------------------------- */
252 #endif /* ndef IMAGE_NT_SIGNATURE */
253 /* ----------------------------------------------------------- */
254 #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;
289 #pragma pack(pop)
291 /* ------------------------------------------------------------- */
292 /* internal temporary structures */
295 #define IMAGE_SCN_CNT_CODE 0x00000020
296 #define IMAGE_SCN_CNT_INITIALIZED_DATA 0x00000040
297 #define IMAGE_SCN_CNT_UNINITIALIZED_DATA 0x00000080
298 #define IMAGE_SCN_MEM_DISCARDABLE 0x02000000
299 #define IMAGE_SCN_MEM_SHARED 0x10000000
300 #define IMAGE_SCN_MEM_EXECUTE 0x20000000
301 #define IMAGE_SCN_MEM_READ 0x40000000
302 #define IMAGE_SCN_MEM_WRITE 0x80000000
305 enum {
306 sec_text = 0,
307 sec_data ,
308 sec_bss ,
309 sec_idata ,
310 sec_pdata ,
311 sec_other ,
312 sec_rsrc ,
313 sec_stab ,
314 sec_reloc ,
315 sec_last
318 static const DWORD pe_sec_flags[] = {
319 0x60000020, /* ".text" , */
320 0xC0000040, /* ".data" , */
321 0xC0000080, /* ".bss" , */
322 0x40000040, /* ".idata" , */
323 0x40000040, /* ".pdata" , */
324 0xE0000060, /* < other > , */
325 0x40000040, /* ".rsrc" , */
326 0x42000802, /* ".stab" , */
327 0x42000040, /* ".reloc" , */
330 struct section_info {
331 int cls, ord;
332 char name[32];
333 DWORD sh_addr;
334 DWORD sh_size;
335 DWORD sh_flags;
336 unsigned char *data;
337 DWORD data_size;
338 IMAGE_SECTION_HEADER ish;
341 struct import_symbol {
342 int sym_index;
343 int iat_index;
344 int thk_offset;
347 struct pe_import_info {
348 int dll_index;
349 int sym_count;
350 struct import_symbol **symbols;
353 struct pe_info {
354 TCCState *s1;
355 Section *reloc;
356 Section *thunk;
357 const char *filename;
358 int type;
359 DWORD sizeofheaders;
360 ADDR3264 imagebase;
361 const char *start_symbol;
362 DWORD start_addr;
363 DWORD imp_offs;
364 DWORD imp_size;
365 DWORD iat_offs;
366 DWORD iat_size;
367 DWORD exp_offs;
368 DWORD exp_size;
369 int subsystem;
370 DWORD section_align;
371 DWORD file_align;
372 struct section_info *sec_info;
373 int sec_count;
374 struct pe_import_info **imp_info;
375 int imp_count;
378 #define PE_NUL 0
379 #define PE_DLL 1
380 #define PE_GUI 2
381 #define PE_EXE 3
382 #define PE_RUN 4
384 /* --------------------------------------------*/
386 static const char *pe_export_name(TCCState *s1, ElfW(Sym) *sym)
388 const char *name = symtab_section->link->data + sym->st_name;
389 if (s1->leading_underscore && name[0] == '_' && !(sym->st_other & ST_PE_STDCALL))
390 return name + 1;
391 return name;
394 static int pe_find_import(TCCState * s1, ElfW(Sym) *sym)
396 char buffer[200];
397 const char *s, *p;
398 int sym_index = 0, n = 0;
399 int a, err = 0;
401 do {
402 s = pe_export_name(s1, sym);
403 a = 0;
404 if (n) {
405 /* second try: */
406 if (sym->st_other & ST_PE_STDCALL) {
407 /* try w/0 stdcall deco (windows API convention) */
408 p = strrchr(s, '@');
409 if (!p || s[0] != '_')
410 break;
411 strcpy(buffer, s+1)[p-s-1] = 0;
412 } else if (s[0] != '_') { /* try non-ansi function */
413 buffer[0] = '_', strcpy(buffer + 1, s);
414 } else if (0 == memcmp(s, "__imp_", 6)) { /* mingw 2.0 */
415 strcpy(buffer, s + 6), a = 1;
416 } else if (0 == memcmp(s, "_imp__", 6)) { /* mingw 3.7 */
417 strcpy(buffer, s + 6), a = 1;
418 } else {
419 continue;
421 s = buffer;
423 sym_index = find_elf_sym(s1->dynsymtab_section, s);
424 // printf("find (%d) %d %s\n", n, sym_index, s);
425 if (sym_index
426 && ELFW(ST_TYPE)(sym->st_info) == STT_OBJECT
427 && 0 == (sym->st_other & ST_PE_IMPORT)
428 && 0 == a
429 ) err = -1, sym_index = 0;
430 } while (0 == sym_index && ++n < 2);
431 return n == 2 ? err : sym_index;
434 /*----------------------------------------------------------------------------*/
436 static int dynarray_assoc(void **pp, int n, int key)
438 int i;
439 for (i = 0; i < n; ++i, ++pp)
440 if (key == **(int **) pp)
441 return i;
442 return -1;
445 #if 0
446 ST_FN DWORD umin(DWORD a, DWORD b)
448 return a < b ? a : b;
450 #endif
452 static DWORD umax(DWORD a, DWORD b)
454 return a < b ? b : a;
457 static DWORD pe_file_align(struct pe_info *pe, DWORD n)
459 return (n + (pe->file_align - 1)) & ~(pe->file_align - 1);
462 static DWORD pe_virtual_align(struct pe_info *pe, DWORD n)
464 return (n + (pe->section_align - 1)) & ~(pe->section_align - 1);
467 static void pe_align_section(Section *s, int a)
469 int i = s->data_offset & (a-1);
470 if (i)
471 section_ptr_add(s, a - i);
474 static void pe_set_datadir(struct pe_header *hdr, int dir, DWORD addr, DWORD size)
476 hdr->opthdr.DataDirectory[dir].VirtualAddress = addr;
477 hdr->opthdr.DataDirectory[dir].Size = size;
480 static int pe_fwrite(void *data, unsigned len, FILE *fp, DWORD *psum)
482 if (psum) {
483 DWORD sum = *psum;
484 WORD *p = data;
485 int i;
486 for (i = len; i > 0; i -= 2) {
487 sum += (i >= 2) ? *p++ : *(BYTE*)p;
488 sum = (sum + (sum >> 16)) & 0xFFFF;
490 *psum = sum;
492 return len == fwrite(data, 1, len, fp) ? 0 : -1;
495 static void pe_fpad(FILE *fp, DWORD new_pos)
497 DWORD pos = ftell(fp);
498 while (++pos <= new_pos)
499 fputc(0, fp);
502 /*----------------------------------------------------------------------------*/
503 static int pe_write(struct pe_info *pe)
505 static const struct pe_header pe_template = {
507 /* IMAGE_DOS_HEADER doshdr */
508 0x5A4D, /*WORD e_magic; Magic number */
509 0x0090, /*WORD e_cblp; Bytes on last page of file */
510 0x0003, /*WORD e_cp; Pages in file */
511 0x0000, /*WORD e_crlc; Relocations */
513 0x0004, /*WORD e_cparhdr; Size of header in paragraphs */
514 0x0000, /*WORD e_minalloc; Minimum extra paragraphs needed */
515 0xFFFF, /*WORD e_maxalloc; Maximum extra paragraphs needed */
516 0x0000, /*WORD e_ss; Initial (relative) SS value */
518 0x00B8, /*WORD e_sp; Initial SP value */
519 0x0000, /*WORD e_csum; Checksum */
520 0x0000, /*WORD e_ip; Initial IP value */
521 0x0000, /*WORD e_cs; Initial (relative) CS value */
522 0x0040, /*WORD e_lfarlc; File address of relocation table */
523 0x0000, /*WORD e_ovno; Overlay number */
524 {0,0,0,0}, /*WORD e_res[4]; Reserved words */
525 0x0000, /*WORD e_oemid; OEM identifier (for e_oeminfo) */
526 0x0000, /*WORD e_oeminfo; OEM information; e_oemid specific */
527 {0,0,0,0,0,0,0,0,0,0}, /*WORD e_res2[10]; Reserved words */
528 0x00000080 /*DWORD e_lfanew; File address of new exe header */
530 /* BYTE dosstub[0x40] */
531 /* 14 code bytes + "This program cannot be run in DOS mode.\r\r\n$" + 6 * 0x00 */
532 0x0e,0x1f,0xba,0x0e,0x00,0xb4,0x09,0xcd,0x21,0xb8,0x01,0x4c,0xcd,0x21,0x54,0x68,
533 0x69,0x73,0x20,0x70,0x72,0x6f,0x67,0x72,0x61,0x6d,0x20,0x63,0x61,0x6e,0x6e,0x6f,
534 0x74,0x20,0x62,0x65,0x20,0x72,0x75,0x6e,0x20,0x69,0x6e,0x20,0x44,0x4f,0x53,0x20,
535 0x6d,0x6f,0x64,0x65,0x2e,0x0d,0x0d,0x0a,0x24,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
537 0x00004550, /* DWORD nt_sig = IMAGE_NT_SIGNATURE */
539 /* IMAGE_FILE_HEADER filehdr */
540 IMAGE_FILE_MACHINE, /*WORD Machine; */
541 0x0003, /*WORD NumberOfSections; */
542 0x00000000, /*DWORD TimeDateStamp; */
543 0x00000000, /*DWORD PointerToSymbolTable; */
544 0x00000000, /*DWORD NumberOfSymbols; */
545 #if defined(TCC_TARGET_X86_64)
546 0x00F0, /*WORD SizeOfOptionalHeader; */
547 0x022F /*WORD Characteristics; */
548 #define CHARACTERISTICS_DLL 0x222E
549 #elif defined(TCC_TARGET_I386)
550 0x00E0, /*WORD SizeOfOptionalHeader; */
551 0x030F /*WORD Characteristics; */
552 #define CHARACTERISTICS_DLL 0x230E
553 #elif defined(TCC_TARGET_ARM)
554 0x00E0, /*WORD SizeOfOptionalHeader; */
555 0x010F, /*WORD Characteristics; */
556 #define CHARACTERISTICS_DLL 0x230F
557 #endif
559 /* IMAGE_OPTIONAL_HEADER opthdr */
560 /* Standard fields. */
561 #ifdef TCC_TARGET_X86_64
562 0x020B, /*WORD Magic; */
563 #else
564 0x010B, /*WORD Magic; */
565 #endif
566 0x06, /*BYTE MajorLinkerVersion; */
567 0x00, /*BYTE MinorLinkerVersion; */
568 0x00000000, /*DWORD SizeOfCode; */
569 0x00000000, /*DWORD SizeOfInitializedData; */
570 0x00000000, /*DWORD SizeOfUninitializedData; */
571 0x00000000, /*DWORD AddressOfEntryPoint; */
572 0x00000000, /*DWORD BaseOfCode; */
573 #ifndef TCC_TARGET_X86_64
574 0x00000000, /*DWORD BaseOfData; */
575 #endif
576 /* NT additional fields. */
577 #if defined(TCC_TARGET_ARM)
578 0x00100000, /*DWORD ImageBase; */
579 #else
580 0x00400000, /*DWORD ImageBase; */
581 #endif
582 0x00001000, /*DWORD SectionAlignment; */
583 0x00000200, /*DWORD FileAlignment; */
584 0x0004, /*WORD MajorOperatingSystemVersion; */
585 0x0000, /*WORD MinorOperatingSystemVersion; */
586 0x0000, /*WORD MajorImageVersion; */
587 0x0000, /*WORD MinorImageVersion; */
588 0x0004, /*WORD MajorSubsystemVersion; */
589 0x0000, /*WORD MinorSubsystemVersion; */
590 0x00000000, /*DWORD Win32VersionValue; */
591 0x00000000, /*DWORD SizeOfImage; */
592 0x00000200, /*DWORD SizeOfHeaders; */
593 0x00000000, /*DWORD CheckSum; */
594 0x0002, /*WORD Subsystem; */
595 0x0000, /*WORD DllCharacteristics; */
596 0x00100000, /*DWORD SizeOfStackReserve; */
597 0x00001000, /*DWORD SizeOfStackCommit; */
598 0x00100000, /*DWORD SizeOfHeapReserve; */
599 0x00001000, /*DWORD SizeOfHeapCommit; */
600 0x00000000, /*DWORD LoaderFlags; */
601 0x00000010, /*DWORD NumberOfRvaAndSizes; */
603 /* IMAGE_DATA_DIRECTORY DataDirectory[16]; */
604 {{0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0},
605 {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}}
608 struct pe_header pe_header = pe_template;
610 int i;
611 FILE *op;
612 DWORD file_offset, sum;
613 struct section_info *si;
614 IMAGE_SECTION_HEADER *psh;
616 op = fopen(pe->filename, "wb");
617 if (NULL == op) {
618 tcc_error_noabort("could not write '%s': %s", pe->filename, strerror(errno));
619 return -1;
622 pe->sizeofheaders = pe_file_align(pe,
623 sizeof (struct pe_header)
624 + pe->sec_count * sizeof (IMAGE_SECTION_HEADER)
627 file_offset = pe->sizeofheaders;
629 if (2 == pe->s1->verbose)
630 printf("-------------------------------"
631 "\n virt file size section" "\n");
632 for (i = 0; i < pe->sec_count; ++i) {
633 DWORD addr, size;
634 const char *sh_name;
636 si = pe->sec_info + i;
637 sh_name = si->name;
638 addr = si->sh_addr - pe->imagebase;
639 size = si->sh_size;
640 psh = &si->ish;
642 if (2 == pe->s1->verbose)
643 printf("%6x %6x %6x %s\n",
644 (unsigned)addr, (unsigned)file_offset, (unsigned)size, sh_name);
646 switch (si->cls) {
647 case sec_text:
648 pe_header.opthdr.BaseOfCode = addr;
649 break;
651 case sec_data:
652 #ifndef TCC_TARGET_X86_64
653 pe_header.opthdr.BaseOfData = addr;
654 #endif
655 break;
657 case sec_bss:
658 break;
660 case sec_reloc:
661 pe_set_datadir(&pe_header, IMAGE_DIRECTORY_ENTRY_BASERELOC, addr, size);
662 break;
664 case sec_rsrc:
665 pe_set_datadir(&pe_header, IMAGE_DIRECTORY_ENTRY_RESOURCE, addr, size);
666 break;
668 case sec_pdata:
669 pe_set_datadir(&pe_header, IMAGE_DIRECTORY_ENTRY_EXCEPTION, addr, size);
670 break;
672 case sec_stab:
673 break;
676 if (pe->thunk == pe->s1->sections[si->ord]) {
677 if (pe->imp_size) {
678 pe_set_datadir(&pe_header, IMAGE_DIRECTORY_ENTRY_IMPORT,
679 pe->imp_offs + addr, pe->imp_size);
680 pe_set_datadir(&pe_header, IMAGE_DIRECTORY_ENTRY_IAT,
681 pe->iat_offs + addr, pe->iat_size);
683 if (pe->exp_size) {
684 pe_set_datadir(&pe_header, IMAGE_DIRECTORY_ENTRY_EXPORT,
685 pe->exp_offs + addr, pe->exp_size);
689 strncpy((char*)psh->Name, sh_name, sizeof psh->Name);
691 psh->Characteristics = pe_sec_flags[si->cls];
692 psh->VirtualAddress = addr;
693 psh->Misc.VirtualSize = size;
694 pe_header.opthdr.SizeOfImage =
695 umax(pe_virtual_align(pe, size + addr), pe_header.opthdr.SizeOfImage);
697 if (si->data_size) {
698 psh->PointerToRawData = file_offset;
699 file_offset = pe_file_align(pe, file_offset + si->data_size);
700 psh->SizeOfRawData = file_offset - psh->PointerToRawData;
701 if (si->cls == sec_text)
702 pe_header.opthdr.SizeOfCode += psh->SizeOfRawData;
703 else
704 pe_header.opthdr.SizeOfInitializedData += psh->SizeOfRawData;
708 //pe_header.filehdr.TimeDateStamp = time(NULL);
709 pe_header.filehdr.NumberOfSections = pe->sec_count;
710 pe_header.opthdr.AddressOfEntryPoint = pe->start_addr;
711 pe_header.opthdr.SizeOfHeaders = pe->sizeofheaders;
712 pe_header.opthdr.ImageBase = pe->imagebase;
713 pe_header.opthdr.Subsystem = pe->subsystem;
714 if (pe->s1->pe_stack_size)
715 pe_header.opthdr.SizeOfStackReserve = pe->s1->pe_stack_size;
716 if (PE_DLL == pe->type)
717 pe_header.filehdr.Characteristics = CHARACTERISTICS_DLL;
718 pe_header.filehdr.Characteristics |= pe->s1->pe_characteristics;
720 sum = 0;
721 pe_fwrite(&pe_header, sizeof pe_header, op, &sum);
722 for (i = 0; i < pe->sec_count; ++i)
723 pe_fwrite(&pe->sec_info[i].ish, sizeof(IMAGE_SECTION_HEADER), op, &sum);
724 pe_fpad(op, pe->sizeofheaders);
725 for (i = 0; i < pe->sec_count; ++i) {
726 si = pe->sec_info + i;
727 psh = &si->ish;
728 if (si->data_size) {
729 pe_fwrite(si->data, si->data_size, op, &sum);
730 file_offset = psh->PointerToRawData + psh->SizeOfRawData;
731 pe_fpad(op, file_offset);
735 pe_header.opthdr.CheckSum = sum + file_offset;
736 fseek(op, offsetof(struct pe_header, opthdr.CheckSum), SEEK_SET);
737 pe_fwrite(&pe_header.opthdr.CheckSum, sizeof pe_header.opthdr.CheckSum, op, NULL);
738 fclose (op);
740 if (2 == pe->s1->verbose)
741 printf("-------------------------------\n");
742 if (pe->s1->verbose)
743 printf("<- %s (%u bytes)\n", pe->filename, (unsigned)file_offset);
745 return 0;
748 /*----------------------------------------------------------------------------*/
750 static struct import_symbol *pe_add_import(struct pe_info *pe, int sym_index)
752 int i;
753 int dll_index;
754 struct pe_import_info *p;
755 struct import_symbol *s;
756 ElfW(Sym) *isym;
758 isym = (ElfW(Sym) *)pe->s1->dynsymtab_section->data + sym_index;
759 dll_index = isym->st_size;
761 i = dynarray_assoc ((void**)pe->imp_info, pe->imp_count, dll_index);
762 if (-1 != i) {
763 p = pe->imp_info[i];
764 goto found_dll;
766 p = tcc_mallocz(sizeof *p);
767 p->dll_index = dll_index;
768 dynarray_add(&pe->imp_info, &pe->imp_count, p);
770 found_dll:
771 i = dynarray_assoc ((void**)p->symbols, p->sym_count, sym_index);
772 if (-1 != i)
773 return p->symbols[i];
775 s = tcc_mallocz(sizeof *s);
776 dynarray_add(&p->symbols, &p->sym_count, s);
777 s->sym_index = sym_index;
778 return s;
781 void pe_free_imports(struct pe_info *pe)
783 int i;
784 for (i = 0; i < pe->imp_count; ++i) {
785 struct pe_import_info *p = pe->imp_info[i];
786 dynarray_reset(&p->symbols, &p->sym_count);
788 dynarray_reset(&pe->imp_info, &pe->imp_count);
791 /*----------------------------------------------------------------------------*/
792 static void pe_build_imports(struct pe_info *pe)
794 int thk_ptr, ent_ptr, dll_ptr, sym_cnt, i;
795 DWORD rva_base = pe->thunk->sh_addr - pe->imagebase;
796 int ndlls = pe->imp_count;
798 for (sym_cnt = i = 0; i < ndlls; ++i)
799 sym_cnt += pe->imp_info[i]->sym_count;
801 if (0 == sym_cnt)
802 return;
804 pe_align_section(pe->thunk, 16);
806 pe->imp_offs = dll_ptr = pe->thunk->data_offset;
807 pe->imp_size = (ndlls + 1) * sizeof(IMAGE_IMPORT_DESCRIPTOR);
808 pe->iat_offs = dll_ptr + pe->imp_size;
809 pe->iat_size = (sym_cnt + ndlls) * sizeof(ADDR3264);
810 section_ptr_add(pe->thunk, pe->imp_size + 2*pe->iat_size);
812 thk_ptr = pe->iat_offs;
813 ent_ptr = pe->iat_offs + pe->iat_size;
815 for (i = 0; i < pe->imp_count; ++i) {
816 IMAGE_IMPORT_DESCRIPTOR *hdr;
817 int k, n, dllindex;
818 ADDR3264 v;
819 struct pe_import_info *p = pe->imp_info[i];
820 const char *name;
821 DLLReference *dllref;
823 dllindex = p->dll_index;
824 if (dllindex)
825 name = (dllref = pe->s1->loaded_dlls[dllindex-1])->name;
826 else
827 name = "", dllref = NULL;
829 /* put the dll name into the import header */
830 v = put_elf_str(pe->thunk, name);
831 hdr = (IMAGE_IMPORT_DESCRIPTOR*)(pe->thunk->data + dll_ptr);
832 hdr->FirstThunk = thk_ptr + rva_base;
833 hdr->OriginalFirstThunk = ent_ptr + rva_base;
834 hdr->Name = v + rva_base;
836 for (k = 0, n = p->sym_count; k <= n; ++k) {
837 if (k < n) {
838 int iat_index = p->symbols[k]->iat_index;
839 int sym_index = p->symbols[k]->sym_index;
840 ElfW(Sym) *imp_sym = (ElfW(Sym) *)pe->s1->dynsymtab_section->data + sym_index;
841 ElfW(Sym) *org_sym = (ElfW(Sym) *)symtab_section->data + iat_index;
842 const char *name = pe->s1->dynsymtab_section->link->data + imp_sym->st_name;
843 int ordinal;
845 org_sym->st_value = thk_ptr;
846 org_sym->st_shndx = pe->thunk->sh_num;
848 if (dllref)
849 v = 0, ordinal = imp_sym->st_value; /* ordinal from pe_load_def */
850 else
851 ordinal = 0, v = imp_sym->st_value; /* address from tcc_add_symbol() */
853 #ifdef TCC_IS_NATIVE
854 if (pe->type == PE_RUN) {
855 if (dllref) {
856 if ( !dllref->handle )
857 dllref->handle = LoadLibrary(dllref->name);
858 v = (ADDR3264)GetProcAddress(dllref->handle, ordinal?(char*)0+ordinal:name);
860 if (!v)
861 tcc_error_noabort("can't build symbol '%s'", name);
862 } else
863 #endif
864 if (ordinal) {
865 v = ordinal | (ADDR3264)1 << (sizeof(ADDR3264)*8 - 1);
866 } else {
867 v = pe->thunk->data_offset + rva_base;
868 section_ptr_add(pe->thunk, sizeof(WORD)); /* hint, not used */
869 put_elf_str(pe->thunk, name);
872 } else {
873 v = 0; /* last entry is zero */
876 *(ADDR3264*)(pe->thunk->data+thk_ptr) =
877 *(ADDR3264*)(pe->thunk->data+ent_ptr) = v;
878 thk_ptr += sizeof (ADDR3264);
879 ent_ptr += sizeof (ADDR3264);
881 dll_ptr += sizeof(IMAGE_IMPORT_DESCRIPTOR);
885 /* ------------------------------------------------------------- */
887 struct pe_sort_sym
889 int index;
890 const char *name;
893 static int sym_cmp(const void *va, const void *vb)
895 const char *ca = (*(struct pe_sort_sym**)va)->name;
896 const char *cb = (*(struct pe_sort_sym**)vb)->name;
897 return strcmp(ca, cb);
900 static void pe_build_exports(struct pe_info *pe)
902 ElfW(Sym) *sym;
903 int sym_index, sym_end;
904 DWORD rva_base, func_o, name_o, ord_o, str_o;
905 IMAGE_EXPORT_DIRECTORY *hdr;
906 int sym_count, ord;
907 struct pe_sort_sym **sorted, *p;
909 FILE *op;
910 char buf[MAX_PATH];
911 const char *dllname;
912 const char *name;
914 rva_base = pe->thunk->sh_addr - pe->imagebase;
915 sym_count = 0, sorted = NULL, op = NULL;
917 sym_end = symtab_section->data_offset / sizeof(ElfW(Sym));
918 for (sym_index = 1; sym_index < sym_end; ++sym_index) {
919 sym = (ElfW(Sym)*)symtab_section->data + sym_index;
920 name = pe_export_name(pe->s1, sym);
921 if ((sym->st_other & ST_PE_EXPORT)
922 /* export only symbols from actually written sections */
923 && pe->s1->sections[sym->st_shndx]->sh_addr) {
924 p = tcc_malloc(sizeof *p);
925 p->index = sym_index;
926 p->name = name;
927 dynarray_add(&sorted, &sym_count, p);
929 #if 0
930 if (sym->st_other & ST_PE_EXPORT)
931 printf("export: %s\n", name);
932 if (sym->st_other & ST_PE_STDCALL)
933 printf("stdcall: %s\n", name);
934 #endif
937 if (0 == sym_count)
938 return;
940 qsort (sorted, sym_count, sizeof *sorted, sym_cmp);
942 pe_align_section(pe->thunk, 16);
943 dllname = tcc_basename(pe->filename);
945 pe->exp_offs = pe->thunk->data_offset;
946 func_o = pe->exp_offs + sizeof(IMAGE_EXPORT_DIRECTORY);
947 name_o = func_o + sym_count * sizeof (DWORD);
948 ord_o = name_o + sym_count * sizeof (DWORD);
949 str_o = ord_o + sym_count * sizeof(WORD);
951 hdr = section_ptr_add(pe->thunk, str_o - pe->exp_offs);
952 hdr->Characteristics = 0;
953 hdr->Base = 1;
954 hdr->NumberOfFunctions = sym_count;
955 hdr->NumberOfNames = sym_count;
956 hdr->AddressOfFunctions = func_o + rva_base;
957 hdr->AddressOfNames = name_o + rva_base;
958 hdr->AddressOfNameOrdinals = ord_o + rva_base;
959 hdr->Name = str_o + rva_base;
960 put_elf_str(pe->thunk, dllname);
962 #if 1
963 /* automatically write exports to <output-filename>.def */
964 pstrcpy(buf, sizeof buf, pe->filename);
965 strcpy(tcc_fileextension(buf), ".def");
966 op = fopen(buf, "w");
967 if (NULL == op) {
968 tcc_error_noabort("could not create '%s': %s", buf, strerror(errno));
969 } else {
970 fprintf(op, "LIBRARY %s\n\nEXPORTS\n", dllname);
971 if (pe->s1->verbose)
972 printf("<- %s (%d symbol%s)\n", buf, sym_count, "s" + (sym_count < 2));
974 #endif
976 for (ord = 0; ord < sym_count; ++ord)
978 p = sorted[ord], sym_index = p->index, name = p->name;
979 /* insert actual address later in pe_relocate_rva */
980 put_elf_reloc(symtab_section, pe->thunk,
981 func_o, R_XXX_RELATIVE, sym_index);
982 *(DWORD*)(pe->thunk->data + name_o)
983 = pe->thunk->data_offset + rva_base;
984 *(WORD*)(pe->thunk->data + ord_o)
985 = ord;
986 put_elf_str(pe->thunk, name);
987 func_o += sizeof (DWORD);
988 name_o += sizeof (DWORD);
989 ord_o += sizeof (WORD);
990 if (op)
991 fprintf(op, "%s\n", name);
993 pe->exp_size = pe->thunk->data_offset - pe->exp_offs;
994 dynarray_reset(&sorted, &sym_count);
995 if (op)
996 fclose(op);
999 /* ------------------------------------------------------------- */
1000 static void pe_build_reloc (struct pe_info *pe)
1002 DWORD offset, block_ptr, addr;
1003 int count, i;
1004 ElfW_Rel *rel, *rel_end;
1005 Section *s = NULL, *sr;
1007 offset = addr = block_ptr = count = i = 0;
1008 rel = rel_end = NULL;
1010 for(;;) {
1011 if (rel < rel_end) {
1012 int type = ELFW(R_TYPE)(rel->r_info);
1013 addr = rel->r_offset + s->sh_addr;
1014 ++ rel;
1015 if (type != REL_TYPE_DIRECT)
1016 continue;
1017 if (count == 0) { /* new block */
1018 block_ptr = pe->reloc->data_offset;
1019 section_ptr_add(pe->reloc, sizeof(struct pe_reloc_header));
1020 offset = addr & 0xFFFFFFFF<<12;
1022 if ((addr -= offset) < (1<<12)) { /* one block spans 4k addresses */
1023 WORD *wp = section_ptr_add(pe->reloc, sizeof (WORD));
1024 *wp = addr | IMAGE_REL_BASED_HIGHLOW<<12;
1025 ++count;
1026 continue;
1028 -- rel;
1030 } else if (i < pe->sec_count) {
1031 sr = (s = pe->s1->sections[pe->sec_info[i++].ord])->reloc;
1032 if (sr) {
1033 rel = (ElfW_Rel *)sr->data;
1034 rel_end = (ElfW_Rel *)(sr->data + sr->data_offset);
1036 continue;
1039 if (count) {
1040 /* store the last block and ready for a new one */
1041 struct pe_reloc_header *hdr;
1042 if (count & 1) /* align for DWORDS */
1043 section_ptr_add(pe->reloc, sizeof(WORD)), ++count;
1044 hdr = (struct pe_reloc_header *)(pe->reloc->data + block_ptr);
1045 hdr -> offset = offset - pe->imagebase;
1046 hdr -> size = count * sizeof(WORD) + sizeof(struct pe_reloc_header);
1047 count = 0;
1050 if (rel >= rel_end)
1051 break;
1055 /* ------------------------------------------------------------- */
1056 static int pe_section_class(Section *s)
1058 int type, flags;
1059 const char *name;
1061 type = s->sh_type;
1062 flags = s->sh_flags;
1063 name = s->name;
1064 if (flags & SHF_ALLOC) {
1065 if (type == SHT_PROGBITS) {
1066 if (flags & SHF_EXECINSTR)
1067 return sec_text;
1068 if (flags & SHF_WRITE)
1069 return sec_data;
1070 if (0 == strcmp(name, ".rsrc"))
1071 return sec_rsrc;
1072 if (0 == strcmp(name, ".iedat"))
1073 return sec_idata;
1074 if (0 == strcmp(name, ".pdata"))
1075 return sec_pdata;
1076 return sec_other;
1077 } else if (type == SHT_NOBITS) {
1078 if (flags & SHF_WRITE)
1079 return sec_bss;
1081 } else {
1082 if (0 == strcmp(name, ".reloc"))
1083 return sec_reloc;
1084 if (0 == strncmp(name, ".stab", 5)) /* .stab and .stabstr */
1085 return sec_stab;
1087 return -1;
1090 static int pe_assign_addresses (struct pe_info *pe)
1092 int i, k, o, c;
1093 DWORD addr;
1094 int *section_order;
1095 struct section_info *si;
1096 Section *s;
1098 if (PE_DLL == pe->type)
1099 pe->reloc = new_section(pe->s1, ".reloc", SHT_PROGBITS, 0);
1101 // pe->thunk = new_section(pe->s1, ".iedat", SHT_PROGBITS, SHF_ALLOC);
1103 section_order = tcc_malloc(pe->s1->nb_sections * sizeof (int));
1104 for (o = k = 0 ; k < sec_last; ++k) {
1105 for (i = 1; i < pe->s1->nb_sections; ++i) {
1106 s = pe->s1->sections[i];
1107 if (k == pe_section_class(s)) {
1108 // printf("%s %d\n", s->name, k);
1109 s->sh_addr = pe->imagebase;
1110 section_order[o++] = i;
1115 pe->sec_info = tcc_mallocz(o * sizeof (struct section_info));
1116 addr = pe->imagebase + 1;
1118 for (i = 0; i < o; ++i)
1120 k = section_order[i];
1121 s = pe->s1->sections[k];
1122 c = pe_section_class(s);
1123 si = &pe->sec_info[pe->sec_count];
1125 #ifdef PE_MERGE_DATA
1126 if (c == sec_bss && pe->sec_count && si[-1].cls == sec_data) {
1127 /* append .bss to .data */
1128 s->sh_addr = addr = ((addr-1) | (s->sh_addralign-1)) + 1;
1129 addr += s->data_offset;
1130 si[-1].sh_size = addr - si[-1].sh_addr;
1131 continue;
1133 #endif
1134 if (c == sec_stab && 0 == pe->s1->do_debug)
1135 continue;
1137 strcpy(si->name, s->name);
1138 si->cls = c;
1139 si->ord = k;
1140 si->sh_addr = s->sh_addr = addr = pe_virtual_align(pe, addr);
1141 si->sh_flags = s->sh_flags;
1143 if (c == sec_data && NULL == pe->thunk)
1144 pe->thunk = s;
1146 if (s == pe->thunk) {
1147 pe_build_imports(pe);
1148 pe_build_exports(pe);
1151 if (c == sec_reloc)
1152 pe_build_reloc (pe);
1154 if (s->data_offset)
1156 if (s->sh_type != SHT_NOBITS) {
1157 si->data = s->data;
1158 si->data_size = s->data_offset;
1161 addr += s->data_offset;
1162 si->sh_size = s->data_offset;
1163 ++pe->sec_count;
1165 // printf("%08x %05x %s\n", si->sh_addr, si->sh_size, si->name);
1168 #if 0
1169 for (i = 1; i < pe->s1->nb_sections; ++i) {
1170 Section *s = pe->s1->sections[i];
1171 int type = s->sh_type;
1172 int flags = s->sh_flags;
1173 printf("section %-16s %-10s %5x %s,%s,%s\n",
1174 s->name,
1175 type == SHT_PROGBITS ? "progbits" :
1176 type == SHT_NOBITS ? "nobits" :
1177 type == SHT_SYMTAB ? "symtab" :
1178 type == SHT_STRTAB ? "strtab" :
1179 type == SHT_RELX ? "rel" : "???",
1180 s->data_offset,
1181 flags & SHF_ALLOC ? "alloc" : "",
1182 flags & SHF_WRITE ? "write" : "",
1183 flags & SHF_EXECINSTR ? "exec" : ""
1186 pe->s1->verbose = 2;
1187 #endif
1189 tcc_free(section_order);
1190 return 0;
1193 /* ------------------------------------------------------------- */
1194 static void pe_relocate_rva (struct pe_info *pe, Section *s)
1196 Section *sr = s->reloc;
1197 ElfW_Rel *rel, *rel_end;
1198 rel_end = (ElfW_Rel *)(sr->data + sr->data_offset);
1199 for(rel = (ElfW_Rel *)sr->data; rel < rel_end; rel++) {
1200 if (ELFW(R_TYPE)(rel->r_info) == R_XXX_RELATIVE) {
1201 int sym_index = ELFW(R_SYM)(rel->r_info);
1202 DWORD addr = s->sh_addr;
1203 if (sym_index) {
1204 ElfW(Sym) *sym = (ElfW(Sym) *)symtab_section->data + sym_index;
1205 addr = sym->st_value;
1207 // printf("reloc rva %08x %08x %s\n", (DWORD)rel->r_offset, addr, s->name);
1208 *(DWORD*)(s->data + rel->r_offset) += addr - pe->imagebase;
1213 /*----------------------------------------------------------------------------*/
1215 static int pe_isafunc(int sym_index)
1217 Section *sr = text_section->reloc;
1218 ElfW_Rel *rel, *rel_end;
1219 Elf32_Word info = ELF32_R_INFO(sym_index, R_386_PC32);
1220 if (!sr)
1221 return 0;
1222 rel_end = (ElfW_Rel *)(sr->data + sr->data_offset);
1223 for (rel = (ElfW_Rel *)sr->data; rel < rel_end; rel++)
1224 if (rel->r_info == info)
1225 return 1;
1226 return 0;
1229 /*----------------------------------------------------------------------------*/
1230 static int pe_check_symbols(struct pe_info *pe)
1232 ElfW(Sym) *sym;
1233 int sym_index, sym_end;
1234 int ret = 0;
1236 pe_align_section(text_section, 8);
1238 sym_end = symtab_section->data_offset / sizeof(ElfW(Sym));
1239 for (sym_index = 1; sym_index < sym_end; ++sym_index) {
1241 sym = (ElfW(Sym) *)symtab_section->data + sym_index;
1242 if (sym->st_shndx == SHN_UNDEF) {
1244 const char *name = symtab_section->link->data + sym->st_name;
1245 unsigned type = ELFW(ST_TYPE)(sym->st_info);
1246 int imp_sym = pe_find_import(pe->s1, sym);
1247 struct import_symbol *is;
1249 if (imp_sym <= 0)
1250 goto not_found;
1252 if (type == STT_NOTYPE) {
1253 /* symbols from assembler have no type, find out which */
1254 if (pe_isafunc(sym_index))
1255 type = STT_FUNC;
1256 else
1257 type = STT_OBJECT;
1260 is = pe_add_import(pe, imp_sym);
1262 if (type == STT_FUNC) {
1263 unsigned long offset = is->thk_offset;
1264 if (offset) {
1265 /* got aliased symbol, like stricmp and _stricmp */
1267 } else {
1268 char buffer[100];
1269 WORD *p;
1271 offset = text_section->data_offset;
1272 /* add the 'jmp IAT[x]' instruction */
1273 #ifdef TCC_TARGET_ARM
1274 p = section_ptr_add(text_section, 8+4); // room for code and address
1275 (*(DWORD*)(p)) = 0xE59FC000; // arm code ldr ip, [pc] ; PC+8+0 = 0001xxxx
1276 (*(DWORD*)(p+2)) = 0xE59CF000; // arm code ldr pc, [ip]
1277 #else
1278 p = section_ptr_add(text_section, 8);
1279 *p = 0x25FF;
1280 #ifdef TCC_TARGET_X86_64
1281 *(DWORD*)(p+1) = (DWORD)-4;
1282 #endif
1283 #endif
1284 /* add a helper symbol, will be patched later in
1285 pe_build_imports */
1286 sprintf(buffer, "IAT.%s", name);
1287 is->iat_index = put_elf_sym(
1288 symtab_section, 0, sizeof(DWORD),
1289 ELFW(ST_INFO)(STB_GLOBAL, STT_OBJECT),
1290 0, SHN_UNDEF, buffer);
1291 #ifdef TCC_TARGET_ARM
1292 put_elf_reloc(symtab_section, text_section,
1293 offset + 8, R_XXX_THUNKFIX, is->iat_index); // offset to IAT position
1294 #else
1295 put_elf_reloc(symtab_section, text_section,
1296 offset + 2, R_XXX_THUNKFIX, is->iat_index);
1297 #endif
1298 is->thk_offset = offset;
1301 /* tcc_realloc might have altered sym's address */
1302 sym = (ElfW(Sym) *)symtab_section->data + sym_index;
1304 /* patch the original symbol */
1305 sym->st_value = offset;
1306 sym->st_shndx = text_section->sh_num;
1307 sym->st_other &= ~ST_PE_EXPORT; /* do not export */
1308 continue;
1311 if (type == STT_OBJECT) { /* data, ptr to that should be */
1312 if (0 == is->iat_index) {
1313 /* original symbol will be patched later in pe_build_imports */
1314 is->iat_index = sym_index;
1315 continue;
1319 not_found:
1320 if (ELFW(ST_BIND)(sym->st_info) == STB_WEAK)
1321 /* STB_WEAK undefined symbols are accepted */
1322 continue;
1323 tcc_error_noabort("undefined symbol '%s'%s", name,
1324 imp_sym < 0 ? ", missing __declspec(dllimport)?":"");
1325 ret = -1;
1327 } else if (pe->s1->rdynamic
1328 && ELFW(ST_BIND)(sym->st_info) != STB_LOCAL) {
1329 /* if -rdynamic option, then export all non local symbols */
1330 sym->st_other |= ST_PE_EXPORT;
1333 return ret;
1336 /*----------------------------------------------------------------------------*/
1337 #ifdef PE_PRINT_SECTIONS
1338 static void pe_print_section(FILE * f, Section * s)
1340 /* just if you'r curious */
1341 BYTE *p, *e, b;
1342 int i, n, l, m;
1343 p = s->data;
1344 e = s->data + s->data_offset;
1345 l = e - p;
1347 fprintf(f, "section \"%s\"", s->name);
1348 if (s->link)
1349 fprintf(f, "\nlink \"%s\"", s->link->name);
1350 if (s->reloc)
1351 fprintf(f, "\nreloc \"%s\"", s->reloc->name);
1352 fprintf(f, "\nv_addr %08X", (unsigned)s->sh_addr);
1353 fprintf(f, "\ncontents %08X", (unsigned)l);
1354 fprintf(f, "\n\n");
1356 if (s->sh_type == SHT_NOBITS)
1357 return;
1359 if (0 == l)
1360 return;
1362 if (s->sh_type == SHT_SYMTAB)
1363 m = sizeof(ElfW(Sym));
1364 else if (s->sh_type == SHT_RELX)
1365 m = sizeof(ElfW_Rel);
1366 else
1367 m = 16;
1369 fprintf(f, "%-8s", "offset");
1370 for (i = 0; i < m; ++i)
1371 fprintf(f, " %02x", i);
1372 n = 56;
1374 if (s->sh_type == SHT_SYMTAB || s->sh_type == SHT_RELX) {
1375 const char *fields1[] = {
1376 "name",
1377 "value",
1378 "size",
1379 "bind",
1380 "type",
1381 "other",
1382 "shndx",
1383 NULL
1386 const char *fields2[] = {
1387 "offs",
1388 "type",
1389 "symb",
1390 NULL
1393 const char **p;
1395 if (s->sh_type == SHT_SYMTAB)
1396 p = fields1, n = 106;
1397 else
1398 p = fields2, n = 58;
1400 for (i = 0; p[i]; ++i)
1401 fprintf(f, "%6s", p[i]);
1402 fprintf(f, " symbol");
1405 fprintf(f, "\n");
1406 for (i = 0; i < n; ++i)
1407 fprintf(f, "-");
1408 fprintf(f, "\n");
1410 for (i = 0; i < l;)
1412 fprintf(f, "%08X", i);
1413 for (n = 0; n < m; ++n) {
1414 if (n + i < l)
1415 fprintf(f, " %02X", p[i + n]);
1416 else
1417 fprintf(f, " ");
1420 if (s->sh_type == SHT_SYMTAB) {
1421 ElfW(Sym) *sym = (ElfW(Sym) *) (p + i);
1422 const char *name = s->link->data + sym->st_name;
1423 fprintf(f, " %04X %04X %04X %02X %02X %02X %04X \"%s\"",
1424 (unsigned)sym->st_name,
1425 (unsigned)sym->st_value,
1426 (unsigned)sym->st_size,
1427 (unsigned)ELFW(ST_BIND)(sym->st_info),
1428 (unsigned)ELFW(ST_TYPE)(sym->st_info),
1429 (unsigned)sym->st_other,
1430 (unsigned)sym->st_shndx,
1431 name);
1433 } else if (s->sh_type == SHT_RELX) {
1434 ElfW_Rel *rel = (ElfW_Rel *) (p + i);
1435 ElfW(Sym) *sym =
1436 (ElfW(Sym) *) s->link->data + ELFW(R_SYM)(rel->r_info);
1437 const char *name = s->link->link->data + sym->st_name;
1438 fprintf(f, " %04X %02X %04X \"%s\"",
1439 (unsigned)rel->r_offset,
1440 (unsigned)ELFW(R_TYPE)(rel->r_info),
1441 (unsigned)ELFW(R_SYM)(rel->r_info),
1442 name);
1443 } else {
1444 fprintf(f, " ");
1445 for (n = 0; n < m; ++n) {
1446 if (n + i < l) {
1447 b = p[i + n];
1448 if (b < 32 || b >= 127)
1449 b = '.';
1450 fprintf(f, "%c", b);
1454 i += m;
1455 fprintf(f, "\n");
1457 fprintf(f, "\n\n");
1460 static void pe_print_sections(TCCState *s1, const char *fname)
1462 Section *s;
1463 FILE *f;
1464 int i;
1465 f = fopen(fname, "w");
1466 for (i = 1; i < s1->nb_sections; ++i) {
1467 s = s1->sections[i];
1468 pe_print_section(f, s);
1470 pe_print_section(f, s1->dynsymtab_section);
1471 fclose(f);
1473 #endif
1475 /* ------------------------------------------------------------- */
1476 /* helper function for load/store to insert one more indirection */
1478 #ifndef TCC_TARGET_ARM
1479 ST_FUNC SValue *pe_getimport(SValue *sv, SValue *v2)
1481 int r2;
1482 if ((sv->r & (VT_VALMASK|VT_SYM)) != (VT_CONST|VT_SYM) || (sv->r2 != VT_CONST))
1483 return sv;
1484 if (!(sv->sym->type.t & VT_IMPORT))
1485 return sv;
1486 // printf("import %04x %04x %04x %s\n", sv->type.t, sv->sym->type.t, sv->r, get_tok_str(sv->sym->v, NULL));
1487 memset(v2, 0, sizeof *v2);
1488 v2->type.t = VT_PTR;
1489 v2->r = VT_CONST | VT_SYM | VT_LVAL;
1490 v2->sym = sv->sym;
1492 r2 = get_reg(RC_INT);
1493 load(r2, v2);
1494 v2->r = r2;
1495 if ((uint32_t)sv->c.i) {
1496 vpushv(v2);
1497 vpushi(sv->c.i);
1498 gen_opi('+');
1499 *v2 = *vtop--;
1501 v2->type.t = sv->type.t;
1502 v2->r |= sv->r & VT_LVAL;
1503 return v2;
1505 #endif
1507 ST_FUNC int pe_putimport(TCCState *s1, int dllindex, const char *name, addr_t value)
1509 return set_elf_sym(
1510 s1->dynsymtab_section,
1511 value,
1512 dllindex, /* st_size */
1513 ELFW(ST_INFO)(STB_GLOBAL, STT_NOTYPE),
1515 value ? SHN_ABS : SHN_UNDEF,
1516 name
1520 static int add_dllref(TCCState *s1, const char *dllname)
1522 DLLReference *dllref;
1523 int i;
1524 for (i = 0; i < s1->nb_loaded_dlls; ++i)
1525 if (0 == strcmp(s1->loaded_dlls[i]->name, dllname))
1526 return i + 1;
1527 dllref = tcc_mallocz(sizeof(DLLReference) + strlen(dllname));
1528 strcpy(dllref->name, dllname);
1529 dynarray_add(&s1->loaded_dlls, &s1->nb_loaded_dlls, dllref);
1530 return s1->nb_loaded_dlls;
1533 /* ------------------------------------------------------------- */
1535 static int read_mem(int fd, unsigned offset, void *buffer, unsigned len)
1537 lseek(fd, offset, SEEK_SET);
1538 return len == read(fd, buffer, len);
1541 /* ------------------------------------------------------------- */
1543 PUB_FUNC int tcc_get_dllexports(const char *filename, char **pp)
1545 int l, i, n, n0, ret;
1546 char *p;
1547 int fd;
1549 IMAGE_SECTION_HEADER ish;
1550 IMAGE_EXPORT_DIRECTORY ied;
1551 IMAGE_DOS_HEADER dh;
1552 IMAGE_FILE_HEADER ih;
1553 DWORD sig, ref, addr, ptr, namep;
1554 #ifdef TCC_TARGET_X86_64
1555 IMAGE_OPTIONAL_HEADER64 oh;
1556 #else
1557 IMAGE_OPTIONAL_HEADER32 oh;
1558 #endif
1559 int pef_hdroffset, opt_hdroffset, sec_hdroffset;
1561 n = n0 = 0;
1562 p = NULL;
1563 ret = -1;
1565 fd = open(filename, O_RDONLY | O_BINARY);
1566 if (fd < 0)
1567 goto the_end_1;
1568 ret = 1;
1570 if (!read_mem(fd, 0, &dh, sizeof dh))
1571 goto the_end;
1572 if (!read_mem(fd, dh.e_lfanew, &sig, sizeof sig))
1573 goto the_end;
1574 if (sig != 0x00004550)
1575 goto the_end;
1576 pef_hdroffset = dh.e_lfanew + sizeof sig;
1577 if (!read_mem(fd, pef_hdroffset, &ih, sizeof ih))
1578 goto the_end;
1579 if (IMAGE_FILE_MACHINE != ih.Machine) {
1580 if (ih.Machine == 0x014C)
1581 ret = 32;
1582 else if (ih.Machine == 0x8664)
1583 ret = 64;
1584 goto the_end;
1586 opt_hdroffset = pef_hdroffset + sizeof ih;
1587 sec_hdroffset = opt_hdroffset + sizeof oh;
1588 if (!read_mem(fd, opt_hdroffset, &oh, sizeof oh))
1589 goto the_end;
1591 if (IMAGE_DIRECTORY_ENTRY_EXPORT >= oh.NumberOfRvaAndSizes)
1592 goto the_end_0;
1594 addr = oh.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress;
1595 //printf("addr: %08x\n", addr);
1596 for (i = 0; i < ih.NumberOfSections; ++i) {
1597 if (!read_mem(fd, sec_hdroffset + i * sizeof ish, &ish, sizeof ish))
1598 goto the_end;
1599 //printf("vaddr: %08x\n", ish.VirtualAddress);
1600 if (addr >= ish.VirtualAddress && addr < ish.VirtualAddress + ish.SizeOfRawData)
1601 goto found;
1603 goto the_end_0;
1605 found:
1606 ref = ish.VirtualAddress - ish.PointerToRawData;
1607 if (!read_mem(fd, addr - ref, &ied, sizeof ied))
1608 goto the_end;
1610 namep = ied.AddressOfNames - ref;
1611 for (i = 0; i < ied.NumberOfNames; ++i) {
1612 if (!read_mem(fd, namep, &ptr, sizeof ptr))
1613 goto the_end;
1614 namep += sizeof ptr;
1615 for (l = 0;;) {
1616 if (n+1 >= n0)
1617 p = tcc_realloc(p, n0 = n0 ? n0 * 2 : 256);
1618 if (!read_mem(fd, ptr - ref + l++, p + n, 1)) {
1619 tcc_free(p), p = NULL;
1620 goto the_end;
1622 if (p[n++] == 0)
1623 break;
1626 if (p)
1627 p[n] = 0;
1628 the_end_0:
1629 ret = 0;
1630 the_end:
1631 close(fd);
1632 the_end_1:
1633 *pp = p;
1634 return ret;
1637 /* -------------------------------------------------------------
1638 * This is for compiled windows resources in 'coff' format
1639 * as generated by 'windres.exe -O coff ...'.
1642 static int pe_load_res(TCCState *s1, int fd)
1644 struct pe_rsrc_header hdr;
1645 Section *rsrc_section;
1646 int i, ret = -1;
1647 BYTE *ptr;
1648 unsigned offs;
1650 if (!read_mem(fd, 0, &hdr, sizeof hdr))
1651 goto quit;
1653 if (hdr.filehdr.Machine != IMAGE_FILE_MACHINE
1654 || hdr.filehdr.NumberOfSections != 1
1655 || strcmp(hdr.sectionhdr.Name, ".rsrc") != 0)
1656 goto quit;
1658 rsrc_section = new_section(s1, ".rsrc", SHT_PROGBITS, SHF_ALLOC);
1659 ptr = section_ptr_add(rsrc_section, hdr.sectionhdr.SizeOfRawData);
1660 offs = hdr.sectionhdr.PointerToRawData;
1661 if (!read_mem(fd, offs, ptr, hdr.sectionhdr.SizeOfRawData))
1662 goto quit;
1663 offs = hdr.sectionhdr.PointerToRelocations;
1664 for (i = 0; i < hdr.sectionhdr.NumberOfRelocations; ++i)
1666 struct pe_rsrc_reloc rel;
1667 if (!read_mem(fd, offs, &rel, sizeof rel))
1668 goto quit;
1669 // printf("rsrc_reloc: %x %x %x\n", rel.offset, rel.size, rel.type);
1670 if (rel.type != RSRC_RELTYPE)
1671 goto quit;
1672 put_elf_reloc(symtab_section, rsrc_section,
1673 rel.offset, R_XXX_RELATIVE, 0);
1674 offs += sizeof rel;
1676 ret = 0;
1677 quit:
1678 return ret;
1681 /* ------------------------------------------------------------- */
1683 static char *trimfront(char *p)
1685 while (*p && (unsigned char)*p <= ' ')
1686 ++p;
1687 return p;
1690 static char *trimback(char *a, char *e)
1692 while (e > a && (unsigned char)e[-1] <= ' ')
1693 --e;
1694 *e = 0;;
1695 return a;
1698 /* ------------------------------------------------------------- */
1699 static int pe_load_def(TCCState *s1, int fd)
1701 int state = 0, ret = -1, dllindex = 0, ord;
1702 char line[400], dllname[80], *p, *x;
1703 FILE *fp;
1705 fp = fdopen(dup(fd), "rb");
1706 while (fgets(line, sizeof line, fp))
1708 p = trimfront(trimback(line, strchr(line, 0)));
1709 if (0 == *p || ';' == *p)
1710 continue;
1712 switch (state) {
1713 case 0:
1714 if (0 != strnicmp(p, "LIBRARY", 7))
1715 goto quit;
1716 pstrcpy(dllname, sizeof dllname, trimfront(p+7));
1717 ++state;
1718 continue;
1720 case 1:
1721 if (0 != stricmp(p, "EXPORTS"))
1722 goto quit;
1723 ++state;
1724 continue;
1726 case 2:
1727 dllindex = add_dllref(s1, dllname);
1728 ++state;
1729 /* fall through */
1730 default:
1731 /* get ordinal and will store in sym->st_value */
1732 ord = 0;
1733 x = strchr(p, ' ');
1734 if (x) {
1735 *x = 0, x = strrchr(x + 1, '@');
1736 if (x) {
1737 char *d;
1738 ord = (int)strtol(x + 1, &d, 10);
1739 if (*d)
1740 ord = 0;
1743 pe_putimport(s1, dllindex, p, ord);
1744 continue;
1747 ret = 0;
1748 quit:
1749 fclose(fp);
1750 return ret;
1753 /* ------------------------------------------------------------- */
1754 static int pe_load_dll(TCCState *s1, const char *filename)
1756 char *p, *q;
1757 int index, ret;
1759 ret = tcc_get_dllexports(filename, &p);
1760 if (ret) {
1761 return -1;
1762 } else if (p) {
1763 index = add_dllref(s1, tcc_basename(filename));
1764 for (q = p; *q; q += 1 + strlen(q))
1765 pe_putimport(s1, index, q, 0);
1766 tcc_free(p);
1768 return 0;
1771 /* ------------------------------------------------------------- */
1772 ST_FUNC int pe_load_file(struct TCCState *s1, const char *filename, int fd)
1774 int ret = -1;
1775 char buf[10];
1776 if (0 == strcmp(tcc_fileextension(filename), ".def"))
1777 ret = pe_load_def(s1, fd);
1778 else if (pe_load_res(s1, fd) == 0)
1779 ret = 0;
1780 else if (read_mem(fd, 0, buf, 4) && 0 == memcmp(buf, "MZ\220", 4))
1781 ret = pe_load_dll(s1, filename);
1782 return ret;
1785 /* ------------------------------------------------------------- */
1786 #ifdef TCC_TARGET_X86_64
1787 static unsigned pe_add_uwwind_info(TCCState *s1)
1789 if (NULL == s1->uw_pdata) {
1790 s1->uw_pdata = find_section(tcc_state, ".pdata");
1791 s1->uw_pdata->sh_addralign = 4;
1792 s1->uw_sym = put_elf_sym(symtab_section, 0, 0, 0, 0, text_section->sh_num, NULL);
1795 if (0 == s1->uw_offs) {
1796 /* As our functions all have the same stackframe, we use one entry for all */
1797 static const unsigned char uw_info[] = {
1798 0x01, // UBYTE: 3 Version , UBYTE: 5 Flags
1799 0x04, // UBYTE Size of prolog
1800 0x02, // UBYTE Count of unwind codes
1801 0x05, // UBYTE: 4 Frame Register (rbp), UBYTE: 4 Frame Register offset (scaled)
1802 // USHORT * n Unwind codes array
1803 // 0x0b, 0x01, 0xff, 0xff, // stack size
1804 0x04, 0x03, // set frame ptr (mov rsp -> rbp)
1805 0x01, 0x50 // push reg (rbp)
1808 Section *s = text_section;
1809 unsigned char *p;
1811 section_ptr_add(s, -s->data_offset & 3); /* align */
1812 s1->uw_offs = s->data_offset;
1813 p = section_ptr_add(s, sizeof uw_info);
1814 memcpy(p, uw_info, sizeof uw_info);
1817 return s1->uw_offs;
1820 ST_FUNC void pe_add_unwind_data(unsigned start, unsigned end, unsigned stack)
1822 TCCState *s1 = tcc_state;
1823 Section *pd;
1824 unsigned o, n, d;
1825 struct /* _RUNTIME_FUNCTION */ {
1826 DWORD BeginAddress;
1827 DWORD EndAddress;
1828 DWORD UnwindData;
1829 } *p;
1831 d = pe_add_uwwind_info(s1);
1832 pd = s1->uw_pdata;
1833 o = pd->data_offset;
1834 p = section_ptr_add(pd, sizeof *p);
1836 /* record this function */
1837 p->BeginAddress = start;
1838 p->EndAddress = end;
1839 p->UnwindData = d;
1841 /* put relocations on it */
1842 for (n = o + sizeof *p; o < n; o += sizeof p->BeginAddress)
1843 put_elf_reloc(symtab_section, pd, o, R_X86_64_RELATIVE, s1->uw_sym);
1845 #endif
1846 /* ------------------------------------------------------------- */
1847 #ifdef TCC_TARGET_X86_64
1848 #define PE_STDSYM(n,s) n
1849 #else
1850 #define PE_STDSYM(n,s) "_" n s
1851 #endif
1853 static void pe_add_runtime(TCCState *s1, struct pe_info *pe)
1855 const char *start_symbol;
1856 int pe_type = 0;
1857 int unicode_entry = 0;
1859 if (find_elf_sym(symtab_section, PE_STDSYM("WinMain","@16")))
1860 pe_type = PE_GUI;
1861 else
1862 if (find_elf_sym(symtab_section, PE_STDSYM("wWinMain","@16"))) {
1863 pe_type = PE_GUI;
1864 unicode_entry = PE_GUI;
1866 else
1867 if (TCC_OUTPUT_DLL == s1->output_type) {
1868 pe_type = PE_DLL;
1869 /* need this for 'tccelf.c:relocate_section()' */
1870 s1->output_type = TCC_OUTPUT_EXE;
1872 else {
1873 pe_type = PE_EXE;
1874 if (find_elf_sym(symtab_section, "wmain"))
1875 unicode_entry = PE_EXE;
1878 start_symbol =
1879 TCC_OUTPUT_MEMORY == s1->output_type
1880 ? PE_GUI == pe_type ? (unicode_entry ? "__runwwinmain" : "__runwinmain")
1881 : (unicode_entry ? "__runwmain" : "__runmain")
1882 : PE_DLL == pe_type ? PE_STDSYM("__dllstart","@12")
1883 : PE_GUI == pe_type ? (unicode_entry ? "__wwinstart": "__winstart")
1884 : (unicode_entry ? "__wstart" : "__start")
1887 if (!s1->leading_underscore || strchr(start_symbol, '@'))
1888 ++start_symbol;
1890 /* grab the startup code from libtcc1 */
1891 #ifdef TCC_IS_NATIVE
1892 if (TCC_OUTPUT_MEMORY != s1->output_type || s1->runtime_main)
1893 #endif
1894 set_elf_sym(symtab_section,
1895 0, 0,
1896 ELFW(ST_INFO)(STB_GLOBAL, STT_NOTYPE), 0,
1897 SHN_UNDEF, start_symbol);
1899 tcc_add_pragma_libs(s1);
1901 if (0 == s1->nostdlib) {
1902 static const char *libs[] = {
1903 TCC_LIBTCC1, "msvcrt", "kernel32", "", "user32", "gdi32", NULL
1905 const char **pp, *p;
1906 for (pp = libs; 0 != (p = *pp); ++pp) {
1907 if (0 == *p) {
1908 if (PE_DLL != pe_type && PE_GUI != pe_type)
1909 break;
1910 } else if (pp == libs && tcc_add_dll(s1, p, 0) >= 0) {
1911 continue;
1912 } else {
1913 tcc_add_library_err(s1, p);
1918 if (TCC_OUTPUT_MEMORY == s1->output_type)
1919 pe_type = PE_RUN;
1920 pe->type = pe_type;
1921 pe->start_symbol = start_symbol;
1924 static void pe_set_options(TCCState * s1, struct pe_info *pe)
1926 if (PE_DLL == pe->type) {
1927 /* XXX: check if is correct for arm-pe target */
1928 pe->imagebase = 0x10000000;
1929 } else {
1930 #if defined(TCC_TARGET_ARM)
1931 pe->imagebase = 0x00010000;
1932 #else
1933 pe->imagebase = 0x00400000;
1934 #endif
1937 #if defined(TCC_TARGET_ARM)
1938 /* we use "console" subsystem by default */
1939 pe->subsystem = 9;
1940 #else
1941 if (PE_DLL == pe->type || PE_GUI == pe->type)
1942 pe->subsystem = 2;
1943 else
1944 pe->subsystem = 3;
1945 #endif
1946 /* Allow override via -Wl,-subsystem=... option */
1947 if (s1->pe_subsystem != 0)
1948 pe->subsystem = s1->pe_subsystem;
1950 /* set default file/section alignment */
1951 if (pe->subsystem == 1) {
1952 pe->section_align = 0x20;
1953 pe->file_align = 0x20;
1954 } else {
1955 pe->section_align = 0x1000;
1956 pe->file_align = 0x200;
1959 if (s1->section_align != 0)
1960 pe->section_align = s1->section_align;
1961 if (s1->pe_file_align != 0)
1962 pe->file_align = s1->pe_file_align;
1964 if ((pe->subsystem >= 10) && (pe->subsystem <= 12))
1965 pe->imagebase = 0;
1967 if (s1->has_text_addr)
1968 pe->imagebase = s1->text_addr;
1971 ST_FUNC int pe_output_file(TCCState *s1, const char *filename)
1973 int ret;
1974 struct pe_info pe;
1975 int i;
1977 memset(&pe, 0, sizeof pe);
1978 pe.filename = filename;
1979 pe.s1 = s1;
1981 tcc_add_bcheck(s1);
1982 pe_add_runtime(s1, &pe);
1983 relocate_common_syms(); /* assign bss adresses */
1984 tcc_add_linker_symbols(s1);
1985 pe_set_options(s1, &pe);
1987 ret = pe_check_symbols(&pe);
1988 if (ret)
1990 else if (filename) {
1991 pe_assign_addresses(&pe);
1992 relocate_syms(s1, s1->symtab, 0);
1993 for (i = 1; i < s1->nb_sections; ++i) {
1994 Section *s = s1->sections[i];
1995 if (s->reloc) {
1996 relocate_section(s1, s);
1997 pe_relocate_rva(&pe, s);
2000 pe.start_addr = (DWORD)
2001 ((uintptr_t)tcc_get_symbol_err(s1, pe.start_symbol)
2002 - pe.imagebase);
2003 if (s1->nb_errors)
2004 ret = -1;
2005 else
2006 ret = pe_write(&pe);
2007 tcc_free(pe.sec_info);
2008 } else {
2009 #ifdef TCC_IS_NATIVE
2010 pe.thunk = data_section;
2011 pe_build_imports(&pe);
2012 s1->runtime_main = pe.start_symbol;
2013 #endif
2016 pe_free_imports(&pe);
2018 #ifdef PE_PRINT_SECTIONS
2019 pe_print_sections(s1, "tcc.log");
2020 #endif
2021 return ret;
2024 /* ------------------------------------------------------------- */