called function should pop the arguments when using fastcall
[tinycc.git] / tccpe.c
blob366f0e7ed94bd55ccb85c8dd54db1e38089922ca
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 #ifdef TCC_TARGET_X86_64
32 # define ADDR3264 ULONGLONG
33 # define REL_TYPE_DIRECT R_X86_64_64
34 # define R_XXX_THUNKFIX R_X86_64_PC32
35 # define R_XXX_RELATIVE R_X86_64_RELATIVE
36 # define IMAGE_FILE_MACHINE 0x8664
37 # define RSRC_RELTYPE 3
39 #elif defined TCC_TARGET_ARM
40 # define ADDR3264 DWORD
41 # define REL_TYPE_DIRECT R_ARM_ABS32
42 # define R_XXX_THUNKFIX R_ARM_ABS32
43 # define R_XXX_RELATIVE R_ARM_RELATIVE
44 # define IMAGE_FILE_MACHINE 0x01C0
45 # define RSRC_RELTYPE 7 /* ??? (not tested) */
47 #elif defined TCC_TARGET_I386
48 # define ADDR3264 DWORD
49 # define REL_TYPE_DIRECT R_386_32
50 # define R_XXX_THUNKFIX R_386_32
51 # define R_XXX_RELATIVE R_386_RELATIVE
52 # define IMAGE_FILE_MACHINE 0x014C
53 # define RSRC_RELTYPE 7 /* DIR32NB */
55 #endif
57 #if 0
58 #ifdef _WIN32
59 void dbg_printf (const char *fmt, ...)
61 char buffer[4000];
62 va_list arg;
63 int x;
64 va_start(arg, fmt);
65 x = vsprintf (buffer, fmt, arg);
66 strcpy(buffer+x, "\n");
67 OutputDebugString(buffer);
69 #endif
70 #endif
72 /* ----------------------------------------------------------- */
73 #ifndef IMAGE_NT_SIGNATURE
74 /* ----------------------------------------------------------- */
75 /* definitions below are from winnt.h */
77 typedef unsigned char BYTE;
78 typedef unsigned short WORD;
79 typedef unsigned int DWORD;
80 typedef unsigned long long ULONGLONG;
81 #pragma pack(push, 1)
83 typedef struct _IMAGE_DOS_HEADER { /* DOS .EXE header */
84 WORD e_magic; /* Magic number */
85 WORD e_cblp; /* Bytes on last page of file */
86 WORD e_cp; /* Pages in file */
87 WORD e_crlc; /* Relocations */
88 WORD e_cparhdr; /* Size of header in paragraphs */
89 WORD e_minalloc; /* Minimum extra paragraphs needed */
90 WORD e_maxalloc; /* Maximum extra paragraphs needed */
91 WORD e_ss; /* Initial (relative) SS value */
92 WORD e_sp; /* Initial SP value */
93 WORD e_csum; /* Checksum */
94 WORD e_ip; /* Initial IP value */
95 WORD e_cs; /* Initial (relative) CS value */
96 WORD e_lfarlc; /* File address of relocation table */
97 WORD e_ovno; /* Overlay number */
98 WORD e_res[4]; /* Reserved words */
99 WORD e_oemid; /* OEM identifier (for e_oeminfo) */
100 WORD e_oeminfo; /* OEM information; e_oemid specific */
101 WORD e_res2[10]; /* Reserved words */
102 DWORD e_lfanew; /* File address of new exe header */
103 } IMAGE_DOS_HEADER, *PIMAGE_DOS_HEADER;
105 #define IMAGE_NT_SIGNATURE 0x00004550 /* PE00 */
106 #define SIZE_OF_NT_SIGNATURE 4
108 typedef struct _IMAGE_FILE_HEADER {
109 WORD Machine;
110 WORD NumberOfSections;
111 DWORD TimeDateStamp;
112 DWORD PointerToSymbolTable;
113 DWORD NumberOfSymbols;
114 WORD SizeOfOptionalHeader;
115 WORD Characteristics;
116 } IMAGE_FILE_HEADER, *PIMAGE_FILE_HEADER;
119 #define IMAGE_SIZEOF_FILE_HEADER 20
121 typedef struct _IMAGE_DATA_DIRECTORY {
122 DWORD VirtualAddress;
123 DWORD Size;
124 } IMAGE_DATA_DIRECTORY, *PIMAGE_DATA_DIRECTORY;
127 typedef struct _IMAGE_OPTIONAL_HEADER {
128 /* Standard fields. */
129 WORD Magic;
130 BYTE MajorLinkerVersion;
131 BYTE MinorLinkerVersion;
132 DWORD SizeOfCode;
133 DWORD SizeOfInitializedData;
134 DWORD SizeOfUninitializedData;
135 DWORD AddressOfEntryPoint;
136 DWORD BaseOfCode;
137 #ifndef TCC_TARGET_X86_64
138 DWORD BaseOfData;
139 #endif
140 /* NT additional fields. */
141 ADDR3264 ImageBase;
142 DWORD SectionAlignment;
143 DWORD FileAlignment;
144 WORD MajorOperatingSystemVersion;
145 WORD MinorOperatingSystemVersion;
146 WORD MajorImageVersion;
147 WORD MinorImageVersion;
148 WORD MajorSubsystemVersion;
149 WORD MinorSubsystemVersion;
150 DWORD Win32VersionValue;
151 DWORD SizeOfImage;
152 DWORD SizeOfHeaders;
153 DWORD CheckSum;
154 WORD Subsystem;
155 WORD DllCharacteristics;
156 ADDR3264 SizeOfStackReserve;
157 ADDR3264 SizeOfStackCommit;
158 ADDR3264 SizeOfHeapReserve;
159 ADDR3264 SizeOfHeapCommit;
160 DWORD LoaderFlags;
161 DWORD NumberOfRvaAndSizes;
162 IMAGE_DATA_DIRECTORY DataDirectory[16];
163 } IMAGE_OPTIONAL_HEADER32, IMAGE_OPTIONAL_HEADER64, IMAGE_OPTIONAL_HEADER;
165 #define IMAGE_DIRECTORY_ENTRY_EXPORT 0 /* Export Directory */
166 #define IMAGE_DIRECTORY_ENTRY_IMPORT 1 /* Import Directory */
167 #define IMAGE_DIRECTORY_ENTRY_RESOURCE 2 /* Resource Directory */
168 #define IMAGE_DIRECTORY_ENTRY_EXCEPTION 3 /* Exception Directory */
169 #define IMAGE_DIRECTORY_ENTRY_SECURITY 4 /* Security Directory */
170 #define IMAGE_DIRECTORY_ENTRY_BASERELOC 5 /* Base Relocation Table */
171 #define IMAGE_DIRECTORY_ENTRY_DEBUG 6 /* Debug Directory */
172 /* IMAGE_DIRECTORY_ENTRY_COPYRIGHT 7 (X86 usage) */
173 #define IMAGE_DIRECTORY_ENTRY_ARCHITECTURE 7 /* Architecture Specific Data */
174 #define IMAGE_DIRECTORY_ENTRY_GLOBALPTR 8 /* RVA of GP */
175 #define IMAGE_DIRECTORY_ENTRY_TLS 9 /* TLS Directory */
176 #define IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG 10 /* Load Configuration Directory */
177 #define IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT 11 /* Bound Import Directory in headers */
178 #define IMAGE_DIRECTORY_ENTRY_IAT 12 /* Import Address Table */
179 #define IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT 13 /* Delay Load Import Descriptors */
180 #define IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR 14 /* COM Runtime descriptor */
182 /* Section header format. */
183 #define IMAGE_SIZEOF_SHORT_NAME 8
185 typedef struct _IMAGE_SECTION_HEADER {
186 BYTE Name[IMAGE_SIZEOF_SHORT_NAME];
187 union {
188 DWORD PhysicalAddress;
189 DWORD VirtualSize;
190 } Misc;
191 DWORD VirtualAddress;
192 DWORD SizeOfRawData;
193 DWORD PointerToRawData;
194 DWORD PointerToRelocations;
195 DWORD PointerToLinenumbers;
196 WORD NumberOfRelocations;
197 WORD NumberOfLinenumbers;
198 DWORD Characteristics;
199 } IMAGE_SECTION_HEADER, *PIMAGE_SECTION_HEADER;
201 #define IMAGE_SIZEOF_SECTION_HEADER 40
203 typedef struct _IMAGE_EXPORT_DIRECTORY {
204 DWORD Characteristics;
205 DWORD TimeDateStamp;
206 WORD MajorVersion;
207 WORD MinorVersion;
208 DWORD Name;
209 DWORD Base;
210 DWORD NumberOfFunctions;
211 DWORD NumberOfNames;
212 DWORD AddressOfFunctions;
213 DWORD AddressOfNames;
214 DWORD AddressOfNameOrdinals;
215 } IMAGE_EXPORT_DIRECTORY,*PIMAGE_EXPORT_DIRECTORY;
217 typedef struct _IMAGE_IMPORT_DESCRIPTOR {
218 union {
219 DWORD Characteristics;
220 DWORD OriginalFirstThunk;
222 DWORD TimeDateStamp;
223 DWORD ForwarderChain;
224 DWORD Name;
225 DWORD FirstThunk;
226 } IMAGE_IMPORT_DESCRIPTOR;
228 typedef struct _IMAGE_BASE_RELOCATION {
229 DWORD VirtualAddress;
230 DWORD SizeOfBlock;
231 // WORD TypeOffset[1];
232 } IMAGE_BASE_RELOCATION;
234 #define IMAGE_SIZEOF_BASE_RELOCATION 8
236 #define IMAGE_REL_BASED_ABSOLUTE 0
237 #define IMAGE_REL_BASED_HIGH 1
238 #define IMAGE_REL_BASED_LOW 2
239 #define IMAGE_REL_BASED_HIGHLOW 3
240 #define IMAGE_REL_BASED_HIGHADJ 4
241 #define IMAGE_REL_BASED_MIPS_JMPADDR 5
242 #define IMAGE_REL_BASED_SECTION 6
243 #define IMAGE_REL_BASED_REL32 7
245 #pragma pack(pop)
247 /* ----------------------------------------------------------- */
248 #endif /* ndef IMAGE_NT_SIGNATURE */
249 /* ----------------------------------------------------------- */
250 #pragma pack(push, 1)
252 struct pe_header
254 IMAGE_DOS_HEADER doshdr;
255 BYTE dosstub[0x40];
256 DWORD nt_sig;
257 IMAGE_FILE_HEADER filehdr;
258 #ifdef TCC_TARGET_X86_64
259 IMAGE_OPTIONAL_HEADER64 opthdr;
260 #else
261 #ifdef _WIN64
262 IMAGE_OPTIONAL_HEADER32 opthdr;
263 #else
264 IMAGE_OPTIONAL_HEADER opthdr;
265 #endif
266 #endif
269 struct pe_reloc_header {
270 DWORD offset;
271 DWORD size;
274 struct pe_rsrc_header {
275 struct _IMAGE_FILE_HEADER filehdr;
276 struct _IMAGE_SECTION_HEADER sectionhdr;
279 struct pe_rsrc_reloc {
280 DWORD offset;
281 DWORD size;
282 WORD type;
285 #pragma pack(pop)
287 /* ------------------------------------------------------------- */
288 /* internal temporary structures */
291 #define IMAGE_SCN_CNT_CODE 0x00000020
292 #define IMAGE_SCN_CNT_INITIALIZED_DATA 0x00000040
293 #define IMAGE_SCN_CNT_UNINITIALIZED_DATA 0x00000080
294 #define IMAGE_SCN_MEM_DISCARDABLE 0x02000000
295 #define IMAGE_SCN_MEM_SHARED 0x10000000
296 #define IMAGE_SCN_MEM_EXECUTE 0x20000000
297 #define IMAGE_SCN_MEM_READ 0x40000000
298 #define IMAGE_SCN_MEM_WRITE 0x80000000
301 enum {
302 sec_text = 0,
303 sec_data ,
304 sec_bss ,
305 sec_idata ,
306 sec_pdata ,
307 sec_other ,
308 sec_rsrc ,
309 sec_stab ,
310 sec_reloc ,
311 sec_last
314 static const DWORD pe_sec_flags[] = {
315 0x60000020, /* ".text" , */
316 0xC0000040, /* ".data" , */
317 0xC0000080, /* ".bss" , */
318 0x40000040, /* ".idata" , */
319 0x40000040, /* ".pdata" , */
320 0xE0000060, /* < other > , */
321 0x40000040, /* ".rsrc" , */
322 0x42000802, /* ".stab" , */
323 0x42000040, /* ".reloc" , */
326 struct section_info {
327 int cls, ord;
328 char name[32];
329 DWORD sh_addr;
330 DWORD sh_size;
331 DWORD sh_flags;
332 unsigned char *data;
333 DWORD data_size;
334 IMAGE_SECTION_HEADER ish;
337 struct import_symbol {
338 int sym_index;
339 int iat_index;
340 int thk_offset;
343 struct pe_import_info {
344 int dll_index;
345 int sym_count;
346 struct import_symbol **symbols;
349 struct pe_info {
350 TCCState *s1;
351 Section *reloc;
352 Section *thunk;
353 const char *filename;
354 int type;
355 DWORD sizeofheaders;
356 ADDR3264 imagebase;
357 const char *start_symbol;
358 DWORD start_addr;
359 DWORD imp_offs;
360 DWORD imp_size;
361 DWORD iat_offs;
362 DWORD iat_size;
363 DWORD exp_offs;
364 DWORD exp_size;
365 int subsystem;
366 DWORD section_align;
367 DWORD file_align;
368 struct section_info *sec_info;
369 int sec_count;
370 struct pe_import_info **imp_info;
371 int imp_count;
374 #define PE_NUL 0
375 #define PE_DLL 1
376 #define PE_GUI 2
377 #define PE_EXE 3
378 #define PE_RUN 4
380 /* --------------------------------------------*/
382 static const char *pe_export_name(TCCState *s1, ElfW(Sym) *sym)
384 const char *name = (char*)symtab_section->link->data + sym->st_name;
385 if (s1->leading_underscore && name[0] == '_' && !(sym->st_other & ST_PE_STDCALL))
386 return name + 1;
387 return name;
390 static int pe_find_import(TCCState * s1, ElfW(Sym) *sym)
392 char buffer[200];
393 const char *s, *p;
394 int sym_index = 0, n = 0;
395 int a, err = 0;
397 do {
398 s = pe_export_name(s1, sym);
399 a = 0;
400 if (n) {
401 /* second try: */
402 if (sym->st_other & ST_PE_STDCALL) {
403 /* try w/0 stdcall deco (windows API convention) */
404 p = strrchr(s, '@');
405 if (!p || s[0] != '_')
406 break;
407 strcpy(buffer, s+1)[p-s-1] = 0;
408 } else if (s[0] != '_') { /* try non-ansi function */
409 buffer[0] = '_', strcpy(buffer + 1, s);
410 } else if (0 == memcmp(s, "__imp_", 6)) { /* mingw 2.0 */
411 strcpy(buffer, s + 6), a = 1;
412 } else if (0 == memcmp(s, "_imp__", 6)) { /* mingw 3.7 */
413 strcpy(buffer, s + 6), a = 1;
414 } else {
415 continue;
417 s = buffer;
419 sym_index = find_elf_sym(s1->dynsymtab_section, s);
420 // printf("find (%d) %d %s\n", n, sym_index, s);
421 if (sym_index
422 && ELFW(ST_TYPE)(sym->st_info) == STT_OBJECT
423 && 0 == (sym->st_other & ST_PE_IMPORT)
424 && 0 == a
425 ) err = -1, sym_index = 0;
426 } while (0 == sym_index && ++n < 2);
427 return n == 2 ? err : sym_index;
430 /*----------------------------------------------------------------------------*/
432 static int dynarray_assoc(void **pp, int n, int key)
434 int i;
435 for (i = 0; i < n; ++i, ++pp)
436 if (key == **(int **) pp)
437 return i;
438 return -1;
441 #if 0
442 ST_FN DWORD umin(DWORD a, DWORD b)
444 return a < b ? a : b;
446 #endif
448 static DWORD umax(DWORD a, DWORD b)
450 return a < b ? b : a;
453 static DWORD pe_file_align(struct pe_info *pe, DWORD n)
455 return (n + (pe->file_align - 1)) & ~(pe->file_align - 1);
458 static DWORD pe_virtual_align(struct pe_info *pe, DWORD n)
460 return (n + (pe->section_align - 1)) & ~(pe->section_align - 1);
463 static void pe_align_section(Section *s, int a)
465 int i = s->data_offset & (a-1);
466 if (i)
467 section_ptr_add(s, a - i);
470 static void pe_set_datadir(struct pe_header *hdr, int dir, DWORD addr, DWORD size)
472 hdr->opthdr.DataDirectory[dir].VirtualAddress = addr;
473 hdr->opthdr.DataDirectory[dir].Size = size;
476 static int pe_fwrite(void *data, unsigned len, FILE *fp, DWORD *psum)
478 if (psum) {
479 DWORD sum = *psum;
480 WORD *p = data;
481 int i;
482 for (i = len; i > 0; i -= 2) {
483 sum += (i >= 2) ? *p++ : *(BYTE*)p;
484 sum = (sum + (sum >> 16)) & 0xFFFF;
486 *psum = sum;
488 return len == fwrite(data, 1, len, fp) ? 0 : -1;
491 static void pe_fpad(FILE *fp, DWORD new_pos)
493 DWORD pos = ftell(fp);
494 while (++pos <= new_pos)
495 fputc(0, fp);
498 /*----------------------------------------------------------------------------*/
499 static int pe_write(struct pe_info *pe)
501 static const struct pe_header pe_template = {
503 /* IMAGE_DOS_HEADER doshdr */
504 0x5A4D, /*WORD e_magic; Magic number */
505 0x0090, /*WORD e_cblp; Bytes on last page of file */
506 0x0003, /*WORD e_cp; Pages in file */
507 0x0000, /*WORD e_crlc; Relocations */
509 0x0004, /*WORD e_cparhdr; Size of header in paragraphs */
510 0x0000, /*WORD e_minalloc; Minimum extra paragraphs needed */
511 0xFFFF, /*WORD e_maxalloc; Maximum extra paragraphs needed */
512 0x0000, /*WORD e_ss; Initial (relative) SS value */
514 0x00B8, /*WORD e_sp; Initial SP value */
515 0x0000, /*WORD e_csum; Checksum */
516 0x0000, /*WORD e_ip; Initial IP value */
517 0x0000, /*WORD e_cs; Initial (relative) CS value */
518 0x0040, /*WORD e_lfarlc; File address of relocation table */
519 0x0000, /*WORD e_ovno; Overlay number */
520 {0,0,0,0}, /*WORD e_res[4]; Reserved words */
521 0x0000, /*WORD e_oemid; OEM identifier (for e_oeminfo) */
522 0x0000, /*WORD e_oeminfo; OEM information; e_oemid specific */
523 {0,0,0,0,0,0,0,0,0,0}, /*WORD e_res2[10]; Reserved words */
524 0x00000080 /*DWORD e_lfanew; File address of new exe header */
526 /* BYTE dosstub[0x40] */
527 /* 14 code bytes + "This program cannot be run in DOS mode.\r\r\n$" + 6 * 0x00 */
528 0x0e,0x1f,0xba,0x0e,0x00,0xb4,0x09,0xcd,0x21,0xb8,0x01,0x4c,0xcd,0x21,0x54,0x68,
529 0x69,0x73,0x20,0x70,0x72,0x6f,0x67,0x72,0x61,0x6d,0x20,0x63,0x61,0x6e,0x6e,0x6f,
530 0x74,0x20,0x62,0x65,0x20,0x72,0x75,0x6e,0x20,0x69,0x6e,0x20,0x44,0x4f,0x53,0x20,
531 0x6d,0x6f,0x64,0x65,0x2e,0x0d,0x0d,0x0a,0x24,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
533 0x00004550, /* DWORD nt_sig = IMAGE_NT_SIGNATURE */
535 /* IMAGE_FILE_HEADER filehdr */
536 IMAGE_FILE_MACHINE, /*WORD Machine; */
537 0x0003, /*WORD NumberOfSections; */
538 0x00000000, /*DWORD TimeDateStamp; */
539 0x00000000, /*DWORD PointerToSymbolTable; */
540 0x00000000, /*DWORD NumberOfSymbols; */
541 #if defined(TCC_TARGET_X86_64)
542 0x00F0, /*WORD SizeOfOptionalHeader; */
543 0x022F /*WORD Characteristics; */
544 #define CHARACTERISTICS_DLL 0x222E
545 #elif defined(TCC_TARGET_I386)
546 0x00E0, /*WORD SizeOfOptionalHeader; */
547 0x030F /*WORD Characteristics; */
548 #define CHARACTERISTICS_DLL 0x230E
549 #elif defined(TCC_TARGET_ARM)
550 0x00E0, /*WORD SizeOfOptionalHeader; */
551 0x010F, /*WORD Characteristics; */
552 #define CHARACTERISTICS_DLL 0x230F
553 #endif
555 /* IMAGE_OPTIONAL_HEADER opthdr */
556 /* Standard fields. */
557 #ifdef TCC_TARGET_X86_64
558 0x020B, /*WORD Magic; */
559 #else
560 0x010B, /*WORD Magic; */
561 #endif
562 0x06, /*BYTE MajorLinkerVersion; */
563 0x00, /*BYTE MinorLinkerVersion; */
564 0x00000000, /*DWORD SizeOfCode; */
565 0x00000000, /*DWORD SizeOfInitializedData; */
566 0x00000000, /*DWORD SizeOfUninitializedData; */
567 0x00000000, /*DWORD AddressOfEntryPoint; */
568 0x00000000, /*DWORD BaseOfCode; */
569 #ifndef TCC_TARGET_X86_64
570 0x00000000, /*DWORD BaseOfData; */
571 #endif
572 /* NT additional fields. */
573 #if defined(TCC_TARGET_ARM)
574 0x00100000, /*DWORD ImageBase; */
575 #else
576 0x00400000, /*DWORD ImageBase; */
577 #endif
578 0x00001000, /*DWORD SectionAlignment; */
579 0x00000200, /*DWORD FileAlignment; */
580 0x0004, /*WORD MajorOperatingSystemVersion; */
581 0x0000, /*WORD MinorOperatingSystemVersion; */
582 0x0000, /*WORD MajorImageVersion; */
583 0x0000, /*WORD MinorImageVersion; */
584 0x0004, /*WORD MajorSubsystemVersion; */
585 0x0000, /*WORD MinorSubsystemVersion; */
586 0x00000000, /*DWORD Win32VersionValue; */
587 0x00000000, /*DWORD SizeOfImage; */
588 0x00000200, /*DWORD SizeOfHeaders; */
589 0x00000000, /*DWORD CheckSum; */
590 0x0002, /*WORD Subsystem; */
591 0x0000, /*WORD DllCharacteristics; */
592 0x00100000, /*DWORD SizeOfStackReserve; */
593 0x00001000, /*DWORD SizeOfStackCommit; */
594 0x00100000, /*DWORD SizeOfHeapReserve; */
595 0x00001000, /*DWORD SizeOfHeapCommit; */
596 0x00000000, /*DWORD LoaderFlags; */
597 0x00000010, /*DWORD NumberOfRvaAndSizes; */
599 /* IMAGE_DATA_DIRECTORY DataDirectory[16]; */
600 {{0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0},
601 {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}}
604 struct pe_header pe_header = pe_template;
606 int i;
607 FILE *op;
608 DWORD file_offset, sum;
609 struct section_info *si;
610 IMAGE_SECTION_HEADER *psh;
612 op = fopen(pe->filename, "wb");
613 if (NULL == op) {
614 tcc_error_noabort("could not write '%s': %s", pe->filename, strerror(errno));
615 return -1;
618 pe->sizeofheaders = pe_file_align(pe,
619 sizeof (struct pe_header)
620 + pe->sec_count * sizeof (IMAGE_SECTION_HEADER)
623 file_offset = pe->sizeofheaders;
625 if (2 == pe->s1->verbose)
626 printf("-------------------------------"
627 "\n virt file size section" "\n");
628 for (i = 0; i < pe->sec_count; ++i) {
629 DWORD addr, size;
630 const char *sh_name;
632 si = pe->sec_info + i;
633 sh_name = si->name;
634 addr = si->sh_addr - pe->imagebase;
635 size = si->sh_size;
636 psh = &si->ish;
638 if (2 == pe->s1->verbose)
639 printf("%6x %6x %6x %s\n",
640 (unsigned)addr, (unsigned)file_offset, (unsigned)size, sh_name);
642 switch (si->cls) {
643 case sec_text:
644 pe_header.opthdr.BaseOfCode = addr;
645 break;
647 case sec_data:
648 #ifndef TCC_TARGET_X86_64
649 pe_header.opthdr.BaseOfData = addr;
650 #endif
651 break;
653 case sec_bss:
654 break;
656 case sec_reloc:
657 pe_set_datadir(&pe_header, IMAGE_DIRECTORY_ENTRY_BASERELOC, addr, size);
658 break;
660 case sec_rsrc:
661 pe_set_datadir(&pe_header, IMAGE_DIRECTORY_ENTRY_RESOURCE, addr, size);
662 break;
664 case sec_pdata:
665 pe_set_datadir(&pe_header, IMAGE_DIRECTORY_ENTRY_EXCEPTION, addr, size);
666 break;
668 case sec_stab:
669 break;
672 if (pe->thunk == pe->s1->sections[si->ord]) {
673 if (pe->imp_size) {
674 pe_set_datadir(&pe_header, IMAGE_DIRECTORY_ENTRY_IMPORT,
675 pe->imp_offs + addr, pe->imp_size);
676 pe_set_datadir(&pe_header, IMAGE_DIRECTORY_ENTRY_IAT,
677 pe->iat_offs + addr, pe->iat_size);
679 if (pe->exp_size) {
680 pe_set_datadir(&pe_header, IMAGE_DIRECTORY_ENTRY_EXPORT,
681 pe->exp_offs + addr, pe->exp_size);
685 strncpy((char*)psh->Name, sh_name, sizeof psh->Name);
687 psh->Characteristics = pe_sec_flags[si->cls];
688 psh->VirtualAddress = addr;
689 psh->Misc.VirtualSize = size;
690 pe_header.opthdr.SizeOfImage =
691 umax(pe_virtual_align(pe, size + addr), pe_header.opthdr.SizeOfImage);
693 if (si->data_size) {
694 psh->PointerToRawData = file_offset;
695 file_offset = pe_file_align(pe, file_offset + si->data_size);
696 psh->SizeOfRawData = file_offset - psh->PointerToRawData;
697 if (si->cls == sec_text)
698 pe_header.opthdr.SizeOfCode += psh->SizeOfRawData;
699 else
700 pe_header.opthdr.SizeOfInitializedData += psh->SizeOfRawData;
704 //pe_header.filehdr.TimeDateStamp = time(NULL);
705 pe_header.filehdr.NumberOfSections = pe->sec_count;
706 pe_header.opthdr.AddressOfEntryPoint = pe->start_addr;
707 pe_header.opthdr.SizeOfHeaders = pe->sizeofheaders;
708 pe_header.opthdr.ImageBase = pe->imagebase;
709 pe_header.opthdr.Subsystem = pe->subsystem;
710 if (pe->s1->pe_stack_size)
711 pe_header.opthdr.SizeOfStackReserve = pe->s1->pe_stack_size;
712 if (PE_DLL == pe->type)
713 pe_header.filehdr.Characteristics = CHARACTERISTICS_DLL;
714 pe_header.filehdr.Characteristics |= pe->s1->pe_characteristics;
716 sum = 0;
717 pe_fwrite(&pe_header, sizeof pe_header, op, &sum);
718 for (i = 0; i < pe->sec_count; ++i)
719 pe_fwrite(&pe->sec_info[i].ish, sizeof(IMAGE_SECTION_HEADER), op, &sum);
720 pe_fpad(op, pe->sizeofheaders);
721 for (i = 0; i < pe->sec_count; ++i) {
722 si = pe->sec_info + i;
723 psh = &si->ish;
724 if (si->data_size) {
725 pe_fwrite(si->data, si->data_size, op, &sum);
726 file_offset = psh->PointerToRawData + psh->SizeOfRawData;
727 pe_fpad(op, file_offset);
731 pe_header.opthdr.CheckSum = sum + file_offset;
732 fseek(op, offsetof(struct pe_header, opthdr.CheckSum), SEEK_SET);
733 pe_fwrite(&pe_header.opthdr.CheckSum, sizeof pe_header.opthdr.CheckSum, op, NULL);
734 fclose (op);
736 if (2 == pe->s1->verbose)
737 printf("-------------------------------\n");
738 if (pe->s1->verbose)
739 printf("<- %s (%u bytes)\n", pe->filename, (unsigned)file_offset);
741 return 0;
744 /*----------------------------------------------------------------------------*/
746 static struct import_symbol *pe_add_import(struct pe_info *pe, int sym_index)
748 int i;
749 int dll_index;
750 struct pe_import_info *p;
751 struct import_symbol *s;
752 ElfW(Sym) *isym;
754 isym = (ElfW(Sym) *)pe->s1->dynsymtab_section->data + sym_index;
755 dll_index = isym->st_size;
757 i = dynarray_assoc ((void**)pe->imp_info, pe->imp_count, dll_index);
758 if (-1 != i) {
759 p = pe->imp_info[i];
760 goto found_dll;
762 p = tcc_mallocz(sizeof *p);
763 p->dll_index = dll_index;
764 dynarray_add(&pe->imp_info, &pe->imp_count, p);
766 found_dll:
767 i = dynarray_assoc ((void**)p->symbols, p->sym_count, sym_index);
768 if (-1 != i)
769 return p->symbols[i];
771 s = tcc_mallocz(sizeof *s);
772 dynarray_add(&p->symbols, &p->sym_count, s);
773 s->sym_index = sym_index;
774 return s;
777 void pe_free_imports(struct pe_info *pe)
779 int i;
780 for (i = 0; i < pe->imp_count; ++i) {
781 struct pe_import_info *p = pe->imp_info[i];
782 dynarray_reset(&p->symbols, &p->sym_count);
784 dynarray_reset(&pe->imp_info, &pe->imp_count);
787 /*----------------------------------------------------------------------------*/
788 static void pe_build_imports(struct pe_info *pe)
790 int thk_ptr, ent_ptr, dll_ptr, sym_cnt, i;
791 DWORD rva_base = pe->thunk->sh_addr - pe->imagebase;
792 int ndlls = pe->imp_count;
794 for (sym_cnt = i = 0; i < ndlls; ++i)
795 sym_cnt += pe->imp_info[i]->sym_count;
797 if (0 == sym_cnt)
798 return;
800 pe_align_section(pe->thunk, 16);
802 pe->imp_offs = dll_ptr = pe->thunk->data_offset;
803 pe->imp_size = (ndlls + 1) * sizeof(IMAGE_IMPORT_DESCRIPTOR);
804 pe->iat_offs = dll_ptr + pe->imp_size;
805 pe->iat_size = (sym_cnt + ndlls) * sizeof(ADDR3264);
806 section_ptr_add(pe->thunk, pe->imp_size + 2*pe->iat_size);
808 thk_ptr = pe->iat_offs;
809 ent_ptr = pe->iat_offs + pe->iat_size;
811 for (i = 0; i < pe->imp_count; ++i) {
812 IMAGE_IMPORT_DESCRIPTOR *hdr;
813 int k, n, dllindex;
814 ADDR3264 v;
815 struct pe_import_info *p = pe->imp_info[i];
816 const char *name;
817 DLLReference *dllref;
819 dllindex = p->dll_index;
820 if (dllindex)
821 name = (dllref = pe->s1->loaded_dlls[dllindex-1])->name;
822 else
823 name = "", dllref = NULL;
825 /* put the dll name into the import header */
826 v = put_elf_str(pe->thunk, name);
827 hdr = (IMAGE_IMPORT_DESCRIPTOR*)(pe->thunk->data + dll_ptr);
828 hdr->FirstThunk = thk_ptr + rva_base;
829 hdr->OriginalFirstThunk = ent_ptr + rva_base;
830 hdr->Name = v + rva_base;
832 for (k = 0, n = p->sym_count; k <= n; ++k) {
833 if (k < n) {
834 int iat_index = p->symbols[k]->iat_index;
835 int sym_index = p->symbols[k]->sym_index;
836 ElfW(Sym) *imp_sym = (ElfW(Sym) *)pe->s1->dynsymtab_section->data + sym_index;
837 ElfW(Sym) *org_sym = (ElfW(Sym) *)symtab_section->data + iat_index;
838 const char *name = (char*)pe->s1->dynsymtab_section->link->data + imp_sym->st_name;
839 int ordinal;
841 org_sym->st_value = thk_ptr;
842 org_sym->st_shndx = pe->thunk->sh_num;
844 if (dllref)
845 v = 0, ordinal = imp_sym->st_value; /* ordinal from pe_load_def */
846 else
847 ordinal = 0, v = imp_sym->st_value; /* address from tcc_add_symbol() */
849 #ifdef TCC_IS_NATIVE
850 if (pe->type == PE_RUN) {
851 if (dllref) {
852 if ( !dllref->handle )
853 dllref->handle = LoadLibrary(dllref->name);
854 v = (ADDR3264)GetProcAddress(dllref->handle, ordinal?(char*)0+ordinal:name);
856 if (!v)
857 tcc_error_noabort("can't build symbol '%s'", name);
858 } else
859 #endif
860 if (ordinal) {
861 v = ordinal | (ADDR3264)1 << (sizeof(ADDR3264)*8 - 1);
862 } else {
863 v = pe->thunk->data_offset + rva_base;
864 section_ptr_add(pe->thunk, sizeof(WORD)); /* hint, not used */
865 put_elf_str(pe->thunk, name);
868 } else {
869 v = 0; /* last entry is zero */
872 *(ADDR3264*)(pe->thunk->data+thk_ptr) =
873 *(ADDR3264*)(pe->thunk->data+ent_ptr) = v;
874 thk_ptr += sizeof (ADDR3264);
875 ent_ptr += sizeof (ADDR3264);
877 dll_ptr += sizeof(IMAGE_IMPORT_DESCRIPTOR);
881 /* ------------------------------------------------------------- */
883 struct pe_sort_sym
885 int index;
886 const char *name;
889 static int sym_cmp(const void *va, const void *vb)
891 const char *ca = (*(struct pe_sort_sym**)va)->name;
892 const char *cb = (*(struct pe_sort_sym**)vb)->name;
893 return strcmp(ca, cb);
896 static void pe_build_exports(struct pe_info *pe)
898 ElfW(Sym) *sym;
899 int sym_index, sym_end;
900 DWORD rva_base, func_o, name_o, ord_o, str_o;
901 IMAGE_EXPORT_DIRECTORY *hdr;
902 int sym_count, ord;
903 struct pe_sort_sym **sorted, *p;
905 FILE *op;
906 char buf[260];
907 const char *dllname;
908 const char *name;
910 rva_base = pe->thunk->sh_addr - pe->imagebase;
911 sym_count = 0, sorted = NULL, op = NULL;
913 sym_end = symtab_section->data_offset / sizeof(ElfW(Sym));
914 for (sym_index = 1; sym_index < sym_end; ++sym_index) {
915 sym = (ElfW(Sym)*)symtab_section->data + sym_index;
916 name = pe_export_name(pe->s1, sym);
917 if ((sym->st_other & ST_PE_EXPORT)
918 /* export only symbols from actually written sections */
919 && pe->s1->sections[sym->st_shndx]->sh_addr) {
920 p = tcc_malloc(sizeof *p);
921 p->index = sym_index;
922 p->name = name;
923 dynarray_add(&sorted, &sym_count, p);
925 #if 0
926 if (sym->st_other & ST_PE_EXPORT)
927 printf("export: %s\n", name);
928 if (sym->st_other & ST_PE_STDCALL)
929 printf("stdcall: %s\n", name);
930 #endif
933 if (0 == sym_count)
934 return;
936 qsort (sorted, sym_count, sizeof *sorted, sym_cmp);
938 pe_align_section(pe->thunk, 16);
939 dllname = tcc_basename(pe->filename);
941 pe->exp_offs = pe->thunk->data_offset;
942 func_o = pe->exp_offs + sizeof(IMAGE_EXPORT_DIRECTORY);
943 name_o = func_o + sym_count * sizeof (DWORD);
944 ord_o = name_o + sym_count * sizeof (DWORD);
945 str_o = ord_o + sym_count * sizeof(WORD);
947 hdr = section_ptr_add(pe->thunk, str_o - pe->exp_offs);
948 hdr->Characteristics = 0;
949 hdr->Base = 1;
950 hdr->NumberOfFunctions = sym_count;
951 hdr->NumberOfNames = sym_count;
952 hdr->AddressOfFunctions = func_o + rva_base;
953 hdr->AddressOfNames = name_o + rva_base;
954 hdr->AddressOfNameOrdinals = ord_o + rva_base;
955 hdr->Name = str_o + rva_base;
956 put_elf_str(pe->thunk, dllname);
958 #if 1
959 /* automatically write exports to <output-filename>.def */
960 pstrcpy(buf, sizeof buf, pe->filename);
961 strcpy(tcc_fileextension(buf), ".def");
962 op = fopen(buf, "w");
963 if (NULL == op) {
964 tcc_error_noabort("could not create '%s': %s", buf, strerror(errno));
965 } else {
966 fprintf(op, "LIBRARY %s\n\nEXPORTS\n", dllname);
967 if (pe->s1->verbose)
968 printf("<- %s (%d symbol%s)\n", buf, sym_count, &"s"[sym_count < 2]);
970 #endif
972 for (ord = 0; ord < sym_count; ++ord)
974 p = sorted[ord], sym_index = p->index, name = p->name;
975 /* insert actual address later in pe_relocate_rva */
976 put_elf_reloc(symtab_section, pe->thunk,
977 func_o, R_XXX_RELATIVE, sym_index);
978 *(DWORD*)(pe->thunk->data + name_o)
979 = pe->thunk->data_offset + rva_base;
980 *(WORD*)(pe->thunk->data + ord_o)
981 = ord;
982 put_elf_str(pe->thunk, name);
983 func_o += sizeof (DWORD);
984 name_o += sizeof (DWORD);
985 ord_o += sizeof (WORD);
986 if (op)
987 fprintf(op, "%s\n", name);
989 pe->exp_size = pe->thunk->data_offset - pe->exp_offs;
990 dynarray_reset(&sorted, &sym_count);
991 if (op)
992 fclose(op);
995 /* ------------------------------------------------------------- */
996 static void pe_build_reloc (struct pe_info *pe)
998 DWORD offset, block_ptr, addr;
999 int count, i;
1000 ElfW_Rel *rel, *rel_end;
1001 Section *s = NULL, *sr;
1003 offset = addr = block_ptr = count = i = 0;
1004 rel = rel_end = NULL;
1006 for(;;) {
1007 if (rel < rel_end) {
1008 int type = ELFW(R_TYPE)(rel->r_info);
1009 addr = rel->r_offset + s->sh_addr;
1010 ++ rel;
1011 if (type != REL_TYPE_DIRECT)
1012 continue;
1013 if (count == 0) { /* new block */
1014 block_ptr = pe->reloc->data_offset;
1015 section_ptr_add(pe->reloc, sizeof(struct pe_reloc_header));
1016 offset = addr & 0xFFFFFFFF<<12;
1018 if ((addr -= offset) < (1<<12)) { /* one block spans 4k addresses */
1019 WORD *wp = section_ptr_add(pe->reloc, sizeof (WORD));
1020 *wp = addr | IMAGE_REL_BASED_HIGHLOW<<12;
1021 ++count;
1022 continue;
1024 -- rel;
1026 } else if (i < pe->sec_count) {
1027 sr = (s = pe->s1->sections[pe->sec_info[i++].ord])->reloc;
1028 if (sr) {
1029 rel = (ElfW_Rel *)sr->data;
1030 rel_end = (ElfW_Rel *)(sr->data + sr->data_offset);
1032 continue;
1035 if (count) {
1036 /* store the last block and ready for a new one */
1037 struct pe_reloc_header *hdr;
1038 if (count & 1) /* align for DWORDS */
1039 section_ptr_add(pe->reloc, sizeof(WORD)), ++count;
1040 hdr = (struct pe_reloc_header *)(pe->reloc->data + block_ptr);
1041 hdr -> offset = offset - pe->imagebase;
1042 hdr -> size = count * sizeof(WORD) + sizeof(struct pe_reloc_header);
1043 count = 0;
1046 if (rel >= rel_end)
1047 break;
1051 /* ------------------------------------------------------------- */
1052 static int pe_section_class(Section *s)
1054 int type, flags;
1055 const char *name;
1057 type = s->sh_type;
1058 flags = s->sh_flags;
1059 name = s->name;
1060 if (flags & SHF_ALLOC) {
1061 if (type == SHT_PROGBITS) {
1062 if (flags & SHF_EXECINSTR)
1063 return sec_text;
1064 if (flags & SHF_WRITE)
1065 return sec_data;
1066 if (0 == strcmp(name, ".rsrc"))
1067 return sec_rsrc;
1068 if (0 == strcmp(name, ".iedat"))
1069 return sec_idata;
1070 if (0 == strcmp(name, ".pdata"))
1071 return sec_pdata;
1072 return sec_other;
1073 } else if (type == SHT_NOBITS) {
1074 if (flags & SHF_WRITE)
1075 return sec_bss;
1077 } else {
1078 if (0 == strcmp(name, ".reloc"))
1079 return sec_reloc;
1080 if (0 == strncmp(name, ".stab", 5)) /* .stab and .stabstr */
1081 return sec_stab;
1083 return -1;
1086 static int pe_assign_addresses (struct pe_info *pe)
1088 int i, k, o, c;
1089 DWORD addr;
1090 int *section_order;
1091 struct section_info *si;
1092 Section *s;
1094 if (PE_DLL == pe->type)
1095 pe->reloc = new_section(pe->s1, ".reloc", SHT_PROGBITS, 0);
1097 // pe->thunk = new_section(pe->s1, ".iedat", SHT_PROGBITS, SHF_ALLOC);
1099 section_order = tcc_malloc(pe->s1->nb_sections * sizeof (int));
1100 for (o = k = 0 ; k < sec_last; ++k) {
1101 for (i = 1; i < pe->s1->nb_sections; ++i) {
1102 s = pe->s1->sections[i];
1103 if (k == pe_section_class(s)) {
1104 // printf("%s %d\n", s->name, k);
1105 s->sh_addr = pe->imagebase;
1106 section_order[o++] = i;
1111 pe->sec_info = tcc_mallocz(o * sizeof (struct section_info));
1112 addr = pe->imagebase + 1;
1114 for (i = 0; i < o; ++i)
1116 k = section_order[i];
1117 s = pe->s1->sections[k];
1118 c = pe_section_class(s);
1119 si = &pe->sec_info[pe->sec_count];
1121 #ifdef PE_MERGE_DATA
1122 if (c == sec_bss && pe->sec_count && si[-1].cls == sec_data) {
1123 /* append .bss to .data */
1124 s->sh_addr = addr = ((addr-1) | (s->sh_addralign-1)) + 1;
1125 addr += s->data_offset;
1126 si[-1].sh_size = addr - si[-1].sh_addr;
1127 continue;
1129 #endif
1130 if (c == sec_stab && 0 == pe->s1->do_debug)
1131 continue;
1133 strcpy(si->name, s->name);
1134 si->cls = c;
1135 si->ord = k;
1136 si->sh_addr = s->sh_addr = addr = pe_virtual_align(pe, addr);
1137 si->sh_flags = s->sh_flags;
1139 if (c == sec_data && NULL == pe->thunk)
1140 pe->thunk = s;
1142 if (s == pe->thunk) {
1143 pe_build_imports(pe);
1144 pe_build_exports(pe);
1147 if (c == sec_reloc)
1148 pe_build_reloc (pe);
1150 if (s->data_offset)
1152 if (s->sh_type != SHT_NOBITS) {
1153 si->data = s->data;
1154 si->data_size = s->data_offset;
1157 addr += s->data_offset;
1158 si->sh_size = s->data_offset;
1159 ++pe->sec_count;
1161 // printf("%08x %05x %s\n", si->sh_addr, si->sh_size, si->name);
1164 #if 0
1165 for (i = 1; i < pe->s1->nb_sections; ++i) {
1166 Section *s = pe->s1->sections[i];
1167 int type = s->sh_type;
1168 int flags = s->sh_flags;
1169 printf("section %-16s %-10s %5x %s,%s,%s\n",
1170 s->name,
1171 type == SHT_PROGBITS ? "progbits" :
1172 type == SHT_NOBITS ? "nobits" :
1173 type == SHT_SYMTAB ? "symtab" :
1174 type == SHT_STRTAB ? "strtab" :
1175 type == SHT_RELX ? "rel" : "???",
1176 s->data_offset,
1177 flags & SHF_ALLOC ? "alloc" : "",
1178 flags & SHF_WRITE ? "write" : "",
1179 flags & SHF_EXECINSTR ? "exec" : ""
1182 pe->s1->verbose = 2;
1183 #endif
1185 tcc_free(section_order);
1186 return 0;
1189 /* ------------------------------------------------------------- */
1190 static void pe_relocate_rva (struct pe_info *pe, Section *s)
1192 Section *sr = s->reloc;
1193 ElfW_Rel *rel, *rel_end;
1194 rel_end = (ElfW_Rel *)(sr->data + sr->data_offset);
1195 for(rel = (ElfW_Rel *)sr->data; rel < rel_end; rel++) {
1196 if (ELFW(R_TYPE)(rel->r_info) == R_XXX_RELATIVE) {
1197 int sym_index = ELFW(R_SYM)(rel->r_info);
1198 DWORD addr = s->sh_addr;
1199 if (sym_index) {
1200 ElfW(Sym) *sym = (ElfW(Sym) *)symtab_section->data + sym_index;
1201 addr = sym->st_value;
1203 // printf("reloc rva %08x %08x %s\n", (DWORD)rel->r_offset, addr, s->name);
1204 *(DWORD*)(s->data + rel->r_offset) += addr - pe->imagebase;
1209 /*----------------------------------------------------------------------------*/
1211 static int pe_isafunc(int sym_index)
1213 Section *sr = text_section->reloc;
1214 ElfW_Rel *rel, *rel_end;
1215 Elf32_Word info = ELF32_R_INFO(sym_index, R_386_PC32);
1216 if (!sr)
1217 return 0;
1218 rel_end = (ElfW_Rel *)(sr->data + sr->data_offset);
1219 for (rel = (ElfW_Rel *)sr->data; rel < rel_end; rel++)
1220 if (rel->r_info == info)
1221 return 1;
1222 return 0;
1225 /*----------------------------------------------------------------------------*/
1226 static int pe_check_symbols(struct pe_info *pe)
1228 ElfW(Sym) *sym;
1229 int sym_index, sym_end;
1230 int ret = 0;
1232 pe_align_section(text_section, 8);
1234 sym_end = symtab_section->data_offset / sizeof(ElfW(Sym));
1235 for (sym_index = 1; sym_index < sym_end; ++sym_index) {
1237 sym = (ElfW(Sym) *)symtab_section->data + sym_index;
1238 if (sym->st_shndx == SHN_UNDEF) {
1240 const char *name = (char*)symtab_section->link->data + sym->st_name;
1241 unsigned type = ELFW(ST_TYPE)(sym->st_info);
1242 int imp_sym = pe_find_import(pe->s1, sym);
1243 struct import_symbol *is;
1245 if (imp_sym <= 0)
1246 goto not_found;
1248 if (type == STT_NOTYPE) {
1249 /* symbols from assembler have no type, find out which */
1250 if (pe_isafunc(sym_index))
1251 type = STT_FUNC;
1252 else
1253 type = STT_OBJECT;
1256 is = pe_add_import(pe, imp_sym);
1258 if (type == STT_FUNC) {
1259 unsigned long offset = is->thk_offset;
1260 if (offset) {
1261 /* got aliased symbol, like stricmp and _stricmp */
1263 } else {
1264 char buffer[100];
1265 WORD *p;
1267 offset = text_section->data_offset;
1268 /* add the 'jmp IAT[x]' instruction */
1269 #ifdef TCC_TARGET_ARM
1270 p = section_ptr_add(text_section, 8+4); // room for code and address
1271 (*(DWORD*)(p)) = 0xE59FC000; // arm code ldr ip, [pc] ; PC+8+0 = 0001xxxx
1272 (*(DWORD*)(p+2)) = 0xE59CF000; // arm code ldr pc, [ip]
1273 #else
1274 p = section_ptr_add(text_section, 8);
1275 *p = 0x25FF;
1276 #ifdef TCC_TARGET_X86_64
1277 *(DWORD*)(p+1) = (DWORD)-4;
1278 #endif
1279 #endif
1280 /* add a helper symbol, will be patched later in
1281 pe_build_imports */
1282 sprintf(buffer, "IAT.%s", name);
1283 is->iat_index = put_elf_sym(
1284 symtab_section, 0, sizeof(DWORD),
1285 ELFW(ST_INFO)(STB_GLOBAL, STT_OBJECT),
1286 0, SHN_UNDEF, buffer);
1287 #ifdef TCC_TARGET_ARM
1288 put_elf_reloc(symtab_section, text_section,
1289 offset + 8, R_XXX_THUNKFIX, is->iat_index); // offset to IAT position
1290 #else
1291 put_elf_reloc(symtab_section, text_section,
1292 offset + 2, R_XXX_THUNKFIX, is->iat_index);
1293 #endif
1294 is->thk_offset = offset;
1297 /* tcc_realloc might have altered sym's address */
1298 sym = (ElfW(Sym) *)symtab_section->data + sym_index;
1300 /* patch the original symbol */
1301 sym->st_value = offset;
1302 sym->st_shndx = text_section->sh_num;
1303 sym->st_other &= ~ST_PE_EXPORT; /* do not export */
1304 continue;
1307 if (type == STT_OBJECT) { /* data, ptr to that should be */
1308 if (0 == is->iat_index) {
1309 /* original symbol will be patched later in pe_build_imports */
1310 is->iat_index = sym_index;
1311 continue;
1315 not_found:
1316 if (ELFW(ST_BIND)(sym->st_info) == STB_WEAK)
1317 /* STB_WEAK undefined symbols are accepted */
1318 continue;
1319 tcc_error_noabort("undefined symbol '%s'%s", name,
1320 imp_sym < 0 ? ", missing __declspec(dllimport)?":"");
1321 ret = -1;
1323 } else if (pe->s1->rdynamic
1324 && ELFW(ST_BIND)(sym->st_info) != STB_LOCAL) {
1325 /* if -rdynamic option, then export all non local symbols */
1326 sym->st_other |= ST_PE_EXPORT;
1329 return ret;
1332 /*----------------------------------------------------------------------------*/
1333 #ifdef PE_PRINT_SECTIONS
1334 static void pe_print_section(FILE * f, Section * s)
1336 /* just if you're curious */
1337 BYTE *p, *e, b;
1338 int i, n, l, m;
1339 p = s->data;
1340 e = s->data + s->data_offset;
1341 l = e - p;
1343 fprintf(f, "section \"%s\"", s->name);
1344 if (s->link)
1345 fprintf(f, "\nlink \"%s\"", s->link->name);
1346 if (s->reloc)
1347 fprintf(f, "\nreloc \"%s\"", s->reloc->name);
1348 fprintf(f, "\nv_addr %08X", (unsigned)s->sh_addr);
1349 fprintf(f, "\ncontents %08X", (unsigned)l);
1350 fprintf(f, "\n\n");
1352 if (s->sh_type == SHT_NOBITS)
1353 return;
1355 if (0 == l)
1356 return;
1358 if (s->sh_type == SHT_SYMTAB)
1359 m = sizeof(ElfW(Sym));
1360 else if (s->sh_type == SHT_RELX)
1361 m = sizeof(ElfW_Rel);
1362 else
1363 m = 16;
1365 fprintf(f, "%-8s", "offset");
1366 for (i = 0; i < m; ++i)
1367 fprintf(f, " %02x", i);
1368 n = 56;
1370 if (s->sh_type == SHT_SYMTAB || s->sh_type == SHT_RELX) {
1371 const char *fields1[] = {
1372 "name",
1373 "value",
1374 "size",
1375 "bind",
1376 "type",
1377 "other",
1378 "shndx",
1379 NULL
1382 const char *fields2[] = {
1383 "offs",
1384 "type",
1385 "symb",
1386 NULL
1389 const char **p;
1391 if (s->sh_type == SHT_SYMTAB)
1392 p = fields1, n = 106;
1393 else
1394 p = fields2, n = 58;
1396 for (i = 0; p[i]; ++i)
1397 fprintf(f, "%6s", p[i]);
1398 fprintf(f, " symbol");
1401 fprintf(f, "\n");
1402 for (i = 0; i < n; ++i)
1403 fprintf(f, "-");
1404 fprintf(f, "\n");
1406 for (i = 0; i < l;)
1408 fprintf(f, "%08X", i);
1409 for (n = 0; n < m; ++n) {
1410 if (n + i < l)
1411 fprintf(f, " %02X", p[i + n]);
1412 else
1413 fprintf(f, " ");
1416 if (s->sh_type == SHT_SYMTAB) {
1417 ElfW(Sym) *sym = (ElfW(Sym) *) (p + i);
1418 const char *name = s->link->data + sym->st_name;
1419 fprintf(f, " %04X %04X %04X %02X %02X %02X %04X \"%s\"",
1420 (unsigned)sym->st_name,
1421 (unsigned)sym->st_value,
1422 (unsigned)sym->st_size,
1423 (unsigned)ELFW(ST_BIND)(sym->st_info),
1424 (unsigned)ELFW(ST_TYPE)(sym->st_info),
1425 (unsigned)sym->st_other,
1426 (unsigned)sym->st_shndx,
1427 name);
1429 } else if (s->sh_type == SHT_RELX) {
1430 ElfW_Rel *rel = (ElfW_Rel *) (p + i);
1431 ElfW(Sym) *sym =
1432 (ElfW(Sym) *) s->link->data + ELFW(R_SYM)(rel->r_info);
1433 const char *name = s->link->link->data + sym->st_name;
1434 fprintf(f, " %04X %02X %04X \"%s\"",
1435 (unsigned)rel->r_offset,
1436 (unsigned)ELFW(R_TYPE)(rel->r_info),
1437 (unsigned)ELFW(R_SYM)(rel->r_info),
1438 name);
1439 } else {
1440 fprintf(f, " ");
1441 for (n = 0; n < m; ++n) {
1442 if (n + i < l) {
1443 b = p[i + n];
1444 if (b < 32 || b >= 127)
1445 b = '.';
1446 fprintf(f, "%c", b);
1450 i += m;
1451 fprintf(f, "\n");
1453 fprintf(f, "\n\n");
1456 static void pe_print_sections(TCCState *s1, const char *fname)
1458 Section *s;
1459 FILE *f;
1460 int i;
1461 f = fopen(fname, "w");
1462 for (i = 1; i < s1->nb_sections; ++i) {
1463 s = s1->sections[i];
1464 pe_print_section(f, s);
1466 pe_print_section(f, s1->dynsymtab_section);
1467 fclose(f);
1469 #endif
1471 /* ------------------------------------------------------------- */
1472 /* helper function for load/store to insert one more indirection */
1474 #ifndef TCC_TARGET_ARM
1475 ST_FUNC SValue *pe_getimport(SValue *sv, SValue *v2)
1477 int r2;
1478 if ((sv->r & (VT_VALMASK|VT_SYM)) != (VT_CONST|VT_SYM) || (sv->r2 != VT_CONST))
1479 return sv;
1480 if (!sv->sym->a.dllimport)
1481 return sv;
1482 // printf("import %04x %04x %04x %s\n", sv->type.t, sv->sym->type.t, sv->r, get_tok_str(sv->sym->v, NULL));
1483 memset(v2, 0, sizeof *v2);
1484 v2->type.t = VT_PTR;
1485 v2->r = VT_CONST | VT_SYM | VT_LVAL;
1486 v2->sym = sv->sym;
1488 r2 = get_reg(RC_INT);
1489 load(r2, v2);
1490 v2->r = r2;
1491 if ((uint32_t)sv->c.i) {
1492 vpushv(v2);
1493 vpushi(sv->c.i);
1494 gen_opi('+');
1495 *v2 = *vtop--;
1497 v2->type.t = sv->type.t;
1498 v2->r |= sv->r & VT_LVAL;
1499 return v2;
1501 #endif
1503 ST_FUNC int pe_putimport(TCCState *s1, int dllindex, const char *name, addr_t value)
1505 return set_elf_sym(
1506 s1->dynsymtab_section,
1507 value,
1508 dllindex, /* st_size */
1509 ELFW(ST_INFO)(STB_GLOBAL, STT_NOTYPE),
1511 value ? SHN_ABS : SHN_UNDEF,
1512 name
1516 static int add_dllref(TCCState *s1, const char *dllname)
1518 DLLReference *dllref;
1519 int i;
1520 for (i = 0; i < s1->nb_loaded_dlls; ++i)
1521 if (0 == strcmp(s1->loaded_dlls[i]->name, dllname))
1522 return i + 1;
1523 dllref = tcc_mallocz(sizeof(DLLReference) + strlen(dllname));
1524 strcpy(dllref->name, dllname);
1525 dynarray_add(&s1->loaded_dlls, &s1->nb_loaded_dlls, dllref);
1526 return s1->nb_loaded_dlls;
1529 /* ------------------------------------------------------------- */
1531 static int read_mem(int fd, unsigned offset, void *buffer, unsigned len)
1533 lseek(fd, offset, SEEK_SET);
1534 return len == read(fd, buffer, len);
1537 /* ------------------------------------------------------------- */
1539 PUB_FUNC int tcc_get_dllexports(const char *filename, char **pp)
1541 int l, i, n, n0, ret;
1542 char *p;
1543 int fd;
1545 IMAGE_SECTION_HEADER ish;
1546 IMAGE_EXPORT_DIRECTORY ied;
1547 IMAGE_DOS_HEADER dh;
1548 IMAGE_FILE_HEADER ih;
1549 DWORD sig, ref, addr, ptr, namep;
1551 int pef_hdroffset, opt_hdroffset, sec_hdroffset;
1553 n = n0 = 0;
1554 p = NULL;
1555 ret = -1;
1557 fd = open(filename, O_RDONLY | O_BINARY);
1558 if (fd < 0)
1559 goto the_end_1;
1560 ret = 1;
1561 if (!read_mem(fd, 0, &dh, sizeof dh))
1562 goto the_end;
1563 if (!read_mem(fd, dh.e_lfanew, &sig, sizeof sig))
1564 goto the_end;
1565 if (sig != 0x00004550)
1566 goto the_end;
1567 pef_hdroffset = dh.e_lfanew + sizeof sig;
1568 if (!read_mem(fd, pef_hdroffset, &ih, sizeof ih))
1569 goto the_end;
1570 opt_hdroffset = pef_hdroffset + sizeof ih;
1571 if (ih.Machine == 0x014C) {
1572 IMAGE_OPTIONAL_HEADER32 oh;
1573 sec_hdroffset = opt_hdroffset + sizeof oh;
1574 if (!read_mem(fd, opt_hdroffset, &oh, sizeof oh))
1575 goto the_end;
1576 if (IMAGE_DIRECTORY_ENTRY_EXPORT >= oh.NumberOfRvaAndSizes)
1577 goto the_end_0;
1578 addr = oh.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress;
1579 } else if (ih.Machine == 0x8664) {
1580 IMAGE_OPTIONAL_HEADER64 oh;
1581 sec_hdroffset = opt_hdroffset + sizeof oh;
1582 if (!read_mem(fd, opt_hdroffset, &oh, sizeof oh))
1583 goto the_end;
1584 if (IMAGE_DIRECTORY_ENTRY_EXPORT >= oh.NumberOfRvaAndSizes)
1585 goto the_end_0;
1586 addr = oh.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress;
1587 } else
1588 goto the_end;
1590 //printf("addr: %08x\n", addr);
1591 for (i = 0; i < ih.NumberOfSections; ++i) {
1592 if (!read_mem(fd, sec_hdroffset + i * sizeof ish, &ish, sizeof ish))
1593 goto the_end;
1594 //printf("vaddr: %08x\n", ish.VirtualAddress);
1595 if (addr >= ish.VirtualAddress && addr < ish.VirtualAddress + ish.SizeOfRawData)
1596 goto found;
1598 goto the_end_0;
1600 found:
1601 ref = ish.VirtualAddress - ish.PointerToRawData;
1602 if (!read_mem(fd, addr - ref, &ied, sizeof ied))
1603 goto the_end;
1605 namep = ied.AddressOfNames - ref;
1606 for (i = 0; i < ied.NumberOfNames; ++i) {
1607 if (!read_mem(fd, namep, &ptr, sizeof ptr))
1608 goto the_end;
1609 namep += sizeof ptr;
1610 for (l = 0;;) {
1611 if (n+1 >= n0)
1612 p = tcc_realloc(p, n0 = n0 ? n0 * 2 : 256);
1613 if (!read_mem(fd, ptr - ref + l++, p + n, 1)) {
1614 tcc_free(p), p = NULL;
1615 goto the_end;
1617 if (p[n++] == 0)
1618 break;
1621 if (p)
1622 p[n] = 0;
1623 the_end_0:
1624 ret = 0;
1625 the_end:
1626 close(fd);
1627 the_end_1:
1628 *pp = p;
1629 return ret;
1632 /* -------------------------------------------------------------
1633 * This is for compiled windows resources in 'coff' format
1634 * as generated by 'windres.exe -O coff ...'.
1637 static int pe_load_res(TCCState *s1, int fd)
1639 struct pe_rsrc_header hdr;
1640 Section *rsrc_section;
1641 int i, ret = -1;
1642 BYTE *ptr;
1643 unsigned offs;
1645 if (!read_mem(fd, 0, &hdr, sizeof hdr))
1646 goto quit;
1648 if (hdr.filehdr.Machine != IMAGE_FILE_MACHINE
1649 || hdr.filehdr.NumberOfSections != 1
1650 || strcmp((char*)hdr.sectionhdr.Name, ".rsrc") != 0)
1651 goto quit;
1653 rsrc_section = new_section(s1, ".rsrc", SHT_PROGBITS, SHF_ALLOC);
1654 ptr = section_ptr_add(rsrc_section, hdr.sectionhdr.SizeOfRawData);
1655 offs = hdr.sectionhdr.PointerToRawData;
1656 if (!read_mem(fd, offs, ptr, hdr.sectionhdr.SizeOfRawData))
1657 goto quit;
1658 offs = hdr.sectionhdr.PointerToRelocations;
1659 for (i = 0; i < hdr.sectionhdr.NumberOfRelocations; ++i)
1661 struct pe_rsrc_reloc rel;
1662 if (!read_mem(fd, offs, &rel, sizeof rel))
1663 goto quit;
1664 // printf("rsrc_reloc: %x %x %x\n", rel.offset, rel.size, rel.type);
1665 if (rel.type != RSRC_RELTYPE)
1666 goto quit;
1667 put_elf_reloc(symtab_section, rsrc_section,
1668 rel.offset, R_XXX_RELATIVE, 0);
1669 offs += sizeof rel;
1671 ret = 0;
1672 quit:
1673 return ret;
1676 /* ------------------------------------------------------------- */
1678 static char *trimfront(char *p)
1680 while (*p && (unsigned char)*p <= ' ')
1681 ++p;
1682 return p;
1685 static char *trimback(char *a, char *e)
1687 while (e > a && (unsigned char)e[-1] <= ' ')
1688 --e;
1689 *e = 0;;
1690 return a;
1693 /* ------------------------------------------------------------- */
1694 static int pe_load_def(TCCState *s1, int fd)
1696 int state = 0, ret = -1, dllindex = 0, ord;
1697 char line[400], dllname[80], *p, *x;
1698 FILE *fp;
1700 fp = fdopen(dup(fd), "rb");
1701 while (fgets(line, sizeof line, fp))
1703 p = trimfront(trimback(line, strchr(line, 0)));
1704 if (0 == *p || ';' == *p)
1705 continue;
1707 switch (state) {
1708 case 0:
1709 if (0 != strnicmp(p, "LIBRARY", 7))
1710 goto quit;
1711 pstrcpy(dllname, sizeof dllname, trimfront(p+7));
1712 ++state;
1713 continue;
1715 case 1:
1716 if (0 != stricmp(p, "EXPORTS"))
1717 goto quit;
1718 ++state;
1719 continue;
1721 case 2:
1722 dllindex = add_dllref(s1, dllname);
1723 ++state;
1724 /* fall through */
1725 default:
1726 /* get ordinal and will store in sym->st_value */
1727 ord = 0;
1728 x = strchr(p, ' ');
1729 if (x) {
1730 *x = 0, x = strrchr(x + 1, '@');
1731 if (x) {
1732 char *d;
1733 ord = (int)strtol(x + 1, &d, 10);
1734 if (*d)
1735 ord = 0;
1738 pe_putimport(s1, dllindex, p, ord);
1739 continue;
1742 ret = 0;
1743 quit:
1744 fclose(fp);
1745 return ret;
1748 /* ------------------------------------------------------------- */
1749 static int pe_load_dll(TCCState *s1, const char *filename)
1751 char *p, *q;
1752 int index, ret;
1754 ret = tcc_get_dllexports(filename, &p);
1755 if (ret) {
1756 return -1;
1757 } else if (p) {
1758 index = add_dllref(s1, tcc_basename(filename));
1759 for (q = p; *q; q += 1 + strlen(q))
1760 pe_putimport(s1, index, q, 0);
1761 tcc_free(p);
1763 return 0;
1766 /* ------------------------------------------------------------- */
1767 ST_FUNC int pe_load_file(struct TCCState *s1, const char *filename, int fd)
1769 int ret = -1;
1770 char buf[10];
1771 if (0 == strcmp(tcc_fileextension(filename), ".def"))
1772 ret = pe_load_def(s1, fd);
1773 else if (pe_load_res(s1, fd) == 0)
1774 ret = 0;
1775 else if (read_mem(fd, 0, buf, 4) && 0 == memcmp(buf, "MZ\220", 4))
1776 ret = pe_load_dll(s1, filename);
1777 return ret;
1780 /* ------------------------------------------------------------- */
1781 #ifdef TCC_TARGET_X86_64
1782 static unsigned pe_add_uwwind_info(TCCState *s1)
1784 if (NULL == s1->uw_pdata) {
1785 s1->uw_pdata = find_section(tcc_state, ".pdata");
1786 s1->uw_pdata->sh_addralign = 4;
1787 s1->uw_sym = put_elf_sym(symtab_section, 0, 0, 0, 0, text_section->sh_num, NULL);
1790 if (0 == s1->uw_offs) {
1791 /* As our functions all have the same stackframe, we use one entry for all */
1792 static const unsigned char uw_info[] = {
1793 0x01, // UBYTE: 3 Version , UBYTE: 5 Flags
1794 0x04, // UBYTE Size of prolog
1795 0x02, // UBYTE Count of unwind codes
1796 0x05, // UBYTE: 4 Frame Register (rbp), UBYTE: 4 Frame Register offset (scaled)
1797 // USHORT * n Unwind codes array
1798 // 0x0b, 0x01, 0xff, 0xff, // stack size
1799 0x04, 0x03, // set frame ptr (mov rsp -> rbp)
1800 0x01, 0x50 // push reg (rbp)
1803 Section *s = text_section;
1804 unsigned char *p;
1806 section_ptr_add(s, -s->data_offset & 3); /* align */
1807 s1->uw_offs = s->data_offset;
1808 p = section_ptr_add(s, sizeof uw_info);
1809 memcpy(p, uw_info, sizeof uw_info);
1812 return s1->uw_offs;
1815 ST_FUNC void pe_add_unwind_data(unsigned start, unsigned end, unsigned stack)
1817 TCCState *s1 = tcc_state;
1818 Section *pd;
1819 unsigned o, n, d;
1820 struct /* _RUNTIME_FUNCTION */ {
1821 DWORD BeginAddress;
1822 DWORD EndAddress;
1823 DWORD UnwindData;
1824 } *p;
1826 d = pe_add_uwwind_info(s1);
1827 pd = s1->uw_pdata;
1828 o = pd->data_offset;
1829 p = section_ptr_add(pd, sizeof *p);
1831 /* record this function */
1832 p->BeginAddress = start;
1833 p->EndAddress = end;
1834 p->UnwindData = d;
1836 /* put relocations on it */
1837 for (n = o + sizeof *p; o < n; o += sizeof p->BeginAddress)
1838 put_elf_reloc(symtab_section, pd, o, R_X86_64_RELATIVE, s1->uw_sym);
1840 #endif
1841 /* ------------------------------------------------------------- */
1842 #ifdef TCC_TARGET_X86_64
1843 #define PE_STDSYM(n,s) n
1844 #else
1845 #define PE_STDSYM(n,s) "_" n s
1846 #endif
1848 static void pe_add_runtime(TCCState *s1, struct pe_info *pe)
1850 const char *start_symbol;
1851 int pe_type = 0;
1852 int unicode_entry = 0;
1854 if (find_elf_sym(symtab_section, PE_STDSYM("WinMain","@16")))
1855 pe_type = PE_GUI;
1856 else
1857 if (find_elf_sym(symtab_section, PE_STDSYM("wWinMain","@16"))) {
1858 pe_type = PE_GUI;
1859 unicode_entry = PE_GUI;
1861 else
1862 if (TCC_OUTPUT_DLL == s1->output_type) {
1863 pe_type = PE_DLL;
1864 /* need this for 'tccelf.c:relocate_section()' */
1865 s1->output_type = TCC_OUTPUT_EXE;
1867 else {
1868 pe_type = PE_EXE;
1869 if (find_elf_sym(symtab_section, "wmain"))
1870 unicode_entry = PE_EXE;
1873 start_symbol =
1874 TCC_OUTPUT_MEMORY == s1->output_type
1875 ? PE_GUI == pe_type ? (unicode_entry ? "__runwwinmain" : "__runwinmain")
1876 : (unicode_entry ? "__runwmain" : "__runmain")
1877 : PE_DLL == pe_type ? PE_STDSYM("__dllstart","@12")
1878 : PE_GUI == pe_type ? (unicode_entry ? "__wwinstart": "__winstart")
1879 : (unicode_entry ? "__wstart" : "__start")
1882 if (!s1->leading_underscore || strchr(start_symbol, '@'))
1883 ++start_symbol;
1885 /* grab the startup code from libtcc1 */
1886 #ifdef TCC_IS_NATIVE
1887 if (TCC_OUTPUT_MEMORY != s1->output_type || s1->runtime_main)
1888 #endif
1889 set_elf_sym(symtab_section,
1890 0, 0,
1891 ELFW(ST_INFO)(STB_GLOBAL, STT_NOTYPE), 0,
1892 SHN_UNDEF, start_symbol);
1894 tcc_add_pragma_libs(s1);
1896 if (0 == s1->nostdlib) {
1897 static const char *libs[] = {
1898 TCC_LIBTCC1, "msvcrt", "kernel32", "", "user32", "gdi32", NULL
1900 const char **pp, *p;
1901 for (pp = libs; 0 != (p = *pp); ++pp) {
1902 if (0 == *p) {
1903 if (PE_DLL != pe_type && PE_GUI != pe_type)
1904 break;
1905 } else if (pp == libs && tcc_add_dll(s1, p, 0) >= 0) {
1906 continue;
1907 } else {
1908 tcc_add_library_err(s1, p);
1913 if (TCC_OUTPUT_MEMORY == s1->output_type)
1914 pe_type = PE_RUN;
1915 pe->type = pe_type;
1916 pe->start_symbol = start_symbol;
1919 static void pe_set_options(TCCState * s1, struct pe_info *pe)
1921 if (PE_DLL == pe->type) {
1922 /* XXX: check if is correct for arm-pe target */
1923 pe->imagebase = 0x10000000;
1924 } else {
1925 #if defined(TCC_TARGET_ARM)
1926 pe->imagebase = 0x00010000;
1927 #else
1928 pe->imagebase = 0x00400000;
1929 #endif
1932 #if defined(TCC_TARGET_ARM)
1933 /* we use "console" subsystem by default */
1934 pe->subsystem = 9;
1935 #else
1936 if (PE_DLL == pe->type || PE_GUI == pe->type)
1937 pe->subsystem = 2;
1938 else
1939 pe->subsystem = 3;
1940 #endif
1941 /* Allow override via -Wl,-subsystem=... option */
1942 if (s1->pe_subsystem != 0)
1943 pe->subsystem = s1->pe_subsystem;
1945 /* set default file/section alignment */
1946 if (pe->subsystem == 1) {
1947 pe->section_align = 0x20;
1948 pe->file_align = 0x20;
1949 } else {
1950 pe->section_align = 0x1000;
1951 pe->file_align = 0x200;
1954 if (s1->section_align != 0)
1955 pe->section_align = s1->section_align;
1956 if (s1->pe_file_align != 0)
1957 pe->file_align = s1->pe_file_align;
1959 if ((pe->subsystem >= 10) && (pe->subsystem <= 12))
1960 pe->imagebase = 0;
1962 if (s1->has_text_addr)
1963 pe->imagebase = s1->text_addr;
1966 ST_FUNC int pe_output_file(TCCState *s1, const char *filename)
1968 int ret;
1969 struct pe_info pe;
1970 int i;
1972 memset(&pe, 0, sizeof pe);
1973 pe.filename = filename;
1974 pe.s1 = s1;
1976 tcc_add_bcheck(s1);
1977 pe_add_runtime(s1, &pe);
1978 relocate_common_syms(); /* assign bss addresses */
1979 tcc_add_linker_symbols(s1);
1980 pe_set_options(s1, &pe);
1982 ret = pe_check_symbols(&pe);
1983 if (ret)
1985 else if (filename) {
1986 pe_assign_addresses(&pe);
1987 relocate_syms(s1, s1->symtab, 0);
1988 for (i = 1; i < s1->nb_sections; ++i) {
1989 Section *s = s1->sections[i];
1990 if (s->reloc) {
1991 relocate_section(s1, s);
1992 pe_relocate_rva(&pe, s);
1995 pe.start_addr = (DWORD)
1996 ((uintptr_t)tcc_get_symbol_err(s1, pe.start_symbol)
1997 - pe.imagebase);
1998 if (s1->nb_errors)
1999 ret = -1;
2000 else
2001 ret = pe_write(&pe);
2002 tcc_free(pe.sec_info);
2003 } else {
2004 #ifdef TCC_IS_NATIVE
2005 pe.thunk = data_section;
2006 pe_build_imports(&pe);
2007 s1->runtime_main = pe.start_symbol;
2008 #endif
2011 pe_free_imports(&pe);
2013 #ifdef PE_PRINT_SECTIONS
2014 pe_print_sections(s1, "tcc.log");
2015 #endif
2016 return ret;
2019 /* ------------------------------------------------------------- */