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 PE_PRINT_SECTIONS */
27 #define stricmp strcasecmp
28 #define strnicmp strncasecmp
29 #include <sys/stat.h> /* chmod() */
32 #ifdef TCC_TARGET_X86_64
33 # define ADDR3264 ULONGLONG
34 # define PE_IMAGE_REL IMAGE_REL_BASED_DIR64
35 # define REL_TYPE_DIRECT R_X86_64_64
36 # define R_XXX_THUNKFIX R_X86_64_PC32
37 # define R_XXX_RELATIVE R_X86_64_RELATIVE
38 # define IMAGE_FILE_MACHINE 0x8664
39 # define RSRC_RELTYPE 3
41 #elif defined TCC_TARGET_ARM
42 # define ADDR3264 DWORD
43 # define PE_IMAGE_REL IMAGE_REL_BASED_HIGHLOW
44 # define REL_TYPE_DIRECT R_ARM_ABS32
45 # define R_XXX_THUNKFIX R_ARM_ABS32
46 # define R_XXX_RELATIVE R_ARM_RELATIVE
47 # define IMAGE_FILE_MACHINE 0x01C0
48 # define RSRC_RELTYPE 7 /* ??? (not tested) */
50 #elif defined TCC_TARGET_I386
51 # define ADDR3264 DWORD
52 # define PE_IMAGE_REL IMAGE_REL_BASED_HIGHLOW
53 # define REL_TYPE_DIRECT R_386_32
54 # define R_XXX_THUNKFIX R_386_32
55 # define R_XXX_RELATIVE R_386_RELATIVE
56 # define IMAGE_FILE_MACHINE 0x014C
57 # define RSRC_RELTYPE 7 /* DIR32NB */
61 #ifndef IMAGE_NT_SIGNATURE
62 /* ----------------------------------------------------------- */
63 /* definitions below are from winnt.h */
65 typedef unsigned char BYTE
;
66 typedef unsigned short WORD
;
67 typedef unsigned int DWORD
;
68 typedef unsigned long long ULONGLONG
;
71 typedef struct _IMAGE_DOS_HEADER
{ /* DOS .EXE header */
72 WORD e_magic
; /* Magic number */
73 WORD e_cblp
; /* Bytes on last page of file */
74 WORD e_cp
; /* Pages in file */
75 WORD e_crlc
; /* Relocations */
76 WORD e_cparhdr
; /* Size of header in paragraphs */
77 WORD e_minalloc
; /* Minimum extra paragraphs needed */
78 WORD e_maxalloc
; /* Maximum extra paragraphs needed */
79 WORD e_ss
; /* Initial (relative) SS value */
80 WORD e_sp
; /* Initial SP value */
81 WORD e_csum
; /* Checksum */
82 WORD e_ip
; /* Initial IP value */
83 WORD e_cs
; /* Initial (relative) CS value */
84 WORD e_lfarlc
; /* File address of relocation table */
85 WORD e_ovno
; /* Overlay number */
86 WORD e_res
[4]; /* Reserved words */
87 WORD e_oemid
; /* OEM identifier (for e_oeminfo) */
88 WORD e_oeminfo
; /* OEM information; e_oemid specific */
89 WORD e_res2
[10]; /* Reserved words */
90 DWORD e_lfanew
; /* File address of new exe header */
91 } IMAGE_DOS_HEADER
, *PIMAGE_DOS_HEADER
;
93 #define IMAGE_NT_SIGNATURE 0x00004550 /* PE00 */
94 #define SIZE_OF_NT_SIGNATURE 4
96 typedef struct _IMAGE_FILE_HEADER
{
98 WORD NumberOfSections
;
100 DWORD PointerToSymbolTable
;
101 DWORD NumberOfSymbols
;
102 WORD SizeOfOptionalHeader
;
103 WORD Characteristics
;
104 } IMAGE_FILE_HEADER
, *PIMAGE_FILE_HEADER
;
107 #define IMAGE_SIZEOF_FILE_HEADER 20
109 typedef struct _IMAGE_DATA_DIRECTORY
{
110 DWORD VirtualAddress
;
112 } IMAGE_DATA_DIRECTORY
, *PIMAGE_DATA_DIRECTORY
;
115 typedef struct _IMAGE_OPTIONAL_HEADER
{
116 /* Standard fields. */
118 BYTE MajorLinkerVersion
;
119 BYTE MinorLinkerVersion
;
121 DWORD SizeOfInitializedData
;
122 DWORD SizeOfUninitializedData
;
123 DWORD AddressOfEntryPoint
;
125 #ifndef TCC_TARGET_X86_64
128 /* NT additional fields. */
130 DWORD SectionAlignment
;
132 WORD MajorOperatingSystemVersion
;
133 WORD MinorOperatingSystemVersion
;
134 WORD MajorImageVersion
;
135 WORD MinorImageVersion
;
136 WORD MajorSubsystemVersion
;
137 WORD MinorSubsystemVersion
;
138 DWORD Win32VersionValue
;
143 WORD DllCharacteristics
;
144 ADDR3264 SizeOfStackReserve
;
145 ADDR3264 SizeOfStackCommit
;
146 ADDR3264 SizeOfHeapReserve
;
147 ADDR3264 SizeOfHeapCommit
;
149 DWORD NumberOfRvaAndSizes
;
150 IMAGE_DATA_DIRECTORY DataDirectory
[16];
151 } IMAGE_OPTIONAL_HEADER32
, IMAGE_OPTIONAL_HEADER64
, IMAGE_OPTIONAL_HEADER
;
153 #define IMAGE_DIRECTORY_ENTRY_EXPORT 0 /* Export Directory */
154 #define IMAGE_DIRECTORY_ENTRY_IMPORT 1 /* Import Directory */
155 #define IMAGE_DIRECTORY_ENTRY_RESOURCE 2 /* Resource Directory */
156 #define IMAGE_DIRECTORY_ENTRY_EXCEPTION 3 /* Exception Directory */
157 #define IMAGE_DIRECTORY_ENTRY_SECURITY 4 /* Security Directory */
158 #define IMAGE_DIRECTORY_ENTRY_BASERELOC 5 /* Base Relocation Table */
159 #define IMAGE_DIRECTORY_ENTRY_DEBUG 6 /* Debug Directory */
160 /* IMAGE_DIRECTORY_ENTRY_COPYRIGHT 7 (X86 usage) */
161 #define IMAGE_DIRECTORY_ENTRY_ARCHITECTURE 7 /* Architecture Specific Data */
162 #define IMAGE_DIRECTORY_ENTRY_GLOBALPTR 8 /* RVA of GP */
163 #define IMAGE_DIRECTORY_ENTRY_TLS 9 /* TLS Directory */
164 #define IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG 10 /* Load Configuration Directory */
165 #define IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT 11 /* Bound Import Directory in headers */
166 #define IMAGE_DIRECTORY_ENTRY_IAT 12 /* Import Address Table */
167 #define IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT 13 /* Delay Load Import Descriptors */
168 #define IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR 14 /* COM Runtime descriptor */
170 /* Section header format. */
171 #define IMAGE_SIZEOF_SHORT_NAME 8
173 typedef struct _IMAGE_SECTION_HEADER
{
174 BYTE Name
[IMAGE_SIZEOF_SHORT_NAME
];
176 DWORD PhysicalAddress
;
179 DWORD VirtualAddress
;
181 DWORD PointerToRawData
;
182 DWORD PointerToRelocations
;
183 DWORD PointerToLinenumbers
;
184 WORD NumberOfRelocations
;
185 WORD NumberOfLinenumbers
;
186 DWORD Characteristics
;
187 } IMAGE_SECTION_HEADER
, *PIMAGE_SECTION_HEADER
;
189 #define IMAGE_SIZEOF_SECTION_HEADER 40
191 typedef struct _IMAGE_EXPORT_DIRECTORY
{
192 DWORD Characteristics
;
198 DWORD NumberOfFunctions
;
200 DWORD AddressOfFunctions
;
201 DWORD AddressOfNames
;
202 DWORD AddressOfNameOrdinals
;
203 } IMAGE_EXPORT_DIRECTORY
,*PIMAGE_EXPORT_DIRECTORY
;
205 typedef struct _IMAGE_IMPORT_DESCRIPTOR
{
207 DWORD Characteristics
;
208 DWORD OriginalFirstThunk
;
211 DWORD ForwarderChain
;
214 } IMAGE_IMPORT_DESCRIPTOR
;
216 typedef struct _IMAGE_BASE_RELOCATION
{
217 DWORD VirtualAddress
;
219 // WORD TypeOffset[1];
220 } IMAGE_BASE_RELOCATION
;
222 #define IMAGE_SIZEOF_BASE_RELOCATION 8
224 #define IMAGE_REL_BASED_ABSOLUTE 0
225 #define IMAGE_REL_BASED_HIGH 1
226 #define IMAGE_REL_BASED_LOW 2
227 #define IMAGE_REL_BASED_HIGHLOW 3
228 #define IMAGE_REL_BASED_HIGHADJ 4
229 #define IMAGE_REL_BASED_MIPS_JMPADDR 5
230 #define IMAGE_REL_BASED_SECTION 6
231 #define IMAGE_REL_BASED_REL32 7
232 #define IMAGE_REL_BASED_DIR64 10
234 #define IMAGE_SCN_CNT_CODE 0x00000020
235 #define IMAGE_SCN_CNT_INITIALIZED_DATA 0x00000040
236 #define IMAGE_SCN_CNT_UNINITIALIZED_DATA 0x00000080
237 #define IMAGE_SCN_MEM_DISCARDABLE 0x02000000
238 #define IMAGE_SCN_MEM_SHARED 0x10000000
239 #define IMAGE_SCN_MEM_EXECUTE 0x20000000
240 #define IMAGE_SCN_MEM_READ 0x40000000
241 #define IMAGE_SCN_MEM_WRITE 0x80000000
242 #define IMAGE_SCN_TYPE_NOLOAD 0x00000002
243 #define IMAGE_SCN_LNK_REMOVE 0x00000800
247 /* ----------------------------------------------------------- */
248 #endif /* ndef IMAGE_NT_SIGNATURE */
249 /* ----------------------------------------------------------- */
251 #ifndef IMAGE_REL_BASED_DIR64
252 # define IMAGE_REL_BASED_DIR64 10
255 #pragma pack(push, 1)
258 IMAGE_DOS_HEADER doshdr
;
261 IMAGE_FILE_HEADER filehdr
;
262 #ifdef TCC_TARGET_X86_64
263 IMAGE_OPTIONAL_HEADER64 opthdr
;
266 IMAGE_OPTIONAL_HEADER32 opthdr
;
268 IMAGE_OPTIONAL_HEADER opthdr
;
273 struct pe_reloc_header
{
278 struct pe_rsrc_header
{
279 struct _IMAGE_FILE_HEADER filehdr
;
280 struct _IMAGE_SECTION_HEADER sectionhdr
;
283 struct pe_rsrc_reloc
{
290 /* ------------------------------------------------------------- */
291 /* internal temporary structures */
307 static const DWORD pe_sec_flags
[] = {
308 0x60000020, /* ".text" , */
309 0xC0000040, /* ".data" , */
310 0xC0000080, /* ".bss" , */
311 0x40000040, /* ".idata" , */
312 0x40000040, /* ".pdata" , */
313 0xE0000060, /* < other > , */
314 0x40000040, /* ".rsrc" , */
315 0x42000802, /* ".stab" , */
316 0x42000040, /* ".reloc" , */
320 struct section_info
{
328 IMAGE_SECTION_HEADER ish
;
331 struct import_symbol
{
337 struct pe_import_info
{
340 struct import_symbol
**symbols
;
347 const char *filename
;
351 const char *start_symbol
;
362 struct section_info
*sec_info
;
364 struct pe_import_info
**imp_info
;
374 /* --------------------------------------------*/
376 static const char *pe_export_name(TCCState
*s1
, ElfW(Sym
) *sym
)
378 const char *name
= (char*)symtab_section
->link
->data
+ sym
->st_name
;
379 if (s1
->leading_underscore
&& name
[0] == '_' && !(sym
->st_other
& ST_PE_STDCALL
))
384 static int pe_find_import(TCCState
* s1
, ElfW(Sym
) *sym
)
388 int sym_index
= 0, n
= 0;
392 s
= pe_export_name(s1
, sym
);
396 if (sym
->st_other
& ST_PE_STDCALL
) {
397 /* try w/0 stdcall deco (windows API convention) */
399 if (!p
|| s
[0] != '_')
401 strcpy(buffer
, s
+1)[p
-s
-1] = 0;
402 } else if (s
[0] != '_') { /* try non-ansi function */
403 buffer
[0] = '_', strcpy(buffer
+ 1, s
);
404 } else if (0 == memcmp(s
, "__imp_", 6)) { /* mingw 2.0 */
405 strcpy(buffer
, s
+ 6), a
= 1;
406 } else if (0 == memcmp(s
, "_imp__", 6)) { /* mingw 3.7 */
407 strcpy(buffer
, s
+ 6), a
= 1;
413 sym_index
= find_elf_sym(s1
->dynsymtab_section
, s
);
414 // printf("find (%d) %d %s\n", n, sym_index, s);
416 && ELFW(ST_TYPE
)(sym
->st_info
) == STT_OBJECT
417 && 0 == (sym
->st_other
& ST_PE_IMPORT
)
419 ) err
= -1, sym_index
= 0;
420 } while (0 == sym_index
&& ++n
< 2);
421 return n
== 2 ? err
: sym_index
;
424 /*----------------------------------------------------------------------------*/
426 static int dynarray_assoc(void **pp
, int n
, int key
)
429 for (i
= 0; i
< n
; ++i
, ++pp
)
430 if (key
== **(int **) pp
)
436 ST_FN DWORD
umin(DWORD a
, DWORD b
)
438 return a
< b
? a
: b
;
442 static DWORD
umax(DWORD a
, DWORD b
)
444 return a
< b
? b
: a
;
447 static DWORD
pe_file_align(struct pe_info
*pe
, DWORD n
)
449 return (n
+ (pe
->file_align
- 1)) & ~(pe
->file_align
- 1);
452 static DWORD
pe_virtual_align(struct pe_info
*pe
, DWORD n
)
454 return (n
+ (pe
->section_align
- 1)) & ~(pe
->section_align
- 1);
457 static void pe_align_section(Section
*s
, int a
)
459 int i
= s
->data_offset
& (a
-1);
461 section_ptr_add(s
, a
- i
);
464 static void pe_set_datadir(struct pe_header
*hdr
, int dir
, DWORD addr
, DWORD size
)
466 hdr
->opthdr
.DataDirectory
[dir
].VirtualAddress
= addr
;
467 hdr
->opthdr
.DataDirectory
[dir
].Size
= size
;
470 static int pe_fwrite(void *data
, unsigned len
, FILE *fp
, DWORD
*psum
)
476 for (i
= len
; i
> 0; i
-= 2) {
477 sum
+= (i
>= 2) ? *p
++ : *(BYTE
*)p
;
478 sum
= (sum
+ (sum
>> 16)) & 0xFFFF;
482 return len
== fwrite(data
, 1, len
, fp
) ? 0 : -1;
485 static void pe_fpad(FILE *fp
, DWORD new_pos
)
487 DWORD pos
= ftell(fp
);
488 while (++pos
<= new_pos
)
492 /*----------------------------------------------------------------------------*/
493 static int pe_write(struct pe_info
*pe
)
495 static const struct pe_header pe_template
= {
497 /* IMAGE_DOS_HEADER doshdr */
498 0x5A4D, /*WORD e_magic; Magic number */
499 0x0090, /*WORD e_cblp; Bytes on last page of file */
500 0x0003, /*WORD e_cp; Pages in file */
501 0x0000, /*WORD e_crlc; Relocations */
503 0x0004, /*WORD e_cparhdr; Size of header in paragraphs */
504 0x0000, /*WORD e_minalloc; Minimum extra paragraphs needed */
505 0xFFFF, /*WORD e_maxalloc; Maximum extra paragraphs needed */
506 0x0000, /*WORD e_ss; Initial (relative) SS value */
508 0x00B8, /*WORD e_sp; Initial SP value */
509 0x0000, /*WORD e_csum; Checksum */
510 0x0000, /*WORD e_ip; Initial IP value */
511 0x0000, /*WORD e_cs; Initial (relative) CS value */
512 0x0040, /*WORD e_lfarlc; File address of relocation table */
513 0x0000, /*WORD e_ovno; Overlay number */
514 {0,0,0,0}, /*WORD e_res[4]; Reserved words */
515 0x0000, /*WORD e_oemid; OEM identifier (for e_oeminfo) */
516 0x0000, /*WORD e_oeminfo; OEM information; e_oemid specific */
517 {0,0,0,0,0,0,0,0,0,0}, /*WORD e_res2[10]; Reserved words */
518 0x00000080 /*DWORD e_lfanew; File address of new exe header */
520 /* BYTE dosstub[0x40] */
521 /* 14 code bytes + "This program cannot be run in DOS mode.\r\r\n$" + 6 * 0x00 */
522 0x0e,0x1f,0xba,0x0e,0x00,0xb4,0x09,0xcd,0x21,0xb8,0x01,0x4c,0xcd,0x21,0x54,0x68,
523 0x69,0x73,0x20,0x70,0x72,0x6f,0x67,0x72,0x61,0x6d,0x20,0x63,0x61,0x6e,0x6e,0x6f,
524 0x74,0x20,0x62,0x65,0x20,0x72,0x75,0x6e,0x20,0x69,0x6e,0x20,0x44,0x4f,0x53,0x20,
525 0x6d,0x6f,0x64,0x65,0x2e,0x0d,0x0d,0x0a,0x24,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
527 0x00004550, /* DWORD nt_sig = IMAGE_NT_SIGNATURE */
529 /* IMAGE_FILE_HEADER filehdr */
530 IMAGE_FILE_MACHINE
, /*WORD Machine; */
531 0x0003, /*WORD NumberOfSections; */
532 0x00000000, /*DWORD TimeDateStamp; */
533 0x00000000, /*DWORD PointerToSymbolTable; */
534 0x00000000, /*DWORD NumberOfSymbols; */
535 #if defined(TCC_TARGET_X86_64)
536 0x00F0, /*WORD SizeOfOptionalHeader; */
537 0x022F /*WORD Characteristics; */
538 #define CHARACTERISTICS_DLL 0x222E
539 #elif defined(TCC_TARGET_I386)
540 0x00E0, /*WORD SizeOfOptionalHeader; */
541 0x030F /*WORD Characteristics; */
542 #define CHARACTERISTICS_DLL 0x230E
543 #elif defined(TCC_TARGET_ARM)
544 0x00E0, /*WORD SizeOfOptionalHeader; */
545 0x010F, /*WORD Characteristics; */
546 #define CHARACTERISTICS_DLL 0x230F
549 /* IMAGE_OPTIONAL_HEADER opthdr */
550 /* Standard fields. */
551 #ifdef TCC_TARGET_X86_64
552 0x020B, /*WORD Magic; */
554 0x010B, /*WORD Magic; */
556 0x06, /*BYTE MajorLinkerVersion; */
557 0x00, /*BYTE MinorLinkerVersion; */
558 0x00000000, /*DWORD SizeOfCode; */
559 0x00000000, /*DWORD SizeOfInitializedData; */
560 0x00000000, /*DWORD SizeOfUninitializedData; */
561 0x00000000, /*DWORD AddressOfEntryPoint; */
562 0x00000000, /*DWORD BaseOfCode; */
563 #ifndef TCC_TARGET_X86_64
564 0x00000000, /*DWORD BaseOfData; */
566 /* NT additional fields. */
567 #if defined(TCC_TARGET_ARM)
568 0x00100000, /*DWORD ImageBase; */
570 0x00400000, /*DWORD ImageBase; */
572 0x00001000, /*DWORD SectionAlignment; */
573 0x00000200, /*DWORD FileAlignment; */
574 0x0004, /*WORD MajorOperatingSystemVersion; */
575 0x0000, /*WORD MinorOperatingSystemVersion; */
576 0x0000, /*WORD MajorImageVersion; */
577 0x0000, /*WORD MinorImageVersion; */
578 0x0004, /*WORD MajorSubsystemVersion; */
579 0x0000, /*WORD MinorSubsystemVersion; */
580 0x00000000, /*DWORD Win32VersionValue; */
581 0x00000000, /*DWORD SizeOfImage; */
582 0x00000200, /*DWORD SizeOfHeaders; */
583 0x00000000, /*DWORD CheckSum; */
584 0x0002, /*WORD Subsystem; */
585 0x0000, /*WORD DllCharacteristics; */
586 0x00100000, /*DWORD SizeOfStackReserve; */
587 0x00001000, /*DWORD SizeOfStackCommit; */
588 0x00100000, /*DWORD SizeOfHeapReserve; */
589 0x00001000, /*DWORD SizeOfHeapCommit; */
590 0x00000000, /*DWORD LoaderFlags; */
591 0x00000010, /*DWORD NumberOfRvaAndSizes; */
593 /* IMAGE_DATA_DIRECTORY DataDirectory[16]; */
594 {{0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0},
595 {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}}
598 struct pe_header pe_header
= pe_template
;
602 DWORD file_offset
, sum
;
603 struct section_info
*si
;
604 IMAGE_SECTION_HEADER
*psh
;
605 TCCState
*s1
= pe
->s1
;
607 op
= fopen(pe
->filename
, "wb");
609 tcc_error_noabort("could not write '%s': %s", pe
->filename
, strerror(errno
));
613 pe
->sizeofheaders
= pe_file_align(pe
,
614 sizeof (struct pe_header
)
615 + pe
->sec_count
* sizeof (IMAGE_SECTION_HEADER
)
618 file_offset
= pe
->sizeofheaders
;
620 if (2 == pe
->s1
->verbose
)
621 printf("-------------------------------"
622 "\n virt file size section" "\n");
623 for (i
= 0; i
< pe
->sec_count
; ++i
) {
627 si
= pe
->sec_info
+ i
;
629 addr
= si
->sh_addr
- pe
->imagebase
;
633 if (2 == pe
->s1
->verbose
)
634 printf("%6x %6x %6x %s\n",
635 (unsigned)addr
, (unsigned)file_offset
, (unsigned)size
, sh_name
);
639 if (!pe_header
.opthdr
.BaseOfCode
)
640 pe_header
.opthdr
.BaseOfCode
= addr
;
644 #ifndef TCC_TARGET_X86_64
645 if (!pe_header
.opthdr
.BaseOfData
)
646 pe_header
.opthdr
.BaseOfData
= addr
;
654 pe_set_datadir(&pe_header
, IMAGE_DIRECTORY_ENTRY_BASERELOC
, addr
, size
);
658 pe_set_datadir(&pe_header
, IMAGE_DIRECTORY_ENTRY_RESOURCE
, addr
, size
);
662 pe_set_datadir(&pe_header
, IMAGE_DIRECTORY_ENTRY_EXCEPTION
, addr
, size
);
666 if (pe
->thunk
== pe
->s1
->sections
[si
->ord
]) {
668 pe_set_datadir(&pe_header
, IMAGE_DIRECTORY_ENTRY_IMPORT
,
669 pe
->imp_offs
+ addr
, pe
->imp_size
);
670 pe_set_datadir(&pe_header
, IMAGE_DIRECTORY_ENTRY_IAT
,
671 pe
->iat_offs
+ addr
, pe
->iat_size
);
674 pe_set_datadir(&pe_header
, IMAGE_DIRECTORY_ENTRY_EXPORT
,
675 pe
->exp_offs
+ addr
, pe
->exp_size
);
679 strncpy((char*)psh
->Name
, sh_name
, sizeof psh
->Name
);
681 psh
->Characteristics
= si
->pe_flags
;
682 psh
->VirtualAddress
= addr
;
683 psh
->Misc
.VirtualSize
= size
;
684 pe_header
.opthdr
.SizeOfImage
=
685 umax(pe_virtual_align(pe
, size
+ addr
), pe_header
.opthdr
.SizeOfImage
);
688 psh
->PointerToRawData
= file_offset
;
689 file_offset
= pe_file_align(pe
, file_offset
+ si
->data_size
);
690 psh
->SizeOfRawData
= file_offset
- psh
->PointerToRawData
;
691 if (si
->cls
== sec_text
)
692 pe_header
.opthdr
.SizeOfCode
+= psh
->SizeOfRawData
;
694 pe_header
.opthdr
.SizeOfInitializedData
+= psh
->SizeOfRawData
;
698 //pe_header.filehdr.TimeDateStamp = time(NULL);
699 pe_header
.filehdr
.NumberOfSections
= pe
->sec_count
;
700 pe_header
.opthdr
.AddressOfEntryPoint
= pe
->start_addr
;
701 pe_header
.opthdr
.SizeOfHeaders
= pe
->sizeofheaders
;
702 pe_header
.opthdr
.ImageBase
= pe
->imagebase
;
703 pe_header
.opthdr
.Subsystem
= pe
->subsystem
;
704 if (pe
->s1
->pe_stack_size
)
705 pe_header
.opthdr
.SizeOfStackReserve
= pe
->s1
->pe_stack_size
;
706 if (PE_DLL
== pe
->type
)
707 pe_header
.filehdr
.Characteristics
= CHARACTERISTICS_DLL
;
708 pe_header
.filehdr
.Characteristics
|= pe
->s1
->pe_characteristics
;
711 pe_fwrite(&pe_header
, sizeof pe_header
, op
, &sum
);
712 for (i
= 0; i
< pe
->sec_count
; ++i
)
713 pe_fwrite(&pe
->sec_info
[i
].ish
, sizeof(IMAGE_SECTION_HEADER
), op
, &sum
);
714 pe_fpad(op
, pe
->sizeofheaders
);
715 for (i
= 0; i
< pe
->sec_count
; ++i
) {
716 si
= pe
->sec_info
+ i
;
719 pe_fwrite(si
->data
, si
->data_size
, op
, &sum
);
720 file_offset
= psh
->PointerToRawData
+ psh
->SizeOfRawData
;
721 pe_fpad(op
, file_offset
);
725 pe_header
.opthdr
.CheckSum
= sum
+ file_offset
;
726 fseek(op
, offsetof(struct pe_header
, opthdr
.CheckSum
), SEEK_SET
);
727 pe_fwrite(&pe_header
.opthdr
.CheckSum
, sizeof pe_header
.opthdr
.CheckSum
, op
, NULL
);
730 chmod(pe
->filename
, 0777);
733 if (2 == pe
->s1
->verbose
)
734 printf("-------------------------------\n");
736 printf("<- %s (%u bytes)\n", pe
->filename
, (unsigned)file_offset
);
741 /*----------------------------------------------------------------------------*/
743 static struct import_symbol
*pe_add_import(struct pe_info
*pe
, int sym_index
)
747 struct pe_import_info
*p
;
748 struct import_symbol
*s
;
751 isym
= (ElfW(Sym
) *)pe
->s1
->dynsymtab_section
->data
+ sym_index
;
752 dll_index
= isym
->st_size
;
754 i
= dynarray_assoc ((void**)pe
->imp_info
, pe
->imp_count
, dll_index
);
759 p
= tcc_mallocz(sizeof *p
);
760 p
->dll_index
= dll_index
;
761 dynarray_add(&pe
->imp_info
, &pe
->imp_count
, p
);
764 i
= dynarray_assoc ((void**)p
->symbols
, p
->sym_count
, sym_index
);
766 return p
->symbols
[i
];
768 s
= tcc_mallocz(sizeof *s
);
769 dynarray_add(&p
->symbols
, &p
->sym_count
, s
);
770 s
->sym_index
= sym_index
;
774 void pe_free_imports(struct pe_info
*pe
)
777 for (i
= 0; i
< pe
->imp_count
; ++i
) {
778 struct pe_import_info
*p
= pe
->imp_info
[i
];
779 dynarray_reset(&p
->symbols
, &p
->sym_count
);
781 dynarray_reset(&pe
->imp_info
, &pe
->imp_count
);
784 /*----------------------------------------------------------------------------*/
785 static void pe_build_imports(struct pe_info
*pe
)
787 int thk_ptr
, ent_ptr
, dll_ptr
, sym_cnt
, i
;
788 DWORD rva_base
= pe
->thunk
->sh_addr
- pe
->imagebase
;
789 int ndlls
= pe
->imp_count
;
790 TCCState
*s1
= pe
->s1
;
792 for (sym_cnt
= i
= 0; i
< ndlls
; ++i
)
793 sym_cnt
+= pe
->imp_info
[i
]->sym_count
;
798 pe_align_section(pe
->thunk
, 16);
800 pe
->imp_offs
= dll_ptr
= pe
->thunk
->data_offset
;
801 pe
->imp_size
= (ndlls
+ 1) * sizeof(IMAGE_IMPORT_DESCRIPTOR
);
802 pe
->iat_offs
= dll_ptr
+ pe
->imp_size
;
803 pe
->iat_size
= (sym_cnt
+ ndlls
) * sizeof(ADDR3264
);
804 section_ptr_add(pe
->thunk
, pe
->imp_size
+ 2*pe
->iat_size
);
806 thk_ptr
= pe
->iat_offs
;
807 ent_ptr
= pe
->iat_offs
+ pe
->iat_size
;
809 for (i
= 0; i
< pe
->imp_count
; ++i
) {
810 IMAGE_IMPORT_DESCRIPTOR
*hdr
;
813 struct pe_import_info
*p
= pe
->imp_info
[i
];
815 DLLReference
*dllref
;
817 dllindex
= p
->dll_index
;
819 name
= (dllref
= pe
->s1
->loaded_dlls
[dllindex
-1])->name
;
821 name
= "", dllref
= NULL
;
823 /* put the dll name into the import header */
824 v
= put_elf_str(pe
->thunk
, name
);
825 hdr
= (IMAGE_IMPORT_DESCRIPTOR
*)(pe
->thunk
->data
+ dll_ptr
);
826 hdr
->FirstThunk
= thk_ptr
+ rva_base
;
827 hdr
->OriginalFirstThunk
= ent_ptr
+ rva_base
;
828 hdr
->Name
= v
+ rva_base
;
830 for (k
= 0, n
= p
->sym_count
; k
<= n
; ++k
) {
832 int iat_index
= p
->symbols
[k
]->iat_index
;
833 int sym_index
= p
->symbols
[k
]->sym_index
;
834 ElfW(Sym
) *imp_sym
= (ElfW(Sym
) *)pe
->s1
->dynsymtab_section
->data
+ sym_index
;
835 ElfW(Sym
) *org_sym
= (ElfW(Sym
) *)symtab_section
->data
+ iat_index
;
836 const char *name
= (char*)pe
->s1
->dynsymtab_section
->link
->data
+ imp_sym
->st_name
;
839 org_sym
->st_value
= thk_ptr
;
840 org_sym
->st_shndx
= pe
->thunk
->sh_num
;
843 v
= 0, ordinal
= imp_sym
->st_value
; /* ordinal from pe_load_def */
845 ordinal
= 0, v
= imp_sym
->st_value
; /* address from tcc_add_symbol() */
848 if (pe
->type
== PE_RUN
) {
850 if ( !dllref
->handle
)
851 dllref
->handle
= LoadLibrary(dllref
->name
);
852 v
= (ADDR3264
)GetProcAddress(dllref
->handle
, ordinal
?(char*)0+ordinal
:name
);
855 tcc_error_noabort("can't build symbol '%s'", name
);
859 v
= ordinal
| (ADDR3264
)1 << (sizeof(ADDR3264
)*8 - 1);
861 v
= pe
->thunk
->data_offset
+ rva_base
;
862 section_ptr_add(pe
->thunk
, sizeof(WORD
)); /* hint, not used */
863 put_elf_str(pe
->thunk
, name
);
867 v
= 0; /* last entry is zero */
870 *(ADDR3264
*)(pe
->thunk
->data
+thk_ptr
) =
871 *(ADDR3264
*)(pe
->thunk
->data
+ent_ptr
) = v
;
872 thk_ptr
+= sizeof (ADDR3264
);
873 ent_ptr
+= sizeof (ADDR3264
);
875 dll_ptr
+= sizeof(IMAGE_IMPORT_DESCRIPTOR
);
879 /* ------------------------------------------------------------- */
887 static int sym_cmp(const void *va
, const void *vb
)
889 const char *ca
= (*(struct pe_sort_sym
**)va
)->name
;
890 const char *cb
= (*(struct pe_sort_sym
**)vb
)->name
;
891 return strcmp(ca
, cb
);
894 static void pe_build_exports(struct pe_info
*pe
)
897 int sym_index
, sym_end
;
898 DWORD rva_base
, func_o
, name_o
, ord_o
, str_o
;
899 IMAGE_EXPORT_DIRECTORY
*hdr
;
901 struct pe_sort_sym
**sorted
, *p
;
902 TCCState
*s1
= pe
->s1
;
909 rva_base
= pe
->thunk
->sh_addr
- pe
->imagebase
;
910 sym_count
= 0, sorted
= NULL
, op
= NULL
;
912 sym_end
= symtab_section
->data_offset
/ sizeof(ElfW(Sym
));
913 for (sym_index
= 1; sym_index
< sym_end
; ++sym_index
) {
914 sym
= (ElfW(Sym
)*)symtab_section
->data
+ sym_index
;
915 name
= pe_export_name(pe
->s1
, sym
);
916 if ((sym
->st_other
& ST_PE_EXPORT
)
917 /* export only symbols from actually written sections */
918 && pe
->s1
->sections
[sym
->st_shndx
]->sh_addr
) {
919 p
= tcc_malloc(sizeof *p
);
920 p
->index
= sym_index
;
922 dynarray_add(&sorted
, &sym_count
, p
);
925 if (sym
->st_other
& ST_PE_EXPORT
)
926 printf("export: %s\n", name
);
927 if (sym
->st_other
& ST_PE_STDCALL
)
928 printf("stdcall: %s\n", name
);
935 qsort (sorted
, sym_count
, sizeof *sorted
, sym_cmp
);
937 pe_align_section(pe
->thunk
, 16);
938 dllname
= tcc_basename(pe
->filename
);
940 pe
->exp_offs
= pe
->thunk
->data_offset
;
941 func_o
= pe
->exp_offs
+ sizeof(IMAGE_EXPORT_DIRECTORY
);
942 name_o
= func_o
+ sym_count
* sizeof (DWORD
);
943 ord_o
= name_o
+ sym_count
* sizeof (DWORD
);
944 str_o
= ord_o
+ sym_count
* sizeof(WORD
);
946 hdr
= section_ptr_add(pe
->thunk
, str_o
- pe
->exp_offs
);
947 hdr
->Characteristics
= 0;
949 hdr
->NumberOfFunctions
= sym_count
;
950 hdr
->NumberOfNames
= sym_count
;
951 hdr
->AddressOfFunctions
= func_o
+ rva_base
;
952 hdr
->AddressOfNames
= name_o
+ rva_base
;
953 hdr
->AddressOfNameOrdinals
= ord_o
+ rva_base
;
954 hdr
->Name
= str_o
+ rva_base
;
955 put_elf_str(pe
->thunk
, dllname
);
958 /* automatically write exports to <output-filename>.def */
959 pstrcpy(buf
, sizeof buf
, pe
->filename
);
960 strcpy(tcc_fileextension(buf
), ".def");
961 op
= fopen(buf
, "wb");
963 tcc_error_noabort("could not create '%s': %s", buf
, strerror(errno
));
965 fprintf(op
, "LIBRARY %s\n\nEXPORTS\n", dllname
);
967 printf("<- %s (%d symbol%s)\n", buf
, sym_count
, &"s"[sym_count
< 2]);
971 for (ord
= 0; ord
< sym_count
; ++ord
)
973 p
= sorted
[ord
], sym_index
= p
->index
, name
= p
->name
;
974 /* insert actual address later in relocate_section() */
975 put_elf_reloc(symtab_section
, pe
->thunk
,
976 func_o
, R_XXX_RELATIVE
, sym_index
);
977 *(DWORD
*)(pe
->thunk
->data
+ name_o
)
978 = pe
->thunk
->data_offset
+ rva_base
;
979 *(WORD
*)(pe
->thunk
->data
+ ord_o
)
981 put_elf_str(pe
->thunk
, name
);
982 func_o
+= sizeof (DWORD
);
983 name_o
+= sizeof (DWORD
);
984 ord_o
+= sizeof (WORD
);
986 fprintf(op
, "%s\n", name
);
988 pe
->exp_size
= pe
->thunk
->data_offset
- pe
->exp_offs
;
989 dynarray_reset(&sorted
, &sym_count
);
994 /* ------------------------------------------------------------- */
995 static void pe_build_reloc (struct pe_info
*pe
)
997 DWORD offset
, block_ptr
, addr
;
999 ElfW_Rel
*rel
, *rel_end
;
1000 Section
*s
= NULL
, *sr
;
1002 offset
= addr
= block_ptr
= count
= i
= 0;
1003 rel
= rel_end
= NULL
;
1006 if (rel
< rel_end
) {
1007 int type
= ELFW(R_TYPE
)(rel
->r_info
);
1008 addr
= rel
->r_offset
+ s
->sh_addr
;
1010 if (type
!= REL_TYPE_DIRECT
)
1012 if (count
== 0) { /* new block */
1013 block_ptr
= pe
->reloc
->data_offset
;
1014 section_ptr_add(pe
->reloc
, sizeof(struct pe_reloc_header
));
1015 offset
= addr
& 0xFFFFFFFF<<12;
1017 if ((addr
-= offset
) < (1<<12)) { /* one block spans 4k addresses */
1018 WORD
*wp
= section_ptr_add(pe
->reloc
, sizeof (WORD
));
1019 *wp
= addr
| PE_IMAGE_REL
<<12;
1025 } else if (i
< pe
->sec_count
) {
1026 sr
= (s
= pe
->s1
->sections
[pe
->sec_info
[i
++].ord
])->reloc
;
1028 rel
= (ElfW_Rel
*)sr
->data
;
1029 rel_end
= (ElfW_Rel
*)(sr
->data
+ sr
->data_offset
);
1035 /* store the last block and ready for a new one */
1036 struct pe_reloc_header
*hdr
;
1037 if (count
& 1) /* align for DWORDS */
1038 section_ptr_add(pe
->reloc
, sizeof(WORD
)), ++count
;
1039 hdr
= (struct pe_reloc_header
*)(pe
->reloc
->data
+ block_ptr
);
1040 hdr
-> offset
= offset
- pe
->imagebase
;
1041 hdr
-> size
= count
* sizeof(WORD
) + sizeof(struct pe_reloc_header
);
1050 /* ------------------------------------------------------------- */
1051 static int pe_section_class(Section
*s
)
1057 flags
= s
->sh_flags
;
1059 if (flags
& SHF_ALLOC
) {
1060 if (type
== SHT_PROGBITS
) {
1061 if (flags
& SHF_EXECINSTR
)
1063 if (flags
& SHF_WRITE
)
1065 if (0 == strcmp(name
, ".rsrc"))
1067 if (0 == strcmp(name
, ".iedat"))
1069 if (0 == strcmp(name
, ".pdata"))
1071 } else if (type
== SHT_NOBITS
) {
1072 if (flags
& SHF_WRITE
)
1077 if (0 == strcmp(name
, ".reloc"))
1079 if (0 == memcmp(name
, ".stab", 5))
1085 static int pe_assign_addresses (struct pe_info
*pe
)
1090 struct section_info
*si
;
1093 if (PE_DLL
== pe
->type
)
1094 pe
->reloc
= new_section(pe
->s1
, ".reloc", SHT_PROGBITS
, 0);
1096 // pe->thunk = new_section(pe->s1, ".iedat", SHT_PROGBITS, SHF_ALLOC);
1098 section_order
= tcc_malloc(pe
->s1
->nb_sections
* sizeof (int));
1099 for (o
= k
= 0 ; k
< sec_last
; ++k
) {
1100 for (i
= 1; i
< pe
->s1
->nb_sections
; ++i
) {
1101 s
= pe
->s1
->sections
[i
];
1102 if (k
== pe_section_class(s
)) {
1103 // printf("%s %d\n", s->name, k);
1104 s
->sh_addr
= pe
->imagebase
;
1105 section_order
[o
++] = i
;
1110 pe
->sec_info
= tcc_mallocz(o
* sizeof (struct section_info
));
1111 addr
= pe
->imagebase
+ 1;
1113 for (i
= 0; i
< o
; ++i
)
1115 k
= section_order
[i
];
1116 s
= pe
->s1
->sections
[k
];
1117 c
= pe_section_class(s
);
1118 si
= &pe
->sec_info
[pe
->sec_count
];
1120 #ifdef PE_MERGE_DATA
1121 if (c
== sec_bss
&& pe
->sec_count
&& si
[-1].cls
== sec_data
) {
1122 /* append .bss to .data */
1123 s
->sh_addr
= addr
= ((addr
-1) | (s
->sh_addralign
-1)) + 1;
1124 addr
+= s
->data_offset
;
1125 si
[-1].sh_size
= addr
- si
[-1].sh_addr
;
1129 if (c
== sec_stab
&& 0 == pe
->s1
->do_debug
)
1132 strcpy(si
->name
, s
->name
);
1135 si
->sh_addr
= s
->sh_addr
= addr
= pe_virtual_align(pe
, addr
);
1137 si
->pe_flags
= IMAGE_SCN_MEM_READ
;
1138 if (s
->sh_flags
& SHF_EXECINSTR
)
1139 si
->pe_flags
|= IMAGE_SCN_MEM_EXECUTE
| IMAGE_SCN_CNT_CODE
;
1140 else if (s
->sh_type
== SHT_NOBITS
)
1141 si
->pe_flags
|= IMAGE_SCN_CNT_UNINITIALIZED_DATA
;
1143 si
->pe_flags
|= IMAGE_SCN_CNT_INITIALIZED_DATA
;
1144 if (s
->sh_flags
& SHF_WRITE
)
1145 si
->pe_flags
|= IMAGE_SCN_MEM_WRITE
;
1146 if (0 == (s
->sh_flags
& SHF_ALLOC
)) {
1147 si
->pe_flags
|= IMAGE_SCN_MEM_DISCARDABLE
;
1149 si
->pe_flags
|= 0x802; //IMAGE_SCN_TYPE_NOLOAD|IMAGE_SCN_LNK_REMOVE
1152 if (c
== sec_data
&& NULL
== pe
->thunk
)
1155 if (s
== pe
->thunk
) {
1156 pe_build_imports(pe
);
1157 pe_build_exports(pe
);
1161 pe_build_reloc (pe
);
1165 if (s
->sh_type
!= SHT_NOBITS
) {
1167 si
->data_size
= s
->data_offset
;
1170 addr
+= s
->data_offset
;
1171 si
->sh_size
= s
->data_offset
;
1174 //printf("%08x %05x %s %08x\n", si->sh_addr, si->sh_size, si->name, si->pe_flags);
1177 for (i
= 1; i
< pe
->s1
->nb_sections
; ++i
) {
1178 Section
*s
= pe
->s1
->sections
[i
];
1179 int type
= s
->sh_type
;
1180 int flags
= s
->sh_flags
;
1181 printf("section %-16s %-10s %5x %s,%s,%s\n",
1183 type
== SHT_PROGBITS
? "progbits" :
1184 type
== SHT_NOBITS
? "nobits" :
1185 type
== SHT_SYMTAB
? "symtab" :
1186 type
== SHT_STRTAB
? "strtab" :
1187 type
== SHT_RELX
? "rel" : "???",
1189 flags
& SHF_ALLOC
? "alloc" : "",
1190 flags
& SHF_WRITE
? "write" : "",
1191 flags
& SHF_EXECINSTR
? "exec" : ""
1194 pe
->s1
->verbose
= 2;
1197 tcc_free(section_order
);
1201 /*----------------------------------------------------------------------------*/
1203 static int pe_isafunc(TCCState
*s1
, int sym_index
)
1205 Section
*sr
= text_section
->reloc
;
1206 ElfW_Rel
*rel
, *rel_end
;
1207 Elf32_Word info
= ELF32_R_INFO(sym_index
, R_386_PC32
);
1210 rel_end
= (ElfW_Rel
*)(sr
->data
+ sr
->data_offset
);
1211 for (rel
= (ElfW_Rel
*)sr
->data
; rel
< rel_end
; rel
++)
1212 if (rel
->r_info
== info
)
1217 /*----------------------------------------------------------------------------*/
1218 static int pe_check_symbols(struct pe_info
*pe
)
1221 int sym_index
, sym_end
;
1223 TCCState
*s1
= pe
->s1
;
1225 pe_align_section(text_section
, 8);
1227 sym_end
= symtab_section
->data_offset
/ sizeof(ElfW(Sym
));
1228 for (sym_index
= 1; sym_index
< sym_end
; ++sym_index
) {
1230 sym
= (ElfW(Sym
) *)symtab_section
->data
+ sym_index
;
1231 if (sym
->st_shndx
== SHN_UNDEF
) {
1233 const char *name
= (char*)symtab_section
->link
->data
+ sym
->st_name
;
1234 unsigned type
= ELFW(ST_TYPE
)(sym
->st_info
);
1235 int imp_sym
= pe_find_import(pe
->s1
, sym
);
1236 struct import_symbol
*is
;
1241 if (type
== STT_NOTYPE
) {
1242 /* symbols from assembler have no type, find out which */
1243 if (pe_isafunc(s1
, sym_index
))
1249 is
= pe_add_import(pe
, imp_sym
);
1251 if (type
== STT_FUNC
) {
1252 unsigned long offset
= is
->thk_offset
;
1254 /* got aliased symbol, like stricmp and _stricmp */
1260 offset
= text_section
->data_offset
;
1261 /* add the 'jmp IAT[x]' instruction */
1262 #ifdef TCC_TARGET_ARM
1263 p
= section_ptr_add(text_section
, 8+4); // room for code and address
1264 (*(DWORD
*)(p
)) = 0xE59FC000; // arm code ldr ip, [pc] ; PC+8+0 = 0001xxxx
1265 (*(DWORD
*)(p
+2)) = 0xE59CF000; // arm code ldr pc, [ip]
1267 p
= section_ptr_add(text_section
, 8);
1269 #ifdef TCC_TARGET_X86_64
1270 *(DWORD
*)(p
+1) = (DWORD
)-4;
1273 /* add a helper symbol, will be patched later in
1275 sprintf(buffer
, "IAT.%s", name
);
1276 is
->iat_index
= put_elf_sym(
1277 symtab_section
, 0, sizeof(DWORD
),
1278 ELFW(ST_INFO
)(STB_GLOBAL
, STT_OBJECT
),
1279 0, SHN_UNDEF
, buffer
);
1280 #ifdef TCC_TARGET_ARM
1281 put_elf_reloc(symtab_section
, text_section
,
1282 offset
+ 8, R_XXX_THUNKFIX
, is
->iat_index
); // offset to IAT position
1284 put_elf_reloc(symtab_section
, text_section
,
1285 offset
+ 2, R_XXX_THUNKFIX
, is
->iat_index
);
1287 is
->thk_offset
= offset
;
1290 /* tcc_realloc might have altered sym's address */
1291 sym
= (ElfW(Sym
) *)symtab_section
->data
+ sym_index
;
1293 /* patch the original symbol */
1294 sym
->st_value
= offset
;
1295 sym
->st_shndx
= text_section
->sh_num
;
1296 sym
->st_other
&= ~ST_PE_EXPORT
; /* do not export */
1300 if (type
== STT_OBJECT
) { /* data, ptr to that should be */
1301 if (0 == is
->iat_index
) {
1302 /* original symbol will be patched later in pe_build_imports */
1303 is
->iat_index
= sym_index
;
1309 if (ELFW(ST_BIND
)(sym
->st_info
) == STB_WEAK
)
1310 /* STB_WEAK undefined symbols are accepted */
1312 tcc_error_noabort("undefined symbol '%s'%s", name
,
1313 imp_sym
< 0 ? ", missing __declspec(dllimport)?":"");
1316 } else if (pe
->s1
->rdynamic
1317 && ELFW(ST_BIND
)(sym
->st_info
) != STB_LOCAL
) {
1318 /* if -rdynamic option, then export all non local symbols */
1319 sym
->st_other
|= ST_PE_EXPORT
;
1325 /*----------------------------------------------------------------------------*/
1326 #ifdef PE_PRINT_SECTIONS
1327 static void pe_print_section(FILE * f
, Section
* s
)
1329 /* just if you're curious */
1333 e
= s
->data
+ s
->data_offset
;
1336 fprintf(f
, "section \"%s\"", s
->name
);
1338 fprintf(f
, "\nlink \"%s\"", s
->link
->name
);
1340 fprintf(f
, "\nreloc \"%s\"", s
->reloc
->name
);
1341 fprintf(f
, "\nv_addr %08X", (unsigned)s
->sh_addr
);
1342 fprintf(f
, "\ncontents %08X", (unsigned)l
);
1345 if (s
->sh_type
== SHT_NOBITS
)
1351 if (s
->sh_type
== SHT_SYMTAB
)
1352 m
= sizeof(ElfW(Sym
));
1353 else if (s
->sh_type
== SHT_RELX
)
1354 m
= sizeof(ElfW_Rel
);
1358 fprintf(f
, "%-8s", "offset");
1359 for (i
= 0; i
< m
; ++i
)
1360 fprintf(f
, " %02x", i
);
1363 if (s
->sh_type
== SHT_SYMTAB
|| s
->sh_type
== SHT_RELX
) {
1364 const char *fields1
[] = {
1375 const char *fields2
[] = {
1384 if (s
->sh_type
== SHT_SYMTAB
)
1385 p
= fields1
, n
= 106;
1387 p
= fields2
, n
= 58;
1389 for (i
= 0; p
[i
]; ++i
)
1390 fprintf(f
, "%6s", p
[i
]);
1391 fprintf(f
, " symbol");
1395 for (i
= 0; i
< n
; ++i
)
1401 fprintf(f
, "%08X", i
);
1402 for (n
= 0; n
< m
; ++n
) {
1404 fprintf(f
, " %02X", p
[i
+ n
]);
1409 if (s
->sh_type
== SHT_SYMTAB
) {
1410 ElfW(Sym
) *sym
= (ElfW(Sym
) *) (p
+ i
);
1411 const char *name
= s
->link
->data
+ sym
->st_name
;
1412 fprintf(f
, " %04X %04X %04X %02X %02X %02X %04X \"%s\"",
1413 (unsigned)sym
->st_name
,
1414 (unsigned)sym
->st_value
,
1415 (unsigned)sym
->st_size
,
1416 (unsigned)ELFW(ST_BIND
)(sym
->st_info
),
1417 (unsigned)ELFW(ST_TYPE
)(sym
->st_info
),
1418 (unsigned)sym
->st_other
,
1419 (unsigned)sym
->st_shndx
,
1422 } else if (s
->sh_type
== SHT_RELX
) {
1423 ElfW_Rel
*rel
= (ElfW_Rel
*) (p
+ i
);
1425 (ElfW(Sym
) *) s
->link
->data
+ ELFW(R_SYM
)(rel
->r_info
);
1426 const char *name
= s
->link
->link
->data
+ sym
->st_name
;
1427 fprintf(f
, " %04X %02X %04X \"%s\"",
1428 (unsigned)rel
->r_offset
,
1429 (unsigned)ELFW(R_TYPE
)(rel
->r_info
),
1430 (unsigned)ELFW(R_SYM
)(rel
->r_info
),
1434 for (n
= 0; n
< m
; ++n
) {
1437 if (b
< 32 || b
>= 127)
1439 fprintf(f
, "%c", b
);
1449 static void pe_print_sections(TCCState
*s1
, const char *fname
)
1454 f
= fopen(fname
, "w");
1455 for (i
= 1; i
< s1
->nb_sections
; ++i
) {
1456 s
= s1
->sections
[i
];
1457 pe_print_section(f
, s
);
1459 pe_print_section(f
, s1
->dynsymtab_section
);
1464 /* ------------------------------------------------------------- */
1465 /* helper function for load/store to insert one more indirection */
1467 #if defined TCC_TARGET_I386 || defined TCC_TARGET_X86_64
1468 ST_FUNC SValue
*pe_getimport(SValue
*sv
, SValue
*v2
)
1471 if ((sv
->r
& (VT_VALMASK
|VT_SYM
)) != (VT_CONST
|VT_SYM
) || (sv
->r2
!= VT_CONST
))
1473 if (!sv
->sym
->a
.dllimport
)
1475 // printf("import %04x %04x %04x %s\n", sv->type.t, sv->sym->type.t, sv->r, get_tok_str(sv->sym->v, NULL));
1476 memset(v2
, 0, sizeof *v2
);
1477 v2
->type
.t
= VT_PTR
;
1478 v2
->r
= VT_CONST
| VT_SYM
| VT_LVAL
;
1481 r2
= get_reg(RC_INT
);
1484 if ((uint32_t)sv
->c
.i
) {
1490 v2
->type
.t
= sv
->type
.t
;
1491 v2
->r
|= sv
->r
& VT_LVAL
;
1496 ST_FUNC
int pe_putimport(TCCState
*s1
, int dllindex
, const char *name
, addr_t value
)
1499 s1
->dynsymtab_section
,
1501 dllindex
, /* st_size */
1502 ELFW(ST_INFO
)(STB_GLOBAL
, STT_NOTYPE
),
1504 value
? SHN_ABS
: SHN_UNDEF
,
1509 static int add_dllref(TCCState
*s1
, const char *dllname
)
1511 DLLReference
*dllref
;
1513 for (i
= 0; i
< s1
->nb_loaded_dlls
; ++i
)
1514 if (0 == strcmp(s1
->loaded_dlls
[i
]->name
, dllname
))
1516 dllref
= tcc_mallocz(sizeof(DLLReference
) + strlen(dllname
));
1517 strcpy(dllref
->name
, dllname
);
1518 dynarray_add(&s1
->loaded_dlls
, &s1
->nb_loaded_dlls
, dllref
);
1519 return s1
->nb_loaded_dlls
;
1522 /* ------------------------------------------------------------- */
1524 static int read_mem(int fd
, unsigned offset
, void *buffer
, unsigned len
)
1526 lseek(fd
, offset
, SEEK_SET
);
1527 return len
== read(fd
, buffer
, len
);
1530 /* ------------------------------------------------------------- */
1532 PUB_FUNC
int tcc_get_dllexports(const char *filename
, char **pp
)
1534 int l
, i
, n
, n0
, ret
;
1538 IMAGE_SECTION_HEADER ish
;
1539 IMAGE_EXPORT_DIRECTORY ied
;
1540 IMAGE_DOS_HEADER dh
;
1541 IMAGE_FILE_HEADER ih
;
1542 DWORD sig
, ref
, addr
, ptr
, namep
;
1544 int pef_hdroffset
, opt_hdroffset
, sec_hdroffset
;
1550 fd
= open(filename
, O_RDONLY
| O_BINARY
);
1554 if (!read_mem(fd
, 0, &dh
, sizeof dh
))
1556 if (!read_mem(fd
, dh
.e_lfanew
, &sig
, sizeof sig
))
1558 if (sig
!= 0x00004550)
1560 pef_hdroffset
= dh
.e_lfanew
+ sizeof sig
;
1561 if (!read_mem(fd
, pef_hdroffset
, &ih
, sizeof ih
))
1563 opt_hdroffset
= pef_hdroffset
+ sizeof ih
;
1564 if (ih
.Machine
== 0x014C) {
1565 IMAGE_OPTIONAL_HEADER32 oh
;
1566 sec_hdroffset
= opt_hdroffset
+ sizeof oh
;
1567 if (!read_mem(fd
, opt_hdroffset
, &oh
, sizeof oh
))
1569 if (IMAGE_DIRECTORY_ENTRY_EXPORT
>= oh
.NumberOfRvaAndSizes
)
1571 addr
= oh
.DataDirectory
[IMAGE_DIRECTORY_ENTRY_EXPORT
].VirtualAddress
;
1572 } else if (ih
.Machine
== 0x8664) {
1573 IMAGE_OPTIONAL_HEADER64 oh
;
1574 sec_hdroffset
= opt_hdroffset
+ sizeof oh
;
1575 if (!read_mem(fd
, opt_hdroffset
, &oh
, sizeof oh
))
1577 if (IMAGE_DIRECTORY_ENTRY_EXPORT
>= oh
.NumberOfRvaAndSizes
)
1579 addr
= oh
.DataDirectory
[IMAGE_DIRECTORY_ENTRY_EXPORT
].VirtualAddress
;
1583 //printf("addr: %08x\n", addr);
1584 for (i
= 0; i
< ih
.NumberOfSections
; ++i
) {
1585 if (!read_mem(fd
, sec_hdroffset
+ i
* sizeof ish
, &ish
, sizeof ish
))
1587 //printf("vaddr: %08x\n", ish.VirtualAddress);
1588 if (addr
>= ish
.VirtualAddress
&& addr
< ish
.VirtualAddress
+ ish
.SizeOfRawData
)
1594 ref
= ish
.VirtualAddress
- ish
.PointerToRawData
;
1595 if (!read_mem(fd
, addr
- ref
, &ied
, sizeof ied
))
1598 namep
= ied
.AddressOfNames
- ref
;
1599 for (i
= 0; i
< ied
.NumberOfNames
; ++i
) {
1600 if (!read_mem(fd
, namep
, &ptr
, sizeof ptr
))
1602 namep
+= sizeof ptr
;
1605 p
= tcc_realloc(p
, n0
= n0
? n0
* 2 : 256);
1606 if (!read_mem(fd
, ptr
- ref
+ l
++, p
+ n
, 1)) {
1607 tcc_free(p
), p
= NULL
;
1625 /* -------------------------------------------------------------
1626 * This is for compiled windows resources in 'coff' format
1627 * as generated by 'windres.exe -O coff ...'.
1630 static int pe_load_res(TCCState
*s1
, int fd
)
1632 struct pe_rsrc_header hdr
;
1633 Section
*rsrc_section
;
1634 int i
, ret
= -1, sym_index
;
1638 if (!read_mem(fd
, 0, &hdr
, sizeof hdr
))
1641 if (hdr
.filehdr
.Machine
!= IMAGE_FILE_MACHINE
1642 || hdr
.filehdr
.NumberOfSections
!= 1
1643 || strcmp((char*)hdr
.sectionhdr
.Name
, ".rsrc") != 0)
1646 rsrc_section
= new_section(s1
, ".rsrc", SHT_PROGBITS
, SHF_ALLOC
);
1647 ptr
= section_ptr_add(rsrc_section
, hdr
.sectionhdr
.SizeOfRawData
);
1648 offs
= hdr
.sectionhdr
.PointerToRawData
;
1649 if (!read_mem(fd
, offs
, ptr
, hdr
.sectionhdr
.SizeOfRawData
))
1651 offs
= hdr
.sectionhdr
.PointerToRelocations
;
1652 sym_index
= put_elf_sym(symtab_section
, 0, 0, 0, 0, rsrc_section
->sh_num
, ".rsrc");
1653 for (i
= 0; i
< hdr
.sectionhdr
.NumberOfRelocations
; ++i
) {
1654 struct pe_rsrc_reloc rel
;
1655 if (!read_mem(fd
, offs
, &rel
, sizeof rel
))
1657 // printf("rsrc_reloc: %x %x %x\n", rel.offset, rel.size, rel.type);
1658 if (rel
.type
!= RSRC_RELTYPE
)
1660 put_elf_reloc(symtab_section
, rsrc_section
,
1661 rel
.offset
, R_XXX_RELATIVE
, sym_index
);
1669 /* ------------------------------------------------------------- */
1671 static char *trimfront(char *p
)
1673 while (*p
&& (unsigned char)*p
<= ' ')
1678 static char *trimback(char *a
, char *e
)
1680 while (e
> a
&& (unsigned char)e
[-1] <= ' ')
1686 /* ------------------------------------------------------------- */
1687 static int pe_load_def(TCCState
*s1
, int fd
)
1689 int state
= 0, ret
= -1, dllindex
= 0, ord
;
1690 char line
[400], dllname
[80], *p
, *x
;
1693 fp
= fdopen(dup(fd
), "rb");
1694 while (fgets(line
, sizeof line
, fp
))
1696 p
= trimfront(trimback(line
, strchr(line
, 0)));
1697 if (0 == *p
|| ';' == *p
)
1702 if (0 != strnicmp(p
, "LIBRARY", 7))
1704 pstrcpy(dllname
, sizeof dllname
, trimfront(p
+7));
1709 if (0 != stricmp(p
, "EXPORTS"))
1715 dllindex
= add_dllref(s1
, dllname
);
1719 /* get ordinal and will store in sym->st_value */
1723 *x
= 0, x
= strrchr(x
+ 1, '@');
1726 ord
= (int)strtol(x
+ 1, &d
, 10);
1731 pe_putimport(s1
, dllindex
, p
, ord
);
1741 /* ------------------------------------------------------------- */
1742 static int pe_load_dll(TCCState
*s1
, const char *filename
)
1747 ret
= tcc_get_dllexports(filename
, &p
);
1751 index
= add_dllref(s1
, tcc_basename(filename
));
1752 for (q
= p
; *q
; q
+= 1 + strlen(q
))
1753 pe_putimport(s1
, index
, q
, 0);
1759 /* ------------------------------------------------------------- */
1760 ST_FUNC
int pe_load_file(struct TCCState
*s1
, const char *filename
, int fd
)
1764 if (0 == strcmp(tcc_fileextension(filename
), ".def"))
1765 ret
= pe_load_def(s1
, fd
);
1766 else if (pe_load_res(s1
, fd
) == 0)
1768 else if (read_mem(fd
, 0, buf
, 4) && 0 == memcmp(buf
, "MZ", 2))
1769 ret
= pe_load_dll(s1
, filename
);
1773 /* ------------------------------------------------------------- */
1774 #ifdef TCC_TARGET_X86_64
1775 static unsigned pe_add_uwwind_info(TCCState
*s1
)
1777 if (NULL
== s1
->uw_pdata
) {
1778 s1
->uw_pdata
= find_section(s1
, ".pdata");
1779 s1
->uw_pdata
->sh_addralign
= 4;
1781 if (0 == s1
->uw_sym
)
1782 s1
->uw_sym
= put_elf_sym(symtab_section
, 0, 0, 0, 0, text_section
->sh_num
, ".uw_base");
1783 if (0 == s1
->uw_offs
) {
1784 /* As our functions all have the same stackframe, we use one entry for all */
1785 static const unsigned char uw_info
[] = {
1786 0x01, // UBYTE: 3 Version , UBYTE: 5 Flags
1787 0x04, // UBYTE Size of prolog
1788 0x02, // UBYTE Count of unwind codes
1789 0x05, // UBYTE: 4 Frame Register (rbp), UBYTE: 4 Frame Register offset (scaled)
1790 // USHORT * n Unwind codes array
1791 // 0x0b, 0x01, 0xff, 0xff, // stack size
1792 0x04, 0x03, // set frame ptr (mov rsp -> rbp)
1793 0x01, 0x50 // push reg (rbp)
1796 Section
*s
= text_section
;
1799 section_ptr_add(s
, -s
->data_offset
& 3); /* align */
1800 s1
->uw_offs
= s
->data_offset
;
1801 p
= section_ptr_add(s
, sizeof uw_info
);
1802 memcpy(p
, uw_info
, sizeof uw_info
);
1808 ST_FUNC
void pe_add_unwind_data(unsigned start
, unsigned end
, unsigned stack
)
1810 TCCState
*s1
= tcc_state
;
1813 struct /* _RUNTIME_FUNCTION */ {
1819 d
= pe_add_uwwind_info(s1
);
1821 o
= pd
->data_offset
;
1822 p
= section_ptr_add(pd
, sizeof *p
);
1824 /* record this function */
1825 p
->BeginAddress
= start
;
1826 p
->EndAddress
= end
;
1829 /* put relocations on it */
1830 for (n
= o
+ sizeof *p
; o
< n
; o
+= sizeof p
->BeginAddress
)
1831 put_elf_reloc(symtab_section
, pd
, o
, R_XXX_RELATIVE
, s1
->uw_sym
);
1834 /* ------------------------------------------------------------- */
1835 #ifdef TCC_TARGET_X86_64
1836 #define PE_STDSYM(n,s) n
1838 #define PE_STDSYM(n,s) "_" n s
1841 static void tcc_add_support(TCCState
*s1
, const char *filename
)
1843 if (tcc_add_dll(s1
, filename
, 0) < 0)
1844 tcc_error_noabort("%s not found", filename
);
1847 static void pe_add_runtime(TCCState
*s1
, struct pe_info
*pe
)
1849 const char *start_symbol
;
1851 int unicode_entry
= 0;
1853 if (find_elf_sym(symtab_section
, PE_STDSYM("WinMain","@16")))
1856 if (find_elf_sym(symtab_section
, PE_STDSYM("wWinMain","@16"))) {
1858 unicode_entry
= PE_GUI
;
1861 if (TCC_OUTPUT_DLL
== s1
->output_type
) {
1863 /* need this for 'tccelf.c:relocate_section()' */
1864 s1
->output_type
= TCC_OUTPUT_EXE
;
1868 if (find_elf_sym(symtab_section
, "wmain"))
1869 unicode_entry
= PE_EXE
;
1873 TCC_OUTPUT_MEMORY
== s1
->output_type
1874 ? PE_GUI
== pe_type
? (unicode_entry
? "__runwwinmain" : "__runwinmain")
1875 : (unicode_entry
? "__runwmain" : "__runmain")
1876 : PE_DLL
== pe_type
? PE_STDSYM("__dllstart","@12")
1877 : PE_GUI
== pe_type
? (unicode_entry
? "__wwinstart": "__winstart")
1878 : (unicode_entry
? "__wstart" : "__start")
1881 if (!s1
->leading_underscore
|| strchr(start_symbol
, '@'))
1884 /* grab the startup code from libtcc1 */
1885 #ifdef TCC_IS_NATIVE
1886 if (TCC_OUTPUT_MEMORY
!= s1
->output_type
|| s1
->runtime_main
)
1888 set_elf_sym(symtab_section
,
1890 ELFW(ST_INFO
)(STB_GLOBAL
, STT_NOTYPE
), 0,
1891 SHN_UNDEF
, start_symbol
);
1893 if (0 == s1
->nostdlib
) {
1894 static const char *libs
[] = {
1895 "msvcrt", "kernel32", "", "user32", "gdi32", NULL
1897 const char **pp
, *p
;
1898 #ifdef TCC_IS_NATIVE
1899 if (s1
->do_bounds_check
)
1900 tcc_add_support(s1
, "bcheck.o");
1902 tcc_add_support(s1
, TCC_LIBTCC1
);
1903 for (pp
= libs
; 0 != (p
= *pp
); ++pp
) {
1905 tcc_add_library_err(s1
, p
);
1906 else if (PE_DLL
!= pe_type
&& PE_GUI
!= pe_type
)
1910 if (TCC_OUTPUT_MEMORY
== s1
->output_type
)
1913 pe
->start_symbol
= start_symbol
;
1916 static void pe_set_options(TCCState
* s1
, struct pe_info
*pe
)
1918 if (PE_DLL
== pe
->type
) {
1919 /* XXX: check if is correct for arm-pe target */
1920 pe
->imagebase
= 0x10000000;
1922 #if defined(TCC_TARGET_ARM)
1923 pe
->imagebase
= 0x00010000;
1925 pe
->imagebase
= 0x00400000;
1929 #if defined(TCC_TARGET_ARM)
1930 /* we use "console" subsystem by default */
1933 if (PE_DLL
== pe
->type
|| PE_GUI
== pe
->type
)
1938 /* Allow override via -Wl,-subsystem=... option */
1939 if (s1
->pe_subsystem
!= 0)
1940 pe
->subsystem
= s1
->pe_subsystem
;
1942 /* set default file/section alignment */
1943 if (pe
->subsystem
== 1) {
1944 pe
->section_align
= 0x20;
1945 pe
->file_align
= 0x20;
1947 pe
->section_align
= 0x1000;
1948 pe
->file_align
= 0x200;
1951 if (s1
->section_align
!= 0)
1952 pe
->section_align
= s1
->section_align
;
1953 if (s1
->pe_file_align
!= 0)
1954 pe
->file_align
= s1
->pe_file_align
;
1956 if ((pe
->subsystem
>= 10) && (pe
->subsystem
<= 12))
1959 if (s1
->has_text_addr
)
1960 pe
->imagebase
= s1
->text_addr
;
1963 ST_FUNC
int pe_output_file(TCCState
*s1
, const char *filename
)
1969 memset(&pe
, 0, sizeof pe
);
1970 pe
.filename
= filename
;
1973 tcc_add_runtime(s1
);
1974 pe_add_runtime(s1
, &pe
);
1975 resolve_common_syms(s1
);
1976 pe_set_options(s1
, &pe
);
1978 ret
= pe_check_symbols(&pe
);
1981 else if (filename
) {
1982 pe_assign_addresses(&pe
);
1983 relocate_syms(s1
, s1
->symtab
, 0);
1984 s1
->pe_imagebase
= pe
.imagebase
;
1985 for (i
= 1; i
< s1
->nb_sections
; ++i
) {
1986 Section
*s
= s1
->sections
[i
];
1988 relocate_section(s1
, s
);
1991 pe
.start_addr
= (DWORD
)
1992 ((uintptr_t)tcc_get_symbol_err(s1
, pe
.start_symbol
)
1997 ret
= pe_write(&pe
);
1998 tcc_free(pe
.sec_info
);
2000 #ifdef TCC_IS_NATIVE
2001 pe
.thunk
= data_section
;
2002 pe_build_imports(&pe
);
2003 s1
->runtime_main
= pe
.start_symbol
;
2004 #ifdef TCC_TARGET_X86_64
2005 s1
->uw_pdata
= find_section(s1
, ".pdata");
2010 pe_free_imports(&pe
);
2012 #ifdef PE_PRINT_SECTIONS
2013 pe_print_sections(s1
, "tcc.log");
2018 /* ------------------------------------------------------------- */