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
24 #define ST_DATA static
28 #define stricmp strcasecmp
29 #define strnicmp strncasecmp
37 // #define PE_PRINT_SECTIONS
39 #ifdef TCC_TARGET_X86_64
40 # define ADDR3264 ULONGLONG
42 # define ADDR3264 DWORD
45 #if defined _WIN32 && (defined _WIN64) == (defined TCC_TARGET_X86_64)
50 void dbg_printf (const char *fmt
, ...)
56 x
= vsprintf (buffer
, fmt
, arg
);
57 strcpy(buffer
+x
, "\n");
58 OutputDebugString(buffer
);
62 /* ----------------------------------------------------------- */
63 #ifndef IMAGE_NT_SIGNATURE
64 /* ----------------------------------------------------------- */
65 /* definitions below are from winnt.h */
67 typedef unsigned char BYTE
;
68 typedef unsigned short WORD
;
69 typedef unsigned long DWORD
;
70 typedef unsigned long long ULONGLONG
;
73 typedef struct _IMAGE_DOS_HEADER
{ /* DOS .EXE header */
74 WORD e_magic
; /* Magic number */
75 WORD e_cblp
; /* Bytes on last page of file */
76 WORD e_cp
; /* Pages in file */
77 WORD e_crlc
; /* Relocations */
78 WORD e_cparhdr
; /* Size of header in paragraphs */
79 WORD e_minalloc
; /* Minimum extra paragraphs needed */
80 WORD e_maxalloc
; /* Maximum extra paragraphs needed */
81 WORD e_ss
; /* Initial (relative) SS value */
82 WORD e_sp
; /* Initial SP value */
83 WORD e_csum
; /* Checksum */
84 WORD e_ip
; /* Initial IP value */
85 WORD e_cs
; /* Initial (relative) CS value */
86 WORD e_lfarlc
; /* File address of relocation table */
87 WORD e_ovno
; /* Overlay number */
88 WORD e_res
[4]; /* Reserved words */
89 WORD e_oemid
; /* OEM identifier (for e_oeminfo) */
90 WORD e_oeminfo
; /* OEM information; e_oemid specific */
91 WORD e_res2
[10]; /* Reserved words */
92 DWORD e_lfanew
; /* File address of new exe header */
93 } IMAGE_DOS_HEADER
, *PIMAGE_DOS_HEADER
;
95 #define IMAGE_NT_SIGNATURE 0x00004550 /* PE00 */
96 #define SIZE_OF_NT_SIGNATURE 4
98 typedef struct _IMAGE_FILE_HEADER
{
100 WORD NumberOfSections
;
102 DWORD PointerToSymbolTable
;
103 DWORD NumberOfSymbols
;
104 WORD SizeOfOptionalHeader
;
105 WORD Characteristics
;
106 } IMAGE_FILE_HEADER
, *PIMAGE_FILE_HEADER
;
109 #define IMAGE_SIZEOF_FILE_HEADER 20
111 typedef struct _IMAGE_DATA_DIRECTORY
{
112 DWORD VirtualAddress
;
114 } IMAGE_DATA_DIRECTORY
, *PIMAGE_DATA_DIRECTORY
;
117 typedef struct _IMAGE_OPTIONAL_HEADER
{
118 /* Standard fields. */
120 BYTE MajorLinkerVersion
;
121 BYTE MinorLinkerVersion
;
123 DWORD SizeOfInitializedData
;
124 DWORD SizeOfUninitializedData
;
125 DWORD AddressOfEntryPoint
;
127 #ifndef TCC_TARGET_X86_64
130 /* NT additional fields. */
132 DWORD SectionAlignment
;
134 WORD MajorOperatingSystemVersion
;
135 WORD MinorOperatingSystemVersion
;
136 WORD MajorImageVersion
;
137 WORD MinorImageVersion
;
138 WORD MajorSubsystemVersion
;
139 WORD MinorSubsystemVersion
;
140 DWORD Win32VersionValue
;
145 WORD DllCharacteristics
;
146 ADDR3264 SizeOfStackReserve
;
147 ADDR3264 SizeOfStackCommit
;
148 ADDR3264 SizeOfHeapReserve
;
149 ADDR3264 SizeOfHeapCommit
;
151 DWORD NumberOfRvaAndSizes
;
152 IMAGE_DATA_DIRECTORY DataDirectory
[16];
153 } IMAGE_OPTIONAL_HEADER32
, IMAGE_OPTIONAL_HEADER64
, IMAGE_OPTIONAL_HEADER
;
155 #define IMAGE_DIRECTORY_ENTRY_EXPORT 0 /* Export Directory */
156 #define IMAGE_DIRECTORY_ENTRY_IMPORT 1 /* Import Directory */
157 #define IMAGE_DIRECTORY_ENTRY_RESOURCE 2 /* Resource Directory */
158 #define IMAGE_DIRECTORY_ENTRY_EXCEPTION 3 /* Exception Directory */
159 #define IMAGE_DIRECTORY_ENTRY_SECURITY 4 /* Security Directory */
160 #define IMAGE_DIRECTORY_ENTRY_BASERELOC 5 /* Base Relocation Table */
161 #define IMAGE_DIRECTORY_ENTRY_DEBUG 6 /* Debug Directory */
162 /* IMAGE_DIRECTORY_ENTRY_COPYRIGHT 7 (X86 usage) */
163 #define IMAGE_DIRECTORY_ENTRY_ARCHITECTURE 7 /* Architecture Specific Data */
164 #define IMAGE_DIRECTORY_ENTRY_GLOBALPTR 8 /* RVA of GP */
165 #define IMAGE_DIRECTORY_ENTRY_TLS 9 /* TLS Directory */
166 #define IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG 10 /* Load Configuration Directory */
167 #define IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT 11 /* Bound Import Directory in headers */
168 #define IMAGE_DIRECTORY_ENTRY_IAT 12 /* Import Address Table */
169 #define IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT 13 /* Delay Load Import Descriptors */
170 #define IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR 14 /* COM Runtime descriptor */
172 /* Section header format. */
173 #define IMAGE_SIZEOF_SHORT_NAME 8
175 typedef struct _IMAGE_SECTION_HEADER
{
176 BYTE Name
[IMAGE_SIZEOF_SHORT_NAME
];
178 DWORD PhysicalAddress
;
181 DWORD VirtualAddress
;
183 DWORD PointerToRawData
;
184 DWORD PointerToRelocations
;
185 DWORD PointerToLinenumbers
;
186 WORD NumberOfRelocations
;
187 WORD NumberOfLinenumbers
;
188 DWORD Characteristics
;
189 } IMAGE_SECTION_HEADER
, *PIMAGE_SECTION_HEADER
;
191 #define IMAGE_SIZEOF_SECTION_HEADER 40
193 typedef struct _IMAGE_EXPORT_DIRECTORY
{
194 DWORD Characteristics
;
200 DWORD NumberOfFunctions
;
202 DWORD AddressOfFunctions
;
203 DWORD AddressOfNames
;
204 DWORD AddressOfNameOrdinals
;
205 } IMAGE_EXPORT_DIRECTORY
,*PIMAGE_EXPORT_DIRECTORY
;
207 typedef struct _IMAGE_IMPORT_DESCRIPTOR
{
209 DWORD Characteristics
;
210 DWORD OriginalFirstThunk
;
213 DWORD ForwarderChain
;
216 } IMAGE_IMPORT_DESCRIPTOR
;
218 typedef struct _IMAGE_BASE_RELOCATION
{
219 DWORD VirtualAddress
;
221 // WORD TypeOffset[1];
222 } IMAGE_BASE_RELOCATION
;
224 #define IMAGE_SIZEOF_BASE_RELOCATION 8
226 #define IMAGE_REL_BASED_ABSOLUTE 0
227 #define IMAGE_REL_BASED_HIGH 1
228 #define IMAGE_REL_BASED_LOW 2
229 #define IMAGE_REL_BASED_HIGHLOW 3
230 #define IMAGE_REL_BASED_HIGHADJ 4
231 #define IMAGE_REL_BASED_MIPS_JMPADDR 5
232 #define IMAGE_REL_BASED_SECTION 6
233 #define IMAGE_REL_BASED_REL32 7
237 /* ----------------------------------------------------------- */
238 #endif /* ndef IMAGE_NT_SIGNATURE */
239 /* ----------------------------------------------------------- */
240 #pragma pack(push, 1)
244 IMAGE_DOS_HEADER doshdr
;
247 IMAGE_FILE_HEADER filehdr
;
248 #ifdef TCC_TARGET_X86_64
249 IMAGE_OPTIONAL_HEADER64 opthdr
;
252 IMAGE_OPTIONAL_HEADER32 opthdr
;
254 IMAGE_OPTIONAL_HEADER opthdr
;
259 struct pe_reloc_header
{
264 struct pe_rsrc_header
{
265 struct _IMAGE_FILE_HEADER filehdr
;
266 struct _IMAGE_SECTION_HEADER sectionhdr
;
269 struct pe_rsrc_reloc
{
277 /* ------------------------------------------------------------- */
278 /* internal temporary structures */
281 #define IMAGE_SCN_CNT_CODE 0x00000020
282 #define IMAGE_SCN_CNT_INITIALIZED_DATA 0x00000040
283 #define IMAGE_SCN_CNT_UNINITIALIZED_DATA 0x00000080
284 #define IMAGE_SCN_MEM_DISCARDABLE 0x02000000
285 #define IMAGE_SCN_MEM_SHARED 0x10000000
286 #define IMAGE_SCN_MEM_EXECUTE 0x20000000
287 #define IMAGE_SCN_MEM_READ 0x40000000
288 #define IMAGE_SCN_MEM_WRITE 0x80000000
303 ST_DATA
const DWORD pe_sec_flags
[] = {
304 0x60000020, /* ".text" , */
305 0xC0000040, /* ".data" , */
306 0xC0000080, /* ".bss" , */
307 0x40000040, /* ".idata" , */
308 0xE0000060, /* < other > , */
309 0x40000040, /* ".rsrc" , */
310 0x42000802, /* ".stab" , */
311 0x42000040, /* ".reloc" , */
314 struct section_info
{
322 IMAGE_SECTION_HEADER ish
;
325 struct import_symbol
{
331 struct pe_import_info
{
334 struct import_symbol
**symbols
;
341 const char *filename
;
352 struct section_info
*sec_info
;
354 struct pe_import_info
**imp_info
;
364 /* --------------------------------------------*/
366 ST_FN
const char* get_alt_symbol(char *buffer
, const char *symbol
)
369 p
= strrchr(symbol
, '@');
370 if (p
&& isnum(p
[1]) && symbol
[0] == '_') { /* stdcall decor */
371 strcpy(buffer
, symbol
+1)[p
-symbol
-1] = 0;
372 } else if (symbol
[0] != '_') { /* try non-ansi function */
373 buffer
[0] = '_', strcpy(buffer
+ 1, symbol
);
374 } else if (0 == memcmp(symbol
, "__imp__", 7)) { /* mingw 2.0 */
375 strcpy(buffer
, symbol
+ 6);
376 } else if (0 == memcmp(symbol
, "_imp___", 7)) { /* mingw 3.7 */
377 strcpy(buffer
, symbol
+ 6);
384 ST_FN
int pe_find_import(TCCState
* s1
, const char *symbol
)
388 int sym_index
, n
= 0;
390 s
= n
? get_alt_symbol(buffer
, symbol
) : symbol
;
391 sym_index
= find_elf_sym(s1
->dynsymtab_section
, s
);
392 // printf("find (%d) %d %s\n", n, sym_index, s);
393 } while (0 == sym_index
&& ++n
< 2);
397 /*----------------------------------------------------------------------------*/
399 ST_FN
int dynarray_assoc(void **pp
, int n
, int key
)
402 for (i
= 0; i
< n
; ++i
, ++pp
)
403 if (key
== **(int **) pp
)
409 ST_FN DWORD
umin(DWORD a
, DWORD b
)
411 return a
< b
? a
: b
;
415 ST_FN DWORD
umax(DWORD a
, DWORD b
)
417 return a
< b
? b
: a
;
420 ST_FN DWORD
pe_file_align(DWORD n
)
422 return (n
+ (0x200 - 1)) & ~(0x200 - 1);
425 ST_FN DWORD
pe_virtual_align(DWORD n
)
427 return (n
+ (0x1000 - 1)) & ~(0x1000 - 1);
430 ST_FN
void pe_align_section(Section
*s
, int a
)
432 int i
= s
->data_offset
& (a
-1);
434 section_ptr_add(s
, a
- i
);
437 ST_FN
void pe_set_datadir(struct pe_header
*hdr
, int dir
, DWORD addr
, DWORD size
)
439 hdr
->opthdr
.DataDirectory
[dir
].VirtualAddress
= addr
;
440 hdr
->opthdr
.DataDirectory
[dir
].Size
= size
;
443 ST_FN
int pe_fwrite(void *data
, unsigned len
, FILE *fp
, DWORD
*psum
)
449 for (i
= len
; i
> 0; i
-= 2) {
450 sum
+= (i
>= 2) ? *p
++ : *(BYTE
*)p
;
451 sum
= (sum
+ (sum
>> 16)) & 0xFFFF;
455 return len
== fwrite(data
, 1, len
, fp
) ? 0 : -1;
458 ST_FN
void pe_fpad(FILE *fp
, DWORD new_pos
)
460 DWORD pos
= ftell(fp
);
461 while (++pos
<= new_pos
)
465 /*----------------------------------------------------------------------------*/
466 ST_FN
int pe_write(struct pe_info
*pe
)
468 static const struct pe_header pe_template
= {
470 /* IMAGE_DOS_HEADER doshdr */
471 0x5A4D, /*WORD e_magic; Magic number */
472 0x0090, /*WORD e_cblp; Bytes on last page of file */
473 0x0003, /*WORD e_cp; Pages in file */
474 0x0000, /*WORD e_crlc; Relocations */
476 0x0004, /*WORD e_cparhdr; Size of header in paragraphs */
477 0x0000, /*WORD e_minalloc; Minimum extra paragraphs needed */
478 0xFFFF, /*WORD e_maxalloc; Maximum extra paragraphs needed */
479 0x0000, /*WORD e_ss; Initial (relative) SS value */
481 0x00B8, /*WORD e_sp; Initial SP value */
482 0x0000, /*WORD e_csum; Checksum */
483 0x0000, /*WORD e_ip; Initial IP value */
484 0x0000, /*WORD e_cs; Initial (relative) CS value */
485 0x0040, /*WORD e_lfarlc; File address of relocation table */
486 0x0000, /*WORD e_ovno; Overlay number */
487 {0,0,0,0}, /*WORD e_res[4]; Reserved words */
488 0x0000, /*WORD e_oemid; OEM identifier (for e_oeminfo) */
489 0x0000, /*WORD e_oeminfo; OEM information; e_oemid specific */
490 {0,0,0,0,0,0,0,0,0,0}, /*WORD e_res2[10]; Reserved words */
491 0x00000080 /*DWORD e_lfanew; File address of new exe header */
493 /* BYTE dosstub[0x40] */
494 /* 14 code bytes + "This program cannot be run in DOS mode.\r\r\n$" + 6 * 0x00 */
495 0x0e,0x1f,0xba,0x0e,0x00,0xb4,0x09,0xcd,0x21,0xb8,0x01,0x4c,0xcd,0x21,0x54,0x68,
496 0x69,0x73,0x20,0x70,0x72,0x6f,0x67,0x72,0x61,0x6d,0x20,0x63,0x61,0x6e,0x6e,0x6f,
497 0x74,0x20,0x62,0x65,0x20,0x72,0x75,0x6e,0x20,0x69,0x6e,0x20,0x44,0x4f,0x53,0x20,
498 0x6d,0x6f,0x64,0x65,0x2e,0x0d,0x0d,0x0a,0x24,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
500 0x00004550, /* DWORD nt_sig = IMAGE_NT_SIGNATURE */
502 /* IMAGE_FILE_HEADER filehdr */
503 #ifdef TCC_TARGET_X86_64
504 0x8664, /*WORD Machine; */
506 0x014C, /*WORD Machine; */
508 0x0003, /*WORD NumberOfSections; */
509 0x00000000, /*DWORD TimeDateStamp; */
510 0x00000000, /*DWORD PointerToSymbolTable; */
511 0x00000000, /*DWORD NumberOfSymbols; */
512 #ifdef TCC_TARGET_X86_64
513 0x00F0, /*WORD SizeOfOptionalHeader; */
514 0x022F /*WORD Characteristics; */
515 #define CHARACTERISTICS_DLL 0x222E
517 0x00E0, /*WORD SizeOfOptionalHeader; */
518 0x030F /*WORD Characteristics; */
519 #define CHARACTERISTICS_DLL 0x230E
522 /* IMAGE_OPTIONAL_HEADER opthdr */
523 /* Standard fields. */
524 #ifdef TCC_TARGET_X86_64
525 0x020B, /*WORD Magic; */
527 0x010B, /*WORD Magic; */
529 0x06, /*BYTE MajorLinkerVersion; */
530 0x00, /*BYTE MinorLinkerVersion; */
531 0x00000000, /*DWORD SizeOfCode; */
532 0x00000000, /*DWORD SizeOfInitializedData; */
533 0x00000000, /*DWORD SizeOfUninitializedData; */
534 0x00000000, /*DWORD AddressOfEntryPoint; */
535 0x00000000, /*DWORD BaseOfCode; */
536 #ifndef TCC_TARGET_X86_64
537 0x00000000, /*DWORD BaseOfData; */
539 /* NT additional fields. */
540 0x00400000, /*DWORD ImageBase; */
541 0x00001000, /*DWORD SectionAlignment; */
542 0x00000200, /*DWORD FileAlignment; */
543 0x0004, /*WORD MajorOperatingSystemVersion; */
544 0x0000, /*WORD MinorOperatingSystemVersion; */
545 0x0000, /*WORD MajorImageVersion; */
546 0x0000, /*WORD MinorImageVersion; */
547 0x0004, /*WORD MajorSubsystemVersion; */
548 0x0000, /*WORD MinorSubsystemVersion; */
549 0x00000000, /*DWORD Win32VersionValue; */
550 0x00000000, /*DWORD SizeOfImage; */
551 0x00000200, /*DWORD SizeOfHeaders; */
552 0x00000000, /*DWORD CheckSum; */
553 0x0002, /*WORD Subsystem; */
554 0x0000, /*WORD DllCharacteristics; */
555 0x00100000, /*DWORD SizeOfStackReserve; */
556 0x00001000, /*DWORD SizeOfStackCommit; */
557 0x00100000, /*DWORD SizeOfHeapReserve; */
558 0x00001000, /*DWORD SizeOfHeapCommit; */
559 0x00000000, /*DWORD LoaderFlags; */
560 0x00000010, /*DWORD NumberOfRvaAndSizes; */
562 /* IMAGE_DATA_DIRECTORY DataDirectory[16]; */
563 {{0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0},
564 {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}}
567 struct pe_header pe_header
= pe_template
;
571 DWORD file_offset
, sum
;
572 struct section_info
*si
;
573 IMAGE_SECTION_HEADER
*psh
;
575 op
= fopen(pe
->filename
, "wb");
577 error_noabort("could not write '%s': %s", pe
->filename
, strerror(errno
));
581 pe
->sizeofheaders
= pe_file_align(
582 sizeof (struct pe_header
)
583 + pe
->sec_count
* sizeof (IMAGE_SECTION_HEADER
)
586 file_offset
= pe
->sizeofheaders
;
588 if (2 == pe
->s1
->verbose
)
589 printf("-------------------------------"
590 "\n virt file size section" "\n");
591 for (i
= 0; i
< pe
->sec_count
; ++i
) {
592 unsigned long addr
, size
;
595 si
= pe
->sec_info
+ i
;
597 addr
= si
->sh_addr
- pe
->imagebase
;
601 if (2 == pe
->s1
->verbose
)
602 printf("%6lx %6lx %6lx %s\n",
603 addr
, file_offset
, size
, sh_name
);
607 pe_header
.opthdr
.BaseOfCode
= addr
;
608 pe_header
.opthdr
.AddressOfEntryPoint
= addr
+ pe
->start_addr
;
612 #ifndef TCC_TARGET_X86_64
613 pe_header
.opthdr
.BaseOfData
= addr
;
621 pe_set_datadir(&pe_header
, IMAGE_DIRECTORY_ENTRY_BASERELOC
, addr
, size
);
625 pe_set_datadir(&pe_header
, IMAGE_DIRECTORY_ENTRY_RESOURCE
, addr
, size
);
632 if (pe
->thunk
== pe
->s1
->sections
[si
->ord
]) {
634 pe_set_datadir(&pe_header
, IMAGE_DIRECTORY_ENTRY_IMPORT
,
635 pe
->imp_offs
+ addr
, pe
->imp_size
);
636 pe_set_datadir(&pe_header
, IMAGE_DIRECTORY_ENTRY_IAT
,
637 pe
->iat_offs
+ addr
, pe
->iat_size
);
640 pe_set_datadir(&pe_header
, IMAGE_DIRECTORY_ENTRY_EXPORT
,
641 pe
->exp_offs
+ addr
, pe
->exp_size
);
645 strcpy((char*)psh
->Name
, sh_name
);
647 psh
->Characteristics
= pe_sec_flags
[si
->cls
];
648 psh
->VirtualAddress
= addr
;
649 psh
->Misc
.VirtualSize
= size
;
650 pe_header
.opthdr
.SizeOfImage
=
651 umax(pe_virtual_align(size
+ addr
), pe_header
.opthdr
.SizeOfImage
);
654 psh
->PointerToRawData
= file_offset
;
655 file_offset
= pe_file_align(file_offset
+ si
->data_size
);
656 psh
->SizeOfRawData
= file_offset
- psh
->PointerToRawData
;
660 //pe_header.filehdr.TimeDateStamp = time(NULL);
661 pe_header
.filehdr
.NumberOfSections
= pe
->sec_count
;
662 pe_header
.opthdr
.SizeOfHeaders
= pe
->sizeofheaders
;
663 pe_header
.opthdr
.ImageBase
= pe
->imagebase
;
664 if (PE_DLL
== pe
->type
)
665 pe_header
.filehdr
.Characteristics
= CHARACTERISTICS_DLL
;
666 else if (PE_GUI
!= pe
->type
)
667 pe_header
.opthdr
.Subsystem
= 3;
670 pe_fwrite(&pe_header
, sizeof pe_header
, op
, &sum
);
671 for (i
= 0; i
< pe
->sec_count
; ++i
)
672 pe_fwrite(&pe
->sec_info
[i
].ish
, sizeof(IMAGE_SECTION_HEADER
), op
, &sum
);
673 pe_fpad(op
, pe
->sizeofheaders
);
674 for (i
= 0; i
< pe
->sec_count
; ++i
) {
675 si
= pe
->sec_info
+ i
;
678 pe_fwrite(si
->data
, si
->data_size
, op
, &sum
);
679 file_offset
= psh
->PointerToRawData
+ psh
->SizeOfRawData
;
680 pe_fpad(op
, file_offset
);
684 pe_header
.opthdr
.CheckSum
= sum
+ file_offset
;
685 fseek(op
, offsetof(struct pe_header
, opthdr
.CheckSum
), SEEK_SET
);
686 pe_fwrite(&pe_header
.opthdr
.CheckSum
, sizeof pe_header
.opthdr
.CheckSum
, op
, NULL
);
689 if (2 == pe
->s1
->verbose
)
690 printf("-------------------------------\n");
692 printf("<- %s (%lu bytes)\n", pe
->filename
, file_offset
);
697 /*----------------------------------------------------------------------------*/
699 #ifdef TCC_TARGET_X86_64
700 #define ELFW_R_(type) ELF64_R_##type
701 #define ElfW_Rel ElfW(Rela)
703 #define REL_TYPE_DIRECT R_X86_64_64
704 #define R_XXX_THUNKFIX R_X86_64_PC32
705 #define R_XXX_RELATIVE R_X86_64_RELATIVE
707 #define ELFW_ST_BIND ELF64_ST_BIND
708 #define ELFW_ST_TYPE ELF64_ST_TYPE
709 #define ELFW_ST_INFO ELF64_ST_INFO
711 #define ELFW_R_(type) ELF32_R_##type
712 #define ElfW_Rel ElfW(Rel)
714 #define REL_TYPE_DIRECT R_386_32
715 #define R_XXX_THUNKFIX R_386_32
716 #define R_XXX_RELATIVE R_386_RELATIVE
718 #define ELFW_ST_BIND ELF32_ST_BIND
719 #define ELFW_ST_TYPE ELF32_ST_TYPE
720 #define ELFW_ST_INFO ELF32_ST_INFO
722 /*----------------------------------------------------------------------------*/
724 ST_FN
struct import_symbol
*pe_add_import(struct pe_info
*pe
, int sym_index
)
728 struct pe_import_info
*p
;
729 struct import_symbol
*s
;
731 dll_index
= ((ElfW(Sym
) *)pe
->s1
->dynsymtab_section
->data
+ sym_index
)->st_value
;
735 i
= dynarray_assoc ((void**)pe
->imp_info
, pe
->imp_count
, dll_index
);
740 p
= tcc_mallocz(sizeof *p
);
741 p
->dll_index
= dll_index
;
742 dynarray_add((void***)&pe
->imp_info
, &pe
->imp_count
, p
);
745 i
= dynarray_assoc ((void**)p
->symbols
, p
->sym_count
, sym_index
);
747 return p
->symbols
[i
];
749 s
= tcc_mallocz(sizeof *s
);
750 dynarray_add((void***)&p
->symbols
, &p
->sym_count
, s
);
751 s
->sym_index
= sym_index
;
755 /*----------------------------------------------------------------------------*/
756 ST_FN
void pe_build_imports(struct pe_info
*pe
)
758 int thk_ptr
, ent_ptr
, dll_ptr
, sym_cnt
, i
;
759 DWORD rva_base
= pe
->thunk
->sh_addr
- pe
->imagebase
;
760 int ndlls
= pe
->imp_count
;
762 for (sym_cnt
= i
= 0; i
< ndlls
; ++i
)
763 sym_cnt
+= pe
->imp_info
[i
]->sym_count
;
768 pe_align_section(pe
->thunk
, 16);
770 pe
->imp_offs
= dll_ptr
= pe
->thunk
->data_offset
;
771 pe
->imp_size
= (ndlls
+ 1) * sizeof(IMAGE_IMPORT_DESCRIPTOR
);
772 pe
->iat_offs
= dll_ptr
+ pe
->imp_size
;
773 pe
->iat_size
= (sym_cnt
+ ndlls
) * sizeof(ADDR3264
);
774 section_ptr_add(pe
->thunk
, pe
->imp_size
+ 2*pe
->iat_size
);
776 thk_ptr
= pe
->iat_offs
;
777 ent_ptr
= pe
->iat_offs
+ pe
->iat_size
;
779 for (i
= 0; i
< pe
->imp_count
; ++i
) {
780 IMAGE_IMPORT_DESCRIPTOR
*hdr
;
783 struct pe_import_info
*p
= pe
->imp_info
[i
];
784 const char *name
= pe
->s1
->loaded_dlls
[p
->dll_index
-1]->name
;
786 /* put the dll name into the import header */
787 v
= put_elf_str(pe
->thunk
, name
);
789 hdr
= (IMAGE_IMPORT_DESCRIPTOR
*)(pe
->thunk
->data
+ dll_ptr
);
790 hdr
->FirstThunk
= thk_ptr
+ rva_base
;
791 hdr
->OriginalFirstThunk
= ent_ptr
+ rva_base
;
792 hdr
->Name
= v
+ rva_base
;
794 for (k
= 0, n
= p
->sym_count
; k
<= n
; ++k
) {
796 int iat_index
= p
->symbols
[k
]->iat_index
;
797 int sym_index
= p
->symbols
[k
]->sym_index
;
798 ElfW(Sym
) *imp_sym
= (ElfW(Sym
) *)pe
->s1
->dynsymtab_section
->data
+ sym_index
;
799 ElfW(Sym
) *org_sym
= (ElfW(Sym
) *)symtab_section
->data
+ iat_index
;
800 const char *name
= pe
->s1
->dynsymtab_section
->link
->data
+ imp_sym
->st_name
;
802 org_sym
->st_value
= thk_ptr
;
803 org_sym
->st_shndx
= pe
->thunk
->sh_num
;
804 v
= pe
->thunk
->data_offset
+ rva_base
;
805 section_ptr_add(pe
->thunk
, sizeof(WORD
)); /* hint, not used */
806 put_elf_str(pe
->thunk
, name
);
808 if (pe
->type
== PE_RUN
) {
809 DLLReference
*dllref
= pe
->s1
->loaded_dlls
[imp_sym
->st_value
-1];
810 if ( !dllref
->handle
)
811 dllref
->handle
= LoadLibrary(dllref
->name
);
812 v
= (ADDR3264
)GetProcAddress(dllref
->handle
, name
);
814 error_noabort("undefined symbol '%s'", name
);
818 v
= 0; /* last entry is zero */
820 *(ADDR3264
*)(pe
->thunk
->data
+thk_ptr
) =
821 *(ADDR3264
*)(pe
->thunk
->data
+ent_ptr
) = v
;
822 thk_ptr
+= sizeof (ADDR3264
);
823 ent_ptr
+= sizeof (ADDR3264
);
825 dll_ptr
+= sizeof(IMAGE_IMPORT_DESCRIPTOR
);
826 dynarray_reset(&p
->symbols
, &p
->sym_count
);
828 dynarray_reset(&pe
->imp_info
, &pe
->imp_count
);
831 /* ------------------------------------------------------------- */
833 For now only functions are exported. Export of data
834 would work, but import requires compiler support to
835 do an additional indirection.
838 __declspec(dllimport) extern int something;
840 needs to be translated to:
851 ST_FN
int sym_cmp(const void *va
, const void *vb
)
853 const char *ca
= (*(struct pe_sort_sym
**)va
)->name
;
854 const char *cb
= (*(struct pe_sort_sym
**)vb
)->name
;
855 return strcmp(ca
, cb
);
858 ST_FN
void pe_build_exports(struct pe_info
*pe
)
861 int sym_index
, sym_end
;
862 DWORD rva_base
, func_o
, name_o
, ord_o
, str_o
;
863 IMAGE_EXPORT_DIRECTORY
*hdr
;
865 struct pe_sort_sym
**sorted
, *p
;
872 rva_base
= pe
->thunk
->sh_addr
- pe
->imagebase
;
873 sym_count
= 0, sorted
= NULL
, op
= NULL
;
875 sym_end
= symtab_section
->data_offset
/ sizeof(ElfW(Sym
));
876 for (sym_index
= 1; sym_index
< sym_end
; ++sym_index
) {
877 sym
= (ElfW(Sym
)*)symtab_section
->data
+ sym_index
;
878 name
= symtab_section
->link
->data
+ sym
->st_name
;
879 if ((sym
->st_other
& 1)
880 /* export only symbols from actually written sections */
881 && pe
->s1
->sections
[sym
->st_shndx
]->sh_addr
) {
882 p
= tcc_malloc(sizeof *p
);
883 p
->index
= sym_index
;
885 dynarray_add((void***)&sorted
, &sym_count
, p
);
888 if (sym
->st_other
& 1)
889 printf("export: %s\n", name
);
890 if (sym
->st_other
& 2)
891 printf("stdcall: %s\n", name
);
898 qsort (sorted
, sym_count
, sizeof *sorted
, sym_cmp
);
900 pe_align_section(pe
->thunk
, 16);
901 dllname
= tcc_basename(pe
->filename
);
903 pe
->exp_offs
= pe
->thunk
->data_offset
;
904 func_o
= pe
->exp_offs
+ sizeof(IMAGE_EXPORT_DIRECTORY
);
905 name_o
= func_o
+ sym_count
* sizeof (DWORD
);
906 ord_o
= name_o
+ sym_count
* sizeof (DWORD
);
907 str_o
= ord_o
+ sym_count
* sizeof(WORD
);
909 hdr
= section_ptr_add(pe
->thunk
, str_o
- pe
->exp_offs
);
910 hdr
->Characteristics
= 0;
912 hdr
->NumberOfFunctions
= sym_count
;
913 hdr
->NumberOfNames
= sym_count
;
914 hdr
->AddressOfFunctions
= func_o
+ rva_base
;
915 hdr
->AddressOfNames
= name_o
+ rva_base
;
916 hdr
->AddressOfNameOrdinals
= ord_o
+ rva_base
;
917 hdr
->Name
= str_o
+ rva_base
;
918 put_elf_str(pe
->thunk
, dllname
);
921 /* automatically write exports to <output-filename>.def */
922 strcpy(buf
, pe
->filename
);
923 strcpy(tcc_fileextension(buf
), ".def");
924 op
= fopen(buf
, "w");
926 error_noabort("could not create '%s': %s", buf
, strerror(errno
));
928 fprintf(op
, "LIBRARY %s\n\nEXPORTS\n", dllname
);
930 printf("<- %s (%d symbols)\n", buf
, sym_count
);
934 for (ord
= 0; ord
< sym_count
; ++ord
)
936 p
= sorted
[ord
], sym_index
= p
->index
, name
= p
->name
;
937 /* insert actual address later in pe_relocate_rva */
938 put_elf_reloc(symtab_section
, pe
->thunk
,
939 func_o
, R_XXX_RELATIVE
, sym_index
);
940 *(DWORD
*)(pe
->thunk
->data
+ name_o
)
941 = pe
->thunk
->data_offset
+ rva_base
;
942 *(WORD
*)(pe
->thunk
->data
+ ord_o
)
944 put_elf_str(pe
->thunk
, name
);
945 func_o
+= sizeof (DWORD
);
946 name_o
+= sizeof (DWORD
);
947 ord_o
+= sizeof (WORD
);
949 fprintf(op
, "%s\n", name
);
951 pe
->exp_size
= pe
->thunk
->data_offset
- pe
->exp_offs
;
952 dynarray_reset(&sorted
, &sym_count
);
955 /* ------------------------------------------------------------- */
956 ST_FN
void pe_build_reloc (struct pe_info
*pe
)
958 DWORD offset
, block_ptr
, addr
;
960 ElfW_Rel
*rel
, *rel_end
;
961 Section
*s
= NULL
, *sr
;
963 offset
= addr
= block_ptr
= count
= i
= 0;
964 rel
= rel_end
= NULL
;
968 int type
= ELFW_R_(TYPE
)(rel
->r_info
);
969 addr
= rel
->r_offset
+ s
->sh_addr
;
971 if (type
!= REL_TYPE_DIRECT
)
973 if (count
== 0) { /* new block */
974 block_ptr
= pe
->reloc
->data_offset
;
975 section_ptr_add(pe
->reloc
, sizeof(struct pe_reloc_header
));
976 offset
= addr
& 0xFFFFFFFF<<12;
978 if ((addr
-= offset
) < (1<<12)) { /* one block spans 4k addresses */
979 WORD
*wp
= section_ptr_add(pe
->reloc
, sizeof (WORD
));
980 *wp
= addr
| IMAGE_REL_BASED_HIGHLOW
<<12;
986 } else if (i
< pe
->sec_count
) {
987 sr
= (s
= pe
->s1
->sections
[pe
->sec_info
[i
++].ord
])->reloc
;
989 rel
= (ElfW_Rel
*)sr
->data
;
990 rel_end
= (ElfW_Rel
*)(sr
->data
+ sr
->data_offset
);
996 /* store the last block and ready for a new one */
997 struct pe_reloc_header
*hdr
;
998 if (count
& 1) /* align for DWORDS */
999 section_ptr_add(pe
->reloc
, sizeof(WORD
)), ++count
;
1000 hdr
= (struct pe_reloc_header
*)(pe
->reloc
->data
+ block_ptr
);
1001 hdr
-> offset
= offset
- pe
->imagebase
;
1002 hdr
-> size
= count
* sizeof(WORD
) + sizeof(struct pe_reloc_header
);
1011 /* ------------------------------------------------------------- */
1012 ST_FN
int pe_section_class(Section
*s
)
1018 flags
= s
->sh_flags
;
1020 if (flags
& SHF_ALLOC
) {
1021 if (type
== SHT_PROGBITS
) {
1022 if (flags
& SHF_EXECINSTR
)
1024 if (flags
& SHF_WRITE
)
1026 if (0 == strcmp(name
, ".rsrc"))
1028 if (0 == strcmp(name
, ".iedat"))
1031 } else if (type
== SHT_NOBITS
) {
1032 if (flags
& SHF_WRITE
)
1036 if (0 == strcmp(name
, ".reloc"))
1038 if (0 == strncmp(name
, ".stab", 5)) /* .stab and .stabstr */
1044 ST_FN
int pe_assign_addresses (struct pe_info
*pe
)
1049 struct section_info
*si
;
1052 // pe->thunk = new_section(pe->s1, ".iedat", SHT_PROGBITS, SHF_ALLOC);
1054 section_order
= tcc_malloc(pe
->s1
->nb_sections
* sizeof (int));
1055 for (o
= k
= 0 ; k
< sec_last
; ++k
) {
1056 for (i
= 1; i
< pe
->s1
->nb_sections
; ++i
) {
1057 s
= pe
->s1
->sections
[i
];
1058 if (k
== pe_section_class(s
)) {
1059 // printf("%s %d\n", s->name, k);
1060 s
->sh_addr
= pe
->imagebase
;
1061 section_order
[o
++] = i
;
1066 pe
->sec_info
= tcc_mallocz(o
* sizeof (struct section_info
));
1067 addr
= pe
->imagebase
+ 1;
1069 for (i
= 0; i
< o
; ++i
)
1071 k
= section_order
[i
];
1072 s
= pe
->s1
->sections
[k
];
1073 c
= pe_section_class(s
);
1074 si
= &pe
->sec_info
[pe
->sec_count
];
1076 #ifdef PE_MERGE_DATA
1077 if (c
== sec_bss
&& pe
->sec_count
&& si
[-1].cls
== sec_data
) {
1078 /* append .bss to .data */
1079 s
->sh_addr
= addr
= ((addr
-1) | 15) + 1;
1080 addr
+= s
->data_offset
;
1081 si
[-1].sh_size
= addr
- si
[-1].sh_addr
;
1085 strcpy(si
->name
, s
->name
);
1088 si
->sh_addr
= s
->sh_addr
= addr
= pe_virtual_align(addr
);
1089 si
->sh_flags
= s
->sh_flags
;
1091 if (c
== sec_data
&& NULL
== pe
->thunk
)
1094 if (s
== pe
->thunk
) {
1095 pe_build_imports(pe
);
1096 pe_build_exports(pe
);
1100 pe_build_reloc (pe
);
1104 if (s
->sh_type
!= SHT_NOBITS
) {
1106 si
->data_size
= s
->data_offset
;
1109 addr
+= s
->data_offset
;
1110 si
->sh_size
= s
->data_offset
;
1113 // printf("%08x %05x %s\n", si->sh_addr, si->sh_size, si->name);
1117 for (i
= 1; i
< pe
->s1
->nb_sections
; ++i
) {
1118 Section
*s
= pe
->s1
->sections
[i
];
1119 int type
= s
->sh_type
;
1120 int flags
= s
->sh_flags
;
1121 printf("section %-16s %-10s %5x %s,%s,%s\n",
1123 type
== SHT_PROGBITS
? "progbits" :
1124 type
== SHT_NOBITS
? "nobits" :
1125 type
== SHT_SYMTAB
? "symtab" :
1126 type
== SHT_STRTAB
? "strtab" :
1127 type
== SHT_RELX
? "rel" : "???",
1129 flags
& SHF_ALLOC
? "alloc" : "",
1130 flags
& SHF_WRITE
? "write" : "",
1131 flags
& SHF_EXECINSTR
? "exec" : ""
1134 pe
->s1
->verbose
= 2;
1137 tcc_free(section_order
);
1141 /* ------------------------------------------------------------- */
1142 ST_FN
void pe_relocate_rva (struct pe_info
*pe
, Section
*s
)
1144 Section
*sr
= s
->reloc
;
1145 ElfW_Rel
*rel
, *rel_end
;
1146 rel_end
= (ElfW_Rel
*)(sr
->data
+ sr
->data_offset
);
1147 for(rel
= (ElfW_Rel
*)sr
->data
; rel
< rel_end
; rel
++) {
1148 if (ELFW_R_(TYPE
)(rel
->r_info
) == R_XXX_RELATIVE
) {
1149 int sym_index
= ELFW_R_(SYM
)(rel
->r_info
);
1150 DWORD addr
= s
->sh_addr
;
1152 ElfW(Sym
) *sym
= (ElfW(Sym
) *)symtab_section
->data
+ sym_index
;
1153 addr
= sym
->st_value
;
1155 // printf("reloc rva %08x %08x\n", (DWORD)rel->r_offset, addr);
1156 *(DWORD
*)(s
->data
+ rel
->r_offset
) += addr
- pe
->imagebase
;
1161 /*----------------------------------------------------------------------------*/
1162 ST_FN
int pe_check_symbols(struct pe_info
*pe
)
1165 int sym_index
, sym_end
;
1168 pe_align_section(text_section
, 8);
1170 sym_end
= symtab_section
->data_offset
/ sizeof(ElfW(Sym
));
1171 for (sym_index
= 1; sym_index
< sym_end
; ++sym_index
) {
1173 sym
= (ElfW(Sym
) *)symtab_section
->data
+ sym_index
;
1174 if (sym
->st_shndx
== SHN_UNDEF
) {
1176 const char *name
= symtab_section
->link
->data
+ sym
->st_name
;
1177 unsigned type
= ELFW_ST_TYPE(sym
->st_info
);
1178 int imp_sym
= pe_find_import(pe
->s1
, name
);
1179 struct import_symbol
*is
;
1183 is
= pe_add_import(pe
, imp_sym
);
1187 if (type
== STT_FUNC
) {
1188 unsigned long offset
= is
->thk_offset
;
1190 /* got aliased symbol, like stricmp and _stricmp */
1196 offset
= text_section
->data_offset
;
1197 /* add the 'jmp IAT[x]' instruction */
1198 p
= section_ptr_add(text_section
, 8);
1200 #ifdef TCC_TARGET_X86_64
1201 *(DWORD
*)(p
+1) = (DWORD
)-4;
1203 /* add a helper symbol, will be patched later in
1205 sprintf(buffer
, "IAT.%s", name
);
1206 is
->iat_index
= put_elf_sym(
1207 symtab_section
, 0, sizeof(DWORD
),
1208 ELFW_ST_INFO(STB_GLOBAL
, STT_OBJECT
),
1209 0, SHN_UNDEF
, buffer
);
1210 put_elf_reloc(symtab_section
, text_section
,
1211 offset
+ 2, R_XXX_THUNKFIX
, is
->iat_index
);
1212 is
->thk_offset
= offset
;
1215 /* tcc_realloc might have altered sym's address */
1216 sym
= (ElfW(Sym
) *)symtab_section
->data
+ sym_index
;
1218 /* patch the original symbol */
1219 sym
->st_value
= offset
;
1220 sym
->st_shndx
= text_section
->sh_num
;
1221 sym
->st_other
&= ~1; /* do not export */
1225 if (type
== STT_OBJECT
) { /* data, ptr to that should be */
1226 if (0 == is
->iat_index
) {
1227 /* original symbol will be patched later in pe_build_imports */
1228 is
->iat_index
= sym_index
;
1234 error_noabort("undefined symbol '%s'", name
);
1237 } else if (pe
->s1
->rdynamic
1238 && ELFW_ST_BIND(sym
->st_info
) != STB_LOCAL
) {
1239 /* if -rdynamic option, then export all non local symbols */
1246 /*----------------------------------------------------------------------------*/
1247 #ifdef PE_PRINT_SECTIONS
1248 ST_FN
void pe_print_section(FILE * f
, Section
* s
)
1250 /* just if you'r curious */
1254 e
= s
->data
+ s
->data_offset
;
1257 fprintf(f
, "section \"%s\"", s
->name
);
1259 fprintf(f
, "\nlink \"%s\"", s
->link
->name
);
1261 fprintf(f
, "\nreloc \"%s\"", s
->reloc
->name
);
1262 fprintf(f
, "\nv_addr %08X", (unsigned)s
->sh_addr
);
1263 fprintf(f
, "\ncontents %08X", (unsigned)l
);
1266 if (s
->sh_type
== SHT_NOBITS
)
1272 if (s
->sh_type
== SHT_SYMTAB
)
1273 m
= sizeof(ElfW(Sym
));
1274 else if (s
->sh_type
== SHT_RELX
)
1275 m
= sizeof(ElfW_Rel
);
1279 fprintf(f
, "%-8s", "offset");
1280 for (i
= 0; i
< m
; ++i
)
1281 fprintf(f
, " %02x", i
);
1284 if (s
->sh_type
== SHT_SYMTAB
|| s
->sh_type
== SHT_RELX
) {
1285 const char *fields1
[] = {
1296 const char *fields2
[] = {
1305 if (s
->sh_type
== SHT_SYMTAB
)
1306 p
= fields1
, n
= 106;
1308 p
= fields2
, n
= 58;
1310 for (i
= 0; p
[i
]; ++i
)
1311 fprintf(f
, "%6s", p
[i
]);
1312 fprintf(f
, " symbol");
1316 for (i
= 0; i
< n
; ++i
)
1322 fprintf(f
, "%08X", i
);
1323 for (n
= 0; n
< m
; ++n
) {
1325 fprintf(f
, " %02X", p
[i
+ n
]);
1330 if (s
->sh_type
== SHT_SYMTAB
) {
1331 ElfW(Sym
) *sym
= (ElfW(Sym
) *) (p
+ i
);
1332 const char *name
= s
->link
->data
+ sym
->st_name
;
1333 fprintf(f
, " %04X %04X %04X %02X %02X %02X %04X \"%s\"",
1334 (unsigned)sym
->st_name
,
1335 (unsigned)sym
->st_value
,
1336 (unsigned)sym
->st_size
,
1337 (unsigned)ELFW_ST_BIND(sym
->st_info
),
1338 (unsigned)ELFW_ST_TYPE(sym
->st_info
),
1339 (unsigned)sym
->st_other
,
1340 (unsigned)sym
->st_shndx
,
1343 } else if (s
->sh_type
== SHT_RELX
) {
1344 ElfW_Rel
*rel
= (ElfW_Rel
*) (p
+ i
);
1346 (ElfW(Sym
) *) s
->link
->data
+ ELFW_R_(SYM
)(rel
->r_info
);
1347 const char *name
= s
->link
->link
->data
+ sym
->st_name
;
1348 fprintf(f
, " %04X %02X %04X \"%s\"",
1349 (unsigned)rel
->r_offset
,
1350 (unsigned)ELFW_R_(TYPE
)(rel
->r_info
),
1351 (unsigned)ELFW_R_(SYM
)(rel
->r_info
),
1355 for (n
= 0; n
< m
; ++n
) {
1358 if (b
< 32 || b
>= 127)
1360 fprintf(f
, "%c", b
);
1370 ST_FN
void pe_print_sections(TCCState
*s1
, const char *fname
)
1375 f
= fopen(fname
, "w");
1376 for (i
= 1; i
< s1
->nb_sections
; ++i
) {
1377 s
= s1
->sections
[i
];
1378 pe_print_section(f
, s
);
1380 pe_print_section(f
, s1
->dynsymtab_section
);
1385 /* ------------------------------------------------------------- */
1387 ST_FN
int read_mem(FILE *fp
, unsigned offset
, void *buffer
, unsigned len
)
1389 fseek(fp
, offset
, 0);
1390 return len
== fread(buffer
, 1, len
, fp
);
1393 /* -------------------------------------------------------------
1394 * This is for compiled windows resources in 'coff' format
1395 * as generated by 'windres.exe -O coff ...'.
1398 ST_FN
int pe_load_res(TCCState
*s1
, FILE *fp
)
1400 struct pe_rsrc_header hdr
;
1401 Section
*rsrc_section
;
1406 if (!read_mem(fp
, 0, &hdr
, sizeof hdr
))
1409 if (hdr
.filehdr
.Machine
!= 0x014C
1410 || hdr
.filehdr
.NumberOfSections
!= 1
1411 || strcmp(hdr
.sectionhdr
.Name
, ".rsrc") != 0)
1414 rsrc_section
= new_section(s1
, ".rsrc", SHT_PROGBITS
, SHF_ALLOC
);
1415 ptr
= section_ptr_add(rsrc_section
, hdr
.sectionhdr
.SizeOfRawData
);
1416 offs
= hdr
.sectionhdr
.PointerToRawData
;
1417 if (!read_mem(fp
, offs
, ptr
, hdr
.sectionhdr
.SizeOfRawData
))
1419 offs
= hdr
.sectionhdr
.PointerToRelocations
;
1420 for (i
= 0; i
< hdr
.sectionhdr
.NumberOfRelocations
; ++i
)
1422 struct pe_rsrc_reloc rel
;
1423 if (!read_mem(fp
, offs
, &rel
, sizeof rel
))
1425 // printf("rsrc_reloc: %x %x %x\n", rel.offset, rel.size, rel.type);
1426 if (rel
.type
!= 7) /* DIR32NB */
1428 put_elf_reloc(symtab_section
, rsrc_section
,
1429 rel
.offset
, R_XXX_RELATIVE
, 0);
1437 /* ------------------------------------------------------------- */
1438 ST_FN
char *trimfront(char *p
)
1440 while (*p
&& (unsigned char)*p
<= ' ')
1445 ST_FN
char *trimback(char *a
, char *e
)
1447 while (e
> a
&& (unsigned char)e
[-1] <= ' ')
1453 ST_FN
char *get_line(char *line
, int size
, FILE *fp
)
1455 if (NULL
== fgets(line
, size
, fp
))
1457 trimback(line
, strchr(line
, 0));
1458 return trimfront(line
);
1461 /* ------------------------------------------------------------- */
1462 ST_FN
int pe_load_def(TCCState
*s1
, FILE *fp
)
1464 DLLReference
*dllref
;
1465 int state
= 0, ret
= -1;
1466 char line
[400], dllname
[80], *p
;
1469 p
= get_line(line
, sizeof line
, fp
);
1472 if (0 == *p
|| ';' == *p
)
1476 if (0 != strnicmp(p
, "LIBRARY", 7))
1478 strcpy(dllname
, trimfront(p
+7));
1483 if (0 != stricmp(p
, "EXPORTS"))
1489 dllref
= tcc_mallocz(sizeof(DLLReference
) + strlen(dllname
));
1490 strcpy(dllref
->name
, dllname
);
1491 dynarray_add((void ***) &s1
->loaded_dlls
, &s1
->nb_loaded_dlls
, dllref
);
1495 add_elf_sym(s1
->dynsymtab_section
,
1496 s1
->nb_loaded_dlls
, 0,
1497 ELFW_ST_INFO(STB_GLOBAL
, STT_FUNC
), 0,
1498 text_section
->sh_num
, p
);
1507 /* ------------------------------------------------------------- */
1508 #define TINY_IMPDEF_GET_EXPORT_NAMES_ONLY
1509 #include "win32/tools/tiny_impdef.c"
1511 ST_FN
int pe_load_dll(TCCState
*s1
, const char *dllname
, FILE *fp
)
1515 p
= get_export_names(fp
);
1517 DLLReference
*dllref
;
1518 dllref
= tcc_mallocz(sizeof(DLLReference
) + strlen(dllname
));
1519 strcpy(dllref
->name
, dllname
);
1520 dynarray_add((void ***) &s1
->loaded_dlls
, &s1
->nb_loaded_dlls
, dllref
);
1521 for (q
= p
, i
= 0; *q
; ++i
) {
1522 add_elf_sym(s1
->dynsymtab_section
,
1523 s1
->nb_loaded_dlls
, 0,
1524 ELFW_ST_INFO(STB_GLOBAL
, STT_FUNC
), 0,
1525 text_section
->sh_num
, q
);
1533 /* ------------------------------------------------------------- */
1534 PUB_FN
int pe_load_file(struct TCCState
*s1
, const char *filename
, int fd
)
1536 FILE *fp
= fdopen(dup(fd
), "rb");
1540 if (0 == strcmp(tcc_fileextension(filename
), ".def"))
1541 ret
= pe_load_def(s1
, fp
);
1542 else if (pe_load_res(s1
, fp
) == 0)
1544 else if (read_mem(fp
, 0, buf
, sizeof buf
) && 0 == strncmp(buf
, "MZ", 2))
1545 ret
= pe_load_dll(s1
, tcc_basename(filename
), fp
);
1551 int pe_add_dll(struct TCCState
*s
, const char *libraryname
)
1554 snprintf(buf
, sizeof(buf
), "%s.def", libraryname
);
1555 if (tcc_add_dll(s
, buf
, 0) == 0)
1557 snprintf(buf
, sizeof(buf
), "%s.dll", libraryname
);
1558 if (tcc_add_dll(s
, buf
, 0) == 0)
1563 /* ------------------------------------------------------------- */
1564 #ifdef TCC_TARGET_X86_64
1565 #define PE_STDSYM(n,s) n
1567 #define PE_STDSYM(n,s) "_" n s
1570 ST_FN
void pe_add_runtime_ex(TCCState
*s1
, struct pe_info
*pe
)
1572 const char *start_symbol
;
1573 unsigned long addr
= 0;
1576 if (find_elf_sym(symtab_section
, PE_STDSYM("WinMain","@16")))
1579 if (TCC_OUTPUT_DLL
== s1
->output_type
) {
1581 /* need this for 'tccelf.c:relocate_section()' */
1582 s1
->output_type
= TCC_OUTPUT_EXE
;
1586 TCC_OUTPUT_MEMORY
== s1
->output_type
1587 ? PE_GUI
== pe_type
? "_runwinmain" : NULL
1588 : PE_DLL
== pe_type
? PE_STDSYM("_dllstart","@12")
1589 : PE_GUI
== pe_type
? "_winstart" : "_start"
1592 /* grab the startup code from libtcc1 */
1594 add_elf_sym(symtab_section
,
1596 ELFW_ST_INFO(STB_GLOBAL
, STT_NOTYPE
), 0,
1597 SHN_UNDEF
, start_symbol
);
1599 if (0 == s1
->nostdlib
) {
1600 static const char *libs
[] = {
1601 "tcc1", "msvcrt", "kernel32", "", "user32", "gdi32", NULL
1603 const char **pp
, *p
;
1604 for (pp
= libs
; 0 != (p
= *pp
); ++pp
) {
1606 if (PE_DLL
!= pe_type
&& PE_GUI
!= pe_type
)
1608 } else if (tcc_add_library(s1
, p
) < 0)
1609 error_noabort("cannot find library: %s", p
);
1614 addr
= (uplong
)tcc_get_symbol_err(s1
, start_symbol
);
1615 if (s1
->output_type
== TCC_OUTPUT_MEMORY
&& addr
)
1616 /* for -run GUI's, put '_runwinmain' instead of 'main' */
1617 add_elf_sym(symtab_section
,
1619 ELFW_ST_INFO(STB_GLOBAL
, STT_NOTYPE
), 0,
1620 text_section
->sh_num
, "main");
1624 pe
->start_addr
= addr
;
1627 PUB_FN
int pe_output_file(TCCState
* s1
, const char *filename
)
1633 memset(&pe
, 0, sizeof pe
);
1634 pe
.filename
= filename
;
1637 pe_add_runtime_ex(s1
, &pe
);
1638 relocate_common_syms(); /* assign bss adresses */
1639 tcc_add_linker_symbols(s1
);
1641 ret
= pe_check_symbols(&pe
);
1646 if (PE_DLL
== pe
.type
) {
1647 pe
.reloc
= new_section(pe
.s1
, ".reloc", SHT_PROGBITS
, 0);
1648 pe
.imagebase
= 0x10000000;
1650 pe
.imagebase
= 0x00400000;
1652 pe_assign_addresses(&pe
);
1653 relocate_syms(s1
, 0);
1654 for (i
= 1; i
< s1
->nb_sections
; ++i
) {
1655 Section
*s
= s1
->sections
[i
];
1657 relocate_section(s1
, s
);
1658 pe_relocate_rva(&pe
, s
);
1664 ret
= pe_write(&pe
);
1665 tcc_free(pe
.sec_info
);
1667 #ifndef TCC_IS_NATIVE
1668 error_noabort("-run supported only on native platform");
1671 pe
.thunk
= data_section
;
1672 pe_build_imports(&pe
);
1675 #ifdef PE_PRINT_SECTIONS
1676 pe_print_sections(s1
, "tcc.log");
1681 /* ------------------------------------------------------------- */
1682 #endif /* def TCC_TARGET_PE */
1683 /* ------------------------------------------------------------- */