Improve cygwin Makefile that now support TARGET=32/64 to force final version for...
[tinycc.git] / tccpe.c
blob8d29070b99ab7c93282d38210dde7e1f5311034a
1 /*
2 * TCCPE.C - PE file output for the Tiny C Compiler
4 * Copyright (c) 2005-2007 grischka
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
21 #include "tcc.h"
23 #define PE_MERGE_DATA
24 /* #define PE_PRINT_SECTIONS */
26 #ifndef _WIN32
27 #define stricmp strcasecmp
28 #define strnicmp strncasecmp
29 #endif
31 #ifndef MAX_PATH
32 #define MAX_PATH 260
33 #endif
35 #ifdef TCC_TARGET_X86_64
36 # define ADDR3264 ULONGLONG
37 # define REL_TYPE_DIRECT R_X86_64_64
38 # define R_XXX_THUNKFIX R_X86_64_PC32
39 # define R_XXX_RELATIVE R_X86_64_RELATIVE
40 # define IMAGE_FILE_MACHINE 0x8664
41 # define RSRC_RELTYPE 3
43 #elif defined TCC_TARGET_ARM
44 # define ADDR3264 DWORD
45 # define REL_TYPE_DIRECT R_ARM_ABS32
46 # define R_XXX_THUNKFIX R_ARM_ABS32
47 # define R_XXX_RELATIVE R_ARM_RELATIVE
48 # define IMAGE_FILE_MACHINE 0x01C0
49 # define RSRC_RELTYPE 7 /* ??? (not tested) */
51 #elif defined TCC_TARGET_I386
52 # define ADDR3264 DWORD
53 # define REL_TYPE_DIRECT R_386_32
54 # define R_XXX_THUNKFIX R_386_32
55 # define R_XXX_RELATIVE R_386_RELATIVE
56 # define IMAGE_FILE_MACHINE 0x014C
57 # define RSRC_RELTYPE 7 /* DIR32NB */
59 #endif
61 #if 0
62 #ifdef _WIN32
63 void dbg_printf (const char *fmt, ...)
65 char buffer[4000];
66 va_list arg;
67 int x;
68 va_start(arg, fmt);
69 x = vsprintf (buffer, fmt, arg);
70 strcpy(buffer+x, "\n");
71 OutputDebugString(buffer);
73 #endif
74 #endif
76 /* ----------------------------------------------------------- */
77 #ifndef IMAGE_NT_SIGNATURE
78 /* ----------------------------------------------------------- */
79 /* definitions below are from winnt.h */
81 typedef unsigned char BYTE;
82 typedef unsigned short WORD;
83 typedef unsigned int DWORD;
84 typedef unsigned long long ULONGLONG;
85 #pragma pack(push, 1)
87 typedef struct _IMAGE_DOS_HEADER { /* DOS .EXE header */
88 WORD e_magic; /* Magic number */
89 WORD e_cblp; /* Bytes on last page of file */
90 WORD e_cp; /* Pages in file */
91 WORD e_crlc; /* Relocations */
92 WORD e_cparhdr; /* Size of header in paragraphs */
93 WORD e_minalloc; /* Minimum extra paragraphs needed */
94 WORD e_maxalloc; /* Maximum extra paragraphs needed */
95 WORD e_ss; /* Initial (relative) SS value */
96 WORD e_sp; /* Initial SP value */
97 WORD e_csum; /* Checksum */
98 WORD e_ip; /* Initial IP value */
99 WORD e_cs; /* Initial (relative) CS value */
100 WORD e_lfarlc; /* File address of relocation table */
101 WORD e_ovno; /* Overlay number */
102 WORD e_res[4]; /* Reserved words */
103 WORD e_oemid; /* OEM identifier (for e_oeminfo) */
104 WORD e_oeminfo; /* OEM information; e_oemid specific */
105 WORD e_res2[10]; /* Reserved words */
106 DWORD e_lfanew; /* File address of new exe header */
107 } IMAGE_DOS_HEADER, *PIMAGE_DOS_HEADER;
109 #define IMAGE_NT_SIGNATURE 0x00004550 /* PE00 */
110 #define SIZE_OF_NT_SIGNATURE 4
112 typedef struct _IMAGE_FILE_HEADER {
113 WORD Machine;
114 WORD NumberOfSections;
115 DWORD TimeDateStamp;
116 DWORD PointerToSymbolTable;
117 DWORD NumberOfSymbols;
118 WORD SizeOfOptionalHeader;
119 WORD Characteristics;
120 } IMAGE_FILE_HEADER, *PIMAGE_FILE_HEADER;
123 #define IMAGE_SIZEOF_FILE_HEADER 20
125 typedef struct _IMAGE_DATA_DIRECTORY {
126 DWORD VirtualAddress;
127 DWORD Size;
128 } IMAGE_DATA_DIRECTORY, *PIMAGE_DATA_DIRECTORY;
131 typedef struct _IMAGE_OPTIONAL_HEADER {
132 /* Standard fields. */
133 WORD Magic;
134 BYTE MajorLinkerVersion;
135 BYTE MinorLinkerVersion;
136 DWORD SizeOfCode;
137 DWORD SizeOfInitializedData;
138 DWORD SizeOfUninitializedData;
139 DWORD AddressOfEntryPoint;
140 DWORD BaseOfCode;
141 #ifndef TCC_TARGET_X86_64
142 DWORD BaseOfData;
143 #endif
144 /* NT additional fields. */
145 ADDR3264 ImageBase;
146 DWORD SectionAlignment;
147 DWORD FileAlignment;
148 WORD MajorOperatingSystemVersion;
149 WORD MinorOperatingSystemVersion;
150 WORD MajorImageVersion;
151 WORD MinorImageVersion;
152 WORD MajorSubsystemVersion;
153 WORD MinorSubsystemVersion;
154 DWORD Win32VersionValue;
155 DWORD SizeOfImage;
156 DWORD SizeOfHeaders;
157 DWORD CheckSum;
158 WORD Subsystem;
159 WORD DllCharacteristics;
160 ADDR3264 SizeOfStackReserve;
161 ADDR3264 SizeOfStackCommit;
162 ADDR3264 SizeOfHeapReserve;
163 ADDR3264 SizeOfHeapCommit;
164 DWORD LoaderFlags;
165 DWORD NumberOfRvaAndSizes;
166 IMAGE_DATA_DIRECTORY DataDirectory[16];
167 } IMAGE_OPTIONAL_HEADER32, IMAGE_OPTIONAL_HEADER64, IMAGE_OPTIONAL_HEADER;
169 #define IMAGE_DIRECTORY_ENTRY_EXPORT 0 /* Export Directory */
170 #define IMAGE_DIRECTORY_ENTRY_IMPORT 1 /* Import Directory */
171 #define IMAGE_DIRECTORY_ENTRY_RESOURCE 2 /* Resource Directory */
172 #define IMAGE_DIRECTORY_ENTRY_EXCEPTION 3 /* Exception Directory */
173 #define IMAGE_DIRECTORY_ENTRY_SECURITY 4 /* Security Directory */
174 #define IMAGE_DIRECTORY_ENTRY_BASERELOC 5 /* Base Relocation Table */
175 #define IMAGE_DIRECTORY_ENTRY_DEBUG 6 /* Debug Directory */
176 /* IMAGE_DIRECTORY_ENTRY_COPYRIGHT 7 (X86 usage) */
177 #define IMAGE_DIRECTORY_ENTRY_ARCHITECTURE 7 /* Architecture Specific Data */
178 #define IMAGE_DIRECTORY_ENTRY_GLOBALPTR 8 /* RVA of GP */
179 #define IMAGE_DIRECTORY_ENTRY_TLS 9 /* TLS Directory */
180 #define IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG 10 /* Load Configuration Directory */
181 #define IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT 11 /* Bound Import Directory in headers */
182 #define IMAGE_DIRECTORY_ENTRY_IAT 12 /* Import Address Table */
183 #define IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT 13 /* Delay Load Import Descriptors */
184 #define IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR 14 /* COM Runtime descriptor */
186 /* Section header format. */
187 #define IMAGE_SIZEOF_SHORT_NAME 8
189 typedef struct _IMAGE_SECTION_HEADER {
190 BYTE Name[IMAGE_SIZEOF_SHORT_NAME];
191 union {
192 DWORD PhysicalAddress;
193 DWORD VirtualSize;
194 } Misc;
195 DWORD VirtualAddress;
196 DWORD SizeOfRawData;
197 DWORD PointerToRawData;
198 DWORD PointerToRelocations;
199 DWORD PointerToLinenumbers;
200 WORD NumberOfRelocations;
201 WORD NumberOfLinenumbers;
202 DWORD Characteristics;
203 } IMAGE_SECTION_HEADER, *PIMAGE_SECTION_HEADER;
205 #define IMAGE_SIZEOF_SECTION_HEADER 40
207 typedef struct _IMAGE_EXPORT_DIRECTORY {
208 DWORD Characteristics;
209 DWORD TimeDateStamp;
210 WORD MajorVersion;
211 WORD MinorVersion;
212 DWORD Name;
213 DWORD Base;
214 DWORD NumberOfFunctions;
215 DWORD NumberOfNames;
216 DWORD AddressOfFunctions;
217 DWORD AddressOfNames;
218 DWORD AddressOfNameOrdinals;
219 } IMAGE_EXPORT_DIRECTORY,*PIMAGE_EXPORT_DIRECTORY;
221 typedef struct _IMAGE_IMPORT_DESCRIPTOR {
222 union {
223 DWORD Characteristics;
224 DWORD OriginalFirstThunk;
226 DWORD TimeDateStamp;
227 DWORD ForwarderChain;
228 DWORD Name;
229 DWORD FirstThunk;
230 } IMAGE_IMPORT_DESCRIPTOR;
232 typedef struct _IMAGE_BASE_RELOCATION {
233 DWORD VirtualAddress;
234 DWORD SizeOfBlock;
235 // WORD TypeOffset[1];
236 } IMAGE_BASE_RELOCATION;
238 #define IMAGE_SIZEOF_BASE_RELOCATION 8
240 #define IMAGE_REL_BASED_ABSOLUTE 0
241 #define IMAGE_REL_BASED_HIGH 1
242 #define IMAGE_REL_BASED_LOW 2
243 #define IMAGE_REL_BASED_HIGHLOW 3
244 #define IMAGE_REL_BASED_HIGHADJ 4
245 #define IMAGE_REL_BASED_MIPS_JMPADDR 5
246 #define IMAGE_REL_BASED_SECTION 6
247 #define IMAGE_REL_BASED_REL32 7
249 #pragma pack(pop)
251 /* ----------------------------------------------------------- */
252 #endif /* ndef IMAGE_NT_SIGNATURE */
253 /* ----------------------------------------------------------- */
254 #pragma pack(push, 1)
256 struct pe_header
258 IMAGE_DOS_HEADER doshdr;
259 BYTE dosstub[0x40];
260 DWORD nt_sig;
261 IMAGE_FILE_HEADER filehdr;
262 #ifdef TCC_TARGET_X86_64
263 IMAGE_OPTIONAL_HEADER64 opthdr;
264 #else
265 #ifdef _WIN64
266 IMAGE_OPTIONAL_HEADER32 opthdr;
267 #else
268 IMAGE_OPTIONAL_HEADER opthdr;
269 #endif
270 #endif
273 struct pe_reloc_header {
274 DWORD offset;
275 DWORD size;
278 struct pe_rsrc_header {
279 struct _IMAGE_FILE_HEADER filehdr;
280 struct _IMAGE_SECTION_HEADER sectionhdr;
283 struct pe_rsrc_reloc {
284 DWORD offset;
285 DWORD size;
286 WORD type;
289 #pragma pack(pop)
291 /* ------------------------------------------------------------- */
292 /* internal temporary structures */
295 #define IMAGE_SCN_CNT_CODE 0x00000020
296 #define IMAGE_SCN_CNT_INITIALIZED_DATA 0x00000040
297 #define IMAGE_SCN_CNT_UNINITIALIZED_DATA 0x00000080
298 #define IMAGE_SCN_MEM_DISCARDABLE 0x02000000
299 #define IMAGE_SCN_MEM_SHARED 0x10000000
300 #define IMAGE_SCN_MEM_EXECUTE 0x20000000
301 #define IMAGE_SCN_MEM_READ 0x40000000
302 #define IMAGE_SCN_MEM_WRITE 0x80000000
305 enum {
306 sec_text = 0,
307 sec_data ,
308 sec_bss ,
309 sec_idata ,
310 sec_pdata ,
311 sec_other ,
312 sec_rsrc ,
313 sec_stab ,
314 sec_reloc ,
315 sec_last
318 static const DWORD pe_sec_flags[] = {
319 0x60000020, /* ".text" , */
320 0xC0000040, /* ".data" , */
321 0xC0000080, /* ".bss" , */
322 0x40000040, /* ".idata" , */
323 0x40000040, /* ".pdata" , */
324 0xE0000060, /* < other > , */
325 0x40000040, /* ".rsrc" , */
326 0x42000802, /* ".stab" , */
327 0x42000040, /* ".reloc" , */
330 struct section_info {
331 int cls, ord;
332 char name[32];
333 DWORD sh_addr;
334 DWORD sh_size;
335 DWORD sh_flags;
336 unsigned char *data;
337 DWORD data_size;
338 IMAGE_SECTION_HEADER ish;
341 struct import_symbol {
342 int sym_index;
343 int iat_index;
344 int thk_offset;
347 struct pe_import_info {
348 int dll_index;
349 int sym_count;
350 struct import_symbol **symbols;
353 struct pe_info {
354 TCCState *s1;
355 Section *reloc;
356 Section *thunk;
357 const char *filename;
358 int type;
359 DWORD sizeofheaders;
360 ADDR3264 imagebase;
361 DWORD start_addr;
362 DWORD imp_offs;
363 DWORD imp_size;
364 DWORD iat_offs;
365 DWORD iat_size;
366 DWORD exp_offs;
367 DWORD exp_size;
368 int subsystem;
369 DWORD section_align;
370 DWORD file_align;
371 struct section_info *sec_info;
372 int sec_count;
373 struct pe_import_info **imp_info;
374 int imp_count;
377 #define PE_NUL 0
378 #define PE_DLL 1
379 #define PE_GUI 2
380 #define PE_EXE 3
381 #define PE_RUN 4
383 /* --------------------------------------------*/
385 static const char *pe_export_name(TCCState *s1, ElfW(Sym) *sym)
387 const char *name = symtab_section->link->data + sym->st_name;
388 if (s1->leading_underscore && name[0] == '_' && !(sym->st_other & ST_PE_STDCALL))
389 return name + 1;
390 return name;
393 static int pe_find_import(TCCState * s1, ElfW(Sym) *sym)
395 char buffer[200];
396 const char *s, *p;
397 int sym_index = 0, n = 0;
399 do {
400 s = pe_export_name(s1, sym);
401 if (n) {
402 /* second try: */
403 if (sym->st_other & ST_PE_STDCALL) {
404 /* try w/0 stdcall deco (windows API convention) */
405 p = strrchr(s, '@');
406 if (!p || s[0] != '_')
407 break;
408 strcpy(buffer, s+1)[p-s-1] = 0;
409 } else if (s[0] != '_') { /* try non-ansi function */
410 buffer[0] = '_', strcpy(buffer + 1, s);
411 } else if (0 == memcmp(s, "__imp__", 7)) { /* mingw 2.0 */
412 strcpy(buffer, s + 6);
413 } else if (0 == memcmp(s, "_imp___", 7)) { /* mingw 3.7 */
414 strcpy(buffer, s + 6);
415 } else {
416 break;
418 s = buffer;
420 sym_index = find_elf_sym(s1->dynsymtab_section, s);
421 // printf("find (%d) %d %s\n", n, sym_index, s);
422 } while (0 == sym_index && ++n < 2);
423 return sym_index;
426 /*----------------------------------------------------------------------------*/
428 static int dynarray_assoc(void **pp, int n, int key)
430 int i;
431 for (i = 0; i < n; ++i, ++pp)
432 if (key == **(int **) pp)
433 return i;
434 return -1;
437 #if 0
438 ST_FN DWORD umin(DWORD a, DWORD b)
440 return a < b ? a : b;
442 #endif
444 static DWORD umax(DWORD a, DWORD b)
446 return a < b ? b : a;
449 static DWORD pe_file_align(struct pe_info *pe, DWORD n)
451 return (n + (pe->file_align - 1)) & ~(pe->file_align - 1);
454 static DWORD pe_virtual_align(struct pe_info *pe, DWORD n)
456 return (n + (pe->section_align - 1)) & ~(pe->section_align - 1);
459 static void pe_align_section(Section *s, int a)
461 int i = s->data_offset & (a-1);
462 if (i)
463 section_ptr_add(s, a - i);
466 static void pe_set_datadir(struct pe_header *hdr, int dir, DWORD addr, DWORD size)
468 hdr->opthdr.DataDirectory[dir].VirtualAddress = addr;
469 hdr->opthdr.DataDirectory[dir].Size = size;
472 static int pe_fwrite(void *data, unsigned len, FILE *fp, DWORD *psum)
474 if (psum) {
475 DWORD sum = *psum;
476 WORD *p = data;
477 int i;
478 for (i = len; i > 0; i -= 2) {
479 sum += (i >= 2) ? *p++ : *(BYTE*)p;
480 sum = (sum + (sum >> 16)) & 0xFFFF;
482 *psum = sum;
484 return len == fwrite(data, 1, len, fp) ? 0 : -1;
487 static void pe_fpad(FILE *fp, DWORD new_pos)
489 DWORD pos = ftell(fp);
490 while (++pos <= new_pos)
491 fputc(0, fp);
494 /*----------------------------------------------------------------------------*/
495 static int pe_write(struct pe_info *pe)
497 static const struct pe_header pe_template = {
499 /* IMAGE_DOS_HEADER doshdr */
500 0x5A4D, /*WORD e_magic; Magic number */
501 0x0090, /*WORD e_cblp; Bytes on last page of file */
502 0x0003, /*WORD e_cp; Pages in file */
503 0x0000, /*WORD e_crlc; Relocations */
505 0x0004, /*WORD e_cparhdr; Size of header in paragraphs */
506 0x0000, /*WORD e_minalloc; Minimum extra paragraphs needed */
507 0xFFFF, /*WORD e_maxalloc; Maximum extra paragraphs needed */
508 0x0000, /*WORD e_ss; Initial (relative) SS value */
510 0x00B8, /*WORD e_sp; Initial SP value */
511 0x0000, /*WORD e_csum; Checksum */
512 0x0000, /*WORD e_ip; Initial IP value */
513 0x0000, /*WORD e_cs; Initial (relative) CS value */
514 0x0040, /*WORD e_lfarlc; File address of relocation table */
515 0x0000, /*WORD e_ovno; Overlay number */
516 {0,0,0,0}, /*WORD e_res[4]; Reserved words */
517 0x0000, /*WORD e_oemid; OEM identifier (for e_oeminfo) */
518 0x0000, /*WORD e_oeminfo; OEM information; e_oemid specific */
519 {0,0,0,0,0,0,0,0,0,0}, /*WORD e_res2[10]; Reserved words */
520 0x00000080 /*DWORD e_lfanew; File address of new exe header */
522 /* BYTE dosstub[0x40] */
523 /* 14 code bytes + "This program cannot be run in DOS mode.\r\r\n$" + 6 * 0x00 */
524 0x0e,0x1f,0xba,0x0e,0x00,0xb4,0x09,0xcd,0x21,0xb8,0x01,0x4c,0xcd,0x21,0x54,0x68,
525 0x69,0x73,0x20,0x70,0x72,0x6f,0x67,0x72,0x61,0x6d,0x20,0x63,0x61,0x6e,0x6e,0x6f,
526 0x74,0x20,0x62,0x65,0x20,0x72,0x75,0x6e,0x20,0x69,0x6e,0x20,0x44,0x4f,0x53,0x20,
527 0x6d,0x6f,0x64,0x65,0x2e,0x0d,0x0d,0x0a,0x24,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
529 0x00004550, /* DWORD nt_sig = IMAGE_NT_SIGNATURE */
531 /* IMAGE_FILE_HEADER filehdr */
532 IMAGE_FILE_MACHINE, /*WORD Machine; */
533 0x0003, /*WORD NumberOfSections; */
534 0x00000000, /*DWORD TimeDateStamp; */
535 0x00000000, /*DWORD PointerToSymbolTable; */
536 0x00000000, /*DWORD NumberOfSymbols; */
537 #if defined(TCC_TARGET_X86_64)
538 0x00F0, /*WORD SizeOfOptionalHeader; */
539 0x022F /*WORD Characteristics; */
540 #define CHARACTERISTICS_DLL 0x222E
541 #elif defined(TCC_TARGET_I386)
542 0x00E0, /*WORD SizeOfOptionalHeader; */
543 0x030F /*WORD Characteristics; */
544 #define CHARACTERISTICS_DLL 0x230E
545 #elif defined(TCC_TARGET_ARM)
546 0x00E0, /*WORD SizeOfOptionalHeader; */
547 0x010F, /*WORD Characteristics; */
548 #define CHARACTERISTICS_DLL 0x230F
549 #endif
551 /* IMAGE_OPTIONAL_HEADER opthdr */
552 /* Standard fields. */
553 #ifdef TCC_TARGET_X86_64
554 0x020B, /*WORD Magic; */
555 #else
556 0x010B, /*WORD Magic; */
557 #endif
558 0x06, /*BYTE MajorLinkerVersion; */
559 0x00, /*BYTE MinorLinkerVersion; */
560 0x00000000, /*DWORD SizeOfCode; */
561 0x00000000, /*DWORD SizeOfInitializedData; */
562 0x00000000, /*DWORD SizeOfUninitializedData; */
563 0x00000000, /*DWORD AddressOfEntryPoint; */
564 0x00000000, /*DWORD BaseOfCode; */
565 #ifndef TCC_TARGET_X86_64
566 0x00000000, /*DWORD BaseOfData; */
567 #endif
568 /* NT additional fields. */
569 #if defined(TCC_TARGET_ARM)
570 0x00100000, /*DWORD ImageBase; */
571 #else
572 0x00400000, /*DWORD ImageBase; */
573 #endif
574 0x00001000, /*DWORD SectionAlignment; */
575 0x00000200, /*DWORD FileAlignment; */
576 0x0004, /*WORD MajorOperatingSystemVersion; */
577 0x0000, /*WORD MinorOperatingSystemVersion; */
578 0x0000, /*WORD MajorImageVersion; */
579 0x0000, /*WORD MinorImageVersion; */
580 0x0004, /*WORD MajorSubsystemVersion; */
581 0x0000, /*WORD MinorSubsystemVersion; */
582 0x00000000, /*DWORD Win32VersionValue; */
583 0x00000000, /*DWORD SizeOfImage; */
584 0x00000200, /*DWORD SizeOfHeaders; */
585 0x00000000, /*DWORD CheckSum; */
586 0x0002, /*WORD Subsystem; */
587 0x0000, /*WORD DllCharacteristics; */
588 0x00100000, /*DWORD SizeOfStackReserve; */
589 0x00001000, /*DWORD SizeOfStackCommit; */
590 0x00100000, /*DWORD SizeOfHeapReserve; */
591 0x00001000, /*DWORD SizeOfHeapCommit; */
592 0x00000000, /*DWORD LoaderFlags; */
593 0x00000010, /*DWORD NumberOfRvaAndSizes; */
595 /* IMAGE_DATA_DIRECTORY DataDirectory[16]; */
596 {{0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0},
597 {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}}
600 struct pe_header pe_header = pe_template;
602 int i;
603 FILE *op;
604 DWORD file_offset, sum;
605 struct section_info *si;
606 IMAGE_SECTION_HEADER *psh;
608 op = fopen(pe->filename, "wb");
609 if (NULL == op) {
610 tcc_error_noabort("could not write '%s': %s", pe->filename, strerror(errno));
611 return -1;
614 pe->sizeofheaders = pe_file_align(pe,
615 sizeof (struct pe_header)
616 + pe->sec_count * sizeof (IMAGE_SECTION_HEADER)
619 file_offset = pe->sizeofheaders;
621 if (2 == pe->s1->verbose)
622 printf("-------------------------------"
623 "\n virt file size section" "\n");
624 for (i = 0; i < pe->sec_count; ++i) {
625 DWORD addr, size;
626 const char *sh_name;
628 si = pe->sec_info + i;
629 sh_name = si->name;
630 addr = si->sh_addr - pe->imagebase;
631 size = si->sh_size;
632 psh = &si->ish;
634 if (2 == pe->s1->verbose)
635 printf("%6x %6x %6x %s\n",
636 (unsigned)addr, (unsigned)file_offset, (unsigned)size, sh_name);
638 switch (si->cls) {
639 case sec_text:
640 pe_header.opthdr.BaseOfCode = addr;
641 pe_header.opthdr.AddressOfEntryPoint = addr + pe->start_addr;
642 break;
644 case sec_data:
645 #ifndef TCC_TARGET_X86_64
646 pe_header.opthdr.BaseOfData = addr;
647 #endif
648 break;
650 case sec_bss:
651 break;
653 case sec_reloc:
654 pe_set_datadir(&pe_header, IMAGE_DIRECTORY_ENTRY_BASERELOC, addr, size);
655 break;
657 case sec_rsrc:
658 pe_set_datadir(&pe_header, IMAGE_DIRECTORY_ENTRY_RESOURCE, addr, size);
659 break;
661 case sec_pdata:
662 pe_set_datadir(&pe_header, IMAGE_DIRECTORY_ENTRY_EXCEPTION, addr, size);
663 break;
665 case sec_stab:
666 break;
669 if (pe->thunk == pe->s1->sections[si->ord]) {
670 if (pe->imp_size) {
671 pe_set_datadir(&pe_header, IMAGE_DIRECTORY_ENTRY_IMPORT,
672 pe->imp_offs + addr, pe->imp_size);
673 pe_set_datadir(&pe_header, IMAGE_DIRECTORY_ENTRY_IAT,
674 pe->iat_offs + addr, pe->iat_size);
676 if (pe->exp_size) {
677 pe_set_datadir(&pe_header, IMAGE_DIRECTORY_ENTRY_EXPORT,
678 pe->exp_offs + addr, pe->exp_size);
682 strncpy((char*)psh->Name, sh_name, sizeof psh->Name);
684 psh->Characteristics = pe_sec_flags[si->cls];
685 psh->VirtualAddress = addr;
686 psh->Misc.VirtualSize = size;
687 pe_header.opthdr.SizeOfImage =
688 umax(pe_virtual_align(pe, size + addr), pe_header.opthdr.SizeOfImage);
690 if (si->data_size) {
691 psh->PointerToRawData = file_offset;
692 file_offset = pe_file_align(pe, file_offset + si->data_size);
693 psh->SizeOfRawData = file_offset - psh->PointerToRawData;
694 if (si->cls == sec_text)
695 pe_header.opthdr.SizeOfCode += psh->SizeOfRawData;
696 else
697 pe_header.opthdr.SizeOfInitializedData += psh->SizeOfRawData;
701 //pe_header.filehdr.TimeDateStamp = time(NULL);
702 pe_header.filehdr.NumberOfSections = pe->sec_count;
703 pe_header.opthdr.SizeOfHeaders = pe->sizeofheaders;
704 pe_header.opthdr.ImageBase = pe->imagebase;
705 pe_header.opthdr.Subsystem = pe->subsystem;
706 if (pe->s1->pe_stack_size)
707 pe_header.opthdr.SizeOfStackReserve = pe->s1->pe_stack_size;
708 if (PE_DLL == pe->type)
709 pe_header.filehdr.Characteristics = CHARACTERISTICS_DLL;
710 pe_header.filehdr.Characteristics |= pe->s1->pe_characteristics;
712 sum = 0;
713 pe_fwrite(&pe_header, sizeof pe_header, op, &sum);
714 for (i = 0; i < pe->sec_count; ++i)
715 pe_fwrite(&pe->sec_info[i].ish, sizeof(IMAGE_SECTION_HEADER), op, &sum);
716 pe_fpad(op, pe->sizeofheaders);
717 for (i = 0; i < pe->sec_count; ++i) {
718 si = pe->sec_info + i;
719 psh = &si->ish;
720 if (si->data_size) {
721 pe_fwrite(si->data, si->data_size, op, &sum);
722 file_offset = psh->PointerToRawData + psh->SizeOfRawData;
723 pe_fpad(op, file_offset);
727 pe_header.opthdr.CheckSum = sum + file_offset;
728 fseek(op, offsetof(struct pe_header, opthdr.CheckSum), SEEK_SET);
729 pe_fwrite(&pe_header.opthdr.CheckSum, sizeof pe_header.opthdr.CheckSum, op, NULL);
730 fclose (op);
732 if (2 == pe->s1->verbose)
733 printf("-------------------------------\n");
734 if (pe->s1->verbose)
735 printf("<- %s (%u bytes)\n", pe->filename, (unsigned)file_offset);
737 return 0;
740 /*----------------------------------------------------------------------------*/
742 static struct import_symbol *pe_add_import(struct pe_info *pe, int sym_index)
744 int i;
745 int dll_index;
746 struct pe_import_info *p;
747 struct import_symbol *s;
748 ElfW(Sym) *isym;
750 isym = (ElfW(Sym) *)pe->s1->dynsymtab_section->data + sym_index;
751 dll_index = isym->st_size;
753 i = dynarray_assoc ((void**)pe->imp_info, pe->imp_count, dll_index);
754 if (-1 != i) {
755 p = pe->imp_info[i];
756 goto found_dll;
758 p = tcc_mallocz(sizeof *p);
759 p->dll_index = dll_index;
760 dynarray_add(&pe->imp_info, &pe->imp_count, p);
762 found_dll:
763 i = dynarray_assoc ((void**)p->symbols, p->sym_count, sym_index);
764 if (-1 != i)
765 return p->symbols[i];
767 s = tcc_mallocz(sizeof *s);
768 dynarray_add(&p->symbols, &p->sym_count, s);
769 s->sym_index = sym_index;
770 return s;
773 void pe_free_imports(struct pe_info *pe)
775 int i;
776 for (i = 0; i < pe->imp_count; ++i) {
777 struct pe_import_info *p = pe->imp_info[i];
778 dynarray_reset(&p->symbols, &p->sym_count);
780 dynarray_reset(&pe->imp_info, &pe->imp_count);
783 /*----------------------------------------------------------------------------*/
784 static void pe_build_imports(struct pe_info *pe)
786 int thk_ptr, ent_ptr, dll_ptr, sym_cnt, i;
787 DWORD rva_base = pe->thunk->sh_addr - pe->imagebase;
788 int ndlls = pe->imp_count;
790 for (sym_cnt = i = 0; i < ndlls; ++i)
791 sym_cnt += pe->imp_info[i]->sym_count;
793 if (0 == sym_cnt)
794 return;
796 pe_align_section(pe->thunk, 16);
798 pe->imp_offs = dll_ptr = pe->thunk->data_offset;
799 pe->imp_size = (ndlls + 1) * sizeof(IMAGE_IMPORT_DESCRIPTOR);
800 pe->iat_offs = dll_ptr + pe->imp_size;
801 pe->iat_size = (sym_cnt + ndlls) * sizeof(ADDR3264);
802 section_ptr_add(pe->thunk, pe->imp_size + 2*pe->iat_size);
804 thk_ptr = pe->iat_offs;
805 ent_ptr = pe->iat_offs + pe->iat_size;
807 for (i = 0; i < pe->imp_count; ++i) {
808 IMAGE_IMPORT_DESCRIPTOR *hdr;
809 int k, n, dllindex;
810 ADDR3264 v;
811 struct pe_import_info *p = pe->imp_info[i];
812 const char *name;
813 DLLReference *dllref;
815 dllindex = p->dll_index;
816 if (dllindex)
817 name = (dllref = pe->s1->loaded_dlls[dllindex-1])->name;
818 else
819 name = "", dllref = NULL;
821 /* put the dll name into the import header */
822 v = put_elf_str(pe->thunk, name);
823 hdr = (IMAGE_IMPORT_DESCRIPTOR*)(pe->thunk->data + dll_ptr);
824 hdr->FirstThunk = thk_ptr + rva_base;
825 hdr->OriginalFirstThunk = ent_ptr + rva_base;
826 hdr->Name = v + rva_base;
828 for (k = 0, n = p->sym_count; k <= n; ++k) {
829 if (k < n) {
830 int iat_index = p->symbols[k]->iat_index;
831 int sym_index = p->symbols[k]->sym_index;
832 ElfW(Sym) *imp_sym = (ElfW(Sym) *)pe->s1->dynsymtab_section->data + sym_index;
833 ElfW(Sym) *org_sym = (ElfW(Sym) *)symtab_section->data + iat_index;
834 const char *name = pe->s1->dynsymtab_section->link->data + imp_sym->st_name;
835 int ordinal;
837 org_sym->st_value = thk_ptr;
838 org_sym->st_shndx = pe->thunk->sh_num;
840 if (dllref)
841 v = 0, ordinal = imp_sym->st_value; /* ordinal from pe_load_def */
842 else
843 ordinal = 0, v = imp_sym->st_value; /* address from tcc_add_symbol() */
845 #ifdef TCC_IS_NATIVE
846 if (pe->type == PE_RUN) {
847 if (dllref) {
848 if ( !dllref->handle )
849 dllref->handle = LoadLibrary(dllref->name);
850 v = (ADDR3264)GetProcAddress(dllref->handle, ordinal?(char*)0+ordinal:name);
852 if (!v)
853 tcc_error_noabort("can't build symbol '%s'", name);
854 } else
855 #endif
856 if (ordinal) {
857 v = ordinal | (ADDR3264)1 << (sizeof(ADDR3264)*8 - 1);
858 } else {
859 v = pe->thunk->data_offset + rva_base;
860 section_ptr_add(pe->thunk, sizeof(WORD)); /* hint, not used */
861 put_elf_str(pe->thunk, name);
864 } else {
865 v = 0; /* last entry is zero */
868 *(ADDR3264*)(pe->thunk->data+thk_ptr) =
869 *(ADDR3264*)(pe->thunk->data+ent_ptr) = v;
870 thk_ptr += sizeof (ADDR3264);
871 ent_ptr += sizeof (ADDR3264);
873 dll_ptr += sizeof(IMAGE_IMPORT_DESCRIPTOR);
877 /* ------------------------------------------------------------- */
879 struct pe_sort_sym
881 int index;
882 const char *name;
885 static int sym_cmp(const void *va, const void *vb)
887 const char *ca = (*(struct pe_sort_sym**)va)->name;
888 const char *cb = (*(struct pe_sort_sym**)vb)->name;
889 return strcmp(ca, cb);
892 static void pe_build_exports(struct pe_info *pe)
894 ElfW(Sym) *sym;
895 int sym_index, sym_end;
896 DWORD rva_base, func_o, name_o, ord_o, str_o;
897 IMAGE_EXPORT_DIRECTORY *hdr;
898 int sym_count, ord;
899 struct pe_sort_sym **sorted, *p;
901 FILE *op;
902 char buf[MAX_PATH];
903 const char *dllname;
904 const char *name;
906 rva_base = pe->thunk->sh_addr - pe->imagebase;
907 sym_count = 0, sorted = NULL, op = NULL;
909 sym_end = symtab_section->data_offset / sizeof(ElfW(Sym));
910 for (sym_index = 1; sym_index < sym_end; ++sym_index) {
911 sym = (ElfW(Sym)*)symtab_section->data + sym_index;
912 name = pe_export_name(pe->s1, sym);
913 if ((sym->st_other & ST_PE_EXPORT)
914 /* export only symbols from actually written sections */
915 && pe->s1->sections[sym->st_shndx]->sh_addr) {
916 p = tcc_malloc(sizeof *p);
917 p->index = sym_index;
918 p->name = name;
919 dynarray_add(&sorted, &sym_count, p);
921 #if 0
922 if (sym->st_other & ST_PE_EXPORT)
923 printf("export: %s\n", name);
924 if (sym->st_other & ST_PE_STDCALL)
925 printf("stdcall: %s\n", name);
926 #endif
929 if (0 == sym_count)
930 return;
932 qsort (sorted, sym_count, sizeof *sorted, sym_cmp);
934 pe_align_section(pe->thunk, 16);
935 dllname = tcc_basename(pe->filename);
937 pe->exp_offs = pe->thunk->data_offset;
938 func_o = pe->exp_offs + sizeof(IMAGE_EXPORT_DIRECTORY);
939 name_o = func_o + sym_count * sizeof (DWORD);
940 ord_o = name_o + sym_count * sizeof (DWORD);
941 str_o = ord_o + sym_count * sizeof(WORD);
943 hdr = section_ptr_add(pe->thunk, str_o - pe->exp_offs);
944 hdr->Characteristics = 0;
945 hdr->Base = 1;
946 hdr->NumberOfFunctions = sym_count;
947 hdr->NumberOfNames = sym_count;
948 hdr->AddressOfFunctions = func_o + rva_base;
949 hdr->AddressOfNames = name_o + rva_base;
950 hdr->AddressOfNameOrdinals = ord_o + rva_base;
951 hdr->Name = str_o + rva_base;
952 put_elf_str(pe->thunk, dllname);
954 #if 1
955 /* automatically write exports to <output-filename>.def */
956 pstrcpy(buf, sizeof buf, pe->filename);
957 strcpy(tcc_fileextension(buf), ".def");
958 op = fopen(buf, "w");
959 if (NULL == op) {
960 tcc_error_noabort("could not create '%s': %s", buf, strerror(errno));
961 } else {
962 fprintf(op, "LIBRARY %s\n\nEXPORTS\n", dllname);
963 if (pe->s1->verbose)
964 printf("<- %s (%d symbols)\n", buf, sym_count);
966 #endif
968 for (ord = 0; ord < sym_count; ++ord)
970 p = sorted[ord], sym_index = p->index, name = p->name;
971 /* insert actual address later in pe_relocate_rva */
972 put_elf_reloc(symtab_section, pe->thunk,
973 func_o, R_XXX_RELATIVE, sym_index);
974 *(DWORD*)(pe->thunk->data + name_o)
975 = pe->thunk->data_offset + rva_base;
976 *(WORD*)(pe->thunk->data + ord_o)
977 = ord;
978 put_elf_str(pe->thunk, name);
979 func_o += sizeof (DWORD);
980 name_o += sizeof (DWORD);
981 ord_o += sizeof (WORD);
982 if (op)
983 fprintf(op, "%s\n", name);
985 pe->exp_size = pe->thunk->data_offset - pe->exp_offs;
986 dynarray_reset(&sorted, &sym_count);
987 if (op)
988 fclose(op);
991 /* ------------------------------------------------------------- */
992 static void pe_build_reloc (struct pe_info *pe)
994 DWORD offset, block_ptr, addr;
995 int count, i;
996 ElfW_Rel *rel, *rel_end;
997 Section *s = NULL, *sr;
999 offset = addr = block_ptr = count = i = 0;
1000 rel = rel_end = NULL;
1002 for(;;) {
1003 if (rel < rel_end) {
1004 int type = ELFW(R_TYPE)(rel->r_info);
1005 addr = rel->r_offset + s->sh_addr;
1006 ++ rel;
1007 if (type != REL_TYPE_DIRECT)
1008 continue;
1009 if (count == 0) { /* new block */
1010 block_ptr = pe->reloc->data_offset;
1011 section_ptr_add(pe->reloc, sizeof(struct pe_reloc_header));
1012 offset = addr & 0xFFFFFFFF<<12;
1014 if ((addr -= offset) < (1<<12)) { /* one block spans 4k addresses */
1015 WORD *wp = section_ptr_add(pe->reloc, sizeof (WORD));
1016 *wp = addr | IMAGE_REL_BASED_HIGHLOW<<12;
1017 ++count;
1018 continue;
1020 -- rel;
1022 } else if (i < pe->sec_count) {
1023 sr = (s = pe->s1->sections[pe->sec_info[i++].ord])->reloc;
1024 if (sr) {
1025 rel = (ElfW_Rel *)sr->data;
1026 rel_end = (ElfW_Rel *)(sr->data + sr->data_offset);
1028 continue;
1031 if (count) {
1032 /* store the last block and ready for a new one */
1033 struct pe_reloc_header *hdr;
1034 if (count & 1) /* align for DWORDS */
1035 section_ptr_add(pe->reloc, sizeof(WORD)), ++count;
1036 hdr = (struct pe_reloc_header *)(pe->reloc->data + block_ptr);
1037 hdr -> offset = offset - pe->imagebase;
1038 hdr -> size = count * sizeof(WORD) + sizeof(struct pe_reloc_header);
1039 count = 0;
1042 if (rel >= rel_end)
1043 break;
1047 /* ------------------------------------------------------------- */
1048 static int pe_section_class(Section *s)
1050 int type, flags;
1051 const char *name;
1053 type = s->sh_type;
1054 flags = s->sh_flags;
1055 name = s->name;
1056 if (flags & SHF_ALLOC) {
1057 if (type == SHT_PROGBITS) {
1058 if (flags & SHF_EXECINSTR)
1059 return sec_text;
1060 if (flags & SHF_WRITE)
1061 return sec_data;
1062 if (0 == strcmp(name, ".rsrc"))
1063 return sec_rsrc;
1064 if (0 == strcmp(name, ".iedat"))
1065 return sec_idata;
1066 if (0 == strcmp(name, ".pdata"))
1067 return sec_pdata;
1068 return sec_other;
1069 } else if (type == SHT_NOBITS) {
1070 if (flags & SHF_WRITE)
1071 return sec_bss;
1073 } else {
1074 if (0 == strcmp(name, ".reloc"))
1075 return sec_reloc;
1076 if (0 == strncmp(name, ".stab", 5)) /* .stab and .stabstr */
1077 return sec_stab;
1079 return -1;
1082 static int pe_assign_addresses (struct pe_info *pe)
1084 int i, k, o, c;
1085 DWORD addr;
1086 int *section_order;
1087 struct section_info *si;
1088 Section *s;
1090 if (PE_DLL == pe->type)
1091 pe->reloc = new_section(pe->s1, ".reloc", SHT_PROGBITS, 0);
1093 // pe->thunk = new_section(pe->s1, ".iedat", SHT_PROGBITS, SHF_ALLOC);
1095 section_order = tcc_malloc(pe->s1->nb_sections * sizeof (int));
1096 for (o = k = 0 ; k < sec_last; ++k) {
1097 for (i = 1; i < pe->s1->nb_sections; ++i) {
1098 s = pe->s1->sections[i];
1099 if (k == pe_section_class(s)) {
1100 // printf("%s %d\n", s->name, k);
1101 s->sh_addr = pe->imagebase;
1102 section_order[o++] = i;
1107 pe->sec_info = tcc_mallocz(o * sizeof (struct section_info));
1108 addr = pe->imagebase + 1;
1110 for (i = 0; i < o; ++i)
1112 k = section_order[i];
1113 s = pe->s1->sections[k];
1114 c = pe_section_class(s);
1115 si = &pe->sec_info[pe->sec_count];
1117 #ifdef PE_MERGE_DATA
1118 if (c == sec_bss && pe->sec_count && si[-1].cls == sec_data) {
1119 /* append .bss to .data */
1120 s->sh_addr = addr = ((addr-1) | (s->sh_addralign-1)) + 1;
1121 addr += s->data_offset;
1122 si[-1].sh_size = addr - si[-1].sh_addr;
1123 continue;
1125 #endif
1126 if (c == sec_stab && 0 == pe->s1->do_debug)
1127 continue;
1129 strcpy(si->name, s->name);
1130 si->cls = c;
1131 si->ord = k;
1132 si->sh_addr = s->sh_addr = addr = pe_virtual_align(pe, addr);
1133 si->sh_flags = s->sh_flags;
1135 if (c == sec_data && NULL == pe->thunk)
1136 pe->thunk = s;
1138 if (s == pe->thunk) {
1139 pe_build_imports(pe);
1140 pe_build_exports(pe);
1143 if (c == sec_reloc)
1144 pe_build_reloc (pe);
1146 if (s->data_offset)
1148 if (s->sh_type != SHT_NOBITS) {
1149 si->data = s->data;
1150 si->data_size = s->data_offset;
1153 addr += s->data_offset;
1154 si->sh_size = s->data_offset;
1155 ++pe->sec_count;
1157 // printf("%08x %05x %s\n", si->sh_addr, si->sh_size, si->name);
1160 #if 0
1161 for (i = 1; i < pe->s1->nb_sections; ++i) {
1162 Section *s = pe->s1->sections[i];
1163 int type = s->sh_type;
1164 int flags = s->sh_flags;
1165 printf("section %-16s %-10s %5x %s,%s,%s\n",
1166 s->name,
1167 type == SHT_PROGBITS ? "progbits" :
1168 type == SHT_NOBITS ? "nobits" :
1169 type == SHT_SYMTAB ? "symtab" :
1170 type == SHT_STRTAB ? "strtab" :
1171 type == SHT_RELX ? "rel" : "???",
1172 s->data_offset,
1173 flags & SHF_ALLOC ? "alloc" : "",
1174 flags & SHF_WRITE ? "write" : "",
1175 flags & SHF_EXECINSTR ? "exec" : ""
1178 pe->s1->verbose = 2;
1179 #endif
1181 tcc_free(section_order);
1182 return 0;
1185 /* ------------------------------------------------------------- */
1186 static void pe_relocate_rva (struct pe_info *pe, Section *s)
1188 Section *sr = s->reloc;
1189 ElfW_Rel *rel, *rel_end;
1190 rel_end = (ElfW_Rel *)(sr->data + sr->data_offset);
1191 for(rel = (ElfW_Rel *)sr->data; rel < rel_end; rel++) {
1192 if (ELFW(R_TYPE)(rel->r_info) == R_XXX_RELATIVE) {
1193 int sym_index = ELFW(R_SYM)(rel->r_info);
1194 DWORD addr = s->sh_addr;
1195 if (sym_index) {
1196 ElfW(Sym) *sym = (ElfW(Sym) *)symtab_section->data + sym_index;
1197 addr = sym->st_value;
1199 // printf("reloc rva %08x %08x %s\n", (DWORD)rel->r_offset, addr, s->name);
1200 *(DWORD*)(s->data + rel->r_offset) += addr - pe->imagebase;
1205 /*----------------------------------------------------------------------------*/
1207 static int pe_isafunc(int sym_index)
1209 Section *sr = text_section->reloc;
1210 ElfW_Rel *rel, *rel_end;
1211 Elf32_Word info = ELF32_R_INFO(sym_index, R_386_PC32);
1212 if (!sr)
1213 return 0;
1214 rel_end = (ElfW_Rel *)(sr->data + sr->data_offset);
1215 for (rel = (ElfW_Rel *)sr->data; rel < rel_end; rel++)
1216 if (rel->r_info == info)
1217 return 1;
1218 return 0;
1221 /*----------------------------------------------------------------------------*/
1222 static int pe_check_symbols(struct pe_info *pe)
1224 ElfW(Sym) *sym;
1225 int sym_index, sym_end;
1226 int ret = 0;
1228 pe_align_section(text_section, 8);
1230 sym_end = symtab_section->data_offset / sizeof(ElfW(Sym));
1231 for (sym_index = 1; sym_index < sym_end; ++sym_index) {
1233 sym = (ElfW(Sym) *)symtab_section->data + sym_index;
1234 if (sym->st_shndx == SHN_UNDEF) {
1236 const char *name = symtab_section->link->data + sym->st_name;
1237 unsigned type = ELFW(ST_TYPE)(sym->st_info);
1238 int imp_sym = pe_find_import(pe->s1, sym);
1239 struct import_symbol *is;
1241 if (0 == imp_sym)
1242 goto not_found;
1244 if (type == STT_NOTYPE) {
1245 /* symbols from assembler have no type, find out which */
1246 if (pe_isafunc(sym_index))
1247 type = STT_FUNC;
1248 else
1249 type = STT_OBJECT;
1252 is = pe_add_import(pe, imp_sym);
1254 if (type == STT_FUNC) {
1255 unsigned long offset = is->thk_offset;
1256 if (offset) {
1257 /* got aliased symbol, like stricmp and _stricmp */
1259 } else {
1260 char buffer[100];
1261 WORD *p;
1263 offset = text_section->data_offset;
1264 /* add the 'jmp IAT[x]' instruction */
1265 #ifdef TCC_TARGET_ARM
1266 p = section_ptr_add(text_section, 8+4); // room for code and address
1267 (*(DWORD*)(p)) = 0xE59FC000; // arm code ldr ip, [pc] ; PC+8+0 = 0001xxxx
1268 (*(DWORD*)(p+2)) = 0xE59CF000; // arm code ldr pc, [ip]
1269 #else
1270 p = section_ptr_add(text_section, 8);
1271 *p = 0x25FF;
1272 #ifdef TCC_TARGET_X86_64
1273 *(DWORD*)(p+1) = (DWORD)-4;
1274 #endif
1275 #endif
1276 /* add a helper symbol, will be patched later in
1277 pe_build_imports */
1278 sprintf(buffer, "IAT.%s", name);
1279 is->iat_index = put_elf_sym(
1280 symtab_section, 0, sizeof(DWORD),
1281 ELFW(ST_INFO)(STB_GLOBAL, STT_OBJECT),
1282 0, SHN_UNDEF, buffer);
1283 #ifdef TCC_TARGET_ARM
1284 put_elf_reloc(symtab_section, text_section,
1285 offset + 8, R_XXX_THUNKFIX, is->iat_index); // offset to IAT position
1286 #else
1287 put_elf_reloc(symtab_section, text_section,
1288 offset + 2, R_XXX_THUNKFIX, is->iat_index);
1289 #endif
1290 is->thk_offset = offset;
1293 /* tcc_realloc might have altered sym's address */
1294 sym = (ElfW(Sym) *)symtab_section->data + sym_index;
1296 /* patch the original symbol */
1297 sym->st_value = offset;
1298 sym->st_shndx = text_section->sh_num;
1299 sym->st_other &= ~ST_PE_EXPORT; /* do not export */
1300 continue;
1303 if (type == STT_OBJECT) { /* data, ptr to that should be */
1304 if (0 == is->iat_index) {
1305 /* original symbol will be patched later in pe_build_imports */
1306 is->iat_index = sym_index;
1307 continue;
1311 not_found:
1312 tcc_error_noabort("undefined symbol '%s'", name);
1313 ret = -1;
1315 } else if (pe->s1->rdynamic
1316 && ELFW(ST_BIND)(sym->st_info) != STB_LOCAL) {
1317 /* if -rdynamic option, then export all non local symbols */
1318 sym->st_other |= ST_PE_EXPORT;
1321 return ret;
1324 /*----------------------------------------------------------------------------*/
1325 #ifdef PE_PRINT_SECTIONS
1326 static void pe_print_section(FILE * f, Section * s)
1328 /* just if you'r curious */
1329 BYTE *p, *e, b;
1330 int i, n, l, m;
1331 p = s->data;
1332 e = s->data + s->data_offset;
1333 l = e - p;
1335 fprintf(f, "section \"%s\"", s->name);
1336 if (s->link)
1337 fprintf(f, "\nlink \"%s\"", s->link->name);
1338 if (s->reloc)
1339 fprintf(f, "\nreloc \"%s\"", s->reloc->name);
1340 fprintf(f, "\nv_addr %08X", (unsigned)s->sh_addr);
1341 fprintf(f, "\ncontents %08X", (unsigned)l);
1342 fprintf(f, "\n\n");
1344 if (s->sh_type == SHT_NOBITS)
1345 return;
1347 if (0 == l)
1348 return;
1350 if (s->sh_type == SHT_SYMTAB)
1351 m = sizeof(ElfW(Sym));
1352 else if (s->sh_type == SHT_RELX)
1353 m = sizeof(ElfW_Rel);
1354 else
1355 m = 16;
1357 fprintf(f, "%-8s", "offset");
1358 for (i = 0; i < m; ++i)
1359 fprintf(f, " %02x", i);
1360 n = 56;
1362 if (s->sh_type == SHT_SYMTAB || s->sh_type == SHT_RELX) {
1363 const char *fields1[] = {
1364 "name",
1365 "value",
1366 "size",
1367 "bind",
1368 "type",
1369 "other",
1370 "shndx",
1371 NULL
1374 const char *fields2[] = {
1375 "offs",
1376 "type",
1377 "symb",
1378 NULL
1381 const char **p;
1383 if (s->sh_type == SHT_SYMTAB)
1384 p = fields1, n = 106;
1385 else
1386 p = fields2, n = 58;
1388 for (i = 0; p[i]; ++i)
1389 fprintf(f, "%6s", p[i]);
1390 fprintf(f, " symbol");
1393 fprintf(f, "\n");
1394 for (i = 0; i < n; ++i)
1395 fprintf(f, "-");
1396 fprintf(f, "\n");
1398 for (i = 0; i < l;)
1400 fprintf(f, "%08X", i);
1401 for (n = 0; n < m; ++n) {
1402 if (n + i < l)
1403 fprintf(f, " %02X", p[i + n]);
1404 else
1405 fprintf(f, " ");
1408 if (s->sh_type == SHT_SYMTAB) {
1409 ElfW(Sym) *sym = (ElfW(Sym) *) (p + i);
1410 const char *name = s->link->data + sym->st_name;
1411 fprintf(f, " %04X %04X %04X %02X %02X %02X %04X \"%s\"",
1412 (unsigned)sym->st_name,
1413 (unsigned)sym->st_value,
1414 (unsigned)sym->st_size,
1415 (unsigned)ELFW(ST_BIND)(sym->st_info),
1416 (unsigned)ELFW(ST_TYPE)(sym->st_info),
1417 (unsigned)sym->st_other,
1418 (unsigned)sym->st_shndx,
1419 name);
1421 } else if (s->sh_type == SHT_RELX) {
1422 ElfW_Rel *rel = (ElfW_Rel *) (p + i);
1423 ElfW(Sym) *sym =
1424 (ElfW(Sym) *) s->link->data + ELFW(R_SYM)(rel->r_info);
1425 const char *name = s->link->link->data + sym->st_name;
1426 fprintf(f, " %04X %02X %04X \"%s\"",
1427 (unsigned)rel->r_offset,
1428 (unsigned)ELFW(R_TYPE)(rel->r_info),
1429 (unsigned)ELFW(R_SYM)(rel->r_info),
1430 name);
1431 } else {
1432 fprintf(f, " ");
1433 for (n = 0; n < m; ++n) {
1434 if (n + i < l) {
1435 b = p[i + n];
1436 if (b < 32 || b >= 127)
1437 b = '.';
1438 fprintf(f, "%c", b);
1442 i += m;
1443 fprintf(f, "\n");
1445 fprintf(f, "\n\n");
1448 static void pe_print_sections(TCCState *s1, const char *fname)
1450 Section *s;
1451 FILE *f;
1452 int i;
1453 f = fopen(fname, "w");
1454 for (i = 1; i < s1->nb_sections; ++i) {
1455 s = s1->sections[i];
1456 pe_print_section(f, s);
1458 pe_print_section(f, s1->dynsymtab_section);
1459 fclose(f);
1461 #endif
1463 /* ------------------------------------------------------------- */
1464 /* helper function for load/store to insert one more indirection */
1466 #ifndef TCC_TARGET_ARM
1467 ST_FUNC SValue *pe_getimport(SValue *sv, SValue *v2)
1469 Sym *sym;
1470 ElfW(Sym) *esym;
1471 int r2;
1473 if ((sv->r & (VT_VALMASK|VT_SYM)) != (VT_CONST|VT_SYM) || (sv->r2 != VT_CONST))
1474 return sv;
1475 sym = sv->sym;
1476 if ((sym->type.t & (VT_EXTERN|VT_STATIC)) != VT_EXTERN)
1477 return sv;
1478 if (!sym->c)
1479 put_extern_sym(sym, NULL, 0, 0);
1480 esym = &((ElfW(Sym) *)symtab_section->data)[sym->c];
1481 if (!(esym->st_other & ST_PE_IMPORT))
1482 return sv;
1484 // printf("import %04x %04x %04x %s\n", sv->type.t, sym->type.t, sv->r, get_tok_str(sv->sym->v, NULL));
1486 memset(v2, 0, sizeof *v2);
1487 v2->type.t = VT_PTR;
1488 v2->r = VT_CONST | VT_SYM | VT_LVAL;
1489 v2->sym = sv->sym;
1491 r2 = get_reg(RC_INT);
1492 load(r2, v2);
1493 v2->r = r2;
1495 if ((uint32_t)sv->c.i) {
1496 vpushv(v2);
1497 vpushi(sv->c.i);
1498 gen_opi('+');
1499 *v2 = *vtop--;
1502 v2->type.t = sv->type.t;
1503 v2->r |= sv->r & VT_LVAL;
1504 return v2;
1506 #endif
1508 ST_FUNC int pe_putimport(TCCState *s1, int dllindex, const char *name, addr_t value)
1510 return set_elf_sym(
1511 s1->dynsymtab_section,
1512 value,
1513 dllindex, /* st_size */
1514 ELFW(ST_INFO)(STB_GLOBAL, STT_NOTYPE),
1516 value ? SHN_ABS : SHN_UNDEF,
1517 name
1521 static int add_dllref(TCCState *s1, const char *dllname)
1523 DLLReference *dllref;
1524 int i;
1525 for (i = 0; i < s1->nb_loaded_dlls; ++i)
1526 if (0 == strcmp(s1->loaded_dlls[i]->name, dllname))
1527 return i + 1;
1528 dllref = tcc_mallocz(sizeof(DLLReference) + strlen(dllname));
1529 strcpy(dllref->name, dllname);
1530 dynarray_add(&s1->loaded_dlls, &s1->nb_loaded_dlls, dllref);
1531 return s1->nb_loaded_dlls;
1534 /* ------------------------------------------------------------- */
1536 static int read_mem(int fd, unsigned offset, void *buffer, unsigned len)
1538 lseek(fd, offset, SEEK_SET);
1539 return len == read(fd, buffer, len);
1542 /* -------------------------------------------------------------
1543 * This is for compiled windows resources in 'coff' format
1544 * as generated by 'windres.exe -O coff ...'.
1547 static int pe_load_res(TCCState *s1, int fd)
1549 struct pe_rsrc_header hdr;
1550 Section *rsrc_section;
1551 int i, ret = -1;
1552 BYTE *ptr;
1553 unsigned offs;
1555 if (!read_mem(fd, 0, &hdr, sizeof hdr))
1556 goto quit;
1558 if (hdr.filehdr.Machine != IMAGE_FILE_MACHINE
1559 || hdr.filehdr.NumberOfSections != 1
1560 || strcmp(hdr.sectionhdr.Name, ".rsrc") != 0)
1561 goto quit;
1563 rsrc_section = new_section(s1, ".rsrc", SHT_PROGBITS, SHF_ALLOC);
1564 ptr = section_ptr_add(rsrc_section, hdr.sectionhdr.SizeOfRawData);
1565 offs = hdr.sectionhdr.PointerToRawData;
1566 if (!read_mem(fd, offs, ptr, hdr.sectionhdr.SizeOfRawData))
1567 goto quit;
1568 offs = hdr.sectionhdr.PointerToRelocations;
1569 for (i = 0; i < hdr.sectionhdr.NumberOfRelocations; ++i)
1571 struct pe_rsrc_reloc rel;
1572 if (!read_mem(fd, offs, &rel, sizeof rel))
1573 goto quit;
1574 // printf("rsrc_reloc: %x %x %x\n", rel.offset, rel.size, rel.type);
1575 if (rel.type != RSRC_RELTYPE)
1576 goto quit;
1577 put_elf_reloc(symtab_section, rsrc_section,
1578 rel.offset, R_XXX_RELATIVE, 0);
1579 offs += sizeof rel;
1581 ret = 0;
1582 quit:
1583 return ret;
1586 /* ------------------------------------------------------------- */
1588 static char *trimfront(char *p)
1590 while (*p && (unsigned char)*p <= ' ')
1591 ++p;
1592 return p;
1595 static char *trimback(char *a, char *e)
1597 while (e > a && (unsigned char)e[-1] <= ' ')
1598 --e;
1599 *e = 0;;
1600 return a;
1603 /* ------------------------------------------------------------- */
1604 static int pe_load_def(TCCState *s1, int fd)
1606 int state = 0, ret = -1, dllindex = 0, ord;
1607 char line[400], dllname[80], *p, *x;
1608 FILE *fp;
1610 fp = fdopen(dup(fd), "rb");
1611 while (fgets(line, sizeof line, fp))
1613 p = trimfront(trimback(line, strchr(line, 0)));
1614 if (0 == *p || ';' == *p)
1615 continue;
1617 switch (state) {
1618 case 0:
1619 if (0 != strnicmp(p, "LIBRARY", 7))
1620 goto quit;
1621 pstrcpy(dllname, sizeof dllname, trimfront(p+7));
1622 ++state;
1623 continue;
1625 case 1:
1626 if (0 != stricmp(p, "EXPORTS"))
1627 goto quit;
1628 ++state;
1629 continue;
1631 case 2:
1632 dllindex = add_dllref(s1, dllname);
1633 ++state;
1634 /* fall through */
1635 default:
1636 /* get ordinal and will store in sym->st_value */
1637 ord = 0;
1638 x = strchr(p, ' ');
1639 if (x) {
1640 *x = 0, x = strrchr(x + 1, '@');
1641 if (x) {
1642 char *d;
1643 ord = (int)strtol(x + 1, &d, 10);
1644 if (*d)
1645 ord = 0;
1648 pe_putimport(s1, dllindex, p, ord);
1649 continue;
1652 ret = 0;
1653 quit:
1654 fclose(fp);
1655 return ret;
1658 /* ------------------------------------------------------------- */
1659 #define TINY_IMPDEF_GET_EXPORT_NAMES_ONLY
1660 #include "win32/tools/tiny_impdef.c"
1662 static int pe_load_dll(TCCState *s1, const char *dllname, int fd)
1664 char *p, *q;
1665 int index;
1666 p = get_export_names(fd);
1667 if (!p)
1668 return -1;
1669 index = add_dllref(s1, dllname);
1670 for (q = p; *q; q += 1 + strlen(q))
1671 pe_putimport(s1, index, q, 0);
1672 tcc_free(p);
1673 return 0;
1676 /* ------------------------------------------------------------- */
1677 ST_FUNC int pe_load_file(struct TCCState *s1, const char *filename, int fd)
1679 int ret = -1;
1680 char buf[10];
1681 if (0 == strcmp(tcc_fileextension(filename), ".def"))
1682 ret = pe_load_def(s1, fd);
1683 else if (pe_load_res(s1, fd) == 0)
1684 ret = 0;
1685 else if (read_mem(fd, 0, buf, 4) && 0 == memcmp(buf, "MZ\220", 4))
1686 ret = pe_load_dll(s1, tcc_basename(filename), fd);
1687 return ret;
1690 /* ------------------------------------------------------------- */
1691 #ifdef TCC_TARGET_X86_64
1692 static unsigned pe_add_uwwind_info(TCCState *s1)
1694 if (NULL == s1->uw_pdata) {
1695 s1->uw_pdata = find_section(tcc_state, ".pdata");
1696 s1->uw_pdata->sh_addralign = 4;
1697 s1->uw_sym = put_elf_sym(symtab_section, 0, 0, 0, 0, text_section->sh_num, NULL);
1700 if (0 == s1->uw_offs) {
1701 /* As our functions all have the same stackframe, we use one entry for all */
1702 static const unsigned char uw_info[] = {
1703 0x01, // UBYTE: 3 Version , UBYTE: 5 Flags
1704 0x04, // UBYTE Size of prolog
1705 0x02, // UBYTE Count of unwind codes
1706 0x05, // UBYTE: 4 Frame Register (rbp), UBYTE: 4 Frame Register offset (scaled)
1707 // USHORT * n Unwind codes array
1708 // 0x0b, 0x01, 0xff, 0xff, // stack size
1709 0x04, 0x03, // set frame ptr (mov rsp -> rbp)
1710 0x01, 0x50 // push reg (rbp)
1713 Section *s = text_section;
1714 unsigned char *p;
1716 section_ptr_add(s, -s->data_offset & 3); /* align */
1717 s1->uw_offs = s->data_offset;
1718 p = section_ptr_add(s, sizeof uw_info);
1719 memcpy(p, uw_info, sizeof uw_info);
1722 return s1->uw_offs;
1725 ST_FUNC void pe_add_unwind_data(unsigned start, unsigned end, unsigned stack)
1727 TCCState *s1 = tcc_state;
1728 Section *pd;
1729 unsigned o, n, d;
1730 struct /* _RUNTIME_FUNCTION */ {
1731 DWORD BeginAddress;
1732 DWORD EndAddress;
1733 DWORD UnwindData;
1734 } *p;
1736 d = pe_add_uwwind_info(s1);
1737 pd = s1->uw_pdata;
1738 o = pd->data_offset;
1739 p = section_ptr_add(pd, sizeof *p);
1741 /* record this function */
1742 p->BeginAddress = start;
1743 p->EndAddress = end;
1744 p->UnwindData = d;
1746 /* put relocations on it */
1747 for (n = o + sizeof *p; o < n; o += sizeof p->BeginAddress)
1748 put_elf_reloc(symtab_section, pd, o, R_X86_64_RELATIVE, s1->uw_sym);
1750 #endif
1751 /* ------------------------------------------------------------- */
1752 #ifdef TCC_TARGET_X86_64
1753 #define PE_STDSYM(n,s) n
1754 #else
1755 #define PE_STDSYM(n,s) "_" n s
1756 #endif
1758 static void pe_add_runtime(TCCState *s1, struct pe_info *pe)
1760 const char *start_symbol;
1761 int pe_type = 0;
1763 if (find_elf_sym(symtab_section, PE_STDSYM("WinMain","@16")))
1764 pe_type = PE_GUI;
1765 else
1766 if (TCC_OUTPUT_DLL == s1->output_type) {
1767 pe_type = PE_DLL;
1768 /* need this for 'tccelf.c:relocate_section()' */
1769 s1->output_type = TCC_OUTPUT_EXE;
1771 else
1772 pe_type = PE_EXE;
1774 start_symbol =
1775 TCC_OUTPUT_MEMORY == s1->output_type
1776 ? PE_GUI == pe_type ? "__runwinmain" : "_main"
1777 : PE_DLL == pe_type ? PE_STDSYM("__dllstart","@12")
1778 : PE_GUI == pe_type ? "__winstart" : "__start"
1781 if (!s1->leading_underscore || strchr(start_symbol, '@'))
1782 ++start_symbol;
1784 /* grab the startup code from libtcc1 */
1785 if (TCC_OUTPUT_MEMORY != s1->output_type || PE_GUI == pe_type)
1786 set_elf_sym(symtab_section,
1787 0, 0,
1788 ELFW(ST_INFO)(STB_GLOBAL, STT_NOTYPE), 0,
1789 SHN_UNDEF, start_symbol);
1791 tcc_add_pragma_libs(s1);
1793 if (0 == s1->nostdlib) {
1794 static const char *libs[] = {
1795 "tcc1", "msvcrt", "kernel32", "", "user32", "gdi32", NULL
1797 const char **pp, *p;
1798 for (pp = libs; 0 != (p = *pp); ++pp) {
1799 if (0 == *p) {
1800 if (PE_DLL != pe_type && PE_GUI != pe_type)
1801 break;
1802 } else if (tcc_add_library_err(s1, p) < 0) {
1803 break;
1808 if (TCC_OUTPUT_MEMORY == s1->output_type) {
1809 pe_type = PE_RUN;
1810 #ifdef TCC_IS_NATIVE
1811 s1->runtime_main = start_symbol;
1812 #endif
1813 } else {
1814 pe->start_addr = (DWORD)(uintptr_t)tcc_get_symbol_err(s1, start_symbol);
1817 pe->type = pe_type;
1820 static void pe_set_options(TCCState * s1, struct pe_info *pe)
1822 if (PE_DLL == pe->type) {
1823 /* XXX: check if is correct for arm-pe target */
1824 pe->imagebase = 0x10000000;
1825 } else {
1826 #if defined(TCC_TARGET_ARM)
1827 pe->imagebase = 0x00010000;
1828 #else
1829 pe->imagebase = 0x00400000;
1830 #endif
1833 #if defined(TCC_TARGET_ARM)
1834 /* we use "console" subsystem by default */
1835 pe->subsystem = 9;
1836 #else
1837 if (PE_DLL == pe->type || PE_GUI == pe->type)
1838 pe->subsystem = 2;
1839 else
1840 pe->subsystem = 3;
1841 #endif
1842 /* Allow override via -Wl,-subsystem=... option */
1843 if (s1->pe_subsystem != 0)
1844 pe->subsystem = s1->pe_subsystem;
1846 /* set default file/section alignment */
1847 if (pe->subsystem == 1) {
1848 pe->section_align = 0x20;
1849 pe->file_align = 0x20;
1850 } else {
1851 pe->section_align = 0x1000;
1852 pe->file_align = 0x200;
1855 if (s1->section_align != 0)
1856 pe->section_align = s1->section_align;
1857 if (s1->pe_file_align != 0)
1858 pe->file_align = s1->pe_file_align;
1860 if ((pe->subsystem >= 10) && (pe->subsystem <= 12))
1861 pe->imagebase = 0;
1863 if (s1->has_text_addr)
1864 pe->imagebase = s1->text_addr;
1867 ST_FUNC int pe_output_file(TCCState *s1, const char *filename)
1869 int ret;
1870 struct pe_info pe;
1871 int i;
1873 memset(&pe, 0, sizeof pe);
1874 pe.filename = filename;
1875 pe.s1 = s1;
1877 tcc_add_bcheck(s1);
1878 pe_add_runtime(s1, &pe);
1879 relocate_common_syms(); /* assign bss adresses */
1880 tcc_add_linker_symbols(s1);
1881 pe_set_options(s1, &pe);
1883 ret = pe_check_symbols(&pe);
1884 if (ret)
1886 else if (filename) {
1887 pe_assign_addresses(&pe);
1888 relocate_syms(s1, s1->symtab, 0);
1889 for (i = 1; i < s1->nb_sections; ++i) {
1890 Section *s = s1->sections[i];
1891 if (s->reloc) {
1892 relocate_section(s1, s);
1893 pe_relocate_rva(&pe, s);
1896 if (s1->nb_errors)
1897 ret = -1;
1898 else
1899 ret = pe_write(&pe);
1900 tcc_free(pe.sec_info);
1901 } else {
1902 #ifdef TCC_IS_NATIVE
1903 pe.thunk = data_section;
1904 pe_build_imports(&pe);
1905 #endif
1908 pe_free_imports(&pe);
1910 #ifdef PE_PRINT_SECTIONS
1911 pe_print_sections(s1, "tcc.log");
1912 #endif
1913 return ret;
1916 /* ------------------------------------------------------------- */