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
31 #ifdef TCC_TARGET_X86_64
32 # define ADDR3264 ULONGLONG
33 # define REL_TYPE_DIRECT R_X86_64_64
34 # define R_XXX_THUNKFIX R_X86_64_PC32
35 # define R_XXX_RELATIVE R_X86_64_RELATIVE
36 # define IMAGE_FILE_MACHINE 0x8664
37 # define RSRC_RELTYPE 3
39 #elif defined TCC_TARGET_ARM
40 # define ADDR3264 DWORD
41 # define REL_TYPE_DIRECT R_ARM_ABS32
42 # define R_XXX_THUNKFIX R_ARM_ABS32
43 # define R_XXX_RELATIVE R_ARM_RELATIVE
44 # define IMAGE_FILE_MACHINE 0x01C0
45 # define RSRC_RELTYPE 7 /* ??? (not tested) */
47 #elif defined TCC_TARGET_I386
48 # define ADDR3264 DWORD
49 # define REL_TYPE_DIRECT R_386_32
50 # define R_XXX_THUNKFIX R_386_32
51 # define R_XXX_RELATIVE R_386_RELATIVE
52 # define IMAGE_FILE_MACHINE 0x014C
53 # define RSRC_RELTYPE 7 /* DIR32NB */
59 void dbg_printf (const char *fmt
, ...)
65 x
= vsprintf (buffer
, fmt
, arg
);
66 strcpy(buffer
+x
, "\n");
67 OutputDebugString(buffer
);
72 /* ----------------------------------------------------------- */
73 #ifndef IMAGE_NT_SIGNATURE
74 /* ----------------------------------------------------------- */
75 /* definitions below are from winnt.h */
77 typedef unsigned char BYTE
;
78 typedef unsigned short WORD
;
79 typedef unsigned int DWORD
;
80 typedef unsigned long long ULONGLONG
;
83 typedef struct _IMAGE_DOS_HEADER
{ /* DOS .EXE header */
84 WORD e_magic
; /* Magic number */
85 WORD e_cblp
; /* Bytes on last page of file */
86 WORD e_cp
; /* Pages in file */
87 WORD e_crlc
; /* Relocations */
88 WORD e_cparhdr
; /* Size of header in paragraphs */
89 WORD e_minalloc
; /* Minimum extra paragraphs needed */
90 WORD e_maxalloc
; /* Maximum extra paragraphs needed */
91 WORD e_ss
; /* Initial (relative) SS value */
92 WORD e_sp
; /* Initial SP value */
93 WORD e_csum
; /* Checksum */
94 WORD e_ip
; /* Initial IP value */
95 WORD e_cs
; /* Initial (relative) CS value */
96 WORD e_lfarlc
; /* File address of relocation table */
97 WORD e_ovno
; /* Overlay number */
98 WORD e_res
[4]; /* Reserved words */
99 WORD e_oemid
; /* OEM identifier (for e_oeminfo) */
100 WORD e_oeminfo
; /* OEM information; e_oemid specific */
101 WORD e_res2
[10]; /* Reserved words */
102 DWORD e_lfanew
; /* File address of new exe header */
103 } IMAGE_DOS_HEADER
, *PIMAGE_DOS_HEADER
;
105 #define IMAGE_NT_SIGNATURE 0x00004550 /* PE00 */
106 #define SIZE_OF_NT_SIGNATURE 4
108 typedef struct _IMAGE_FILE_HEADER
{
110 WORD NumberOfSections
;
112 DWORD PointerToSymbolTable
;
113 DWORD NumberOfSymbols
;
114 WORD SizeOfOptionalHeader
;
115 WORD Characteristics
;
116 } IMAGE_FILE_HEADER
, *PIMAGE_FILE_HEADER
;
119 #define IMAGE_SIZEOF_FILE_HEADER 20
121 typedef struct _IMAGE_DATA_DIRECTORY
{
122 DWORD VirtualAddress
;
124 } IMAGE_DATA_DIRECTORY
, *PIMAGE_DATA_DIRECTORY
;
127 typedef struct _IMAGE_OPTIONAL_HEADER
{
128 /* Standard fields. */
130 BYTE MajorLinkerVersion
;
131 BYTE MinorLinkerVersion
;
133 DWORD SizeOfInitializedData
;
134 DWORD SizeOfUninitializedData
;
135 DWORD AddressOfEntryPoint
;
137 #ifndef TCC_TARGET_X86_64
140 /* NT additional fields. */
142 DWORD SectionAlignment
;
144 WORD MajorOperatingSystemVersion
;
145 WORD MinorOperatingSystemVersion
;
146 WORD MajorImageVersion
;
147 WORD MinorImageVersion
;
148 WORD MajorSubsystemVersion
;
149 WORD MinorSubsystemVersion
;
150 DWORD Win32VersionValue
;
155 WORD DllCharacteristics
;
156 ADDR3264 SizeOfStackReserve
;
157 ADDR3264 SizeOfStackCommit
;
158 ADDR3264 SizeOfHeapReserve
;
159 ADDR3264 SizeOfHeapCommit
;
161 DWORD NumberOfRvaAndSizes
;
162 IMAGE_DATA_DIRECTORY DataDirectory
[16];
163 } IMAGE_OPTIONAL_HEADER32
, IMAGE_OPTIONAL_HEADER64
, IMAGE_OPTIONAL_HEADER
;
165 #define IMAGE_DIRECTORY_ENTRY_EXPORT 0 /* Export Directory */
166 #define IMAGE_DIRECTORY_ENTRY_IMPORT 1 /* Import Directory */
167 #define IMAGE_DIRECTORY_ENTRY_RESOURCE 2 /* Resource Directory */
168 #define IMAGE_DIRECTORY_ENTRY_EXCEPTION 3 /* Exception Directory */
169 #define IMAGE_DIRECTORY_ENTRY_SECURITY 4 /* Security Directory */
170 #define IMAGE_DIRECTORY_ENTRY_BASERELOC 5 /* Base Relocation Table */
171 #define IMAGE_DIRECTORY_ENTRY_DEBUG 6 /* Debug Directory */
172 /* IMAGE_DIRECTORY_ENTRY_COPYRIGHT 7 (X86 usage) */
173 #define IMAGE_DIRECTORY_ENTRY_ARCHITECTURE 7 /* Architecture Specific Data */
174 #define IMAGE_DIRECTORY_ENTRY_GLOBALPTR 8 /* RVA of GP */
175 #define IMAGE_DIRECTORY_ENTRY_TLS 9 /* TLS Directory */
176 #define IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG 10 /* Load Configuration Directory */
177 #define IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT 11 /* Bound Import Directory in headers */
178 #define IMAGE_DIRECTORY_ENTRY_IAT 12 /* Import Address Table */
179 #define IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT 13 /* Delay Load Import Descriptors */
180 #define IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR 14 /* COM Runtime descriptor */
182 /* Section header format. */
183 #define IMAGE_SIZEOF_SHORT_NAME 8
185 typedef struct _IMAGE_SECTION_HEADER
{
186 BYTE Name
[IMAGE_SIZEOF_SHORT_NAME
];
188 DWORD PhysicalAddress
;
191 DWORD VirtualAddress
;
193 DWORD PointerToRawData
;
194 DWORD PointerToRelocations
;
195 DWORD PointerToLinenumbers
;
196 WORD NumberOfRelocations
;
197 WORD NumberOfLinenumbers
;
198 DWORD Characteristics
;
199 } IMAGE_SECTION_HEADER
, *PIMAGE_SECTION_HEADER
;
201 #define IMAGE_SIZEOF_SECTION_HEADER 40
203 typedef struct _IMAGE_EXPORT_DIRECTORY
{
204 DWORD Characteristics
;
210 DWORD NumberOfFunctions
;
212 DWORD AddressOfFunctions
;
213 DWORD AddressOfNames
;
214 DWORD AddressOfNameOrdinals
;
215 } IMAGE_EXPORT_DIRECTORY
,*PIMAGE_EXPORT_DIRECTORY
;
217 typedef struct _IMAGE_IMPORT_DESCRIPTOR
{
219 DWORD Characteristics
;
220 DWORD OriginalFirstThunk
;
223 DWORD ForwarderChain
;
226 } IMAGE_IMPORT_DESCRIPTOR
;
228 typedef struct _IMAGE_BASE_RELOCATION
{
229 DWORD VirtualAddress
;
231 // WORD TypeOffset[1];
232 } IMAGE_BASE_RELOCATION
;
234 #define IMAGE_SIZEOF_BASE_RELOCATION 8
236 #define IMAGE_REL_BASED_ABSOLUTE 0
237 #define IMAGE_REL_BASED_HIGH 1
238 #define IMAGE_REL_BASED_LOW 2
239 #define IMAGE_REL_BASED_HIGHLOW 3
240 #define IMAGE_REL_BASED_HIGHADJ 4
241 #define IMAGE_REL_BASED_MIPS_JMPADDR 5
242 #define IMAGE_REL_BASED_SECTION 6
243 #define IMAGE_REL_BASED_REL32 7
247 /* ----------------------------------------------------------- */
248 #endif /* ndef IMAGE_NT_SIGNATURE */
249 /* ----------------------------------------------------------- */
250 #pragma pack(push, 1)
254 IMAGE_DOS_HEADER doshdr
;
257 IMAGE_FILE_HEADER filehdr
;
258 #ifdef TCC_TARGET_X86_64
259 IMAGE_OPTIONAL_HEADER64 opthdr
;
262 IMAGE_OPTIONAL_HEADER32 opthdr
;
264 IMAGE_OPTIONAL_HEADER opthdr
;
269 struct pe_reloc_header
{
274 struct pe_rsrc_header
{
275 struct _IMAGE_FILE_HEADER filehdr
;
276 struct _IMAGE_SECTION_HEADER sectionhdr
;
279 struct pe_rsrc_reloc
{
287 /* ------------------------------------------------------------- */
288 /* internal temporary structures */
291 #define IMAGE_SCN_CNT_CODE 0x00000020
292 #define IMAGE_SCN_CNT_INITIALIZED_DATA 0x00000040
293 #define IMAGE_SCN_CNT_UNINITIALIZED_DATA 0x00000080
294 #define IMAGE_SCN_MEM_DISCARDABLE 0x02000000
295 #define IMAGE_SCN_MEM_SHARED 0x10000000
296 #define IMAGE_SCN_MEM_EXECUTE 0x20000000
297 #define IMAGE_SCN_MEM_READ 0x40000000
298 #define IMAGE_SCN_MEM_WRITE 0x80000000
314 static const DWORD pe_sec_flags
[] = {
315 0x60000020, /* ".text" , */
316 0xC0000040, /* ".data" , */
317 0xC0000080, /* ".bss" , */
318 0x40000040, /* ".idata" , */
319 0x40000040, /* ".pdata" , */
320 0xE0000060, /* < other > , */
321 0x40000040, /* ".rsrc" , */
322 0x42000802, /* ".stab" , */
323 0x42000040, /* ".reloc" , */
326 struct section_info
{
334 IMAGE_SECTION_HEADER ish
;
337 struct import_symbol
{
343 struct pe_import_info
{
346 struct import_symbol
**symbols
;
353 const char *filename
;
357 const char *start_symbol
;
368 struct section_info
*sec_info
;
370 struct pe_import_info
**imp_info
;
380 /* --------------------------------------------*/
382 static const char *pe_export_name(TCCState
*s1
, ElfW(Sym
) *sym
)
384 const char *name
= (char*)symtab_section
->link
->data
+ sym
->st_name
;
385 if (s1
->leading_underscore
&& name
[0] == '_' && !(sym
->st_other
& ST_PE_STDCALL
))
390 static int pe_find_import(TCCState
* s1
, ElfW(Sym
) *sym
)
394 int sym_index
= 0, n
= 0;
398 s
= pe_export_name(s1
, sym
);
402 if (sym
->st_other
& ST_PE_STDCALL
) {
403 /* try w/0 stdcall deco (windows API convention) */
405 if (!p
|| s
[0] != '_')
407 strcpy(buffer
, s
+1)[p
-s
-1] = 0;
408 } else if (s
[0] != '_') { /* try non-ansi function */
409 buffer
[0] = '_', strcpy(buffer
+ 1, s
);
410 } else if (0 == memcmp(s
, "__imp_", 6)) { /* mingw 2.0 */
411 strcpy(buffer
, s
+ 6), a
= 1;
412 } else if (0 == memcmp(s
, "_imp__", 6)) { /* mingw 3.7 */
413 strcpy(buffer
, s
+ 6), a
= 1;
419 sym_index
= find_elf_sym(s1
->dynsymtab_section
, s
);
420 // printf("find (%d) %d %s\n", n, sym_index, s);
422 && ELFW(ST_TYPE
)(sym
->st_info
) == STT_OBJECT
423 && 0 == (sym
->st_other
& ST_PE_IMPORT
)
425 ) err
= -1, sym_index
= 0;
426 } while (0 == sym_index
&& ++n
< 2);
427 return n
== 2 ? err
: sym_index
;
430 /*----------------------------------------------------------------------------*/
432 static int dynarray_assoc(void **pp
, int n
, int key
)
435 for (i
= 0; i
< n
; ++i
, ++pp
)
436 if (key
== **(int **) pp
)
442 ST_FN DWORD
umin(DWORD a
, DWORD b
)
444 return a
< b
? a
: b
;
448 static DWORD
umax(DWORD a
, DWORD b
)
450 return a
< b
? b
: a
;
453 static DWORD
pe_file_align(struct pe_info
*pe
, DWORD n
)
455 return (n
+ (pe
->file_align
- 1)) & ~(pe
->file_align
- 1);
458 static DWORD
pe_virtual_align(struct pe_info
*pe
, DWORD n
)
460 return (n
+ (pe
->section_align
- 1)) & ~(pe
->section_align
- 1);
463 static void pe_align_section(Section
*s
, int a
)
465 int i
= s
->data_offset
& (a
-1);
467 section_ptr_add(s
, a
- i
);
470 static void pe_set_datadir(struct pe_header
*hdr
, int dir
, DWORD addr
, DWORD size
)
472 hdr
->opthdr
.DataDirectory
[dir
].VirtualAddress
= addr
;
473 hdr
->opthdr
.DataDirectory
[dir
].Size
= size
;
476 static int pe_fwrite(void *data
, unsigned len
, FILE *fp
, DWORD
*psum
)
482 for (i
= len
; i
> 0; i
-= 2) {
483 sum
+= (i
>= 2) ? *p
++ : *(BYTE
*)p
;
484 sum
= (sum
+ (sum
>> 16)) & 0xFFFF;
488 return len
== fwrite(data
, 1, len
, fp
) ? 0 : -1;
491 static void pe_fpad(FILE *fp
, DWORD new_pos
)
493 DWORD pos
= ftell(fp
);
494 while (++pos
<= new_pos
)
498 /*----------------------------------------------------------------------------*/
499 static int pe_write(struct pe_info
*pe
)
501 static const struct pe_header pe_template
= {
503 /* IMAGE_DOS_HEADER doshdr */
504 0x5A4D, /*WORD e_magic; Magic number */
505 0x0090, /*WORD e_cblp; Bytes on last page of file */
506 0x0003, /*WORD e_cp; Pages in file */
507 0x0000, /*WORD e_crlc; Relocations */
509 0x0004, /*WORD e_cparhdr; Size of header in paragraphs */
510 0x0000, /*WORD e_minalloc; Minimum extra paragraphs needed */
511 0xFFFF, /*WORD e_maxalloc; Maximum extra paragraphs needed */
512 0x0000, /*WORD e_ss; Initial (relative) SS value */
514 0x00B8, /*WORD e_sp; Initial SP value */
515 0x0000, /*WORD e_csum; Checksum */
516 0x0000, /*WORD e_ip; Initial IP value */
517 0x0000, /*WORD e_cs; Initial (relative) CS value */
518 0x0040, /*WORD e_lfarlc; File address of relocation table */
519 0x0000, /*WORD e_ovno; Overlay number */
520 {0,0,0,0}, /*WORD e_res[4]; Reserved words */
521 0x0000, /*WORD e_oemid; OEM identifier (for e_oeminfo) */
522 0x0000, /*WORD e_oeminfo; OEM information; e_oemid specific */
523 {0,0,0,0,0,0,0,0,0,0}, /*WORD e_res2[10]; Reserved words */
524 0x00000080 /*DWORD e_lfanew; File address of new exe header */
526 /* BYTE dosstub[0x40] */
527 /* 14 code bytes + "This program cannot be run in DOS mode.\r\r\n$" + 6 * 0x00 */
528 0x0e,0x1f,0xba,0x0e,0x00,0xb4,0x09,0xcd,0x21,0xb8,0x01,0x4c,0xcd,0x21,0x54,0x68,
529 0x69,0x73,0x20,0x70,0x72,0x6f,0x67,0x72,0x61,0x6d,0x20,0x63,0x61,0x6e,0x6e,0x6f,
530 0x74,0x20,0x62,0x65,0x20,0x72,0x75,0x6e,0x20,0x69,0x6e,0x20,0x44,0x4f,0x53,0x20,
531 0x6d,0x6f,0x64,0x65,0x2e,0x0d,0x0d,0x0a,0x24,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
533 0x00004550, /* DWORD nt_sig = IMAGE_NT_SIGNATURE */
535 /* IMAGE_FILE_HEADER filehdr */
536 IMAGE_FILE_MACHINE
, /*WORD Machine; */
537 0x0003, /*WORD NumberOfSections; */
538 0x00000000, /*DWORD TimeDateStamp; */
539 0x00000000, /*DWORD PointerToSymbolTable; */
540 0x00000000, /*DWORD NumberOfSymbols; */
541 #if defined(TCC_TARGET_X86_64)
542 0x00F0, /*WORD SizeOfOptionalHeader; */
543 0x022F /*WORD Characteristics; */
544 #define CHARACTERISTICS_DLL 0x222E
545 #elif defined(TCC_TARGET_I386)
546 0x00E0, /*WORD SizeOfOptionalHeader; */
547 0x030F /*WORD Characteristics; */
548 #define CHARACTERISTICS_DLL 0x230E
549 #elif defined(TCC_TARGET_ARM)
550 0x00E0, /*WORD SizeOfOptionalHeader; */
551 0x010F, /*WORD Characteristics; */
552 #define CHARACTERISTICS_DLL 0x230F
555 /* IMAGE_OPTIONAL_HEADER opthdr */
556 /* Standard fields. */
557 #ifdef TCC_TARGET_X86_64
558 0x020B, /*WORD Magic; */
560 0x010B, /*WORD Magic; */
562 0x06, /*BYTE MajorLinkerVersion; */
563 0x00, /*BYTE MinorLinkerVersion; */
564 0x00000000, /*DWORD SizeOfCode; */
565 0x00000000, /*DWORD SizeOfInitializedData; */
566 0x00000000, /*DWORD SizeOfUninitializedData; */
567 0x00000000, /*DWORD AddressOfEntryPoint; */
568 0x00000000, /*DWORD BaseOfCode; */
569 #ifndef TCC_TARGET_X86_64
570 0x00000000, /*DWORD BaseOfData; */
572 /* NT additional fields. */
573 #if defined(TCC_TARGET_ARM)
574 0x00100000, /*DWORD ImageBase; */
576 0x00400000, /*DWORD ImageBase; */
578 0x00001000, /*DWORD SectionAlignment; */
579 0x00000200, /*DWORD FileAlignment; */
580 0x0004, /*WORD MajorOperatingSystemVersion; */
581 0x0000, /*WORD MinorOperatingSystemVersion; */
582 0x0000, /*WORD MajorImageVersion; */
583 0x0000, /*WORD MinorImageVersion; */
584 0x0004, /*WORD MajorSubsystemVersion; */
585 0x0000, /*WORD MinorSubsystemVersion; */
586 0x00000000, /*DWORD Win32VersionValue; */
587 0x00000000, /*DWORD SizeOfImage; */
588 0x00000200, /*DWORD SizeOfHeaders; */
589 0x00000000, /*DWORD CheckSum; */
590 0x0002, /*WORD Subsystem; */
591 0x0000, /*WORD DllCharacteristics; */
592 0x00100000, /*DWORD SizeOfStackReserve; */
593 0x00001000, /*DWORD SizeOfStackCommit; */
594 0x00100000, /*DWORD SizeOfHeapReserve; */
595 0x00001000, /*DWORD SizeOfHeapCommit; */
596 0x00000000, /*DWORD LoaderFlags; */
597 0x00000010, /*DWORD NumberOfRvaAndSizes; */
599 /* IMAGE_DATA_DIRECTORY DataDirectory[16]; */
600 {{0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0},
601 {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}}
604 struct pe_header pe_header
= pe_template
;
608 DWORD file_offset
, sum
;
609 struct section_info
*si
;
610 IMAGE_SECTION_HEADER
*psh
;
612 op
= fopen(pe
->filename
, "wb");
614 tcc_error_noabort("could not write '%s': %s", pe
->filename
, strerror(errno
));
618 pe
->sizeofheaders
= pe_file_align(pe
,
619 sizeof (struct pe_header
)
620 + pe
->sec_count
* sizeof (IMAGE_SECTION_HEADER
)
623 file_offset
= pe
->sizeofheaders
;
625 if (2 == pe
->s1
->verbose
)
626 printf("-------------------------------"
627 "\n virt file size section" "\n");
628 for (i
= 0; i
< pe
->sec_count
; ++i
) {
632 si
= pe
->sec_info
+ i
;
634 addr
= si
->sh_addr
- pe
->imagebase
;
638 if (2 == pe
->s1
->verbose
)
639 printf("%6x %6x %6x %s\n",
640 (unsigned)addr
, (unsigned)file_offset
, (unsigned)size
, sh_name
);
644 pe_header
.opthdr
.BaseOfCode
= addr
;
648 #ifndef TCC_TARGET_X86_64
649 pe_header
.opthdr
.BaseOfData
= addr
;
657 pe_set_datadir(&pe_header
, IMAGE_DIRECTORY_ENTRY_BASERELOC
, addr
, size
);
661 pe_set_datadir(&pe_header
, IMAGE_DIRECTORY_ENTRY_RESOURCE
, addr
, size
);
665 pe_set_datadir(&pe_header
, IMAGE_DIRECTORY_ENTRY_EXCEPTION
, addr
, size
);
672 if (pe
->thunk
== pe
->s1
->sections
[si
->ord
]) {
674 pe_set_datadir(&pe_header
, IMAGE_DIRECTORY_ENTRY_IMPORT
,
675 pe
->imp_offs
+ addr
, pe
->imp_size
);
676 pe_set_datadir(&pe_header
, IMAGE_DIRECTORY_ENTRY_IAT
,
677 pe
->iat_offs
+ addr
, pe
->iat_size
);
680 pe_set_datadir(&pe_header
, IMAGE_DIRECTORY_ENTRY_EXPORT
,
681 pe
->exp_offs
+ addr
, pe
->exp_size
);
685 strncpy((char*)psh
->Name
, sh_name
, sizeof psh
->Name
);
687 psh
->Characteristics
= pe_sec_flags
[si
->cls
];
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
;
717 pe_fwrite(&pe_header
, sizeof pe_header
, op
, &sum
);
718 for (i
= 0; i
< pe
->sec_count
; ++i
)
719 pe_fwrite(&pe
->sec_info
[i
].ish
, sizeof(IMAGE_SECTION_HEADER
), op
, &sum
);
720 pe_fpad(op
, pe
->sizeofheaders
);
721 for (i
= 0; i
< pe
->sec_count
; ++i
) {
722 si
= pe
->sec_info
+ i
;
725 pe_fwrite(si
->data
, si
->data_size
, op
, &sum
);
726 file_offset
= psh
->PointerToRawData
+ psh
->SizeOfRawData
;
727 pe_fpad(op
, file_offset
);
731 pe_header
.opthdr
.CheckSum
= sum
+ file_offset
;
732 fseek(op
, offsetof(struct pe_header
, opthdr
.CheckSum
), SEEK_SET
);
733 pe_fwrite(&pe_header
.opthdr
.CheckSum
, sizeof pe_header
.opthdr
.CheckSum
, op
, NULL
);
736 if (2 == pe
->s1
->verbose
)
737 printf("-------------------------------\n");
739 printf("<- %s (%u bytes)\n", pe
->filename
, (unsigned)file_offset
);
744 /*----------------------------------------------------------------------------*/
746 static struct import_symbol
*pe_add_import(struct pe_info
*pe
, int sym_index
)
750 struct pe_import_info
*p
;
751 struct import_symbol
*s
;
754 isym
= (ElfW(Sym
) *)pe
->s1
->dynsymtab_section
->data
+ sym_index
;
755 dll_index
= isym
->st_size
;
757 i
= dynarray_assoc ((void**)pe
->imp_info
, pe
->imp_count
, dll_index
);
762 p
= tcc_mallocz(sizeof *p
);
763 p
->dll_index
= dll_index
;
764 dynarray_add(&pe
->imp_info
, &pe
->imp_count
, p
);
767 i
= dynarray_assoc ((void**)p
->symbols
, p
->sym_count
, sym_index
);
769 return p
->symbols
[i
];
771 s
= tcc_mallocz(sizeof *s
);
772 dynarray_add(&p
->symbols
, &p
->sym_count
, s
);
773 s
->sym_index
= sym_index
;
777 void pe_free_imports(struct pe_info
*pe
)
780 for (i
= 0; i
< pe
->imp_count
; ++i
) {
781 struct pe_import_info
*p
= pe
->imp_info
[i
];
782 dynarray_reset(&p
->symbols
, &p
->sym_count
);
784 dynarray_reset(&pe
->imp_info
, &pe
->imp_count
);
787 /*----------------------------------------------------------------------------*/
788 static void pe_build_imports(struct pe_info
*pe
)
790 int thk_ptr
, ent_ptr
, dll_ptr
, sym_cnt
, i
;
791 DWORD rva_base
= pe
->thunk
->sh_addr
- pe
->imagebase
;
792 int ndlls
= pe
->imp_count
;
794 for (sym_cnt
= i
= 0; i
< ndlls
; ++i
)
795 sym_cnt
+= pe
->imp_info
[i
]->sym_count
;
800 pe_align_section(pe
->thunk
, 16);
802 pe
->imp_offs
= dll_ptr
= pe
->thunk
->data_offset
;
803 pe
->imp_size
= (ndlls
+ 1) * sizeof(IMAGE_IMPORT_DESCRIPTOR
);
804 pe
->iat_offs
= dll_ptr
+ pe
->imp_size
;
805 pe
->iat_size
= (sym_cnt
+ ndlls
) * sizeof(ADDR3264
);
806 section_ptr_add(pe
->thunk
, pe
->imp_size
+ 2*pe
->iat_size
);
808 thk_ptr
= pe
->iat_offs
;
809 ent_ptr
= pe
->iat_offs
+ pe
->iat_size
;
811 for (i
= 0; i
< pe
->imp_count
; ++i
) {
812 IMAGE_IMPORT_DESCRIPTOR
*hdr
;
815 struct pe_import_info
*p
= pe
->imp_info
[i
];
817 DLLReference
*dllref
;
819 dllindex
= p
->dll_index
;
821 name
= (dllref
= pe
->s1
->loaded_dlls
[dllindex
-1])->name
;
823 name
= "", dllref
= NULL
;
825 /* put the dll name into the import header */
826 v
= put_elf_str(pe
->thunk
, name
);
827 hdr
= (IMAGE_IMPORT_DESCRIPTOR
*)(pe
->thunk
->data
+ dll_ptr
);
828 hdr
->FirstThunk
= thk_ptr
+ rva_base
;
829 hdr
->OriginalFirstThunk
= ent_ptr
+ rva_base
;
830 hdr
->Name
= v
+ rva_base
;
832 for (k
= 0, n
= p
->sym_count
; k
<= n
; ++k
) {
834 int iat_index
= p
->symbols
[k
]->iat_index
;
835 int sym_index
= p
->symbols
[k
]->sym_index
;
836 ElfW(Sym
) *imp_sym
= (ElfW(Sym
) *)pe
->s1
->dynsymtab_section
->data
+ sym_index
;
837 ElfW(Sym
) *org_sym
= (ElfW(Sym
) *)symtab_section
->data
+ iat_index
;
838 const char *name
= (char*)pe
->s1
->dynsymtab_section
->link
->data
+ imp_sym
->st_name
;
841 org_sym
->st_value
= thk_ptr
;
842 org_sym
->st_shndx
= pe
->thunk
->sh_num
;
845 v
= 0, ordinal
= imp_sym
->st_value
; /* ordinal from pe_load_def */
847 ordinal
= 0, v
= imp_sym
->st_value
; /* address from tcc_add_symbol() */
850 if (pe
->type
== PE_RUN
) {
852 if ( !dllref
->handle
)
853 dllref
->handle
= LoadLibrary(dllref
->name
);
854 v
= (ADDR3264
)GetProcAddress(dllref
->handle
, ordinal
?(char*)0+ordinal
:name
);
857 tcc_error_noabort("can't build symbol '%s'", name
);
861 v
= ordinal
| (ADDR3264
)1 << (sizeof(ADDR3264
)*8 - 1);
863 v
= pe
->thunk
->data_offset
+ rva_base
;
864 section_ptr_add(pe
->thunk
, sizeof(WORD
)); /* hint, not used */
865 put_elf_str(pe
->thunk
, name
);
869 v
= 0; /* last entry is zero */
872 *(ADDR3264
*)(pe
->thunk
->data
+thk_ptr
) =
873 *(ADDR3264
*)(pe
->thunk
->data
+ent_ptr
) = v
;
874 thk_ptr
+= sizeof (ADDR3264
);
875 ent_ptr
+= sizeof (ADDR3264
);
877 dll_ptr
+= sizeof(IMAGE_IMPORT_DESCRIPTOR
);
881 /* ------------------------------------------------------------- */
889 static int sym_cmp(const void *va
, const void *vb
)
891 const char *ca
= (*(struct pe_sort_sym
**)va
)->name
;
892 const char *cb
= (*(struct pe_sort_sym
**)vb
)->name
;
893 return strcmp(ca
, cb
);
896 static void pe_build_exports(struct pe_info
*pe
)
899 int sym_index
, sym_end
;
900 DWORD rva_base
, func_o
, name_o
, ord_o
, str_o
;
901 IMAGE_EXPORT_DIRECTORY
*hdr
;
903 struct pe_sort_sym
**sorted
, *p
;
910 rva_base
= pe
->thunk
->sh_addr
- pe
->imagebase
;
911 sym_count
= 0, sorted
= NULL
, op
= NULL
;
913 sym_end
= symtab_section
->data_offset
/ sizeof(ElfW(Sym
));
914 for (sym_index
= 1; sym_index
< sym_end
; ++sym_index
) {
915 sym
= (ElfW(Sym
)*)symtab_section
->data
+ sym_index
;
916 name
= pe_export_name(pe
->s1
, sym
);
917 if ((sym
->st_other
& ST_PE_EXPORT
)
918 /* export only symbols from actually written sections */
919 && pe
->s1
->sections
[sym
->st_shndx
]->sh_addr
) {
920 p
= tcc_malloc(sizeof *p
);
921 p
->index
= sym_index
;
923 dynarray_add(&sorted
, &sym_count
, p
);
926 if (sym
->st_other
& ST_PE_EXPORT
)
927 printf("export: %s\n", name
);
928 if (sym
->st_other
& ST_PE_STDCALL
)
929 printf("stdcall: %s\n", name
);
936 qsort (sorted
, sym_count
, sizeof *sorted
, sym_cmp
);
938 pe_align_section(pe
->thunk
, 16);
939 dllname
= tcc_basename(pe
->filename
);
941 pe
->exp_offs
= pe
->thunk
->data_offset
;
942 func_o
= pe
->exp_offs
+ sizeof(IMAGE_EXPORT_DIRECTORY
);
943 name_o
= func_o
+ sym_count
* sizeof (DWORD
);
944 ord_o
= name_o
+ sym_count
* sizeof (DWORD
);
945 str_o
= ord_o
+ sym_count
* sizeof(WORD
);
947 hdr
= section_ptr_add(pe
->thunk
, str_o
- pe
->exp_offs
);
948 hdr
->Characteristics
= 0;
950 hdr
->NumberOfFunctions
= sym_count
;
951 hdr
->NumberOfNames
= sym_count
;
952 hdr
->AddressOfFunctions
= func_o
+ rva_base
;
953 hdr
->AddressOfNames
= name_o
+ rva_base
;
954 hdr
->AddressOfNameOrdinals
= ord_o
+ rva_base
;
955 hdr
->Name
= str_o
+ rva_base
;
956 put_elf_str(pe
->thunk
, dllname
);
959 /* automatically write exports to <output-filename>.def */
960 pstrcpy(buf
, sizeof buf
, pe
->filename
);
961 strcpy(tcc_fileextension(buf
), ".def");
962 op
= fopen(buf
, "w");
964 tcc_error_noabort("could not create '%s': %s", buf
, strerror(errno
));
966 fprintf(op
, "LIBRARY %s\n\nEXPORTS\n", dllname
);
968 printf("<- %s (%d symbol%s)\n", buf
, sym_count
, &"s"[sym_count
< 2]);
972 for (ord
= 0; ord
< sym_count
; ++ord
)
974 p
= sorted
[ord
], sym_index
= p
->index
, name
= p
->name
;
975 /* insert actual address later in pe_relocate_rva */
976 put_elf_reloc(symtab_section
, pe
->thunk
,
977 func_o
, R_XXX_RELATIVE
, sym_index
);
978 *(DWORD
*)(pe
->thunk
->data
+ name_o
)
979 = pe
->thunk
->data_offset
+ rva_base
;
980 *(WORD
*)(pe
->thunk
->data
+ ord_o
)
982 put_elf_str(pe
->thunk
, name
);
983 func_o
+= sizeof (DWORD
);
984 name_o
+= sizeof (DWORD
);
985 ord_o
+= sizeof (WORD
);
987 fprintf(op
, "%s\n", name
);
989 pe
->exp_size
= pe
->thunk
->data_offset
- pe
->exp_offs
;
990 dynarray_reset(&sorted
, &sym_count
);
995 /* ------------------------------------------------------------- */
996 static void pe_build_reloc (struct pe_info
*pe
)
998 DWORD offset
, block_ptr
, addr
;
1000 ElfW_Rel
*rel
, *rel_end
;
1001 Section
*s
= NULL
, *sr
;
1003 offset
= addr
= block_ptr
= count
= i
= 0;
1004 rel
= rel_end
= NULL
;
1007 if (rel
< rel_end
) {
1008 int type
= ELFW(R_TYPE
)(rel
->r_info
);
1009 addr
= rel
->r_offset
+ s
->sh_addr
;
1011 if (type
!= REL_TYPE_DIRECT
)
1013 if (count
== 0) { /* new block */
1014 block_ptr
= pe
->reloc
->data_offset
;
1015 section_ptr_add(pe
->reloc
, sizeof(struct pe_reloc_header
));
1016 offset
= addr
& 0xFFFFFFFF<<12;
1018 if ((addr
-= offset
) < (1<<12)) { /* one block spans 4k addresses */
1019 WORD
*wp
= section_ptr_add(pe
->reloc
, sizeof (WORD
));
1020 *wp
= addr
| IMAGE_REL_BASED_HIGHLOW
<<12;
1026 } else if (i
< pe
->sec_count
) {
1027 sr
= (s
= pe
->s1
->sections
[pe
->sec_info
[i
++].ord
])->reloc
;
1029 rel
= (ElfW_Rel
*)sr
->data
;
1030 rel_end
= (ElfW_Rel
*)(sr
->data
+ sr
->data_offset
);
1036 /* store the last block and ready for a new one */
1037 struct pe_reloc_header
*hdr
;
1038 if (count
& 1) /* align for DWORDS */
1039 section_ptr_add(pe
->reloc
, sizeof(WORD
)), ++count
;
1040 hdr
= (struct pe_reloc_header
*)(pe
->reloc
->data
+ block_ptr
);
1041 hdr
-> offset
= offset
- pe
->imagebase
;
1042 hdr
-> size
= count
* sizeof(WORD
) + sizeof(struct pe_reloc_header
);
1051 /* ------------------------------------------------------------- */
1052 static int pe_section_class(Section
*s
)
1058 flags
= s
->sh_flags
;
1060 if (flags
& SHF_ALLOC
) {
1061 if (type
== SHT_PROGBITS
) {
1062 if (flags
& SHF_EXECINSTR
)
1064 if (flags
& SHF_WRITE
)
1066 if (0 == strcmp(name
, ".rsrc"))
1068 if (0 == strcmp(name
, ".iedat"))
1070 if (0 == strcmp(name
, ".pdata"))
1073 } else if (type
== SHT_NOBITS
) {
1074 if (flags
& SHF_WRITE
)
1078 if (0 == strcmp(name
, ".reloc"))
1080 if (0 == strncmp(name
, ".stab", 5)) /* .stab and .stabstr */
1086 static int pe_assign_addresses (struct pe_info
*pe
)
1091 struct section_info
*si
;
1094 if (PE_DLL
== pe
->type
)
1095 pe
->reloc
= new_section(pe
->s1
, ".reloc", SHT_PROGBITS
, 0);
1097 // pe->thunk = new_section(pe->s1, ".iedat", SHT_PROGBITS, SHF_ALLOC);
1099 section_order
= tcc_malloc(pe
->s1
->nb_sections
* sizeof (int));
1100 for (o
= k
= 0 ; k
< sec_last
; ++k
) {
1101 for (i
= 1; i
< pe
->s1
->nb_sections
; ++i
) {
1102 s
= pe
->s1
->sections
[i
];
1103 if (k
== pe_section_class(s
)) {
1104 // printf("%s %d\n", s->name, k);
1105 s
->sh_addr
= pe
->imagebase
;
1106 section_order
[o
++] = i
;
1111 pe
->sec_info
= tcc_mallocz(o
* sizeof (struct section_info
));
1112 addr
= pe
->imagebase
+ 1;
1114 for (i
= 0; i
< o
; ++i
)
1116 k
= section_order
[i
];
1117 s
= pe
->s1
->sections
[k
];
1118 c
= pe_section_class(s
);
1119 si
= &pe
->sec_info
[pe
->sec_count
];
1121 #ifdef PE_MERGE_DATA
1122 if (c
== sec_bss
&& pe
->sec_count
&& si
[-1].cls
== sec_data
) {
1123 /* append .bss to .data */
1124 s
->sh_addr
= addr
= ((addr
-1) | (s
->sh_addralign
-1)) + 1;
1125 addr
+= s
->data_offset
;
1126 si
[-1].sh_size
= addr
- si
[-1].sh_addr
;
1130 if (c
== sec_stab
&& 0 == pe
->s1
->do_debug
)
1133 strcpy(si
->name
, s
->name
);
1136 si
->sh_addr
= s
->sh_addr
= addr
= pe_virtual_align(pe
, addr
);
1137 si
->sh_flags
= s
->sh_flags
;
1139 if (c
== sec_data
&& NULL
== pe
->thunk
)
1142 if (s
== pe
->thunk
) {
1143 pe_build_imports(pe
);
1144 pe_build_exports(pe
);
1148 pe_build_reloc (pe
);
1152 if (s
->sh_type
!= SHT_NOBITS
) {
1154 si
->data_size
= s
->data_offset
;
1157 addr
+= s
->data_offset
;
1158 si
->sh_size
= s
->data_offset
;
1161 // printf("%08x %05x %s\n", si->sh_addr, si->sh_size, si->name);
1165 for (i
= 1; i
< pe
->s1
->nb_sections
; ++i
) {
1166 Section
*s
= pe
->s1
->sections
[i
];
1167 int type
= s
->sh_type
;
1168 int flags
= s
->sh_flags
;
1169 printf("section %-16s %-10s %5x %s,%s,%s\n",
1171 type
== SHT_PROGBITS
? "progbits" :
1172 type
== SHT_NOBITS
? "nobits" :
1173 type
== SHT_SYMTAB
? "symtab" :
1174 type
== SHT_STRTAB
? "strtab" :
1175 type
== SHT_RELX
? "rel" : "???",
1177 flags
& SHF_ALLOC
? "alloc" : "",
1178 flags
& SHF_WRITE
? "write" : "",
1179 flags
& SHF_EXECINSTR
? "exec" : ""
1182 pe
->s1
->verbose
= 2;
1185 tcc_free(section_order
);
1189 /* ------------------------------------------------------------- */
1190 static void pe_relocate_rva (struct pe_info
*pe
, Section
*s
)
1192 Section
*sr
= s
->reloc
;
1193 ElfW_Rel
*rel
, *rel_end
;
1194 rel_end
= (ElfW_Rel
*)(sr
->data
+ sr
->data_offset
);
1195 for(rel
= (ElfW_Rel
*)sr
->data
; rel
< rel_end
; rel
++) {
1196 if (ELFW(R_TYPE
)(rel
->r_info
) == R_XXX_RELATIVE
) {
1197 int sym_index
= ELFW(R_SYM
)(rel
->r_info
);
1198 DWORD addr
= s
->sh_addr
;
1200 ElfW(Sym
) *sym
= (ElfW(Sym
) *)symtab_section
->data
+ sym_index
;
1201 addr
= sym
->st_value
;
1203 // printf("reloc rva %08x %08x %s\n", (DWORD)rel->r_offset, addr, s->name);
1204 *(DWORD
*)(s
->data
+ rel
->r_offset
) += addr
- pe
->imagebase
;
1209 /*----------------------------------------------------------------------------*/
1211 static int pe_isafunc(int sym_index
)
1213 Section
*sr
= text_section
->reloc
;
1214 ElfW_Rel
*rel
, *rel_end
;
1215 Elf32_Word info
= ELF32_R_INFO(sym_index
, R_386_PC32
);
1218 rel_end
= (ElfW_Rel
*)(sr
->data
+ sr
->data_offset
);
1219 for (rel
= (ElfW_Rel
*)sr
->data
; rel
< rel_end
; rel
++)
1220 if (rel
->r_info
== info
)
1225 /*----------------------------------------------------------------------------*/
1226 static int pe_check_symbols(struct pe_info
*pe
)
1229 int sym_index
, sym_end
;
1232 pe_align_section(text_section
, 8);
1234 sym_end
= symtab_section
->data_offset
/ sizeof(ElfW(Sym
));
1235 for (sym_index
= 1; sym_index
< sym_end
; ++sym_index
) {
1237 sym
= (ElfW(Sym
) *)symtab_section
->data
+ sym_index
;
1238 if (sym
->st_shndx
== SHN_UNDEF
) {
1240 const char *name
= (char*)symtab_section
->link
->data
+ sym
->st_name
;
1241 unsigned type
= ELFW(ST_TYPE
)(sym
->st_info
);
1242 int imp_sym
= pe_find_import(pe
->s1
, sym
);
1243 struct import_symbol
*is
;
1248 if (type
== STT_NOTYPE
) {
1249 /* symbols from assembler have no type, find out which */
1250 if (pe_isafunc(sym_index
))
1256 is
= pe_add_import(pe
, imp_sym
);
1258 if (type
== STT_FUNC
) {
1259 unsigned long offset
= is
->thk_offset
;
1261 /* got aliased symbol, like stricmp and _stricmp */
1267 offset
= text_section
->data_offset
;
1268 /* add the 'jmp IAT[x]' instruction */
1269 #ifdef TCC_TARGET_ARM
1270 p
= section_ptr_add(text_section
, 8+4); // room for code and address
1271 (*(DWORD
*)(p
)) = 0xE59FC000; // arm code ldr ip, [pc] ; PC+8+0 = 0001xxxx
1272 (*(DWORD
*)(p
+2)) = 0xE59CF000; // arm code ldr pc, [ip]
1274 p
= section_ptr_add(text_section
, 8);
1276 #ifdef TCC_TARGET_X86_64
1277 *(DWORD
*)(p
+1) = (DWORD
)-4;
1280 /* add a helper symbol, will be patched later in
1282 sprintf(buffer
, "IAT.%s", name
);
1283 is
->iat_index
= put_elf_sym(
1284 symtab_section
, 0, sizeof(DWORD
),
1285 ELFW(ST_INFO
)(STB_GLOBAL
, STT_OBJECT
),
1286 0, SHN_UNDEF
, buffer
);
1287 #ifdef TCC_TARGET_ARM
1288 put_elf_reloc(symtab_section
, text_section
,
1289 offset
+ 8, R_XXX_THUNKFIX
, is
->iat_index
); // offset to IAT position
1291 put_elf_reloc(symtab_section
, text_section
,
1292 offset
+ 2, R_XXX_THUNKFIX
, is
->iat_index
);
1294 is
->thk_offset
= offset
;
1297 /* tcc_realloc might have altered sym's address */
1298 sym
= (ElfW(Sym
) *)symtab_section
->data
+ sym_index
;
1300 /* patch the original symbol */
1301 sym
->st_value
= offset
;
1302 sym
->st_shndx
= text_section
->sh_num
;
1303 sym
->st_other
&= ~ST_PE_EXPORT
; /* do not export */
1307 if (type
== STT_OBJECT
) { /* data, ptr to that should be */
1308 if (0 == is
->iat_index
) {
1309 /* original symbol will be patched later in pe_build_imports */
1310 is
->iat_index
= sym_index
;
1316 if (ELFW(ST_BIND
)(sym
->st_info
) == STB_WEAK
)
1317 /* STB_WEAK undefined symbols are accepted */
1319 tcc_error_noabort("undefined symbol '%s'%s", name
,
1320 imp_sym
< 0 ? ", missing __declspec(dllimport)?":"");
1323 } else if (pe
->s1
->rdynamic
1324 && ELFW(ST_BIND
)(sym
->st_info
) != STB_LOCAL
) {
1325 /* if -rdynamic option, then export all non local symbols */
1326 sym
->st_other
|= ST_PE_EXPORT
;
1332 /*----------------------------------------------------------------------------*/
1333 #ifdef PE_PRINT_SECTIONS
1334 static void pe_print_section(FILE * f
, Section
* s
)
1336 /* just if you're curious */
1340 e
= s
->data
+ s
->data_offset
;
1343 fprintf(f
, "section \"%s\"", s
->name
);
1345 fprintf(f
, "\nlink \"%s\"", s
->link
->name
);
1347 fprintf(f
, "\nreloc \"%s\"", s
->reloc
->name
);
1348 fprintf(f
, "\nv_addr %08X", (unsigned)s
->sh_addr
);
1349 fprintf(f
, "\ncontents %08X", (unsigned)l
);
1352 if (s
->sh_type
== SHT_NOBITS
)
1358 if (s
->sh_type
== SHT_SYMTAB
)
1359 m
= sizeof(ElfW(Sym
));
1360 else if (s
->sh_type
== SHT_RELX
)
1361 m
= sizeof(ElfW_Rel
);
1365 fprintf(f
, "%-8s", "offset");
1366 for (i
= 0; i
< m
; ++i
)
1367 fprintf(f
, " %02x", i
);
1370 if (s
->sh_type
== SHT_SYMTAB
|| s
->sh_type
== SHT_RELX
) {
1371 const char *fields1
[] = {
1382 const char *fields2
[] = {
1391 if (s
->sh_type
== SHT_SYMTAB
)
1392 p
= fields1
, n
= 106;
1394 p
= fields2
, n
= 58;
1396 for (i
= 0; p
[i
]; ++i
)
1397 fprintf(f
, "%6s", p
[i
]);
1398 fprintf(f
, " symbol");
1402 for (i
= 0; i
< n
; ++i
)
1408 fprintf(f
, "%08X", i
);
1409 for (n
= 0; n
< m
; ++n
) {
1411 fprintf(f
, " %02X", p
[i
+ n
]);
1416 if (s
->sh_type
== SHT_SYMTAB
) {
1417 ElfW(Sym
) *sym
= (ElfW(Sym
) *) (p
+ i
);
1418 const char *name
= s
->link
->data
+ sym
->st_name
;
1419 fprintf(f
, " %04X %04X %04X %02X %02X %02X %04X \"%s\"",
1420 (unsigned)sym
->st_name
,
1421 (unsigned)sym
->st_value
,
1422 (unsigned)sym
->st_size
,
1423 (unsigned)ELFW(ST_BIND
)(sym
->st_info
),
1424 (unsigned)ELFW(ST_TYPE
)(sym
->st_info
),
1425 (unsigned)sym
->st_other
,
1426 (unsigned)sym
->st_shndx
,
1429 } else if (s
->sh_type
== SHT_RELX
) {
1430 ElfW_Rel
*rel
= (ElfW_Rel
*) (p
+ i
);
1432 (ElfW(Sym
) *) s
->link
->data
+ ELFW(R_SYM
)(rel
->r_info
);
1433 const char *name
= s
->link
->link
->data
+ sym
->st_name
;
1434 fprintf(f
, " %04X %02X %04X \"%s\"",
1435 (unsigned)rel
->r_offset
,
1436 (unsigned)ELFW(R_TYPE
)(rel
->r_info
),
1437 (unsigned)ELFW(R_SYM
)(rel
->r_info
),
1441 for (n
= 0; n
< m
; ++n
) {
1444 if (b
< 32 || b
>= 127)
1446 fprintf(f
, "%c", b
);
1456 static void pe_print_sections(TCCState
*s1
, const char *fname
)
1461 f
= fopen(fname
, "w");
1462 for (i
= 1; i
< s1
->nb_sections
; ++i
) {
1463 s
= s1
->sections
[i
];
1464 pe_print_section(f
, s
);
1466 pe_print_section(f
, s1
->dynsymtab_section
);
1471 /* ------------------------------------------------------------- */
1472 /* helper function for load/store to insert one more indirection */
1474 #ifndef TCC_TARGET_ARM
1475 ST_FUNC SValue
*pe_getimport(SValue
*sv
, SValue
*v2
)
1478 if ((sv
->r
& (VT_VALMASK
|VT_SYM
)) != (VT_CONST
|VT_SYM
) || (sv
->r2
!= VT_CONST
))
1480 if (!(sv
->sym
->type
.t
& VT_IMPORT
))
1482 // printf("import %04x %04x %04x %s\n", sv->type.t, sv->sym->type.t, sv->r, get_tok_str(sv->sym->v, NULL));
1483 memset(v2
, 0, sizeof *v2
);
1484 v2
->type
.t
= VT_PTR
;
1485 v2
->r
= VT_CONST
| VT_SYM
| VT_LVAL
;
1488 r2
= get_reg(RC_INT
);
1491 if ((uint32_t)sv
->c
.i
) {
1497 v2
->type
.t
= sv
->type
.t
;
1498 v2
->r
|= sv
->r
& VT_LVAL
;
1503 ST_FUNC
int pe_putimport(TCCState
*s1
, int dllindex
, const char *name
, addr_t value
)
1506 s1
->dynsymtab_section
,
1508 dllindex
, /* st_size */
1509 ELFW(ST_INFO
)(STB_GLOBAL
, STT_NOTYPE
),
1511 value
? SHN_ABS
: SHN_UNDEF
,
1516 static int add_dllref(TCCState
*s1
, const char *dllname
)
1518 DLLReference
*dllref
;
1520 for (i
= 0; i
< s1
->nb_loaded_dlls
; ++i
)
1521 if (0 == strcmp(s1
->loaded_dlls
[i
]->name
, dllname
))
1523 dllref
= tcc_mallocz(sizeof(DLLReference
) + strlen(dllname
));
1524 strcpy(dllref
->name
, dllname
);
1525 dynarray_add(&s1
->loaded_dlls
, &s1
->nb_loaded_dlls
, dllref
);
1526 return s1
->nb_loaded_dlls
;
1529 /* ------------------------------------------------------------- */
1531 static int read_mem(int fd
, unsigned offset
, void *buffer
, unsigned len
)
1533 lseek(fd
, offset
, SEEK_SET
);
1534 return len
== read(fd
, buffer
, len
);
1537 /* ------------------------------------------------------------- */
1539 PUB_FUNC
int tcc_get_dllexports(const char *filename
, char **pp
)
1541 int l
, i
, n
, n0
, ret
;
1545 IMAGE_SECTION_HEADER ish
;
1546 IMAGE_EXPORT_DIRECTORY ied
;
1547 IMAGE_DOS_HEADER dh
;
1548 IMAGE_FILE_HEADER ih
;
1549 DWORD sig
, ref
, addr
, ptr
, namep
;
1551 int pef_hdroffset
, opt_hdroffset
, sec_hdroffset
;
1557 fd
= open(filename
, O_RDONLY
| O_BINARY
);
1561 if (!read_mem(fd
, 0, &dh
, sizeof dh
))
1563 if (!read_mem(fd
, dh
.e_lfanew
, &sig
, sizeof sig
))
1565 if (sig
!= 0x00004550)
1567 pef_hdroffset
= dh
.e_lfanew
+ sizeof sig
;
1568 if (!read_mem(fd
, pef_hdroffset
, &ih
, sizeof ih
))
1570 opt_hdroffset
= pef_hdroffset
+ sizeof ih
;
1571 if (ih
.Machine
== 0x014C) {
1572 IMAGE_OPTIONAL_HEADER32 oh
;
1573 sec_hdroffset
= opt_hdroffset
+ sizeof oh
;
1574 if (!read_mem(fd
, opt_hdroffset
, &oh
, sizeof oh
))
1576 if (IMAGE_DIRECTORY_ENTRY_EXPORT
>= oh
.NumberOfRvaAndSizes
)
1578 addr
= oh
.DataDirectory
[IMAGE_DIRECTORY_ENTRY_EXPORT
].VirtualAddress
;
1579 } else if (ih
.Machine
== 0x8664) {
1580 IMAGE_OPTIONAL_HEADER64 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
;
1590 //printf("addr: %08x\n", addr);
1591 for (i
= 0; i
< ih
.NumberOfSections
; ++i
) {
1592 if (!read_mem(fd
, sec_hdroffset
+ i
* sizeof ish
, &ish
, sizeof ish
))
1594 //printf("vaddr: %08x\n", ish.VirtualAddress);
1595 if (addr
>= ish
.VirtualAddress
&& addr
< ish
.VirtualAddress
+ ish
.SizeOfRawData
)
1601 ref
= ish
.VirtualAddress
- ish
.PointerToRawData
;
1602 if (!read_mem(fd
, addr
- ref
, &ied
, sizeof ied
))
1605 namep
= ied
.AddressOfNames
- ref
;
1606 for (i
= 0; i
< ied
.NumberOfNames
; ++i
) {
1607 if (!read_mem(fd
, namep
, &ptr
, sizeof ptr
))
1609 namep
+= sizeof ptr
;
1612 p
= tcc_realloc(p
, n0
= n0
? n0
* 2 : 256);
1613 if (!read_mem(fd
, ptr
- ref
+ l
++, p
+ n
, 1)) {
1614 tcc_free(p
), p
= NULL
;
1632 /* -------------------------------------------------------------
1633 * This is for compiled windows resources in 'coff' format
1634 * as generated by 'windres.exe -O coff ...'.
1637 static int pe_load_res(TCCState
*s1
, int fd
)
1639 struct pe_rsrc_header hdr
;
1640 Section
*rsrc_section
;
1645 if (!read_mem(fd
, 0, &hdr
, sizeof hdr
))
1648 if (hdr
.filehdr
.Machine
!= IMAGE_FILE_MACHINE
1649 || hdr
.filehdr
.NumberOfSections
!= 1
1650 || strcmp((char*)hdr
.sectionhdr
.Name
, ".rsrc") != 0)
1653 rsrc_section
= new_section(s1
, ".rsrc", SHT_PROGBITS
, SHF_ALLOC
);
1654 ptr
= section_ptr_add(rsrc_section
, hdr
.sectionhdr
.SizeOfRawData
);
1655 offs
= hdr
.sectionhdr
.PointerToRawData
;
1656 if (!read_mem(fd
, offs
, ptr
, hdr
.sectionhdr
.SizeOfRawData
))
1658 offs
= hdr
.sectionhdr
.PointerToRelocations
;
1659 for (i
= 0; i
< hdr
.sectionhdr
.NumberOfRelocations
; ++i
)
1661 struct pe_rsrc_reloc rel
;
1662 if (!read_mem(fd
, offs
, &rel
, sizeof rel
))
1664 // printf("rsrc_reloc: %x %x %x\n", rel.offset, rel.size, rel.type);
1665 if (rel
.type
!= RSRC_RELTYPE
)
1667 put_elf_reloc(symtab_section
, rsrc_section
,
1668 rel
.offset
, R_XXX_RELATIVE
, 0);
1676 /* ------------------------------------------------------------- */
1678 static char *trimfront(char *p
)
1680 while (*p
&& (unsigned char)*p
<= ' ')
1685 static char *trimback(char *a
, char *e
)
1687 while (e
> a
&& (unsigned char)e
[-1] <= ' ')
1693 /* ------------------------------------------------------------- */
1694 static int pe_load_def(TCCState
*s1
, int fd
)
1696 int state
= 0, ret
= -1, dllindex
= 0, ord
;
1697 char line
[400], dllname
[80], *p
, *x
;
1700 fp
= fdopen(dup(fd
), "rb");
1701 while (fgets(line
, sizeof line
, fp
))
1703 p
= trimfront(trimback(line
, strchr(line
, 0)));
1704 if (0 == *p
|| ';' == *p
)
1709 if (0 != strnicmp(p
, "LIBRARY", 7))
1711 pstrcpy(dllname
, sizeof dllname
, trimfront(p
+7));
1716 if (0 != stricmp(p
, "EXPORTS"))
1722 dllindex
= add_dllref(s1
, dllname
);
1726 /* get ordinal and will store in sym->st_value */
1730 *x
= 0, x
= strrchr(x
+ 1, '@');
1733 ord
= (int)strtol(x
+ 1, &d
, 10);
1738 pe_putimport(s1
, dllindex
, p
, ord
);
1748 /* ------------------------------------------------------------- */
1749 static int pe_load_dll(TCCState
*s1
, const char *filename
)
1754 ret
= tcc_get_dllexports(filename
, &p
);
1758 index
= add_dllref(s1
, tcc_basename(filename
));
1759 for (q
= p
; *q
; q
+= 1 + strlen(q
))
1760 pe_putimport(s1
, index
, q
, 0);
1766 /* ------------------------------------------------------------- */
1767 ST_FUNC
int pe_load_file(struct TCCState
*s1
, const char *filename
, int fd
)
1771 if (0 == strcmp(tcc_fileextension(filename
), ".def"))
1772 ret
= pe_load_def(s1
, fd
);
1773 else if (pe_load_res(s1
, fd
) == 0)
1775 else if (read_mem(fd
, 0, buf
, 4) && 0 == memcmp(buf
, "MZ\220", 4))
1776 ret
= pe_load_dll(s1
, filename
);
1780 /* ------------------------------------------------------------- */
1781 #ifdef TCC_TARGET_X86_64
1782 static unsigned pe_add_uwwind_info(TCCState
*s1
)
1784 if (NULL
== s1
->uw_pdata
) {
1785 s1
->uw_pdata
= find_section(tcc_state
, ".pdata");
1786 s1
->uw_pdata
->sh_addralign
= 4;
1787 s1
->uw_sym
= put_elf_sym(symtab_section
, 0, 0, 0, 0, text_section
->sh_num
, NULL
);
1790 if (0 == s1
->uw_offs
) {
1791 /* As our functions all have the same stackframe, we use one entry for all */
1792 static const unsigned char uw_info
[] = {
1793 0x01, // UBYTE: 3 Version , UBYTE: 5 Flags
1794 0x04, // UBYTE Size of prolog
1795 0x02, // UBYTE Count of unwind codes
1796 0x05, // UBYTE: 4 Frame Register (rbp), UBYTE: 4 Frame Register offset (scaled)
1797 // USHORT * n Unwind codes array
1798 // 0x0b, 0x01, 0xff, 0xff, // stack size
1799 0x04, 0x03, // set frame ptr (mov rsp -> rbp)
1800 0x01, 0x50 // push reg (rbp)
1803 Section
*s
= text_section
;
1806 section_ptr_add(s
, -s
->data_offset
& 3); /* align */
1807 s1
->uw_offs
= s
->data_offset
;
1808 p
= section_ptr_add(s
, sizeof uw_info
);
1809 memcpy(p
, uw_info
, sizeof uw_info
);
1815 ST_FUNC
void pe_add_unwind_data(unsigned start
, unsigned end
, unsigned stack
)
1817 TCCState
*s1
= tcc_state
;
1820 struct /* _RUNTIME_FUNCTION */ {
1826 d
= pe_add_uwwind_info(s1
);
1828 o
= pd
->data_offset
;
1829 p
= section_ptr_add(pd
, sizeof *p
);
1831 /* record this function */
1832 p
->BeginAddress
= start
;
1833 p
->EndAddress
= end
;
1836 /* put relocations on it */
1837 for (n
= o
+ sizeof *p
; o
< n
; o
+= sizeof p
->BeginAddress
)
1838 put_elf_reloc(symtab_section
, pd
, o
, R_X86_64_RELATIVE
, s1
->uw_sym
);
1841 /* ------------------------------------------------------------- */
1842 #ifdef TCC_TARGET_X86_64
1843 #define PE_STDSYM(n,s) n
1845 #define PE_STDSYM(n,s) "_" n s
1848 static void pe_add_runtime(TCCState
*s1
, struct pe_info
*pe
)
1850 const char *start_symbol
;
1852 int unicode_entry
= 0;
1854 if (find_elf_sym(symtab_section
, PE_STDSYM("WinMain","@16")))
1857 if (find_elf_sym(symtab_section
, PE_STDSYM("wWinMain","@16"))) {
1859 unicode_entry
= PE_GUI
;
1862 if (TCC_OUTPUT_DLL
== s1
->output_type
) {
1864 /* need this for 'tccelf.c:relocate_section()' */
1865 s1
->output_type
= TCC_OUTPUT_EXE
;
1869 if (find_elf_sym(symtab_section
, "wmain"))
1870 unicode_entry
= PE_EXE
;
1874 TCC_OUTPUT_MEMORY
== s1
->output_type
1875 ? PE_GUI
== pe_type
? (unicode_entry
? "__runwwinmain" : "__runwinmain")
1876 : (unicode_entry
? "__runwmain" : "__runmain")
1877 : PE_DLL
== pe_type
? PE_STDSYM("__dllstart","@12")
1878 : PE_GUI
== pe_type
? (unicode_entry
? "__wwinstart": "__winstart")
1879 : (unicode_entry
? "__wstart" : "__start")
1882 if (!s1
->leading_underscore
|| strchr(start_symbol
, '@'))
1885 /* grab the startup code from libtcc1 */
1886 #ifdef TCC_IS_NATIVE
1887 if (TCC_OUTPUT_MEMORY
!= s1
->output_type
|| s1
->runtime_main
)
1889 set_elf_sym(symtab_section
,
1891 ELFW(ST_INFO
)(STB_GLOBAL
, STT_NOTYPE
), 0,
1892 SHN_UNDEF
, start_symbol
);
1894 tcc_add_pragma_libs(s1
);
1896 if (0 == s1
->nostdlib
) {
1897 static const char *libs
[] = {
1898 TCC_LIBTCC1
, "msvcrt", "kernel32", "", "user32", "gdi32", NULL
1900 const char **pp
, *p
;
1901 for (pp
= libs
; 0 != (p
= *pp
); ++pp
) {
1903 if (PE_DLL
!= pe_type
&& PE_GUI
!= pe_type
)
1905 } else if (pp
== libs
&& tcc_add_dll(s1
, p
, 0) >= 0) {
1908 tcc_add_library_err(s1
, p
);
1913 if (TCC_OUTPUT_MEMORY
== s1
->output_type
)
1916 pe
->start_symbol
= start_symbol
;
1919 static void pe_set_options(TCCState
* s1
, struct pe_info
*pe
)
1921 if (PE_DLL
== pe
->type
) {
1922 /* XXX: check if is correct for arm-pe target */
1923 pe
->imagebase
= 0x10000000;
1925 #if defined(TCC_TARGET_ARM)
1926 pe
->imagebase
= 0x00010000;
1928 pe
->imagebase
= 0x00400000;
1932 #if defined(TCC_TARGET_ARM)
1933 /* we use "console" subsystem by default */
1936 if (PE_DLL
== pe
->type
|| PE_GUI
== pe
->type
)
1941 /* Allow override via -Wl,-subsystem=... option */
1942 if (s1
->pe_subsystem
!= 0)
1943 pe
->subsystem
= s1
->pe_subsystem
;
1945 /* set default file/section alignment */
1946 if (pe
->subsystem
== 1) {
1947 pe
->section_align
= 0x20;
1948 pe
->file_align
= 0x20;
1950 pe
->section_align
= 0x1000;
1951 pe
->file_align
= 0x200;
1954 if (s1
->section_align
!= 0)
1955 pe
->section_align
= s1
->section_align
;
1956 if (s1
->pe_file_align
!= 0)
1957 pe
->file_align
= s1
->pe_file_align
;
1959 if ((pe
->subsystem
>= 10) && (pe
->subsystem
<= 12))
1962 if (s1
->has_text_addr
)
1963 pe
->imagebase
= s1
->text_addr
;
1966 ST_FUNC
int pe_output_file(TCCState
*s1
, const char *filename
)
1972 memset(&pe
, 0, sizeof pe
);
1973 pe
.filename
= filename
;
1977 pe_add_runtime(s1
, &pe
);
1978 relocate_common_syms(); /* assign bss addresses */
1979 tcc_add_linker_symbols(s1
);
1980 pe_set_options(s1
, &pe
);
1982 ret
= pe_check_symbols(&pe
);
1985 else if (filename
) {
1986 pe_assign_addresses(&pe
);
1987 relocate_syms(s1
, s1
->symtab
, 0);
1988 for (i
= 1; i
< s1
->nb_sections
; ++i
) {
1989 Section
*s
= s1
->sections
[i
];
1991 relocate_section(s1
, s
);
1992 pe_relocate_rva(&pe
, s
);
1995 pe
.start_addr
= (DWORD
)
1996 ((uintptr_t)tcc_get_symbol_err(s1
, pe
.start_symbol
)
2001 ret
= pe_write(&pe
);
2002 tcc_free(pe
.sec_info
);
2004 #ifdef TCC_IS_NATIVE
2005 pe
.thunk
= data_section
;
2006 pe_build_imports(&pe
);
2007 s1
->runtime_main
= pe
.start_symbol
;
2011 pe_free_imports(&pe
);
2013 #ifdef PE_PRINT_SECTIONS
2014 pe_print_sections(s1
, "tcc.log");
2019 /* ------------------------------------------------------------- */