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 stricmp strcasecmp
25 #define strnicmp strncasecmp
33 // #define PE_PRINT_SECTIONS
35 #ifdef TCC_TARGET_X86_64
36 # define ADDR3264 ULONGLONG
38 # define ADDR3264 DWORD
41 #if defined _WIN32 && (defined _WIN64) == (defined TCC_TARGET_X86_64)
46 void dbg_printf (const char *fmt
, ...)
52 x
= vsprintf (buffer
, fmt
, arg
);
53 strcpy(buffer
+x
, "\n");
54 OutputDebugString(buffer
);
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 long DWORD
;
66 typedef unsigned long long ULONGLONG
;
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
{
96 WORD NumberOfSections
;
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
;
110 } IMAGE_DATA_DIRECTORY
, *PIMAGE_DATA_DIRECTORY
;
113 typedef struct _IMAGE_OPTIONAL_HEADER
{
114 /* Standard fields. */
116 BYTE MajorLinkerVersion
;
117 BYTE MinorLinkerVersion
;
119 DWORD SizeOfInitializedData
;
120 DWORD SizeOfUninitializedData
;
121 DWORD AddressOfEntryPoint
;
123 #ifndef TCC_TARGET_X86_64
126 /* NT additional fields. */
128 DWORD SectionAlignment
;
130 WORD MajorOperatingSystemVersion
;
131 WORD MinorOperatingSystemVersion
;
132 WORD MajorImageVersion
;
133 WORD MinorImageVersion
;
134 WORD MajorSubsystemVersion
;
135 WORD MinorSubsystemVersion
;
136 DWORD Win32VersionValue
;
141 WORD DllCharacteristics
;
142 ADDR3264 SizeOfStackReserve
;
143 ADDR3264 SizeOfStackCommit
;
144 ADDR3264 SizeOfHeapReserve
;
145 ADDR3264 SizeOfHeapCommit
;
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
];
174 DWORD PhysicalAddress
;
177 DWORD VirtualAddress
;
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
;
196 DWORD NumberOfFunctions
;
198 DWORD AddressOfFunctions
;
199 DWORD AddressOfNames
;
200 DWORD AddressOfNameOrdinals
;
201 } IMAGE_EXPORT_DIRECTORY
,*PIMAGE_EXPORT_DIRECTORY
;
203 typedef struct _IMAGE_IMPORT_DESCRIPTOR
{
205 DWORD Characteristics
;
206 DWORD OriginalFirstThunk
;
209 DWORD ForwarderChain
;
212 } IMAGE_IMPORT_DESCRIPTOR
;
214 typedef struct _IMAGE_BASE_RELOCATION
{
215 DWORD VirtualAddress
;
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
233 /* ----------------------------------------------------------- */
234 #endif /* ndef IMAGE_NT_SIGNATURE */
235 /* ----------------------------------------------------------- */
236 #pragma pack(push, 1)
240 IMAGE_DOS_HEADER doshdr
;
243 IMAGE_FILE_HEADER filehdr
;
244 #ifdef TCC_TARGET_X86_64
245 IMAGE_OPTIONAL_HEADER64 opthdr
;
248 IMAGE_OPTIONAL_HEADER32 opthdr
;
250 IMAGE_OPTIONAL_HEADER opthdr
;
255 struct pe_reloc_header
{
260 struct pe_rsrc_header
{
261 struct _IMAGE_FILE_HEADER filehdr
;
262 struct _IMAGE_SECTION_HEADER sectionhdr
;
265 struct pe_rsrc_reloc
{
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
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
{
320 IMAGE_SECTION_HEADER ish
;
323 struct import_symbol
{
329 struct pe_import_info
{
332 struct import_symbol
**symbols
;
339 const char *filename
;
353 struct section_info
*sec_info
;
355 struct pe_import_info
**imp_info
;
365 /* --------------------------------------------*/
367 static const char* get_alt_symbol(char *buffer
, const char *symbol
)
370 p
= strrchr(symbol
, '@');
371 if (p
&& isnum(p
[1]) && symbol
[0] == '_') { /* stdcall decor */
372 strcpy(buffer
, symbol
+1)[p
-symbol
-1] = 0;
373 } else if (symbol
[0] != '_') { /* try non-ansi function */
374 buffer
[0] = '_', strcpy(buffer
+ 1, symbol
);
375 } else if (0 == memcmp(symbol
, "__imp__", 7)) { /* mingw 2.0 */
376 strcpy(buffer
, symbol
+ 6);
377 } else if (0 == memcmp(symbol
, "_imp___", 7)) { /* mingw 3.7 */
378 strcpy(buffer
, symbol
+ 6);
385 static int pe_find_import(TCCState
* s1
, const char *symbol
)
389 int sym_index
, n
= 0;
391 s
= n
? get_alt_symbol(buffer
, symbol
) : symbol
;
392 sym_index
= find_elf_sym(s1
->dynsymtab_section
, s
);
393 // printf("find (%d) %d %s\n", n, sym_index, s);
394 } while (0 == sym_index
&& ++n
< 2);
398 /*----------------------------------------------------------------------------*/
400 static int dynarray_assoc(void **pp
, int n
, int key
)
403 for (i
= 0; i
< n
; ++i
, ++pp
)
404 if (key
== **(int **) pp
)
410 ST_FN DWORD
umin(DWORD a
, DWORD b
)
412 return a
< b
? a
: b
;
416 static DWORD
umax(DWORD a
, DWORD b
)
418 return a
< b
? b
: a
;
421 static DWORD
pe_file_align(struct pe_info
*pe
, DWORD n
)
423 return (n
+ (pe
->file_align
- 1)) & ~(pe
->file_align
- 1);
426 static DWORD
pe_virtual_align(struct pe_info
*pe
, DWORD n
)
428 return (n
+ (pe
->section_align
- 1)) & ~(pe
->section_align
- 1);
431 static void pe_align_section(Section
*s
, int a
)
433 int i
= s
->data_offset
& (a
-1);
435 section_ptr_add(s
, a
- i
);
438 static void pe_set_datadir(struct pe_header
*hdr
, int dir
, DWORD addr
, DWORD size
)
440 hdr
->opthdr
.DataDirectory
[dir
].VirtualAddress
= addr
;
441 hdr
->opthdr
.DataDirectory
[dir
].Size
= size
;
444 static int pe_fwrite(void *data
, unsigned len
, FILE *fp
, DWORD
*psum
)
450 for (i
= len
; i
> 0; i
-= 2) {
451 sum
+= (i
>= 2) ? *p
++ : *(BYTE
*)p
;
452 sum
= (sum
+ (sum
>> 16)) & 0xFFFF;
456 return len
== fwrite(data
, 1, len
, fp
) ? 0 : -1;
459 static void pe_fpad(FILE *fp
, DWORD new_pos
)
461 DWORD pos
= ftell(fp
);
462 while (++pos
<= new_pos
)
466 /*----------------------------------------------------------------------------*/
467 static int pe_write(struct pe_info
*pe
)
469 static const struct pe_header pe_template
= {
471 /* IMAGE_DOS_HEADER doshdr */
472 0x5A4D, /*WORD e_magic; Magic number */
473 0x0090, /*WORD e_cblp; Bytes on last page of file */
474 0x0003, /*WORD e_cp; Pages in file */
475 0x0000, /*WORD e_crlc; Relocations */
477 0x0004, /*WORD e_cparhdr; Size of header in paragraphs */
478 0x0000, /*WORD e_minalloc; Minimum extra paragraphs needed */
479 0xFFFF, /*WORD e_maxalloc; Maximum extra paragraphs needed */
480 0x0000, /*WORD e_ss; Initial (relative) SS value */
482 0x00B8, /*WORD e_sp; Initial SP value */
483 0x0000, /*WORD e_csum; Checksum */
484 0x0000, /*WORD e_ip; Initial IP value */
485 0x0000, /*WORD e_cs; Initial (relative) CS value */
486 0x0040, /*WORD e_lfarlc; File address of relocation table */
487 0x0000, /*WORD e_ovno; Overlay number */
488 {0,0,0,0}, /*WORD e_res[4]; Reserved words */
489 0x0000, /*WORD e_oemid; OEM identifier (for e_oeminfo) */
490 0x0000, /*WORD e_oeminfo; OEM information; e_oemid specific */
491 {0,0,0,0,0,0,0,0,0,0}, /*WORD e_res2[10]; Reserved words */
492 0x00000080 /*DWORD e_lfanew; File address of new exe header */
494 /* BYTE dosstub[0x40] */
495 /* 14 code bytes + "This program cannot be run in DOS mode.\r\r\n$" + 6 * 0x00 */
496 0x0e,0x1f,0xba,0x0e,0x00,0xb4,0x09,0xcd,0x21,0xb8,0x01,0x4c,0xcd,0x21,0x54,0x68,
497 0x69,0x73,0x20,0x70,0x72,0x6f,0x67,0x72,0x61,0x6d,0x20,0x63,0x61,0x6e,0x6e,0x6f,
498 0x74,0x20,0x62,0x65,0x20,0x72,0x75,0x6e,0x20,0x69,0x6e,0x20,0x44,0x4f,0x53,0x20,
499 0x6d,0x6f,0x64,0x65,0x2e,0x0d,0x0d,0x0a,0x24,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
501 0x00004550, /* DWORD nt_sig = IMAGE_NT_SIGNATURE */
503 /* IMAGE_FILE_HEADER filehdr */
504 #if defined(TCC_TARGET_I386)
505 0x014C, /*WORD Machine; */
506 #elif defined(TCC_TARGET_X86_64)
507 0x8664, /*WORD Machine; */
508 #elif defined(TCC_TARGET_ARM)
509 0x01C0, /*WORD Machine; */
511 0x0003, /*WORD NumberOfSections; */
512 0x00000000, /*DWORD TimeDateStamp; */
513 0x00000000, /*DWORD PointerToSymbolTable; */
514 0x00000000, /*DWORD NumberOfSymbols; */
515 #if defined(TCC_TARGET_X86_64)
516 0x00F0, /*WORD SizeOfOptionalHeader; */
517 0x022F /*WORD Characteristics; */
518 #define CHARACTERISTICS_DLL 0x222E
519 #elif defined(TCC_TARGET_I386)
520 0x00E0, /*WORD SizeOfOptionalHeader; */
521 0x030F /*WORD Characteristics; */
522 #define CHARACTERISTICS_DLL 0x230E
523 #elif defined(TCC_TARGET_ARM)
524 0x00E0, /*WORD SizeOfOptionalHeader; */
525 0x010F, /*WORD Characteristics; */
526 #define CHARACTERISTICS_DLL 0x230F
529 /* IMAGE_OPTIONAL_HEADER opthdr */
530 /* Standard fields. */
531 #ifdef TCC_TARGET_X86_64
532 0x020B, /*WORD Magic; */
534 0x010B, /*WORD Magic; */
536 0x06, /*BYTE MajorLinkerVersion; */
537 0x00, /*BYTE MinorLinkerVersion; */
538 0x00000000, /*DWORD SizeOfCode; */
539 0x00000000, /*DWORD SizeOfInitializedData; */
540 0x00000000, /*DWORD SizeOfUninitializedData; */
541 0x00000000, /*DWORD AddressOfEntryPoint; */
542 0x00000000, /*DWORD BaseOfCode; */
543 #ifndef TCC_TARGET_X86_64
544 0x00000000, /*DWORD BaseOfData; */
546 /* NT additional fields. */
547 #if defined(TCC_TARGET_ARM)
548 0x00100000, /*DWORD ImageBase; */
550 0x00400000, /*DWORD ImageBase; */
552 0x00001000, /*DWORD SectionAlignment; */
553 0x00000200, /*DWORD FileAlignment; */
554 0x0004, /*WORD MajorOperatingSystemVersion; */
555 0x0000, /*WORD MinorOperatingSystemVersion; */
556 0x0000, /*WORD MajorImageVersion; */
557 0x0000, /*WORD MinorImageVersion; */
558 0x0004, /*WORD MajorSubsystemVersion; */
559 0x0000, /*WORD MinorSubsystemVersion; */
560 0x00000000, /*DWORD Win32VersionValue; */
561 0x00000000, /*DWORD SizeOfImage; */
562 0x00000200, /*DWORD SizeOfHeaders; */
563 0x00000000, /*DWORD CheckSum; */
564 0x0002, /*WORD Subsystem; */
565 0x0000, /*WORD DllCharacteristics; */
566 0x00100000, /*DWORD SizeOfStackReserve; */
567 0x00001000, /*DWORD SizeOfStackCommit; */
568 0x00100000, /*DWORD SizeOfHeapReserve; */
569 0x00001000, /*DWORD SizeOfHeapCommit; */
570 0x00000000, /*DWORD LoaderFlags; */
571 0x00000010, /*DWORD NumberOfRvaAndSizes; */
573 /* IMAGE_DATA_DIRECTORY DataDirectory[16]; */
574 {{0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0},
575 {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}}
578 struct pe_header pe_header
= pe_template
;
582 DWORD file_offset
, sum
;
583 struct section_info
*si
;
584 IMAGE_SECTION_HEADER
*psh
;
586 op
= fopen(pe
->filename
, "wb");
588 error_noabort("could not write '%s': %s", pe
->filename
, strerror(errno
));
592 pe
->sizeofheaders
= pe_file_align(pe
,
593 sizeof (struct pe_header
)
594 + pe
->sec_count
* sizeof (IMAGE_SECTION_HEADER
)
597 file_offset
= pe
->sizeofheaders
;
599 if (2 == pe
->s1
->verbose
)
600 printf("-------------------------------"
601 "\n virt file size section" "\n");
602 for (i
= 0; i
< pe
->sec_count
; ++i
) {
603 unsigned long addr
, size
;
606 si
= pe
->sec_info
+ i
;
608 addr
= si
->sh_addr
- pe
->imagebase
;
612 if (2 == pe
->s1
->verbose
)
613 printf("%6lx %6lx %6lx %s\n",
614 addr
, file_offset
, size
, sh_name
);
618 pe_header
.opthdr
.BaseOfCode
= addr
;
619 pe_header
.opthdr
.AddressOfEntryPoint
= addr
+ pe
->start_addr
;
623 #ifndef TCC_TARGET_X86_64
624 pe_header
.opthdr
.BaseOfData
= addr
;
632 pe_set_datadir(&pe_header
, IMAGE_DIRECTORY_ENTRY_BASERELOC
, addr
, size
);
636 pe_set_datadir(&pe_header
, IMAGE_DIRECTORY_ENTRY_RESOURCE
, addr
, size
);
640 pe_set_datadir(&pe_header
, IMAGE_DIRECTORY_ENTRY_EXCEPTION
, addr
, size
);
647 if (pe
->thunk
== pe
->s1
->sections
[si
->ord
]) {
649 pe_set_datadir(&pe_header
, IMAGE_DIRECTORY_ENTRY_IMPORT
,
650 pe
->imp_offs
+ addr
, pe
->imp_size
);
651 pe_set_datadir(&pe_header
, IMAGE_DIRECTORY_ENTRY_IAT
,
652 pe
->iat_offs
+ addr
, pe
->iat_size
);
655 pe_set_datadir(&pe_header
, IMAGE_DIRECTORY_ENTRY_EXPORT
,
656 pe
->exp_offs
+ addr
, pe
->exp_size
);
660 strcpy((char*)psh
->Name
, sh_name
);
662 psh
->Characteristics
= pe_sec_flags
[si
->cls
];
663 psh
->VirtualAddress
= addr
;
664 psh
->Misc
.VirtualSize
= size
;
665 pe_header
.opthdr
.SizeOfImage
=
666 umax(pe_virtual_align(pe
, size
+ addr
), pe_header
.opthdr
.SizeOfImage
);
669 psh
->PointerToRawData
= file_offset
;
670 file_offset
= pe_file_align(pe
, file_offset
+ si
->data_size
);
671 psh
->SizeOfRawData
= file_offset
- psh
->PointerToRawData
;
675 //pe_header.filehdr.TimeDateStamp = time(NULL);
676 pe_header
.filehdr
.NumberOfSections
= pe
->sec_count
;
677 pe_header
.opthdr
.SizeOfHeaders
= pe
->sizeofheaders
;
678 pe_header
.opthdr
.ImageBase
= pe
->imagebase
;
679 if (PE_DLL
== pe
->type
)
680 pe_header
.filehdr
.Characteristics
= CHARACTERISTICS_DLL
;
681 else if (PE_GUI
!= pe
->type
)
682 pe_header
.opthdr
.Subsystem
= 3;
685 pe_fwrite(&pe_header
, sizeof pe_header
, op
, &sum
);
686 for (i
= 0; i
< pe
->sec_count
; ++i
)
687 pe_fwrite(&pe
->sec_info
[i
].ish
, sizeof(IMAGE_SECTION_HEADER
), op
, &sum
);
688 pe_fpad(op
, pe
->sizeofheaders
);
689 for (i
= 0; i
< pe
->sec_count
; ++i
) {
690 si
= pe
->sec_info
+ i
;
693 pe_fwrite(si
->data
, si
->data_size
, op
, &sum
);
694 file_offset
= psh
->PointerToRawData
+ psh
->SizeOfRawData
;
695 pe_fpad(op
, file_offset
);
699 pe_header
.opthdr
.CheckSum
= sum
+ file_offset
;
700 fseek(op
, offsetof(struct pe_header
, opthdr
.CheckSum
), SEEK_SET
);
701 pe_fwrite(&pe_header
.opthdr
.CheckSum
, sizeof pe_header
.opthdr
.CheckSum
, op
, NULL
);
704 if (2 == pe
->s1
->verbose
)
705 printf("-------------------------------\n");
707 printf("<- %s (%lu bytes)\n", pe
->filename
, file_offset
);
712 /*----------------------------------------------------------------------------*/
714 #if defined(TCC_TARGET_X86_64)
715 #define ELFW_R_(type) ELF64_R_##type
716 #define ElfW_Rel ElfW(Rela)
718 #define REL_TYPE_DIRECT R_X86_64_64
719 #define R_XXX_THUNKFIX R_X86_64_PC32
720 #define R_XXX_RELATIVE R_X86_64_RELATIVE
722 #define ELFW_ST_BIND ELF64_ST_BIND
723 #define ELFW_ST_TYPE ELF64_ST_TYPE
724 #define ELFW_ST_INFO ELF64_ST_INFO
725 #elif defined(TCC_TARGET_I386)
726 #define ELFW_R_(type) ELF32_R_##type
727 #define ElfW_Rel ElfW(Rel)
729 #define REL_TYPE_DIRECT R_386_32
730 #define R_XXX_THUNKFIX R_386_32
731 #define R_XXX_RELATIVE R_386_RELATIVE
733 #define ELFW_ST_BIND ELF32_ST_BIND
734 #define ELFW_ST_TYPE ELF32_ST_TYPE
735 #define ELFW_ST_INFO ELF32_ST_INFO
736 #elif defined(TCC_TARGET_ARM)
737 #define ELFW_R_(type) ELF32_R_##type
738 #define ElfW_Rel ElfW(Rel)
740 #define REL_TYPE_DIRECT R_ARM_ABS32
741 #define R_XXX_THUNKFIX R_ARM_ABS32
742 #define R_XXX_RELATIVE R_ARM_RELATIVE
744 #define ELFW_ST_BIND ELF32_ST_BIND
745 #define ELFW_ST_TYPE ELF32_ST_TYPE
746 #define ELFW_ST_INFO ELF32_ST_INFO
748 /*----------------------------------------------------------------------------*/
750 static struct import_symbol
*pe_add_import(struct pe_info
*pe
, int sym_index
)
754 struct pe_import_info
*p
;
755 struct import_symbol
*s
;
757 dll_index
= ((ElfW(Sym
) *)pe
->s1
->dynsymtab_section
->data
+ sym_index
)->st_value
;
761 i
= dynarray_assoc ((void**)pe
->imp_info
, pe
->imp_count
, dll_index
);
766 p
= tcc_mallocz(sizeof *p
);
767 p
->dll_index
= dll_index
;
768 dynarray_add((void***)&pe
->imp_info
, &pe
->imp_count
, p
);
771 i
= dynarray_assoc ((void**)p
->symbols
, p
->sym_count
, sym_index
);
773 return p
->symbols
[i
];
775 s
= tcc_mallocz(sizeof *s
);
776 dynarray_add((void***)&p
->symbols
, &p
->sym_count
, s
);
777 s
->sym_index
= sym_index
;
781 /*----------------------------------------------------------------------------*/
782 static void pe_build_imports(struct pe_info
*pe
)
784 int thk_ptr
, ent_ptr
, dll_ptr
, sym_cnt
, i
;
785 DWORD rva_base
= pe
->thunk
->sh_addr
- pe
->imagebase
;
786 int ndlls
= pe
->imp_count
;
788 for (sym_cnt
= i
= 0; i
< ndlls
; ++i
)
789 sym_cnt
+= pe
->imp_info
[i
]->sym_count
;
794 pe_align_section(pe
->thunk
, 16);
796 pe
->imp_offs
= dll_ptr
= pe
->thunk
->data_offset
;
797 pe
->imp_size
= (ndlls
+ 1) * sizeof(IMAGE_IMPORT_DESCRIPTOR
);
798 pe
->iat_offs
= dll_ptr
+ pe
->imp_size
;
799 pe
->iat_size
= (sym_cnt
+ ndlls
) * sizeof(ADDR3264
);
800 section_ptr_add(pe
->thunk
, pe
->imp_size
+ 2*pe
->iat_size
);
802 thk_ptr
= pe
->iat_offs
;
803 ent_ptr
= pe
->iat_offs
+ pe
->iat_size
;
805 for (i
= 0; i
< pe
->imp_count
; ++i
) {
806 IMAGE_IMPORT_DESCRIPTOR
*hdr
;
809 struct pe_import_info
*p
= pe
->imp_info
[i
];
810 const char *name
= pe
->s1
->loaded_dlls
[p
->dll_index
-1]->name
;
812 /* put the dll name into the import header */
813 v
= put_elf_str(pe
->thunk
, name
);
815 hdr
= (IMAGE_IMPORT_DESCRIPTOR
*)(pe
->thunk
->data
+ dll_ptr
);
816 hdr
->FirstThunk
= thk_ptr
+ rva_base
;
817 hdr
->OriginalFirstThunk
= ent_ptr
+ rva_base
;
818 hdr
->Name
= v
+ rva_base
;
820 for (k
= 0, n
= p
->sym_count
; k
<= n
; ++k
) {
822 int iat_index
= p
->symbols
[k
]->iat_index
;
823 int sym_index
= p
->symbols
[k
]->sym_index
;
824 ElfW(Sym
) *imp_sym
= (ElfW(Sym
) *)pe
->s1
->dynsymtab_section
->data
+ sym_index
;
825 ElfW(Sym
) *org_sym
= (ElfW(Sym
) *)symtab_section
->data
+ iat_index
;
826 const char *name
= pe
->s1
->dynsymtab_section
->link
->data
+ imp_sym
->st_name
;
828 org_sym
->st_value
= thk_ptr
;
829 org_sym
->st_shndx
= pe
->thunk
->sh_num
;
830 v
= pe
->thunk
->data_offset
+ rva_base
;
831 section_ptr_add(pe
->thunk
, sizeof(WORD
)); /* hint, not used */
832 put_elf_str(pe
->thunk
, name
);
834 if (pe
->type
== PE_RUN
) {
835 DLLReference
*dllref
= pe
->s1
->loaded_dlls
[imp_sym
->st_value
-1];
836 if ( !dllref
->handle
)
837 dllref
->handle
= LoadLibrary(dllref
->name
);
838 v
= (ADDR3264
)GetProcAddress(dllref
->handle
, name
);
840 error_noabort("undefined symbol '%s'", name
);
844 v
= 0; /* last entry is zero */
846 *(ADDR3264
*)(pe
->thunk
->data
+thk_ptr
) =
847 *(ADDR3264
*)(pe
->thunk
->data
+ent_ptr
) = v
;
848 thk_ptr
+= sizeof (ADDR3264
);
849 ent_ptr
+= sizeof (ADDR3264
);
851 dll_ptr
+= sizeof(IMAGE_IMPORT_DESCRIPTOR
);
852 dynarray_reset(&p
->symbols
, &p
->sym_count
);
854 dynarray_reset(&pe
->imp_info
, &pe
->imp_count
);
857 /* ------------------------------------------------------------- */
865 static int sym_cmp(const void *va
, const void *vb
)
867 const char *ca
= (*(struct pe_sort_sym
**)va
)->name
;
868 const char *cb
= (*(struct pe_sort_sym
**)vb
)->name
;
869 return strcmp(ca
, cb
);
872 static void pe_build_exports(struct pe_info
*pe
)
875 int sym_index
, sym_end
;
876 DWORD rva_base
, func_o
, name_o
, ord_o
, str_o
;
877 IMAGE_EXPORT_DIRECTORY
*hdr
;
879 struct pe_sort_sym
**sorted
, *p
;
886 rva_base
= pe
->thunk
->sh_addr
- pe
->imagebase
;
887 sym_count
= 0, sorted
= NULL
, op
= NULL
;
889 sym_end
= symtab_section
->data_offset
/ sizeof(ElfW(Sym
));
890 for (sym_index
= 1; sym_index
< sym_end
; ++sym_index
) {
891 sym
= (ElfW(Sym
)*)symtab_section
->data
+ sym_index
;
892 name
= symtab_section
->link
->data
+ sym
->st_name
;
893 if ((sym
->st_other
& 1)
894 /* export only symbols from actually written sections */
895 && pe
->s1
->sections
[sym
->st_shndx
]->sh_addr
) {
896 p
= tcc_malloc(sizeof *p
);
897 p
->index
= sym_index
;
899 dynarray_add((void***)&sorted
, &sym_count
, p
);
902 if (sym
->st_other
& 1)
903 printf("export: %s\n", name
);
904 if (sym
->st_other
& 2)
905 printf("stdcall: %s\n", name
);
912 qsort (sorted
, sym_count
, sizeof *sorted
, sym_cmp
);
914 pe_align_section(pe
->thunk
, 16);
915 dllname
= tcc_basename(pe
->filename
);
917 pe
->exp_offs
= pe
->thunk
->data_offset
;
918 func_o
= pe
->exp_offs
+ sizeof(IMAGE_EXPORT_DIRECTORY
);
919 name_o
= func_o
+ sym_count
* sizeof (DWORD
);
920 ord_o
= name_o
+ sym_count
* sizeof (DWORD
);
921 str_o
= ord_o
+ sym_count
* sizeof(WORD
);
923 hdr
= section_ptr_add(pe
->thunk
, str_o
- pe
->exp_offs
);
924 hdr
->Characteristics
= 0;
926 hdr
->NumberOfFunctions
= sym_count
;
927 hdr
->NumberOfNames
= sym_count
;
928 hdr
->AddressOfFunctions
= func_o
+ rva_base
;
929 hdr
->AddressOfNames
= name_o
+ rva_base
;
930 hdr
->AddressOfNameOrdinals
= ord_o
+ rva_base
;
931 hdr
->Name
= str_o
+ rva_base
;
932 put_elf_str(pe
->thunk
, dllname
);
935 /* automatically write exports to <output-filename>.def */
936 strcpy(buf
, pe
->filename
);
937 strcpy(tcc_fileextension(buf
), ".def");
938 op
= fopen(buf
, "w");
940 error_noabort("could not create '%s': %s", buf
, strerror(errno
));
942 fprintf(op
, "LIBRARY %s\n\nEXPORTS\n", dllname
);
944 printf("<- %s (%d symbols)\n", buf
, sym_count
);
948 for (ord
= 0; ord
< sym_count
; ++ord
)
950 p
= sorted
[ord
], sym_index
= p
->index
, name
= p
->name
;
951 /* insert actual address later in pe_relocate_rva */
952 put_elf_reloc(symtab_section
, pe
->thunk
,
953 func_o
, R_XXX_RELATIVE
, sym_index
);
954 *(DWORD
*)(pe
->thunk
->data
+ name_o
)
955 = pe
->thunk
->data_offset
+ rva_base
;
956 *(WORD
*)(pe
->thunk
->data
+ ord_o
)
958 put_elf_str(pe
->thunk
, name
);
959 func_o
+= sizeof (DWORD
);
960 name_o
+= sizeof (DWORD
);
961 ord_o
+= sizeof (WORD
);
963 fprintf(op
, "%s\n", name
);
965 pe
->exp_size
= pe
->thunk
->data_offset
- pe
->exp_offs
;
966 dynarray_reset(&sorted
, &sym_count
);
971 /* ------------------------------------------------------------- */
972 static void pe_build_reloc (struct pe_info
*pe
)
974 DWORD offset
, block_ptr
, addr
;
976 ElfW_Rel
*rel
, *rel_end
;
977 Section
*s
= NULL
, *sr
;
979 offset
= addr
= block_ptr
= count
= i
= 0;
980 rel
= rel_end
= NULL
;
984 int type
= ELFW_R_(TYPE
)(rel
->r_info
);
985 addr
= rel
->r_offset
+ s
->sh_addr
;
987 if (type
!= REL_TYPE_DIRECT
)
989 if (count
== 0) { /* new block */
990 block_ptr
= pe
->reloc
->data_offset
;
991 section_ptr_add(pe
->reloc
, sizeof(struct pe_reloc_header
));
992 offset
= addr
& 0xFFFFFFFF<<12;
994 if ((addr
-= offset
) < (1<<12)) { /* one block spans 4k addresses */
995 WORD
*wp
= section_ptr_add(pe
->reloc
, sizeof (WORD
));
996 *wp
= addr
| IMAGE_REL_BASED_HIGHLOW
<<12;
1002 } else if (i
< pe
->sec_count
) {
1003 sr
= (s
= pe
->s1
->sections
[pe
->sec_info
[i
++].ord
])->reloc
;
1005 rel
= (ElfW_Rel
*)sr
->data
;
1006 rel_end
= (ElfW_Rel
*)(sr
->data
+ sr
->data_offset
);
1012 /* store the last block and ready for a new one */
1013 struct pe_reloc_header
*hdr
;
1014 if (count
& 1) /* align for DWORDS */
1015 section_ptr_add(pe
->reloc
, sizeof(WORD
)), ++count
;
1016 hdr
= (struct pe_reloc_header
*)(pe
->reloc
->data
+ block_ptr
);
1017 hdr
-> offset
= offset
- pe
->imagebase
;
1018 hdr
-> size
= count
* sizeof(WORD
) + sizeof(struct pe_reloc_header
);
1027 /* ------------------------------------------------------------- */
1028 static int pe_section_class(Section
*s
)
1034 flags
= s
->sh_flags
;
1036 if (flags
& SHF_ALLOC
) {
1037 if (type
== SHT_PROGBITS
) {
1038 if (flags
& SHF_EXECINSTR
)
1040 if (flags
& SHF_WRITE
)
1042 if (0 == strcmp(name
, ".rsrc"))
1044 if (0 == strcmp(name
, ".iedat"))
1046 if (0 == strcmp(name
, ".pdata"))
1049 } else if (type
== SHT_NOBITS
) {
1050 if (flags
& SHF_WRITE
)
1054 if (0 == strcmp(name
, ".reloc"))
1056 if (0 == strncmp(name
, ".stab", 5)) /* .stab and .stabstr */
1062 static int pe_assign_addresses (struct pe_info
*pe
)
1067 struct section_info
*si
;
1070 // pe->thunk = new_section(pe->s1, ".iedat", SHT_PROGBITS, SHF_ALLOC);
1072 section_order
= tcc_malloc(pe
->s1
->nb_sections
* sizeof (int));
1073 for (o
= k
= 0 ; k
< sec_last
; ++k
) {
1074 for (i
= 1; i
< pe
->s1
->nb_sections
; ++i
) {
1075 s
= pe
->s1
->sections
[i
];
1076 if (k
== pe_section_class(s
)) {
1077 // printf("%s %d\n", s->name, k);
1078 s
->sh_addr
= pe
->imagebase
;
1079 section_order
[o
++] = i
;
1084 pe
->sec_info
= tcc_mallocz(o
* sizeof (struct section_info
));
1085 addr
= pe
->imagebase
+ 1;
1087 for (i
= 0; i
< o
; ++i
)
1089 k
= section_order
[i
];
1090 s
= pe
->s1
->sections
[k
];
1091 c
= pe_section_class(s
);
1092 si
= &pe
->sec_info
[pe
->sec_count
];
1094 #ifdef PE_MERGE_DATA
1095 if (c
== sec_bss
&& pe
->sec_count
&& si
[-1].cls
== sec_data
) {
1096 /* append .bss to .data */
1097 s
->sh_addr
= addr
= ((addr
-1) | (s
->sh_addralign
-1)) + 1;
1098 addr
+= s
->data_offset
;
1099 si
[-1].sh_size
= addr
- si
[-1].sh_addr
;
1103 strcpy(si
->name
, s
->name
);
1106 si
->sh_addr
= s
->sh_addr
= addr
= pe_virtual_align(pe
, addr
);
1107 si
->sh_flags
= s
->sh_flags
;
1109 if (c
== sec_data
&& NULL
== pe
->thunk
)
1112 if (s
== pe
->thunk
) {
1113 pe_build_imports(pe
);
1114 pe_build_exports(pe
);
1118 pe_build_reloc (pe
);
1122 if (s
->sh_type
!= SHT_NOBITS
) {
1124 si
->data_size
= s
->data_offset
;
1127 addr
+= s
->data_offset
;
1128 si
->sh_size
= s
->data_offset
;
1131 // printf("%08x %05x %s\n", si->sh_addr, si->sh_size, si->name);
1135 for (i
= 1; i
< pe
->s1
->nb_sections
; ++i
) {
1136 Section
*s
= pe
->s1
->sections
[i
];
1137 int type
= s
->sh_type
;
1138 int flags
= s
->sh_flags
;
1139 printf("section %-16s %-10s %5x %s,%s,%s\n",
1141 type
== SHT_PROGBITS
? "progbits" :
1142 type
== SHT_NOBITS
? "nobits" :
1143 type
== SHT_SYMTAB
? "symtab" :
1144 type
== SHT_STRTAB
? "strtab" :
1145 type
== SHT_RELX
? "rel" : "???",
1147 flags
& SHF_ALLOC
? "alloc" : "",
1148 flags
& SHF_WRITE
? "write" : "",
1149 flags
& SHF_EXECINSTR
? "exec" : ""
1152 pe
->s1
->verbose
= 2;
1155 tcc_free(section_order
);
1159 /* ------------------------------------------------------------- */
1160 static void pe_relocate_rva (struct pe_info
*pe
, Section
*s
)
1162 Section
*sr
= s
->reloc
;
1163 ElfW_Rel
*rel
, *rel_end
;
1164 rel_end
= (ElfW_Rel
*)(sr
->data
+ sr
->data_offset
);
1165 for(rel
= (ElfW_Rel
*)sr
->data
; rel
< rel_end
; rel
++) {
1166 if (ELFW_R_(TYPE
)(rel
->r_info
) == R_XXX_RELATIVE
) {
1167 int sym_index
= ELFW_R_(SYM
)(rel
->r_info
);
1168 DWORD addr
= s
->sh_addr
;
1170 ElfW(Sym
) *sym
= (ElfW(Sym
) *)symtab_section
->data
+ sym_index
;
1171 addr
= sym
->st_value
;
1173 // printf("reloc rva %08x %08x %s\n", (DWORD)rel->r_offset, addr, s->name);
1174 *(DWORD
*)(s
->data
+ rel
->r_offset
) += addr
- pe
->imagebase
;
1179 /*----------------------------------------------------------------------------*/
1181 static int pe_isafunc(int sym_index
)
1183 Section
*sr
= text_section
->reloc
;
1184 ElfW_Rel
*rel
, *rel_end
;
1185 Elf32_Word info
= ELF32_R_INFO(sym_index
, R_386_PC32
);
1188 rel_end
= (ElfW_Rel
*)(sr
->data
+ sr
->data_offset
);
1189 for (rel
= (ElfW_Rel
*)sr
->data
; rel
< rel_end
; rel
++)
1190 if (rel
->r_info
== info
)
1195 /*----------------------------------------------------------------------------*/
1196 static int pe_check_symbols(struct pe_info
*pe
)
1199 int sym_index
, sym_end
;
1202 pe_align_section(text_section
, 8);
1204 sym_end
= symtab_section
->data_offset
/ sizeof(ElfW(Sym
));
1205 for (sym_index
= 1; sym_index
< sym_end
; ++sym_index
) {
1207 sym
= (ElfW(Sym
) *)symtab_section
->data
+ sym_index
;
1208 if (sym
->st_shndx
== SHN_UNDEF
) {
1210 const char *name
= symtab_section
->link
->data
+ sym
->st_name
;
1211 unsigned type
= ELFW_ST_TYPE(sym
->st_info
);
1212 int imp_sym
= pe_find_import(pe
->s1
, name
);
1213 struct import_symbol
*is
;
1217 is
= pe_add_import(pe
, imp_sym
);
1221 if (type
== STT_NOTYPE
) {
1222 /* symbols from assembler have no type, find out which */
1223 if (pe_isafunc(sym_index
))
1229 if (type
== STT_FUNC
) {
1230 unsigned long offset
= is
->thk_offset
;
1232 /* got aliased symbol, like stricmp and _stricmp */
1238 offset
= text_section
->data_offset
;
1239 /* add the 'jmp IAT[x]' instruction */
1240 p
= section_ptr_add(text_section
, 8);
1242 #ifdef TCC_TARGET_X86_64
1243 *(DWORD
*)(p
+1) = (DWORD
)-4;
1245 /* add a helper symbol, will be patched later in
1247 sprintf(buffer
, "IAT.%s", name
);
1248 is
->iat_index
= put_elf_sym(
1249 symtab_section
, 0, sizeof(DWORD
),
1250 ELFW_ST_INFO(STB_GLOBAL
, STT_OBJECT
),
1251 0, SHN_UNDEF
, buffer
);
1252 put_elf_reloc(symtab_section
, text_section
,
1253 offset
+ 2, R_XXX_THUNKFIX
, is
->iat_index
);
1254 is
->thk_offset
= offset
;
1257 /* tcc_realloc might have altered sym's address */
1258 sym
= (ElfW(Sym
) *)symtab_section
->data
+ sym_index
;
1260 /* patch the original symbol */
1261 sym
->st_value
= offset
;
1262 sym
->st_shndx
= text_section
->sh_num
;
1263 sym
->st_other
&= ~1; /* do not export */
1267 if (type
== STT_OBJECT
) { /* data, ptr to that should be */
1268 if (0 == is
->iat_index
) {
1269 /* original symbol will be patched later in pe_build_imports */
1270 is
->iat_index
= sym_index
;
1276 error_noabort("undefined symbol '%s'", name
);
1279 } else if (pe
->s1
->rdynamic
1280 && ELFW_ST_BIND(sym
->st_info
) != STB_LOCAL
) {
1281 /* if -rdynamic option, then export all non local symbols */
1288 /*----------------------------------------------------------------------------*/
1289 #ifdef PE_PRINT_SECTIONS
1290 static void pe_print_section(FILE * f
, Section
* s
)
1292 /* just if you'r curious */
1296 e
= s
->data
+ s
->data_offset
;
1299 fprintf(f
, "section \"%s\"", s
->name
);
1301 fprintf(f
, "\nlink \"%s\"", s
->link
->name
);
1303 fprintf(f
, "\nreloc \"%s\"", s
->reloc
->name
);
1304 fprintf(f
, "\nv_addr %08X", (unsigned)s
->sh_addr
);
1305 fprintf(f
, "\ncontents %08X", (unsigned)l
);
1308 if (s
->sh_type
== SHT_NOBITS
)
1314 if (s
->sh_type
== SHT_SYMTAB
)
1315 m
= sizeof(ElfW(Sym
));
1316 else if (s
->sh_type
== SHT_RELX
)
1317 m
= sizeof(ElfW_Rel
);
1321 fprintf(f
, "%-8s", "offset");
1322 for (i
= 0; i
< m
; ++i
)
1323 fprintf(f
, " %02x", i
);
1326 if (s
->sh_type
== SHT_SYMTAB
|| s
->sh_type
== SHT_RELX
) {
1327 const char *fields1
[] = {
1338 const char *fields2
[] = {
1347 if (s
->sh_type
== SHT_SYMTAB
)
1348 p
= fields1
, n
= 106;
1350 p
= fields2
, n
= 58;
1352 for (i
= 0; p
[i
]; ++i
)
1353 fprintf(f
, "%6s", p
[i
]);
1354 fprintf(f
, " symbol");
1358 for (i
= 0; i
< n
; ++i
)
1364 fprintf(f
, "%08X", i
);
1365 for (n
= 0; n
< m
; ++n
) {
1367 fprintf(f
, " %02X", p
[i
+ n
]);
1372 if (s
->sh_type
== SHT_SYMTAB
) {
1373 ElfW(Sym
) *sym
= (ElfW(Sym
) *) (p
+ i
);
1374 const char *name
= s
->link
->data
+ sym
->st_name
;
1375 fprintf(f
, " %04X %04X %04X %02X %02X %02X %04X \"%s\"",
1376 (unsigned)sym
->st_name
,
1377 (unsigned)sym
->st_value
,
1378 (unsigned)sym
->st_size
,
1379 (unsigned)ELFW_ST_BIND(sym
->st_info
),
1380 (unsigned)ELFW_ST_TYPE(sym
->st_info
),
1381 (unsigned)sym
->st_other
,
1382 (unsigned)sym
->st_shndx
,
1385 } else if (s
->sh_type
== SHT_RELX
) {
1386 ElfW_Rel
*rel
= (ElfW_Rel
*) (p
+ i
);
1388 (ElfW(Sym
) *) s
->link
->data
+ ELFW_R_(SYM
)(rel
->r_info
);
1389 const char *name
= s
->link
->link
->data
+ sym
->st_name
;
1390 fprintf(f
, " %04X %02X %04X \"%s\"",
1391 (unsigned)rel
->r_offset
,
1392 (unsigned)ELFW_R_(TYPE
)(rel
->r_info
),
1393 (unsigned)ELFW_R_(SYM
)(rel
->r_info
),
1397 for (n
= 0; n
< m
; ++n
) {
1400 if (b
< 32 || b
>= 127)
1402 fprintf(f
, "%c", b
);
1412 static void pe_print_sections(TCCState
*s1
, const char *fname
)
1417 f
= fopen(fname
, "w");
1418 for (i
= 1; i
< s1
->nb_sections
; ++i
) {
1419 s
= s1
->sections
[i
];
1420 pe_print_section(f
, s
);
1422 pe_print_section(f
, s1
->dynsymtab_section
);
1427 /* ------------------------------------------------------------- */
1429 static int read_mem(FILE *fp
, unsigned offset
, void *buffer
, unsigned len
)
1431 fseek(fp
, offset
, 0);
1432 return len
== fread(buffer
, 1, len
, fp
);
1435 /* -------------------------------------------------------------
1436 * This is for compiled windows resources in 'coff' format
1437 * as generated by 'windres.exe -O coff ...'.
1440 static int pe_load_res(TCCState
*s1
, FILE *fp
)
1442 struct pe_rsrc_header hdr
;
1443 Section
*rsrc_section
;
1448 if (!read_mem(fp
, 0, &hdr
, sizeof hdr
))
1451 if (hdr
.filehdr
.Machine
!= 0x014C
1452 || hdr
.filehdr
.NumberOfSections
!= 1
1453 || strcmp(hdr
.sectionhdr
.Name
, ".rsrc") != 0)
1456 rsrc_section
= new_section(s1
, ".rsrc", SHT_PROGBITS
, SHF_ALLOC
);
1457 ptr
= section_ptr_add(rsrc_section
, hdr
.sectionhdr
.SizeOfRawData
);
1458 offs
= hdr
.sectionhdr
.PointerToRawData
;
1459 if (!read_mem(fp
, offs
, ptr
, hdr
.sectionhdr
.SizeOfRawData
))
1461 offs
= hdr
.sectionhdr
.PointerToRelocations
;
1462 for (i
= 0; i
< hdr
.sectionhdr
.NumberOfRelocations
; ++i
)
1464 struct pe_rsrc_reloc rel
;
1465 if (!read_mem(fp
, offs
, &rel
, sizeof rel
))
1467 // printf("rsrc_reloc: %x %x %x\n", rel.offset, rel.size, rel.type);
1468 if (rel
.type
!= 7) /* DIR32NB */
1470 put_elf_reloc(symtab_section
, rsrc_section
,
1471 rel
.offset
, R_XXX_RELATIVE
, 0);
1479 /* ------------------------------------------------------------- */
1480 static char *trimfront(char *p
)
1482 while (*p
&& (unsigned char)*p
<= ' ')
1487 static char *trimback(char *a
, char *e
)
1489 while (e
> a
&& (unsigned char)e
[-1] <= ' ')
1495 static char *get_line(char *line
, int size
, FILE *fp
)
1497 if (NULL
== fgets(line
, size
, fp
))
1499 trimback(line
, strchr(line
, 0));
1500 return trimfront(line
);
1503 /* ------------------------------------------------------------- */
1504 static int pe_load_def(TCCState
*s1
, FILE *fp
)
1506 DLLReference
*dllref
;
1507 int state
= 0, ret
= -1;
1508 char line
[400], dllname
[80], *p
;
1511 p
= get_line(line
, sizeof line
, fp
);
1514 if (0 == *p
|| ';' == *p
)
1518 if (0 != strnicmp(p
, "LIBRARY", 7))
1520 strcpy(dllname
, trimfront(p
+7));
1525 if (0 != stricmp(p
, "EXPORTS"))
1531 dllref
= tcc_mallocz(sizeof(DLLReference
) + strlen(dllname
));
1532 strcpy(dllref
->name
, dllname
);
1533 dynarray_add((void ***) &s1
->loaded_dlls
, &s1
->nb_loaded_dlls
, dllref
);
1537 add_elf_sym(s1
->dynsymtab_section
,
1538 s1
->nb_loaded_dlls
, 0,
1539 ELFW_ST_INFO(STB_GLOBAL
, STT_FUNC
), 0,
1540 text_section
->sh_num
, p
);
1549 /* ------------------------------------------------------------- */
1550 #define TINY_IMPDEF_GET_EXPORT_NAMES_ONLY
1551 #include "win32/tools/tiny_impdef.c"
1553 static int pe_load_dll(TCCState
*s1
, const char *dllname
, FILE *fp
)
1557 p
= get_export_names(fp
);
1559 DLLReference
*dllref
;
1560 dllref
= tcc_mallocz(sizeof(DLLReference
) + strlen(dllname
));
1561 strcpy(dllref
->name
, dllname
);
1562 dynarray_add((void ***) &s1
->loaded_dlls
, &s1
->nb_loaded_dlls
, dllref
);
1563 for (q
= p
, i
= 0; *q
; ++i
) {
1564 add_elf_sym(s1
->dynsymtab_section
,
1565 s1
->nb_loaded_dlls
, 0,
1566 ELFW_ST_INFO(STB_GLOBAL
, STT_FUNC
), 0,
1567 text_section
->sh_num
, q
);
1575 /* ------------------------------------------------------------- */
1576 ST_FUNC
int pe_load_file(struct TCCState
*s1
, const char *filename
, int fd
)
1578 FILE *fp
= fdopen(dup(fd
), "rb");
1582 if (0 == strcmp(tcc_fileextension(filename
), ".def"))
1583 ret
= pe_load_def(s1
, fp
);
1584 else if (pe_load_res(s1
, fp
) == 0)
1586 else if (read_mem(fp
, 0, buf
, sizeof buf
) && 0 == strncmp(buf
, "MZ", 2))
1587 ret
= pe_load_dll(s1
, tcc_basename(filename
), fp
);
1593 ST_FUNC
int pe_add_dll(struct TCCState
*s
, const char *libname
)
1595 static const char *pat
[] = {
1596 "%s.def", "lib%s.def", "%s.dll", "lib%s.dll", NULL
1598 const char **p
= pat
;
1601 snprintf(buf
, sizeof(buf
), *p
, libname
);
1602 if (tcc_add_dll(s
, buf
, 0) == 0)
1608 /* ------------------------------------------------------------- */
1609 /* helper function for load/store to insert one more indirection */
1611 ST_FUNC
int pe_dllimport(int r
, SValue
*sv
, void (*fn
)(int r
, SValue
*sv
))
1614 if ((sv
->r
& (VT_VALMASK
|VT_SYM
|VT_CONST
)) != (VT_SYM
|VT_CONST
))
1616 t
= sv
->sym
->type
.t
;
1617 if (0 == (t
& VT_IMPORT
))
1620 sv
->sym
->type
.t
= t
& ~VT_IMPORT
;
1621 //printf("import %x %04x %s\n", t, ind, get_tok_str(sv->sym->v, NULL));
1624 vtop
->type
.t
&= ~(VT_ARRAY
|VT_IMPORT
);
1625 mk_pointer(&vtop
->type
);
1630 sv
->sym
->type
.t
= t
;
1634 /* ------------------------------------------------------------- */
1635 #ifdef TCC_TARGET_X86_64
1636 ST_FUNC
void pe_add_unwind_data(unsigned start
, unsigned end
, unsigned stack
)
1638 static const char uw_info
[] = {
1639 0x01, // UBYTE: 3 Version , UBYTE: 5 Flags
1640 0x04, // UBYTE Size of prolog
1641 0x02, // UBYTE Count of unwind codes
1642 0x05, // UBYTE: 4 Frame Register (rbp), UBYTE: 4 Frame Register offset (scaled)
1643 // USHORT * n Unwind codes array
1644 // 0x0b, 0x01, 0xff, 0xff, // stack size
1645 0x04, 0x03, // set frame ptr (mov rsp -> rbp)
1646 0x01, 0x50 // push reg (rbp)
1649 struct pe_uw
*pe_uw
= &tcc_state
->pe_unwind
;
1660 pe_uw
->pdata
= pd
= find_section(tcc_state
, ".pdata");
1661 pe_uw
->pdata
->sh_addralign
= 4;
1662 section_ptr_add(uw
, -uw
->data_offset
& 3);
1663 pe_uw
->offs_1
= uw
->data_offset
;
1664 p1
= section_ptr_add(uw
, sizeof uw_info
);
1665 /* use one common entry for all functions */
1666 memcpy(p1
, uw_info
, sizeof uw_info
);
1667 pe_uw
->sym_1
= put_elf_sym(symtab_section
, 0, 0, 0, 0, text_section
->sh_num
, NULL
);
1668 pe_uw
->sym_2
= put_elf_sym(symtab_section
, 0, 0, 0, 0, uw
->sh_num
, NULL
);
1671 o2
= pd
->data_offset
;
1672 p2
= section_ptr_add(pd
, 3 * sizeof (DWORD
));
1673 /* record this function */
1676 p2
[2] = pe_uw
->offs_1
;
1677 /* put relocations on it */
1678 put_elf_reloc(symtab_section
, pd
, o2
, R_X86_64_RELATIVE
, pe_uw
->sym_1
);
1679 put_elf_reloc(symtab_section
, pd
, o2
+4, R_X86_64_RELATIVE
, pe_uw
->sym_1
);
1680 put_elf_reloc(symtab_section
, pd
, o2
+8, R_X86_64_RELATIVE
, pe_uw
->sym_2
);
1684 /* ------------------------------------------------------------- */
1685 #ifdef TCC_TARGET_X86_64
1686 #define PE_STDSYM(n,s) n
1688 #define PE_STDSYM(n,s) "_" n s
1691 static void pe_add_runtime_ex(TCCState
*s1
, struct pe_info
*pe
)
1693 const char *start_symbol
;
1694 unsigned long addr
= 0;
1697 if (find_elf_sym(symtab_section
, PE_STDSYM("WinMain","@16")))
1700 if (TCC_OUTPUT_DLL
== s1
->output_type
) {
1702 /* need this for 'tccelf.c:relocate_section()' */
1703 s1
->output_type
= TCC_OUTPUT_EXE
;
1707 TCC_OUTPUT_MEMORY
== s1
->output_type
1708 ? PE_GUI
== pe_type
? "_runwinmain" : NULL
1709 : PE_DLL
== pe_type
? PE_STDSYM("_dllstart","@12")
1710 : PE_GUI
== pe_type
? "_winstart" : "_start"
1713 /* grab the startup code from libtcc1 */
1715 add_elf_sym(symtab_section
,
1717 ELFW_ST_INFO(STB_GLOBAL
, STT_NOTYPE
), 0,
1718 SHN_UNDEF
, start_symbol
);
1720 if (0 == s1
->nostdlib
) {
1721 static const char *libs
[] = {
1722 "tcc1", "msvcrt", "kernel32", "", "user32", "gdi32", NULL
1724 const char **pp
, *p
;
1725 for (pp
= libs
; 0 != (p
= *pp
); ++pp
) {
1727 if (PE_DLL
!= pe_type
&& PE_GUI
!= pe_type
)
1729 } else if (tcc_add_library(s1
, p
) < 0)
1730 error_noabort("cannot find library: %s", p
);
1735 addr
= (uplong
)tcc_get_symbol_err(s1
, start_symbol
);
1736 if (s1
->output_type
== TCC_OUTPUT_MEMORY
&& addr
)
1737 /* for -run GUI's, put '_runwinmain' instead of 'main' */
1738 add_elf_sym(symtab_section
,
1740 ELFW_ST_INFO(STB_GLOBAL
, STT_NOTYPE
), 0,
1741 text_section
->sh_num
, "main");
1745 pe
->start_addr
= addr
;
1748 ST_FUNC
int pe_output_file(TCCState
* s1
, const char *filename
)
1754 memset(&pe
, 0, sizeof pe
);
1755 pe
.filename
= filename
;
1759 pe_add_runtime_ex(s1
, &pe
);
1760 relocate_common_syms(); /* assign bss adresses */
1761 tcc_add_linker_symbols(s1
);
1763 ret
= pe_check_symbols(&pe
);
1766 else if (filename
) {
1767 if (PE_DLL
== pe
.type
) {
1768 pe
.reloc
= new_section(pe
.s1
, ".reloc", SHT_PROGBITS
, 0);
1769 /* XXX: check if is correct for arm-pe target */
1770 pe
.imagebase
= 0x10000000;
1772 #if defined(TCC_TARGET_ARM)
1773 pe
.imagebase
= 0x00010000;
1775 pe
.imagebase
= 0x00400000;
1779 /* if no subsystem specified, we use "console" subsystem by default */
1780 if (s1
->pe_subsystem
!= 0)
1781 pe
.subsystem
= s1
->pe_subsystem
;
1783 #if defined(TCC_TARGET_ARM)
1788 /* set default file/section alignment */
1789 if (pe
.subsystem
== 1) {
1790 pe
.section_align
= 0x20;
1791 pe
.file_align
= 0x20;
1793 pe
.section_align
= 0x1000;
1794 pe
.file_align
= 0x200;
1797 if (s1
->section_align
!= 0)
1798 pe
.section_align
= s1
->section_align
;
1799 if (s1
->pe_file_align
!= 0)
1800 pe
.file_align
= s1
->pe_file_align
;
1802 if ((pe
.subsystem
>= 10) && (pe
.subsystem
<= 12))
1805 if (s1
->has_text_addr
)
1806 pe
.imagebase
= s1
->text_addr
;
1808 pe_assign_addresses(&pe
);
1809 relocate_syms(s1
, 0);
1810 for (i
= 1; i
< s1
->nb_sections
; ++i
) {
1811 Section
*s
= s1
->sections
[i
];
1813 relocate_section(s1
, s
);
1814 pe_relocate_rva(&pe
, s
);
1820 ret
= pe_write(&pe
);
1821 tcc_free(pe
.sec_info
);
1823 #ifndef TCC_IS_NATIVE
1824 error_noabort("-run supported only on native platform");
1827 pe
.thunk
= data_section
;
1828 pe_build_imports(&pe
);
1831 #ifdef PE_PRINT_SECTIONS
1832 pe_print_sections(s1
, "tcc.log");
1837 /* ------------------------------------------------------------- */