Add missing ws2tcpip.h which lets tcc compile Microsoft Winsock Server sample on...
[tinycc.git] / tccpe.c
blobd524294628e338ae05a515bda680290be1b13279
1 /*
2 * TCCPE.C - PE file output for the Tiny C Compiler
4 * Copyright (c) 2005-2007 grischka
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
21 #include "tcc.h"
23 #define PE_MERGE_DATA
24 /* #define PE_PRINT_SECTIONS */
26 #ifndef _WIN32
27 #define stricmp strcasecmp
28 #define strnicmp strncasecmp
29 #include <sys/stat.h> /* chmod() */
30 #endif
32 #ifdef TCC_TARGET_X86_64
33 # define ADDR3264 ULONGLONG
34 # define PE_IMAGE_REL IMAGE_REL_BASED_DIR64
35 # define REL_TYPE_DIRECT R_X86_64_64
36 # define R_XXX_THUNKFIX R_X86_64_PC32
37 # define R_XXX_RELATIVE R_X86_64_RELATIVE
38 # define IMAGE_FILE_MACHINE 0x8664
39 # define RSRC_RELTYPE 3
41 #elif defined TCC_TARGET_ARM
42 # define ADDR3264 DWORD
43 # define PE_IMAGE_REL IMAGE_REL_BASED_HIGHLOW
44 # define REL_TYPE_DIRECT R_ARM_ABS32
45 # define R_XXX_THUNKFIX R_ARM_ABS32
46 # define R_XXX_RELATIVE R_ARM_RELATIVE
47 # define IMAGE_FILE_MACHINE 0x01C0
48 # define RSRC_RELTYPE 7 /* ??? (not tested) */
50 #elif defined TCC_TARGET_I386
51 # define ADDR3264 DWORD
52 # define PE_IMAGE_REL IMAGE_REL_BASED_HIGHLOW
53 # define REL_TYPE_DIRECT R_386_32
54 # define R_XXX_THUNKFIX R_386_32
55 # define R_XXX_RELATIVE R_386_RELATIVE
56 # define IMAGE_FILE_MACHINE 0x014C
57 # define RSRC_RELTYPE 7 /* DIR32NB */
59 #endif
61 #ifndef IMAGE_NT_SIGNATURE
62 /* ----------------------------------------------------------- */
63 /* definitions below are from winnt.h */
65 typedef unsigned char BYTE;
66 typedef unsigned short WORD;
67 typedef unsigned int DWORD;
68 typedef unsigned long long ULONGLONG;
69 #pragma pack(push, 1)
71 typedef struct _IMAGE_DOS_HEADER { /* DOS .EXE header */
72 WORD e_magic; /* Magic number */
73 WORD e_cblp; /* Bytes on last page of file */
74 WORD e_cp; /* Pages in file */
75 WORD e_crlc; /* Relocations */
76 WORD e_cparhdr; /* Size of header in paragraphs */
77 WORD e_minalloc; /* Minimum extra paragraphs needed */
78 WORD e_maxalloc; /* Maximum extra paragraphs needed */
79 WORD e_ss; /* Initial (relative) SS value */
80 WORD e_sp; /* Initial SP value */
81 WORD e_csum; /* Checksum */
82 WORD e_ip; /* Initial IP value */
83 WORD e_cs; /* Initial (relative) CS value */
84 WORD e_lfarlc; /* File address of relocation table */
85 WORD e_ovno; /* Overlay number */
86 WORD e_res[4]; /* Reserved words */
87 WORD e_oemid; /* OEM identifier (for e_oeminfo) */
88 WORD e_oeminfo; /* OEM information; e_oemid specific */
89 WORD e_res2[10]; /* Reserved words */
90 DWORD e_lfanew; /* File address of new exe header */
91 } IMAGE_DOS_HEADER, *PIMAGE_DOS_HEADER;
93 #define IMAGE_NT_SIGNATURE 0x00004550 /* PE00 */
94 #define SIZE_OF_NT_SIGNATURE 4
96 typedef struct _IMAGE_FILE_HEADER {
97 WORD Machine;
98 WORD NumberOfSections;
99 DWORD TimeDateStamp;
100 DWORD PointerToSymbolTable;
101 DWORD NumberOfSymbols;
102 WORD SizeOfOptionalHeader;
103 WORD Characteristics;
104 } IMAGE_FILE_HEADER, *PIMAGE_FILE_HEADER;
107 #define IMAGE_SIZEOF_FILE_HEADER 20
109 typedef struct _IMAGE_DATA_DIRECTORY {
110 DWORD VirtualAddress;
111 DWORD Size;
112 } IMAGE_DATA_DIRECTORY, *PIMAGE_DATA_DIRECTORY;
115 typedef struct _IMAGE_OPTIONAL_HEADER {
116 /* Standard fields. */
117 WORD Magic;
118 BYTE MajorLinkerVersion;
119 BYTE MinorLinkerVersion;
120 DWORD SizeOfCode;
121 DWORD SizeOfInitializedData;
122 DWORD SizeOfUninitializedData;
123 DWORD AddressOfEntryPoint;
124 DWORD BaseOfCode;
125 #ifndef TCC_TARGET_X86_64
126 DWORD BaseOfData;
127 #endif
128 /* NT additional fields. */
129 ADDR3264 ImageBase;
130 DWORD SectionAlignment;
131 DWORD FileAlignment;
132 WORD MajorOperatingSystemVersion;
133 WORD MinorOperatingSystemVersion;
134 WORD MajorImageVersion;
135 WORD MinorImageVersion;
136 WORD MajorSubsystemVersion;
137 WORD MinorSubsystemVersion;
138 DWORD Win32VersionValue;
139 DWORD SizeOfImage;
140 DWORD SizeOfHeaders;
141 DWORD CheckSum;
142 WORD Subsystem;
143 WORD DllCharacteristics;
144 ADDR3264 SizeOfStackReserve;
145 ADDR3264 SizeOfStackCommit;
146 ADDR3264 SizeOfHeapReserve;
147 ADDR3264 SizeOfHeapCommit;
148 DWORD LoaderFlags;
149 DWORD NumberOfRvaAndSizes;
150 IMAGE_DATA_DIRECTORY DataDirectory[16];
151 } IMAGE_OPTIONAL_HEADER32, IMAGE_OPTIONAL_HEADER64, IMAGE_OPTIONAL_HEADER;
153 #define IMAGE_DIRECTORY_ENTRY_EXPORT 0 /* Export Directory */
154 #define IMAGE_DIRECTORY_ENTRY_IMPORT 1 /* Import Directory */
155 #define IMAGE_DIRECTORY_ENTRY_RESOURCE 2 /* Resource Directory */
156 #define IMAGE_DIRECTORY_ENTRY_EXCEPTION 3 /* Exception Directory */
157 #define IMAGE_DIRECTORY_ENTRY_SECURITY 4 /* Security Directory */
158 #define IMAGE_DIRECTORY_ENTRY_BASERELOC 5 /* Base Relocation Table */
159 #define IMAGE_DIRECTORY_ENTRY_DEBUG 6 /* Debug Directory */
160 /* IMAGE_DIRECTORY_ENTRY_COPYRIGHT 7 (X86 usage) */
161 #define IMAGE_DIRECTORY_ENTRY_ARCHITECTURE 7 /* Architecture Specific Data */
162 #define IMAGE_DIRECTORY_ENTRY_GLOBALPTR 8 /* RVA of GP */
163 #define IMAGE_DIRECTORY_ENTRY_TLS 9 /* TLS Directory */
164 #define IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG 10 /* Load Configuration Directory */
165 #define IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT 11 /* Bound Import Directory in headers */
166 #define IMAGE_DIRECTORY_ENTRY_IAT 12 /* Import Address Table */
167 #define IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT 13 /* Delay Load Import Descriptors */
168 #define IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR 14 /* COM Runtime descriptor */
170 /* Section header format. */
171 #define IMAGE_SIZEOF_SHORT_NAME 8
173 typedef struct _IMAGE_SECTION_HEADER {
174 BYTE Name[IMAGE_SIZEOF_SHORT_NAME];
175 union {
176 DWORD PhysicalAddress;
177 DWORD VirtualSize;
178 } Misc;
179 DWORD VirtualAddress;
180 DWORD SizeOfRawData;
181 DWORD PointerToRawData;
182 DWORD PointerToRelocations;
183 DWORD PointerToLinenumbers;
184 WORD NumberOfRelocations;
185 WORD NumberOfLinenumbers;
186 DWORD Characteristics;
187 } IMAGE_SECTION_HEADER, *PIMAGE_SECTION_HEADER;
189 #define IMAGE_SIZEOF_SECTION_HEADER 40
191 typedef struct _IMAGE_EXPORT_DIRECTORY {
192 DWORD Characteristics;
193 DWORD TimeDateStamp;
194 WORD MajorVersion;
195 WORD MinorVersion;
196 DWORD Name;
197 DWORD Base;
198 DWORD NumberOfFunctions;
199 DWORD NumberOfNames;
200 DWORD AddressOfFunctions;
201 DWORD AddressOfNames;
202 DWORD AddressOfNameOrdinals;
203 } IMAGE_EXPORT_DIRECTORY,*PIMAGE_EXPORT_DIRECTORY;
205 typedef struct _IMAGE_IMPORT_DESCRIPTOR {
206 union {
207 DWORD Characteristics;
208 DWORD OriginalFirstThunk;
210 DWORD TimeDateStamp;
211 DWORD ForwarderChain;
212 DWORD Name;
213 DWORD FirstThunk;
214 } IMAGE_IMPORT_DESCRIPTOR;
216 typedef struct _IMAGE_BASE_RELOCATION {
217 DWORD VirtualAddress;
218 DWORD SizeOfBlock;
219 // WORD TypeOffset[1];
220 } IMAGE_BASE_RELOCATION;
222 #define IMAGE_SIZEOF_BASE_RELOCATION 8
224 #define IMAGE_REL_BASED_ABSOLUTE 0
225 #define IMAGE_REL_BASED_HIGH 1
226 #define IMAGE_REL_BASED_LOW 2
227 #define IMAGE_REL_BASED_HIGHLOW 3
228 #define IMAGE_REL_BASED_HIGHADJ 4
229 #define IMAGE_REL_BASED_MIPS_JMPADDR 5
230 #define IMAGE_REL_BASED_SECTION 6
231 #define IMAGE_REL_BASED_REL32 7
232 #define IMAGE_REL_BASED_DIR64 10
234 #define IMAGE_SCN_CNT_CODE 0x00000020
235 #define IMAGE_SCN_CNT_INITIALIZED_DATA 0x00000040
236 #define IMAGE_SCN_CNT_UNINITIALIZED_DATA 0x00000080
237 #define IMAGE_SCN_MEM_DISCARDABLE 0x02000000
238 #define IMAGE_SCN_MEM_SHARED 0x10000000
239 #define IMAGE_SCN_MEM_EXECUTE 0x20000000
240 #define IMAGE_SCN_MEM_READ 0x40000000
241 #define IMAGE_SCN_MEM_WRITE 0x80000000
243 #pragma pack(pop)
245 /* ----------------------------------------------------------- */
246 #endif /* ndef IMAGE_NT_SIGNATURE */
247 /* ----------------------------------------------------------- */
249 #ifndef IMAGE_REL_BASED_DIR64
250 # define IMAGE_REL_BASED_DIR64 10
251 #endif
253 #pragma pack(push, 1)
254 struct pe_header
256 IMAGE_DOS_HEADER doshdr;
257 BYTE dosstub[0x40];
258 DWORD nt_sig;
259 IMAGE_FILE_HEADER filehdr;
260 #ifdef TCC_TARGET_X86_64
261 IMAGE_OPTIONAL_HEADER64 opthdr;
262 #else
263 #ifdef _WIN64
264 IMAGE_OPTIONAL_HEADER32 opthdr;
265 #else
266 IMAGE_OPTIONAL_HEADER opthdr;
267 #endif
268 #endif
271 struct pe_reloc_header {
272 DWORD offset;
273 DWORD size;
276 struct pe_rsrc_header {
277 struct _IMAGE_FILE_HEADER filehdr;
278 struct _IMAGE_SECTION_HEADER sectionhdr;
281 struct pe_rsrc_reloc {
282 DWORD offset;
283 DWORD size;
284 WORD type;
286 #pragma pack(pop)
288 /* ------------------------------------------------------------- */
289 /* internal temporary structures */
291 enum {
292 sec_text = 0,
293 sec_data ,
294 sec_bss ,
295 sec_idata ,
296 sec_pdata ,
297 sec_other ,
298 sec_rsrc ,
299 sec_stab ,
300 sec_stabstr ,
301 sec_reloc ,
302 sec_last
305 #if 0
306 static const DWORD pe_sec_flags[] = {
307 0x60000020, /* ".text" , */
308 0xC0000040, /* ".data" , */
309 0xC0000080, /* ".bss" , */
310 0x40000040, /* ".idata" , */
311 0x40000040, /* ".pdata" , */
312 0xE0000060, /* < other > , */
313 0x40000040, /* ".rsrc" , */
314 0x42000802, /* ".stab" , */
315 0x42000040, /* ".reloc" , */
317 #endif
319 struct section_info {
320 int cls;
321 char name[32];
322 DWORD sh_addr;
323 DWORD sh_size;
324 DWORD pe_flags;
325 Section *sec;
326 DWORD data_size;
327 IMAGE_SECTION_HEADER ish;
330 struct import_symbol {
331 int sym_index;
332 int iat_index;
333 int thk_offset;
336 struct pe_import_info {
337 int dll_index;
338 int sym_count;
339 struct import_symbol **symbols;
342 struct pe_info {
343 TCCState *s1;
344 Section *reloc;
345 Section *thunk;
346 const char *filename;
347 int type;
348 DWORD sizeofheaders;
349 ADDR3264 imagebase;
350 const char *start_symbol;
351 DWORD start_addr;
352 DWORD imp_offs;
353 DWORD imp_size;
354 DWORD iat_offs;
355 DWORD iat_size;
356 DWORD exp_offs;
357 DWORD exp_size;
358 int subsystem;
359 DWORD section_align;
360 DWORD file_align;
361 struct section_info **sec_info;
362 int sec_count;
363 struct pe_import_info **imp_info;
364 int imp_count;
367 #define PE_NUL 0
368 #define PE_DLL 1
369 #define PE_GUI 2
370 #define PE_EXE 3
371 #define PE_RUN 4
373 /* --------------------------------------------*/
375 static const char *pe_export_name(TCCState *s1, ElfW(Sym) *sym)
377 const char *name = (char*)symtab_section->link->data + sym->st_name;
378 if (s1->leading_underscore && name[0] == '_' && !(sym->st_other & ST_PE_STDCALL))
379 return name + 1;
380 return name;
383 static int pe_find_import(TCCState * s1, ElfW(Sym) *sym)
385 char buffer[200];
386 const char *s, *p;
387 int sym_index = 0, n = 0;
388 int a, err = 0;
390 do {
391 s = pe_export_name(s1, sym);
392 a = 0;
393 if (n) {
394 /* second try: */
395 if (sym->st_other & ST_PE_STDCALL) {
396 /* try w/0 stdcall deco (windows API convention) */
397 p = strrchr(s, '@');
398 if (!p || s[0] != '_')
399 break;
400 strcpy(buffer, s+1)[p-s-1] = 0;
401 } else if (s[0] != '_') { /* try non-ansi function */
402 buffer[0] = '_', strcpy(buffer + 1, s);
403 } else if (0 == memcmp(s, "__imp_", 6)) { /* mingw 2.0 */
404 strcpy(buffer, s + 6), a = 1;
405 } else if (0 == memcmp(s, "_imp__", 6)) { /* mingw 3.7 */
406 strcpy(buffer, s + 6), a = 1;
407 } else {
408 continue;
410 s = buffer;
412 sym_index = find_elf_sym(s1->dynsymtab_section, s);
413 // printf("find (%d) %d %s\n", n, sym_index, s);
414 if (sym_index
415 && ELFW(ST_TYPE)(sym->st_info) == STT_OBJECT
416 && 0 == (sym->st_other & ST_PE_IMPORT)
417 && 0 == a
418 ) err = -1, sym_index = 0;
419 } while (0 == sym_index && ++n < 2);
420 return n == 2 ? err : sym_index;
423 /*----------------------------------------------------------------------------*/
425 static int dynarray_assoc(void **pp, int n, int key)
427 int i;
428 for (i = 0; i < n; ++i, ++pp)
429 if (key == **(int **) pp)
430 return i;
431 return -1;
434 static DWORD umin(DWORD a, DWORD b)
436 return a < b ? a : b;
439 static DWORD umax(DWORD a, DWORD b)
441 return a < b ? b : a;
444 static DWORD pe_file_align(struct pe_info *pe, DWORD n)
446 return (n + (pe->file_align - 1)) & ~(pe->file_align - 1);
449 static DWORD pe_virtual_align(struct pe_info *pe, DWORD n)
451 return (n + (pe->section_align - 1)) & ~(pe->section_align - 1);
454 static void pe_align_section(Section *s, int a)
456 int i = s->data_offset & (a-1);
457 if (i)
458 section_ptr_add(s, a - i);
461 static void pe_set_datadir(struct pe_header *hdr, int dir, DWORD addr, DWORD size)
463 hdr->opthdr.DataDirectory[dir].VirtualAddress = addr;
464 hdr->opthdr.DataDirectory[dir].Size = size;
467 struct pe_file {
468 FILE *op;
469 DWORD sum;
470 unsigned pos;
473 static int pe_fwrite(void *data, int len, struct pe_file *pf)
475 WORD *p = data;
476 DWORD sum;
477 int ret, i;
478 pf->pos += (ret = fwrite(data, 1, len, pf->op));
479 sum = pf->sum;
480 for (i = len; i > 0; i -= 2) {
481 sum += (i >= 2) ? *p++ : *(BYTE*)p;
482 sum = (sum + (sum >> 16)) & 0xFFFF;
484 pf->sum = sum;
485 return len == ret ? 0 : -1;
488 static void pe_fpad(struct pe_file *pf, DWORD new_pos)
490 char buf[256];
491 int n, diff = new_pos - pf->pos;
492 memset(buf, 0, sizeof buf);
493 while (diff > 0) {
494 diff -= n = umin(diff, sizeof buf);
495 fwrite(buf, n, 1, pf->op);
497 pf->pos = new_pos;
500 /*----------------------------------------------------------------------------*/
501 static int pe_write(struct pe_info *pe)
503 static const struct pe_header pe_template = {
505 /* IMAGE_DOS_HEADER doshdr */
506 0x5A4D, /*WORD e_magic; Magic number */
507 0x0090, /*WORD e_cblp; Bytes on last page of file */
508 0x0003, /*WORD e_cp; Pages in file */
509 0x0000, /*WORD e_crlc; Relocations */
511 0x0004, /*WORD e_cparhdr; Size of header in paragraphs */
512 0x0000, /*WORD e_minalloc; Minimum extra paragraphs needed */
513 0xFFFF, /*WORD e_maxalloc; Maximum extra paragraphs needed */
514 0x0000, /*WORD e_ss; Initial (relative) SS value */
516 0x00B8, /*WORD e_sp; Initial SP value */
517 0x0000, /*WORD e_csum; Checksum */
518 0x0000, /*WORD e_ip; Initial IP value */
519 0x0000, /*WORD e_cs; Initial (relative) CS value */
520 0x0040, /*WORD e_lfarlc; File address of relocation table */
521 0x0000, /*WORD e_ovno; Overlay number */
522 {0,0,0,0}, /*WORD e_res[4]; Reserved words */
523 0x0000, /*WORD e_oemid; OEM identifier (for e_oeminfo) */
524 0x0000, /*WORD e_oeminfo; OEM information; e_oemid specific */
525 {0,0,0,0,0,0,0,0,0,0}, /*WORD e_res2[10]; Reserved words */
526 0x00000080 /*DWORD e_lfanew; File address of new exe header */
528 /* BYTE dosstub[0x40] */
529 /* 14 code bytes + "This program cannot be run in DOS mode.\r\r\n$" + 6 * 0x00 */
530 0x0e,0x1f,0xba,0x0e,0x00,0xb4,0x09,0xcd,0x21,0xb8,0x01,0x4c,0xcd,0x21,0x54,0x68,
531 0x69,0x73,0x20,0x70,0x72,0x6f,0x67,0x72,0x61,0x6d,0x20,0x63,0x61,0x6e,0x6e,0x6f,
532 0x74,0x20,0x62,0x65,0x20,0x72,0x75,0x6e,0x20,0x69,0x6e,0x20,0x44,0x4f,0x53,0x20,
533 0x6d,0x6f,0x64,0x65,0x2e,0x0d,0x0d,0x0a,0x24,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
535 0x00004550, /* DWORD nt_sig = IMAGE_NT_SIGNATURE */
537 /* IMAGE_FILE_HEADER filehdr */
538 IMAGE_FILE_MACHINE, /*WORD Machine; */
539 0x0003, /*WORD NumberOfSections; */
540 0x00000000, /*DWORD TimeDateStamp; */
541 0x00000000, /*DWORD PointerToSymbolTable; */
542 0x00000000, /*DWORD NumberOfSymbols; */
543 #if defined(TCC_TARGET_X86_64)
544 0x00F0, /*WORD SizeOfOptionalHeader; */
545 0x022F /*WORD Characteristics; */
546 #define CHARACTERISTICS_DLL 0x222E
547 #elif defined(TCC_TARGET_I386)
548 0x00E0, /*WORD SizeOfOptionalHeader; */
549 0x030F /*WORD Characteristics; */
550 #define CHARACTERISTICS_DLL 0x230E
551 #elif defined(TCC_TARGET_ARM)
552 0x00E0, /*WORD SizeOfOptionalHeader; */
553 0x010F, /*WORD Characteristics; */
554 #define CHARACTERISTICS_DLL 0x230F
555 #endif
557 /* IMAGE_OPTIONAL_HEADER opthdr */
558 /* Standard fields. */
559 #ifdef TCC_TARGET_X86_64
560 0x020B, /*WORD Magic; */
561 #else
562 0x010B, /*WORD Magic; */
563 #endif
564 0x06, /*BYTE MajorLinkerVersion; */
565 0x00, /*BYTE MinorLinkerVersion; */
566 0x00000000, /*DWORD SizeOfCode; */
567 0x00000000, /*DWORD SizeOfInitializedData; */
568 0x00000000, /*DWORD SizeOfUninitializedData; */
569 0x00000000, /*DWORD AddressOfEntryPoint; */
570 0x00000000, /*DWORD BaseOfCode; */
571 #ifndef TCC_TARGET_X86_64
572 0x00000000, /*DWORD BaseOfData; */
573 #endif
574 /* NT additional fields. */
575 #if defined(TCC_TARGET_ARM)
576 0x00100000, /*DWORD ImageBase; */
577 #else
578 0x00400000, /*DWORD ImageBase; */
579 #endif
580 0x00001000, /*DWORD SectionAlignment; */
581 0x00000200, /*DWORD FileAlignment; */
582 0x0004, /*WORD MajorOperatingSystemVersion; */
583 0x0000, /*WORD MinorOperatingSystemVersion; */
584 0x0000, /*WORD MajorImageVersion; */
585 0x0000, /*WORD MinorImageVersion; */
586 0x0004, /*WORD MajorSubsystemVersion; */
587 0x0000, /*WORD MinorSubsystemVersion; */
588 0x00000000, /*DWORD Win32VersionValue; */
589 0x00000000, /*DWORD SizeOfImage; */
590 0x00000200, /*DWORD SizeOfHeaders; */
591 0x00000000, /*DWORD CheckSum; */
592 0x0002, /*WORD Subsystem; */
593 0x0000, /*WORD DllCharacteristics; */
594 0x00100000, /*DWORD SizeOfStackReserve; */
595 0x00001000, /*DWORD SizeOfStackCommit; */
596 0x00100000, /*DWORD SizeOfHeapReserve; */
597 0x00001000, /*DWORD SizeOfHeapCommit; */
598 0x00000000, /*DWORD LoaderFlags; */
599 0x00000010, /*DWORD NumberOfRvaAndSizes; */
601 /* IMAGE_DATA_DIRECTORY DataDirectory[16]; */
602 {{0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0},
603 {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}}
606 struct pe_header pe_header = pe_template;
608 int i;
609 struct pe_file pf = {0};
610 DWORD file_offset;
611 struct section_info *si;
612 IMAGE_SECTION_HEADER *psh;
613 TCCState *s1 = pe->s1;
615 pf.op = fopen(pe->filename, "wb");
616 if (NULL == pf.op) {
617 tcc_error_noabort("could not write '%s': %s", pe->filename, strerror(errno));
618 return -1;
621 pe->sizeofheaders = pe_file_align(pe,
622 sizeof (struct pe_header)
623 + pe->sec_count * sizeof (IMAGE_SECTION_HEADER)
626 file_offset = pe->sizeofheaders;
628 if (2 == pe->s1->verbose)
629 printf("-------------------------------"
630 "\n virt file size section" "\n");
631 for (i = 0; i < pe->sec_count; ++i) {
632 DWORD addr, size;
633 const char *sh_name;
635 si = pe->sec_info[i];
636 sh_name = si->name;
637 addr = si->sh_addr - pe->imagebase;
638 size = si->sh_size;
639 psh = &si->ish;
641 if (2 == pe->s1->verbose)
642 printf("%6x %6x %6x %s\n",
643 (unsigned)addr, (unsigned)file_offset, (unsigned)size, sh_name);
645 switch (si->cls) {
646 case sec_text:
647 if (!pe_header.opthdr.BaseOfCode)
648 pe_header.opthdr.BaseOfCode = addr;
649 break;
651 case sec_data:
652 #ifndef TCC_TARGET_X86_64
653 if (!pe_header.opthdr.BaseOfData)
654 pe_header.opthdr.BaseOfData = addr;
655 #endif
656 break;
658 case sec_bss:
659 break;
661 case sec_reloc:
662 pe_set_datadir(&pe_header, IMAGE_DIRECTORY_ENTRY_BASERELOC, addr, size);
663 break;
665 case sec_rsrc:
666 pe_set_datadir(&pe_header, IMAGE_DIRECTORY_ENTRY_RESOURCE, addr, size);
667 break;
669 case sec_pdata:
670 pe_set_datadir(&pe_header, IMAGE_DIRECTORY_ENTRY_EXCEPTION, addr, size);
671 break;
674 if (pe->imp_size) {
675 pe_set_datadir(&pe_header, IMAGE_DIRECTORY_ENTRY_IMPORT,
676 pe->imp_offs, pe->imp_size);
677 pe_set_datadir(&pe_header, IMAGE_DIRECTORY_ENTRY_IAT,
678 pe->iat_offs, pe->iat_size);
680 if (pe->exp_size) {
681 pe_set_datadir(&pe_header, IMAGE_DIRECTORY_ENTRY_EXPORT,
682 pe->exp_offs, pe->exp_size);
685 memcpy(psh->Name, sh_name, umin(strlen(sh_name), sizeof psh->Name));
687 psh->Characteristics = si->pe_flags;
688 psh->VirtualAddress = addr;
689 psh->Misc.VirtualSize = size;
690 pe_header.opthdr.SizeOfImage =
691 umax(pe_virtual_align(pe, size + addr), pe_header.opthdr.SizeOfImage);
693 if (si->data_size) {
694 psh->PointerToRawData = file_offset;
695 file_offset = pe_file_align(pe, file_offset + si->data_size);
696 psh->SizeOfRawData = file_offset - psh->PointerToRawData;
697 if (si->cls == sec_text)
698 pe_header.opthdr.SizeOfCode += psh->SizeOfRawData;
699 else
700 pe_header.opthdr.SizeOfInitializedData += psh->SizeOfRawData;
704 //pe_header.filehdr.TimeDateStamp = time(NULL);
705 pe_header.filehdr.NumberOfSections = pe->sec_count;
706 pe_header.opthdr.AddressOfEntryPoint = pe->start_addr;
707 pe_header.opthdr.SizeOfHeaders = pe->sizeofheaders;
708 pe_header.opthdr.ImageBase = pe->imagebase;
709 pe_header.opthdr.Subsystem = pe->subsystem;
710 if (pe->s1->pe_stack_size)
711 pe_header.opthdr.SizeOfStackReserve = pe->s1->pe_stack_size;
712 if (PE_DLL == pe->type)
713 pe_header.filehdr.Characteristics = CHARACTERISTICS_DLL;
714 pe_header.filehdr.Characteristics |= pe->s1->pe_characteristics;
716 pe_fwrite(&pe_header, sizeof pe_header, &pf);
717 for (i = 0; i < pe->sec_count; ++i)
718 pe_fwrite(&pe->sec_info[i]->ish, sizeof(IMAGE_SECTION_HEADER), &pf);
720 file_offset = pe->sizeofheaders;
721 for (i = 0; i < pe->sec_count; ++i) {
722 Section *s;
723 si = pe->sec_info[i];
724 for (s = si->sec; s; s = s->prev) {
725 pe_fpad(&pf, file_offset);
726 pe_fwrite(s->data, s->data_offset, &pf);
727 if (s->prev)
728 file_offset += s->prev->sh_addr - s->sh_addr;
730 file_offset = si->ish.PointerToRawData + si->ish.SizeOfRawData;
731 pe_fpad(&pf, file_offset);
734 pf.sum += file_offset;
735 fseek(pf.op, offsetof(struct pe_header, opthdr.CheckSum), SEEK_SET);
736 pe_fwrite(&pf.sum, sizeof (DWORD), &pf);
738 fclose (pf.op);
739 #ifndef _WIN32
740 chmod(pe->filename, 0777);
741 #endif
743 if (2 == pe->s1->verbose)
744 printf("-------------------------------\n");
745 if (pe->s1->verbose)
746 printf("<- %s (%u bytes)\n", pe->filename, (unsigned)file_offset);
748 return 0;
751 /*----------------------------------------------------------------------------*/
753 static struct import_symbol *pe_add_import(struct pe_info *pe, int sym_index)
755 int i;
756 int dll_index;
757 struct pe_import_info *p;
758 struct import_symbol *s;
759 ElfW(Sym) *isym;
761 isym = (ElfW(Sym) *)pe->s1->dynsymtab_section->data + sym_index;
762 dll_index = isym->st_size;
764 i = dynarray_assoc ((void**)pe->imp_info, pe->imp_count, dll_index);
765 if (-1 != i) {
766 p = pe->imp_info[i];
767 goto found_dll;
769 p = tcc_mallocz(sizeof *p);
770 p->dll_index = dll_index;
771 dynarray_add(&pe->imp_info, &pe->imp_count, p);
773 found_dll:
774 i = dynarray_assoc ((void**)p->symbols, p->sym_count, sym_index);
775 if (-1 != i)
776 return p->symbols[i];
778 s = tcc_mallocz(sizeof *s);
779 dynarray_add(&p->symbols, &p->sym_count, s);
780 s->sym_index = sym_index;
781 return s;
784 void pe_free_imports(struct pe_info *pe)
786 int i;
787 for (i = 0; i < pe->imp_count; ++i) {
788 struct pe_import_info *p = pe->imp_info[i];
789 dynarray_reset(&p->symbols, &p->sym_count);
791 dynarray_reset(&pe->imp_info, &pe->imp_count);
794 /*----------------------------------------------------------------------------*/
795 static void pe_build_imports(struct pe_info *pe)
797 int thk_ptr, ent_ptr, dll_ptr, sym_cnt, i;
798 DWORD rva_base = pe->thunk->sh_addr - pe->imagebase;
799 int ndlls = pe->imp_count;
800 TCCState *s1 = pe->s1;
802 for (sym_cnt = i = 0; i < ndlls; ++i)
803 sym_cnt += pe->imp_info[i]->sym_count;
805 if (0 == sym_cnt)
806 return;
808 pe_align_section(pe->thunk, 16);
809 pe->imp_size = (ndlls + 1) * sizeof(IMAGE_IMPORT_DESCRIPTOR);
810 pe->iat_size = (sym_cnt + ndlls) * sizeof(ADDR3264);
811 dll_ptr = pe->thunk->data_offset;
812 thk_ptr = dll_ptr + pe->imp_size;
813 ent_ptr = thk_ptr + pe->iat_size;
814 pe->imp_offs = dll_ptr + rva_base;
815 pe->iat_offs = thk_ptr + rva_base;
816 section_ptr_add(pe->thunk, pe->imp_size + 2*pe->iat_size);
818 for (i = 0; i < pe->imp_count; ++i) {
819 IMAGE_IMPORT_DESCRIPTOR *hdr;
820 int k, n, dllindex;
821 ADDR3264 v;
822 struct pe_import_info *p = pe->imp_info[i];
823 const char *name;
824 DLLReference *dllref;
826 dllindex = p->dll_index;
827 if (dllindex)
828 name = (dllref = pe->s1->loaded_dlls[dllindex-1])->name;
829 else
830 name = "", dllref = NULL;
832 /* put the dll name into the import header */
833 v = put_elf_str(pe->thunk, name);
834 hdr = (IMAGE_IMPORT_DESCRIPTOR*)(pe->thunk->data + dll_ptr);
835 hdr->FirstThunk = thk_ptr + rva_base;
836 hdr->OriginalFirstThunk = ent_ptr + rva_base;
837 hdr->Name = v + rva_base;
839 for (k = 0, n = p->sym_count; k <= n; ++k) {
840 if (k < n) {
841 int iat_index = p->symbols[k]->iat_index;
842 int sym_index = p->symbols[k]->sym_index;
843 ElfW(Sym) *imp_sym = (ElfW(Sym) *)pe->s1->dynsymtab_section->data + sym_index;
844 ElfW(Sym) *org_sym = (ElfW(Sym) *)symtab_section->data + iat_index;
845 const char *name = (char*)pe->s1->dynsymtab_section->link->data + imp_sym->st_name;
846 int ordinal;
848 org_sym->st_value = thk_ptr;
849 org_sym->st_shndx = pe->thunk->sh_num;
851 if (dllref)
852 v = 0, ordinal = imp_sym->st_value; /* ordinal from pe_load_def */
853 else
854 ordinal = 0, v = imp_sym->st_value; /* address from tcc_add_symbol() */
856 #ifdef TCC_IS_NATIVE
857 if (pe->type == PE_RUN) {
858 if (dllref) {
859 if ( !dllref->handle )
860 dllref->handle = LoadLibrary(dllref->name);
861 v = (ADDR3264)GetProcAddress(dllref->handle, ordinal?(char*)0+ordinal:name);
863 if (!v)
864 tcc_error_noabort("could not resolve symbol '%s'", name);
865 } else
866 #endif
867 if (ordinal) {
868 v = ordinal | (ADDR3264)1 << (sizeof(ADDR3264)*8 - 1);
869 } else {
870 v = pe->thunk->data_offset + rva_base;
871 section_ptr_add(pe->thunk, sizeof(WORD)); /* hint, not used */
872 put_elf_str(pe->thunk, name);
875 } else {
876 v = 0; /* last entry is zero */
879 *(ADDR3264*)(pe->thunk->data+thk_ptr) =
880 *(ADDR3264*)(pe->thunk->data+ent_ptr) = v;
881 thk_ptr += sizeof (ADDR3264);
882 ent_ptr += sizeof (ADDR3264);
884 dll_ptr += sizeof(IMAGE_IMPORT_DESCRIPTOR);
888 /* ------------------------------------------------------------- */
890 struct pe_sort_sym
892 int index;
893 const char *name;
896 static int sym_cmp(const void *va, const void *vb)
898 const char *ca = (*(struct pe_sort_sym**)va)->name;
899 const char *cb = (*(struct pe_sort_sym**)vb)->name;
900 return strcmp(ca, cb);
903 static void pe_build_exports(struct pe_info *pe)
905 ElfW(Sym) *sym;
906 int sym_index, sym_end;
907 DWORD rva_base, base_o, func_o, name_o, ord_o, str_o;
908 IMAGE_EXPORT_DIRECTORY *hdr;
909 int sym_count, ord;
910 struct pe_sort_sym **sorted, *p;
911 TCCState *s1 = pe->s1;
913 FILE *op;
914 char buf[260];
915 const char *dllname;
916 const char *name;
918 rva_base = pe->thunk->sh_addr - pe->imagebase;
919 sym_count = 0, sorted = NULL, op = NULL;
921 sym_end = symtab_section->data_offset / sizeof(ElfW(Sym));
922 for (sym_index = 1; sym_index < sym_end; ++sym_index) {
923 sym = (ElfW(Sym)*)symtab_section->data + sym_index;
924 name = pe_export_name(pe->s1, sym);
925 if ((sym->st_other & ST_PE_EXPORT)
926 /* export only symbols from actually written sections */
927 && pe->s1->sections[sym->st_shndx]->sh_addr) {
928 p = tcc_malloc(sizeof *p);
929 p->index = sym_index;
930 p->name = name;
931 dynarray_add(&sorted, &sym_count, p);
933 #if 0
934 if (sym->st_other & ST_PE_EXPORT)
935 printf("export: %s\n", name);
936 if (sym->st_other & ST_PE_STDCALL)
937 printf("stdcall: %s\n", name);
938 #endif
941 if (0 == sym_count)
942 return;
944 qsort (sorted, sym_count, sizeof *sorted, sym_cmp);
946 pe_align_section(pe->thunk, 16);
947 dllname = tcc_basename(pe->filename);
949 base_o = pe->thunk->data_offset;
950 func_o = base_o + sizeof(IMAGE_EXPORT_DIRECTORY);
951 name_o = func_o + sym_count * sizeof (DWORD);
952 ord_o = name_o + sym_count * sizeof (DWORD);
953 str_o = ord_o + sym_count * sizeof(WORD);
955 hdr = section_ptr_add(pe->thunk, str_o - base_o);
956 hdr->Characteristics = 0;
957 hdr->Base = 1;
958 hdr->NumberOfFunctions = sym_count;
959 hdr->NumberOfNames = sym_count;
960 hdr->AddressOfFunctions = func_o + rva_base;
961 hdr->AddressOfNames = name_o + rva_base;
962 hdr->AddressOfNameOrdinals = ord_o + rva_base;
963 hdr->Name = str_o + rva_base;
964 put_elf_str(pe->thunk, dllname);
966 #if 1
967 /* automatically write exports to <output-filename>.def */
968 pstrcpy(buf, sizeof buf, pe->filename);
969 strcpy(tcc_fileextension(buf), ".def");
970 op = fopen(buf, "wb");
971 if (NULL == op) {
972 tcc_error_noabort("could not create '%s': %s", buf, strerror(errno));
973 } else {
974 fprintf(op, "LIBRARY %s\n\nEXPORTS\n", dllname);
975 if (pe->s1->verbose)
976 printf("<- %s (%d symbol%s)\n", buf, sym_count, &"s"[sym_count < 2]);
978 #endif
980 for (ord = 0; ord < sym_count; ++ord)
982 p = sorted[ord], sym_index = p->index, name = p->name;
983 /* insert actual address later in relocate_section() */
984 put_elf_reloc(symtab_section, pe->thunk,
985 func_o, R_XXX_RELATIVE, sym_index);
986 *(DWORD*)(pe->thunk->data + name_o)
987 = pe->thunk->data_offset + rva_base;
988 *(WORD*)(pe->thunk->data + ord_o)
989 = ord;
990 put_elf_str(pe->thunk, name);
991 func_o += sizeof (DWORD);
992 name_o += sizeof (DWORD);
993 ord_o += sizeof (WORD);
994 if (op)
995 fprintf(op, "%s\n", name);
998 pe->exp_offs = base_o + rva_base;
999 pe->exp_size = pe->thunk->data_offset - base_o;
1000 dynarray_reset(&sorted, &sym_count);
1001 if (op)
1002 fclose(op);
1005 /* ------------------------------------------------------------- */
1006 static void pe_build_reloc (struct pe_info *pe)
1008 DWORD offset, block_ptr, sh_addr, addr;
1009 int count, i;
1010 ElfW_Rel *rel, *rel_end;
1011 Section *s = NULL, *sr;
1012 struct pe_reloc_header *hdr;
1014 sh_addr = offset = block_ptr = count = i = 0;
1015 rel = rel_end = NULL;
1017 for(;;) {
1018 if (rel < rel_end) {
1019 int type = ELFW(R_TYPE)(rel->r_info);
1020 addr = rel->r_offset + sh_addr;
1021 ++ rel;
1022 if (type != REL_TYPE_DIRECT)
1023 continue;
1024 if (count == 0) { /* new block */
1025 block_ptr = pe->reloc->data_offset;
1026 section_ptr_add(pe->reloc, sizeof(struct pe_reloc_header));
1027 offset = addr & 0xFFFFFFFF<<12;
1029 if ((addr -= offset) < (1<<12)) { /* one block spans 4k addresses */
1030 WORD *wp = section_ptr_add(pe->reloc, sizeof (WORD));
1031 *wp = addr | PE_IMAGE_REL<<12;
1032 ++count;
1033 continue;
1035 -- rel;
1037 } else if (s) {
1038 sr = s->reloc;
1039 if (sr) {
1040 rel = (ElfW_Rel *)sr->data;
1041 rel_end = (ElfW_Rel *)(sr->data + sr->data_offset);
1042 sh_addr = s->sh_addr;
1044 s = s->prev;
1045 continue;
1047 } else if (i < pe->sec_count) {
1048 s = pe->sec_info[i]->sec, ++i;
1049 continue;
1051 } else if (!count)
1052 break;
1054 /* fill the last block and ready for a new one */
1055 if (count & 1) /* align for DWORDS */
1056 section_ptr_add(pe->reloc, sizeof(WORD)), ++count;
1057 hdr = (struct pe_reloc_header *)(pe->reloc->data + block_ptr);
1058 hdr -> offset = offset - pe->imagebase;
1059 hdr -> size = count * sizeof(WORD) + sizeof(struct pe_reloc_header);
1060 count = 0;
1064 /* ------------------------------------------------------------- */
1065 static int pe_section_class(Section *s)
1067 int type, flags;
1068 const char *name;
1070 type = s->sh_type;
1071 flags = s->sh_flags;
1072 name = s->name;
1073 if (flags & SHF_ALLOC) {
1074 if (type == SHT_PROGBITS) {
1075 if (flags & SHF_EXECINSTR)
1076 return sec_text;
1077 if (flags & SHF_WRITE)
1078 return sec_data;
1079 if (0 == strcmp(name, ".rsrc"))
1080 return sec_rsrc;
1081 if (0 == strcmp(name, ".iedat"))
1082 return sec_idata;
1083 if (0 == strcmp(name, ".pdata"))
1084 return sec_pdata;
1085 } else if (type == SHT_NOBITS) {
1086 if (flags & SHF_WRITE)
1087 return sec_bss;
1089 } else {
1090 if (0 == strcmp(name, ".reloc"))
1091 return sec_reloc;
1093 if (0 == memcmp(name, ".stab", 5))
1094 return name[5] ? sec_stabstr : sec_stab;
1095 if (flags & SHF_ALLOC)
1096 return sec_other;
1097 return -1;
1100 static int pe_assign_addresses (struct pe_info *pe)
1102 int i, k, o, c;
1103 DWORD addr;
1104 int *section_order;
1105 struct section_info *si;
1106 Section *s;
1108 if (PE_DLL == pe->type)
1109 pe->reloc = new_section(pe->s1, ".reloc", SHT_PROGBITS, 0);
1110 // pe->thunk = new_section(pe->s1, ".iedat", SHT_PROGBITS, SHF_ALLOC);
1112 section_order = tcc_malloc(pe->s1->nb_sections * sizeof (int));
1113 for (o = k = 0 ; k < sec_last; ++k) {
1114 for (i = 1; i < pe->s1->nb_sections; ++i) {
1115 s = pe->s1->sections[i];
1116 if (k == pe_section_class(s))
1117 section_order[o++] = i;
1121 si = NULL;
1122 addr = pe->imagebase + 1;
1124 for (i = 0; i < o; ++i) {
1125 k = section_order[i];
1126 s = pe->s1->sections[k];
1127 c = pe_section_class(s);
1129 if ((c == sec_stab || c == sec_stabstr) && 0 == pe->s1->do_debug)
1130 continue;
1132 #ifdef PE_MERGE_DATA
1133 if (c == sec_bss)
1134 c = sec_data;
1135 #endif
1136 if (si && c == si->cls) {
1137 /* merge with previous section */
1138 s->sh_addr = addr = ((addr - 1) | (16 - 1)) + 1;
1139 } else {
1140 si = NULL;
1141 s->sh_addr = addr = pe_virtual_align(pe, addr);
1144 if (c == sec_data && NULL == pe->thunk)
1145 pe->thunk = s;
1147 if (s == pe->thunk) {
1148 pe_build_imports(pe);
1149 pe_build_exports(pe);
1151 if (s == pe->reloc)
1152 pe_build_reloc (pe);
1154 if (0 == s->data_offset)
1155 continue;
1157 if (si)
1158 goto add_section;
1160 si = tcc_mallocz(sizeof *si);
1161 dynarray_add(&pe->sec_info, &pe->sec_count, si);
1163 strcpy(si->name, s->name);
1164 si->cls = c;
1165 si->sh_addr = addr;
1167 si->pe_flags = IMAGE_SCN_MEM_READ;
1168 if (s->sh_flags & SHF_EXECINSTR)
1169 si->pe_flags |= IMAGE_SCN_MEM_EXECUTE | IMAGE_SCN_CNT_CODE;
1170 else if (s->sh_type == SHT_NOBITS)
1171 si->pe_flags |= IMAGE_SCN_CNT_UNINITIALIZED_DATA;
1172 else
1173 si->pe_flags |= IMAGE_SCN_CNT_INITIALIZED_DATA;
1174 if (s->sh_flags & SHF_WRITE)
1175 si->pe_flags |= IMAGE_SCN_MEM_WRITE;
1176 if (0 == (s->sh_flags & SHF_ALLOC))
1177 si->pe_flags |= IMAGE_SCN_MEM_DISCARDABLE;
1179 add_section:
1180 addr += s->data_offset;
1181 si->sh_size = addr - si->sh_addr;
1182 if (s->sh_type != SHT_NOBITS) {
1183 Section **ps = &si->sec;
1184 while (*ps)
1185 ps = &(*ps)->prev;
1186 *ps = s, s->prev = NULL;
1187 si->data_size = si->sh_size;
1189 //printf("%08x %05x %08x %s\n", si->sh_addr, si->sh_size, si->pe_flags, s->name);
1191 tcc_free(section_order);
1192 #if 0
1193 for (i = 1; i < pe->s1->nb_sections; ++i) {
1194 Section *s = pe->s1->sections[i];
1195 int type = s->sh_type;
1196 int flags = s->sh_flags;
1197 printf("section %-16s %-10s %08x %04x %s,%s,%s\n",
1198 s->name,
1199 type == SHT_PROGBITS ? "progbits" :
1200 type == SHT_NOBITS ? "nobits" :
1201 type == SHT_SYMTAB ? "symtab" :
1202 type == SHT_STRTAB ? "strtab" :
1203 type == SHT_RELX ? "rel" : "???",
1204 s->sh_addr,
1205 s->data_offset,
1206 flags & SHF_ALLOC ? "alloc" : "",
1207 flags & SHF_WRITE ? "write" : "",
1208 flags & SHF_EXECINSTR ? "exec" : ""
1211 pe->s1->verbose = 2;
1212 #endif
1213 return 0;
1216 /*----------------------------------------------------------------------------*/
1218 static int pe_isafunc(TCCState *s1, int sym_index)
1220 Section *sr = text_section->reloc;
1221 ElfW_Rel *rel, *rel_end;
1222 Elf32_Word info = ELF32_R_INFO(sym_index, R_386_PC32);
1223 if (!sr)
1224 return 0;
1225 rel_end = (ElfW_Rel *)(sr->data + sr->data_offset);
1226 for (rel = (ElfW_Rel *)sr->data; rel < rel_end; rel++)
1227 if (rel->r_info == info)
1228 return 1;
1229 return 0;
1232 /*----------------------------------------------------------------------------*/
1233 static int pe_check_symbols(struct pe_info *pe)
1235 ElfW(Sym) *sym;
1236 int sym_index, sym_end;
1237 int ret = 0;
1238 TCCState *s1 = pe->s1;
1240 pe_align_section(text_section, 8);
1242 sym_end = symtab_section->data_offset / sizeof(ElfW(Sym));
1243 for (sym_index = 1; sym_index < sym_end; ++sym_index) {
1245 sym = (ElfW(Sym) *)symtab_section->data + sym_index;
1246 if (sym->st_shndx == SHN_UNDEF) {
1248 const char *name = (char*)symtab_section->link->data + sym->st_name;
1249 unsigned type = ELFW(ST_TYPE)(sym->st_info);
1250 int imp_sym = pe_find_import(pe->s1, sym);
1251 struct import_symbol *is;
1253 if (imp_sym <= 0)
1254 goto not_found;
1256 if (type == STT_NOTYPE) {
1257 /* symbols from assembler have no type, find out which */
1258 if (pe_isafunc(s1, sym_index))
1259 type = STT_FUNC;
1260 else
1261 type = STT_OBJECT;
1264 is = pe_add_import(pe, imp_sym);
1266 if (type == STT_FUNC) {
1267 unsigned long offset = is->thk_offset;
1268 if (offset) {
1269 /* got aliased symbol, like stricmp and _stricmp */
1271 } else {
1272 char buffer[100];
1273 WORD *p;
1275 offset = text_section->data_offset;
1276 /* add the 'jmp IAT[x]' instruction */
1277 #ifdef TCC_TARGET_ARM
1278 p = section_ptr_add(text_section, 8+4); // room for code and address
1279 (*(DWORD*)(p)) = 0xE59FC000; // arm code ldr ip, [pc] ; PC+8+0 = 0001xxxx
1280 (*(DWORD*)(p+2)) = 0xE59CF000; // arm code ldr pc, [ip]
1281 #else
1282 p = section_ptr_add(text_section, 8);
1283 *p = 0x25FF;
1284 #ifdef TCC_TARGET_X86_64
1285 *(DWORD*)(p+1) = (DWORD)-4;
1286 #endif
1287 #endif
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);
1295 #ifdef TCC_TARGET_ARM
1296 put_elf_reloc(symtab_section, text_section,
1297 offset + 8, R_XXX_THUNKFIX, is->iat_index); // offset to IAT position
1298 #else
1299 put_elf_reloc(symtab_section, text_section,
1300 offset + 2, R_XXX_THUNKFIX, is->iat_index);
1301 #endif
1302 is->thk_offset = offset;
1305 /* tcc_realloc might have altered sym's address */
1306 sym = (ElfW(Sym) *)symtab_section->data + sym_index;
1308 /* patch the original symbol */
1309 sym->st_value = offset;
1310 sym->st_shndx = text_section->sh_num;
1311 sym->st_other &= ~ST_PE_EXPORT; /* do not export */
1312 continue;
1315 if (type == STT_OBJECT) { /* data, ptr to that should be */
1316 if (0 == is->iat_index) {
1317 /* original symbol will be patched later in pe_build_imports */
1318 is->iat_index = sym_index;
1319 continue;
1323 not_found:
1324 if (ELFW(ST_BIND)(sym->st_info) == STB_WEAK)
1325 /* STB_WEAK undefined symbols are accepted */
1326 continue;
1327 tcc_error_noabort("undefined symbol '%s'%s", name,
1328 imp_sym < 0 ? ", missing __declspec(dllimport)?":"");
1329 ret = -1;
1331 } else if (pe->s1->rdynamic
1332 && ELFW(ST_BIND)(sym->st_info) != STB_LOCAL) {
1333 /* if -rdynamic option, then export all non local symbols */
1334 sym->st_other |= ST_PE_EXPORT;
1337 return ret;
1340 /*----------------------------------------------------------------------------*/
1341 #ifdef PE_PRINT_SECTIONS
1342 static void pe_print_section(FILE * f, Section * s)
1344 /* just if you're curious */
1345 BYTE *p, *e, b;
1346 int i, n, l, m;
1347 p = s->data;
1348 e = s->data + s->data_offset;
1349 l = e - p;
1351 fprintf(f, "section \"%s\"", s->name);
1352 if (s->link)
1353 fprintf(f, "\nlink \"%s\"", s->link->name);
1354 if (s->reloc)
1355 fprintf(f, "\nreloc \"%s\"", s->reloc->name);
1356 fprintf(f, "\nv_addr %08X", (unsigned)s->sh_addr);
1357 fprintf(f, "\ncontents %08X", (unsigned)l);
1358 fprintf(f, "\n\n");
1360 if (s->sh_type == SHT_NOBITS)
1361 return;
1363 if (0 == l)
1364 return;
1366 if (s->sh_type == SHT_SYMTAB)
1367 m = sizeof(ElfW(Sym));
1368 else if (s->sh_type == SHT_RELX)
1369 m = sizeof(ElfW_Rel);
1370 else
1371 m = 16;
1373 fprintf(f, "%-8s", "offset");
1374 for (i = 0; i < m; ++i)
1375 fprintf(f, " %02x", i);
1376 n = 56;
1378 if (s->sh_type == SHT_SYMTAB || s->sh_type == SHT_RELX) {
1379 const char *fields1[] = {
1380 "name",
1381 "value",
1382 "size",
1383 "bind",
1384 "type",
1385 "other",
1386 "shndx",
1387 NULL
1390 const char *fields2[] = {
1391 "offs",
1392 "type",
1393 "symb",
1394 NULL
1397 const char **p;
1399 if (s->sh_type == SHT_SYMTAB)
1400 p = fields1, n = 106;
1401 else
1402 p = fields2, n = 58;
1404 for (i = 0; p[i]; ++i)
1405 fprintf(f, "%6s", p[i]);
1406 fprintf(f, " symbol");
1409 fprintf(f, "\n");
1410 for (i = 0; i < n; ++i)
1411 fprintf(f, "-");
1412 fprintf(f, "\n");
1414 for (i = 0; i < l;)
1416 fprintf(f, "%08X", i);
1417 for (n = 0; n < m; ++n) {
1418 if (n + i < l)
1419 fprintf(f, " %02X", p[i + n]);
1420 else
1421 fprintf(f, " ");
1424 if (s->sh_type == SHT_SYMTAB) {
1425 ElfW(Sym) *sym = (ElfW(Sym) *) (p + i);
1426 const char *name = s->link->data + sym->st_name;
1427 fprintf(f, " %04X %04X %04X %02X %02X %02X %04X \"%s\"",
1428 (unsigned)sym->st_name,
1429 (unsigned)sym->st_value,
1430 (unsigned)sym->st_size,
1431 (unsigned)ELFW(ST_BIND)(sym->st_info),
1432 (unsigned)ELFW(ST_TYPE)(sym->st_info),
1433 (unsigned)sym->st_other,
1434 (unsigned)sym->st_shndx,
1435 name);
1437 } else if (s->sh_type == SHT_RELX) {
1438 ElfW_Rel *rel = (ElfW_Rel *) (p + i);
1439 ElfW(Sym) *sym =
1440 (ElfW(Sym) *) s->link->data + ELFW(R_SYM)(rel->r_info);
1441 const char *name = s->link->link->data + sym->st_name;
1442 fprintf(f, " %04X %02X %04X \"%s\"",
1443 (unsigned)rel->r_offset,
1444 (unsigned)ELFW(R_TYPE)(rel->r_info),
1445 (unsigned)ELFW(R_SYM)(rel->r_info),
1446 name);
1447 } else {
1448 fprintf(f, " ");
1449 for (n = 0; n < m; ++n) {
1450 if (n + i < l) {
1451 b = p[i + n];
1452 if (b < 32 || b >= 127)
1453 b = '.';
1454 fprintf(f, "%c", b);
1458 i += m;
1459 fprintf(f, "\n");
1461 fprintf(f, "\n\n");
1464 static void pe_print_sections(TCCState *s1, const char *fname)
1466 Section *s;
1467 FILE *f;
1468 int i;
1469 f = fopen(fname, "w");
1470 for (i = 1; i < s1->nb_sections; ++i) {
1471 s = s1->sections[i];
1472 pe_print_section(f, s);
1474 pe_print_section(f, s1->dynsymtab_section);
1475 fclose(f);
1477 #endif
1479 /* ------------------------------------------------------------- */
1480 /* helper function for load/store to insert one more indirection */
1482 #if defined TCC_TARGET_I386 || defined TCC_TARGET_X86_64
1483 ST_FUNC SValue *pe_getimport(SValue *sv, SValue *v2)
1485 int r2;
1486 if ((sv->r & (VT_VALMASK|VT_SYM)) != (VT_CONST|VT_SYM) || (sv->r2 != VT_CONST))
1487 return sv;
1488 if (!sv->sym->a.dllimport)
1489 return sv;
1490 // printf("import %04x %04x %04x %s\n", sv->type.t, sv->sym->type.t, sv->r, get_tok_str(sv->sym->v, NULL));
1491 memset(v2, 0, sizeof *v2);
1492 v2->type.t = VT_PTR;
1493 v2->r = VT_CONST | VT_SYM | VT_LVAL;
1494 v2->sym = sv->sym;
1496 r2 = get_reg(RC_INT);
1497 load(r2, v2);
1498 v2->r = r2;
1499 if ((uint32_t)sv->c.i) {
1500 vpushv(v2);
1501 vpushi(sv->c.i);
1502 gen_opi('+');
1503 *v2 = *vtop--;
1505 v2->type.t = sv->type.t;
1506 v2->r |= sv->r & VT_LVAL;
1507 return v2;
1509 #endif
1511 ST_FUNC int pe_putimport(TCCState *s1, int dllindex, const char *name, addr_t value)
1513 return set_elf_sym(
1514 s1->dynsymtab_section,
1515 value,
1516 dllindex, /* st_size */
1517 ELFW(ST_INFO)(STB_GLOBAL, STT_NOTYPE),
1519 value ? SHN_ABS : SHN_UNDEF,
1520 name
1524 static int add_dllref(TCCState *s1, const char *dllname)
1526 DLLReference *dllref;
1527 int i;
1528 for (i = 0; i < s1->nb_loaded_dlls; ++i)
1529 if (0 == strcmp(s1->loaded_dlls[i]->name, dllname))
1530 return i + 1;
1531 dllref = tcc_mallocz(sizeof(DLLReference) + strlen(dllname));
1532 strcpy(dllref->name, dllname);
1533 dynarray_add(&s1->loaded_dlls, &s1->nb_loaded_dlls, dllref);
1534 return s1->nb_loaded_dlls;
1537 /* ------------------------------------------------------------- */
1539 static int read_mem(int fd, unsigned offset, void *buffer, unsigned len)
1541 lseek(fd, offset, SEEK_SET);
1542 return len == read(fd, buffer, len);
1545 /* ------------------------------------------------------------- */
1547 PUB_FUNC int tcc_get_dllexports(const char *filename, char **pp)
1549 int l, i, n, n0, ret;
1550 char *p;
1551 int fd;
1553 IMAGE_SECTION_HEADER ish;
1554 IMAGE_EXPORT_DIRECTORY ied;
1555 IMAGE_DOS_HEADER dh;
1556 IMAGE_FILE_HEADER ih;
1557 DWORD sig, ref, addr, ptr, namep;
1559 int pef_hdroffset, opt_hdroffset, sec_hdroffset;
1561 n = n0 = 0;
1562 p = NULL;
1563 ret = -1;
1565 fd = open(filename, O_RDONLY | O_BINARY);
1566 if (fd < 0)
1567 goto the_end_1;
1568 ret = 1;
1569 if (!read_mem(fd, 0, &dh, sizeof dh))
1570 goto the_end;
1571 if (!read_mem(fd, dh.e_lfanew, &sig, sizeof sig))
1572 goto the_end;
1573 if (sig != 0x00004550)
1574 goto the_end;
1575 pef_hdroffset = dh.e_lfanew + sizeof sig;
1576 if (!read_mem(fd, pef_hdroffset, &ih, sizeof ih))
1577 goto the_end;
1578 opt_hdroffset = pef_hdroffset + sizeof ih;
1579 if (ih.Machine == 0x014C) {
1580 IMAGE_OPTIONAL_HEADER32 oh;
1581 sec_hdroffset = opt_hdroffset + sizeof oh;
1582 if (!read_mem(fd, opt_hdroffset, &oh, sizeof oh))
1583 goto the_end;
1584 if (IMAGE_DIRECTORY_ENTRY_EXPORT >= oh.NumberOfRvaAndSizes)
1585 goto the_end_0;
1586 addr = oh.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress;
1587 } else if (ih.Machine == 0x8664) {
1588 IMAGE_OPTIONAL_HEADER64 oh;
1589 sec_hdroffset = opt_hdroffset + sizeof oh;
1590 if (!read_mem(fd, opt_hdroffset, &oh, sizeof oh))
1591 goto the_end;
1592 if (IMAGE_DIRECTORY_ENTRY_EXPORT >= oh.NumberOfRvaAndSizes)
1593 goto the_end_0;
1594 addr = oh.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress;
1595 } else
1596 goto the_end;
1598 //printf("addr: %08x\n", addr);
1599 for (i = 0; i < ih.NumberOfSections; ++i) {
1600 if (!read_mem(fd, sec_hdroffset + i * sizeof ish, &ish, sizeof ish))
1601 goto the_end;
1602 //printf("vaddr: %08x\n", ish.VirtualAddress);
1603 if (addr >= ish.VirtualAddress && addr < ish.VirtualAddress + ish.SizeOfRawData)
1604 goto found;
1606 goto the_end_0;
1608 found:
1609 ref = ish.VirtualAddress - ish.PointerToRawData;
1610 if (!read_mem(fd, addr - ref, &ied, sizeof ied))
1611 goto the_end;
1613 namep = ied.AddressOfNames - ref;
1614 for (i = 0; i < ied.NumberOfNames; ++i) {
1615 if (!read_mem(fd, namep, &ptr, sizeof ptr))
1616 goto the_end;
1617 namep += sizeof ptr;
1618 for (l = 0;;) {
1619 if (n+1 >= n0)
1620 p = tcc_realloc(p, n0 = n0 ? n0 * 2 : 256);
1621 if (!read_mem(fd, ptr - ref + l++, p + n, 1)) {
1622 tcc_free(p), p = NULL;
1623 goto the_end;
1625 if (p[n++] == 0)
1626 break;
1629 if (p)
1630 p[n] = 0;
1631 the_end_0:
1632 ret = 0;
1633 the_end:
1634 close(fd);
1635 the_end_1:
1636 *pp = p;
1637 return ret;
1640 /* -------------------------------------------------------------
1641 * This is for compiled windows resources in 'coff' format
1642 * as generated by 'windres.exe -O coff ...'.
1645 static int pe_load_res(TCCState *s1, int fd)
1647 struct pe_rsrc_header hdr;
1648 Section *rsrc_section;
1649 int i, ret = -1, sym_index;
1650 BYTE *ptr;
1651 unsigned offs;
1653 if (!read_mem(fd, 0, &hdr, sizeof hdr))
1654 goto quit;
1656 if (hdr.filehdr.Machine != IMAGE_FILE_MACHINE
1657 || hdr.filehdr.NumberOfSections != 1
1658 || strcmp((char*)hdr.sectionhdr.Name, ".rsrc") != 0)
1659 goto quit;
1661 rsrc_section = new_section(s1, ".rsrc", SHT_PROGBITS, SHF_ALLOC);
1662 ptr = section_ptr_add(rsrc_section, hdr.sectionhdr.SizeOfRawData);
1663 offs = hdr.sectionhdr.PointerToRawData;
1664 if (!read_mem(fd, offs, ptr, hdr.sectionhdr.SizeOfRawData))
1665 goto quit;
1666 offs = hdr.sectionhdr.PointerToRelocations;
1667 sym_index = put_elf_sym(symtab_section, 0, 0, 0, 0, rsrc_section->sh_num, ".rsrc");
1668 for (i = 0; i < hdr.sectionhdr.NumberOfRelocations; ++i) {
1669 struct pe_rsrc_reloc rel;
1670 if (!read_mem(fd, offs, &rel, sizeof rel))
1671 goto quit;
1672 // printf("rsrc_reloc: %x %x %x\n", rel.offset, rel.size, rel.type);
1673 if (rel.type != RSRC_RELTYPE)
1674 goto quit;
1675 put_elf_reloc(symtab_section, rsrc_section,
1676 rel.offset, R_XXX_RELATIVE, sym_index);
1677 offs += sizeof rel;
1679 ret = 0;
1680 quit:
1681 return ret;
1684 /* ------------------------------------------------------------- */
1686 static char *trimfront(char *p)
1688 while (*p && (unsigned char)*p <= ' ')
1689 ++p;
1690 return p;
1693 static char *trimback(char *a, char *e)
1695 while (e > a && (unsigned char)e[-1] <= ' ')
1696 --e;
1697 *e = 0;;
1698 return a;
1701 /* ------------------------------------------------------------- */
1702 static int pe_load_def(TCCState *s1, int fd)
1704 int state = 0, ret = -1, dllindex = 0, ord;
1705 char line[400], dllname[80], *p, *x;
1706 FILE *fp;
1708 fp = fdopen(dup(fd), "rb");
1709 while (fgets(line, sizeof line, fp))
1711 p = trimfront(trimback(line, strchr(line, 0)));
1712 if (0 == *p || ';' == *p)
1713 continue;
1715 switch (state) {
1716 case 0:
1717 if (0 != strnicmp(p, "LIBRARY", 7))
1718 goto quit;
1719 pstrcpy(dllname, sizeof dllname, trimfront(p+7));
1720 ++state;
1721 continue;
1723 case 1:
1724 if (0 != stricmp(p, "EXPORTS"))
1725 goto quit;
1726 ++state;
1727 continue;
1729 case 2:
1730 dllindex = add_dllref(s1, dllname);
1731 ++state;
1732 /* fall through */
1733 default:
1734 /* get ordinal and will store in sym->st_value */
1735 ord = 0;
1736 x = strchr(p, ' ');
1737 if (x) {
1738 *x = 0, x = strrchr(x + 1, '@');
1739 if (x) {
1740 char *d;
1741 ord = (int)strtol(x + 1, &d, 10);
1742 if (*d)
1743 ord = 0;
1746 pe_putimport(s1, dllindex, p, ord);
1747 continue;
1750 ret = 0;
1751 quit:
1752 fclose(fp);
1753 return ret;
1756 /* ------------------------------------------------------------- */
1757 static int pe_load_dll(TCCState *s1, const char *filename)
1759 char *p, *q;
1760 int index, ret;
1762 ret = tcc_get_dllexports(filename, &p);
1763 if (ret) {
1764 return -1;
1765 } else if (p) {
1766 index = add_dllref(s1, tcc_basename(filename));
1767 for (q = p; *q; q += 1 + strlen(q))
1768 pe_putimport(s1, index, q, 0);
1769 tcc_free(p);
1771 return 0;
1774 /* ------------------------------------------------------------- */
1775 ST_FUNC int pe_load_file(struct TCCState *s1, const char *filename, int fd)
1777 int ret = -1;
1778 char buf[10];
1779 if (0 == strcmp(tcc_fileextension(filename), ".def"))
1780 ret = pe_load_def(s1, fd);
1781 else if (pe_load_res(s1, fd) == 0)
1782 ret = 0;
1783 else if (read_mem(fd, 0, buf, 4) && 0 == memcmp(buf, "MZ", 2))
1784 ret = pe_load_dll(s1, filename);
1785 return ret;
1788 /* ------------------------------------------------------------- */
1789 #ifdef TCC_TARGET_X86_64
1790 static unsigned pe_add_uwwind_info(TCCState *s1)
1792 if (NULL == s1->uw_pdata) {
1793 s1->uw_pdata = find_section(s1, ".pdata");
1794 s1->uw_pdata->sh_addralign = 4;
1796 if (0 == s1->uw_sym)
1797 s1->uw_sym = put_elf_sym(symtab_section, 0, 0, 0, 0, text_section->sh_num, ".uw_base");
1798 if (0 == s1->uw_offs) {
1799 /* As our functions all have the same stackframe, we use one entry for all */
1800 static const unsigned char uw_info[] = {
1801 0x01, // UBYTE: 3 Version , UBYTE: 5 Flags
1802 0x04, // UBYTE Size of prolog
1803 0x02, // UBYTE Count of unwind codes
1804 0x05, // UBYTE: 4 Frame Register (rbp), UBYTE: 4 Frame Register offset (scaled)
1805 // USHORT * n Unwind codes array
1806 // 0x0b, 0x01, 0xff, 0xff, // stack size
1807 0x04, 0x03, // set frame ptr (mov rsp -> rbp)
1808 0x01, 0x50 // push reg (rbp)
1811 Section *s = text_section;
1812 unsigned char *p;
1814 section_ptr_add(s, -s->data_offset & 3); /* align */
1815 s1->uw_offs = s->data_offset;
1816 p = section_ptr_add(s, sizeof uw_info);
1817 memcpy(p, uw_info, sizeof uw_info);
1820 return s1->uw_offs;
1823 ST_FUNC void pe_add_unwind_data(unsigned start, unsigned end, unsigned stack)
1825 TCCState *s1 = tcc_state;
1826 Section *pd;
1827 unsigned o, n, d;
1828 struct /* _RUNTIME_FUNCTION */ {
1829 DWORD BeginAddress;
1830 DWORD EndAddress;
1831 DWORD UnwindData;
1832 } *p;
1834 d = pe_add_uwwind_info(s1);
1835 pd = s1->uw_pdata;
1836 o = pd->data_offset;
1837 p = section_ptr_add(pd, sizeof *p);
1839 /* record this function */
1840 p->BeginAddress = start;
1841 p->EndAddress = end;
1842 p->UnwindData = d;
1844 /* put relocations on it */
1845 for (n = o + sizeof *p; o < n; o += sizeof p->BeginAddress)
1846 put_elf_reloc(symtab_section, pd, o, R_XXX_RELATIVE, s1->uw_sym);
1848 #endif
1849 /* ------------------------------------------------------------- */
1850 #ifdef TCC_TARGET_X86_64
1851 #define PE_STDSYM(n,s) n
1852 #else
1853 #define PE_STDSYM(n,s) "_" n s
1854 #endif
1856 static void tcc_add_support(TCCState *s1, const char *filename)
1858 if (tcc_add_dll(s1, filename, 0) < 0)
1859 tcc_error_noabort("%s not found", filename);
1862 static void pe_add_runtime(TCCState *s1, struct pe_info *pe)
1864 const char *start_symbol;
1865 int pe_type = 0;
1866 int unicode_entry = 0;
1868 if (find_elf_sym(symtab_section, PE_STDSYM("WinMain","@16")))
1869 pe_type = PE_GUI;
1870 else
1871 if (find_elf_sym(symtab_section, PE_STDSYM("wWinMain","@16"))) {
1872 pe_type = PE_GUI;
1873 unicode_entry = PE_GUI;
1875 else
1876 if (TCC_OUTPUT_DLL == s1->output_type) {
1877 pe_type = PE_DLL;
1879 else {
1880 pe_type = PE_EXE;
1881 if (find_elf_sym(symtab_section, "wmain"))
1882 unicode_entry = PE_EXE;
1885 start_symbol =
1886 TCC_OUTPUT_MEMORY == s1->output_type
1887 ? PE_GUI == pe_type ? (unicode_entry ? "__runwwinmain" : "__runwinmain")
1888 : (unicode_entry ? "__runwmain" : "__runmain")
1889 : PE_DLL == pe_type ? PE_STDSYM("__dllstart","@12")
1890 : PE_GUI == pe_type ? (unicode_entry ? "__wwinstart": "__winstart")
1891 : (unicode_entry ? "__wstart" : "__start")
1894 if (!s1->leading_underscore || strchr(start_symbol, '@'))
1895 ++start_symbol;
1897 #ifdef CONFIG_TCC_BACKTRACE
1898 if (s1->do_backtrace) {
1899 #ifdef CONFIG_TCC_BCHECK
1900 if (s1->do_bounds_check && s1->output_type != TCC_OUTPUT_DLL)
1901 tcc_add_support(s1, "bcheck.o");
1902 #endif
1903 if (s1->output_type == TCC_OUTPUT_EXE)
1904 tcc_add_support(s1, "bt-exe.o");
1905 if (s1->output_type == TCC_OUTPUT_DLL)
1906 tcc_add_support(s1, "bt-dll.o");
1907 if (s1->output_type != TCC_OUTPUT_DLL)
1908 tcc_add_support(s1, "bt-log.o");
1909 if (s1->output_type != TCC_OUTPUT_MEMORY)
1910 tcc_add_btstub(s1);
1912 #endif
1914 /* grab the startup code from libtcc1.a */
1915 #ifdef TCC_IS_NATIVE
1916 if (TCC_OUTPUT_MEMORY != s1->output_type || s1->runtime_main)
1917 #endif
1918 set_global_sym(s1, start_symbol, NULL, 0);
1920 if (0 == s1->nostdlib) {
1921 static const char *libs[] = {
1922 "msvcrt", "kernel32", "", "user32", "gdi32", NULL
1924 const char **pp, *p;
1925 tcc_add_support(s1, TCC_LIBTCC1);
1926 for (pp = libs; 0 != (p = *pp); ++pp) {
1927 if (*p)
1928 tcc_add_library_err(s1, p);
1929 else if (PE_DLL != pe_type && PE_GUI != pe_type)
1930 break;
1934 /* need this for 'tccelf.c:relocate_section()' */
1935 if (TCC_OUTPUT_DLL == s1->output_type)
1936 s1->output_type = TCC_OUTPUT_EXE;
1937 if (TCC_OUTPUT_MEMORY == s1->output_type)
1938 pe_type = PE_RUN;
1939 pe->type = pe_type;
1940 pe->start_symbol = start_symbol;
1943 static void pe_set_options(TCCState * s1, struct pe_info *pe)
1945 if (PE_DLL == pe->type) {
1946 /* XXX: check if is correct for arm-pe target */
1947 pe->imagebase = 0x10000000;
1948 } else {
1949 #if defined(TCC_TARGET_ARM)
1950 pe->imagebase = 0x00010000;
1951 #else
1952 pe->imagebase = 0x00400000;
1953 #endif
1956 #if defined(TCC_TARGET_ARM)
1957 /* we use "console" subsystem by default */
1958 pe->subsystem = 9;
1959 #else
1960 if (PE_DLL == pe->type || PE_GUI == pe->type)
1961 pe->subsystem = 2;
1962 else
1963 pe->subsystem = 3;
1964 #endif
1965 /* Allow override via -Wl,-subsystem=... option */
1966 if (s1->pe_subsystem != 0)
1967 pe->subsystem = s1->pe_subsystem;
1969 /* set default file/section alignment */
1970 if (pe->subsystem == 1) {
1971 pe->section_align = 0x20;
1972 pe->file_align = 0x20;
1973 } else {
1974 pe->section_align = 0x1000;
1975 pe->file_align = 0x200;
1978 if (s1->section_align != 0)
1979 pe->section_align = s1->section_align;
1980 if (s1->pe_file_align != 0)
1981 pe->file_align = s1->pe_file_align;
1983 if ((pe->subsystem >= 10) && (pe->subsystem <= 12))
1984 pe->imagebase = 0;
1986 if (s1->has_text_addr)
1987 pe->imagebase = s1->text_addr;
1990 ST_FUNC int pe_output_file(TCCState *s1, const char *filename)
1992 int ret;
1993 struct pe_info pe;
1994 int i;
1996 memset(&pe, 0, sizeof pe);
1997 pe.filename = filename;
1998 pe.s1 = s1;
1999 s1->filetype = 0;
2001 #ifdef CONFIG_TCC_BCHECK
2002 tcc_add_bcheck(s1);
2003 #endif
2004 tcc_add_pragma_libs(s1);
2005 pe_add_runtime(s1, &pe);
2006 resolve_common_syms(s1);
2007 pe_set_options(s1, &pe);
2009 ret = pe_check_symbols(&pe);
2010 if (ret)
2012 else if (filename) {
2013 pe_assign_addresses(&pe);
2014 relocate_syms(s1, s1->symtab, 0);
2015 s1->pe_imagebase = pe.imagebase;
2016 for (i = 1; i < s1->nb_sections; ++i) {
2017 Section *s = s1->sections[i];
2018 if (s->reloc) {
2019 relocate_section(s1, s);
2022 pe.start_addr = (DWORD)
2023 ((uintptr_t)tcc_get_symbol_err(s1, pe.start_symbol)
2024 - pe.imagebase);
2025 if (s1->nb_errors)
2026 ret = -1;
2027 else
2028 ret = pe_write(&pe);
2029 dynarray_reset(&pe.sec_info, &pe.sec_count);
2030 } else {
2031 #ifdef TCC_IS_NATIVE
2032 pe.thunk = data_section;
2033 pe_build_imports(&pe);
2034 s1->runtime_main = pe.start_symbol;
2035 #ifdef TCC_TARGET_X86_64
2036 s1->uw_pdata = find_section(s1, ".pdata");
2037 #endif
2038 #endif
2041 pe_free_imports(&pe);
2043 #ifdef PE_PRINT_SECTIONS
2044 pe_print_sections(s1, "tcc.log");
2045 #endif
2046 return ret;
2049 /* ------------------------------------------------------------- */