Fix include SHT_NOTE sections everywhere
[tinycc/self_contained.git] / tccpe.c
blob3f5965fdcbc5bb1659f539db73d9edadf1c1afbd
1 /*
2 * TCCPE.C - PE file output for the Tiny C Compiler
4 * Copyright (c) 2005-2007 grischka
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
21 #include "tcc.h"
23 #define PE_MERGE_DATA
24 /* #define PE_PRINT_SECTIONS */
26 #ifndef _WIN32
27 #define stricmp strcasecmp
28 #define strnicmp strncasecmp
29 #include <sys/stat.h> /* chmod() */
30 #endif
32 #ifdef TCC_TARGET_X86_64
33 # define ADDR3264 ULONGLONG
34 # define PE_IMAGE_REL IMAGE_REL_BASED_DIR64
35 # define REL_TYPE_DIRECT R_X86_64_64
36 # define R_XXX_THUNKFIX R_X86_64_PC32
37 # define R_XXX_RELATIVE R_X86_64_RELATIVE
38 # define 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_data ,
298 sec_bss ,
299 sec_idata ,
300 sec_pdata ,
301 sec_other ,
302 sec_rsrc ,
303 sec_stab ,
304 sec_stabstr ,
305 sec_reloc ,
306 sec_last
309 #if 0
310 static const DWORD pe_sec_flags[] = {
311 0x60000020, /* ".text" , */
312 0xC0000040, /* ".data" , */
313 0xC0000080, /* ".bss" , */
314 0x40000040, /* ".idata" , */
315 0x40000040, /* ".pdata" , */
316 0xE0000060, /* < other > , */
317 0x40000040, /* ".rsrc" , */
318 0x42000802, /* ".stab" , */
319 0x42000040, /* ".reloc" , */
321 #endif
323 struct section_info {
324 int cls;
325 char name[32];
326 DWORD sh_addr;
327 DWORD sh_size;
328 DWORD pe_flags;
329 Section *sec;
330 DWORD data_size;
331 IMAGE_SECTION_HEADER ish;
334 struct import_symbol {
335 int sym_index;
336 int iat_index;
337 int thk_offset;
340 struct pe_import_info {
341 int dll_index;
342 int sym_count;
343 struct import_symbol **symbols;
346 struct pe_info {
347 TCCState *s1;
348 Section *reloc;
349 Section *thunk;
350 const char *filename;
351 int type;
352 DWORD sizeofheaders;
353 ADDR3264 imagebase;
354 const char *start_symbol;
355 DWORD start_addr;
356 DWORD imp_offs;
357 DWORD imp_size;
358 DWORD iat_offs;
359 DWORD iat_size;
360 DWORD exp_offs;
361 DWORD exp_size;
362 int subsystem;
363 DWORD section_align;
364 DWORD file_align;
365 struct section_info **sec_info;
366 int sec_count;
367 struct pe_import_info **imp_info;
368 int imp_count;
371 #define PE_NUL 0
372 #define PE_DLL 1
373 #define PE_GUI 2
374 #define PE_EXE 3
375 #define PE_RUN 4
377 /* --------------------------------------------*/
379 static const char *pe_export_name(TCCState *s1, ElfW(Sym) *sym)
381 const char *name = (char*)symtab_section->link->data + sym->st_name;
382 if (s1->leading_underscore && name[0] == '_' && !(sym->st_other & ST_PE_STDCALL))
383 return name + 1;
384 return name;
387 static int pe_find_import(TCCState * s1, ElfW(Sym) *sym)
389 char buffer[200];
390 const char *s, *p;
391 int sym_index = 0, n = 0;
392 int a, err = 0;
394 do {
395 s = pe_export_name(s1, sym);
396 a = 0;
397 if (n) {
398 /* second try: */
399 if (sym->st_other & ST_PE_STDCALL) {
400 /* try w/0 stdcall deco (windows API convention) */
401 p = strrchr(s, '@');
402 if (!p || s[0] != '_')
403 break;
404 strcpy(buffer, s+1)[p-s-1] = 0;
405 } else if (s[0] != '_') { /* try non-ansi function */
406 buffer[0] = '_', strcpy(buffer + 1, s);
407 } else if (0 == memcmp(s, "__imp_", 6)) { /* mingw 2.0 */
408 strcpy(buffer, s + 6), a = 1;
409 } else if (0 == memcmp(s, "_imp__", 6)) { /* mingw 3.7 */
410 strcpy(buffer, s + 6), a = 1;
411 } else {
412 continue;
414 s = buffer;
416 sym_index = find_elf_sym(s1->dynsymtab_section, s);
417 // printf("find (%d) %d %s\n", n, sym_index, s);
418 if (sym_index
419 && ELFW(ST_TYPE)(sym->st_info) == STT_OBJECT
420 && 0 == (sym->st_other & ST_PE_IMPORT)
421 && 0 == a
422 ) err = -1, sym_index = 0;
423 } while (0 == sym_index && ++n < 2);
424 return n == 2 ? err : sym_index;
427 /*----------------------------------------------------------------------------*/
429 static int dynarray_assoc(void **pp, int n, int key)
431 int i;
432 for (i = 0; i < n; ++i, ++pp)
433 if (key == **(int **) pp)
434 return i;
435 return -1;
438 static DWORD umin(DWORD a, DWORD b)
440 return a < b ? a : b;
443 static DWORD umax(DWORD a, DWORD b)
445 return a < b ? b : a;
448 static DWORD pe_file_align(struct pe_info *pe, DWORD n)
450 return (n + (pe->file_align - 1)) & ~(pe->file_align - 1);
453 static DWORD pe_virtual_align(struct pe_info *pe, DWORD n)
455 return (n + (pe->section_align - 1)) & ~(pe->section_align - 1);
458 static void pe_align_section(Section *s, int a)
460 int i = s->data_offset & (a-1);
461 if (i)
462 section_ptr_add(s, a - i);
465 static void pe_set_datadir(struct pe_header *hdr, int dir, DWORD addr, DWORD size)
467 hdr->opthdr.DataDirectory[dir].VirtualAddress = addr;
468 hdr->opthdr.DataDirectory[dir].Size = size;
471 struct pe_file {
472 FILE *op;
473 DWORD sum;
474 unsigned pos;
477 static int pe_fwrite(void *data, int len, struct pe_file *pf)
479 WORD *p = data;
480 DWORD sum;
481 int ret, i;
482 pf->pos += (ret = fwrite(data, 1, len, pf->op));
483 sum = pf->sum;
484 for (i = len; i > 0; i -= 2) {
485 sum += (i >= 2) ? *p++ : *(BYTE*)p;
486 sum = (sum + (sum >> 16)) & 0xFFFF;
488 pf->sum = sum;
489 return len == ret ? 0 : -1;
492 static void pe_fpad(struct pe_file *pf, DWORD new_pos)
494 char buf[256];
495 int n, diff = new_pos - pf->pos;
496 memset(buf, 0, sizeof buf);
497 while (diff > 0) {
498 diff -= n = umin(diff, sizeof buf);
499 fwrite(buf, n, 1, pf->op);
501 pf->pos = new_pos;
504 /*----------------------------------------------------------------------------*/
505 static int pe_write(struct pe_info *pe)
507 static const struct pe_header pe_template = {
509 /* IMAGE_DOS_HEADER doshdr */
510 0x5A4D, /*WORD e_magic; Magic number */
511 0x0090, /*WORD e_cblp; Bytes on last page of file */
512 0x0003, /*WORD e_cp; Pages in file */
513 0x0000, /*WORD e_crlc; Relocations */
515 0x0004, /*WORD e_cparhdr; Size of header in paragraphs */
516 0x0000, /*WORD e_minalloc; Minimum extra paragraphs needed */
517 0xFFFF, /*WORD e_maxalloc; Maximum extra paragraphs needed */
518 0x0000, /*WORD e_ss; Initial (relative) SS value */
520 0x00B8, /*WORD e_sp; Initial SP value */
521 0x0000, /*WORD e_csum; Checksum */
522 0x0000, /*WORD e_ip; Initial IP value */
523 0x0000, /*WORD e_cs; Initial (relative) CS value */
524 0x0040, /*WORD e_lfarlc; File address of relocation table */
525 0x0000, /*WORD e_ovno; Overlay number */
526 {0,0,0,0}, /*WORD e_res[4]; Reserved words */
527 0x0000, /*WORD e_oemid; OEM identifier (for e_oeminfo) */
528 0x0000, /*WORD e_oeminfo; OEM information; e_oemid specific */
529 {0,0,0,0,0,0,0,0,0,0}, /*WORD e_res2[10]; Reserved words */
530 0x00000080 /*DWORD e_lfanew; File address of new exe header */
532 /* BYTE dosstub[0x40] */
533 /* 14 code bytes + "This program cannot be run in DOS mode.\r\r\n$" + 6 * 0x00 */
534 0x0e,0x1f,0xba,0x0e,0x00,0xb4,0x09,0xcd,0x21,0xb8,0x01,0x4c,0xcd,0x21,0x54,0x68,
535 0x69,0x73,0x20,0x70,0x72,0x6f,0x67,0x72,0x61,0x6d,0x20,0x63,0x61,0x6e,0x6e,0x6f,
536 0x74,0x20,0x62,0x65,0x20,0x72,0x75,0x6e,0x20,0x69,0x6e,0x20,0x44,0x4f,0x53,0x20,
537 0x6d,0x6f,0x64,0x65,0x2e,0x0d,0x0d,0x0a,0x24,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
539 0x00004550, /* DWORD nt_sig = IMAGE_NT_SIGNATURE */
541 /* IMAGE_FILE_HEADER filehdr */
542 IMAGE_FILE_MACHINE, /*WORD Machine; */
543 0x0003, /*WORD NumberOfSections; */
544 0x00000000, /*DWORD TimeDateStamp; */
545 0x00000000, /*DWORD PointerToSymbolTable; */
546 0x00000000, /*DWORD NumberOfSymbols; */
547 #if defined(TCC_TARGET_X86_64)
548 0x00F0, /*WORD SizeOfOptionalHeader; */
549 0x022F /*WORD Characteristics; */
550 #define CHARACTERISTICS_DLL 0x222E
551 #elif defined(TCC_TARGET_I386)
552 0x00E0, /*WORD SizeOfOptionalHeader; */
553 0x030F /*WORD Characteristics; */
554 #define CHARACTERISTICS_DLL 0x230E
555 #elif defined(TCC_TARGET_ARM)
556 0x00E0, /*WORD SizeOfOptionalHeader; */
557 0x010F, /*WORD Characteristics; */
558 #define CHARACTERISTICS_DLL 0x230F
559 #endif
561 /* IMAGE_OPTIONAL_HEADER opthdr */
562 /* Standard fields. */
563 #ifdef TCC_TARGET_X86_64
564 0x020B, /*WORD Magic; */
565 #else
566 0x010B, /*WORD Magic; */
567 #endif
568 0x06, /*BYTE MajorLinkerVersion; */
569 0x00, /*BYTE MinorLinkerVersion; */
570 0x00000000, /*DWORD SizeOfCode; */
571 0x00000000, /*DWORD SizeOfInitializedData; */
572 0x00000000, /*DWORD SizeOfUninitializedData; */
573 0x00000000, /*DWORD AddressOfEntryPoint; */
574 0x00000000, /*DWORD BaseOfCode; */
575 #ifndef TCC_TARGET_X86_64
576 0x00000000, /*DWORD BaseOfData; */
577 #endif
578 /* NT additional fields. */
579 #if defined(TCC_TARGET_ARM)
580 0x00100000, /*DWORD ImageBase; */
581 #else
582 0x00400000, /*DWORD ImageBase; */
583 #endif
584 0x00001000, /*DWORD SectionAlignment; */
585 0x00000200, /*DWORD FileAlignment; */
586 0x0004, /*WORD MajorOperatingSystemVersion; */
587 0x0000, /*WORD MinorOperatingSystemVersion; */
588 0x0000, /*WORD MajorImageVersion; */
589 0x0000, /*WORD MinorImageVersion; */
590 0x0004, /*WORD MajorSubsystemVersion; */
591 0x0000, /*WORD MinorSubsystemVersion; */
592 0x00000000, /*DWORD Win32VersionValue; */
593 0x00000000, /*DWORD SizeOfImage; */
594 0x00000200, /*DWORD SizeOfHeaders; */
595 0x00000000, /*DWORD CheckSum; */
596 0x0002, /*WORD Subsystem; */
597 0x0000, /*WORD DllCharacteristics; */
598 0x00100000, /*DWORD SizeOfStackReserve; */
599 0x00001000, /*DWORD SizeOfStackCommit; */
600 0x00100000, /*DWORD SizeOfHeapReserve; */
601 0x00001000, /*DWORD SizeOfHeapCommit; */
602 0x00000000, /*DWORD LoaderFlags; */
603 0x00000010, /*DWORD NumberOfRvaAndSizes; */
605 /* IMAGE_DATA_DIRECTORY DataDirectory[16]; */
606 {{0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0},
607 {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}}
610 struct pe_header pe_header = pe_template;
612 int i;
613 struct pe_file pf = {0};
614 DWORD file_offset;
615 struct section_info *si;
616 IMAGE_SECTION_HEADER *psh;
617 TCCState *s1 = pe->s1;
619 pf.op = fopen(pe->filename, "wb");
620 if (NULL == pf.op) {
621 tcc_error_noabort("could not write '%s': %s", pe->filename, strerror(errno));
622 return -1;
625 pe->sizeofheaders = pe_file_align(pe,
626 sizeof (struct pe_header)
627 + pe->sec_count * sizeof (IMAGE_SECTION_HEADER)
630 file_offset = pe->sizeofheaders;
632 if (2 == pe->s1->verbose)
633 printf("-------------------------------"
634 "\n virt file size section" "\n");
635 for (i = 0; i < pe->sec_count; ++i) {
636 DWORD addr, size;
637 const char *sh_name;
639 si = pe->sec_info[i];
640 sh_name = si->name;
641 addr = si->sh_addr - pe->imagebase;
642 size = si->sh_size;
643 psh = &si->ish;
645 if (2 == pe->s1->verbose)
646 printf("%6x %6x %6x %s\n",
647 (unsigned)addr, (unsigned)file_offset, (unsigned)size, sh_name);
649 switch (si->cls) {
650 case sec_text:
651 if (!pe_header.opthdr.BaseOfCode)
652 pe_header.opthdr.BaseOfCode = addr;
653 break;
655 case sec_data:
656 #ifndef TCC_TARGET_X86_64
657 if (!pe_header.opthdr.BaseOfData)
658 pe_header.opthdr.BaseOfData = addr;
659 #endif
660 break;
662 case sec_bss:
663 break;
665 case sec_reloc:
666 pe_set_datadir(&pe_header, IMAGE_DIRECTORY_ENTRY_BASERELOC, addr, size);
667 break;
669 case sec_rsrc:
670 pe_set_datadir(&pe_header, IMAGE_DIRECTORY_ENTRY_RESOURCE, addr, size);
671 break;
673 case sec_pdata:
674 pe_set_datadir(&pe_header, IMAGE_DIRECTORY_ENTRY_EXCEPTION, addr, size);
675 break;
678 if (pe->imp_size) {
679 pe_set_datadir(&pe_header, IMAGE_DIRECTORY_ENTRY_IMPORT,
680 pe->imp_offs, pe->imp_size);
681 pe_set_datadir(&pe_header, IMAGE_DIRECTORY_ENTRY_IAT,
682 pe->iat_offs, pe->iat_size);
684 if (pe->exp_size) {
685 pe_set_datadir(&pe_header, IMAGE_DIRECTORY_ENTRY_EXPORT,
686 pe->exp_offs, pe->exp_size);
689 memcpy(psh->Name, sh_name, umin(strlen(sh_name), sizeof psh->Name));
691 psh->Characteristics = si->pe_flags;
692 psh->VirtualAddress = addr;
693 psh->Misc.VirtualSize = size;
694 pe_header.opthdr.SizeOfImage =
695 umax(pe_virtual_align(pe, size + addr), pe_header.opthdr.SizeOfImage);
697 if (si->data_size) {
698 psh->PointerToRawData = file_offset;
699 file_offset = pe_file_align(pe, file_offset + si->data_size);
700 psh->SizeOfRawData = file_offset - psh->PointerToRawData;
701 if (si->cls == sec_text)
702 pe_header.opthdr.SizeOfCode += psh->SizeOfRawData;
703 else
704 pe_header.opthdr.SizeOfInitializedData += psh->SizeOfRawData;
708 //pe_header.filehdr.TimeDateStamp = time(NULL);
709 pe_header.filehdr.NumberOfSections = pe->sec_count;
710 pe_header.opthdr.AddressOfEntryPoint = pe->start_addr;
711 pe_header.opthdr.SizeOfHeaders = pe->sizeofheaders;
712 pe_header.opthdr.ImageBase = pe->imagebase;
713 pe_header.opthdr.Subsystem = pe->subsystem;
714 if (pe->s1->pe_stack_size)
715 pe_header.opthdr.SizeOfStackReserve = pe->s1->pe_stack_size;
716 if (PE_DLL == pe->type)
717 pe_header.filehdr.Characteristics = CHARACTERISTICS_DLL;
718 pe_header.filehdr.Characteristics |= pe->s1->pe_characteristics;
720 pe_fwrite(&pe_header, sizeof pe_header, &pf);
721 for (i = 0; i < pe->sec_count; ++i)
722 pe_fwrite(&pe->sec_info[i]->ish, sizeof(IMAGE_SECTION_HEADER), &pf);
724 file_offset = pe->sizeofheaders;
725 for (i = 0; i < pe->sec_count; ++i) {
726 Section *s;
727 si = pe->sec_info[i];
728 for (s = si->sec; s; s = s->prev) {
729 pe_fpad(&pf, file_offset);
730 pe_fwrite(s->data, s->data_offset, &pf);
731 if (s->prev)
732 file_offset += s->prev->sh_addr - s->sh_addr;
734 file_offset = si->ish.PointerToRawData + si->ish.SizeOfRawData;
735 pe_fpad(&pf, file_offset);
738 pf.sum += file_offset;
739 fseek(pf.op, offsetof(struct pe_header, opthdr.CheckSum), SEEK_SET);
740 pe_fwrite(&pf.sum, sizeof (DWORD), &pf);
742 fclose (pf.op);
743 #ifndef _WIN32
744 chmod(pe->filename, 0777);
745 #endif
747 if (2 == pe->s1->verbose)
748 printf("-------------------------------\n");
749 if (pe->s1->verbose)
750 printf("<- %s (%u bytes)\n", pe->filename, (unsigned)file_offset);
752 return 0;
755 /*----------------------------------------------------------------------------*/
757 static struct import_symbol *pe_add_import(struct pe_info *pe, int sym_index)
759 int i;
760 int dll_index;
761 struct pe_import_info *p;
762 struct import_symbol *s;
763 ElfW(Sym) *isym;
765 isym = (ElfW(Sym) *)pe->s1->dynsymtab_section->data + sym_index;
766 dll_index = isym->st_size;
768 i = dynarray_assoc ((void**)pe->imp_info, pe->imp_count, dll_index);
769 if (-1 != i) {
770 p = pe->imp_info[i];
771 goto found_dll;
773 p = tcc_mallocz(sizeof *p);
774 p->dll_index = dll_index;
775 dynarray_add(&pe->imp_info, &pe->imp_count, p);
777 found_dll:
778 i = dynarray_assoc ((void**)p->symbols, p->sym_count, sym_index);
779 if (-1 != i)
780 return p->symbols[i];
782 s = tcc_mallocz(sizeof *s);
783 dynarray_add(&p->symbols, &p->sym_count, s);
784 s->sym_index = sym_index;
785 return s;
788 void pe_free_imports(struct pe_info *pe)
790 int i;
791 for (i = 0; i < pe->imp_count; ++i) {
792 struct pe_import_info *p = pe->imp_info[i];
793 dynarray_reset(&p->symbols, &p->sym_count);
795 dynarray_reset(&pe->imp_info, &pe->imp_count);
798 /*----------------------------------------------------------------------------*/
799 static void pe_build_imports(struct pe_info *pe)
801 int thk_ptr, ent_ptr, dll_ptr, sym_cnt, i;
802 DWORD rva_base = pe->thunk->sh_addr - pe->imagebase;
803 int ndlls = pe->imp_count;
804 TCCState *s1 = pe->s1;
806 for (sym_cnt = i = 0; i < ndlls; ++i)
807 sym_cnt += pe->imp_info[i]->sym_count;
809 if (0 == sym_cnt)
810 return;
812 pe_align_section(pe->thunk, 16);
813 pe->imp_size = (ndlls + 1) * sizeof(IMAGE_IMPORT_DESCRIPTOR);
814 pe->iat_size = (sym_cnt + ndlls) * sizeof(ADDR3264);
815 dll_ptr = pe->thunk->data_offset;
816 thk_ptr = dll_ptr + pe->imp_size;
817 ent_ptr = thk_ptr + pe->iat_size;
818 pe->imp_offs = dll_ptr + rva_base;
819 pe->iat_offs = thk_ptr + rva_base;
820 section_ptr_add(pe->thunk, pe->imp_size + 2*pe->iat_size);
822 for (i = 0; i < pe->imp_count; ++i) {
823 IMAGE_IMPORT_DESCRIPTOR *hdr;
824 int k, n, dllindex;
825 ADDR3264 v;
826 struct pe_import_info *p = pe->imp_info[i];
827 const char *name;
828 DLLReference *dllref;
830 dllindex = p->dll_index;
831 if (dllindex)
832 name = tcc_basename((dllref = pe->s1->loaded_dlls[dllindex-1])->name);
833 else
834 name = "", dllref = NULL;
836 /* put the dll name into the import header */
837 v = put_elf_str(pe->thunk, name);
838 hdr = (IMAGE_IMPORT_DESCRIPTOR*)(pe->thunk->data + dll_ptr);
839 hdr->FirstThunk = thk_ptr + rva_base;
840 hdr->OriginalFirstThunk = ent_ptr + rva_base;
841 hdr->Name = v + rva_base;
843 for (k = 0, n = p->sym_count; k <= n; ++k) {
844 if (k < n) {
845 int iat_index = p->symbols[k]->iat_index;
846 int sym_index = p->symbols[k]->sym_index;
847 ElfW(Sym) *imp_sym = (ElfW(Sym) *)pe->s1->dynsymtab_section->data + sym_index;
848 ElfW(Sym) *org_sym = (ElfW(Sym) *)symtab_section->data + iat_index;
849 const char *name = (char*)pe->s1->dynsymtab_section->link->data + imp_sym->st_name;
850 int ordinal;
852 org_sym->st_value = thk_ptr;
853 org_sym->st_shndx = pe->thunk->sh_num;
855 if (dllref)
856 v = 0, ordinal = imp_sym->st_value; /* ordinal from pe_load_def */
857 else
858 ordinal = 0, v = imp_sym->st_value; /* address from tcc_add_symbol() */
860 #ifdef TCC_IS_NATIVE
861 if (pe->type == PE_RUN) {
862 if (dllref) {
863 if ( !dllref->handle )
864 dllref->handle = LoadLibrary(dllref->name);
865 v = (ADDR3264)GetProcAddress(dllref->handle, ordinal?(char*)0+ordinal:name);
867 if (!v)
868 tcc_error_noabort("could not resolve symbol '%s'", name);
869 } else
870 #endif
871 if (ordinal) {
872 v = ordinal | (ADDR3264)1 << (sizeof(ADDR3264)*8 - 1);
873 } else {
874 v = pe->thunk->data_offset + rva_base;
875 section_ptr_add(pe->thunk, sizeof(WORD)); /* hint, not used */
876 put_elf_str(pe->thunk, name);
879 } else {
880 v = 0; /* last entry is zero */
883 *(ADDR3264*)(pe->thunk->data+thk_ptr) =
884 *(ADDR3264*)(pe->thunk->data+ent_ptr) = v;
885 thk_ptr += sizeof (ADDR3264);
886 ent_ptr += sizeof (ADDR3264);
888 dll_ptr += sizeof(IMAGE_IMPORT_DESCRIPTOR);
892 /* ------------------------------------------------------------- */
894 struct pe_sort_sym
896 int index;
897 const char *name;
900 static int sym_cmp(const void *va, const void *vb)
902 const char *ca = (*(struct pe_sort_sym**)va)->name;
903 const char *cb = (*(struct pe_sort_sym**)vb)->name;
904 return strcmp(ca, cb);
907 static void pe_build_exports(struct pe_info *pe)
909 ElfW(Sym) *sym;
910 int sym_index, sym_end;
911 DWORD rva_base, base_o, func_o, name_o, ord_o, str_o;
912 IMAGE_EXPORT_DIRECTORY *hdr;
913 int sym_count, ord;
914 struct pe_sort_sym **sorted, *p;
915 TCCState *s1 = pe->s1;
917 FILE *op;
918 char buf[260];
919 const char *dllname;
920 const char *name;
922 rva_base = pe->thunk->sh_addr - pe->imagebase;
923 sym_count = 0, sorted = NULL, op = NULL;
925 sym_end = symtab_section->data_offset / sizeof(ElfW(Sym));
926 for (sym_index = 1; sym_index < sym_end; ++sym_index) {
927 sym = (ElfW(Sym)*)symtab_section->data + sym_index;
928 name = pe_export_name(pe->s1, sym);
929 if (sym->st_other & ST_PE_EXPORT) {
930 p = tcc_malloc(sizeof *p);
931 p->index = sym_index;
932 p->name = name;
933 dynarray_add(&sorted, &sym_count, p);
935 #if 0
936 if (sym->st_other & ST_PE_EXPORT)
937 printf("export: %s\n", name);
938 if (sym->st_other & ST_PE_STDCALL)
939 printf("stdcall: %s\n", name);
940 #endif
943 if (0 == sym_count)
944 return;
946 qsort (sorted, sym_count, sizeof *sorted, sym_cmp);
948 pe_align_section(pe->thunk, 16);
949 dllname = tcc_basename(pe->filename);
951 base_o = pe->thunk->data_offset;
952 func_o = base_o + sizeof(IMAGE_EXPORT_DIRECTORY);
953 name_o = func_o + sym_count * sizeof (DWORD);
954 ord_o = name_o + sym_count * sizeof (DWORD);
955 str_o = ord_o + sym_count * sizeof(WORD);
957 hdr = section_ptr_add(pe->thunk, str_o - base_o);
958 hdr->Characteristics = 0;
959 hdr->Base = 1;
960 hdr->NumberOfFunctions = sym_count;
961 hdr->NumberOfNames = sym_count;
962 hdr->AddressOfFunctions = func_o + rva_base;
963 hdr->AddressOfNames = name_o + rva_base;
964 hdr->AddressOfNameOrdinals = ord_o + rva_base;
965 hdr->Name = str_o + rva_base;
966 put_elf_str(pe->thunk, dllname);
968 #if 1
969 /* automatically write exports to <output-filename>.def */
970 pstrcpy(buf, sizeof buf, pe->filename);
971 strcpy(tcc_fileextension(buf), ".def");
972 op = fopen(buf, "wb");
973 if (NULL == op) {
974 tcc_error_noabort("could not create '%s': %s", buf, strerror(errno));
975 } else {
976 fprintf(op, "LIBRARY %s\n\nEXPORTS\n", dllname);
977 if (pe->s1->verbose)
978 printf("<- %s (%d symbol%s)\n", buf, sym_count, &"s"[sym_count < 2]);
980 #endif
982 for (ord = 0; ord < sym_count; ++ord)
984 p = sorted[ord], sym_index = p->index, name = p->name;
985 /* insert actual address later in relocate_section() */
986 put_elf_reloc(symtab_section, pe->thunk,
987 func_o, R_XXX_RELATIVE, sym_index);
988 *(DWORD*)(pe->thunk->data + name_o)
989 = pe->thunk->data_offset + rva_base;
990 *(WORD*)(pe->thunk->data + ord_o)
991 = ord;
992 put_elf_str(pe->thunk, name);
993 func_o += sizeof (DWORD);
994 name_o += sizeof (DWORD);
995 ord_o += sizeof (WORD);
996 if (op)
997 fprintf(op, "%s\n", name);
1000 pe->exp_offs = base_o + rva_base;
1001 pe->exp_size = pe->thunk->data_offset - base_o;
1002 dynarray_reset(&sorted, &sym_count);
1003 if (op)
1004 fclose(op);
1007 /* ------------------------------------------------------------- */
1008 static void pe_build_reloc (struct pe_info *pe)
1010 DWORD offset, block_ptr, sh_addr, addr;
1011 int count, i;
1012 ElfW_Rel *rel, *rel_end;
1013 Section *s = NULL, *sr;
1014 struct pe_reloc_header *hdr;
1016 sh_addr = offset = block_ptr = count = i = 0;
1017 rel = rel_end = NULL;
1019 for(;;) {
1020 if (rel < rel_end) {
1021 int type = ELFW(R_TYPE)(rel->r_info);
1022 addr = rel->r_offset + sh_addr;
1023 ++ rel;
1024 if (type != REL_TYPE_DIRECT)
1025 continue;
1026 if (count == 0) { /* new block */
1027 block_ptr = pe->reloc->data_offset;
1028 section_ptr_add(pe->reloc, sizeof(struct pe_reloc_header));
1029 offset = addr & 0xFFFFFFFF<<12;
1031 if ((addr -= offset) < (1<<12)) { /* one block spans 4k addresses */
1032 WORD *wp = section_ptr_add(pe->reloc, sizeof (WORD));
1033 *wp = addr | PE_IMAGE_REL<<12;
1034 ++count;
1035 continue;
1037 -- rel;
1039 } else if (s) {
1040 sr = s->reloc;
1041 if (sr) {
1042 rel = (ElfW_Rel *)sr->data;
1043 rel_end = (ElfW_Rel *)(sr->data + sr->data_offset);
1044 sh_addr = s->sh_addr;
1046 s = s->prev;
1047 continue;
1049 } else if (i < pe->sec_count) {
1050 s = pe->sec_info[i]->sec, ++i;
1051 continue;
1053 } else if (!count)
1054 break;
1056 /* fill the last block and ready for a new one */
1057 if (count & 1) /* align for DWORDS */
1058 section_ptr_add(pe->reloc, sizeof(WORD)), ++count;
1059 hdr = (struct pe_reloc_header *)(pe->reloc->data + block_ptr);
1060 hdr -> offset = offset - pe->imagebase;
1061 hdr -> size = count * sizeof(WORD) + sizeof(struct pe_reloc_header);
1062 count = 0;
1066 /* ------------------------------------------------------------- */
1067 static int pe_section_class(Section *s)
1069 int type, flags;
1070 const char *name;
1072 type = s->sh_type;
1073 flags = s->sh_flags;
1074 name = s->name;
1075 if (flags & SHF_ALLOC) {
1076 if (type == SHT_PROGBITS) {
1077 if (flags & SHF_EXECINSTR)
1078 return sec_text;
1079 if (flags & SHF_WRITE)
1080 return sec_data;
1081 if (0 == strcmp(name, ".rsrc"))
1082 return sec_rsrc;
1083 if (0 == strcmp(name, ".iedat"))
1084 return sec_idata;
1085 if (0 == strcmp(name, ".pdata"))
1086 return sec_pdata;
1087 } else if (type == SHT_NOBITS) {
1088 if (flags & SHF_WRITE)
1089 return sec_bss;
1091 } else {
1092 if (0 == strcmp(name, ".reloc"))
1093 return sec_reloc;
1095 if (0 == memcmp(name, ".stab", 5))
1096 return name[5] ? sec_stabstr : sec_stab;
1097 if (flags & SHF_ALLOC)
1098 return sec_other;
1099 return -1;
1102 static int pe_assign_addresses (struct pe_info *pe)
1104 int i, k, o, c;
1105 DWORD addr;
1106 int *section_order;
1107 struct section_info *si;
1108 Section *s;
1110 if (PE_DLL == pe->type)
1111 pe->reloc = new_section(pe->s1, ".reloc", SHT_PROGBITS, 0);
1112 // pe->thunk = new_section(pe->s1, ".iedat", SHT_PROGBITS, SHF_ALLOC);
1114 section_order = tcc_malloc(pe->s1->nb_sections * sizeof (int));
1115 for (o = k = 0 ; k < sec_last; ++k) {
1116 for (i = 1; i < pe->s1->nb_sections; ++i) {
1117 s = pe->s1->sections[i];
1118 if (k == pe_section_class(s))
1119 section_order[o++] = i;
1123 si = NULL;
1124 addr = pe->imagebase + 1;
1126 for (i = 0; i < o; ++i) {
1127 k = section_order[i];
1128 s = pe->s1->sections[k];
1129 c = pe_section_class(s);
1131 if ((c == sec_stab || c == sec_stabstr) && 0 == pe->s1->do_debug)
1132 continue;
1134 #ifdef PE_MERGE_DATA
1135 if (c == sec_bss)
1136 c = sec_data;
1137 #endif
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 (c == sec_data && NULL == pe->thunk)
1147 pe->thunk = s;
1149 if (s == pe->thunk) {
1150 pe_build_imports(pe);
1151 pe_build_exports(pe);
1153 if (s == pe->reloc)
1154 pe_build_reloc (pe);
1156 if (0 == s->data_offset)
1157 continue;
1159 if (si)
1160 goto add_section;
1162 si = tcc_mallocz(sizeof *si);
1163 dynarray_add(&pe->sec_info, &pe->sec_count, si);
1165 strcpy(si->name, s->name);
1166 si->cls = c;
1167 si->sh_addr = addr;
1169 si->pe_flags = IMAGE_SCN_MEM_READ;
1170 if (s->sh_flags & SHF_EXECINSTR)
1171 si->pe_flags |= IMAGE_SCN_MEM_EXECUTE | IMAGE_SCN_CNT_CODE;
1172 else if (s->sh_type == SHT_NOBITS)
1173 si->pe_flags |= IMAGE_SCN_CNT_UNINITIALIZED_DATA;
1174 else
1175 si->pe_flags |= IMAGE_SCN_CNT_INITIALIZED_DATA;
1176 if (s->sh_flags & SHF_WRITE)
1177 si->pe_flags |= IMAGE_SCN_MEM_WRITE;
1178 if (0 == (s->sh_flags & SHF_ALLOC))
1179 si->pe_flags |= IMAGE_SCN_MEM_DISCARDABLE;
1181 add_section:
1182 addr += s->data_offset;
1183 si->sh_size = addr - si->sh_addr;
1184 if (s->sh_type != SHT_NOBITS) {
1185 Section **ps = &si->sec;
1186 while (*ps)
1187 ps = &(*ps)->prev;
1188 *ps = s, s->prev = NULL;
1189 si->data_size = si->sh_size;
1191 //printf("%08x %05x %08x %s\n", si->sh_addr, si->sh_size, si->pe_flags, s->name);
1193 tcc_free(section_order);
1194 #if 0
1195 for (i = 1; i < pe->s1->nb_sections; ++i) {
1196 Section *s = pe->s1->sections[i];
1197 int type = s->sh_type;
1198 int flags = s->sh_flags;
1199 printf("section %-16s %-10s %08x %04x %s,%s,%s\n",
1200 s->name,
1201 type == SHT_PROGBITS ? "progbits" :
1202 type == SHT_NOBITS ? "nobits" :
1203 type == SHT_SYMTAB ? "symtab" :
1204 type == SHT_STRTAB ? "strtab" :
1205 type == SHT_RELX ? "rel" : "???",
1206 s->sh_addr,
1207 s->data_offset,
1208 flags & SHF_ALLOC ? "alloc" : "",
1209 flags & SHF_WRITE ? "write" : "",
1210 flags & SHF_EXECINSTR ? "exec" : ""
1213 pe->s1->verbose = 2;
1214 #endif
1215 return 0;
1218 /*----------------------------------------------------------------------------*/
1220 static int pe_isafunc(TCCState *s1, int sym_index)
1222 Section *sr = text_section->reloc;
1223 ElfW_Rel *rel, *rel_end;
1224 ElfW(Addr)info = ELFW(R_INFO)(sym_index, R_XXX_FUNCCALL);
1225 #ifdef R_XXX_FUNCCALL2
1226 ElfW(Addr)info2 = ELFW(R_INFO)(sym_index, R_XXX_FUNCCALL2);
1227 #endif
1228 if (!sr)
1229 return 0;
1230 rel_end = (ElfW_Rel *)(sr->data + sr->data_offset);
1231 for (rel = (ElfW_Rel *)sr->data; rel < rel_end; rel++) {
1232 if (rel->r_info == info)
1233 return 1;
1234 #ifdef R_XXX_FUNCCALL2
1235 if (rel->r_info == info2)
1236 return 1;
1237 #endif
1239 return 0;
1242 /*----------------------------------------------------------------------------*/
1243 static int pe_check_symbols(struct pe_info *pe)
1245 ElfW(Sym) *sym;
1246 int sym_index, sym_end;
1247 int ret = 0;
1248 TCCState *s1 = pe->s1;
1250 pe_align_section(text_section, 8);
1252 sym_end = symtab_section->data_offset / sizeof(ElfW(Sym));
1253 for (sym_index = 1; sym_index < sym_end; ++sym_index) {
1255 sym = (ElfW(Sym) *)symtab_section->data + sym_index;
1256 if (sym->st_shndx == SHN_UNDEF) {
1258 const char *name = (char*)symtab_section->link->data + sym->st_name;
1259 unsigned type = ELFW(ST_TYPE)(sym->st_info);
1260 int imp_sym = pe_find_import(pe->s1, sym);
1261 struct import_symbol *is;
1263 if (imp_sym <= 0)
1264 goto not_found;
1266 if (type == STT_NOTYPE) {
1267 /* symbols from assembler have no type, find out which */
1268 if (pe_isafunc(s1, sym_index))
1269 type = STT_FUNC;
1270 else
1271 type = STT_OBJECT;
1274 is = pe_add_import(pe, imp_sym);
1276 if (type == STT_FUNC) {
1277 unsigned long offset = is->thk_offset;
1278 if (offset) {
1279 /* got aliased symbol, like stricmp and _stricmp */
1280 } else {
1281 char buffer[100];
1282 unsigned char *p;
1284 /* add a helper symbol, will be patched later in
1285 pe_build_imports */
1286 sprintf(buffer, "IAT.%s", name);
1287 is->iat_index = put_elf_sym(
1288 symtab_section, 0, sizeof(DWORD),
1289 ELFW(ST_INFO)(STB_GLOBAL, STT_OBJECT),
1290 0, SHN_UNDEF, buffer);
1292 offset = text_section->data_offset;
1293 is->thk_offset = offset;
1295 /* add the 'jmp IAT[x]' instruction */
1296 #ifdef TCC_TARGET_ARM
1297 p = section_ptr_add(text_section, 8+4); // room for code and address
1298 write32le(p + 0, 0xE59FC000); // arm code ldr ip, [pc] ; PC+8+0 = 0001xxxx
1299 write32le(p + 4, 0xE59CF000); // arm code ldr pc, [ip]
1300 put_elf_reloc(symtab_section, text_section,
1301 offset + 8, R_XXX_THUNKFIX, is->iat_index); // offset to IAT position
1302 #else
1303 p = section_ptr_add(text_section, 8);
1304 write16le(p, 0x25FF);
1305 #ifdef TCC_TARGET_X86_64
1306 write32le(p + 2, (DWORD)-4);
1307 #endif
1308 put_elf_reloc(symtab_section, text_section,
1309 offset + 2, R_XXX_THUNKFIX, is->iat_index);
1310 #endif
1312 /* tcc_realloc might have altered sym's address */
1313 sym = (ElfW(Sym) *)symtab_section->data + sym_index;
1315 /* patch the original symbol */
1316 sym->st_value = offset;
1317 sym->st_shndx = text_section->sh_num;
1318 sym->st_other &= ~ST_PE_EXPORT; /* do not export */
1319 continue;
1322 if (type == STT_OBJECT) { /* data, ptr to that should be */
1323 if (0 == is->iat_index) {
1324 /* original symbol will be patched later in pe_build_imports */
1325 is->iat_index = sym_index;
1326 continue;
1330 not_found:
1331 if (ELFW(ST_BIND)(sym->st_info) == STB_WEAK)
1332 /* STB_WEAK undefined symbols are accepted */
1333 continue;
1334 tcc_error_noabort("undefined symbol '%s'%s", name,
1335 imp_sym < 0 ? ", missing __declspec(dllimport)?":"");
1336 ret = -1;
1338 } else if (pe->s1->rdynamic
1339 && ELFW(ST_BIND)(sym->st_info) != STB_LOCAL) {
1340 /* if -rdynamic option, then export all non local symbols */
1341 sym->st_other |= ST_PE_EXPORT;
1344 return ret;
1347 /*----------------------------------------------------------------------------*/
1348 #ifdef PE_PRINT_SECTIONS
1349 static void pe_print_section(FILE * f, Section * s)
1351 /* just if you're curious */
1352 BYTE *p, *e, b;
1353 int i, n, l, m;
1354 p = s->data;
1355 e = s->data + s->data_offset;
1356 l = e - p;
1358 fprintf(f, "section \"%s\"", s->name);
1359 if (s->link)
1360 fprintf(f, "\nlink \"%s\"", s->link->name);
1361 if (s->reloc)
1362 fprintf(f, "\nreloc \"%s\"", s->reloc->name);
1363 fprintf(f, "\nv_addr %08X", (unsigned)s->sh_addr);
1364 fprintf(f, "\ncontents %08X", (unsigned)l);
1365 fprintf(f, "\n\n");
1367 if (s->sh_type == SHT_NOBITS)
1368 return;
1370 if (0 == l)
1371 return;
1373 if (s->sh_type == SHT_SYMTAB)
1374 m = sizeof(ElfW(Sym));
1375 else if (s->sh_type == SHT_RELX)
1376 m = sizeof(ElfW_Rel);
1377 else
1378 m = 16;
1380 fprintf(f, "%-8s", "offset");
1381 for (i = 0; i < m; ++i)
1382 fprintf(f, " %02x", i);
1383 n = 56;
1385 if (s->sh_type == SHT_SYMTAB || s->sh_type == SHT_RELX) {
1386 const char *fields1[] = {
1387 "name",
1388 "value",
1389 "size",
1390 "bind",
1391 "type",
1392 "other",
1393 "shndx",
1394 NULL
1397 const char *fields2[] = {
1398 "offs",
1399 "type",
1400 "symb",
1401 NULL
1404 const char **p;
1406 if (s->sh_type == SHT_SYMTAB)
1407 p = fields1, n = 106;
1408 else
1409 p = fields2, n = 58;
1411 for (i = 0; p[i]; ++i)
1412 fprintf(f, "%6s", p[i]);
1413 fprintf(f, " symbol");
1416 fprintf(f, "\n");
1417 for (i = 0; i < n; ++i)
1418 fprintf(f, "-");
1419 fprintf(f, "\n");
1421 for (i = 0; i < l;)
1423 fprintf(f, "%08X", i);
1424 for (n = 0; n < m; ++n) {
1425 if (n + i < l)
1426 fprintf(f, " %02X", p[i + n]);
1427 else
1428 fprintf(f, " ");
1431 if (s->sh_type == SHT_SYMTAB) {
1432 ElfW(Sym) *sym = (ElfW(Sym) *) (p + i);
1433 const char *name = s->link->data + sym->st_name;
1434 fprintf(f, " %04X %04X %04X %02X %02X %02X %04X \"%s\"",
1435 (unsigned)sym->st_name,
1436 (unsigned)sym->st_value,
1437 (unsigned)sym->st_size,
1438 (unsigned)ELFW(ST_BIND)(sym->st_info),
1439 (unsigned)ELFW(ST_TYPE)(sym->st_info),
1440 (unsigned)sym->st_other,
1441 (unsigned)sym->st_shndx,
1442 name);
1444 } else if (s->sh_type == SHT_RELX) {
1445 ElfW_Rel *rel = (ElfW_Rel *) (p + i);
1446 ElfW(Sym) *sym =
1447 (ElfW(Sym) *) s->link->data + ELFW(R_SYM)(rel->r_info);
1448 const char *name = s->link->link->data + sym->st_name;
1449 fprintf(f, " %04X %02X %04X \"%s\"",
1450 (unsigned)rel->r_offset,
1451 (unsigned)ELFW(R_TYPE)(rel->r_info),
1452 (unsigned)ELFW(R_SYM)(rel->r_info),
1453 name);
1454 } else {
1455 fprintf(f, " ");
1456 for (n = 0; n < m; ++n) {
1457 if (n + i < l) {
1458 b = p[i + n];
1459 if (b < 32 || b >= 127)
1460 b = '.';
1461 fprintf(f, "%c", b);
1465 i += m;
1466 fprintf(f, "\n");
1468 fprintf(f, "\n\n");
1471 static void pe_print_sections(TCCState *s1, const char *fname)
1473 Section *s;
1474 FILE *f;
1475 int i;
1476 f = fopen(fname, "w");
1477 for (i = 1; i < s1->nb_sections; ++i) {
1478 s = s1->sections[i];
1479 pe_print_section(f, s);
1481 pe_print_section(f, s1->dynsymtab_section);
1482 fclose(f);
1484 #endif
1486 /* ------------------------------------------------------------- */
1487 /* helper function for load/store to insert one more indirection */
1489 #if defined TCC_TARGET_I386 || defined TCC_TARGET_X86_64
1490 ST_FUNC SValue *pe_getimport(SValue *sv, SValue *v2)
1492 int r2;
1493 if ((sv->r & (VT_VALMASK|VT_SYM)) != (VT_CONST|VT_SYM) || (sv->r2 != VT_CONST))
1494 return sv;
1495 if (!sv->sym->a.dllimport)
1496 return sv;
1497 // printf("import %04x %04x %04x %s\n", sv->type.t, sv->sym->type.t, sv->r, get_tok_str(sv->sym->v, NULL));
1498 memset(v2, 0, sizeof *v2);
1499 v2->type.t = VT_PTR;
1500 v2->r = VT_CONST | VT_SYM | VT_LVAL;
1501 v2->sym = sv->sym;
1503 r2 = get_reg(RC_INT);
1504 load(r2, v2);
1505 v2->r = r2;
1506 if ((uint32_t)sv->c.i) {
1507 vpushv(v2);
1508 vpushi(sv->c.i);
1509 gen_opi('+');
1510 *v2 = *vtop--;
1512 v2->type.t = sv->type.t;
1513 v2->r |= sv->r & VT_LVAL;
1514 return v2;
1516 #endif
1518 ST_FUNC int pe_putimport(TCCState *s1, int dllindex, const char *name, addr_t value)
1520 return set_elf_sym(
1521 s1->dynsymtab_section,
1522 value,
1523 dllindex, /* st_size */
1524 ELFW(ST_INFO)(STB_GLOBAL, STT_NOTYPE),
1526 value ? SHN_ABS : SHN_UNDEF,
1527 name
1531 static int pe_add_dllref(TCCState *s1, const char *dllname)
1533 int i;
1534 for (i = 0; i < s1->nb_loaded_dlls; ++i)
1535 if (0 == strcmp(s1->loaded_dlls[i]->name, dllname))
1536 return i + 1;
1537 tcc_add_dllref(s1, dllname);
1538 return s1->nb_loaded_dlls;
1541 /* ------------------------------------------------------------- */
1543 static int read_mem(int fd, unsigned offset, void *buffer, unsigned len)
1545 lseek(fd, offset, SEEK_SET);
1546 return len == read(fd, buffer, len);
1549 /* ------------------------------------------------------------- */
1551 PUB_FUNC int tcc_get_dllexports(const char *filename, char **pp)
1553 int l, i, n, n0, ret;
1554 char *p;
1555 int fd;
1557 IMAGE_SECTION_HEADER ish;
1558 IMAGE_EXPORT_DIRECTORY ied;
1559 IMAGE_DOS_HEADER dh;
1560 IMAGE_FILE_HEADER ih;
1561 DWORD sig, ref, addr, ptr, namep;
1563 int pef_hdroffset, opt_hdroffset, sec_hdroffset;
1565 n = n0 = 0;
1566 p = NULL;
1567 ret = -1;
1569 fd = open(filename, O_RDONLY | O_BINARY);
1570 if (fd < 0)
1571 goto the_end_1;
1572 ret = 1;
1573 if (!read_mem(fd, 0, &dh, sizeof dh))
1574 goto the_end;
1575 if (!read_mem(fd, dh.e_lfanew, &sig, sizeof sig))
1576 goto the_end;
1577 if (sig != 0x00004550)
1578 goto the_end;
1579 pef_hdroffset = dh.e_lfanew + sizeof sig;
1580 if (!read_mem(fd, pef_hdroffset, &ih, sizeof ih))
1581 goto the_end;
1582 opt_hdroffset = pef_hdroffset + sizeof ih;
1583 if (ih.Machine == 0x014C) {
1584 IMAGE_OPTIONAL_HEADER32 oh;
1585 sec_hdroffset = opt_hdroffset + sizeof oh;
1586 if (!read_mem(fd, opt_hdroffset, &oh, sizeof oh))
1587 goto the_end;
1588 if (IMAGE_DIRECTORY_ENTRY_EXPORT >= oh.NumberOfRvaAndSizes)
1589 goto the_end_0;
1590 addr = oh.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress;
1591 } else if (ih.Machine == 0x8664) {
1592 IMAGE_OPTIONAL_HEADER64 oh;
1593 sec_hdroffset = opt_hdroffset + sizeof oh;
1594 if (!read_mem(fd, opt_hdroffset, &oh, sizeof oh))
1595 goto the_end;
1596 if (IMAGE_DIRECTORY_ENTRY_EXPORT >= oh.NumberOfRvaAndSizes)
1597 goto the_end_0;
1598 addr = oh.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress;
1599 } else
1600 goto the_end;
1602 //printf("addr: %08x\n", addr);
1603 for (i = 0; i < ih.NumberOfSections; ++i) {
1604 if (!read_mem(fd, sec_hdroffset + i * sizeof ish, &ish, sizeof ish))
1605 goto the_end;
1606 //printf("vaddr: %08x\n", ish.VirtualAddress);
1607 if (addr >= ish.VirtualAddress && addr < ish.VirtualAddress + ish.SizeOfRawData)
1608 goto found;
1610 goto the_end_0;
1612 found:
1613 ref = ish.VirtualAddress - ish.PointerToRawData;
1614 if (!read_mem(fd, addr - ref, &ied, sizeof ied))
1615 goto the_end;
1617 namep = ied.AddressOfNames - ref;
1618 for (i = 0; i < ied.NumberOfNames; ++i) {
1619 if (!read_mem(fd, namep, &ptr, sizeof ptr))
1620 goto the_end;
1621 namep += sizeof ptr;
1622 for (l = 0;;) {
1623 if (n+1 >= n0)
1624 p = tcc_realloc(p, n0 = n0 ? n0 * 2 : 256);
1625 if (!read_mem(fd, ptr - ref + l++, p + n, 1)) {
1626 tcc_free(p), p = NULL;
1627 goto the_end;
1629 if (p[n++] == 0)
1630 break;
1633 if (p)
1634 p[n] = 0;
1635 the_end_0:
1636 ret = 0;
1637 the_end:
1638 close(fd);
1639 the_end_1:
1640 *pp = p;
1641 return ret;
1644 /* -------------------------------------------------------------
1645 * This is for compiled windows resources in 'coff' format
1646 * as generated by 'windres.exe -O coff ...'.
1649 static int pe_load_res(TCCState *s1, int fd)
1651 struct pe_rsrc_header hdr;
1652 Section *rsrc_section;
1653 int i, ret = -1, sym_index;
1654 BYTE *ptr;
1655 unsigned offs;
1657 if (!read_mem(fd, 0, &hdr, sizeof hdr))
1658 goto quit;
1660 if (hdr.filehdr.Machine != IMAGE_FILE_MACHINE
1661 || hdr.filehdr.NumberOfSections != 1
1662 || strcmp((char*)hdr.sectionhdr.Name, ".rsrc") != 0)
1663 goto quit;
1665 rsrc_section = new_section(s1, ".rsrc", SHT_PROGBITS, SHF_ALLOC);
1666 ptr = section_ptr_add(rsrc_section, hdr.sectionhdr.SizeOfRawData);
1667 offs = hdr.sectionhdr.PointerToRawData;
1668 if (!read_mem(fd, offs, ptr, hdr.sectionhdr.SizeOfRawData))
1669 goto quit;
1670 offs = hdr.sectionhdr.PointerToRelocations;
1671 sym_index = put_elf_sym(symtab_section, 0, 0, 0, 0, rsrc_section->sh_num, ".rsrc");
1672 for (i = 0; i < hdr.sectionhdr.NumberOfRelocations; ++i) {
1673 struct pe_rsrc_reloc rel;
1674 if (!read_mem(fd, offs, &rel, sizeof rel))
1675 goto quit;
1676 // printf("rsrc_reloc: %x %x %x\n", rel.offset, rel.size, rel.type);
1677 if (rel.type != RSRC_RELTYPE)
1678 goto quit;
1679 put_elf_reloc(symtab_section, rsrc_section,
1680 rel.offset, R_XXX_RELATIVE, sym_index);
1681 offs += sizeof rel;
1683 ret = 0;
1684 quit:
1685 return ret;
1688 /* ------------------------------------------------------------- */
1690 static char *trimfront(char *p)
1692 while (*p && (unsigned char)*p <= ' ')
1693 ++p;
1694 return p;
1697 static char *trimback(char *a, char *e)
1699 while (e > a && (unsigned char)e[-1] <= ' ')
1700 --e;
1701 *e = 0;;
1702 return a;
1705 /* ------------------------------------------------------------- */
1706 static int pe_load_def(TCCState *s1, int fd)
1708 int state = 0, ret = -1, dllindex = 0, ord;
1709 char line[400], dllname[80], *p, *x;
1710 FILE *fp;
1712 fp = fdopen(dup(fd), "rb");
1713 while (fgets(line, sizeof line, fp))
1715 p = trimfront(trimback(line, strchr(line, 0)));
1716 if (0 == *p || ';' == *p)
1717 continue;
1719 switch (state) {
1720 case 0:
1721 if (0 != strnicmp(p, "LIBRARY", 7))
1722 goto quit;
1723 pstrcpy(dllname, sizeof dllname, trimfront(p+7));
1724 ++state;
1725 continue;
1727 case 1:
1728 if (0 != stricmp(p, "EXPORTS"))
1729 goto quit;
1730 ++state;
1731 continue;
1733 case 2:
1734 dllindex = pe_add_dllref(s1, dllname);
1735 ++state;
1736 /* fall through */
1737 default:
1738 /* get ordinal and will store in sym->st_value */
1739 ord = 0;
1740 x = strchr(p, ' ');
1741 if (x) {
1742 *x = 0, x = strrchr(x + 1, '@');
1743 if (x) {
1744 char *d;
1745 ord = (int)strtol(x + 1, &d, 10);
1746 if (*d)
1747 ord = 0;
1750 pe_putimport(s1, dllindex, p, ord);
1751 continue;
1754 ret = 0;
1755 quit:
1756 fclose(fp);
1757 return ret;
1760 /* ------------------------------------------------------------- */
1761 static int pe_load_dll(TCCState *s1, const char *filename)
1763 char *p, *q;
1764 int index, ret;
1766 ret = tcc_get_dllexports(filename, &p);
1767 if (ret) {
1768 return -1;
1769 } else if (p) {
1770 index = pe_add_dllref(s1, filename);
1771 for (q = p; *q; q += 1 + strlen(q))
1772 pe_putimport(s1, index, q, 0);
1773 tcc_free(p);
1775 return 0;
1778 /* ------------------------------------------------------------- */
1779 ST_FUNC int pe_load_file(struct TCCState *s1, int fd, const char *filename)
1781 int ret = -1;
1782 char buf[10];
1783 if (0 == strcmp(tcc_fileextension(filename), ".def"))
1784 ret = pe_load_def(s1, fd);
1785 else if (pe_load_res(s1, fd) == 0)
1786 ret = 0;
1787 else if (read_mem(fd, 0, buf, 4) && 0 == memcmp(buf, "MZ", 2))
1788 ret = pe_load_dll(s1, filename);
1789 return ret;
1792 /* ------------------------------------------------------------- */
1793 #ifdef TCC_TARGET_X86_64
1794 static unsigned pe_add_uwwind_info(TCCState *s1)
1796 if (NULL == s1->uw_pdata) {
1797 s1->uw_pdata = find_section(s1, ".pdata");
1798 s1->uw_pdata->sh_addralign = 4;
1800 if (0 == s1->uw_sym)
1801 s1->uw_sym = put_elf_sym(symtab_section, 0, 0, 0, 0, text_section->sh_num, ".uw_base");
1802 if (0 == s1->uw_offs) {
1803 /* As our functions all have the same stackframe, we use one entry for all */
1804 static const unsigned char uw_info[] = {
1805 0x01, // UBYTE: 3 Version , UBYTE: 5 Flags
1806 0x04, // UBYTE Size of prolog
1807 0x02, // UBYTE Count of unwind codes
1808 0x05, // UBYTE: 4 Frame Register (rbp), UBYTE: 4 Frame Register offset (scaled)
1809 // USHORT * n Unwind codes array
1810 // 0x0b, 0x01, 0xff, 0xff, // stack size
1811 0x04, 0x03, // set frame ptr (mov rsp -> rbp)
1812 0x01, 0x50 // push reg (rbp)
1815 Section *s = text_section;
1816 unsigned char *p;
1818 section_ptr_add(s, -s->data_offset & 3); /* align */
1819 s1->uw_offs = s->data_offset;
1820 p = section_ptr_add(s, sizeof uw_info);
1821 memcpy(p, uw_info, sizeof uw_info);
1824 return s1->uw_offs;
1827 ST_FUNC void pe_add_unwind_data(unsigned start, unsigned end, unsigned stack)
1829 TCCState *s1 = tcc_state;
1830 Section *pd;
1831 unsigned o, n, d;
1832 struct /* _RUNTIME_FUNCTION */ {
1833 DWORD BeginAddress;
1834 DWORD EndAddress;
1835 DWORD UnwindData;
1836 } *p;
1838 d = pe_add_uwwind_info(s1);
1839 pd = s1->uw_pdata;
1840 o = pd->data_offset;
1841 p = section_ptr_add(pd, sizeof *p);
1843 /* record this function */
1844 p->BeginAddress = start;
1845 p->EndAddress = end;
1846 p->UnwindData = d;
1848 /* put relocations on it */
1849 for (n = o + sizeof *p; o < n; o += sizeof p->BeginAddress)
1850 put_elf_reloc(symtab_section, pd, o, R_XXX_RELATIVE, s1->uw_sym);
1852 #endif
1853 /* ------------------------------------------------------------- */
1854 #ifdef TCC_TARGET_X86_64
1855 #define PE_STDSYM(n,s) n
1856 #else
1857 #define PE_STDSYM(n,s) "_" n s
1858 #endif
1860 static void tcc_add_support(TCCState *s1, const char *filename)
1862 if (tcc_add_dll(s1, filename, 0) < 0)
1863 tcc_error_noabort("%s not found", filename);
1866 static void pe_add_runtime(TCCState *s1, struct pe_info *pe)
1868 const char *start_symbol;
1869 int pe_type;
1871 if (TCC_OUTPUT_DLL == s1->output_type) {
1872 pe_type = PE_DLL;
1873 start_symbol = PE_STDSYM("__dllstart","@12");
1874 } else {
1875 const char *run_symbol;
1876 if (find_elf_sym(symtab_section, PE_STDSYM("WinMain","@16"))) {
1877 start_symbol = "__winstart";
1878 run_symbol = "__runwinmain";
1879 pe_type = PE_GUI;
1880 } else if (find_elf_sym(symtab_section, PE_STDSYM("wWinMain","@16"))) {
1881 start_symbol = "__wwinstart";
1882 run_symbol = "__runwwinmain";
1883 pe_type = PE_GUI;
1884 } else if (find_elf_sym(symtab_section, "wmain")) {
1885 start_symbol = "__wstart";
1886 run_symbol = "__runwmain";
1887 pe_type = PE_EXE;
1888 } else {
1889 start_symbol = "__start";
1890 run_symbol = "__runmain";
1891 pe_type = PE_EXE;
1894 if (TCC_OUTPUT_MEMORY == s1->output_type)
1895 start_symbol = run_symbol;
1898 pe->start_symbol = start_symbol + 1;
1899 if (!s1->leading_underscore || strchr(start_symbol, '@'))
1900 ++start_symbol;
1902 #ifdef CONFIG_TCC_BACKTRACE
1903 if (s1->do_backtrace) {
1904 #ifdef CONFIG_TCC_BCHECK
1905 if (s1->do_bounds_check && s1->output_type != TCC_OUTPUT_DLL)
1906 tcc_add_support(s1, "bcheck.o");
1907 #endif
1908 if (s1->output_type == TCC_OUTPUT_EXE)
1909 tcc_add_support(s1, "bt-exe.o");
1910 if (s1->output_type == TCC_OUTPUT_DLL)
1911 tcc_add_support(s1, "bt-dll.o");
1912 if (s1->output_type != TCC_OUTPUT_DLL)
1913 tcc_add_support(s1, "bt-log.o");
1914 if (s1->output_type != TCC_OUTPUT_MEMORY)
1915 tcc_add_btstub(s1);
1917 #endif
1919 /* grab the startup code from libtcc1.a */
1920 #ifdef TCC_IS_NATIVE
1921 if (TCC_OUTPUT_MEMORY != s1->output_type || s1->runtime_main)
1922 #endif
1923 set_global_sym(s1, start_symbol, NULL, 0);
1925 if (0 == s1->nostdlib) {
1926 static const char *libs[] = {
1927 "msvcrt", "kernel32", "", "user32", "gdi32", NULL
1929 const char **pp, *p;
1930 if (strlen(TCC_LIBTCC1) > 0)
1931 tcc_add_support(s1, TCC_LIBTCC1);
1932 for (pp = libs; 0 != (p = *pp); ++pp) {
1933 if (*p)
1934 tcc_add_library_err(s1, p);
1935 else if (PE_DLL != pe_type && PE_GUI != pe_type)
1936 break;
1940 /* need this for 'tccelf.c:relocate_section()' */
1941 if (TCC_OUTPUT_DLL == s1->output_type)
1942 s1->output_type = TCC_OUTPUT_EXE;
1943 if (TCC_OUTPUT_MEMORY == s1->output_type)
1944 pe_type = PE_RUN;
1945 pe->type = pe_type;
1948 static void pe_set_options(TCCState * s1, struct pe_info *pe)
1950 if (PE_DLL == pe->type) {
1951 /* XXX: check if is correct for arm-pe target */
1952 pe->imagebase = 0x10000000;
1953 } else {
1954 #if defined(TCC_TARGET_ARM)
1955 pe->imagebase = 0x00010000;
1956 #else
1957 pe->imagebase = 0x00400000;
1958 #endif
1961 #if defined(TCC_TARGET_ARM)
1962 /* we use "console" subsystem by default */
1963 pe->subsystem = 9;
1964 #else
1965 if (PE_DLL == pe->type || PE_GUI == pe->type)
1966 pe->subsystem = 2;
1967 else
1968 pe->subsystem = 3;
1969 #endif
1970 /* Allow override via -Wl,-subsystem=... option */
1971 if (s1->pe_subsystem != 0)
1972 pe->subsystem = s1->pe_subsystem;
1974 /* set default file/section alignment */
1975 if (pe->subsystem == 1) {
1976 pe->section_align = 0x20;
1977 pe->file_align = 0x20;
1978 } else {
1979 pe->section_align = 0x1000;
1980 pe->file_align = 0x200;
1983 if (s1->section_align != 0)
1984 pe->section_align = s1->section_align;
1985 if (s1->pe_file_align != 0)
1986 pe->file_align = s1->pe_file_align;
1988 if ((pe->subsystem >= 10) && (pe->subsystem <= 12))
1989 pe->imagebase = 0;
1991 if (s1->has_text_addr)
1992 pe->imagebase = s1->text_addr;
1995 ST_FUNC int pe_output_file(TCCState *s1, const char *filename)
1997 int ret;
1998 struct pe_info pe;
1999 int i;
2001 memset(&pe, 0, sizeof pe);
2002 pe.filename = filename;
2003 pe.s1 = s1;
2004 s1->filetype = 0;
2006 #ifdef CONFIG_TCC_BCHECK
2007 tcc_add_bcheck(s1);
2008 #endif
2009 tcc_add_pragma_libs(s1);
2010 pe_add_runtime(s1, &pe);
2011 resolve_common_syms(s1);
2012 pe_set_options(s1, &pe);
2014 ret = pe_check_symbols(&pe);
2015 if (ret)
2017 else if (filename) {
2018 pe_assign_addresses(&pe);
2019 relocate_syms(s1, s1->symtab, 0);
2020 s1->pe_imagebase = pe.imagebase;
2021 for (i = 1; i < s1->nb_sections; ++i) {
2022 Section *s = s1->sections[i];
2023 if (s->reloc) {
2024 relocate_section(s1, s);
2027 pe.start_addr = (DWORD)
2028 (get_sym_addr(s1, pe.start_symbol, 1, 1) - pe.imagebase);
2029 if (s1->nb_errors)
2030 ret = -1;
2031 else
2032 ret = pe_write(&pe);
2033 dynarray_reset(&pe.sec_info, &pe.sec_count);
2034 } else {
2035 #ifdef TCC_IS_NATIVE
2036 pe.thunk = data_section;
2037 pe_build_imports(&pe);
2038 s1->runtime_main = pe.start_symbol;
2039 #ifdef TCC_TARGET_X86_64
2040 s1->uw_pdata = find_section(s1, ".pdata");
2041 #endif
2042 #endif
2045 pe_free_imports(&pe);
2047 #ifdef PE_PRINT_SECTIONS
2048 pe_print_sections(s1, "tcc.log");
2049 #endif
2050 return ret;
2053 /* ------------------------------------------------------------- */