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
245 /* ----------------------------------------------------------- */
246 #endif /* ndef IMAGE_NT_SIGNATURE */
247 /* ----------------------------------------------------------- */
249 #ifndef IMAGE_REL_BASED_DIR64
250 # define IMAGE_REL_BASED_DIR64 10
253 #pragma pack(push, 1)
256 IMAGE_DOS_HEADER doshdr
;
259 IMAGE_FILE_HEADER filehdr
;
260 #ifdef TCC_TARGET_X86_64
261 IMAGE_OPTIONAL_HEADER64 opthdr
;
264 IMAGE_OPTIONAL_HEADER32 opthdr
;
266 IMAGE_OPTIONAL_HEADER opthdr
;
271 struct pe_reloc_header
{
276 struct pe_rsrc_header
{
277 struct _IMAGE_FILE_HEADER filehdr
;
278 struct _IMAGE_SECTION_HEADER sectionhdr
;
281 struct pe_rsrc_reloc
{
288 /* ------------------------------------------------------------- */
289 /* internal temporary structures */
306 static const DWORD pe_sec_flags
[] = {
307 0x60000020, /* ".text" , */
308 0xC0000040, /* ".data" , */
309 0xC0000080, /* ".bss" , */
310 0x40000040, /* ".idata" , */
311 0x40000040, /* ".pdata" , */
312 0xE0000060, /* < other > , */
313 0x40000040, /* ".rsrc" , */
314 0x42000802, /* ".stab" , */
315 0x42000040, /* ".reloc" , */
319 struct section_info
{
327 IMAGE_SECTION_HEADER ish
;
330 struct import_symbol
{
336 struct pe_import_info
{
339 struct import_symbol
**symbols
;
346 const char *filename
;
350 const char *start_symbol
;
361 struct section_info
**sec_info
;
363 struct pe_import_info
**imp_info
;
373 /* --------------------------------------------*/
375 static const char *pe_export_name(TCCState
*s1
, ElfW(Sym
) *sym
)
377 const char *name
= (char*)symtab_section
->link
->data
+ sym
->st_name
;
378 if (s1
->leading_underscore
&& name
[0] == '_' && !(sym
->st_other
& ST_PE_STDCALL
))
383 static int pe_find_import(TCCState
* s1
, ElfW(Sym
) *sym
)
387 int sym_index
= 0, n
= 0;
391 s
= pe_export_name(s1
, sym
);
395 if (sym
->st_other
& ST_PE_STDCALL
) {
396 /* try w/0 stdcall deco (windows API convention) */
398 if (!p
|| s
[0] != '_')
400 strcpy(buffer
, s
+1)[p
-s
-1] = 0;
401 } else if (s
[0] != '_') { /* try non-ansi function */
402 buffer
[0] = '_', strcpy(buffer
+ 1, s
);
403 } else if (0 == memcmp(s
, "__imp_", 6)) { /* mingw 2.0 */
404 strcpy(buffer
, s
+ 6), a
= 1;
405 } else if (0 == memcmp(s
, "_imp__", 6)) { /* mingw 3.7 */
406 strcpy(buffer
, s
+ 6), a
= 1;
412 sym_index
= find_elf_sym(s1
->dynsymtab_section
, s
);
413 // printf("find (%d) %d %s\n", n, sym_index, s);
415 && ELFW(ST_TYPE
)(sym
->st_info
) == STT_OBJECT
416 && 0 == (sym
->st_other
& ST_PE_IMPORT
)
418 ) err
= -1, sym_index
= 0;
419 } while (0 == sym_index
&& ++n
< 2);
420 return n
== 2 ? err
: sym_index
;
423 /*----------------------------------------------------------------------------*/
425 static int dynarray_assoc(void **pp
, int n
, int key
)
428 for (i
= 0; i
< n
; ++i
, ++pp
)
429 if (key
== **(int **) pp
)
434 static DWORD
umin(DWORD a
, DWORD b
)
436 return a
< b
? a
: b
;
439 static DWORD
umax(DWORD a
, DWORD b
)
441 return a
< b
? b
: a
;
444 static DWORD
pe_file_align(struct pe_info
*pe
, DWORD n
)
446 return (n
+ (pe
->file_align
- 1)) & ~(pe
->file_align
- 1);
449 static DWORD
pe_virtual_align(struct pe_info
*pe
, DWORD n
)
451 return (n
+ (pe
->section_align
- 1)) & ~(pe
->section_align
- 1);
454 static void pe_align_section(Section
*s
, int a
)
456 int i
= s
->data_offset
& (a
-1);
458 section_ptr_add(s
, a
- i
);
461 static void pe_set_datadir(struct pe_header
*hdr
, int dir
, DWORD addr
, DWORD size
)
463 hdr
->opthdr
.DataDirectory
[dir
].VirtualAddress
= addr
;
464 hdr
->opthdr
.DataDirectory
[dir
].Size
= size
;
473 static int pe_fwrite(void *data
, int len
, struct pe_file
*pf
)
478 pf
->pos
+= (ret
= fwrite(data
, 1, len
, pf
->op
));
480 for (i
= len
; i
> 0; i
-= 2) {
481 sum
+= (i
>= 2) ? *p
++ : *(BYTE
*)p
;
482 sum
= (sum
+ (sum
>> 16)) & 0xFFFF;
485 return len
== ret
? 0 : -1;
488 static void pe_fpad(struct pe_file
*pf
, DWORD new_pos
)
491 int n
, diff
= new_pos
- pf
->pos
;
492 memset(buf
, 0, sizeof buf
);
494 diff
-= n
= umin(diff
, sizeof buf
);
495 fwrite(buf
, n
, 1, pf
->op
);
500 /*----------------------------------------------------------------------------*/
501 static int pe_write(struct pe_info
*pe
)
503 static const struct pe_header pe_template
= {
505 /* IMAGE_DOS_HEADER doshdr */
506 0x5A4D, /*WORD e_magic; Magic number */
507 0x0090, /*WORD e_cblp; Bytes on last page of file */
508 0x0003, /*WORD e_cp; Pages in file */
509 0x0000, /*WORD e_crlc; Relocations */
511 0x0004, /*WORD e_cparhdr; Size of header in paragraphs */
512 0x0000, /*WORD e_minalloc; Minimum extra paragraphs needed */
513 0xFFFF, /*WORD e_maxalloc; Maximum extra paragraphs needed */
514 0x0000, /*WORD e_ss; Initial (relative) SS value */
516 0x00B8, /*WORD e_sp; Initial SP value */
517 0x0000, /*WORD e_csum; Checksum */
518 0x0000, /*WORD e_ip; Initial IP value */
519 0x0000, /*WORD e_cs; Initial (relative) CS value */
520 0x0040, /*WORD e_lfarlc; File address of relocation table */
521 0x0000, /*WORD e_ovno; Overlay number */
522 {0,0,0,0}, /*WORD e_res[4]; Reserved words */
523 0x0000, /*WORD e_oemid; OEM identifier (for e_oeminfo) */
524 0x0000, /*WORD e_oeminfo; OEM information; e_oemid specific */
525 {0,0,0,0,0,0,0,0,0,0}, /*WORD e_res2[10]; Reserved words */
526 0x00000080 /*DWORD e_lfanew; File address of new exe header */
528 /* BYTE dosstub[0x40] */
529 /* 14 code bytes + "This program cannot be run in DOS mode.\r\r\n$" + 6 * 0x00 */
530 0x0e,0x1f,0xba,0x0e,0x00,0xb4,0x09,0xcd,0x21,0xb8,0x01,0x4c,0xcd,0x21,0x54,0x68,
531 0x69,0x73,0x20,0x70,0x72,0x6f,0x67,0x72,0x61,0x6d,0x20,0x63,0x61,0x6e,0x6e,0x6f,
532 0x74,0x20,0x62,0x65,0x20,0x72,0x75,0x6e,0x20,0x69,0x6e,0x20,0x44,0x4f,0x53,0x20,
533 0x6d,0x6f,0x64,0x65,0x2e,0x0d,0x0d,0x0a,0x24,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
535 0x00004550, /* DWORD nt_sig = IMAGE_NT_SIGNATURE */
537 /* IMAGE_FILE_HEADER filehdr */
538 IMAGE_FILE_MACHINE
, /*WORD Machine; */
539 0x0003, /*WORD NumberOfSections; */
540 0x00000000, /*DWORD TimeDateStamp; */
541 0x00000000, /*DWORD PointerToSymbolTable; */
542 0x00000000, /*DWORD NumberOfSymbols; */
543 #if defined(TCC_TARGET_X86_64)
544 0x00F0, /*WORD SizeOfOptionalHeader; */
545 0x022F /*WORD Characteristics; */
546 #define CHARACTERISTICS_DLL 0x222E
547 #elif defined(TCC_TARGET_I386)
548 0x00E0, /*WORD SizeOfOptionalHeader; */
549 0x030F /*WORD Characteristics; */
550 #define CHARACTERISTICS_DLL 0x230E
551 #elif defined(TCC_TARGET_ARM)
552 0x00E0, /*WORD SizeOfOptionalHeader; */
553 0x010F, /*WORD Characteristics; */
554 #define CHARACTERISTICS_DLL 0x230F
557 /* IMAGE_OPTIONAL_HEADER opthdr */
558 /* Standard fields. */
559 #ifdef TCC_TARGET_X86_64
560 0x020B, /*WORD Magic; */
562 0x010B, /*WORD Magic; */
564 0x06, /*BYTE MajorLinkerVersion; */
565 0x00, /*BYTE MinorLinkerVersion; */
566 0x00000000, /*DWORD SizeOfCode; */
567 0x00000000, /*DWORD SizeOfInitializedData; */
568 0x00000000, /*DWORD SizeOfUninitializedData; */
569 0x00000000, /*DWORD AddressOfEntryPoint; */
570 0x00000000, /*DWORD BaseOfCode; */
571 #ifndef TCC_TARGET_X86_64
572 0x00000000, /*DWORD BaseOfData; */
574 /* NT additional fields. */
575 #if defined(TCC_TARGET_ARM)
576 0x00100000, /*DWORD ImageBase; */
578 0x00400000, /*DWORD ImageBase; */
580 0x00001000, /*DWORD SectionAlignment; */
581 0x00000200, /*DWORD FileAlignment; */
582 0x0004, /*WORD MajorOperatingSystemVersion; */
583 0x0000, /*WORD MinorOperatingSystemVersion; */
584 0x0000, /*WORD MajorImageVersion; */
585 0x0000, /*WORD MinorImageVersion; */
586 0x0004, /*WORD MajorSubsystemVersion; */
587 0x0000, /*WORD MinorSubsystemVersion; */
588 0x00000000, /*DWORD Win32VersionValue; */
589 0x00000000, /*DWORD SizeOfImage; */
590 0x00000200, /*DWORD SizeOfHeaders; */
591 0x00000000, /*DWORD CheckSum; */
592 0x0002, /*WORD Subsystem; */
593 0x0000, /*WORD DllCharacteristics; */
594 0x00100000, /*DWORD SizeOfStackReserve; */
595 0x00001000, /*DWORD SizeOfStackCommit; */
596 0x00100000, /*DWORD SizeOfHeapReserve; */
597 0x00001000, /*DWORD SizeOfHeapCommit; */
598 0x00000000, /*DWORD LoaderFlags; */
599 0x00000010, /*DWORD NumberOfRvaAndSizes; */
601 /* IMAGE_DATA_DIRECTORY DataDirectory[16]; */
602 {{0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0},
603 {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}}
606 struct pe_header pe_header
= pe_template
;
609 struct pe_file pf
= {0};
611 struct section_info
*si
;
612 IMAGE_SECTION_HEADER
*psh
;
613 TCCState
*s1
= pe
->s1
;
615 pf
.op
= fopen(pe
->filename
, "wb");
617 tcc_error_noabort("could not write '%s': %s", pe
->filename
, strerror(errno
));
621 pe
->sizeofheaders
= pe_file_align(pe
,
622 sizeof (struct pe_header
)
623 + pe
->sec_count
* sizeof (IMAGE_SECTION_HEADER
)
626 file_offset
= pe
->sizeofheaders
;
628 if (2 == pe
->s1
->verbose
)
629 printf("-------------------------------"
630 "\n virt file size section" "\n");
631 for (i
= 0; i
< pe
->sec_count
; ++i
) {
635 si
= pe
->sec_info
[i
];
637 addr
= si
->sh_addr
- pe
->imagebase
;
641 if (2 == pe
->s1
->verbose
)
642 printf("%6x %6x %6x %s\n",
643 (unsigned)addr
, (unsigned)file_offset
, (unsigned)size
, sh_name
);
647 if (!pe_header
.opthdr
.BaseOfCode
)
648 pe_header
.opthdr
.BaseOfCode
= addr
;
652 #ifndef TCC_TARGET_X86_64
653 if (!pe_header
.opthdr
.BaseOfData
)
654 pe_header
.opthdr
.BaseOfData
= addr
;
662 pe_set_datadir(&pe_header
, IMAGE_DIRECTORY_ENTRY_BASERELOC
, addr
, size
);
666 pe_set_datadir(&pe_header
, IMAGE_DIRECTORY_ENTRY_RESOURCE
, addr
, size
);
670 pe_set_datadir(&pe_header
, IMAGE_DIRECTORY_ENTRY_EXCEPTION
, addr
, size
);
675 pe_set_datadir(&pe_header
, IMAGE_DIRECTORY_ENTRY_IMPORT
,
676 pe
->imp_offs
, pe
->imp_size
);
677 pe_set_datadir(&pe_header
, IMAGE_DIRECTORY_ENTRY_IAT
,
678 pe
->iat_offs
, pe
->iat_size
);
681 pe_set_datadir(&pe_header
, IMAGE_DIRECTORY_ENTRY_EXPORT
,
682 pe
->exp_offs
, pe
->exp_size
);
685 memcpy(psh
->Name
, sh_name
, umin(strlen(sh_name
), sizeof psh
->Name
));
687 psh
->Characteristics
= si
->pe_flags
;
688 psh
->VirtualAddress
= addr
;
689 psh
->Misc
.VirtualSize
= size
;
690 pe_header
.opthdr
.SizeOfImage
=
691 umax(pe_virtual_align(pe
, size
+ addr
), pe_header
.opthdr
.SizeOfImage
);
694 psh
->PointerToRawData
= file_offset
;
695 file_offset
= pe_file_align(pe
, file_offset
+ si
->data_size
);
696 psh
->SizeOfRawData
= file_offset
- psh
->PointerToRawData
;
697 if (si
->cls
== sec_text
)
698 pe_header
.opthdr
.SizeOfCode
+= psh
->SizeOfRawData
;
700 pe_header
.opthdr
.SizeOfInitializedData
+= psh
->SizeOfRawData
;
704 //pe_header.filehdr.TimeDateStamp = time(NULL);
705 pe_header
.filehdr
.NumberOfSections
= pe
->sec_count
;
706 pe_header
.opthdr
.AddressOfEntryPoint
= pe
->start_addr
;
707 pe_header
.opthdr
.SizeOfHeaders
= pe
->sizeofheaders
;
708 pe_header
.opthdr
.ImageBase
= pe
->imagebase
;
709 pe_header
.opthdr
.Subsystem
= pe
->subsystem
;
710 if (pe
->s1
->pe_stack_size
)
711 pe_header
.opthdr
.SizeOfStackReserve
= pe
->s1
->pe_stack_size
;
712 if (PE_DLL
== pe
->type
)
713 pe_header
.filehdr
.Characteristics
= CHARACTERISTICS_DLL
;
714 pe_header
.filehdr
.Characteristics
|= pe
->s1
->pe_characteristics
;
716 pe_fwrite(&pe_header
, sizeof pe_header
, &pf
);
717 for (i
= 0; i
< pe
->sec_count
; ++i
)
718 pe_fwrite(&pe
->sec_info
[i
]->ish
, sizeof(IMAGE_SECTION_HEADER
), &pf
);
720 file_offset
= pe
->sizeofheaders
;
721 for (i
= 0; i
< pe
->sec_count
; ++i
) {
723 si
= pe
->sec_info
[i
];
724 for (s
= si
->sec
; s
; s
= s
->prev
) {
725 pe_fpad(&pf
, file_offset
);
726 pe_fwrite(s
->data
, s
->data_offset
, &pf
);
728 file_offset
+= s
->prev
->sh_addr
- s
->sh_addr
;
730 file_offset
= si
->ish
.PointerToRawData
+ si
->ish
.SizeOfRawData
;
731 pe_fpad(&pf
, file_offset
);
734 pf
.sum
+= file_offset
;
735 fseek(pf
.op
, offsetof(struct pe_header
, opthdr
.CheckSum
), SEEK_SET
);
736 pe_fwrite(&pf
.sum
, sizeof (DWORD
), &pf
);
740 chmod(pe
->filename
, 0777);
743 if (2 == pe
->s1
->verbose
)
744 printf("-------------------------------\n");
746 printf("<- %s (%u bytes)\n", pe
->filename
, (unsigned)file_offset
);
751 /*----------------------------------------------------------------------------*/
753 static struct import_symbol
*pe_add_import(struct pe_info
*pe
, int sym_index
)
757 struct pe_import_info
*p
;
758 struct import_symbol
*s
;
761 isym
= (ElfW(Sym
) *)pe
->s1
->dynsymtab_section
->data
+ sym_index
;
762 dll_index
= isym
->st_size
;
764 i
= dynarray_assoc ((void**)pe
->imp_info
, pe
->imp_count
, dll_index
);
769 p
= tcc_mallocz(sizeof *p
);
770 p
->dll_index
= dll_index
;
771 dynarray_add(&pe
->imp_info
, &pe
->imp_count
, p
);
774 i
= dynarray_assoc ((void**)p
->symbols
, p
->sym_count
, sym_index
);
776 return p
->symbols
[i
];
778 s
= tcc_mallocz(sizeof *s
);
779 dynarray_add(&p
->symbols
, &p
->sym_count
, s
);
780 s
->sym_index
= sym_index
;
784 void pe_free_imports(struct pe_info
*pe
)
787 for (i
= 0; i
< pe
->imp_count
; ++i
) {
788 struct pe_import_info
*p
= pe
->imp_info
[i
];
789 dynarray_reset(&p
->symbols
, &p
->sym_count
);
791 dynarray_reset(&pe
->imp_info
, &pe
->imp_count
);
794 /*----------------------------------------------------------------------------*/
795 static void pe_build_imports(struct pe_info
*pe
)
797 int thk_ptr
, ent_ptr
, dll_ptr
, sym_cnt
, i
;
798 DWORD rva_base
= pe
->thunk
->sh_addr
- pe
->imagebase
;
799 int ndlls
= pe
->imp_count
;
800 TCCState
*s1
= pe
->s1
;
802 for (sym_cnt
= i
= 0; i
< ndlls
; ++i
)
803 sym_cnt
+= pe
->imp_info
[i
]->sym_count
;
808 pe_align_section(pe
->thunk
, 16);
809 pe
->imp_size
= (ndlls
+ 1) * sizeof(IMAGE_IMPORT_DESCRIPTOR
);
810 pe
->iat_size
= (sym_cnt
+ ndlls
) * sizeof(ADDR3264
);
811 dll_ptr
= pe
->thunk
->data_offset
;
812 thk_ptr
= dll_ptr
+ pe
->imp_size
;
813 ent_ptr
= thk_ptr
+ pe
->iat_size
;
814 pe
->imp_offs
= dll_ptr
+ rva_base
;
815 pe
->iat_offs
= thk_ptr
+ rva_base
;
816 section_ptr_add(pe
->thunk
, pe
->imp_size
+ 2*pe
->iat_size
);
818 for (i
= 0; i
< pe
->imp_count
; ++i
) {
819 IMAGE_IMPORT_DESCRIPTOR
*hdr
;
822 struct pe_import_info
*p
= pe
->imp_info
[i
];
824 DLLReference
*dllref
;
826 dllindex
= p
->dll_index
;
828 name
= (dllref
= pe
->s1
->loaded_dlls
[dllindex
-1])->name
;
830 name
= "", dllref
= NULL
;
832 /* put the dll name into the import header */
833 v
= put_elf_str(pe
->thunk
, name
);
834 hdr
= (IMAGE_IMPORT_DESCRIPTOR
*)(pe
->thunk
->data
+ dll_ptr
);
835 hdr
->FirstThunk
= thk_ptr
+ rva_base
;
836 hdr
->OriginalFirstThunk
= ent_ptr
+ rva_base
;
837 hdr
->Name
= v
+ rva_base
;
839 for (k
= 0, n
= p
->sym_count
; k
<= n
; ++k
) {
841 int iat_index
= p
->symbols
[k
]->iat_index
;
842 int sym_index
= p
->symbols
[k
]->sym_index
;
843 ElfW(Sym
) *imp_sym
= (ElfW(Sym
) *)pe
->s1
->dynsymtab_section
->data
+ sym_index
;
844 ElfW(Sym
) *org_sym
= (ElfW(Sym
) *)symtab_section
->data
+ iat_index
;
845 const char *name
= (char*)pe
->s1
->dynsymtab_section
->link
->data
+ imp_sym
->st_name
;
848 org_sym
->st_value
= thk_ptr
;
849 org_sym
->st_shndx
= pe
->thunk
->sh_num
;
852 v
= 0, ordinal
= imp_sym
->st_value
; /* ordinal from pe_load_def */
854 ordinal
= 0, v
= imp_sym
->st_value
; /* address from tcc_add_symbol() */
857 if (pe
->type
== PE_RUN
) {
859 if ( !dllref
->handle
)
860 dllref
->handle
= LoadLibrary(dllref
->name
);
861 v
= (ADDR3264
)GetProcAddress(dllref
->handle
, ordinal
?(char*)0+ordinal
:name
);
864 tcc_error_noabort("could not resolve symbol '%s'", name
);
868 v
= ordinal
| (ADDR3264
)1 << (sizeof(ADDR3264
)*8 - 1);
870 v
= pe
->thunk
->data_offset
+ rva_base
;
871 section_ptr_add(pe
->thunk
, sizeof(WORD
)); /* hint, not used */
872 put_elf_str(pe
->thunk
, name
);
876 v
= 0; /* last entry is zero */
879 *(ADDR3264
*)(pe
->thunk
->data
+thk_ptr
) =
880 *(ADDR3264
*)(pe
->thunk
->data
+ent_ptr
) = v
;
881 thk_ptr
+= sizeof (ADDR3264
);
882 ent_ptr
+= sizeof (ADDR3264
);
884 dll_ptr
+= sizeof(IMAGE_IMPORT_DESCRIPTOR
);
888 /* ------------------------------------------------------------- */
896 static int sym_cmp(const void *va
, const void *vb
)
898 const char *ca
= (*(struct pe_sort_sym
**)va
)->name
;
899 const char *cb
= (*(struct pe_sort_sym
**)vb
)->name
;
900 return strcmp(ca
, cb
);
903 static void pe_build_exports(struct pe_info
*pe
)
906 int sym_index
, sym_end
;
907 DWORD rva_base
, base_o
, func_o
, name_o
, ord_o
, str_o
;
908 IMAGE_EXPORT_DIRECTORY
*hdr
;
910 struct pe_sort_sym
**sorted
, *p
;
911 TCCState
*s1
= pe
->s1
;
918 rva_base
= pe
->thunk
->sh_addr
- pe
->imagebase
;
919 sym_count
= 0, sorted
= NULL
, op
= NULL
;
921 sym_end
= symtab_section
->data_offset
/ sizeof(ElfW(Sym
));
922 for (sym_index
= 1; sym_index
< sym_end
; ++sym_index
) {
923 sym
= (ElfW(Sym
)*)symtab_section
->data
+ sym_index
;
924 name
= pe_export_name(pe
->s1
, sym
);
925 if ((sym
->st_other
& ST_PE_EXPORT
)
926 /* export only symbols from actually written sections */
927 && pe
->s1
->sections
[sym
->st_shndx
]->sh_addr
) {
928 p
= tcc_malloc(sizeof *p
);
929 p
->index
= sym_index
;
931 dynarray_add(&sorted
, &sym_count
, p
);
934 if (sym
->st_other
& ST_PE_EXPORT
)
935 printf("export: %s\n", name
);
936 if (sym
->st_other
& ST_PE_STDCALL
)
937 printf("stdcall: %s\n", name
);
944 qsort (sorted
, sym_count
, sizeof *sorted
, sym_cmp
);
946 pe_align_section(pe
->thunk
, 16);
947 dllname
= tcc_basename(pe
->filename
);
949 base_o
= pe
->thunk
->data_offset
;
950 func_o
= base_o
+ sizeof(IMAGE_EXPORT_DIRECTORY
);
951 name_o
= func_o
+ sym_count
* sizeof (DWORD
);
952 ord_o
= name_o
+ sym_count
* sizeof (DWORD
);
953 str_o
= ord_o
+ sym_count
* sizeof(WORD
);
955 hdr
= section_ptr_add(pe
->thunk
, str_o
- base_o
);
956 hdr
->Characteristics
= 0;
958 hdr
->NumberOfFunctions
= sym_count
;
959 hdr
->NumberOfNames
= sym_count
;
960 hdr
->AddressOfFunctions
= func_o
+ rva_base
;
961 hdr
->AddressOfNames
= name_o
+ rva_base
;
962 hdr
->AddressOfNameOrdinals
= ord_o
+ rva_base
;
963 hdr
->Name
= str_o
+ rva_base
;
964 put_elf_str(pe
->thunk
, dllname
);
967 /* automatically write exports to <output-filename>.def */
968 pstrcpy(buf
, sizeof buf
, pe
->filename
);
969 strcpy(tcc_fileextension(buf
), ".def");
970 op
= fopen(buf
, "wb");
972 tcc_error_noabort("could not create '%s': %s", buf
, strerror(errno
));
974 fprintf(op
, "LIBRARY %s\n\nEXPORTS\n", dllname
);
976 printf("<- %s (%d symbol%s)\n", buf
, sym_count
, &"s"[sym_count
< 2]);
980 for (ord
= 0; ord
< sym_count
; ++ord
)
982 p
= sorted
[ord
], sym_index
= p
->index
, name
= p
->name
;
983 /* insert actual address later in relocate_section() */
984 put_elf_reloc(symtab_section
, pe
->thunk
,
985 func_o
, R_XXX_RELATIVE
, sym_index
);
986 *(DWORD
*)(pe
->thunk
->data
+ name_o
)
987 = pe
->thunk
->data_offset
+ rva_base
;
988 *(WORD
*)(pe
->thunk
->data
+ ord_o
)
990 put_elf_str(pe
->thunk
, name
);
991 func_o
+= sizeof (DWORD
);
992 name_o
+= sizeof (DWORD
);
993 ord_o
+= sizeof (WORD
);
995 fprintf(op
, "%s\n", name
);
998 pe
->exp_offs
= base_o
+ rva_base
;
999 pe
->exp_size
= pe
->thunk
->data_offset
- base_o
;
1000 dynarray_reset(&sorted
, &sym_count
);
1005 /* ------------------------------------------------------------- */
1006 static void pe_build_reloc (struct pe_info
*pe
)
1008 DWORD offset
, block_ptr
, sh_addr
, addr
;
1010 ElfW_Rel
*rel
, *rel_end
;
1011 Section
*s
= NULL
, *sr
;
1012 struct pe_reloc_header
*hdr
;
1014 sh_addr
= offset
= block_ptr
= count
= i
= 0;
1015 rel
= rel_end
= NULL
;
1018 if (rel
< rel_end
) {
1019 int type
= ELFW(R_TYPE
)(rel
->r_info
);
1020 addr
= rel
->r_offset
+ sh_addr
;
1022 if (type
!= REL_TYPE_DIRECT
)
1024 if (count
== 0) { /* new block */
1025 block_ptr
= pe
->reloc
->data_offset
;
1026 section_ptr_add(pe
->reloc
, sizeof(struct pe_reloc_header
));
1027 offset
= addr
& 0xFFFFFFFF<<12;
1029 if ((addr
-= offset
) < (1<<12)) { /* one block spans 4k addresses */
1030 WORD
*wp
= section_ptr_add(pe
->reloc
, sizeof (WORD
));
1031 *wp
= addr
| PE_IMAGE_REL
<<12;
1040 rel
= (ElfW_Rel
*)sr
->data
;
1041 rel_end
= (ElfW_Rel
*)(sr
->data
+ sr
->data_offset
);
1042 sh_addr
= s
->sh_addr
;
1047 } else if (i
< pe
->sec_count
) {
1048 s
= pe
->sec_info
[i
]->sec
, ++i
;
1054 /* fill the last block and ready for a new one */
1055 if (count
& 1) /* align for DWORDS */
1056 section_ptr_add(pe
->reloc
, sizeof(WORD
)), ++count
;
1057 hdr
= (struct pe_reloc_header
*)(pe
->reloc
->data
+ block_ptr
);
1058 hdr
-> offset
= offset
- pe
->imagebase
;
1059 hdr
-> size
= count
* sizeof(WORD
) + sizeof(struct pe_reloc_header
);
1064 /* ------------------------------------------------------------- */
1065 static int pe_section_class(Section
*s
)
1071 flags
= s
->sh_flags
;
1073 if (flags
& SHF_ALLOC
) {
1074 if (type
== SHT_PROGBITS
) {
1075 if (flags
& SHF_EXECINSTR
)
1077 if (flags
& SHF_WRITE
)
1079 if (0 == strcmp(name
, ".rsrc"))
1081 if (0 == strcmp(name
, ".iedat"))
1083 if (0 == strcmp(name
, ".pdata"))
1085 } else if (type
== SHT_NOBITS
) {
1086 if (flags
& SHF_WRITE
)
1090 if (0 == strcmp(name
, ".reloc"))
1093 if (0 == memcmp(name
, ".stab", 5))
1094 return name
[5] ? sec_stabstr
: sec_stab
;
1095 if (flags
& SHF_ALLOC
)
1100 static int pe_assign_addresses (struct pe_info
*pe
)
1105 struct section_info
*si
;
1108 if (PE_DLL
== pe
->type
)
1109 pe
->reloc
= new_section(pe
->s1
, ".reloc", SHT_PROGBITS
, 0);
1110 // pe->thunk = new_section(pe->s1, ".iedat", SHT_PROGBITS, SHF_ALLOC);
1112 section_order
= tcc_malloc(pe
->s1
->nb_sections
* sizeof (int));
1113 for (o
= k
= 0 ; k
< sec_last
; ++k
) {
1114 for (i
= 1; i
< pe
->s1
->nb_sections
; ++i
) {
1115 s
= pe
->s1
->sections
[i
];
1116 if (k
== pe_section_class(s
))
1117 section_order
[o
++] = i
;
1122 addr
= pe
->imagebase
+ 1;
1124 for (i
= 0; i
< o
; ++i
) {
1125 k
= section_order
[i
];
1126 s
= pe
->s1
->sections
[k
];
1127 c
= pe_section_class(s
);
1129 if ((c
== sec_stab
|| c
== sec_stabstr
) && 0 == pe
->s1
->do_debug
)
1132 #ifdef PE_MERGE_DATA
1136 if (si
&& c
== si
->cls
) {
1137 /* merge with previous section */
1138 s
->sh_addr
= addr
= ((addr
- 1) | (16 - 1)) + 1;
1141 s
->sh_addr
= addr
= pe_virtual_align(pe
, addr
);
1144 if (c
== sec_data
&& NULL
== pe
->thunk
)
1147 if (s
== pe
->thunk
) {
1148 pe_build_imports(pe
);
1149 pe_build_exports(pe
);
1152 pe_build_reloc (pe
);
1154 if (0 == s
->data_offset
)
1160 si
= tcc_mallocz(sizeof *si
);
1161 dynarray_add(&pe
->sec_info
, &pe
->sec_count
, si
);
1163 strcpy(si
->name
, s
->name
);
1167 si
->pe_flags
= IMAGE_SCN_MEM_READ
;
1168 if (s
->sh_flags
& SHF_EXECINSTR
)
1169 si
->pe_flags
|= IMAGE_SCN_MEM_EXECUTE
| IMAGE_SCN_CNT_CODE
;
1170 else if (s
->sh_type
== SHT_NOBITS
)
1171 si
->pe_flags
|= IMAGE_SCN_CNT_UNINITIALIZED_DATA
;
1173 si
->pe_flags
|= IMAGE_SCN_CNT_INITIALIZED_DATA
;
1174 if (s
->sh_flags
& SHF_WRITE
)
1175 si
->pe_flags
|= IMAGE_SCN_MEM_WRITE
;
1176 if (0 == (s
->sh_flags
& SHF_ALLOC
))
1177 si
->pe_flags
|= IMAGE_SCN_MEM_DISCARDABLE
;
1180 addr
+= s
->data_offset
;
1181 si
->sh_size
= addr
- si
->sh_addr
;
1182 if (s
->sh_type
!= SHT_NOBITS
) {
1183 Section
**ps
= &si
->sec
;
1186 *ps
= s
, s
->prev
= NULL
;
1187 si
->data_size
= si
->sh_size
;
1189 //printf("%08x %05x %08x %s\n", si->sh_addr, si->sh_size, si->pe_flags, s->name);
1191 tcc_free(section_order
);
1193 for (i
= 1; i
< pe
->s1
->nb_sections
; ++i
) {
1194 Section
*s
= pe
->s1
->sections
[i
];
1195 int type
= s
->sh_type
;
1196 int flags
= s
->sh_flags
;
1197 printf("section %-16s %-10s %08x %04x %s,%s,%s\n",
1199 type
== SHT_PROGBITS
? "progbits" :
1200 type
== SHT_NOBITS
? "nobits" :
1201 type
== SHT_SYMTAB
? "symtab" :
1202 type
== SHT_STRTAB
? "strtab" :
1203 type
== SHT_RELX
? "rel" : "???",
1206 flags
& SHF_ALLOC
? "alloc" : "",
1207 flags
& SHF_WRITE
? "write" : "",
1208 flags
& SHF_EXECINSTR
? "exec" : ""
1211 pe
->s1
->verbose
= 2;
1216 /*----------------------------------------------------------------------------*/
1218 static int pe_isafunc(TCCState
*s1
, int sym_index
)
1220 Section
*sr
= text_section
->reloc
;
1221 ElfW_Rel
*rel
, *rel_end
;
1222 Elf32_Word info
= ELF32_R_INFO(sym_index
, R_386_PC32
);
1225 rel_end
= (ElfW_Rel
*)(sr
->data
+ sr
->data_offset
);
1226 for (rel
= (ElfW_Rel
*)sr
->data
; rel
< rel_end
; rel
++)
1227 if (rel
->r_info
== info
)
1232 /*----------------------------------------------------------------------------*/
1233 static int pe_check_symbols(struct pe_info
*pe
)
1236 int sym_index
, sym_end
;
1238 TCCState
*s1
= pe
->s1
;
1240 pe_align_section(text_section
, 8);
1242 sym_end
= symtab_section
->data_offset
/ sizeof(ElfW(Sym
));
1243 for (sym_index
= 1; sym_index
< sym_end
; ++sym_index
) {
1245 sym
= (ElfW(Sym
) *)symtab_section
->data
+ sym_index
;
1246 if (sym
->st_shndx
== SHN_UNDEF
) {
1248 const char *name
= (char*)symtab_section
->link
->data
+ sym
->st_name
;
1249 unsigned type
= ELFW(ST_TYPE
)(sym
->st_info
);
1250 int imp_sym
= pe_find_import(pe
->s1
, sym
);
1251 struct import_symbol
*is
;
1256 if (type
== STT_NOTYPE
) {
1257 /* symbols from assembler have no type, find out which */
1258 if (pe_isafunc(s1
, sym_index
))
1264 is
= pe_add_import(pe
, imp_sym
);
1266 if (type
== STT_FUNC
) {
1267 unsigned long offset
= is
->thk_offset
;
1269 /* got aliased symbol, like stricmp and _stricmp */
1275 offset
= text_section
->data_offset
;
1276 /* add the 'jmp IAT[x]' instruction */
1277 #ifdef TCC_TARGET_ARM
1278 p
= section_ptr_add(text_section
, 8+4); // room for code and address
1279 (*(DWORD
*)(p
)) = 0xE59FC000; // arm code ldr ip, [pc] ; PC+8+0 = 0001xxxx
1280 (*(DWORD
*)(p
+2)) = 0xE59CF000; // arm code ldr pc, [ip]
1282 p
= section_ptr_add(text_section
, 8);
1284 #ifdef TCC_TARGET_X86_64
1285 *(DWORD
*)(p
+1) = (DWORD
)-4;
1288 /* add a helper symbol, will be patched later in
1290 sprintf(buffer
, "IAT.%s", name
);
1291 is
->iat_index
= put_elf_sym(
1292 symtab_section
, 0, sizeof(DWORD
),
1293 ELFW(ST_INFO
)(STB_GLOBAL
, STT_OBJECT
),
1294 0, SHN_UNDEF
, buffer
);
1295 #ifdef TCC_TARGET_ARM
1296 put_elf_reloc(symtab_section
, text_section
,
1297 offset
+ 8, R_XXX_THUNKFIX
, is
->iat_index
); // offset to IAT position
1299 put_elf_reloc(symtab_section
, text_section
,
1300 offset
+ 2, R_XXX_THUNKFIX
, is
->iat_index
);
1302 is
->thk_offset
= offset
;
1305 /* tcc_realloc might have altered sym's address */
1306 sym
= (ElfW(Sym
) *)symtab_section
->data
+ sym_index
;
1308 /* patch the original symbol */
1309 sym
->st_value
= offset
;
1310 sym
->st_shndx
= text_section
->sh_num
;
1311 sym
->st_other
&= ~ST_PE_EXPORT
; /* do not export */
1315 if (type
== STT_OBJECT
) { /* data, ptr to that should be */
1316 if (0 == is
->iat_index
) {
1317 /* original symbol will be patched later in pe_build_imports */
1318 is
->iat_index
= sym_index
;
1324 if (ELFW(ST_BIND
)(sym
->st_info
) == STB_WEAK
)
1325 /* STB_WEAK undefined symbols are accepted */
1327 tcc_error_noabort("undefined symbol '%s'%s", name
,
1328 imp_sym
< 0 ? ", missing __declspec(dllimport)?":"");
1331 } else if (pe
->s1
->rdynamic
1332 && ELFW(ST_BIND
)(sym
->st_info
) != STB_LOCAL
) {
1333 /* if -rdynamic option, then export all non local symbols */
1334 sym
->st_other
|= ST_PE_EXPORT
;
1340 /*----------------------------------------------------------------------------*/
1341 #ifdef PE_PRINT_SECTIONS
1342 static void pe_print_section(FILE * f
, Section
* s
)
1344 /* just if you're curious */
1348 e
= s
->data
+ s
->data_offset
;
1351 fprintf(f
, "section \"%s\"", s
->name
);
1353 fprintf(f
, "\nlink \"%s\"", s
->link
->name
);
1355 fprintf(f
, "\nreloc \"%s\"", s
->reloc
->name
);
1356 fprintf(f
, "\nv_addr %08X", (unsigned)s
->sh_addr
);
1357 fprintf(f
, "\ncontents %08X", (unsigned)l
);
1360 if (s
->sh_type
== SHT_NOBITS
)
1366 if (s
->sh_type
== SHT_SYMTAB
)
1367 m
= sizeof(ElfW(Sym
));
1368 else if (s
->sh_type
== SHT_RELX
)
1369 m
= sizeof(ElfW_Rel
);
1373 fprintf(f
, "%-8s", "offset");
1374 for (i
= 0; i
< m
; ++i
)
1375 fprintf(f
, " %02x", i
);
1378 if (s
->sh_type
== SHT_SYMTAB
|| s
->sh_type
== SHT_RELX
) {
1379 const char *fields1
[] = {
1390 const char *fields2
[] = {
1399 if (s
->sh_type
== SHT_SYMTAB
)
1400 p
= fields1
, n
= 106;
1402 p
= fields2
, n
= 58;
1404 for (i
= 0; p
[i
]; ++i
)
1405 fprintf(f
, "%6s", p
[i
]);
1406 fprintf(f
, " symbol");
1410 for (i
= 0; i
< n
; ++i
)
1416 fprintf(f
, "%08X", i
);
1417 for (n
= 0; n
< m
; ++n
) {
1419 fprintf(f
, " %02X", p
[i
+ n
]);
1424 if (s
->sh_type
== SHT_SYMTAB
) {
1425 ElfW(Sym
) *sym
= (ElfW(Sym
) *) (p
+ i
);
1426 const char *name
= s
->link
->data
+ sym
->st_name
;
1427 fprintf(f
, " %04X %04X %04X %02X %02X %02X %04X \"%s\"",
1428 (unsigned)sym
->st_name
,
1429 (unsigned)sym
->st_value
,
1430 (unsigned)sym
->st_size
,
1431 (unsigned)ELFW(ST_BIND
)(sym
->st_info
),
1432 (unsigned)ELFW(ST_TYPE
)(sym
->st_info
),
1433 (unsigned)sym
->st_other
,
1434 (unsigned)sym
->st_shndx
,
1437 } else if (s
->sh_type
== SHT_RELX
) {
1438 ElfW_Rel
*rel
= (ElfW_Rel
*) (p
+ i
);
1440 (ElfW(Sym
) *) s
->link
->data
+ ELFW(R_SYM
)(rel
->r_info
);
1441 const char *name
= s
->link
->link
->data
+ sym
->st_name
;
1442 fprintf(f
, " %04X %02X %04X \"%s\"",
1443 (unsigned)rel
->r_offset
,
1444 (unsigned)ELFW(R_TYPE
)(rel
->r_info
),
1445 (unsigned)ELFW(R_SYM
)(rel
->r_info
),
1449 for (n
= 0; n
< m
; ++n
) {
1452 if (b
< 32 || b
>= 127)
1454 fprintf(f
, "%c", b
);
1464 static void pe_print_sections(TCCState
*s1
, const char *fname
)
1469 f
= fopen(fname
, "w");
1470 for (i
= 1; i
< s1
->nb_sections
; ++i
) {
1471 s
= s1
->sections
[i
];
1472 pe_print_section(f
, s
);
1474 pe_print_section(f
, s1
->dynsymtab_section
);
1479 /* ------------------------------------------------------------- */
1480 /* helper function for load/store to insert one more indirection */
1482 #if defined TCC_TARGET_I386 || defined TCC_TARGET_X86_64
1483 ST_FUNC SValue
*pe_getimport(SValue
*sv
, SValue
*v2
)
1486 if ((sv
->r
& (VT_VALMASK
|VT_SYM
)) != (VT_CONST
|VT_SYM
) || (sv
->r2
!= VT_CONST
))
1488 if (!sv
->sym
->a
.dllimport
)
1490 // printf("import %04x %04x %04x %s\n", sv->type.t, sv->sym->type.t, sv->r, get_tok_str(sv->sym->v, NULL));
1491 memset(v2
, 0, sizeof *v2
);
1492 v2
->type
.t
= VT_PTR
;
1493 v2
->r
= VT_CONST
| VT_SYM
| VT_LVAL
;
1496 r2
= get_reg(RC_INT
);
1499 if ((uint32_t)sv
->c
.i
) {
1505 v2
->type
.t
= sv
->type
.t
;
1506 v2
->r
|= sv
->r
& VT_LVAL
;
1511 ST_FUNC
int pe_putimport(TCCState
*s1
, int dllindex
, const char *name
, addr_t value
)
1514 s1
->dynsymtab_section
,
1516 dllindex
, /* st_size */
1517 ELFW(ST_INFO
)(STB_GLOBAL
, STT_NOTYPE
),
1519 value
? SHN_ABS
: SHN_UNDEF
,
1524 static int add_dllref(TCCState
*s1
, const char *dllname
)
1526 DLLReference
*dllref
;
1528 for (i
= 0; i
< s1
->nb_loaded_dlls
; ++i
)
1529 if (0 == strcmp(s1
->loaded_dlls
[i
]->name
, dllname
))
1531 dllref
= tcc_mallocz(sizeof(DLLReference
) + strlen(dllname
));
1532 strcpy(dllref
->name
, dllname
);
1533 dynarray_add(&s1
->loaded_dlls
, &s1
->nb_loaded_dlls
, dllref
);
1534 return s1
->nb_loaded_dlls
;
1537 /* ------------------------------------------------------------- */
1539 static int read_mem(int fd
, unsigned offset
, void *buffer
, unsigned len
)
1541 lseek(fd
, offset
, SEEK_SET
);
1542 return len
== read(fd
, buffer
, len
);
1545 /* ------------------------------------------------------------- */
1547 PUB_FUNC
int tcc_get_dllexports(const char *filename
, char **pp
)
1549 int l
, i
, n
, n0
, ret
;
1553 IMAGE_SECTION_HEADER ish
;
1554 IMAGE_EXPORT_DIRECTORY ied
;
1555 IMAGE_DOS_HEADER dh
;
1556 IMAGE_FILE_HEADER ih
;
1557 DWORD sig
, ref
, addr
, ptr
, namep
;
1559 int pef_hdroffset
, opt_hdroffset
, sec_hdroffset
;
1565 fd
= open(filename
, O_RDONLY
| O_BINARY
);
1569 if (!read_mem(fd
, 0, &dh
, sizeof dh
))
1571 if (!read_mem(fd
, dh
.e_lfanew
, &sig
, sizeof sig
))
1573 if (sig
!= 0x00004550)
1575 pef_hdroffset
= dh
.e_lfanew
+ sizeof sig
;
1576 if (!read_mem(fd
, pef_hdroffset
, &ih
, sizeof ih
))
1578 opt_hdroffset
= pef_hdroffset
+ sizeof ih
;
1579 if (ih
.Machine
== 0x014C) {
1580 IMAGE_OPTIONAL_HEADER32 oh
;
1581 sec_hdroffset
= opt_hdroffset
+ sizeof oh
;
1582 if (!read_mem(fd
, opt_hdroffset
, &oh
, sizeof oh
))
1584 if (IMAGE_DIRECTORY_ENTRY_EXPORT
>= oh
.NumberOfRvaAndSizes
)
1586 addr
= oh
.DataDirectory
[IMAGE_DIRECTORY_ENTRY_EXPORT
].VirtualAddress
;
1587 } else if (ih
.Machine
== 0x8664) {
1588 IMAGE_OPTIONAL_HEADER64 oh
;
1589 sec_hdroffset
= opt_hdroffset
+ sizeof oh
;
1590 if (!read_mem(fd
, opt_hdroffset
, &oh
, sizeof oh
))
1592 if (IMAGE_DIRECTORY_ENTRY_EXPORT
>= oh
.NumberOfRvaAndSizes
)
1594 addr
= oh
.DataDirectory
[IMAGE_DIRECTORY_ENTRY_EXPORT
].VirtualAddress
;
1598 //printf("addr: %08x\n", addr);
1599 for (i
= 0; i
< ih
.NumberOfSections
; ++i
) {
1600 if (!read_mem(fd
, sec_hdroffset
+ i
* sizeof ish
, &ish
, sizeof ish
))
1602 //printf("vaddr: %08x\n", ish.VirtualAddress);
1603 if (addr
>= ish
.VirtualAddress
&& addr
< ish
.VirtualAddress
+ ish
.SizeOfRawData
)
1609 ref
= ish
.VirtualAddress
- ish
.PointerToRawData
;
1610 if (!read_mem(fd
, addr
- ref
, &ied
, sizeof ied
))
1613 namep
= ied
.AddressOfNames
- ref
;
1614 for (i
= 0; i
< ied
.NumberOfNames
; ++i
) {
1615 if (!read_mem(fd
, namep
, &ptr
, sizeof ptr
))
1617 namep
+= sizeof ptr
;
1620 p
= tcc_realloc(p
, n0
= n0
? n0
* 2 : 256);
1621 if (!read_mem(fd
, ptr
- ref
+ l
++, p
+ n
, 1)) {
1622 tcc_free(p
), p
= NULL
;
1640 /* -------------------------------------------------------------
1641 * This is for compiled windows resources in 'coff' format
1642 * as generated by 'windres.exe -O coff ...'.
1645 static int pe_load_res(TCCState
*s1
, int fd
)
1647 struct pe_rsrc_header hdr
;
1648 Section
*rsrc_section
;
1649 int i
, ret
= -1, sym_index
;
1653 if (!read_mem(fd
, 0, &hdr
, sizeof hdr
))
1656 if (hdr
.filehdr
.Machine
!= IMAGE_FILE_MACHINE
1657 || hdr
.filehdr
.NumberOfSections
!= 1
1658 || strcmp((char*)hdr
.sectionhdr
.Name
, ".rsrc") != 0)
1661 rsrc_section
= new_section(s1
, ".rsrc", SHT_PROGBITS
, SHF_ALLOC
);
1662 ptr
= section_ptr_add(rsrc_section
, hdr
.sectionhdr
.SizeOfRawData
);
1663 offs
= hdr
.sectionhdr
.PointerToRawData
;
1664 if (!read_mem(fd
, offs
, ptr
, hdr
.sectionhdr
.SizeOfRawData
))
1666 offs
= hdr
.sectionhdr
.PointerToRelocations
;
1667 sym_index
= put_elf_sym(symtab_section
, 0, 0, 0, 0, rsrc_section
->sh_num
, ".rsrc");
1668 for (i
= 0; i
< hdr
.sectionhdr
.NumberOfRelocations
; ++i
) {
1669 struct pe_rsrc_reloc rel
;
1670 if (!read_mem(fd
, offs
, &rel
, sizeof rel
))
1672 // printf("rsrc_reloc: %x %x %x\n", rel.offset, rel.size, rel.type);
1673 if (rel
.type
!= RSRC_RELTYPE
)
1675 put_elf_reloc(symtab_section
, rsrc_section
,
1676 rel
.offset
, R_XXX_RELATIVE
, sym_index
);
1684 /* ------------------------------------------------------------- */
1686 static char *trimfront(char *p
)
1688 while (*p
&& (unsigned char)*p
<= ' ')
1693 static char *trimback(char *a
, char *e
)
1695 while (e
> a
&& (unsigned char)e
[-1] <= ' ')
1701 /* ------------------------------------------------------------- */
1702 static int pe_load_def(TCCState
*s1
, int fd
)
1704 int state
= 0, ret
= -1, dllindex
= 0, ord
;
1705 char line
[400], dllname
[80], *p
, *x
;
1708 fp
= fdopen(dup(fd
), "rb");
1709 while (fgets(line
, sizeof line
, fp
))
1711 p
= trimfront(trimback(line
, strchr(line
, 0)));
1712 if (0 == *p
|| ';' == *p
)
1717 if (0 != strnicmp(p
, "LIBRARY", 7))
1719 pstrcpy(dllname
, sizeof dllname
, trimfront(p
+7));
1724 if (0 != stricmp(p
, "EXPORTS"))
1730 dllindex
= add_dllref(s1
, dllname
);
1734 /* get ordinal and will store in sym->st_value */
1738 *x
= 0, x
= strrchr(x
+ 1, '@');
1741 ord
= (int)strtol(x
+ 1, &d
, 10);
1746 pe_putimport(s1
, dllindex
, p
, ord
);
1756 /* ------------------------------------------------------------- */
1757 static int pe_load_dll(TCCState
*s1
, const char *filename
)
1762 ret
= tcc_get_dllexports(filename
, &p
);
1766 index
= add_dllref(s1
, tcc_basename(filename
));
1767 for (q
= p
; *q
; q
+= 1 + strlen(q
))
1768 pe_putimport(s1
, index
, q
, 0);
1774 /* ------------------------------------------------------------- */
1775 ST_FUNC
int pe_load_file(struct TCCState
*s1
, const char *filename
, int fd
)
1779 if (0 == strcmp(tcc_fileextension(filename
), ".def"))
1780 ret
= pe_load_def(s1
, fd
);
1781 else if (pe_load_res(s1
, fd
) == 0)
1783 else if (read_mem(fd
, 0, buf
, 4) && 0 == memcmp(buf
, "MZ", 2))
1784 ret
= pe_load_dll(s1
, filename
);
1788 /* ------------------------------------------------------------- */
1789 #ifdef TCC_TARGET_X86_64
1790 static unsigned pe_add_uwwind_info(TCCState
*s1
)
1792 if (NULL
== s1
->uw_pdata
) {
1793 s1
->uw_pdata
= find_section(s1
, ".pdata");
1794 s1
->uw_pdata
->sh_addralign
= 4;
1796 if (0 == s1
->uw_sym
)
1797 s1
->uw_sym
= put_elf_sym(symtab_section
, 0, 0, 0, 0, text_section
->sh_num
, ".uw_base");
1798 if (0 == s1
->uw_offs
) {
1799 /* As our functions all have the same stackframe, we use one entry for all */
1800 static const unsigned char uw_info
[] = {
1801 0x01, // UBYTE: 3 Version , UBYTE: 5 Flags
1802 0x04, // UBYTE Size of prolog
1803 0x02, // UBYTE Count of unwind codes
1804 0x05, // UBYTE: 4 Frame Register (rbp), UBYTE: 4 Frame Register offset (scaled)
1805 // USHORT * n Unwind codes array
1806 // 0x0b, 0x01, 0xff, 0xff, // stack size
1807 0x04, 0x03, // set frame ptr (mov rsp -> rbp)
1808 0x01, 0x50 // push reg (rbp)
1811 Section
*s
= text_section
;
1814 section_ptr_add(s
, -s
->data_offset
& 3); /* align */
1815 s1
->uw_offs
= s
->data_offset
;
1816 p
= section_ptr_add(s
, sizeof uw_info
);
1817 memcpy(p
, uw_info
, sizeof uw_info
);
1823 ST_FUNC
void pe_add_unwind_data(unsigned start
, unsigned end
, unsigned stack
)
1825 TCCState
*s1
= tcc_state
;
1828 struct /* _RUNTIME_FUNCTION */ {
1834 d
= pe_add_uwwind_info(s1
);
1836 o
= pd
->data_offset
;
1837 p
= section_ptr_add(pd
, sizeof *p
);
1839 /* record this function */
1840 p
->BeginAddress
= start
;
1841 p
->EndAddress
= end
;
1844 /* put relocations on it */
1845 for (n
= o
+ sizeof *p
; o
< n
; o
+= sizeof p
->BeginAddress
)
1846 put_elf_reloc(symtab_section
, pd
, o
, R_XXX_RELATIVE
, s1
->uw_sym
);
1849 /* ------------------------------------------------------------- */
1850 #ifdef TCC_TARGET_X86_64
1851 #define PE_STDSYM(n,s) n
1853 #define PE_STDSYM(n,s) "_" n s
1856 static void tcc_add_support(TCCState
*s1
, const char *filename
)
1858 if (tcc_add_dll(s1
, filename
, 0) < 0)
1859 tcc_error_noabort("%s not found", filename
);
1862 static void pe_add_runtime(TCCState
*s1
, struct pe_info
*pe
)
1864 const char *start_symbol
;
1866 int unicode_entry
= 0;
1868 if (find_elf_sym(symtab_section
, PE_STDSYM("WinMain","@16")))
1871 if (find_elf_sym(symtab_section
, PE_STDSYM("wWinMain","@16"))) {
1873 unicode_entry
= PE_GUI
;
1876 if (TCC_OUTPUT_DLL
== s1
->output_type
) {
1881 if (find_elf_sym(symtab_section
, "wmain"))
1882 unicode_entry
= PE_EXE
;
1886 TCC_OUTPUT_MEMORY
== s1
->output_type
1887 ? PE_GUI
== pe_type
? (unicode_entry
? "__runwwinmain" : "__runwinmain")
1888 : (unicode_entry
? "__runwmain" : "__runmain")
1889 : PE_DLL
== pe_type
? PE_STDSYM("__dllstart","@12")
1890 : PE_GUI
== pe_type
? (unicode_entry
? "__wwinstart": "__winstart")
1891 : (unicode_entry
? "__wstart" : "__start")
1894 if (!s1
->leading_underscore
|| strchr(start_symbol
, '@'))
1897 #ifdef CONFIG_TCC_BACKTRACE
1898 if (s1
->do_backtrace
) {
1899 #ifdef CONFIG_TCC_BCHECK
1900 if (s1
->do_bounds_check
&& s1
->output_type
!= TCC_OUTPUT_DLL
)
1901 tcc_add_support(s1
, "bcheck.o");
1903 if (s1
->output_type
== TCC_OUTPUT_EXE
)
1904 tcc_add_support(s1
, "bt-exe.o");
1905 if (s1
->output_type
== TCC_OUTPUT_DLL
)
1906 tcc_add_support(s1
, "bt-dll.o");
1907 if (s1
->output_type
!= TCC_OUTPUT_DLL
)
1908 tcc_add_support(s1
, "bt-log.o");
1909 if (s1
->output_type
!= TCC_OUTPUT_MEMORY
)
1914 /* grab the startup code from libtcc1.a */
1915 #ifdef TCC_IS_NATIVE
1916 if (TCC_OUTPUT_MEMORY
!= s1
->output_type
|| s1
->runtime_main
)
1918 set_global_sym(s1
, start_symbol
, NULL
, 0);
1920 if (0 == s1
->nostdlib
) {
1921 static const char *libs
[] = {
1922 "msvcrt", "kernel32", "", "user32", "gdi32", NULL
1924 const char **pp
, *p
;
1925 tcc_add_support(s1
, TCC_LIBTCC1
);
1926 for (pp
= libs
; 0 != (p
= *pp
); ++pp
) {
1928 tcc_add_library_err(s1
, p
);
1929 else if (PE_DLL
!= pe_type
&& PE_GUI
!= pe_type
)
1934 /* need this for 'tccelf.c:relocate_section()' */
1935 if (TCC_OUTPUT_DLL
== s1
->output_type
)
1936 s1
->output_type
= TCC_OUTPUT_EXE
;
1937 if (TCC_OUTPUT_MEMORY
== s1
->output_type
)
1940 pe
->start_symbol
= start_symbol
;
1943 static void pe_set_options(TCCState
* s1
, struct pe_info
*pe
)
1945 if (PE_DLL
== pe
->type
) {
1946 /* XXX: check if is correct for arm-pe target */
1947 pe
->imagebase
= 0x10000000;
1949 #if defined(TCC_TARGET_ARM)
1950 pe
->imagebase
= 0x00010000;
1952 pe
->imagebase
= 0x00400000;
1956 #if defined(TCC_TARGET_ARM)
1957 /* we use "console" subsystem by default */
1960 if (PE_DLL
== pe
->type
|| PE_GUI
== pe
->type
)
1965 /* Allow override via -Wl,-subsystem=... option */
1966 if (s1
->pe_subsystem
!= 0)
1967 pe
->subsystem
= s1
->pe_subsystem
;
1969 /* set default file/section alignment */
1970 if (pe
->subsystem
== 1) {
1971 pe
->section_align
= 0x20;
1972 pe
->file_align
= 0x20;
1974 pe
->section_align
= 0x1000;
1975 pe
->file_align
= 0x200;
1978 if (s1
->section_align
!= 0)
1979 pe
->section_align
= s1
->section_align
;
1980 if (s1
->pe_file_align
!= 0)
1981 pe
->file_align
= s1
->pe_file_align
;
1983 if ((pe
->subsystem
>= 10) && (pe
->subsystem
<= 12))
1986 if (s1
->has_text_addr
)
1987 pe
->imagebase
= s1
->text_addr
;
1990 ST_FUNC
int pe_output_file(TCCState
*s1
, const char *filename
)
1996 memset(&pe
, 0, sizeof pe
);
1997 pe
.filename
= filename
;
2001 #ifdef CONFIG_TCC_BCHECK
2004 tcc_add_pragma_libs(s1
);
2005 pe_add_runtime(s1
, &pe
);
2006 resolve_common_syms(s1
);
2007 pe_set_options(s1
, &pe
);
2009 ret
= pe_check_symbols(&pe
);
2012 else if (filename
) {
2013 pe_assign_addresses(&pe
);
2014 relocate_syms(s1
, s1
->symtab
, 0);
2015 s1
->pe_imagebase
= pe
.imagebase
;
2016 for (i
= 1; i
< s1
->nb_sections
; ++i
) {
2017 Section
*s
= s1
->sections
[i
];
2019 relocate_section(s1
, s
);
2022 pe
.start_addr
= (DWORD
)
2023 ((uintptr_t)tcc_get_symbol_err(s1
, pe
.start_symbol
)
2028 ret
= pe_write(&pe
);
2029 dynarray_reset(&pe
.sec_info
, &pe
.sec_count
);
2031 #ifdef TCC_IS_NATIVE
2032 pe
.thunk
= data_section
;
2033 pe_build_imports(&pe
);
2034 s1
->runtime_main
= pe
.start_symbol
;
2035 #ifdef TCC_TARGET_X86_64
2036 s1
->uw_pdata
= find_section(s1
, ".pdata");
2041 pe_free_imports(&pe
);
2043 #ifdef PE_PRINT_SECTIONS
2044 pe_print_sections(s1
, "tcc.log");
2049 /* ------------------------------------------------------------- */