tccgen: update "Fix invalid load generated by gfunc_return()"
[tinycc.git] / tccpe.c
blobab610af1df4a5ac3c76b3346ef0dee6eecc985f3
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 1
24 #define PE_PRINT_SECTIONS 0
26 #ifndef _WIN32
27 #define stricmp strcasecmp
28 #define strnicmp strncasecmp
29 #include <sys/stat.h> /* chmod() */
30 #endif
32 #ifdef TCC_TARGET_X86_64
33 # define ADDR3264 ULONGLONG
34 # define PE_IMAGE_REL IMAGE_REL_BASED_DIR64
35 # define REL_TYPE_DIRECT R_X86_64_64
36 # define R_XXX_THUNKFIX R_X86_64_PC32
37 # define R_XXX_RELATIVE R_X86_64_RELATIVE
38 # define R_XXX_FUNCCALL R_X86_64_PC32
39 # define IMAGE_FILE_MACHINE 0x8664
40 # define RSRC_RELTYPE 3
42 #elif defined TCC_TARGET_ARM
43 # define ADDR3264 DWORD
44 # define PE_IMAGE_REL IMAGE_REL_BASED_HIGHLOW
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 R_XXX_FUNCCALL R_ARM_PC24
49 # define R_XXX_FUNCCALL2 R_ARM_ABS32
50 # define IMAGE_FILE_MACHINE 0x01C0
51 # define RSRC_RELTYPE 7 /* ??? (not tested) */
53 #elif defined TCC_TARGET_I386
54 # define ADDR3264 DWORD
55 # define PE_IMAGE_REL IMAGE_REL_BASED_HIGHLOW
56 # define REL_TYPE_DIRECT R_386_32
57 # define R_XXX_THUNKFIX R_386_32
58 # define R_XXX_RELATIVE R_386_RELATIVE
59 # define R_XXX_FUNCCALL R_386_PC32
60 # define IMAGE_FILE_MACHINE 0x014C
61 # define RSRC_RELTYPE 7 /* DIR32NB */
63 #endif
65 #ifndef IMAGE_NT_SIGNATURE
66 /* ----------------------------------------------------------- */
67 /* definitions below are from winnt.h */
69 typedef unsigned char BYTE;
70 typedef unsigned short WORD;
71 typedef unsigned int DWORD;
72 typedef unsigned long long ULONGLONG;
73 #pragma pack(push, 1)
75 typedef struct _IMAGE_DOS_HEADER { /* DOS .EXE header */
76 WORD e_magic; /* Magic number */
77 WORD e_cblp; /* Bytes on last page of file */
78 WORD e_cp; /* Pages in file */
79 WORD e_crlc; /* Relocations */
80 WORD e_cparhdr; /* Size of header in paragraphs */
81 WORD e_minalloc; /* Minimum extra paragraphs needed */
82 WORD e_maxalloc; /* Maximum extra paragraphs needed */
83 WORD e_ss; /* Initial (relative) SS value */
84 WORD e_sp; /* Initial SP value */
85 WORD e_csum; /* Checksum */
86 WORD e_ip; /* Initial IP value */
87 WORD e_cs; /* Initial (relative) CS value */
88 WORD e_lfarlc; /* File address of relocation table */
89 WORD e_ovno; /* Overlay number */
90 WORD e_res[4]; /* Reserved words */
91 WORD e_oemid; /* OEM identifier (for e_oeminfo) */
92 WORD e_oeminfo; /* OEM information; e_oemid specific */
93 WORD e_res2[10]; /* Reserved words */
94 DWORD e_lfanew; /* File address of new exe header */
95 } IMAGE_DOS_HEADER, *PIMAGE_DOS_HEADER;
97 #define IMAGE_NT_SIGNATURE 0x00004550 /* PE00 */
98 #define SIZE_OF_NT_SIGNATURE 4
100 typedef struct _IMAGE_FILE_HEADER {
101 WORD Machine;
102 WORD NumberOfSections;
103 DWORD TimeDateStamp;
104 DWORD PointerToSymbolTable;
105 DWORD NumberOfSymbols;
106 WORD SizeOfOptionalHeader;
107 WORD Characteristics;
108 } IMAGE_FILE_HEADER, *PIMAGE_FILE_HEADER;
111 #define IMAGE_SIZEOF_FILE_HEADER 20
113 typedef struct _IMAGE_DATA_DIRECTORY {
114 DWORD VirtualAddress;
115 DWORD Size;
116 } IMAGE_DATA_DIRECTORY, *PIMAGE_DATA_DIRECTORY;
119 typedef struct _IMAGE_OPTIONAL_HEADER {
120 /* Standard fields. */
121 WORD Magic;
122 BYTE MajorLinkerVersion;
123 BYTE MinorLinkerVersion;
124 DWORD SizeOfCode;
125 DWORD SizeOfInitializedData;
126 DWORD SizeOfUninitializedData;
127 DWORD AddressOfEntryPoint;
128 DWORD BaseOfCode;
129 #ifndef TCC_TARGET_X86_64
130 DWORD BaseOfData;
131 #endif
132 /* NT additional fields. */
133 ADDR3264 ImageBase;
134 DWORD SectionAlignment;
135 DWORD FileAlignment;
136 WORD MajorOperatingSystemVersion;
137 WORD MinorOperatingSystemVersion;
138 WORD MajorImageVersion;
139 WORD MinorImageVersion;
140 WORD MajorSubsystemVersion;
141 WORD MinorSubsystemVersion;
142 DWORD Win32VersionValue;
143 DWORD SizeOfImage;
144 DWORD SizeOfHeaders;
145 DWORD CheckSum;
146 WORD Subsystem;
147 WORD DllCharacteristics;
148 ADDR3264 SizeOfStackReserve;
149 ADDR3264 SizeOfStackCommit;
150 ADDR3264 SizeOfHeapReserve;
151 ADDR3264 SizeOfHeapCommit;
152 DWORD LoaderFlags;
153 DWORD NumberOfRvaAndSizes;
154 IMAGE_DATA_DIRECTORY DataDirectory[16];
155 } IMAGE_OPTIONAL_HEADER32, IMAGE_OPTIONAL_HEADER64, IMAGE_OPTIONAL_HEADER;
157 #define IMAGE_DIRECTORY_ENTRY_EXPORT 0 /* Export Directory */
158 #define IMAGE_DIRECTORY_ENTRY_IMPORT 1 /* Import Directory */
159 #define IMAGE_DIRECTORY_ENTRY_RESOURCE 2 /* Resource Directory */
160 #define IMAGE_DIRECTORY_ENTRY_EXCEPTION 3 /* Exception Directory */
161 #define IMAGE_DIRECTORY_ENTRY_SECURITY 4 /* Security Directory */
162 #define IMAGE_DIRECTORY_ENTRY_BASERELOC 5 /* Base Relocation Table */
163 #define IMAGE_DIRECTORY_ENTRY_DEBUG 6 /* Debug Directory */
164 /* IMAGE_DIRECTORY_ENTRY_COPYRIGHT 7 (X86 usage) */
165 #define IMAGE_DIRECTORY_ENTRY_ARCHITECTURE 7 /* Architecture Specific Data */
166 #define IMAGE_DIRECTORY_ENTRY_GLOBALPTR 8 /* RVA of GP */
167 #define IMAGE_DIRECTORY_ENTRY_TLS 9 /* TLS Directory */
168 #define IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG 10 /* Load Configuration Directory */
169 #define IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT 11 /* Bound Import Directory in headers */
170 #define IMAGE_DIRECTORY_ENTRY_IAT 12 /* Import Address Table */
171 #define IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT 13 /* Delay Load Import Descriptors */
172 #define IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR 14 /* COM Runtime descriptor */
174 /* Section header format. */
175 #define IMAGE_SIZEOF_SHORT_NAME 8
177 typedef struct _IMAGE_SECTION_HEADER {
178 BYTE Name[IMAGE_SIZEOF_SHORT_NAME];
179 union {
180 DWORD PhysicalAddress;
181 DWORD VirtualSize;
182 } Misc;
183 DWORD VirtualAddress;
184 DWORD SizeOfRawData;
185 DWORD PointerToRawData;
186 DWORD PointerToRelocations;
187 DWORD PointerToLinenumbers;
188 WORD NumberOfRelocations;
189 WORD NumberOfLinenumbers;
190 DWORD Characteristics;
191 } IMAGE_SECTION_HEADER, *PIMAGE_SECTION_HEADER;
193 #define IMAGE_SIZEOF_SECTION_HEADER 40
195 typedef struct _IMAGE_EXPORT_DIRECTORY {
196 DWORD Characteristics;
197 DWORD TimeDateStamp;
198 WORD MajorVersion;
199 WORD MinorVersion;
200 DWORD Name;
201 DWORD Base;
202 DWORD NumberOfFunctions;
203 DWORD NumberOfNames;
204 DWORD AddressOfFunctions;
205 DWORD AddressOfNames;
206 DWORD AddressOfNameOrdinals;
207 } IMAGE_EXPORT_DIRECTORY,*PIMAGE_EXPORT_DIRECTORY;
209 typedef struct _IMAGE_IMPORT_DESCRIPTOR {
210 union {
211 DWORD Characteristics;
212 DWORD OriginalFirstThunk;
214 DWORD TimeDateStamp;
215 DWORD ForwarderChain;
216 DWORD Name;
217 DWORD FirstThunk;
218 } IMAGE_IMPORT_DESCRIPTOR;
220 typedef struct _IMAGE_BASE_RELOCATION {
221 DWORD VirtualAddress;
222 DWORD SizeOfBlock;
223 // WORD TypeOffset[1];
224 } IMAGE_BASE_RELOCATION;
226 #define IMAGE_SIZEOF_BASE_RELOCATION 8
228 #define IMAGE_REL_BASED_ABSOLUTE 0
229 #define IMAGE_REL_BASED_HIGH 1
230 #define IMAGE_REL_BASED_LOW 2
231 #define IMAGE_REL_BASED_HIGHLOW 3
232 #define IMAGE_REL_BASED_HIGHADJ 4
233 #define IMAGE_REL_BASED_MIPS_JMPADDR 5
234 #define IMAGE_REL_BASED_SECTION 6
235 #define IMAGE_REL_BASED_REL32 7
236 #define IMAGE_REL_BASED_DIR64 10
238 #define IMAGE_SCN_CNT_CODE 0x00000020
239 #define IMAGE_SCN_CNT_INITIALIZED_DATA 0x00000040
240 #define IMAGE_SCN_CNT_UNINITIALIZED_DATA 0x00000080
241 #define IMAGE_SCN_MEM_DISCARDABLE 0x02000000
242 #define IMAGE_SCN_MEM_SHARED 0x10000000
243 #define IMAGE_SCN_MEM_EXECUTE 0x20000000
244 #define IMAGE_SCN_MEM_READ 0x40000000
245 #define IMAGE_SCN_MEM_WRITE 0x80000000
247 #pragma pack(pop)
249 /* ----------------------------------------------------------- */
250 #endif /* ndef IMAGE_NT_SIGNATURE */
251 /* ----------------------------------------------------------- */
253 #ifndef IMAGE_REL_BASED_DIR64
254 # define IMAGE_REL_BASED_DIR64 10
255 #endif
257 #pragma pack(push, 1)
258 struct pe_header
260 IMAGE_DOS_HEADER doshdr;
261 BYTE dosstub[0x40];
262 DWORD nt_sig;
263 IMAGE_FILE_HEADER filehdr;
264 #ifdef TCC_TARGET_X86_64
265 IMAGE_OPTIONAL_HEADER64 opthdr;
266 #else
267 #ifdef _WIN64
268 IMAGE_OPTIONAL_HEADER32 opthdr;
269 #else
270 IMAGE_OPTIONAL_HEADER opthdr;
271 #endif
272 #endif
275 struct pe_reloc_header {
276 DWORD offset;
277 DWORD size;
280 struct pe_rsrc_header {
281 struct _IMAGE_FILE_HEADER filehdr;
282 struct _IMAGE_SECTION_HEADER sectionhdr;
285 struct pe_rsrc_reloc {
286 DWORD offset;
287 DWORD size;
288 WORD type;
290 #pragma pack(pop)
292 /* ------------------------------------------------------------- */
293 /* internal temporary structures */
295 enum {
296 sec_text = 0,
297 sec_rdata ,
298 sec_data ,
299 sec_bss ,
300 sec_idata ,
301 sec_pdata ,
302 sec_other ,
303 sec_rsrc ,
304 sec_stab ,
305 sec_stabstr ,
306 sec_reloc ,
307 sec_last
310 #if 0
311 static const DWORD pe_sec_flags[] = {
312 0x60000020, /* ".text" , */
313 0xC0000040, /* ".data" , */
314 0xC0000080, /* ".bss" , */
315 0x40000040, /* ".idata" , */
316 0x40000040, /* ".pdata" , */
317 0xE0000060, /* < other > , */
318 0x40000040, /* ".rsrc" , */
319 0x42000802, /* ".stab" , */
320 0x42000040, /* ".reloc" , */
322 #endif
324 struct section_info {
325 int cls;
326 char name[32];
327 ADDR3264 sh_addr;
328 DWORD sh_size;
329 DWORD pe_flags;
330 Section *sec;
331 DWORD data_size;
332 IMAGE_SECTION_HEADER ish;
335 struct import_symbol {
336 int sym_index;
337 int iat_index;
338 int thk_offset;
341 struct pe_import_info {
342 int dll_index;
343 int sym_count;
344 struct import_symbol **symbols;
347 struct pe_info {
348 TCCState *s1;
349 Section *reloc;
350 Section *thunk;
351 const char *filename;
352 int type;
353 DWORD sizeofheaders;
354 ADDR3264 imagebase;
355 const char *start_symbol;
356 DWORD start_addr;
357 DWORD imp_offs;
358 DWORD imp_size;
359 DWORD iat_offs;
360 DWORD iat_size;
361 DWORD exp_offs;
362 DWORD exp_size;
363 int subsystem;
364 DWORD section_align;
365 DWORD file_align;
366 struct section_info **sec_info;
367 int sec_count;
368 struct pe_import_info **imp_info;
369 int imp_count;
372 #define PE_NUL 0
373 #define PE_DLL 1
374 #define PE_GUI 2
375 #define PE_EXE 3
376 #define PE_RUN 4
378 /* --------------------------------------------*/
380 static const char *pe_export_name(TCCState *s1, ElfW(Sym) *sym)
382 const char *name = (char*)symtab_section->link->data + sym->st_name;
383 if (s1->leading_underscore && name[0] == '_' && !(sym->st_other & ST_PE_STDCALL))
384 return name + 1;
385 return name;
388 static int pe_find_import(TCCState * s1, ElfW(Sym) *sym)
390 char buffer[200];
391 const char *s, *p;
392 int sym_index = 0, n = 0;
393 int a, err = 0;
395 do {
396 s = pe_export_name(s1, sym);
397 a = 0;
398 if (n) {
399 /* second try: */
400 if (sym->st_other & ST_PE_STDCALL) {
401 /* try w/0 stdcall deco (windows API convention) */
402 p = strrchr(s, '@');
403 if (!p || s[0] != '_')
404 break;
405 strcpy(buffer, s+1)[p-s-1] = 0;
406 } else if (s[0] != '_') { /* try non-ansi function */
407 buffer[0] = '_', strcpy(buffer + 1, s);
408 } else if (0 == memcmp(s, "__imp_", 6)) { /* mingw 2.0 */
409 strcpy(buffer, s + 6), a = 1;
410 } else if (0 == memcmp(s, "_imp__", 6)) { /* mingw 3.7 */
411 strcpy(buffer, s + 6), a = 1;
412 } else {
413 continue;
415 s = buffer;
417 sym_index = find_elf_sym(s1->dynsymtab_section, s);
418 // printf("find (%d) %d %s\n", n, sym_index, s);
419 if (sym_index
420 && ELFW(ST_TYPE)(sym->st_info) == STT_OBJECT
421 && 0 == (sym->st_other & ST_PE_IMPORT)
422 && 0 == a
423 ) err = -1, sym_index = 0;
424 } while (0 == sym_index && ++n < 2);
425 return n == 2 ? err : sym_index;
428 /*----------------------------------------------------------------------------*/
430 static int dynarray_assoc(void **pp, int n, int key)
432 int i;
433 for (i = 0; i < n; ++i, ++pp)
434 if (key == **(int **) pp)
435 return i;
436 return -1;
439 static DWORD umin(DWORD a, DWORD b)
441 return a < b ? a : b;
444 static DWORD umax(DWORD a, DWORD b)
446 return a < b ? b : a;
449 static DWORD pe_file_align(struct pe_info *pe, DWORD n)
451 return (n + (pe->file_align - 1)) & ~(pe->file_align - 1);
454 static ADDR3264 pe_virtual_align(struct pe_info *pe, ADDR3264 n)
456 return (n + (pe->section_align - 1)) & ~(ADDR3264)(pe->section_align - 1);
459 static void pe_align_section(Section *s, int a)
461 int i = s->data_offset & (a-1);
462 if (i)
463 section_ptr_add(s, a - i);
466 static void pe_set_datadir(struct pe_header *hdr, int dir, DWORD addr, DWORD size)
468 hdr->opthdr.DataDirectory[dir].VirtualAddress = addr;
469 hdr->opthdr.DataDirectory[dir].Size = size;
472 struct pe_file {
473 FILE *op;
474 DWORD sum;
475 unsigned pos;
478 static int pe_fwrite(void *data, int len, struct pe_file *pf)
480 WORD *p = data;
481 DWORD sum;
482 int ret, i;
483 pf->pos += (ret = fwrite(data, 1, len, pf->op));
484 sum = pf->sum;
485 for (i = len; i > 0; i -= 2) {
486 sum += (i >= 2) ? *p++ : *(BYTE*)p;
487 sum = (sum + (sum >> 16)) & 0xFFFF;
489 pf->sum = sum;
490 return len == ret ? 0 : -1;
493 static void pe_fpad(struct pe_file *pf, DWORD new_pos)
495 char buf[256];
496 int n, diff = new_pos - pf->pos;
497 memset(buf, 0, sizeof buf);
498 while (diff > 0) {
499 diff -= n = umin(diff, sizeof buf);
500 fwrite(buf, n, 1, pf->op);
502 pf->pos = new_pos;
505 /*----------------------------------------------------------------------------*/
506 static int pe_write(struct pe_info *pe)
508 static const struct pe_header pe_template = {
510 /* IMAGE_DOS_HEADER doshdr */
511 0x5A4D, /*WORD e_magic; Magic number */
512 0x0090, /*WORD e_cblp; Bytes on last page of file */
513 0x0003, /*WORD e_cp; Pages in file */
514 0x0000, /*WORD e_crlc; Relocations */
516 0x0004, /*WORD e_cparhdr; Size of header in paragraphs */
517 0x0000, /*WORD e_minalloc; Minimum extra paragraphs needed */
518 0xFFFF, /*WORD e_maxalloc; Maximum extra paragraphs needed */
519 0x0000, /*WORD e_ss; Initial (relative) SS value */
521 0x00B8, /*WORD e_sp; Initial SP value */
522 0x0000, /*WORD e_csum; Checksum */
523 0x0000, /*WORD e_ip; Initial IP value */
524 0x0000, /*WORD e_cs; Initial (relative) CS value */
525 0x0040, /*WORD e_lfarlc; File address of relocation table */
526 0x0000, /*WORD e_ovno; Overlay number */
527 {0,0,0,0}, /*WORD e_res[4]; Reserved words */
528 0x0000, /*WORD e_oemid; OEM identifier (for e_oeminfo) */
529 0x0000, /*WORD e_oeminfo; OEM information; e_oemid specific */
530 {0,0,0,0,0,0,0,0,0,0}, /*WORD e_res2[10]; Reserved words */
531 0x00000080 /*DWORD e_lfanew; File address of new exe header */
533 /* BYTE dosstub[0x40] */
534 /* 14 code bytes + "This program cannot be run in DOS mode.\r\r\n$" + 6 * 0x00 */
535 0x0e,0x1f,0xba,0x0e,0x00,0xb4,0x09,0xcd,0x21,0xb8,0x01,0x4c,0xcd,0x21,0x54,0x68,
536 0x69,0x73,0x20,0x70,0x72,0x6f,0x67,0x72,0x61,0x6d,0x20,0x63,0x61,0x6e,0x6e,0x6f,
537 0x74,0x20,0x62,0x65,0x20,0x72,0x75,0x6e,0x20,0x69,0x6e,0x20,0x44,0x4f,0x53,0x20,
538 0x6d,0x6f,0x64,0x65,0x2e,0x0d,0x0d,0x0a,0x24,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
540 0x00004550, /* DWORD nt_sig = IMAGE_NT_SIGNATURE */
542 /* IMAGE_FILE_HEADER filehdr */
543 IMAGE_FILE_MACHINE, /*WORD Machine; */
544 0x0003, /*WORD NumberOfSections; */
545 0x00000000, /*DWORD TimeDateStamp; */
546 0x00000000, /*DWORD PointerToSymbolTable; */
547 0x00000000, /*DWORD NumberOfSymbols; */
548 #if defined(TCC_TARGET_X86_64)
549 0x00F0, /*WORD SizeOfOptionalHeader; */
550 0x022F /*WORD Characteristics; */
551 #define CHARACTERISTICS_DLL 0x222E
552 #elif defined(TCC_TARGET_I386)
553 0x00E0, /*WORD SizeOfOptionalHeader; */
554 0x030F /*WORD Characteristics; */
555 #define CHARACTERISTICS_DLL 0x230E
556 #elif defined(TCC_TARGET_ARM)
557 0x00E0, /*WORD SizeOfOptionalHeader; */
558 0x010F, /*WORD Characteristics; */
559 #define CHARACTERISTICS_DLL 0x230F
560 #endif
562 /* IMAGE_OPTIONAL_HEADER opthdr */
563 /* Standard fields. */
564 #ifdef TCC_TARGET_X86_64
565 0x020B, /*WORD Magic; */
566 #else
567 0x010B, /*WORD Magic; */
568 #endif
569 0x06, /*BYTE MajorLinkerVersion; */
570 0x00, /*BYTE MinorLinkerVersion; */
571 0x00000000, /*DWORD SizeOfCode; */
572 0x00000000, /*DWORD SizeOfInitializedData; */
573 0x00000000, /*DWORD SizeOfUninitializedData; */
574 0x00000000, /*DWORD AddressOfEntryPoint; */
575 0x00000000, /*DWORD BaseOfCode; */
576 #ifndef TCC_TARGET_X86_64
577 0x00000000, /*DWORD BaseOfData; */
578 #endif
579 /* NT additional fields. */
580 #if defined(TCC_TARGET_ARM)
581 0x00100000, /*DWORD ImageBase; */
582 #else
583 0x00400000, /*DWORD ImageBase; */
584 #endif
585 0x00001000, /*DWORD SectionAlignment; */
586 0x00000200, /*DWORD FileAlignment; */
587 0x0004, /*WORD MajorOperatingSystemVersion; */
588 0x0000, /*WORD MinorOperatingSystemVersion; */
589 0x0000, /*WORD MajorImageVersion; */
590 0x0000, /*WORD MinorImageVersion; */
591 0x0004, /*WORD MajorSubsystemVersion; */
592 0x0000, /*WORD MinorSubsystemVersion; */
593 0x00000000, /*DWORD Win32VersionValue; */
594 0x00000000, /*DWORD SizeOfImage; */
595 0x00000200, /*DWORD SizeOfHeaders; */
596 0x00000000, /*DWORD CheckSum; */
597 0x0002, /*WORD Subsystem; */
598 0x0000, /*WORD DllCharacteristics; */
599 0x00100000, /*DWORD SizeOfStackReserve; */
600 0x00001000, /*DWORD SizeOfStackCommit; */
601 0x00100000, /*DWORD SizeOfHeapReserve; */
602 0x00001000, /*DWORD SizeOfHeapCommit; */
603 0x00000000, /*DWORD LoaderFlags; */
604 0x00000010, /*DWORD NumberOfRvaAndSizes; */
606 /* IMAGE_DATA_DIRECTORY DataDirectory[16]; */
607 {{0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0},
608 {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}}
611 struct pe_header pe_header = pe_template;
613 int i;
614 struct pe_file pf = {0};
615 DWORD file_offset;
616 struct section_info *si;
617 IMAGE_SECTION_HEADER *psh;
618 TCCState *s1 = pe->s1;
620 pf.op = fopen(pe->filename, "wb");
621 if (NULL == pf.op)
622 return tcc_error_noabort("could not write '%s': %s", pe->filename, strerror(errno));
624 pe->sizeofheaders = pe_file_align(pe,
625 sizeof (struct pe_header)
626 + pe->sec_count * sizeof (IMAGE_SECTION_HEADER)
629 file_offset = pe->sizeofheaders;
631 if (2 == pe->s1->verbose)
632 printf("-------------------------------"
633 "\n virt file size section" "\n");
634 for (i = 0; i < pe->sec_count; ++i) {
635 DWORD addr, size;
636 const char *sh_name;
638 si = pe->sec_info[i];
639 sh_name = si->name;
640 addr = si->sh_addr - pe->imagebase;
641 size = si->sh_size;
642 psh = &si->ish;
644 if (2 == pe->s1->verbose)
645 printf("%6x %6x %6x %s\n",
646 (unsigned)addr, (unsigned)file_offset, (unsigned)size, sh_name);
648 switch (si->cls) {
649 case sec_text:
650 if (!pe_header.opthdr.BaseOfCode)
651 pe_header.opthdr.BaseOfCode = addr;
652 break;
654 case sec_data:
655 #ifndef TCC_TARGET_X86_64
656 if (!pe_header.opthdr.BaseOfData)
657 pe_header.opthdr.BaseOfData = addr;
658 #endif
659 break;
661 case sec_bss:
662 break;
664 case sec_reloc:
665 pe_set_datadir(&pe_header, IMAGE_DIRECTORY_ENTRY_BASERELOC, addr, size);
666 break;
668 case sec_rsrc:
669 pe_set_datadir(&pe_header, IMAGE_DIRECTORY_ENTRY_RESOURCE, addr, size);
670 break;
672 case sec_pdata:
673 pe_set_datadir(&pe_header, IMAGE_DIRECTORY_ENTRY_EXCEPTION, addr, size);
674 break;
677 if (pe->imp_size) {
678 pe_set_datadir(&pe_header, IMAGE_DIRECTORY_ENTRY_IMPORT,
679 pe->imp_offs, pe->imp_size);
680 pe_set_datadir(&pe_header, IMAGE_DIRECTORY_ENTRY_IAT,
681 pe->iat_offs, pe->iat_size);
683 if (pe->exp_size) {
684 pe_set_datadir(&pe_header, IMAGE_DIRECTORY_ENTRY_EXPORT,
685 pe->exp_offs, pe->exp_size);
688 memcpy(psh->Name, sh_name, umin(strlen(sh_name), sizeof psh->Name));
690 psh->Characteristics = si->pe_flags;
691 psh->VirtualAddress = addr;
692 psh->Misc.VirtualSize = size;
693 pe_header.opthdr.SizeOfImage =
694 umax(pe_virtual_align(pe, size + addr), pe_header.opthdr.SizeOfImage);
696 if (si->data_size) {
697 psh->PointerToRawData = file_offset;
698 file_offset = pe_file_align(pe, file_offset + si->data_size);
699 psh->SizeOfRawData = file_offset - psh->PointerToRawData;
700 if (si->cls == sec_text)
701 pe_header.opthdr.SizeOfCode += psh->SizeOfRawData;
702 else
703 pe_header.opthdr.SizeOfInitializedData += psh->SizeOfRawData;
707 //pe_header.filehdr.TimeDateStamp = time(NULL);
708 pe_header.filehdr.NumberOfSections = pe->sec_count;
709 pe_header.opthdr.AddressOfEntryPoint = pe->start_addr;
710 pe_header.opthdr.SizeOfHeaders = pe->sizeofheaders;
711 pe_header.opthdr.ImageBase = pe->imagebase;
712 pe_header.opthdr.Subsystem = pe->subsystem;
713 if (pe->s1->pe_stack_size)
714 pe_header.opthdr.SizeOfStackReserve = pe->s1->pe_stack_size;
715 if (PE_DLL == pe->type)
716 pe_header.filehdr.Characteristics = CHARACTERISTICS_DLL;
717 pe_header.filehdr.Characteristics |= pe->s1->pe_characteristics;
719 pe_fwrite(&pe_header, sizeof pe_header, &pf);
720 for (i = 0; i < pe->sec_count; ++i)
721 pe_fwrite(&pe->sec_info[i]->ish, sizeof(IMAGE_SECTION_HEADER), &pf);
723 file_offset = pe->sizeofheaders;
724 for (i = 0; i < pe->sec_count; ++i) {
725 Section *s;
726 si = pe->sec_info[i];
727 if (!si->data_size)
728 continue;
729 for (s = si->sec; s; s = s->prev) {
730 pe_fpad(&pf, file_offset);
731 pe_fwrite(s->data, s->data_offset, &pf);
732 if (s->prev)
733 file_offset += s->prev->sh_addr - s->sh_addr;
735 file_offset = si->ish.PointerToRawData + si->ish.SizeOfRawData;
736 pe_fpad(&pf, file_offset);
739 pf.sum += file_offset;
740 fseek(pf.op, offsetof(struct pe_header, opthdr.CheckSum), SEEK_SET);
741 pe_fwrite(&pf.sum, sizeof (DWORD), &pf);
743 fclose (pf.op);
744 #ifndef _WIN32
745 chmod(pe->filename, 0777);
746 #endif
748 if (2 == pe->s1->verbose)
749 printf("-------------------------------\n");
750 if (pe->s1->verbose)
751 printf("<- %s (%u bytes)\n", pe->filename, (unsigned)file_offset);
753 return 0;
756 /*----------------------------------------------------------------------------*/
758 static struct import_symbol *pe_add_import(struct pe_info *pe, int sym_index)
760 int i;
761 int dll_index;
762 struct pe_import_info *p;
763 struct import_symbol *s;
764 ElfW(Sym) *isym;
766 isym = (ElfW(Sym) *)pe->s1->dynsymtab_section->data + sym_index;
767 dll_index = isym->st_size;
769 i = dynarray_assoc ((void**)pe->imp_info, pe->imp_count, dll_index);
770 if (-1 != i) {
771 p = pe->imp_info[i];
772 goto found_dll;
774 p = tcc_mallocz(sizeof *p);
775 p->dll_index = dll_index;
776 dynarray_add(&pe->imp_info, &pe->imp_count, p);
778 found_dll:
779 i = dynarray_assoc ((void**)p->symbols, p->sym_count, sym_index);
780 if (-1 != i)
781 return p->symbols[i];
783 s = tcc_mallocz(sizeof *s);
784 dynarray_add(&p->symbols, &p->sym_count, s);
785 s->sym_index = sym_index;
786 return s;
789 void pe_free_imports(struct pe_info *pe)
791 int i;
792 for (i = 0; i < pe->imp_count; ++i) {
793 struct pe_import_info *p = pe->imp_info[i];
794 dynarray_reset(&p->symbols, &p->sym_count);
796 dynarray_reset(&pe->imp_info, &pe->imp_count);
799 /*----------------------------------------------------------------------------*/
800 static void pe_build_imports(struct pe_info *pe)
802 int thk_ptr, ent_ptr, dll_ptr, sym_cnt, i;
803 DWORD rva_base = pe->thunk->sh_addr - pe->imagebase;
804 int ndlls = pe->imp_count;
805 TCCState *s1 = pe->s1;
807 for (sym_cnt = i = 0; i < ndlls; ++i)
808 sym_cnt += pe->imp_info[i]->sym_count;
810 if (0 == sym_cnt)
811 return;
813 pe_align_section(pe->thunk, 16);
814 pe->imp_size = (ndlls + 1) * sizeof(IMAGE_IMPORT_DESCRIPTOR);
815 pe->iat_size = (sym_cnt + ndlls) * sizeof(ADDR3264);
816 dll_ptr = pe->thunk->data_offset;
817 thk_ptr = dll_ptr + pe->imp_size;
818 ent_ptr = thk_ptr + pe->iat_size;
819 pe->imp_offs = dll_ptr + rva_base;
820 pe->iat_offs = thk_ptr + rva_base;
821 section_ptr_add(pe->thunk, pe->imp_size + 2*pe->iat_size);
823 for (i = 0; i < pe->imp_count; ++i) {
824 IMAGE_IMPORT_DESCRIPTOR *hdr;
825 int k, n, dllindex;
826 ADDR3264 v;
827 struct pe_import_info *p = pe->imp_info[i];
828 const char *name;
829 DLLReference *dllref;
831 dllindex = p->dll_index;
832 if (dllindex)
833 name = tcc_basename((dllref = pe->s1->loaded_dlls[dllindex-1])->name);
834 else
835 name = "", dllref = NULL;
837 /* put the dll name into the import header */
838 v = put_elf_str(pe->thunk, name);
839 hdr = (IMAGE_IMPORT_DESCRIPTOR*)(pe->thunk->data + dll_ptr);
840 hdr->FirstThunk = thk_ptr + rva_base;
841 hdr->OriginalFirstThunk = ent_ptr + rva_base;
842 hdr->Name = v + rva_base;
844 for (k = 0, n = p->sym_count; k <= n; ++k) {
845 if (k < n) {
846 int iat_index = p->symbols[k]->iat_index;
847 int sym_index = p->symbols[k]->sym_index;
848 ElfW(Sym) *imp_sym = (ElfW(Sym) *)pe->s1->dynsymtab_section->data + sym_index;
849 ElfW(Sym) *org_sym = (ElfW(Sym) *)symtab_section->data + iat_index;
850 const char *name = (char*)pe->s1->dynsymtab_section->link->data + imp_sym->st_name;
851 int ordinal;
853 org_sym->st_value = thk_ptr;
854 org_sym->st_shndx = pe->thunk->sh_num;
856 if (dllref)
857 v = 0, ordinal = imp_sym->st_value; /* ordinal from pe_load_def */
858 else
859 ordinal = 0, v = imp_sym->st_value; /* address from tcc_add_symbol() */
861 #ifdef TCC_IS_NATIVE
862 if (pe->type == PE_RUN) {
863 if (dllref) {
864 if ( !dllref->handle )
865 dllref->handle = LoadLibrary(dllref->name);
866 v = (ADDR3264)GetProcAddress(dllref->handle, ordinal?(char*)0+ordinal:name);
868 if (!v)
869 tcc_error_noabort("could not resolve symbol '%s'", name);
870 } else
871 #endif
872 if (ordinal) {
873 v = ordinal | (ADDR3264)1 << (sizeof(ADDR3264)*8 - 1);
874 } else {
875 v = pe->thunk->data_offset + rva_base;
876 section_ptr_add(pe->thunk, sizeof(WORD)); /* hint, not used */
877 put_elf_str(pe->thunk, name);
880 } else {
881 v = 0; /* last entry is zero */
884 *(ADDR3264*)(pe->thunk->data+thk_ptr) =
885 *(ADDR3264*)(pe->thunk->data+ent_ptr) = v;
886 thk_ptr += sizeof (ADDR3264);
887 ent_ptr += sizeof (ADDR3264);
889 dll_ptr += sizeof(IMAGE_IMPORT_DESCRIPTOR);
893 /* ------------------------------------------------------------- */
895 struct pe_sort_sym
897 int index;
898 const char *name;
901 static int sym_cmp(const void *va, const void *vb)
903 const char *ca = (*(struct pe_sort_sym**)va)->name;
904 const char *cb = (*(struct pe_sort_sym**)vb)->name;
905 return strcmp(ca, cb);
908 static void pe_build_exports(struct pe_info *pe)
910 ElfW(Sym) *sym;
911 int sym_index, sym_end;
912 DWORD rva_base, base_o, func_o, name_o, ord_o, str_o;
913 IMAGE_EXPORT_DIRECTORY *hdr;
914 int sym_count, ord;
915 struct pe_sort_sym **sorted, *p;
916 TCCState *s1 = pe->s1;
918 FILE *op;
919 char buf[260];
920 const char *dllname;
921 const char *name;
923 rva_base = pe->thunk->sh_addr - pe->imagebase;
924 sym_count = 0, sorted = NULL, op = NULL;
926 sym_end = symtab_section->data_offset / sizeof(ElfW(Sym));
927 for (sym_index = 1; sym_index < sym_end; ++sym_index) {
928 sym = (ElfW(Sym)*)symtab_section->data + sym_index;
929 name = pe_export_name(pe->s1, sym);
930 if (sym->st_other & ST_PE_EXPORT) {
931 p = tcc_malloc(sizeof *p);
932 p->index = sym_index;
933 p->name = name;
934 dynarray_add(&sorted, &sym_count, p);
936 #if 0
937 if (sym->st_other & ST_PE_EXPORT)
938 printf("export: %s\n", name);
939 if (sym->st_other & ST_PE_STDCALL)
940 printf("stdcall: %s\n", name);
941 #endif
944 if (0 == sym_count)
945 return;
947 qsort (sorted, sym_count, sizeof *sorted, sym_cmp);
949 pe_align_section(pe->thunk, 16);
950 dllname = tcc_basename(pe->filename);
952 base_o = pe->thunk->data_offset;
953 func_o = base_o + sizeof(IMAGE_EXPORT_DIRECTORY);
954 name_o = func_o + sym_count * sizeof (DWORD);
955 ord_o = name_o + sym_count * sizeof (DWORD);
956 str_o = ord_o + sym_count * sizeof(WORD);
958 hdr = section_ptr_add(pe->thunk, str_o - base_o);
959 hdr->Characteristics = 0;
960 hdr->Base = 1;
961 hdr->NumberOfFunctions = sym_count;
962 hdr->NumberOfNames = sym_count;
963 hdr->AddressOfFunctions = func_o + rva_base;
964 hdr->AddressOfNames = name_o + rva_base;
965 hdr->AddressOfNameOrdinals = ord_o + rva_base;
966 hdr->Name = str_o + rva_base;
967 put_elf_str(pe->thunk, dllname);
969 #if 1
970 /* automatically write exports to <output-filename>.def */
971 pstrcpy(buf, sizeof buf, pe->filename);
972 strcpy(tcc_fileextension(buf), ".def");
973 op = fopen(buf, "wb");
974 if (NULL == op) {
975 tcc_error_noabort("could not create '%s': %s", buf, strerror(errno));
976 } else {
977 fprintf(op, "LIBRARY %s\n\nEXPORTS\n", dllname);
978 if (pe->s1->verbose)
979 printf("<- %s (%d symbol%s)\n", buf, sym_count, &"s"[sym_count < 2]);
981 #endif
983 for (ord = 0; ord < sym_count; ++ord)
985 p = sorted[ord], sym_index = p->index, name = p->name;
986 /* insert actual address later in relocate_sections() */
987 put_elf_reloc(symtab_section, pe->thunk,
988 func_o, R_XXX_RELATIVE, sym_index);
989 *(DWORD*)(pe->thunk->data + name_o)
990 = pe->thunk->data_offset + rva_base;
991 *(WORD*)(pe->thunk->data + ord_o)
992 = ord;
993 put_elf_str(pe->thunk, name);
994 func_o += sizeof (DWORD);
995 name_o += sizeof (DWORD);
996 ord_o += sizeof (WORD);
997 if (op)
998 fprintf(op, "%s\n", name);
1001 pe->exp_offs = base_o + rva_base;
1002 pe->exp_size = pe->thunk->data_offset - base_o;
1003 dynarray_reset(&sorted, &sym_count);
1004 if (op)
1005 fclose(op);
1008 /* ------------------------------------------------------------- */
1009 static void pe_build_reloc (struct pe_info *pe)
1011 DWORD offset, block_ptr, sh_addr, addr;
1012 int count, i;
1013 ElfW_Rel *rel, *rel_end;
1014 Section *s = NULL, *sr;
1015 struct pe_reloc_header *hdr;
1017 sh_addr = offset = block_ptr = count = i = 0;
1018 rel = rel_end = NULL;
1020 for(;;) {
1021 if (rel < rel_end) {
1022 int type = ELFW(R_TYPE)(rel->r_info);
1023 addr = rel->r_offset + sh_addr;
1024 ++ rel;
1025 if (type != REL_TYPE_DIRECT)
1026 continue;
1027 if (count == 0) { /* new block */
1028 block_ptr = pe->reloc->data_offset;
1029 section_ptr_add(pe->reloc, sizeof(struct pe_reloc_header));
1030 offset = addr & 0xFFFFFFFF<<12;
1032 if ((addr -= offset) < (1<<12)) { /* one block spans 4k addresses */
1033 WORD *wp = section_ptr_add(pe->reloc, sizeof (WORD));
1034 *wp = addr | PE_IMAGE_REL<<12;
1035 ++count;
1036 continue;
1038 -- rel;
1040 } else if (s) {
1041 sr = s->reloc;
1042 if (sr) {
1043 rel = (ElfW_Rel *)sr->data;
1044 rel_end = (ElfW_Rel *)(sr->data + sr->data_offset);
1045 sh_addr = s->sh_addr;
1047 s = s->prev;
1048 continue;
1050 } else if (i < pe->sec_count) {
1051 s = pe->sec_info[i]->sec, ++i;
1052 continue;
1054 } else if (!count)
1055 break;
1057 /* fill the last block and ready for a new one */
1058 if (count & 1) /* align for DWORDS */
1059 section_ptr_add(pe->reloc, sizeof(WORD)), ++count;
1060 hdr = (struct pe_reloc_header *)(pe->reloc->data + block_ptr);
1061 hdr -> offset = offset - pe->imagebase;
1062 hdr -> size = count * sizeof(WORD) + sizeof(struct pe_reloc_header);
1063 count = 0;
1067 /* ------------------------------------------------------------- */
1068 static int pe_section_class(Section *s)
1070 int type, flags;
1071 const char *name;
1072 type = s->sh_type;
1073 flags = s->sh_flags;
1074 name = s->name;
1075 if (0 == memcmp(name, ".stab", 5)) {
1076 if (0 == s->s1->do_debug)
1077 return sec_last;
1078 return name[5] ? sec_stabstr : sec_stab;
1080 if (flags & SHF_ALLOC) {
1081 if (type == SHT_PROGBITS
1082 || type == SHT_INIT_ARRAY
1083 || type == SHT_FINI_ARRAY) {
1084 if (flags & SHF_EXECINSTR)
1085 return sec_text;
1086 if (flags & SHF_WRITE)
1087 return sec_data;
1088 if (0 == strcmp(name, ".rsrc"))
1089 return sec_rsrc;
1090 if (0 == strcmp(name, ".iedat"))
1091 return sec_idata;
1092 if (0 == strcmp(name, ".pdata"))
1093 return sec_pdata;
1094 return sec_rdata;
1095 } else if (type == SHT_NOBITS) {
1096 return sec_bss;
1098 return sec_other;
1099 } else {
1100 if (0 == strcmp(name, ".reloc"))
1101 return sec_reloc;
1103 return sec_last;
1106 static int pe_assign_addresses (struct pe_info *pe)
1108 int i, k, n, c, nbs;
1109 ADDR3264 addr;
1110 int *sec_order, *sec_cls;
1111 struct section_info *si;
1112 Section *s;
1113 TCCState *s1 = pe->s1;
1115 if (PE_DLL == pe->type)
1116 pe->reloc = new_section(pe->s1, ".reloc", SHT_PROGBITS, 0);
1117 //pe->thunk = new_section(pe->s1, ".iedat", SHT_PROGBITS, SHF_ALLOC);
1119 nbs = s1->nb_sections;
1120 sec_order = tcc_mallocz(2 * sizeof (int) * nbs);
1121 sec_cls = sec_order + nbs;
1122 for (i = 1; i < nbs; ++i) {
1123 s = s1->sections[i];
1124 k = pe_section_class(s);
1125 for (n = i; n > 1 && k < (c = sec_cls[n - 1]); --n)
1126 sec_cls[n] = c, sec_order[n] = sec_order[n - 1];
1127 sec_cls[n] = k, sec_order[n] = i;
1129 si = NULL;
1130 addr = pe->imagebase + 1;
1132 for (i = 1; (c = sec_cls[i]) < sec_last; ++i) {
1133 s = s1->sections[sec_order[i]];
1135 if (PE_MERGE_DATA && c == sec_bss)
1136 c = sec_data;
1138 if (si && c == si->cls) {
1139 /* merge with previous section */
1140 s->sh_addr = addr = ((addr - 1) | (16 - 1)) + 1;
1141 } else {
1142 si = NULL;
1143 s->sh_addr = addr = pe_virtual_align(pe, addr);
1146 if (NULL == pe->thunk
1147 && c == (data_section == rodata_section ? sec_data : sec_rdata))
1148 pe->thunk = s;
1150 if (s == pe->thunk) {
1151 pe_build_imports(pe);
1152 pe_build_exports(pe);
1154 if (s == pe->reloc)
1155 pe_build_reloc (pe);
1157 if (0 == s->data_offset)
1158 continue;
1160 if (si)
1161 goto add_section;
1163 si = tcc_mallocz(sizeof *si);
1164 dynarray_add(&pe->sec_info, &pe->sec_count, si);
1166 strcpy(si->name, s->name);
1167 si->cls = c;
1168 si->sh_addr = addr;
1170 si->pe_flags = IMAGE_SCN_MEM_READ;
1171 if (s->sh_flags & SHF_EXECINSTR)
1172 si->pe_flags |= IMAGE_SCN_MEM_EXECUTE | IMAGE_SCN_CNT_CODE;
1173 else if (s->sh_type == SHT_NOBITS)
1174 si->pe_flags |= IMAGE_SCN_CNT_UNINITIALIZED_DATA;
1175 else
1176 si->pe_flags |= IMAGE_SCN_CNT_INITIALIZED_DATA;
1177 if (s->sh_flags & SHF_WRITE)
1178 si->pe_flags |= IMAGE_SCN_MEM_WRITE;
1179 if (0 == (s->sh_flags & SHF_ALLOC))
1180 si->pe_flags |= IMAGE_SCN_MEM_DISCARDABLE;
1182 add_section:
1183 addr += s->data_offset;
1184 si->sh_size = addr - si->sh_addr;
1185 if (s->sh_type != SHT_NOBITS) {
1186 Section **ps = &si->sec;
1187 while (*ps)
1188 ps = &(*ps)->prev;
1189 *ps = s, s->prev = NULL;
1190 si->data_size = si->sh_size;
1192 //printf("%08x %05x %08x %s\n", si->sh_addr, si->sh_size, si->pe_flags, s->name);
1194 #if 0
1195 for (i = 1; i < nbs; ++i) {
1196 Section *s = s1->sections[sec_order[i]];
1197 int type = s->sh_type;
1198 int flags = s->sh_flags;
1199 printf("section %-16s %-10s %p %04x %s,%s,%s\n",
1200 s->name,
1201 type == SHT_PROGBITS ? "progbits" :
1202 type == SHT_INIT_ARRAY ? "initarr" :
1203 type == SHT_FINI_ARRAY ? "finiarr" :
1204 type == SHT_NOBITS ? "nobits" :
1205 type == SHT_SYMTAB ? "symtab" :
1206 type == SHT_STRTAB ? "strtab" :
1207 type == SHT_RELX ? "rel" : "???",
1208 s->sh_addr,
1209 (unsigned)s->data_offset,
1210 flags & SHF_ALLOC ? "alloc" : "",
1211 flags & SHF_WRITE ? "write" : "",
1212 flags & SHF_EXECINSTR ? "exec" : ""
1214 fflush(stdout);
1216 s1->verbose = 2;
1217 #endif
1218 tcc_free(sec_order);
1219 return 0;
1222 /*----------------------------------------------------------------------------*/
1224 static int pe_isafunc(TCCState *s1, int sym_index)
1226 Section *sr = text_section->reloc;
1227 ElfW_Rel *rel, *rel_end;
1228 ElfW(Addr)info = ELFW(R_INFO)(sym_index, R_XXX_FUNCCALL);
1229 #ifdef R_XXX_FUNCCALL2
1230 ElfW(Addr)info2 = ELFW(R_INFO)(sym_index, R_XXX_FUNCCALL2);
1231 #endif
1232 if (!sr)
1233 return 0;
1234 rel_end = (ElfW_Rel *)(sr->data + sr->data_offset);
1235 for (rel = (ElfW_Rel *)sr->data; rel < rel_end; rel++) {
1236 if (rel->r_info == info)
1237 return 1;
1238 #ifdef R_XXX_FUNCCALL2
1239 if (rel->r_info == info2)
1240 return 1;
1241 #endif
1243 return 0;
1246 /*----------------------------------------------------------------------------*/
1247 static int pe_check_symbols(struct pe_info *pe)
1249 ElfW(Sym) *sym;
1250 int sym_index, sym_end;
1251 int ret = 0;
1252 TCCState *s1 = pe->s1;
1254 pe_align_section(text_section, 8);
1256 sym_end = symtab_section->data_offset / sizeof(ElfW(Sym));
1257 for (sym_index = 1; sym_index < sym_end; ++sym_index) {
1259 sym = (ElfW(Sym) *)symtab_section->data + sym_index;
1260 if (sym->st_shndx == SHN_UNDEF) {
1262 const char *name = (char*)symtab_section->link->data + sym->st_name;
1263 unsigned type = ELFW(ST_TYPE)(sym->st_info);
1264 int imp_sym = pe_find_import(pe->s1, sym);
1265 struct import_symbol *is;
1267 if (imp_sym <= 0)
1268 goto not_found;
1270 if (type == STT_NOTYPE) {
1271 /* symbols from assembler have no type, find out which */
1272 if (pe_isafunc(s1, sym_index))
1273 type = STT_FUNC;
1274 else
1275 type = STT_OBJECT;
1278 is = pe_add_import(pe, imp_sym);
1280 if (type == STT_FUNC) {
1281 unsigned offset = is->thk_offset;
1282 if (offset) {
1283 /* got aliased symbol, like stricmp and _stricmp */
1284 } else {
1285 char buffer[100];
1286 unsigned char *p;
1288 /* add a helper symbol, will be patched later in
1289 pe_build_imports */
1290 sprintf(buffer, "IAT.%s", name);
1291 is->iat_index = put_elf_sym(
1292 symtab_section, 0, sizeof(DWORD),
1293 ELFW(ST_INFO)(STB_GLOBAL, STT_OBJECT),
1294 0, SHN_UNDEF, buffer);
1296 offset = text_section->data_offset;
1297 is->thk_offset = offset;
1299 /* add the 'jmp IAT[x]' instruction */
1300 #ifdef TCC_TARGET_ARM
1301 p = section_ptr_add(text_section, 8+4); // room for code and address
1302 write32le(p + 0, 0xE59FC000); // arm code ldr ip, [pc] ; PC+8+0 = 0001xxxx
1303 write32le(p + 4, 0xE59CF000); // arm code ldr pc, [ip]
1304 put_elf_reloc(symtab_section, text_section,
1305 offset + 8, R_XXX_THUNKFIX, is->iat_index); // offset to IAT position
1306 #else
1307 p = section_ptr_add(text_section, 8);
1308 write16le(p, 0x25FF);
1309 #ifdef TCC_TARGET_X86_64
1310 write32le(p + 2, (DWORD)-4);
1311 #endif
1312 put_elf_reloc(symtab_section, text_section,
1313 offset + 2, R_XXX_THUNKFIX, is->iat_index);
1314 #endif
1316 /* tcc_realloc might have altered sym's address */
1317 sym = (ElfW(Sym) *)symtab_section->data + sym_index;
1319 /* patch the original symbol */
1320 sym->st_value = offset;
1321 sym->st_shndx = text_section->sh_num;
1322 sym->st_other &= ~ST_PE_EXPORT; /* do not export */
1323 continue;
1326 if (type == STT_OBJECT) { /* data, ptr to that should be */
1327 if (0 == is->iat_index) {
1328 /* original symbol will be patched later in pe_build_imports */
1329 is->iat_index = sym_index;
1330 continue;
1334 not_found:
1335 if (ELFW(ST_BIND)(sym->st_info) == STB_WEAK)
1336 /* STB_WEAK undefined symbols are accepted */
1337 continue;
1338 ret = tcc_error_noabort("undefined symbol '%s'%s", name,
1339 imp_sym < 0 ? ", missing __declspec(dllimport)?":"");
1341 } else if (pe->s1->rdynamic
1342 && ELFW(ST_BIND)(sym->st_info) != STB_LOCAL) {
1343 /* if -rdynamic option, then export all non local symbols */
1344 sym->st_other |= ST_PE_EXPORT;
1347 return ret;
1350 /*----------------------------------------------------------------------------*/
1351 #if PE_PRINT_SECTIONS
1352 static void pe_print_section(FILE * f, Section * s)
1354 /* just if you're curious */
1355 BYTE *p, *e, b;
1356 int i, n, l, m;
1357 p = s->data;
1358 e = s->data + s->data_offset;
1359 l = e - p;
1361 fprintf(f, "section \"%s\"", s->name);
1362 if (s->link)
1363 fprintf(f, "\nlink \"%s\"", s->link->name);
1364 if (s->reloc)
1365 fprintf(f, "\nreloc \"%s\"", s->reloc->name);
1366 fprintf(f, "\nv_addr %08X", (unsigned)s->sh_addr);
1367 fprintf(f, "\ncontents %08X", (unsigned)l);
1368 fprintf(f, "\n\n");
1370 if (s->sh_type == SHT_NOBITS)
1371 return;
1373 if (0 == l)
1374 return;
1376 if (s->sh_type == SHT_SYMTAB)
1377 m = sizeof(ElfW(Sym));
1378 else if (s->sh_type == SHT_RELX)
1379 m = sizeof(ElfW_Rel);
1380 else
1381 m = 16;
1383 fprintf(f, "%-8s", "offset");
1384 for (i = 0; i < m; ++i)
1385 fprintf(f, " %02x", i);
1386 n = 56;
1388 if (s->sh_type == SHT_SYMTAB || s->sh_type == SHT_RELX) {
1389 const char *fields1[] = {
1390 "name",
1391 "value",
1392 "size",
1393 "bind",
1394 "type",
1395 "other",
1396 "shndx",
1397 NULL
1400 const char *fields2[] = {
1401 "offs",
1402 "type",
1403 "symb",
1404 NULL
1407 const char **p;
1409 if (s->sh_type == SHT_SYMTAB)
1410 p = fields1, n = 106;
1411 else
1412 p = fields2, n = 58;
1414 for (i = 0; p[i]; ++i)
1415 fprintf(f, "%6s", p[i]);
1416 fprintf(f, " symbol");
1419 fprintf(f, "\n");
1420 for (i = 0; i < n; ++i)
1421 fprintf(f, "-");
1422 fprintf(f, "\n");
1424 for (i = 0; i < l;)
1426 fprintf(f, "%08X", i);
1427 for (n = 0; n < m; ++n) {
1428 if (n + i < l)
1429 fprintf(f, " %02X", p[i + n]);
1430 else
1431 fprintf(f, " ");
1434 if (s->sh_type == SHT_SYMTAB) {
1435 ElfW(Sym) *sym = (ElfW(Sym) *) (p + i);
1436 const char *name = s->link->data + sym->st_name;
1437 fprintf(f, " %04X %04X %04X %02X %02X %02X %04X \"%s\"",
1438 (unsigned)sym->st_name,
1439 (unsigned)sym->st_value,
1440 (unsigned)sym->st_size,
1441 (unsigned)ELFW(ST_BIND)(sym->st_info),
1442 (unsigned)ELFW(ST_TYPE)(sym->st_info),
1443 (unsigned)sym->st_other,
1444 (unsigned)sym->st_shndx,
1445 name);
1447 } else if (s->sh_type == SHT_RELX) {
1448 ElfW_Rel *rel = (ElfW_Rel *) (p + i);
1449 ElfW(Sym) *sym =
1450 (ElfW(Sym) *) s->link->data + ELFW(R_SYM)(rel->r_info);
1451 const char *name = s->link->link->data + sym->st_name;
1452 fprintf(f, " %04X %02X %04X \"%s\"",
1453 (unsigned)rel->r_offset,
1454 (unsigned)ELFW(R_TYPE)(rel->r_info),
1455 (unsigned)ELFW(R_SYM)(rel->r_info),
1456 name);
1457 } else {
1458 fprintf(f, " ");
1459 for (n = 0; n < m; ++n) {
1460 if (n + i < l) {
1461 b = p[i + n];
1462 if (b < 32 || b >= 127)
1463 b = '.';
1464 fprintf(f, "%c", b);
1468 i += m;
1469 fprintf(f, "\n");
1471 fprintf(f, "\n\n");
1474 static void pe_print_sections(TCCState *s1, const char *fname)
1476 Section *s;
1477 FILE *f;
1478 int i;
1479 f = fopen(fname, "w");
1480 for (i = 1; i < s1->nb_sections; ++i) {
1481 s = s1->sections[i];
1482 pe_print_section(f, s);
1484 pe_print_section(f, s1->dynsymtab_section);
1485 fclose(f);
1487 #endif
1489 /* ------------------------------------------------------------- */
1490 /* helper function for load/store to insert one more indirection */
1492 #if defined TCC_TARGET_I386 || defined TCC_TARGET_X86_64
1493 ST_FUNC SValue *pe_getimport(SValue *sv, SValue *v2)
1495 int r2;
1496 if ((sv->r & (VT_VALMASK|VT_SYM)) != (VT_CONST|VT_SYM) || (sv->r2 != VT_CONST))
1497 return sv;
1498 if (!sv->sym->a.dllimport)
1499 return sv;
1500 // printf("import %04x %04x %04x %s\n", sv->type.t, sv->sym->type.t, sv->r, get_tok_str(sv->sym->v, NULL));
1501 memset(v2, 0, sizeof *v2);
1502 v2->type.t = VT_PTR;
1503 v2->r = VT_CONST | VT_SYM | VT_LVAL;
1504 v2->sym = sv->sym;
1506 r2 = get_reg(RC_INT);
1507 load(r2, v2);
1508 v2->r = r2;
1509 if ((uint32_t)sv->c.i) {
1510 vpushv(v2);
1511 vpushi(sv->c.i);
1512 gen_opi('+');
1513 *v2 = *vtop--;
1515 v2->type.t = sv->type.t;
1516 v2->r |= sv->r & VT_LVAL;
1517 return v2;
1519 #endif
1521 ST_FUNC int pe_putimport(TCCState *s1, int dllindex, const char *name, addr_t value)
1523 return set_elf_sym(
1524 s1->dynsymtab_section,
1525 value,
1526 dllindex, /* st_size */
1527 ELFW(ST_INFO)(STB_GLOBAL, STT_NOTYPE),
1529 value ? SHN_ABS : SHN_UNDEF,
1530 name
1534 static int read_mem(int fd, unsigned offset, void *buffer, unsigned len)
1536 lseek(fd, offset, SEEK_SET);
1537 return len == read(fd, buffer, len);
1540 /* ------------------------------------------------------------- */
1542 static int get_dllexports(int fd, char **pp)
1544 int l, i, n, n0, ret;
1545 char *p;
1547 IMAGE_SECTION_HEADER ish;
1548 IMAGE_EXPORT_DIRECTORY ied;
1549 IMAGE_DOS_HEADER dh;
1550 IMAGE_FILE_HEADER ih;
1551 DWORD sig, ref, addr, ptr, namep;
1553 int pef_hdroffset, opt_hdroffset, sec_hdroffset;
1555 n = n0 = 0;
1556 p = NULL;
1557 ret = 1;
1558 if (!read_mem(fd, 0, &dh, sizeof dh))
1559 goto the_end;
1560 if (!read_mem(fd, dh.e_lfanew, &sig, sizeof sig))
1561 goto the_end;
1562 if (sig != 0x00004550)
1563 goto the_end;
1564 pef_hdroffset = dh.e_lfanew + sizeof sig;
1565 if (!read_mem(fd, pef_hdroffset, &ih, sizeof ih))
1566 goto the_end;
1567 opt_hdroffset = pef_hdroffset + sizeof ih;
1568 if (ih.Machine == 0x014C) {
1569 IMAGE_OPTIONAL_HEADER32 oh;
1570 sec_hdroffset = opt_hdroffset + sizeof oh;
1571 if (!read_mem(fd, opt_hdroffset, &oh, sizeof oh))
1572 goto the_end;
1573 if (IMAGE_DIRECTORY_ENTRY_EXPORT >= oh.NumberOfRvaAndSizes)
1574 goto the_end_0;
1575 addr = oh.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress;
1576 } else if (ih.Machine == 0x8664) {
1577 IMAGE_OPTIONAL_HEADER64 oh;
1578 sec_hdroffset = opt_hdroffset + sizeof oh;
1579 if (!read_mem(fd, opt_hdroffset, &oh, sizeof oh))
1580 goto the_end;
1581 if (IMAGE_DIRECTORY_ENTRY_EXPORT >= oh.NumberOfRvaAndSizes)
1582 goto the_end_0;
1583 addr = oh.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress;
1584 } else
1585 goto the_end;
1587 //printf("addr: %08x\n", addr);
1588 for (i = 0; i < ih.NumberOfSections; ++i) {
1589 if (!read_mem(fd, sec_hdroffset + i * sizeof ish, &ish, sizeof ish))
1590 goto the_end;
1591 //printf("vaddr: %08x\n", ish.VirtualAddress);
1592 if (addr >= ish.VirtualAddress && addr < ish.VirtualAddress + ish.SizeOfRawData)
1593 goto found;
1595 goto the_end_0;
1597 found:
1598 ref = ish.VirtualAddress - ish.PointerToRawData;
1599 if (!read_mem(fd, addr - ref, &ied, sizeof ied))
1600 goto the_end;
1602 namep = ied.AddressOfNames - ref;
1603 for (i = 0; i < ied.NumberOfNames; ++i) {
1604 if (!read_mem(fd, namep, &ptr, sizeof ptr))
1605 goto the_end;
1606 namep += sizeof ptr;
1607 for (l = 0;;) {
1608 if (n+1 >= n0)
1609 p = tcc_realloc(p, n0 = n0 ? n0 * 2 : 256);
1610 if (!read_mem(fd, ptr - ref + l++, p + n, 1)) {
1611 tcc_free(p), p = NULL;
1612 goto the_end;
1614 if (p[n++] == 0)
1615 break;
1618 if (p)
1619 p[n] = 0;
1620 the_end_0:
1621 ret = 0;
1622 the_end:
1623 *pp = p;
1624 return ret;
1627 /* -------------------------------------------------------------
1628 * This is for compiled windows resources in 'coff' format
1629 * as generated by 'windres.exe -O coff ...'.
1632 static int pe_load_res(TCCState *s1, int fd)
1634 struct pe_rsrc_header hdr;
1635 Section *rsrc_section;
1636 int i, ret = -1, sym_index;
1637 BYTE *ptr;
1638 unsigned offs;
1640 if (!read_mem(fd, 0, &hdr, sizeof hdr))
1641 goto quit;
1643 if (hdr.filehdr.Machine != IMAGE_FILE_MACHINE
1644 || hdr.filehdr.NumberOfSections != 1
1645 || strcmp((char*)hdr.sectionhdr.Name, ".rsrc") != 0)
1646 goto quit;
1648 rsrc_section = new_section(s1, ".rsrc", SHT_PROGBITS, SHF_ALLOC);
1649 ptr = section_ptr_add(rsrc_section, hdr.sectionhdr.SizeOfRawData);
1650 offs = hdr.sectionhdr.PointerToRawData;
1651 if (!read_mem(fd, offs, ptr, hdr.sectionhdr.SizeOfRawData))
1652 goto quit;
1653 offs = hdr.sectionhdr.PointerToRelocations;
1654 sym_index = put_elf_sym(symtab_section, 0, 0, 0, 0, rsrc_section->sh_num, ".rsrc");
1655 for (i = 0; i < hdr.sectionhdr.NumberOfRelocations; ++i) {
1656 struct pe_rsrc_reloc rel;
1657 if (!read_mem(fd, offs, &rel, sizeof rel))
1658 goto quit;
1659 // printf("rsrc_reloc: %x %x %x\n", rel.offset, rel.size, rel.type);
1660 if (rel.type != RSRC_RELTYPE)
1661 goto quit;
1662 put_elf_reloc(symtab_section, rsrc_section,
1663 rel.offset, R_XXX_RELATIVE, sym_index);
1664 offs += sizeof rel;
1666 ret = 0;
1667 quit:
1668 return ret;
1671 /* ------------------------------------------------------------- */
1673 static char *trimfront(char *p)
1675 while ((unsigned char)*p <= ' ' && *p && *p != '\n')
1676 ++p;
1677 return p;
1681 static char *trimback(char *a, char *e)
1683 while (e > a && (unsigned char)e[-1] <= ' ')
1684 --e;
1685 *e = 0;;
1686 return a;
1689 static char *get_token(char **s, char *f)
1691 char *p = *s, *e;
1692 p = e = trimfront(p);
1693 while ((unsigned char)*e > ' ')
1694 ++e;
1695 *s = trimfront(e);
1696 *f = **s; *e = 0;
1697 return p;
1700 static int pe_load_def(TCCState *s1, int fd)
1702 int state = 0, ret = -1, dllindex = 0, ord;
1703 char dllname[80], *buf, *line, *p, *x, next;
1705 buf = tcc_load_text(fd);
1706 for (line = buf;; ++line) {
1707 p = get_token(&line, &next);
1708 if (!(*p && *p != ';'))
1709 goto skip;
1710 switch (state) {
1711 case 0:
1712 if (0 != stricmp(p, "LIBRARY") || next == '\n')
1713 goto quit;
1714 pstrcpy(dllname, sizeof dllname, get_token(&line, &next));
1715 ++state;
1716 break;
1717 case 1:
1718 if (0 != stricmp(p, "EXPORTS"))
1719 goto quit;
1720 ++state;
1721 break;
1722 case 2:
1723 dllindex = tcc_add_dllref(s1, dllname, 0)->index;
1724 ++state;
1725 /* fall through */
1726 default:
1727 /* get ordinal and will store in sym->st_value */
1728 ord = 0;
1729 if (next == '@') {
1730 x = get_token(&line, &next);
1731 ord = (int)strtol(x + 1, &x, 10);
1733 //printf("token %s ; %s : %d\n", dllname, p, ord);
1734 pe_putimport(s1, dllindex, p, ord);
1735 break;
1737 skip:
1738 while ((unsigned char)next > ' ')
1739 get_token(&line, &next);
1740 if (next != '\n')
1741 break;
1743 ret = 0;
1744 quit:
1745 tcc_free(buf);
1746 return ret;
1749 /* ------------------------------------------------------------- */
1751 static int pe_load_dll(TCCState *s1, int fd, const char *filename)
1753 char *p, *q;
1754 int index, ret;
1756 ret = get_dllexports(fd, &p);
1757 if (ret) {
1758 return -1;
1759 } else if (p) {
1760 index = tcc_add_dllref(s1, filename, 0)->index;
1761 for (q = p; *q; q += 1 + strlen(q))
1762 pe_putimport(s1, index, q, 0);
1763 tcc_free(p);
1765 return 0;
1768 ST_FUNC int pe_load_file(struct TCCState *s1, int fd, const char *filename)
1770 int ret = -1;
1771 char buf[10];
1772 if (0 == strcmp(tcc_fileextension(filename), ".def"))
1773 ret = pe_load_def(s1, fd);
1774 else if (pe_load_res(s1, fd) == 0)
1775 ret = 0;
1776 else if (read_mem(fd, 0, buf, 4) && 0 == memcmp(buf, "MZ", 2))
1777 ret = pe_load_dll(s1, fd, filename);
1778 return ret;
1781 PUB_FUNC int tcc_get_dllexports(const char *filename, char **pp)
1783 int ret, fd = open(filename, O_RDONLY | O_BINARY);
1784 if (fd < 0)
1785 return -1;
1786 ret = get_dllexports(fd, pp);
1787 close(fd);
1788 return ret;
1791 /* ------------------------------------------------------------- */
1792 #ifdef TCC_TARGET_X86_64
1793 static unsigned pe_add_uwwind_info(TCCState *s1)
1795 if (NULL == s1->uw_pdata) {
1796 s1->uw_pdata = find_section(s1, ".pdata");
1797 s1->uw_pdata->sh_addralign = 4;
1799 if (0 == s1->uw_sym)
1800 s1->uw_sym = put_elf_sym(symtab_section, 0, 0, 0, 0, text_section->sh_num, ".uw_base");
1801 if (0 == s1->uw_offs) {
1802 /* As our functions all have the same stackframe, we use one entry for all */
1803 static const unsigned char uw_info[] = {
1804 0x01, // UBYTE: 3 Version , UBYTE: 5 Flags
1805 0x04, // UBYTE Size of prolog
1806 0x02, // UBYTE Count of unwind codes
1807 0x05, // UBYTE: 4 Frame Register (rbp), UBYTE: 4 Frame Register offset (scaled)
1808 // USHORT * n Unwind codes array
1809 // 0x0b, 0x01, 0xff, 0xff, // stack size
1810 0x04, 0x03, // set frame ptr (mov rsp -> rbp)
1811 0x01, 0x50 // push reg (rbp)
1814 Section *s = text_section;
1815 unsigned char *p;
1817 section_ptr_add(s, -s->data_offset & 3); /* align */
1818 s1->uw_offs = s->data_offset;
1819 p = section_ptr_add(s, sizeof uw_info);
1820 memcpy(p, uw_info, sizeof uw_info);
1823 return s1->uw_offs;
1826 ST_FUNC void pe_add_unwind_data(unsigned start, unsigned end, unsigned stack)
1828 TCCState *s1 = tcc_state;
1829 Section *pd;
1830 unsigned o, n, d;
1831 struct /* _RUNTIME_FUNCTION */ {
1832 DWORD BeginAddress;
1833 DWORD EndAddress;
1834 DWORD UnwindData;
1835 } *p;
1837 d = pe_add_uwwind_info(s1);
1838 pd = s1->uw_pdata;
1839 o = pd->data_offset;
1840 p = section_ptr_add(pd, sizeof *p);
1842 /* record this function */
1843 p->BeginAddress = start;
1844 p->EndAddress = end;
1845 p->UnwindData = d;
1847 /* put relocations on it */
1848 for (n = o + sizeof *p; o < n; o += sizeof p->BeginAddress)
1849 put_elf_reloc(symtab_section, pd, o, R_XXX_RELATIVE, s1->uw_sym);
1851 #endif
1852 /* ------------------------------------------------------------- */
1853 #ifdef TCC_TARGET_X86_64
1854 #define PE_STDSYM(n,s) n
1855 #else
1856 #define PE_STDSYM(n,s) "_" n s
1857 #endif
1859 static void pe_add_runtime(TCCState *s1, struct pe_info *pe)
1861 const char *start_symbol;
1862 int pe_type;
1864 if (TCC_OUTPUT_DLL == s1->output_type) {
1865 pe_type = PE_DLL;
1866 start_symbol = PE_STDSYM("__dllstart","@12");
1867 } else {
1868 const char *run_symbol;
1869 if (find_elf_sym(symtab_section, PE_STDSYM("WinMain","@16"))) {
1870 start_symbol = "__winstart";
1871 run_symbol = "__runwinmain";
1872 pe_type = PE_GUI;
1873 } else if (find_elf_sym(symtab_section, PE_STDSYM("wWinMain","@16"))) {
1874 start_symbol = "__wwinstart";
1875 run_symbol = "__runwwinmain";
1876 pe_type = PE_GUI;
1877 } else if (find_elf_sym(symtab_section, "wmain")) {
1878 start_symbol = "__wstart";
1879 run_symbol = "__runwmain";
1880 pe_type = PE_EXE;
1881 } else {
1882 start_symbol = "__start";
1883 run_symbol = "__runmain";
1884 pe_type = PE_EXE;
1887 if (TCC_OUTPUT_MEMORY == s1->output_type)
1888 start_symbol = run_symbol;
1891 pe->start_symbol = start_symbol + 1;
1892 if (!s1->leading_underscore || strchr(start_symbol, '@'))
1893 ++start_symbol;
1895 #ifdef CONFIG_TCC_BACKTRACE
1896 if (s1->do_backtrace) {
1897 #ifdef CONFIG_TCC_BCHECK
1898 if (s1->do_bounds_check && s1->output_type != TCC_OUTPUT_DLL)
1899 tcc_add_support(s1, "bcheck.o");
1900 #endif
1901 if (s1->output_type == TCC_OUTPUT_EXE)
1902 tcc_add_support(s1, "bt-exe.o");
1903 if (s1->output_type == TCC_OUTPUT_DLL)
1904 tcc_add_support(s1, "bt-dll.o");
1905 if (s1->output_type != TCC_OUTPUT_DLL)
1906 tcc_add_support(s1, "bt-log.o");
1907 if (s1->output_type != TCC_OUTPUT_MEMORY)
1908 tcc_add_btstub(s1);
1910 #endif
1912 /* grab the startup code from libtcc1.a */
1913 #ifdef TCC_IS_NATIVE
1914 if (TCC_OUTPUT_MEMORY != s1->output_type || s1->runtime_main)
1915 #endif
1916 set_global_sym(s1, start_symbol, NULL, 0);
1918 if (0 == s1->nostdlib) {
1919 static const char * const libs[] = {
1920 "msvcrt", "kernel32", "", "user32", "gdi32", NULL
1922 const char * const *pp, *p;
1923 if (TCC_LIBTCC1[0])
1924 tcc_add_support(s1, TCC_LIBTCC1);
1925 for (pp = libs; 0 != (p = *pp); ++pp) {
1926 if (*p)
1927 tcc_add_library_err(s1, p);
1928 else if (PE_DLL != pe_type && PE_GUI != pe_type)
1929 break;
1933 /* need this for 'tccelf.c:relocate_sections()' */
1934 if (TCC_OUTPUT_DLL == s1->output_type)
1935 s1->output_type = TCC_OUTPUT_EXE;
1936 if (TCC_OUTPUT_MEMORY == s1->output_type)
1937 pe_type = PE_RUN;
1938 pe->type = pe_type;
1941 static void pe_set_options(TCCState * s1, struct pe_info *pe)
1943 if (PE_DLL == pe->type) {
1944 /* XXX: check if is correct for arm-pe target */
1945 pe->imagebase = 0x10000000;
1946 } else {
1947 #if defined(TCC_TARGET_ARM)
1948 pe->imagebase = 0x00010000;
1949 #else
1950 pe->imagebase = 0x00400000;
1951 #endif
1954 #if defined(TCC_TARGET_ARM)
1955 /* we use "console" subsystem by default */
1956 pe->subsystem = 9;
1957 #else
1958 if (PE_DLL == pe->type || PE_GUI == pe->type)
1959 pe->subsystem = 2;
1960 else
1961 pe->subsystem = 3;
1962 #endif
1963 /* Allow override via -Wl,-subsystem=... option */
1964 if (s1->pe_subsystem != 0)
1965 pe->subsystem = s1->pe_subsystem;
1967 /* set default file/section alignment */
1968 if (pe->subsystem == 1) {
1969 pe->section_align = 0x20;
1970 pe->file_align = 0x20;
1971 } else {
1972 pe->section_align = 0x1000;
1973 pe->file_align = 0x200;
1976 if (s1->section_align != 0)
1977 pe->section_align = s1->section_align;
1978 if (s1->pe_file_align != 0)
1979 pe->file_align = s1->pe_file_align;
1981 if ((pe->subsystem >= 10) && (pe->subsystem <= 12))
1982 pe->imagebase = 0;
1984 if (s1->has_text_addr)
1985 pe->imagebase = s1->text_addr;
1988 ST_FUNC int pe_output_file(TCCState *s1, const char *filename)
1990 struct pe_info pe;
1992 memset(&pe, 0, sizeof pe);
1993 pe.filename = filename;
1994 pe.s1 = s1;
1995 s1->filetype = 0;
1997 #ifdef CONFIG_TCC_BCHECK
1998 tcc_add_bcheck(s1);
1999 #endif
2000 tcc_add_pragma_libs(s1);
2001 pe_add_runtime(s1, &pe);
2002 resolve_common_syms(s1);
2003 pe_set_options(s1, &pe);
2004 pe_check_symbols(&pe);
2006 if (s1->nb_errors)
2008 else if (filename) {
2009 pe_assign_addresses(&pe);
2010 relocate_syms(s1, s1->symtab, 0);
2011 s1->pe_imagebase = pe.imagebase;
2012 relocate_sections(s1);
2013 pe.start_addr = (DWORD)
2014 (get_sym_addr(s1, pe.start_symbol, 1, 1) - pe.imagebase);
2015 if (0 == s1->nb_errors)
2016 pe_write(&pe);
2017 dynarray_reset(&pe.sec_info, &pe.sec_count);
2018 } else {
2019 #ifdef TCC_IS_NATIVE
2020 pe.thunk = data_section;
2021 pe_build_imports(&pe);
2022 s1->runtime_main = pe.start_symbol;
2023 #ifdef TCC_TARGET_X86_64
2024 s1->uw_pdata = find_section(s1, ".pdata");
2025 #endif
2026 #endif
2028 pe_free_imports(&pe);
2029 #if PE_PRINT_SECTIONS
2030 if (s1->g_debug & 8)
2031 pe_print_sections(s1, "tcc.log");
2032 #endif
2033 return s1->nb_errors ? -1 : 0;
2036 /* ------------------------------------------------------------- */