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
;
606 op
= fopen(pe
->filename
, "wb");
608 tcc_error_noabort("could not write '%s': %s", pe
->filename
, strerror(errno
));
612 pe
->sizeofheaders
= pe_file_align(pe
,
613 sizeof (struct pe_header
)
614 + pe
->sec_count
* sizeof (IMAGE_SECTION_HEADER
)
617 file_offset
= pe
->sizeofheaders
;
619 if (2 == pe
->s1
->verbose
)
620 printf("-------------------------------"
621 "\n virt file size section" "\n");
622 for (i
= 0; i
< pe
->sec_count
; ++i
) {
626 si
= pe
->sec_info
+ i
;
628 addr
= si
->sh_addr
- pe
->imagebase
;
632 if (2 == pe
->s1
->verbose
)
633 printf("%6x %6x %6x %s\n",
634 (unsigned)addr
, (unsigned)file_offset
, (unsigned)size
, sh_name
);
638 pe_header
.opthdr
.BaseOfCode
= addr
;
642 #ifndef TCC_TARGET_X86_64
643 pe_header
.opthdr
.BaseOfData
= addr
;
651 pe_set_datadir(&pe_header
, IMAGE_DIRECTORY_ENTRY_BASERELOC
, addr
, size
);
655 pe_set_datadir(&pe_header
, IMAGE_DIRECTORY_ENTRY_RESOURCE
, addr
, size
);
659 pe_set_datadir(&pe_header
, IMAGE_DIRECTORY_ENTRY_EXCEPTION
, addr
, size
);
663 if (pe
->thunk
== pe
->s1
->sections
[si
->ord
]) {
665 pe_set_datadir(&pe_header
, IMAGE_DIRECTORY_ENTRY_IMPORT
,
666 pe
->imp_offs
+ addr
, pe
->imp_size
);
667 pe_set_datadir(&pe_header
, IMAGE_DIRECTORY_ENTRY_IAT
,
668 pe
->iat_offs
+ addr
, pe
->iat_size
);
671 pe_set_datadir(&pe_header
, IMAGE_DIRECTORY_ENTRY_EXPORT
,
672 pe
->exp_offs
+ addr
, pe
->exp_size
);
676 strncpy((char*)psh
->Name
, sh_name
, sizeof psh
->Name
);
678 psh
->Characteristics
= si
->pe_flags
;
679 psh
->VirtualAddress
= addr
;
680 psh
->Misc
.VirtualSize
= size
;
681 pe_header
.opthdr
.SizeOfImage
=
682 umax(pe_virtual_align(pe
, size
+ addr
), pe_header
.opthdr
.SizeOfImage
);
685 psh
->PointerToRawData
= file_offset
;
686 file_offset
= pe_file_align(pe
, file_offset
+ si
->data_size
);
687 psh
->SizeOfRawData
= file_offset
- psh
->PointerToRawData
;
688 if (si
->cls
== sec_text
)
689 pe_header
.opthdr
.SizeOfCode
+= psh
->SizeOfRawData
;
691 pe_header
.opthdr
.SizeOfInitializedData
+= psh
->SizeOfRawData
;
695 //pe_header.filehdr.TimeDateStamp = time(NULL);
696 pe_header
.filehdr
.NumberOfSections
= pe
->sec_count
;
697 pe_header
.opthdr
.AddressOfEntryPoint
= pe
->start_addr
;
698 pe_header
.opthdr
.SizeOfHeaders
= pe
->sizeofheaders
;
699 pe_header
.opthdr
.ImageBase
= pe
->imagebase
;
700 pe_header
.opthdr
.Subsystem
= pe
->subsystem
;
701 if (pe
->s1
->pe_stack_size
)
702 pe_header
.opthdr
.SizeOfStackReserve
= pe
->s1
->pe_stack_size
;
703 if (PE_DLL
== pe
->type
)
704 pe_header
.filehdr
.Characteristics
= CHARACTERISTICS_DLL
;
705 pe_header
.filehdr
.Characteristics
|= pe
->s1
->pe_characteristics
;
708 pe_fwrite(&pe_header
, sizeof pe_header
, op
, &sum
);
709 for (i
= 0; i
< pe
->sec_count
; ++i
)
710 pe_fwrite(&pe
->sec_info
[i
].ish
, sizeof(IMAGE_SECTION_HEADER
), op
, &sum
);
711 pe_fpad(op
, pe
->sizeofheaders
);
712 for (i
= 0; i
< pe
->sec_count
; ++i
) {
713 si
= pe
->sec_info
+ i
;
716 pe_fwrite(si
->data
, si
->data_size
, op
, &sum
);
717 file_offset
= psh
->PointerToRawData
+ psh
->SizeOfRawData
;
718 pe_fpad(op
, file_offset
);
722 pe_header
.opthdr
.CheckSum
= sum
+ file_offset
;
723 fseek(op
, offsetof(struct pe_header
, opthdr
.CheckSum
), SEEK_SET
);
724 pe_fwrite(&pe_header
.opthdr
.CheckSum
, sizeof pe_header
.opthdr
.CheckSum
, op
, NULL
);
727 chmod(pe
->filename
, 0777);
730 if (2 == pe
->s1
->verbose
)
731 printf("-------------------------------\n");
733 printf("<- %s (%u bytes)\n", pe
->filename
, (unsigned)file_offset
);
738 /*----------------------------------------------------------------------------*/
740 static struct import_symbol
*pe_add_import(struct pe_info
*pe
, int sym_index
)
744 struct pe_import_info
*p
;
745 struct import_symbol
*s
;
748 isym
= (ElfW(Sym
) *)pe
->s1
->dynsymtab_section
->data
+ sym_index
;
749 dll_index
= isym
->st_size
;
751 i
= dynarray_assoc ((void**)pe
->imp_info
, pe
->imp_count
, dll_index
);
756 p
= tcc_mallocz(sizeof *p
);
757 p
->dll_index
= dll_index
;
758 dynarray_add(&pe
->imp_info
, &pe
->imp_count
, p
);
761 i
= dynarray_assoc ((void**)p
->symbols
, p
->sym_count
, sym_index
);
763 return p
->symbols
[i
];
765 s
= tcc_mallocz(sizeof *s
);
766 dynarray_add(&p
->symbols
, &p
->sym_count
, s
);
767 s
->sym_index
= sym_index
;
771 void pe_free_imports(struct pe_info
*pe
)
774 for (i
= 0; i
< pe
->imp_count
; ++i
) {
775 struct pe_import_info
*p
= pe
->imp_info
[i
];
776 dynarray_reset(&p
->symbols
, &p
->sym_count
);
778 dynarray_reset(&pe
->imp_info
, &pe
->imp_count
);
781 /*----------------------------------------------------------------------------*/
782 static void pe_build_imports(struct pe_info
*pe
)
784 int thk_ptr
, ent_ptr
, dll_ptr
, sym_cnt
, i
;
785 DWORD rva_base
= pe
->thunk
->sh_addr
- pe
->imagebase
;
786 int ndlls
= pe
->imp_count
;
788 for (sym_cnt
= i
= 0; i
< ndlls
; ++i
)
789 sym_cnt
+= pe
->imp_info
[i
]->sym_count
;
794 pe_align_section(pe
->thunk
, 16);
796 pe
->imp_offs
= dll_ptr
= pe
->thunk
->data_offset
;
797 pe
->imp_size
= (ndlls
+ 1) * sizeof(IMAGE_IMPORT_DESCRIPTOR
);
798 pe
->iat_offs
= dll_ptr
+ pe
->imp_size
;
799 pe
->iat_size
= (sym_cnt
+ ndlls
) * sizeof(ADDR3264
);
800 section_ptr_add(pe
->thunk
, pe
->imp_size
+ 2*pe
->iat_size
);
802 thk_ptr
= pe
->iat_offs
;
803 ent_ptr
= pe
->iat_offs
+ pe
->iat_size
;
805 for (i
= 0; i
< pe
->imp_count
; ++i
) {
806 IMAGE_IMPORT_DESCRIPTOR
*hdr
;
809 struct pe_import_info
*p
= pe
->imp_info
[i
];
811 DLLReference
*dllref
;
813 dllindex
= p
->dll_index
;
815 name
= (dllref
= pe
->s1
->loaded_dlls
[dllindex
-1])->name
;
817 name
= "", dllref
= NULL
;
819 /* put the dll name into the import header */
820 v
= put_elf_str(pe
->thunk
, name
);
821 hdr
= (IMAGE_IMPORT_DESCRIPTOR
*)(pe
->thunk
->data
+ dll_ptr
);
822 hdr
->FirstThunk
= thk_ptr
+ rva_base
;
823 hdr
->OriginalFirstThunk
= ent_ptr
+ rva_base
;
824 hdr
->Name
= v
+ rva_base
;
826 for (k
= 0, n
= p
->sym_count
; k
<= n
; ++k
) {
828 int iat_index
= p
->symbols
[k
]->iat_index
;
829 int sym_index
= p
->symbols
[k
]->sym_index
;
830 ElfW(Sym
) *imp_sym
= (ElfW(Sym
) *)pe
->s1
->dynsymtab_section
->data
+ sym_index
;
831 ElfW(Sym
) *org_sym
= (ElfW(Sym
) *)symtab_section
->data
+ iat_index
;
832 const char *name
= (char*)pe
->s1
->dynsymtab_section
->link
->data
+ imp_sym
->st_name
;
835 org_sym
->st_value
= thk_ptr
;
836 org_sym
->st_shndx
= pe
->thunk
->sh_num
;
839 v
= 0, ordinal
= imp_sym
->st_value
; /* ordinal from pe_load_def */
841 ordinal
= 0, v
= imp_sym
->st_value
; /* address from tcc_add_symbol() */
844 if (pe
->type
== PE_RUN
) {
846 if ( !dllref
->handle
)
847 dllref
->handle
= LoadLibrary(dllref
->name
);
848 v
= (ADDR3264
)GetProcAddress(dllref
->handle
, ordinal
?(char*)0+ordinal
:name
);
851 tcc_error_noabort("can't build symbol '%s'", name
);
855 v
= ordinal
| (ADDR3264
)1 << (sizeof(ADDR3264
)*8 - 1);
857 v
= pe
->thunk
->data_offset
+ rva_base
;
858 section_ptr_add(pe
->thunk
, sizeof(WORD
)); /* hint, not used */
859 put_elf_str(pe
->thunk
, name
);
863 v
= 0; /* last entry is zero */
866 *(ADDR3264
*)(pe
->thunk
->data
+thk_ptr
) =
867 *(ADDR3264
*)(pe
->thunk
->data
+ent_ptr
) = v
;
868 thk_ptr
+= sizeof (ADDR3264
);
869 ent_ptr
+= sizeof (ADDR3264
);
871 dll_ptr
+= sizeof(IMAGE_IMPORT_DESCRIPTOR
);
875 /* ------------------------------------------------------------- */
883 static int sym_cmp(const void *va
, const void *vb
)
885 const char *ca
= (*(struct pe_sort_sym
**)va
)->name
;
886 const char *cb
= (*(struct pe_sort_sym
**)vb
)->name
;
887 return strcmp(ca
, cb
);
890 static void pe_build_exports(struct pe_info
*pe
)
893 int sym_index
, sym_end
;
894 DWORD rva_base
, func_o
, name_o
, ord_o
, str_o
;
895 IMAGE_EXPORT_DIRECTORY
*hdr
;
897 struct pe_sort_sym
**sorted
, *p
;
904 rva_base
= pe
->thunk
->sh_addr
- pe
->imagebase
;
905 sym_count
= 0, sorted
= NULL
, op
= NULL
;
907 sym_end
= symtab_section
->data_offset
/ sizeof(ElfW(Sym
));
908 for (sym_index
= 1; sym_index
< sym_end
; ++sym_index
) {
909 sym
= (ElfW(Sym
)*)symtab_section
->data
+ sym_index
;
910 name
= pe_export_name(pe
->s1
, sym
);
911 if ((sym
->st_other
& ST_PE_EXPORT
)
912 /* export only symbols from actually written sections */
913 && pe
->s1
->sections
[sym
->st_shndx
]->sh_addr
) {
914 p
= tcc_malloc(sizeof *p
);
915 p
->index
= sym_index
;
917 dynarray_add(&sorted
, &sym_count
, p
);
920 if (sym
->st_other
& ST_PE_EXPORT
)
921 printf("export: %s\n", name
);
922 if (sym
->st_other
& ST_PE_STDCALL
)
923 printf("stdcall: %s\n", name
);
930 qsort (sorted
, sym_count
, sizeof *sorted
, sym_cmp
);
932 pe_align_section(pe
->thunk
, 16);
933 dllname
= tcc_basename(pe
->filename
);
935 pe
->exp_offs
= pe
->thunk
->data_offset
;
936 func_o
= pe
->exp_offs
+ sizeof(IMAGE_EXPORT_DIRECTORY
);
937 name_o
= func_o
+ sym_count
* sizeof (DWORD
);
938 ord_o
= name_o
+ sym_count
* sizeof (DWORD
);
939 str_o
= ord_o
+ sym_count
* sizeof(WORD
);
941 hdr
= section_ptr_add(pe
->thunk
, str_o
- pe
->exp_offs
);
942 hdr
->Characteristics
= 0;
944 hdr
->NumberOfFunctions
= sym_count
;
945 hdr
->NumberOfNames
= sym_count
;
946 hdr
->AddressOfFunctions
= func_o
+ rva_base
;
947 hdr
->AddressOfNames
= name_o
+ rva_base
;
948 hdr
->AddressOfNameOrdinals
= ord_o
+ rva_base
;
949 hdr
->Name
= str_o
+ rva_base
;
950 put_elf_str(pe
->thunk
, dllname
);
953 /* automatically write exports to <output-filename>.def */
954 pstrcpy(buf
, sizeof buf
, pe
->filename
);
955 strcpy(tcc_fileextension(buf
), ".def");
956 op
= fopen(buf
, "wb");
958 tcc_error_noabort("could not create '%s': %s", buf
, strerror(errno
));
960 fprintf(op
, "LIBRARY %s\n\nEXPORTS\n", dllname
);
962 printf("<- %s (%d symbol%s)\n", buf
, sym_count
, &"s"[sym_count
< 2]);
966 for (ord
= 0; ord
< sym_count
; ++ord
)
968 p
= sorted
[ord
], sym_index
= p
->index
, name
= p
->name
;
969 /* insert actual address later in relocate_section() */
970 put_elf_reloc(symtab_section
, pe
->thunk
,
971 func_o
, R_XXX_RELATIVE
, sym_index
);
972 *(DWORD
*)(pe
->thunk
->data
+ name_o
)
973 = pe
->thunk
->data_offset
+ rva_base
;
974 *(WORD
*)(pe
->thunk
->data
+ ord_o
)
976 put_elf_str(pe
->thunk
, name
);
977 func_o
+= sizeof (DWORD
);
978 name_o
+= sizeof (DWORD
);
979 ord_o
+= sizeof (WORD
);
981 fprintf(op
, "%s\n", name
);
983 pe
->exp_size
= pe
->thunk
->data_offset
- pe
->exp_offs
;
984 dynarray_reset(&sorted
, &sym_count
);
989 /* ------------------------------------------------------------- */
990 static void pe_build_reloc (struct pe_info
*pe
)
992 DWORD offset
, block_ptr
, addr
;
994 ElfW_Rel
*rel
, *rel_end
;
995 Section
*s
= NULL
, *sr
;
997 offset
= addr
= block_ptr
= count
= i
= 0;
998 rel
= rel_end
= NULL
;
1001 if (rel
< rel_end
) {
1002 int type
= ELFW(R_TYPE
)(rel
->r_info
);
1003 addr
= rel
->r_offset
+ s
->sh_addr
;
1005 if (type
!= REL_TYPE_DIRECT
)
1007 if (count
== 0) { /* new block */
1008 block_ptr
= pe
->reloc
->data_offset
;
1009 section_ptr_add(pe
->reloc
, sizeof(struct pe_reloc_header
));
1010 offset
= addr
& 0xFFFFFFFF<<12;
1012 if ((addr
-= offset
) < (1<<12)) { /* one block spans 4k addresses */
1013 WORD
*wp
= section_ptr_add(pe
->reloc
, sizeof (WORD
));
1014 *wp
= addr
| PE_IMAGE_REL
<<12;
1020 } else if (i
< pe
->sec_count
) {
1021 sr
= (s
= pe
->s1
->sections
[pe
->sec_info
[i
++].ord
])->reloc
;
1023 rel
= (ElfW_Rel
*)sr
->data
;
1024 rel_end
= (ElfW_Rel
*)(sr
->data
+ sr
->data_offset
);
1030 /* store the last block and ready for a new one */
1031 struct pe_reloc_header
*hdr
;
1032 if (count
& 1) /* align for DWORDS */
1033 section_ptr_add(pe
->reloc
, sizeof(WORD
)), ++count
;
1034 hdr
= (struct pe_reloc_header
*)(pe
->reloc
->data
+ block_ptr
);
1035 hdr
-> offset
= offset
- pe
->imagebase
;
1036 hdr
-> size
= count
* sizeof(WORD
) + sizeof(struct pe_reloc_header
);
1045 /* ------------------------------------------------------------- */
1046 static int pe_section_class(Section
*s
)
1052 flags
= s
->sh_flags
;
1054 if (flags
& SHF_ALLOC
) {
1055 if (type
== SHT_PROGBITS
) {
1056 if (flags
& SHF_EXECINSTR
)
1058 if (flags
& SHF_WRITE
)
1060 if (0 == strcmp(name
, ".rsrc"))
1062 if (0 == strcmp(name
, ".iedat"))
1064 if (0 == strcmp(name
, ".pdata"))
1066 } else if (type
== SHT_NOBITS
) {
1067 if (flags
& SHF_WRITE
)
1072 if (0 == strcmp(name
, ".reloc"))
1074 if (0 == memcmp(name
, ".stab", 5))
1080 static int pe_assign_addresses (struct pe_info
*pe
)
1085 struct section_info
*si
;
1088 if (PE_DLL
== pe
->type
)
1089 pe
->reloc
= new_section(pe
->s1
, ".reloc", SHT_PROGBITS
, 0);
1091 // pe->thunk = new_section(pe->s1, ".iedat", SHT_PROGBITS, SHF_ALLOC);
1093 section_order
= tcc_malloc(pe
->s1
->nb_sections
* sizeof (int));
1094 for (o
= k
= 0 ; k
< sec_last
; ++k
) {
1095 for (i
= 1; i
< pe
->s1
->nb_sections
; ++i
) {
1096 s
= pe
->s1
->sections
[i
];
1097 if (k
== pe_section_class(s
)) {
1098 // printf("%s %d\n", s->name, k);
1099 s
->sh_addr
= pe
->imagebase
;
1100 section_order
[o
++] = i
;
1105 pe
->sec_info
= tcc_mallocz(o
* sizeof (struct section_info
));
1106 addr
= pe
->imagebase
+ 1;
1108 for (i
= 0; i
< o
; ++i
)
1110 k
= section_order
[i
];
1111 s
= pe
->s1
->sections
[k
];
1112 c
= pe_section_class(s
);
1113 si
= &pe
->sec_info
[pe
->sec_count
];
1115 #ifdef PE_MERGE_DATA
1116 if (c
== sec_bss
&& pe
->sec_count
&& si
[-1].cls
== sec_data
) {
1117 /* append .bss to .data */
1118 s
->sh_addr
= addr
= ((addr
-1) | (s
->sh_addralign
-1)) + 1;
1119 addr
+= s
->data_offset
;
1120 si
[-1].sh_size
= addr
- si
[-1].sh_addr
;
1124 if (c
== sec_stab
&& 0 == pe
->s1
->do_debug
)
1127 strcpy(si
->name
, s
->name
);
1130 si
->sh_addr
= s
->sh_addr
= addr
= pe_virtual_align(pe
, addr
);
1132 si
->pe_flags
= IMAGE_SCN_MEM_READ
;
1133 if (s
->sh_flags
& SHF_EXECINSTR
)
1134 si
->pe_flags
|= IMAGE_SCN_MEM_EXECUTE
| IMAGE_SCN_CNT_CODE
;
1135 else if (s
->sh_type
== SHT_NOBITS
)
1136 si
->pe_flags
|= IMAGE_SCN_CNT_UNINITIALIZED_DATA
;
1138 si
->pe_flags
|= IMAGE_SCN_CNT_INITIALIZED_DATA
;
1139 if (s
->sh_flags
& SHF_WRITE
)
1140 si
->pe_flags
|= IMAGE_SCN_MEM_WRITE
;
1141 if (0 == (s
->sh_flags
& SHF_ALLOC
)) {
1142 si
->pe_flags
|= IMAGE_SCN_MEM_DISCARDABLE
;
1144 si
->pe_flags
|= 0x802; //IMAGE_SCN_TYPE_NOLOAD|IMAGE_SCN_LNK_REMOVE
1147 if (c
== sec_data
&& NULL
== pe
->thunk
)
1150 if (s
== pe
->thunk
) {
1151 pe_build_imports(pe
);
1152 pe_build_exports(pe
);
1156 pe_build_reloc (pe
);
1160 if (s
->sh_type
!= SHT_NOBITS
) {
1162 si
->data_size
= s
->data_offset
;
1165 addr
+= s
->data_offset
;
1166 si
->sh_size
= s
->data_offset
;
1169 //printf("%08x %05x %s %08x\n", si->sh_addr, si->sh_size, si->name, si->pe_flags);
1172 for (i
= 1; i
< pe
->s1
->nb_sections
; ++i
) {
1173 Section
*s
= pe
->s1
->sections
[i
];
1174 int type
= s
->sh_type
;
1175 int flags
= s
->sh_flags
;
1176 printf("section %-16s %-10s %5x %s,%s,%s\n",
1178 type
== SHT_PROGBITS
? "progbits" :
1179 type
== SHT_NOBITS
? "nobits" :
1180 type
== SHT_SYMTAB
? "symtab" :
1181 type
== SHT_STRTAB
? "strtab" :
1182 type
== SHT_RELX
? "rel" : "???",
1184 flags
& SHF_ALLOC
? "alloc" : "",
1185 flags
& SHF_WRITE
? "write" : "",
1186 flags
& SHF_EXECINSTR
? "exec" : ""
1189 pe
->s1
->verbose
= 2;
1192 tcc_free(section_order
);
1196 /*----------------------------------------------------------------------------*/
1198 static int pe_isafunc(int sym_index
)
1200 Section
*sr
= text_section
->reloc
;
1201 ElfW_Rel
*rel
, *rel_end
;
1202 Elf32_Word info
= ELF32_R_INFO(sym_index
, R_386_PC32
);
1205 rel_end
= (ElfW_Rel
*)(sr
->data
+ sr
->data_offset
);
1206 for (rel
= (ElfW_Rel
*)sr
->data
; rel
< rel_end
; rel
++)
1207 if (rel
->r_info
== info
)
1212 /*----------------------------------------------------------------------------*/
1213 static int pe_check_symbols(struct pe_info
*pe
)
1216 int sym_index
, sym_end
;
1219 pe_align_section(text_section
, 8);
1221 sym_end
= symtab_section
->data_offset
/ sizeof(ElfW(Sym
));
1222 for (sym_index
= 1; sym_index
< sym_end
; ++sym_index
) {
1224 sym
= (ElfW(Sym
) *)symtab_section
->data
+ sym_index
;
1225 if (sym
->st_shndx
== SHN_UNDEF
) {
1227 const char *name
= (char*)symtab_section
->link
->data
+ sym
->st_name
;
1228 unsigned type
= ELFW(ST_TYPE
)(sym
->st_info
);
1229 int imp_sym
= pe_find_import(pe
->s1
, sym
);
1230 struct import_symbol
*is
;
1235 if (type
== STT_NOTYPE
) {
1236 /* symbols from assembler have no type, find out which */
1237 if (pe_isafunc(sym_index
))
1243 is
= pe_add_import(pe
, imp_sym
);
1245 if (type
== STT_FUNC
) {
1246 unsigned long offset
= is
->thk_offset
;
1248 /* got aliased symbol, like stricmp and _stricmp */
1254 offset
= text_section
->data_offset
;
1255 /* add the 'jmp IAT[x]' instruction */
1256 #ifdef TCC_TARGET_ARM
1257 p
= section_ptr_add(text_section
, 8+4); // room for code and address
1258 (*(DWORD
*)(p
)) = 0xE59FC000; // arm code ldr ip, [pc] ; PC+8+0 = 0001xxxx
1259 (*(DWORD
*)(p
+2)) = 0xE59CF000; // arm code ldr pc, [ip]
1261 p
= section_ptr_add(text_section
, 8);
1263 #ifdef TCC_TARGET_X86_64
1264 *(DWORD
*)(p
+1) = (DWORD
)-4;
1267 /* add a helper symbol, will be patched later in
1269 sprintf(buffer
, "IAT.%s", name
);
1270 is
->iat_index
= put_elf_sym(
1271 symtab_section
, 0, sizeof(DWORD
),
1272 ELFW(ST_INFO
)(STB_GLOBAL
, STT_OBJECT
),
1273 0, SHN_UNDEF
, buffer
);
1274 #ifdef TCC_TARGET_ARM
1275 put_elf_reloc(symtab_section
, text_section
,
1276 offset
+ 8, R_XXX_THUNKFIX
, is
->iat_index
); // offset to IAT position
1278 put_elf_reloc(symtab_section
, text_section
,
1279 offset
+ 2, R_XXX_THUNKFIX
, is
->iat_index
);
1281 is
->thk_offset
= offset
;
1284 /* tcc_realloc might have altered sym's address */
1285 sym
= (ElfW(Sym
) *)symtab_section
->data
+ sym_index
;
1287 /* patch the original symbol */
1288 sym
->st_value
= offset
;
1289 sym
->st_shndx
= text_section
->sh_num
;
1290 sym
->st_other
&= ~ST_PE_EXPORT
; /* do not export */
1294 if (type
== STT_OBJECT
) { /* data, ptr to that should be */
1295 if (0 == is
->iat_index
) {
1296 /* original symbol will be patched later in pe_build_imports */
1297 is
->iat_index
= sym_index
;
1303 if (ELFW(ST_BIND
)(sym
->st_info
) == STB_WEAK
)
1304 /* STB_WEAK undefined symbols are accepted */
1306 tcc_error_noabort("undefined symbol '%s'%s", name
,
1307 imp_sym
< 0 ? ", missing __declspec(dllimport)?":"");
1310 } else if (pe
->s1
->rdynamic
1311 && ELFW(ST_BIND
)(sym
->st_info
) != STB_LOCAL
) {
1312 /* if -rdynamic option, then export all non local symbols */
1313 sym
->st_other
|= ST_PE_EXPORT
;
1319 /*----------------------------------------------------------------------------*/
1320 #ifdef PE_PRINT_SECTIONS
1321 static void pe_print_section(FILE * f
, Section
* s
)
1323 /* just if you're curious */
1327 e
= s
->data
+ s
->data_offset
;
1330 fprintf(f
, "section \"%s\"", s
->name
);
1332 fprintf(f
, "\nlink \"%s\"", s
->link
->name
);
1334 fprintf(f
, "\nreloc \"%s\"", s
->reloc
->name
);
1335 fprintf(f
, "\nv_addr %08X", (unsigned)s
->sh_addr
);
1336 fprintf(f
, "\ncontents %08X", (unsigned)l
);
1339 if (s
->sh_type
== SHT_NOBITS
)
1345 if (s
->sh_type
== SHT_SYMTAB
)
1346 m
= sizeof(ElfW(Sym
));
1347 else if (s
->sh_type
== SHT_RELX
)
1348 m
= sizeof(ElfW_Rel
);
1352 fprintf(f
, "%-8s", "offset");
1353 for (i
= 0; i
< m
; ++i
)
1354 fprintf(f
, " %02x", i
);
1357 if (s
->sh_type
== SHT_SYMTAB
|| s
->sh_type
== SHT_RELX
) {
1358 const char *fields1
[] = {
1369 const char *fields2
[] = {
1378 if (s
->sh_type
== SHT_SYMTAB
)
1379 p
= fields1
, n
= 106;
1381 p
= fields2
, n
= 58;
1383 for (i
= 0; p
[i
]; ++i
)
1384 fprintf(f
, "%6s", p
[i
]);
1385 fprintf(f
, " symbol");
1389 for (i
= 0; i
< n
; ++i
)
1395 fprintf(f
, "%08X", i
);
1396 for (n
= 0; n
< m
; ++n
) {
1398 fprintf(f
, " %02X", p
[i
+ n
]);
1403 if (s
->sh_type
== SHT_SYMTAB
) {
1404 ElfW(Sym
) *sym
= (ElfW(Sym
) *) (p
+ i
);
1405 const char *name
= s
->link
->data
+ sym
->st_name
;
1406 fprintf(f
, " %04X %04X %04X %02X %02X %02X %04X \"%s\"",
1407 (unsigned)sym
->st_name
,
1408 (unsigned)sym
->st_value
,
1409 (unsigned)sym
->st_size
,
1410 (unsigned)ELFW(ST_BIND
)(sym
->st_info
),
1411 (unsigned)ELFW(ST_TYPE
)(sym
->st_info
),
1412 (unsigned)sym
->st_other
,
1413 (unsigned)sym
->st_shndx
,
1416 } else if (s
->sh_type
== SHT_RELX
) {
1417 ElfW_Rel
*rel
= (ElfW_Rel
*) (p
+ i
);
1419 (ElfW(Sym
) *) s
->link
->data
+ ELFW(R_SYM
)(rel
->r_info
);
1420 const char *name
= s
->link
->link
->data
+ sym
->st_name
;
1421 fprintf(f
, " %04X %02X %04X \"%s\"",
1422 (unsigned)rel
->r_offset
,
1423 (unsigned)ELFW(R_TYPE
)(rel
->r_info
),
1424 (unsigned)ELFW(R_SYM
)(rel
->r_info
),
1428 for (n
= 0; n
< m
; ++n
) {
1431 if (b
< 32 || b
>= 127)
1433 fprintf(f
, "%c", b
);
1443 static void pe_print_sections(TCCState
*s1
, const char *fname
)
1448 f
= fopen(fname
, "w");
1449 for (i
= 1; i
< s1
->nb_sections
; ++i
) {
1450 s
= s1
->sections
[i
];
1451 pe_print_section(f
, s
);
1453 pe_print_section(f
, s1
->dynsymtab_section
);
1458 /* ------------------------------------------------------------- */
1459 /* helper function for load/store to insert one more indirection */
1461 #if defined TCC_TARGET_I386 || defined TCC_TARGET_X86_64
1462 ST_FUNC SValue
*pe_getimport(SValue
*sv
, SValue
*v2
)
1465 if ((sv
->r
& (VT_VALMASK
|VT_SYM
)) != (VT_CONST
|VT_SYM
) || (sv
->r2
!= VT_CONST
))
1467 if (!sv
->sym
->a
.dllimport
)
1469 // printf("import %04x %04x %04x %s\n", sv->type.t, sv->sym->type.t, sv->r, get_tok_str(sv->sym->v, NULL));
1470 memset(v2
, 0, sizeof *v2
);
1471 v2
->type
.t
= VT_PTR
;
1472 v2
->r
= VT_CONST
| VT_SYM
| VT_LVAL
;
1475 r2
= get_reg(RC_INT
);
1478 if ((uint32_t)sv
->c
.i
) {
1484 v2
->type
.t
= sv
->type
.t
;
1485 v2
->r
|= sv
->r
& VT_LVAL
;
1490 ST_FUNC
int pe_putimport(TCCState
*s1
, int dllindex
, const char *name
, addr_t value
)
1493 s1
->dynsymtab_section
,
1495 dllindex
, /* st_size */
1496 ELFW(ST_INFO
)(STB_GLOBAL
, STT_NOTYPE
),
1498 value
? SHN_ABS
: SHN_UNDEF
,
1503 static int add_dllref(TCCState
*s1
, const char *dllname
)
1505 DLLReference
*dllref
;
1507 for (i
= 0; i
< s1
->nb_loaded_dlls
; ++i
)
1508 if (0 == strcmp(s1
->loaded_dlls
[i
]->name
, dllname
))
1510 dllref
= tcc_mallocz(sizeof(DLLReference
) + strlen(dllname
));
1511 strcpy(dllref
->name
, dllname
);
1512 dynarray_add(&s1
->loaded_dlls
, &s1
->nb_loaded_dlls
, dllref
);
1513 return s1
->nb_loaded_dlls
;
1516 /* ------------------------------------------------------------- */
1518 static int read_mem(int fd
, unsigned offset
, void *buffer
, unsigned len
)
1520 lseek(fd
, offset
, SEEK_SET
);
1521 return len
== read(fd
, buffer
, len
);
1524 /* ------------------------------------------------------------- */
1526 PUB_FUNC
int tcc_get_dllexports(const char *filename
, char **pp
)
1528 int l
, i
, n
, n0
, ret
;
1532 IMAGE_SECTION_HEADER ish
;
1533 IMAGE_EXPORT_DIRECTORY ied
;
1534 IMAGE_DOS_HEADER dh
;
1535 IMAGE_FILE_HEADER ih
;
1536 DWORD sig
, ref
, addr
, ptr
, namep
;
1538 int pef_hdroffset
, opt_hdroffset
, sec_hdroffset
;
1544 fd
= open(filename
, O_RDONLY
| O_BINARY
);
1548 if (!read_mem(fd
, 0, &dh
, sizeof dh
))
1550 if (!read_mem(fd
, dh
.e_lfanew
, &sig
, sizeof sig
))
1552 if (sig
!= 0x00004550)
1554 pef_hdroffset
= dh
.e_lfanew
+ sizeof sig
;
1555 if (!read_mem(fd
, pef_hdroffset
, &ih
, sizeof ih
))
1557 opt_hdroffset
= pef_hdroffset
+ sizeof ih
;
1558 if (ih
.Machine
== 0x014C) {
1559 IMAGE_OPTIONAL_HEADER32 oh
;
1560 sec_hdroffset
= opt_hdroffset
+ sizeof oh
;
1561 if (!read_mem(fd
, opt_hdroffset
, &oh
, sizeof oh
))
1563 if (IMAGE_DIRECTORY_ENTRY_EXPORT
>= oh
.NumberOfRvaAndSizes
)
1565 addr
= oh
.DataDirectory
[IMAGE_DIRECTORY_ENTRY_EXPORT
].VirtualAddress
;
1566 } else if (ih
.Machine
== 0x8664) {
1567 IMAGE_OPTIONAL_HEADER64 oh
;
1568 sec_hdroffset
= opt_hdroffset
+ sizeof oh
;
1569 if (!read_mem(fd
, opt_hdroffset
, &oh
, sizeof oh
))
1571 if (IMAGE_DIRECTORY_ENTRY_EXPORT
>= oh
.NumberOfRvaAndSizes
)
1573 addr
= oh
.DataDirectory
[IMAGE_DIRECTORY_ENTRY_EXPORT
].VirtualAddress
;
1577 //printf("addr: %08x\n", addr);
1578 for (i
= 0; i
< ih
.NumberOfSections
; ++i
) {
1579 if (!read_mem(fd
, sec_hdroffset
+ i
* sizeof ish
, &ish
, sizeof ish
))
1581 //printf("vaddr: %08x\n", ish.VirtualAddress);
1582 if (addr
>= ish
.VirtualAddress
&& addr
< ish
.VirtualAddress
+ ish
.SizeOfRawData
)
1588 ref
= ish
.VirtualAddress
- ish
.PointerToRawData
;
1589 if (!read_mem(fd
, addr
- ref
, &ied
, sizeof ied
))
1592 namep
= ied
.AddressOfNames
- ref
;
1593 for (i
= 0; i
< ied
.NumberOfNames
; ++i
) {
1594 if (!read_mem(fd
, namep
, &ptr
, sizeof ptr
))
1596 namep
+= sizeof ptr
;
1599 p
= tcc_realloc(p
, n0
= n0
? n0
* 2 : 256);
1600 if (!read_mem(fd
, ptr
- ref
+ l
++, p
+ n
, 1)) {
1601 tcc_free(p
), p
= NULL
;
1619 /* -------------------------------------------------------------
1620 * This is for compiled windows resources in 'coff' format
1621 * as generated by 'windres.exe -O coff ...'.
1624 static int pe_load_res(TCCState
*s1
, int fd
)
1626 struct pe_rsrc_header hdr
;
1627 Section
*rsrc_section
;
1628 int i
, ret
= -1, sym_index
;
1632 if (!read_mem(fd
, 0, &hdr
, sizeof hdr
))
1635 if (hdr
.filehdr
.Machine
!= IMAGE_FILE_MACHINE
1636 || hdr
.filehdr
.NumberOfSections
!= 1
1637 || strcmp((char*)hdr
.sectionhdr
.Name
, ".rsrc") != 0)
1640 rsrc_section
= new_section(s1
, ".rsrc", SHT_PROGBITS
, SHF_ALLOC
);
1641 ptr
= section_ptr_add(rsrc_section
, hdr
.sectionhdr
.SizeOfRawData
);
1642 offs
= hdr
.sectionhdr
.PointerToRawData
;
1643 if (!read_mem(fd
, offs
, ptr
, hdr
.sectionhdr
.SizeOfRawData
))
1645 offs
= hdr
.sectionhdr
.PointerToRelocations
;
1646 sym_index
= put_elf_sym(symtab_section
, 0, 0, 0, 0, rsrc_section
->sh_num
, ".rsrc");
1647 for (i
= 0; i
< hdr
.sectionhdr
.NumberOfRelocations
; ++i
) {
1648 struct pe_rsrc_reloc rel
;
1649 if (!read_mem(fd
, offs
, &rel
, sizeof rel
))
1651 // printf("rsrc_reloc: %x %x %x\n", rel.offset, rel.size, rel.type);
1652 if (rel
.type
!= RSRC_RELTYPE
)
1654 put_elf_reloc(symtab_section
, rsrc_section
,
1655 rel
.offset
, R_XXX_RELATIVE
, sym_index
);
1663 /* ------------------------------------------------------------- */
1665 static char *trimfront(char *p
)
1667 while (*p
&& (unsigned char)*p
<= ' ')
1672 static char *trimback(char *a
, char *e
)
1674 while (e
> a
&& (unsigned char)e
[-1] <= ' ')
1680 /* ------------------------------------------------------------- */
1681 static int pe_load_def(TCCState
*s1
, int fd
)
1683 int state
= 0, ret
= -1, dllindex
= 0, ord
;
1684 char line
[400], dllname
[80], *p
, *x
;
1687 fp
= fdopen(dup(fd
), "rb");
1688 while (fgets(line
, sizeof line
, fp
))
1690 p
= trimfront(trimback(line
, strchr(line
, 0)));
1691 if (0 == *p
|| ';' == *p
)
1696 if (0 != strnicmp(p
, "LIBRARY", 7))
1698 pstrcpy(dllname
, sizeof dllname
, trimfront(p
+7));
1703 if (0 != stricmp(p
, "EXPORTS"))
1709 dllindex
= add_dllref(s1
, dllname
);
1713 /* get ordinal and will store in sym->st_value */
1717 *x
= 0, x
= strrchr(x
+ 1, '@');
1720 ord
= (int)strtol(x
+ 1, &d
, 10);
1725 pe_putimport(s1
, dllindex
, p
, ord
);
1735 /* ------------------------------------------------------------- */
1736 static int pe_load_dll(TCCState
*s1
, const char *filename
)
1741 ret
= tcc_get_dllexports(filename
, &p
);
1745 index
= add_dllref(s1
, tcc_basename(filename
));
1746 for (q
= p
; *q
; q
+= 1 + strlen(q
))
1747 pe_putimport(s1
, index
, q
, 0);
1753 /* ------------------------------------------------------------- */
1754 ST_FUNC
int pe_load_file(struct TCCState
*s1
, const char *filename
, int fd
)
1758 if (0 == strcmp(tcc_fileextension(filename
), ".def"))
1759 ret
= pe_load_def(s1
, fd
);
1760 else if (pe_load_res(s1
, fd
) == 0)
1762 else if (read_mem(fd
, 0, buf
, 4) && 0 == memcmp(buf
, "MZ", 2))
1763 ret
= pe_load_dll(s1
, filename
);
1767 /* ------------------------------------------------------------- */
1768 #ifdef TCC_TARGET_X86_64
1769 static unsigned pe_add_uwwind_info(TCCState
*s1
)
1771 if (NULL
== s1
->uw_pdata
) {
1772 s1
->uw_pdata
= find_section(tcc_state
, ".pdata");
1773 s1
->uw_pdata
->sh_addralign
= 4;
1775 if (0 == s1
->uw_sym
)
1776 s1
->uw_sym
= put_elf_sym(symtab_section
, 0, 0, 0, 0, text_section
->sh_num
, ".uw_base");
1777 if (0 == s1
->uw_offs
) {
1778 /* As our functions all have the same stackframe, we use one entry for all */
1779 static const unsigned char uw_info
[] = {
1780 0x01, // UBYTE: 3 Version , UBYTE: 5 Flags
1781 0x04, // UBYTE Size of prolog
1782 0x02, // UBYTE Count of unwind codes
1783 0x05, // UBYTE: 4 Frame Register (rbp), UBYTE: 4 Frame Register offset (scaled)
1784 // USHORT * n Unwind codes array
1785 // 0x0b, 0x01, 0xff, 0xff, // stack size
1786 0x04, 0x03, // set frame ptr (mov rsp -> rbp)
1787 0x01, 0x50 // push reg (rbp)
1790 Section
*s
= text_section
;
1793 section_ptr_add(s
, -s
->data_offset
& 3); /* align */
1794 s1
->uw_offs
= s
->data_offset
;
1795 p
= section_ptr_add(s
, sizeof uw_info
);
1796 memcpy(p
, uw_info
, sizeof uw_info
);
1802 ST_FUNC
void pe_add_unwind_data(unsigned start
, unsigned end
, unsigned stack
)
1804 TCCState
*s1
= tcc_state
;
1807 struct /* _RUNTIME_FUNCTION */ {
1813 d
= pe_add_uwwind_info(s1
);
1815 o
= pd
->data_offset
;
1816 p
= section_ptr_add(pd
, sizeof *p
);
1818 /* record this function */
1819 p
->BeginAddress
= start
;
1820 p
->EndAddress
= end
;
1823 /* put relocations on it */
1824 for (n
= o
+ sizeof *p
; o
< n
; o
+= sizeof p
->BeginAddress
)
1825 put_elf_reloc(symtab_section
, pd
, o
, R_XXX_RELATIVE
, s1
->uw_sym
);
1828 /* ------------------------------------------------------------- */
1829 #ifdef TCC_TARGET_X86_64
1830 #define PE_STDSYM(n,s) n
1832 #define PE_STDSYM(n,s) "_" n s
1835 static void pe_add_runtime(TCCState
*s1
, struct pe_info
*pe
)
1837 const char *start_symbol
;
1839 int unicode_entry
= 0;
1841 if (find_elf_sym(symtab_section
, PE_STDSYM("WinMain","@16")))
1844 if (find_elf_sym(symtab_section
, PE_STDSYM("wWinMain","@16"))) {
1846 unicode_entry
= PE_GUI
;
1849 if (TCC_OUTPUT_DLL
== s1
->output_type
) {
1851 /* need this for 'tccelf.c:relocate_section()' */
1852 s1
->output_type
= TCC_OUTPUT_EXE
;
1856 if (find_elf_sym(symtab_section
, "wmain"))
1857 unicode_entry
= PE_EXE
;
1861 TCC_OUTPUT_MEMORY
== s1
->output_type
1862 ? PE_GUI
== pe_type
? (unicode_entry
? "__runwwinmain" : "__runwinmain")
1863 : (unicode_entry
? "__runwmain" : "__runmain")
1864 : PE_DLL
== pe_type
? PE_STDSYM("__dllstart","@12")
1865 : PE_GUI
== pe_type
? (unicode_entry
? "__wwinstart": "__winstart")
1866 : (unicode_entry
? "__wstart" : "__start")
1869 if (!s1
->leading_underscore
|| strchr(start_symbol
, '@'))
1872 /* grab the startup code from libtcc1 */
1873 #ifdef TCC_IS_NATIVE
1874 if (TCC_OUTPUT_MEMORY
!= s1
->output_type
|| s1
->runtime_main
)
1876 set_elf_sym(symtab_section
,
1878 ELFW(ST_INFO
)(STB_GLOBAL
, STT_NOTYPE
), 0,
1879 SHN_UNDEF
, start_symbol
);
1881 if (0 == s1
->nostdlib
) {
1882 static const char *libs
[] = {
1883 TCC_LIBTCC1
, "msvcrt", "kernel32", "", "user32", "gdi32", NULL
1885 const char **pp
, *p
;
1886 for (pp
= libs
; 0 != (p
= *pp
); ++pp
) {
1888 if (PE_DLL
!= pe_type
&& PE_GUI
!= pe_type
)
1890 } else if (pp
== libs
&& tcc_add_dll(s1
, p
, 0) >= 0) {
1893 tcc_add_library_err(s1
, p
);
1898 if (TCC_OUTPUT_MEMORY
== s1
->output_type
)
1901 pe
->start_symbol
= start_symbol
;
1904 static void pe_set_options(TCCState
* s1
, struct pe_info
*pe
)
1906 if (PE_DLL
== pe
->type
) {
1907 /* XXX: check if is correct for arm-pe target */
1908 pe
->imagebase
= 0x10000000;
1910 #if defined(TCC_TARGET_ARM)
1911 pe
->imagebase
= 0x00010000;
1913 pe
->imagebase
= 0x00400000;
1917 #if defined(TCC_TARGET_ARM)
1918 /* we use "console" subsystem by default */
1921 if (PE_DLL
== pe
->type
|| PE_GUI
== pe
->type
)
1926 /* Allow override via -Wl,-subsystem=... option */
1927 if (s1
->pe_subsystem
!= 0)
1928 pe
->subsystem
= s1
->pe_subsystem
;
1930 /* set default file/section alignment */
1931 if (pe
->subsystem
== 1) {
1932 pe
->section_align
= 0x20;
1933 pe
->file_align
= 0x20;
1935 pe
->section_align
= 0x1000;
1936 pe
->file_align
= 0x200;
1939 if (s1
->section_align
!= 0)
1940 pe
->section_align
= s1
->section_align
;
1941 if (s1
->pe_file_align
!= 0)
1942 pe
->file_align
= s1
->pe_file_align
;
1944 if ((pe
->subsystem
>= 10) && (pe
->subsystem
<= 12))
1947 if (s1
->has_text_addr
)
1948 pe
->imagebase
= s1
->text_addr
;
1951 ST_FUNC
int pe_output_file(TCCState
*s1
, const char *filename
)
1957 memset(&pe
, 0, sizeof pe
);
1958 pe
.filename
= filename
;
1961 tcc_add_runtime(s1
);
1962 pe_add_runtime(s1
, &pe
);
1963 resolve_common_syms(s1
);
1964 pe_set_options(s1
, &pe
);
1966 ret
= pe_check_symbols(&pe
);
1969 else if (filename
) {
1970 pe_assign_addresses(&pe
);
1971 relocate_syms(s1
, s1
->symtab
, 0);
1972 s1
->pe_imagebase
= pe
.imagebase
;
1973 for (i
= 1; i
< s1
->nb_sections
; ++i
) {
1974 Section
*s
= s1
->sections
[i
];
1976 relocate_section(s1
, s
);
1979 pe
.start_addr
= (DWORD
)
1980 ((uintptr_t)tcc_get_symbol_err(s1
, pe
.start_symbol
)
1985 ret
= pe_write(&pe
);
1986 tcc_free(pe
.sec_info
);
1988 #ifdef TCC_IS_NATIVE
1989 pe
.thunk
= data_section
;
1990 pe_build_imports(&pe
);
1991 s1
->runtime_main
= pe
.start_symbol
;
1992 #ifdef TCC_TARGET_X86_64
1993 s1
->uw_pdata
= find_section(s1
, ".pdata");
1998 pe_free_imports(&pe
);
2000 #ifdef PE_PRINT_SECTIONS
2001 pe_print_sections(s1
, "tcc.log");
2006 /* ------------------------------------------------------------- */