x86-64: fix flags and zero-pad long doubles
[tinycc.git] / tccpe.c
blobfb545230675cdebcd3a81f4e0e35b47b0a2f4f71
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 #ifndef _WIN32
24 #define stricmp strcasecmp
25 #define strnicmp strncasecmp
26 #endif
28 #ifndef MAX_PATH
29 #define MAX_PATH 260
30 #endif
32 #define PE_MERGE_DATA
33 // #define PE_PRINT_SECTIONS
35 #ifdef TCC_TARGET_X86_64
36 # define ADDR3264 ULONGLONG
37 #else
38 # define ADDR3264 DWORD
39 #endif
41 #if defined _WIN32 && (defined _WIN64) == (defined TCC_TARGET_X86_64)
42 #define TCC_IS_NATIVE
43 #endif
45 #ifdef _WIN32
46 void dbg_printf (const char *fmt, ...)
48 char buffer[4000];
49 va_list arg;
50 int x;
51 va_start(arg, fmt);
52 x = vsprintf (buffer, fmt, arg);
53 strcpy(buffer+x, "\n");
54 OutputDebugString(buffer);
56 #endif
58 /* ----------------------------------------------------------- */
59 #ifndef IMAGE_NT_SIGNATURE
60 /* ----------------------------------------------------------- */
61 /* definitions below are from winnt.h */
63 typedef unsigned char BYTE;
64 typedef unsigned short WORD;
65 typedef unsigned int DWORD;
66 typedef unsigned long long ULONGLONG;
67 #pragma pack(push, 1)
69 typedef struct _IMAGE_DOS_HEADER { /* DOS .EXE header */
70 WORD e_magic; /* Magic number */
71 WORD e_cblp; /* Bytes on last page of file */
72 WORD e_cp; /* Pages in file */
73 WORD e_crlc; /* Relocations */
74 WORD e_cparhdr; /* Size of header in paragraphs */
75 WORD e_minalloc; /* Minimum extra paragraphs needed */
76 WORD e_maxalloc; /* Maximum extra paragraphs needed */
77 WORD e_ss; /* Initial (relative) SS value */
78 WORD e_sp; /* Initial SP value */
79 WORD e_csum; /* Checksum */
80 WORD e_ip; /* Initial IP value */
81 WORD e_cs; /* Initial (relative) CS value */
82 WORD e_lfarlc; /* File address of relocation table */
83 WORD e_ovno; /* Overlay number */
84 WORD e_res[4]; /* Reserved words */
85 WORD e_oemid; /* OEM identifier (for e_oeminfo) */
86 WORD e_oeminfo; /* OEM information; e_oemid specific */
87 WORD e_res2[10]; /* Reserved words */
88 DWORD e_lfanew; /* File address of new exe header */
89 } IMAGE_DOS_HEADER, *PIMAGE_DOS_HEADER;
91 #define IMAGE_NT_SIGNATURE 0x00004550 /* PE00 */
92 #define SIZE_OF_NT_SIGNATURE 4
94 typedef struct _IMAGE_FILE_HEADER {
95 WORD Machine;
96 WORD NumberOfSections;
97 DWORD TimeDateStamp;
98 DWORD PointerToSymbolTable;
99 DWORD NumberOfSymbols;
100 WORD SizeOfOptionalHeader;
101 WORD Characteristics;
102 } IMAGE_FILE_HEADER, *PIMAGE_FILE_HEADER;
105 #define IMAGE_SIZEOF_FILE_HEADER 20
107 typedef struct _IMAGE_DATA_DIRECTORY {
108 DWORD VirtualAddress;
109 DWORD Size;
110 } IMAGE_DATA_DIRECTORY, *PIMAGE_DATA_DIRECTORY;
113 typedef struct _IMAGE_OPTIONAL_HEADER {
114 /* Standard fields. */
115 WORD Magic;
116 BYTE MajorLinkerVersion;
117 BYTE MinorLinkerVersion;
118 DWORD SizeOfCode;
119 DWORD SizeOfInitializedData;
120 DWORD SizeOfUninitializedData;
121 DWORD AddressOfEntryPoint;
122 DWORD BaseOfCode;
123 #ifndef TCC_TARGET_X86_64
124 DWORD BaseOfData;
125 #endif
126 /* NT additional fields. */
127 ADDR3264 ImageBase;
128 DWORD SectionAlignment;
129 DWORD FileAlignment;
130 WORD MajorOperatingSystemVersion;
131 WORD MinorOperatingSystemVersion;
132 WORD MajorImageVersion;
133 WORD MinorImageVersion;
134 WORD MajorSubsystemVersion;
135 WORD MinorSubsystemVersion;
136 DWORD Win32VersionValue;
137 DWORD SizeOfImage;
138 DWORD SizeOfHeaders;
139 DWORD CheckSum;
140 WORD Subsystem;
141 WORD DllCharacteristics;
142 ADDR3264 SizeOfStackReserve;
143 ADDR3264 SizeOfStackCommit;
144 ADDR3264 SizeOfHeapReserve;
145 ADDR3264 SizeOfHeapCommit;
146 DWORD LoaderFlags;
147 DWORD NumberOfRvaAndSizes;
148 IMAGE_DATA_DIRECTORY DataDirectory[16];
149 } IMAGE_OPTIONAL_HEADER32, IMAGE_OPTIONAL_HEADER64, IMAGE_OPTIONAL_HEADER;
151 #define IMAGE_DIRECTORY_ENTRY_EXPORT 0 /* Export Directory */
152 #define IMAGE_DIRECTORY_ENTRY_IMPORT 1 /* Import Directory */
153 #define IMAGE_DIRECTORY_ENTRY_RESOURCE 2 /* Resource Directory */
154 #define IMAGE_DIRECTORY_ENTRY_EXCEPTION 3 /* Exception Directory */
155 #define IMAGE_DIRECTORY_ENTRY_SECURITY 4 /* Security Directory */
156 #define IMAGE_DIRECTORY_ENTRY_BASERELOC 5 /* Base Relocation Table */
157 #define IMAGE_DIRECTORY_ENTRY_DEBUG 6 /* Debug Directory */
158 /* IMAGE_DIRECTORY_ENTRY_COPYRIGHT 7 (X86 usage) */
159 #define IMAGE_DIRECTORY_ENTRY_ARCHITECTURE 7 /* Architecture Specific Data */
160 #define IMAGE_DIRECTORY_ENTRY_GLOBALPTR 8 /* RVA of GP */
161 #define IMAGE_DIRECTORY_ENTRY_TLS 9 /* TLS Directory */
162 #define IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG 10 /* Load Configuration Directory */
163 #define IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT 11 /* Bound Import Directory in headers */
164 #define IMAGE_DIRECTORY_ENTRY_IAT 12 /* Import Address Table */
165 #define IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT 13 /* Delay Load Import Descriptors */
166 #define IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR 14 /* COM Runtime descriptor */
168 /* Section header format. */
169 #define IMAGE_SIZEOF_SHORT_NAME 8
171 typedef struct _IMAGE_SECTION_HEADER {
172 BYTE Name[IMAGE_SIZEOF_SHORT_NAME];
173 union {
174 DWORD PhysicalAddress;
175 DWORD VirtualSize;
176 } Misc;
177 DWORD VirtualAddress;
178 DWORD SizeOfRawData;
179 DWORD PointerToRawData;
180 DWORD PointerToRelocations;
181 DWORD PointerToLinenumbers;
182 WORD NumberOfRelocations;
183 WORD NumberOfLinenumbers;
184 DWORD Characteristics;
185 } IMAGE_SECTION_HEADER, *PIMAGE_SECTION_HEADER;
187 #define IMAGE_SIZEOF_SECTION_HEADER 40
189 typedef struct _IMAGE_EXPORT_DIRECTORY {
190 DWORD Characteristics;
191 DWORD TimeDateStamp;
192 WORD MajorVersion;
193 WORD MinorVersion;
194 DWORD Name;
195 DWORD Base;
196 DWORD NumberOfFunctions;
197 DWORD NumberOfNames;
198 DWORD AddressOfFunctions;
199 DWORD AddressOfNames;
200 DWORD AddressOfNameOrdinals;
201 } IMAGE_EXPORT_DIRECTORY,*PIMAGE_EXPORT_DIRECTORY;
203 typedef struct _IMAGE_IMPORT_DESCRIPTOR {
204 union {
205 DWORD Characteristics;
206 DWORD OriginalFirstThunk;
208 DWORD TimeDateStamp;
209 DWORD ForwarderChain;
210 DWORD Name;
211 DWORD FirstThunk;
212 } IMAGE_IMPORT_DESCRIPTOR;
214 typedef struct _IMAGE_BASE_RELOCATION {
215 DWORD VirtualAddress;
216 DWORD SizeOfBlock;
217 // WORD TypeOffset[1];
218 } IMAGE_BASE_RELOCATION;
220 #define IMAGE_SIZEOF_BASE_RELOCATION 8
222 #define IMAGE_REL_BASED_ABSOLUTE 0
223 #define IMAGE_REL_BASED_HIGH 1
224 #define IMAGE_REL_BASED_LOW 2
225 #define IMAGE_REL_BASED_HIGHLOW 3
226 #define IMAGE_REL_BASED_HIGHADJ 4
227 #define IMAGE_REL_BASED_MIPS_JMPADDR 5
228 #define IMAGE_REL_BASED_SECTION 6
229 #define IMAGE_REL_BASED_REL32 7
231 #pragma pack(pop)
233 /* ----------------------------------------------------------- */
234 #endif /* ndef IMAGE_NT_SIGNATURE */
235 /* ----------------------------------------------------------- */
236 #pragma pack(push, 1)
238 struct pe_header
240 IMAGE_DOS_HEADER doshdr;
241 BYTE dosstub[0x40];
242 DWORD nt_sig;
243 IMAGE_FILE_HEADER filehdr;
244 #ifdef TCC_TARGET_X86_64
245 IMAGE_OPTIONAL_HEADER64 opthdr;
246 #else
247 #ifdef _WIN64
248 IMAGE_OPTIONAL_HEADER32 opthdr;
249 #else
250 IMAGE_OPTIONAL_HEADER opthdr;
251 #endif
252 #endif
255 struct pe_reloc_header {
256 DWORD offset;
257 DWORD size;
260 struct pe_rsrc_header {
261 struct _IMAGE_FILE_HEADER filehdr;
262 struct _IMAGE_SECTION_HEADER sectionhdr;
265 struct pe_rsrc_reloc {
266 DWORD offset;
267 DWORD size;
268 WORD type;
271 #pragma pack(pop)
273 /* ------------------------------------------------------------- */
274 /* internal temporary structures */
277 #define IMAGE_SCN_CNT_CODE 0x00000020
278 #define IMAGE_SCN_CNT_INITIALIZED_DATA 0x00000040
279 #define IMAGE_SCN_CNT_UNINITIALIZED_DATA 0x00000080
280 #define IMAGE_SCN_MEM_DISCARDABLE 0x02000000
281 #define IMAGE_SCN_MEM_SHARED 0x10000000
282 #define IMAGE_SCN_MEM_EXECUTE 0x20000000
283 #define IMAGE_SCN_MEM_READ 0x40000000
284 #define IMAGE_SCN_MEM_WRITE 0x80000000
287 enum {
288 sec_text = 0,
289 sec_data ,
290 sec_bss ,
291 sec_idata ,
292 sec_pdata ,
293 sec_other ,
294 sec_rsrc ,
295 sec_stab ,
296 sec_reloc ,
297 sec_last
300 static const DWORD pe_sec_flags[] = {
301 0x60000020, /* ".text" , */
302 0xC0000040, /* ".data" , */
303 0xC0000080, /* ".bss" , */
304 0x40000040, /* ".idata" , */
305 0x40000040, /* ".pdata" , */
306 0xE0000060, /* < other > , */
307 0x40000040, /* ".rsrc" , */
308 0x42000802, /* ".stab" , */
309 0x42000040, /* ".reloc" , */
312 struct section_info {
313 int cls, ord;
314 char name[32];
315 DWORD sh_addr;
316 DWORD sh_size;
317 DWORD sh_flags;
318 unsigned char *data;
319 DWORD data_size;
320 IMAGE_SECTION_HEADER ish;
323 struct import_symbol {
324 int sym_index;
325 int iat_index;
326 int thk_offset;
329 struct pe_import_info {
330 int dll_index;
331 int sym_count;
332 struct import_symbol **symbols;
335 struct pe_info {
336 TCCState *s1;
337 Section *reloc;
338 Section *thunk;
339 const char *filename;
340 int type;
341 DWORD sizeofheaders;
342 DWORD imagebase;
343 DWORD start_addr;
344 DWORD imp_offs;
345 DWORD imp_size;
346 DWORD iat_offs;
347 DWORD iat_size;
348 DWORD exp_offs;
349 DWORD exp_size;
350 int subsystem;
351 DWORD section_align;
352 DWORD file_align;
353 struct section_info *sec_info;
354 int sec_count;
355 struct pe_import_info **imp_info;
356 int imp_count;
359 #define PE_NUL 0
360 #define PE_DLL 1
361 #define PE_GUI 2
362 #define PE_EXE 3
363 #define PE_RUN 4
365 /* --------------------------------------------*/
367 static const char *pe_export_name(TCCState *s1, ElfW(Sym) *sym)
369 const char *name = symtab_section->link->data + sym->st_name;
370 if (s1->leading_underscore && name[0] == '_' && !(sym->st_other & 2))
371 return name + 1;
372 return name;
375 static int pe_find_import(TCCState * s1, ElfW(Sym) *sym)
377 char buffer[200];
378 const char *s, *p;
379 int sym_index = 0, n = 0;
381 do {
382 s = pe_export_name(s1, sym);
383 if (n) {
384 /* second try: */
385 if (sym->st_other & 2) {
386 /* try w/0 stdcall deco (windows API convention) */
387 p = strrchr(s, '@');
388 if (!p || s[0] != '_')
389 break;
390 strcpy(buffer, s+1)[p-s-1] = 0;
391 } else if (s[0] != '_') { /* try non-ansi function */
392 buffer[0] = '_', strcpy(buffer + 1, s);
393 } else if (0 == memcmp(s, "__imp__", 7)) { /* mingw 2.0 */
394 strcpy(buffer, s + 6);
395 } else if (0 == memcmp(s, "_imp___", 7)) { /* mingw 3.7 */
396 strcpy(buffer, s + 6);
397 } else {
398 break;
400 s = buffer;
402 sym_index = find_elf_sym(s1->dynsymtab_section, s);
403 // printf("find (%d) %d %s\n", n, sym_index, s);
404 } while (0 == sym_index && ++n < 2);
405 return sym_index;
408 /*----------------------------------------------------------------------------*/
410 static int dynarray_assoc(void **pp, int n, int key)
412 int i;
413 for (i = 0; i < n; ++i, ++pp)
414 if (key == **(int **) pp)
415 return i;
416 return -1;
419 #if 0
420 ST_FN DWORD umin(DWORD a, DWORD b)
422 return a < b ? a : b;
424 #endif
426 static DWORD umax(DWORD a, DWORD b)
428 return a < b ? b : a;
431 static DWORD pe_file_align(struct pe_info *pe, DWORD n)
433 return (n + (pe->file_align - 1)) & ~(pe->file_align - 1);
436 static DWORD pe_virtual_align(struct pe_info *pe, DWORD n)
438 return (n + (pe->section_align - 1)) & ~(pe->section_align - 1);
441 static void pe_align_section(Section *s, int a)
443 int i = s->data_offset & (a-1);
444 if (i)
445 section_ptr_add(s, a - i);
448 static void pe_set_datadir(struct pe_header *hdr, int dir, DWORD addr, DWORD size)
450 hdr->opthdr.DataDirectory[dir].VirtualAddress = addr;
451 hdr->opthdr.DataDirectory[dir].Size = size;
454 static int pe_fwrite(void *data, unsigned len, FILE *fp, DWORD *psum)
456 if (psum) {
457 DWORD sum = *psum;
458 WORD *p = data;
459 int i;
460 for (i = len; i > 0; i -= 2) {
461 sum += (i >= 2) ? *p++ : *(BYTE*)p;
462 sum = (sum + (sum >> 16)) & 0xFFFF;
464 *psum = sum;
466 return len == fwrite(data, 1, len, fp) ? 0 : -1;
469 static void pe_fpad(FILE *fp, DWORD new_pos)
471 DWORD pos = ftell(fp);
472 while (++pos <= new_pos)
473 fputc(0, fp);
476 /*----------------------------------------------------------------------------*/
477 static int pe_write(struct pe_info *pe)
479 static const struct pe_header pe_template = {
481 /* IMAGE_DOS_HEADER doshdr */
482 0x5A4D, /*WORD e_magic; Magic number */
483 0x0090, /*WORD e_cblp; Bytes on last page of file */
484 0x0003, /*WORD e_cp; Pages in file */
485 0x0000, /*WORD e_crlc; Relocations */
487 0x0004, /*WORD e_cparhdr; Size of header in paragraphs */
488 0x0000, /*WORD e_minalloc; Minimum extra paragraphs needed */
489 0xFFFF, /*WORD e_maxalloc; Maximum extra paragraphs needed */
490 0x0000, /*WORD e_ss; Initial (relative) SS value */
492 0x00B8, /*WORD e_sp; Initial SP value */
493 0x0000, /*WORD e_csum; Checksum */
494 0x0000, /*WORD e_ip; Initial IP value */
495 0x0000, /*WORD e_cs; Initial (relative) CS value */
496 0x0040, /*WORD e_lfarlc; File address of relocation table */
497 0x0000, /*WORD e_ovno; Overlay number */
498 {0,0,0,0}, /*WORD e_res[4]; Reserved words */
499 0x0000, /*WORD e_oemid; OEM identifier (for e_oeminfo) */
500 0x0000, /*WORD e_oeminfo; OEM information; e_oemid specific */
501 {0,0,0,0,0,0,0,0,0,0}, /*WORD e_res2[10]; Reserved words */
502 0x00000080 /*DWORD e_lfanew; File address of new exe header */
504 /* BYTE dosstub[0x40] */
505 /* 14 code bytes + "This program cannot be run in DOS mode.\r\r\n$" + 6 * 0x00 */
506 0x0e,0x1f,0xba,0x0e,0x00,0xb4,0x09,0xcd,0x21,0xb8,0x01,0x4c,0xcd,0x21,0x54,0x68,
507 0x69,0x73,0x20,0x70,0x72,0x6f,0x67,0x72,0x61,0x6d,0x20,0x63,0x61,0x6e,0x6e,0x6f,
508 0x74,0x20,0x62,0x65,0x20,0x72,0x75,0x6e,0x20,0x69,0x6e,0x20,0x44,0x4f,0x53,0x20,
509 0x6d,0x6f,0x64,0x65,0x2e,0x0d,0x0d,0x0a,0x24,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
511 0x00004550, /* DWORD nt_sig = IMAGE_NT_SIGNATURE */
513 /* IMAGE_FILE_HEADER filehdr */
514 #if defined(TCC_TARGET_I386)
515 0x014C, /*WORD Machine; */
516 #elif defined(TCC_TARGET_X86_64)
517 0x8664, /*WORD Machine; */
518 #elif defined(TCC_TARGET_ARM)
519 0x01C0, /*WORD Machine; */
520 #endif
521 0x0003, /*WORD NumberOfSections; */
522 0x00000000, /*DWORD TimeDateStamp; */
523 0x00000000, /*DWORD PointerToSymbolTable; */
524 0x00000000, /*DWORD NumberOfSymbols; */
525 #if defined(TCC_TARGET_X86_64)
526 0x00F0, /*WORD SizeOfOptionalHeader; */
527 0x022F /*WORD Characteristics; */
528 #define CHARACTERISTICS_DLL 0x222E
529 #elif defined(TCC_TARGET_I386)
530 0x00E0, /*WORD SizeOfOptionalHeader; */
531 0x030F /*WORD Characteristics; */
532 #define CHARACTERISTICS_DLL 0x230E
533 #elif defined(TCC_TARGET_ARM)
534 0x00E0, /*WORD SizeOfOptionalHeader; */
535 0x010F, /*WORD Characteristics; */
536 #define CHARACTERISTICS_DLL 0x230F
537 #endif
539 /* IMAGE_OPTIONAL_HEADER opthdr */
540 /* Standard fields. */
541 #ifdef TCC_TARGET_X86_64
542 0x020B, /*WORD Magic; */
543 #else
544 0x010B, /*WORD Magic; */
545 #endif
546 0x06, /*BYTE MajorLinkerVersion; */
547 0x00, /*BYTE MinorLinkerVersion; */
548 0x00000000, /*DWORD SizeOfCode; */
549 0x00000000, /*DWORD SizeOfInitializedData; */
550 0x00000000, /*DWORD SizeOfUninitializedData; */
551 0x00000000, /*DWORD AddressOfEntryPoint; */
552 0x00000000, /*DWORD BaseOfCode; */
553 #ifndef TCC_TARGET_X86_64
554 0x00000000, /*DWORD BaseOfData; */
555 #endif
556 /* NT additional fields. */
557 #if defined(TCC_TARGET_ARM)
558 0x00100000, /*DWORD ImageBase; */
559 #else
560 0x00400000, /*DWORD ImageBase; */
561 #endif
562 0x00001000, /*DWORD SectionAlignment; */
563 0x00000200, /*DWORD FileAlignment; */
564 0x0004, /*WORD MajorOperatingSystemVersion; */
565 0x0000, /*WORD MinorOperatingSystemVersion; */
566 0x0000, /*WORD MajorImageVersion; */
567 0x0000, /*WORD MinorImageVersion; */
568 0x0004, /*WORD MajorSubsystemVersion; */
569 0x0000, /*WORD MinorSubsystemVersion; */
570 0x00000000, /*DWORD Win32VersionValue; */
571 0x00000000, /*DWORD SizeOfImage; */
572 0x00000200, /*DWORD SizeOfHeaders; */
573 0x00000000, /*DWORD CheckSum; */
574 0x0002, /*WORD Subsystem; */
575 0x0000, /*WORD DllCharacteristics; */
576 0x00100000, /*DWORD SizeOfStackReserve; */
577 0x00001000, /*DWORD SizeOfStackCommit; */
578 0x00100000, /*DWORD SizeOfHeapReserve; */
579 0x00001000, /*DWORD SizeOfHeapCommit; */
580 0x00000000, /*DWORD LoaderFlags; */
581 0x00000010, /*DWORD NumberOfRvaAndSizes; */
583 /* IMAGE_DATA_DIRECTORY DataDirectory[16]; */
584 {{0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0},
585 {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}}
588 struct pe_header pe_header = pe_template;
590 int i;
591 FILE *op;
592 DWORD file_offset, sum;
593 struct section_info *si;
594 IMAGE_SECTION_HEADER *psh;
596 op = fopen(pe->filename, "wb");
597 if (NULL == op) {
598 error_noabort("could not write '%s': %s", pe->filename, strerror(errno));
599 return -1;
602 pe->sizeofheaders = pe_file_align(pe,
603 sizeof (struct pe_header)
604 + pe->sec_count * sizeof (IMAGE_SECTION_HEADER)
607 file_offset = pe->sizeofheaders;
609 if (2 == pe->s1->verbose)
610 printf("-------------------------------"
611 "\n virt file size section" "\n");
612 for (i = 0; i < pe->sec_count; ++i) {
613 DWORD addr, size;
614 const char *sh_name;
616 si = pe->sec_info + i;
617 sh_name = si->name;
618 addr = si->sh_addr - pe->imagebase;
619 size = si->sh_size;
620 psh = &si->ish;
622 if (2 == pe->s1->verbose)
623 printf("%6x %6x %6x %s\n",
624 (unsigned)addr, (unsigned)file_offset, (unsigned)size, sh_name);
626 switch (si->cls) {
627 case sec_text:
628 pe_header.opthdr.BaseOfCode = addr;
629 pe_header.opthdr.AddressOfEntryPoint = addr + pe->start_addr;
630 break;
632 case sec_data:
633 #ifndef TCC_TARGET_X86_64
634 pe_header.opthdr.BaseOfData = addr;
635 #endif
636 break;
638 case sec_bss:
639 break;
641 case sec_reloc:
642 pe_set_datadir(&pe_header, IMAGE_DIRECTORY_ENTRY_BASERELOC, addr, size);
643 break;
645 case sec_rsrc:
646 pe_set_datadir(&pe_header, IMAGE_DIRECTORY_ENTRY_RESOURCE, addr, size);
647 break;
649 case sec_pdata:
650 pe_set_datadir(&pe_header, IMAGE_DIRECTORY_ENTRY_EXCEPTION, addr, size);
651 break;
653 case sec_stab:
654 break;
657 if (pe->thunk == pe->s1->sections[si->ord]) {
658 if (pe->imp_size) {
659 pe_set_datadir(&pe_header, IMAGE_DIRECTORY_ENTRY_IMPORT,
660 pe->imp_offs + addr, pe->imp_size);
661 pe_set_datadir(&pe_header, IMAGE_DIRECTORY_ENTRY_IAT,
662 pe->iat_offs + addr, pe->iat_size);
664 if (pe->exp_size) {
665 pe_set_datadir(&pe_header, IMAGE_DIRECTORY_ENTRY_EXPORT,
666 pe->exp_offs + addr, pe->exp_size);
670 strcpy((char*)psh->Name, sh_name);
672 psh->Characteristics = pe_sec_flags[si->cls];
673 psh->VirtualAddress = addr;
674 psh->Misc.VirtualSize = size;
675 pe_header.opthdr.SizeOfImage =
676 umax(pe_virtual_align(pe, size + addr), pe_header.opthdr.SizeOfImage);
678 if (si->data_size) {
679 psh->PointerToRawData = file_offset;
680 file_offset = pe_file_align(pe, file_offset + si->data_size);
681 psh->SizeOfRawData = file_offset - psh->PointerToRawData;
685 //pe_header.filehdr.TimeDateStamp = time(NULL);
686 pe_header.filehdr.NumberOfSections = pe->sec_count;
687 pe_header.opthdr.SizeOfHeaders = pe->sizeofheaders;
688 pe_header.opthdr.ImageBase = pe->imagebase;
689 if (pe->s1->pe_stack_size)
690 pe_header.opthdr.SizeOfStackReserve = pe->s1->pe_stack_size;
691 if (PE_DLL == pe->type)
692 pe_header.filehdr.Characteristics = CHARACTERISTICS_DLL;
693 else if (PE_GUI != pe->type)
694 pe_header.opthdr.Subsystem = 3;
695 if (pe->subsystem == 9) // WinCE
696 pe_header.opthdr.Subsystem = 9;
698 sum = 0;
699 pe_fwrite(&pe_header, sizeof pe_header, op, &sum);
700 for (i = 0; i < pe->sec_count; ++i)
701 pe_fwrite(&pe->sec_info[i].ish, sizeof(IMAGE_SECTION_HEADER), op, &sum);
702 pe_fpad(op, pe->sizeofheaders);
703 for (i = 0; i < pe->sec_count; ++i) {
704 si = pe->sec_info + i;
705 psh = &si->ish;
706 if (si->data_size) {
707 pe_fwrite(si->data, si->data_size, op, &sum);
708 file_offset = psh->PointerToRawData + psh->SizeOfRawData;
709 pe_fpad(op, file_offset);
713 pe_header.opthdr.CheckSum = sum + file_offset;
714 fseek(op, offsetof(struct pe_header, opthdr.CheckSum), SEEK_SET);
715 pe_fwrite(&pe_header.opthdr.CheckSum, sizeof pe_header.opthdr.CheckSum, op, NULL);
716 fclose (op);
718 if (2 == pe->s1->verbose)
719 printf("-------------------------------\n");
720 if (pe->s1->verbose)
721 printf("<- %s (%u bytes)\n", pe->filename, (unsigned)file_offset);
723 return 0;
726 /*----------------------------------------------------------------------------*/
728 #if defined(TCC_TARGET_X86_64)
729 #define REL_TYPE_DIRECT R_X86_64_64
730 #define R_XXX_THUNKFIX R_X86_64_PC32
731 #define R_XXX_RELATIVE R_X86_64_RELATIVE
733 #elif defined(TCC_TARGET_I386)
734 #define REL_TYPE_DIRECT R_386_32
735 #define R_XXX_THUNKFIX R_386_32
736 #define R_XXX_RELATIVE R_386_RELATIVE
738 #elif defined(TCC_TARGET_ARM)
739 #define REL_TYPE_DIRECT R_ARM_ABS32
740 #define R_XXX_THUNKFIX R_ARM_ABS32
741 #define R_XXX_RELATIVE R_ARM_RELATIVE
743 #endif
744 /*----------------------------------------------------------------------------*/
746 static struct import_symbol *pe_add_import(struct pe_info *pe, int sym_index)
748 int i;
749 int dll_index;
750 struct pe_import_info *p;
751 struct import_symbol *s;
752 ElfW(Sym) *isym;
754 isym = (ElfW(Sym) *)pe->s1->dynsymtab_section->data + sym_index;
755 dll_index = isym->st_size;
757 i = dynarray_assoc ((void**)pe->imp_info, pe->imp_count, dll_index);
758 if (-1 != i) {
759 p = pe->imp_info[i];
760 goto found_dll;
762 p = tcc_mallocz(sizeof *p);
763 p->dll_index = dll_index;
764 dynarray_add((void***)&pe->imp_info, &pe->imp_count, p);
766 found_dll:
767 i = dynarray_assoc ((void**)p->symbols, p->sym_count, sym_index);
768 if (-1 != i)
769 return p->symbols[i];
771 s = tcc_mallocz(sizeof *s);
772 dynarray_add((void***)&p->symbols, &p->sym_count, s);
773 s->sym_index = sym_index;
774 return s;
777 /*----------------------------------------------------------------------------*/
778 static void pe_build_imports(struct pe_info *pe)
780 int thk_ptr, ent_ptr, dll_ptr, sym_cnt, i;
781 DWORD rva_base = pe->thunk->sh_addr - pe->imagebase;
782 int ndlls = pe->imp_count;
784 for (sym_cnt = i = 0; i < ndlls; ++i)
785 sym_cnt += pe->imp_info[i]->sym_count;
787 if (0 == sym_cnt)
788 return;
790 pe_align_section(pe->thunk, 16);
792 pe->imp_offs = dll_ptr = pe->thunk->data_offset;
793 pe->imp_size = (ndlls + 1) * sizeof(IMAGE_IMPORT_DESCRIPTOR);
794 pe->iat_offs = dll_ptr + pe->imp_size;
795 pe->iat_size = (sym_cnt + ndlls) * sizeof(ADDR3264);
796 section_ptr_add(pe->thunk, pe->imp_size + 2*pe->iat_size);
798 thk_ptr = pe->iat_offs;
799 ent_ptr = pe->iat_offs + pe->iat_size;
801 for (i = 0; i < pe->imp_count; ++i) {
802 IMAGE_IMPORT_DESCRIPTOR *hdr;
803 int k, n, dllindex;
804 ADDR3264 v;
805 struct pe_import_info *p = pe->imp_info[i];
806 const char *name;
807 DLLReference *dllref;
809 dllindex = p->dll_index;
810 if (dllindex)
811 name = (dllref = pe->s1->loaded_dlls[dllindex-1])->name;
812 else
813 name = "", dllref = NULL;
815 /* put the dll name into the import header */
816 v = put_elf_str(pe->thunk, name);
817 hdr = (IMAGE_IMPORT_DESCRIPTOR*)(pe->thunk->data + dll_ptr);
818 hdr->FirstThunk = thk_ptr + rva_base;
819 hdr->OriginalFirstThunk = ent_ptr + rva_base;
820 hdr->Name = v + rva_base;
822 for (k = 0, n = p->sym_count; k <= n; ++k) {
823 if (k < n) {
824 int iat_index = p->symbols[k]->iat_index;
825 int sym_index = p->symbols[k]->sym_index;
826 ElfW(Sym) *imp_sym = (ElfW(Sym) *)pe->s1->dynsymtab_section->data + sym_index;
827 ElfW(Sym) *org_sym = (ElfW(Sym) *)symtab_section->data + iat_index;
828 const char *name = pe->s1->dynsymtab_section->link->data + imp_sym->st_name;
830 org_sym->st_value = thk_ptr;
831 org_sym->st_shndx = pe->thunk->sh_num;
832 v = pe->thunk->data_offset + rva_base;
833 section_ptr_add(pe->thunk, sizeof(WORD)); /* hint, not used */
834 put_elf_str(pe->thunk, name);
835 #ifdef TCC_IS_NATIVE
836 if (pe->type == PE_RUN) {
837 v = imp_sym->st_value;
838 if (dllref) {
839 if ( !dllref->handle )
840 dllref->handle = LoadLibrary(dllref->name);
841 v = (ADDR3264)GetProcAddress(dllref->handle, name);
843 if (!v)
844 error_noabort("undefined symbol '%s'", name);
846 #endif
847 } else {
848 v = 0; /* last entry is zero */
850 *(ADDR3264*)(pe->thunk->data+thk_ptr) =
851 *(ADDR3264*)(pe->thunk->data+ent_ptr) = v;
852 thk_ptr += sizeof (ADDR3264);
853 ent_ptr += sizeof (ADDR3264);
855 dll_ptr += sizeof(IMAGE_IMPORT_DESCRIPTOR);
856 dynarray_reset(&p->symbols, &p->sym_count);
858 dynarray_reset(&pe->imp_info, &pe->imp_count);
861 /* ------------------------------------------------------------- */
863 struct pe_sort_sym
865 int index;
866 const char *name;
869 static int sym_cmp(const void *va, const void *vb)
871 const char *ca = (*(struct pe_sort_sym**)va)->name;
872 const char *cb = (*(struct pe_sort_sym**)vb)->name;
873 return strcmp(ca, cb);
876 static void pe_build_exports(struct pe_info *pe)
878 ElfW(Sym) *sym;
879 int sym_index, sym_end;
880 DWORD rva_base, func_o, name_o, ord_o, str_o;
881 IMAGE_EXPORT_DIRECTORY *hdr;
882 int sym_count, ord;
883 struct pe_sort_sym **sorted, *p;
885 FILE *op;
886 char buf[MAX_PATH];
887 const char *dllname;
888 const char *name;
890 rva_base = pe->thunk->sh_addr - pe->imagebase;
891 sym_count = 0, sorted = NULL, op = NULL;
893 sym_end = symtab_section->data_offset / sizeof(ElfW(Sym));
894 for (sym_index = 1; sym_index < sym_end; ++sym_index) {
895 sym = (ElfW(Sym)*)symtab_section->data + sym_index;
896 name = pe_export_name(pe->s1, sym);
897 if ((sym->st_other & 1)
898 /* export only symbols from actually written sections */
899 && pe->s1->sections[sym->st_shndx]->sh_addr) {
900 p = tcc_malloc(sizeof *p);
901 p->index = sym_index;
902 p->name = name;
903 dynarray_add((void***)&sorted, &sym_count, p);
905 #if 0
906 if (sym->st_other & 1)
907 printf("export: %s\n", name);
908 if (sym->st_other & 2)
909 printf("stdcall: %s\n", name);
910 #endif
913 if (0 == sym_count)
914 return;
916 qsort (sorted, sym_count, sizeof *sorted, sym_cmp);
918 pe_align_section(pe->thunk, 16);
919 dllname = tcc_basename(pe->filename);
921 pe->exp_offs = pe->thunk->data_offset;
922 func_o = pe->exp_offs + sizeof(IMAGE_EXPORT_DIRECTORY);
923 name_o = func_o + sym_count * sizeof (DWORD);
924 ord_o = name_o + sym_count * sizeof (DWORD);
925 str_o = ord_o + sym_count * sizeof(WORD);
927 hdr = section_ptr_add(pe->thunk, str_o - pe->exp_offs);
928 hdr->Characteristics = 0;
929 hdr->Base = 1;
930 hdr->NumberOfFunctions = sym_count;
931 hdr->NumberOfNames = sym_count;
932 hdr->AddressOfFunctions = func_o + rva_base;
933 hdr->AddressOfNames = name_o + rva_base;
934 hdr->AddressOfNameOrdinals = ord_o + rva_base;
935 hdr->Name = str_o + rva_base;
936 put_elf_str(pe->thunk, dllname);
938 #if 1
939 /* automatically write exports to <output-filename>.def */
940 strcpy(buf, pe->filename);
941 strcpy(tcc_fileextension(buf), ".def");
942 op = fopen(buf, "w");
943 if (NULL == op) {
944 error_noabort("could not create '%s': %s", buf, strerror(errno));
945 } else {
946 fprintf(op, "LIBRARY %s\n\nEXPORTS\n", dllname);
947 if (pe->s1->verbose)
948 printf("<- %s (%d symbols)\n", buf, sym_count);
950 #endif
952 for (ord = 0; ord < sym_count; ++ord)
954 p = sorted[ord], sym_index = p->index, name = p->name;
955 /* insert actual address later in pe_relocate_rva */
956 put_elf_reloc(symtab_section, pe->thunk,
957 func_o, R_XXX_RELATIVE, sym_index);
958 *(DWORD*)(pe->thunk->data + name_o)
959 = pe->thunk->data_offset + rva_base;
960 *(WORD*)(pe->thunk->data + ord_o)
961 = ord;
962 put_elf_str(pe->thunk, name);
963 func_o += sizeof (DWORD);
964 name_o += sizeof (DWORD);
965 ord_o += sizeof (WORD);
966 if (op)
967 fprintf(op, "%s\n", name);
969 pe->exp_size = pe->thunk->data_offset - pe->exp_offs;
970 dynarray_reset(&sorted, &sym_count);
971 if (op)
972 fclose(op);
975 /* ------------------------------------------------------------- */
976 static void pe_build_reloc (struct pe_info *pe)
978 DWORD offset, block_ptr, addr;
979 int count, i;
980 ElfW_Rel *rel, *rel_end;
981 Section *s = NULL, *sr;
983 offset = addr = block_ptr = count = i = 0;
984 rel = rel_end = NULL;
986 for(;;) {
987 if (rel < rel_end) {
988 int type = ELFW(R_TYPE)(rel->r_info);
989 addr = rel->r_offset + s->sh_addr;
990 ++ rel;
991 if (type != REL_TYPE_DIRECT)
992 continue;
993 if (count == 0) { /* new block */
994 block_ptr = pe->reloc->data_offset;
995 section_ptr_add(pe->reloc, sizeof(struct pe_reloc_header));
996 offset = addr & 0xFFFFFFFF<<12;
998 if ((addr -= offset) < (1<<12)) { /* one block spans 4k addresses */
999 WORD *wp = section_ptr_add(pe->reloc, sizeof (WORD));
1000 *wp = addr | IMAGE_REL_BASED_HIGHLOW<<12;
1001 ++count;
1002 continue;
1004 -- rel;
1006 } else if (i < pe->sec_count) {
1007 sr = (s = pe->s1->sections[pe->sec_info[i++].ord])->reloc;
1008 if (sr) {
1009 rel = (ElfW_Rel *)sr->data;
1010 rel_end = (ElfW_Rel *)(sr->data + sr->data_offset);
1012 continue;
1015 if (count) {
1016 /* store the last block and ready for a new one */
1017 struct pe_reloc_header *hdr;
1018 if (count & 1) /* align for DWORDS */
1019 section_ptr_add(pe->reloc, sizeof(WORD)), ++count;
1020 hdr = (struct pe_reloc_header *)(pe->reloc->data + block_ptr);
1021 hdr -> offset = offset - pe->imagebase;
1022 hdr -> size = count * sizeof(WORD) + sizeof(struct pe_reloc_header);
1023 count = 0;
1026 if (rel >= rel_end)
1027 break;
1031 /* ------------------------------------------------------------- */
1032 static int pe_section_class(Section *s)
1034 int type, flags;
1035 const char *name;
1037 type = s->sh_type;
1038 flags = s->sh_flags;
1039 name = s->name;
1040 if (flags & SHF_ALLOC) {
1041 if (type == SHT_PROGBITS) {
1042 if (flags & SHF_EXECINSTR)
1043 return sec_text;
1044 if (flags & SHF_WRITE)
1045 return sec_data;
1046 if (0 == strcmp(name, ".rsrc"))
1047 return sec_rsrc;
1048 if (0 == strcmp(name, ".iedat"))
1049 return sec_idata;
1050 if (0 == strcmp(name, ".pdata"))
1051 return sec_pdata;
1052 return sec_other;
1053 } else if (type == SHT_NOBITS) {
1054 if (flags & SHF_WRITE)
1055 return sec_bss;
1057 } else {
1058 if (0 == strcmp(name, ".reloc"))
1059 return sec_reloc;
1060 if (0 == strncmp(name, ".stab", 5)) /* .stab and .stabstr */
1061 return sec_stab;
1063 return -1;
1066 static int pe_assign_addresses (struct pe_info *pe)
1068 int i, k, o, c;
1069 DWORD addr;
1070 int *section_order;
1071 struct section_info *si;
1072 Section *s;
1074 // pe->thunk = new_section(pe->s1, ".iedat", SHT_PROGBITS, SHF_ALLOC);
1076 section_order = tcc_malloc(pe->s1->nb_sections * sizeof (int));
1077 for (o = k = 0 ; k < sec_last; ++k) {
1078 for (i = 1; i < pe->s1->nb_sections; ++i) {
1079 s = pe->s1->sections[i];
1080 if (k == pe_section_class(s)) {
1081 // printf("%s %d\n", s->name, k);
1082 s->sh_addr = pe->imagebase;
1083 section_order[o++] = i;
1088 pe->sec_info = tcc_mallocz(o * sizeof (struct section_info));
1089 addr = pe->imagebase + 1;
1091 for (i = 0; i < o; ++i)
1093 k = section_order[i];
1094 s = pe->s1->sections[k];
1095 c = pe_section_class(s);
1096 si = &pe->sec_info[pe->sec_count];
1098 #ifdef PE_MERGE_DATA
1099 if (c == sec_bss && pe->sec_count && si[-1].cls == sec_data) {
1100 /* append .bss to .data */
1101 s->sh_addr = addr = ((addr-1) | (s->sh_addralign-1)) + 1;
1102 addr += s->data_offset;
1103 si[-1].sh_size = addr - si[-1].sh_addr;
1104 continue;
1106 #endif
1107 strcpy(si->name, s->name);
1108 si->cls = c;
1109 si->ord = k;
1110 si->sh_addr = s->sh_addr = addr = pe_virtual_align(pe, addr);
1111 si->sh_flags = s->sh_flags;
1113 if (c == sec_data && NULL == pe->thunk)
1114 pe->thunk = s;
1116 if (s == pe->thunk) {
1117 pe_build_imports(pe);
1118 pe_build_exports(pe);
1121 if (c == sec_reloc)
1122 pe_build_reloc (pe);
1124 if (s->data_offset)
1126 if (s->sh_type != SHT_NOBITS) {
1127 si->data = s->data;
1128 si->data_size = s->data_offset;
1131 addr += s->data_offset;
1132 si->sh_size = s->data_offset;
1133 ++pe->sec_count;
1135 // printf("%08x %05x %s\n", si->sh_addr, si->sh_size, si->name);
1138 #if 0
1139 for (i = 1; i < pe->s1->nb_sections; ++i) {
1140 Section *s = pe->s1->sections[i];
1141 int type = s->sh_type;
1142 int flags = s->sh_flags;
1143 printf("section %-16s %-10s %5x %s,%s,%s\n",
1144 s->name,
1145 type == SHT_PROGBITS ? "progbits" :
1146 type == SHT_NOBITS ? "nobits" :
1147 type == SHT_SYMTAB ? "symtab" :
1148 type == SHT_STRTAB ? "strtab" :
1149 type == SHT_RELX ? "rel" : "???",
1150 s->data_offset,
1151 flags & SHF_ALLOC ? "alloc" : "",
1152 flags & SHF_WRITE ? "write" : "",
1153 flags & SHF_EXECINSTR ? "exec" : ""
1156 pe->s1->verbose = 2;
1157 #endif
1159 tcc_free(section_order);
1160 return 0;
1163 /* ------------------------------------------------------------- */
1164 static void pe_relocate_rva (struct pe_info *pe, Section *s)
1166 Section *sr = s->reloc;
1167 ElfW_Rel *rel, *rel_end;
1168 rel_end = (ElfW_Rel *)(sr->data + sr->data_offset);
1169 for(rel = (ElfW_Rel *)sr->data; rel < rel_end; rel++) {
1170 if (ELFW(R_TYPE)(rel->r_info) == R_XXX_RELATIVE) {
1171 int sym_index = ELFW(R_SYM)(rel->r_info);
1172 DWORD addr = s->sh_addr;
1173 if (sym_index) {
1174 ElfW(Sym) *sym = (ElfW(Sym) *)symtab_section->data + sym_index;
1175 addr = sym->st_value;
1177 // printf("reloc rva %08x %08x %s\n", (DWORD)rel->r_offset, addr, s->name);
1178 *(DWORD*)(s->data + rel->r_offset) += addr - pe->imagebase;
1183 /*----------------------------------------------------------------------------*/
1185 static int pe_isafunc(int sym_index)
1187 Section *sr = text_section->reloc;
1188 ElfW_Rel *rel, *rel_end;
1189 Elf32_Word info = ELF32_R_INFO(sym_index, R_386_PC32);
1190 if (!sr)
1191 return 0;
1192 rel_end = (ElfW_Rel *)(sr->data + sr->data_offset);
1193 for (rel = (ElfW_Rel *)sr->data; rel < rel_end; rel++)
1194 if (rel->r_info == info)
1195 return 1;
1196 return 0;
1199 /*----------------------------------------------------------------------------*/
1200 static int pe_check_symbols(struct pe_info *pe)
1202 ElfW(Sym) *sym;
1203 int sym_index, sym_end;
1204 int ret = 0;
1206 pe_align_section(text_section, 8);
1208 sym_end = symtab_section->data_offset / sizeof(ElfW(Sym));
1209 for (sym_index = 1; sym_index < sym_end; ++sym_index) {
1211 sym = (ElfW(Sym) *)symtab_section->data + sym_index;
1212 if (sym->st_shndx == SHN_UNDEF) {
1214 const char *name = symtab_section->link->data + sym->st_name;
1215 unsigned type = ELFW(ST_TYPE)(sym->st_info);
1216 int imp_sym = pe_find_import(pe->s1, sym);
1217 struct import_symbol *is;
1219 if (0 == imp_sym)
1220 goto not_found;
1222 if (type == STT_NOTYPE) {
1223 /* symbols from assembler have no type, find out which */
1224 if (pe_isafunc(sym_index))
1225 type = STT_FUNC;
1226 else
1227 type = STT_OBJECT;
1230 is = pe_add_import(pe, imp_sym);
1232 if (type == STT_FUNC) {
1233 unsigned long offset = is->thk_offset;
1234 if (offset) {
1235 /* got aliased symbol, like stricmp and _stricmp */
1237 } else {
1238 char buffer[100];
1239 WORD *p;
1241 offset = text_section->data_offset;
1242 /* add the 'jmp IAT[x]' instruction */
1243 #ifdef TCC_TARGET_ARM
1244 p = section_ptr_add(text_section, 8+4); // room for code and address
1245 (*(DWORD*)(p)) = 0xE59FC000; // arm code ldr ip, [pc] ; PC+8+0 = 0001xxxx
1246 (*(DWORD*)(p+2)) = 0xE59CF000; // arm code ldr pc, [ip]
1247 #else
1248 p = section_ptr_add(text_section, 8);
1249 *p = 0x25FF;
1250 #ifdef TCC_TARGET_X86_64
1251 *(DWORD*)(p+1) = (DWORD)-4;
1252 #endif
1253 #endif
1254 /* add a helper symbol, will be patched later in
1255 pe_build_imports */
1256 sprintf(buffer, "IAT.%s", name);
1257 is->iat_index = put_elf_sym(
1258 symtab_section, 0, sizeof(DWORD),
1259 ELFW(ST_INFO)(STB_GLOBAL, STT_OBJECT),
1260 0, SHN_UNDEF, buffer);
1261 #ifdef TCC_TARGET_ARM
1262 put_elf_reloc(symtab_section, text_section,
1263 offset + 8, R_XXX_THUNKFIX, is->iat_index); // offset to IAT position
1264 #else
1265 put_elf_reloc(symtab_section, text_section,
1266 offset + 2, R_XXX_THUNKFIX, is->iat_index);
1267 #endif
1268 is->thk_offset = offset;
1271 /* tcc_realloc might have altered sym's address */
1272 sym = (ElfW(Sym) *)symtab_section->data + sym_index;
1274 /* patch the original symbol */
1275 sym->st_value = offset;
1276 sym->st_shndx = text_section->sh_num;
1277 sym->st_other &= ~1; /* do not export */
1278 continue;
1281 if (type == STT_OBJECT) { /* data, ptr to that should be */
1282 if (0 == is->iat_index) {
1283 /* original symbol will be patched later in pe_build_imports */
1284 is->iat_index = sym_index;
1285 continue;
1289 not_found:
1290 error_noabort("undefined symbol '%s'", name);
1291 ret = -1;
1293 } else if (pe->s1->rdynamic
1294 && ELFW(ST_BIND)(sym->st_info) != STB_LOCAL) {
1295 /* if -rdynamic option, then export all non local symbols */
1296 sym->st_other |= 1;
1299 return ret;
1302 /*----------------------------------------------------------------------------*/
1303 #ifdef PE_PRINT_SECTIONS
1304 static void pe_print_section(FILE * f, Section * s)
1306 /* just if you'r curious */
1307 BYTE *p, *e, b;
1308 int i, n, l, m;
1309 p = s->data;
1310 e = s->data + s->data_offset;
1311 l = e - p;
1313 fprintf(f, "section \"%s\"", s->name);
1314 if (s->link)
1315 fprintf(f, "\nlink \"%s\"", s->link->name);
1316 if (s->reloc)
1317 fprintf(f, "\nreloc \"%s\"", s->reloc->name);
1318 fprintf(f, "\nv_addr %08X", (unsigned)s->sh_addr);
1319 fprintf(f, "\ncontents %08X", (unsigned)l);
1320 fprintf(f, "\n\n");
1322 if (s->sh_type == SHT_NOBITS)
1323 return;
1325 if (0 == l)
1326 return;
1328 if (s->sh_type == SHT_SYMTAB)
1329 m = sizeof(ElfW(Sym));
1330 else if (s->sh_type == SHT_RELX)
1331 m = sizeof(ElfW_Rel);
1332 else
1333 m = 16;
1335 fprintf(f, "%-8s", "offset");
1336 for (i = 0; i < m; ++i)
1337 fprintf(f, " %02x", i);
1338 n = 56;
1340 if (s->sh_type == SHT_SYMTAB || s->sh_type == SHT_RELX) {
1341 const char *fields1[] = {
1342 "name",
1343 "value",
1344 "size",
1345 "bind",
1346 "type",
1347 "other",
1348 "shndx",
1349 NULL
1352 const char *fields2[] = {
1353 "offs",
1354 "type",
1355 "symb",
1356 NULL
1359 const char **p;
1361 if (s->sh_type == SHT_SYMTAB)
1362 p = fields1, n = 106;
1363 else
1364 p = fields2, n = 58;
1366 for (i = 0; p[i]; ++i)
1367 fprintf(f, "%6s", p[i]);
1368 fprintf(f, " symbol");
1371 fprintf(f, "\n");
1372 for (i = 0; i < n; ++i)
1373 fprintf(f, "-");
1374 fprintf(f, "\n");
1376 for (i = 0; i < l;)
1378 fprintf(f, "%08X", i);
1379 for (n = 0; n < m; ++n) {
1380 if (n + i < l)
1381 fprintf(f, " %02X", p[i + n]);
1382 else
1383 fprintf(f, " ");
1386 if (s->sh_type == SHT_SYMTAB) {
1387 ElfW(Sym) *sym = (ElfW(Sym) *) (p + i);
1388 const char *name = s->link->data + sym->st_name;
1389 fprintf(f, " %04X %04X %04X %02X %02X %02X %04X \"%s\"",
1390 (unsigned)sym->st_name,
1391 (unsigned)sym->st_value,
1392 (unsigned)sym->st_size,
1393 (unsigned)ELFW(ST_BIND)(sym->st_info),
1394 (unsigned)ELFW(ST_TYPE)(sym->st_info),
1395 (unsigned)sym->st_other,
1396 (unsigned)sym->st_shndx,
1397 name);
1399 } else if (s->sh_type == SHT_RELX) {
1400 ElfW_Rel *rel = (ElfW_Rel *) (p + i);
1401 ElfW(Sym) *sym =
1402 (ElfW(Sym) *) s->link->data + ELFW(R_SYM)(rel->r_info);
1403 const char *name = s->link->link->data + sym->st_name;
1404 fprintf(f, " %04X %02X %04X \"%s\"",
1405 (unsigned)rel->r_offset,
1406 (unsigned)ELFW(R_TYPE)(rel->r_info),
1407 (unsigned)ELFW(R_SYM)(rel->r_info),
1408 name);
1409 } else {
1410 fprintf(f, " ");
1411 for (n = 0; n < m; ++n) {
1412 if (n + i < l) {
1413 b = p[i + n];
1414 if (b < 32 || b >= 127)
1415 b = '.';
1416 fprintf(f, "%c", b);
1420 i += m;
1421 fprintf(f, "\n");
1423 fprintf(f, "\n\n");
1426 static void pe_print_sections(TCCState *s1, const char *fname)
1428 Section *s;
1429 FILE *f;
1430 int i;
1431 f = fopen(fname, "w");
1432 for (i = 1; i < s1->nb_sections; ++i) {
1433 s = s1->sections[i];
1434 pe_print_section(f, s);
1436 pe_print_section(f, s1->dynsymtab_section);
1437 fclose(f);
1439 #endif
1441 /* ------------------------------------------------------------- */
1442 /* helper function for load/store to insert one more indirection */
1444 ST_FUNC SValue *pe_getimport(SValue *sv, SValue *v2)
1446 Sym *sym;
1447 ElfW(Sym) *esym;
1448 int r2;
1450 if ((sv->r & (VT_VALMASK|VT_SYM)) != (VT_CONST|VT_SYM) || (sv->r2 != VT_CONST))
1451 return sv;
1452 sym = sv->sym;
1453 if ((sym->type.t & (VT_EXTERN|VT_STATIC)) != VT_EXTERN)
1454 return sv;
1455 if (!sym->c)
1456 put_extern_sym(sym, NULL, 0, 0);
1457 esym = &((ElfW(Sym) *)symtab_section->data)[sym->c];
1458 if (!(esym->st_other & 4))
1459 return sv;
1461 // printf("import %04x %04x %04x %s\n", sv->type.t, sym->type.t, sv->r, get_tok_str(sv->sym->v, NULL));
1463 memset(v2, 0, sizeof *v2);
1464 v2->type.t = VT_PTR;
1465 v2->r = VT_CONST | VT_SYM | VT_LVAL;
1466 v2->sym = sv->sym;
1468 r2 = get_reg(RC_INT);
1469 load(r2, v2);
1470 v2->r = r2;
1472 if (sv->c.ui) {
1473 vpushv(v2);
1474 vpushi(sv->c.ui);
1475 gen_opi('+');
1476 *v2 = *vtop--;
1479 v2->type.t = sv->type.t;
1480 v2->r |= sv->r & VT_LVAL;
1481 return v2;
1484 ST_FUNC int pe_putimport(TCCState *s1, int dllindex, const char *name, const void *value)
1486 return add_elf_sym(
1487 s1->dynsymtab_section,
1488 (uplong)value,
1489 dllindex, /* st_size */
1490 ELFW(ST_INFO)(STB_GLOBAL, STT_NOTYPE),
1492 value ? SHN_ABS : SHN_UNDEF,
1493 name
1497 static int add_dllref(TCCState *s1, const char *dllname)
1499 DLLReference *dllref;
1500 int i;
1501 for (i = 0; i < s1->nb_loaded_dlls; ++i)
1502 if (0 == strcmp(s1->loaded_dlls[i]->name, dllname))
1503 return i + 1;
1504 dllref = tcc_mallocz(sizeof(DLLReference) + strlen(dllname));
1505 strcpy(dllref->name, dllname);
1506 dynarray_add((void ***) &s1->loaded_dlls, &s1->nb_loaded_dlls, dllref);
1507 return s1->nb_loaded_dlls;
1510 /* ------------------------------------------------------------- */
1512 static int read_mem(FILE *fp, unsigned offset, void *buffer, unsigned len)
1514 fseek(fp, offset, 0);
1515 return len == fread(buffer, 1, len, fp);
1518 /* -------------------------------------------------------------
1519 * This is for compiled windows resources in 'coff' format
1520 * as generated by 'windres.exe -O coff ...'.
1523 static int pe_load_res(TCCState *s1, FILE *fp)
1525 struct pe_rsrc_header hdr;
1526 Section *rsrc_section;
1527 int i, ret = -1;
1528 BYTE *ptr;
1529 unsigned offs;
1531 if (!read_mem(fp, 0, &hdr, sizeof hdr))
1532 goto quit;
1534 if (hdr.filehdr.Machine != 0x014C
1535 || hdr.filehdr.NumberOfSections != 1
1536 || strcmp(hdr.sectionhdr.Name, ".rsrc") != 0)
1537 goto quit;
1539 rsrc_section = new_section(s1, ".rsrc", SHT_PROGBITS, SHF_ALLOC);
1540 ptr = section_ptr_add(rsrc_section, hdr.sectionhdr.SizeOfRawData);
1541 offs = hdr.sectionhdr.PointerToRawData;
1542 if (!read_mem(fp, offs, ptr, hdr.sectionhdr.SizeOfRawData))
1543 goto quit;
1544 offs = hdr.sectionhdr.PointerToRelocations;
1545 for (i = 0; i < hdr.sectionhdr.NumberOfRelocations; ++i)
1547 struct pe_rsrc_reloc rel;
1548 if (!read_mem(fp, offs, &rel, sizeof rel))
1549 goto quit;
1550 // printf("rsrc_reloc: %x %x %x\n", rel.offset, rel.size, rel.type);
1551 if (rel.type != 7) /* DIR32NB */
1552 goto quit;
1553 put_elf_reloc(symtab_section, rsrc_section,
1554 rel.offset, R_XXX_RELATIVE, 0);
1555 offs += sizeof rel;
1557 ret = 0;
1558 quit:
1559 return ret;
1562 /* ------------------------------------------------------------- */
1563 static char *trimfront(char *p)
1565 while (*p && (unsigned char)*p <= ' ')
1566 ++p;
1567 return p;
1570 static char *trimback(char *a, char *e)
1572 while (e > a && (unsigned char)e[-1] <= ' ')
1573 --e;
1574 *e = 0;;
1575 return a;
1578 static char *get_line(char *line, int size, FILE *fp)
1580 if (NULL == fgets(line, size, fp))
1581 return NULL;
1582 trimback(line, strchr(line, 0));
1583 return trimfront(line);
1586 /* ------------------------------------------------------------- */
1587 static int pe_load_def(TCCState *s1, FILE *fp)
1589 int state = 0, ret = -1, dllindex = 0;
1590 char line[400], dllname[80], *p;
1592 for (;;) {
1593 p = get_line(line, sizeof line, fp);
1594 if (NULL == p)
1595 break;
1596 if (0 == *p || ';' == *p)
1597 continue;
1598 switch (state) {
1599 case 0:
1600 if (0 != strnicmp(p, "LIBRARY", 7))
1601 goto quit;
1602 strcpy(dllname, trimfront(p+7));
1603 ++state;
1604 continue;
1606 case 1:
1607 if (0 != stricmp(p, "EXPORTS"))
1608 goto quit;
1609 ++state;
1610 continue;
1612 case 2:
1613 dllindex = add_dllref(s1, dllname);
1614 ++state;
1616 default:
1617 pe_putimport(s1, dllindex, p, NULL);
1618 continue;
1621 ret = 0;
1622 quit:
1623 return ret;
1626 /* ------------------------------------------------------------- */
1627 #define TINY_IMPDEF_GET_EXPORT_NAMES_ONLY
1628 #include "win32/tools/tiny_impdef.c"
1630 static int pe_load_dll(TCCState *s1, const char *dllname, FILE *fp)
1632 char *p, *q;
1633 int index;
1634 p = get_export_names(fp);
1635 if (!p)
1636 return -1;
1637 index = add_dllref(s1, dllname);
1638 for (q = p; *q; q += 1 + strlen(q))
1639 pe_putimport(s1, index, q, NULL);
1640 tcc_free(p);
1641 return 0;
1644 /* ------------------------------------------------------------- */
1645 ST_FUNC int pe_load_file(struct TCCState *s1, const char *filename, int fd)
1647 FILE *fp = fdopen(dup(fd), "rb");
1648 int ret = -1;
1649 char buf[10];
1650 if (fp) {
1651 if (0 == strcmp(tcc_fileextension(filename), ".def"))
1652 ret = pe_load_def(s1, fp);
1653 else if (pe_load_res(s1, fp) == 0)
1654 ret = 0;
1655 else if (read_mem(fp, 0, buf, sizeof buf) && 0 == strncmp(buf, "MZ", 2))
1656 ret = pe_load_dll(s1, tcc_basename(filename), fp);
1657 fclose(fp);
1659 return ret;
1662 ST_FUNC int pe_add_dll(struct TCCState *s, const char *libname)
1664 static const char *pat[] = {
1665 "%s.def", "lib%s.def", "%s.dll", "lib%s.dll", NULL
1667 const char **p = pat;
1668 do {
1669 char buf[MAX_PATH];
1670 snprintf(buf, sizeof(buf), *p, libname);
1671 if (tcc_add_dll(s, buf, 0) == 0)
1672 return 0;
1673 } while (*++p);
1674 return -1;
1677 /* ------------------------------------------------------------- */
1678 #ifdef TCC_TARGET_X86_64
1679 static unsigned pe_add_uwwind_info(TCCState *s1)
1681 if (NULL == s1->uw_pdata) {
1682 s1->uw_pdata = find_section(tcc_state, ".pdata");
1683 s1->uw_pdata->sh_addralign = 4;
1684 s1->uw_sym = put_elf_sym(symtab_section, 0, 0, 0, 0, text_section->sh_num, NULL);
1687 if (0 == s1->uw_offs) {
1688 /* As our functions all have the same stackframe, we use one entry for all */
1689 static const unsigned char uw_info[] = {
1690 0x01, // UBYTE: 3 Version , UBYTE: 5 Flags
1691 0x04, // UBYTE Size of prolog
1692 0x02, // UBYTE Count of unwind codes
1693 0x05, // UBYTE: 4 Frame Register (rbp), UBYTE: 4 Frame Register offset (scaled)
1694 // USHORT * n Unwind codes array
1695 // 0x0b, 0x01, 0xff, 0xff, // stack size
1696 0x04, 0x03, // set frame ptr (mov rsp -> rbp)
1697 0x01, 0x50 // push reg (rbp)
1700 Section *s = text_section;
1701 unsigned char *p;
1703 section_ptr_add(s, -s->data_offset & 3); /* align */
1704 s1->uw_offs = s->data_offset;
1705 p = section_ptr_add(s, sizeof uw_info);
1706 memcpy(p, uw_info, sizeof uw_info);
1709 return s1->uw_offs;
1712 ST_FUNC void pe_add_unwind_data(unsigned start, unsigned end, unsigned stack)
1714 TCCState *s1 = tcc_state;
1715 Section *pd;
1716 unsigned o, n, d;
1717 struct /* _RUNTIME_FUNCTION */ {
1718 DWORD BeginAddress;
1719 DWORD EndAddress;
1720 DWORD UnwindData;
1721 } *p;
1723 d = pe_add_uwwind_info(s1);
1724 pd = s1->uw_pdata;
1725 o = pd->data_offset;
1726 p = section_ptr_add(pd, sizeof *p);
1728 /* record this function */
1729 p->BeginAddress = start;
1730 p->EndAddress = end;
1731 p->UnwindData = d;
1733 /* put relocations on it */
1734 for (n = o + sizeof *p; o < n; o += sizeof p->BeginAddress)
1735 put_elf_reloc(symtab_section, pd, o, R_X86_64_RELATIVE, s1->uw_sym);
1737 #endif
1738 /* ------------------------------------------------------------- */
1739 #ifdef TCC_TARGET_X86_64
1740 #define PE_STDSYM(n,s) n
1741 #else
1742 #define PE_STDSYM(n,s) "_" n s
1743 #endif
1745 static void pe_add_runtime_ex(TCCState *s1, struct pe_info *pe)
1747 const char *start_symbol;
1748 unsigned long addr = 0;
1749 int pe_type = 0;
1751 if (find_elf_sym(symtab_section, PE_STDSYM("WinMain","@16")))
1752 pe_type = PE_GUI;
1753 else
1754 if (TCC_OUTPUT_DLL == s1->output_type) {
1755 pe_type = PE_DLL;
1756 /* need this for 'tccelf.c:relocate_section()' */
1757 s1->output_type = TCC_OUTPUT_EXE;
1759 else
1760 pe_type = PE_EXE;
1762 start_symbol =
1763 TCC_OUTPUT_MEMORY == s1->output_type
1764 ? PE_GUI == pe_type ? "__runwinmain" : "_main"
1765 : PE_DLL == pe_type ? PE_STDSYM("__dllstart","@12")
1766 : PE_GUI == pe_type ? "__winstart" : "__start"
1769 if (!s1->leading_underscore || strchr(start_symbol, '@')) {
1770 ++start_symbol;
1771 if (start_symbol[0] != '_')
1772 start_symbol = NULL;
1775 /* grab the startup code from libtcc1 */
1776 if (start_symbol)
1777 add_elf_sym(symtab_section,
1778 0, 0,
1779 ELFW(ST_INFO)(STB_GLOBAL, STT_NOTYPE), 0,
1780 SHN_UNDEF, start_symbol);
1782 if (0 == s1->nostdlib) {
1783 static const char *libs[] = {
1784 "tcc1", "msvcrt", "kernel32", "", "user32", "gdi32", NULL
1786 const char **pp, *p;
1787 for (pp = libs; 0 != (p = *pp); ++pp) {
1788 if (0 == *p) {
1789 if (PE_DLL != pe_type && PE_GUI != pe_type)
1790 break;
1791 } else if (tcc_add_library(s1, p) < 0)
1792 error_noabort("cannot find library: %s", p);
1796 if (TCC_OUTPUT_MEMORY == s1->output_type)
1797 pe_type = PE_RUN;
1799 if (start_symbol) {
1800 addr = (uplong)tcc_get_symbol_err(s1, start_symbol);
1801 if (PE_RUN == pe_type && addr)
1802 /* for -run GUI's, put '_runwinmain' instead of 'main' */
1803 add_elf_sym(symtab_section,
1804 addr, 0,
1805 ELFW(ST_INFO)(STB_GLOBAL, STT_NOTYPE), 0,
1806 text_section->sh_num, "main");
1809 pe->type = pe_type;
1810 pe->start_addr = addr;
1813 ST_FUNC int pe_output_file(TCCState * s1, const char *filename)
1815 int ret;
1816 struct pe_info pe;
1817 int i;
1819 memset(&pe, 0, sizeof pe);
1820 pe.filename = filename;
1821 pe.s1 = s1;
1823 tcc_add_bcheck(s1);
1824 pe_add_runtime_ex(s1, &pe);
1825 relocate_common_syms(); /* assign bss adresses */
1826 tcc_add_linker_symbols(s1);
1828 ret = pe_check_symbols(&pe);
1829 if (ret)
1831 else if (filename) {
1832 if (PE_DLL == pe.type) {
1833 pe.reloc = new_section(pe.s1, ".reloc", SHT_PROGBITS, 0);
1834 /* XXX: check if is correct for arm-pe target */
1835 pe.imagebase = 0x10000000;
1836 } else {
1837 #if defined(TCC_TARGET_ARM)
1838 pe.imagebase = 0x00010000;
1839 #else
1840 pe.imagebase = 0x00400000;
1841 #endif
1844 /* if no subsystem specified, we use "console" subsystem by default */
1845 if (s1->pe_subsystem != 0)
1846 pe.subsystem = s1->pe_subsystem;
1847 else
1848 #if defined(TCC_TARGET_ARM)
1849 pe.subsystem = 9;
1850 #else
1851 pe.subsystem = 3;
1852 #endif
1853 /* set default file/section alignment */
1854 if (pe.subsystem == 1) {
1855 pe.section_align = 0x20;
1856 pe.file_align = 0x20;
1857 } else {
1858 pe.section_align = 0x1000;
1859 pe.file_align = 0x200;
1862 if (s1->section_align != 0)
1863 pe.section_align = s1->section_align;
1864 if (s1->pe_file_align != 0)
1865 pe.file_align = s1->pe_file_align;
1867 if ((pe.subsystem >= 10) && (pe.subsystem <= 12))
1868 pe.imagebase = 0;
1870 if (s1->has_text_addr)
1871 pe.imagebase = s1->text_addr;
1873 pe_assign_addresses(&pe);
1874 relocate_syms(s1, 0);
1875 for (i = 1; i < s1->nb_sections; ++i) {
1876 Section *s = s1->sections[i];
1877 if (s->reloc) {
1878 relocate_section(s1, s);
1879 pe_relocate_rva(&pe, s);
1882 if (s1->nb_errors)
1883 ret = -1;
1884 else
1885 ret = pe_write(&pe);
1886 tcc_free(pe.sec_info);
1887 } else {
1888 #ifndef TCC_IS_NATIVE
1889 error_noabort("-run supported only on native platform");
1890 #endif
1891 pe.thunk = data_section;
1892 pe_build_imports(&pe);
1895 #ifdef PE_PRINT_SECTIONS
1896 pe_print_sections(s1, "tcc.log");
1897 #endif
1898 return ret;
1901 /* ------------------------------------------------------------- */