2 * TCCPE.C - PE file output for the Tiny C Compiler
4 * Copyright (c) 2005-2007 grischka
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
24 #define stricmp strcasecmp
25 #define strnicmp strncasecmp
33 /* #define PE_PRINT_SECTIONS */
35 #ifdef TCC_TARGET_X86_64
36 # define ADDR3264 ULONGLONG
37 # define REL_TYPE_DIRECT R_X86_64_64
38 # define R_XXX_THUNKFIX R_X86_64_PC32
39 # define R_XXX_RELATIVE R_X86_64_RELATIVE
40 # define IMAGE_FILE_MACHINE 0x8664
41 # define RSRC_RELTYPE 3
43 #elif defined TCC_TARGET_ARM
44 # define ADDR3264 DWORD
45 # define REL_TYPE_DIRECT R_ARM_ABS32
46 # define R_XXX_THUNKFIX R_ARM_ABS32
47 # define R_XXX_RELATIVE R_ARM_RELATIVE
48 # define IMAGE_FILE_MACHINE 0x01C0
49 # define RSRC_RELTYPE 7 /* ??? (not tested) */
51 #elif defined TCC_TARGET_I386
52 # define ADDR3264 DWORD
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 */
62 void dbg_printf (const char *fmt
, ...)
68 x
= vsprintf (buffer
, fmt
, arg
);
69 strcpy(buffer
+x
, "\n");
70 OutputDebugString(buffer
);
74 /* ----------------------------------------------------------- */
75 #ifndef IMAGE_NT_SIGNATURE
76 /* ----------------------------------------------------------- */
77 /* definitions below are from winnt.h */
79 typedef unsigned char BYTE
;
80 typedef unsigned short WORD
;
81 typedef unsigned int DWORD
;
82 typedef unsigned long long ULONGLONG
;
85 typedef struct _IMAGE_DOS_HEADER
{ /* DOS .EXE header */
86 WORD e_magic
; /* Magic number */
87 WORD e_cblp
; /* Bytes on last page of file */
88 WORD e_cp
; /* Pages in file */
89 WORD e_crlc
; /* Relocations */
90 WORD e_cparhdr
; /* Size of header in paragraphs */
91 WORD e_minalloc
; /* Minimum extra paragraphs needed */
92 WORD e_maxalloc
; /* Maximum extra paragraphs needed */
93 WORD e_ss
; /* Initial (relative) SS value */
94 WORD e_sp
; /* Initial SP value */
95 WORD e_csum
; /* Checksum */
96 WORD e_ip
; /* Initial IP value */
97 WORD e_cs
; /* Initial (relative) CS value */
98 WORD e_lfarlc
; /* File address of relocation table */
99 WORD e_ovno
; /* Overlay number */
100 WORD e_res
[4]; /* Reserved words */
101 WORD e_oemid
; /* OEM identifier (for e_oeminfo) */
102 WORD e_oeminfo
; /* OEM information; e_oemid specific */
103 WORD e_res2
[10]; /* Reserved words */
104 DWORD e_lfanew
; /* File address of new exe header */
105 } IMAGE_DOS_HEADER
, *PIMAGE_DOS_HEADER
;
107 #define IMAGE_NT_SIGNATURE 0x00004550 /* PE00 */
108 #define SIZE_OF_NT_SIGNATURE 4
110 typedef struct _IMAGE_FILE_HEADER
{
112 WORD NumberOfSections
;
114 DWORD PointerToSymbolTable
;
115 DWORD NumberOfSymbols
;
116 WORD SizeOfOptionalHeader
;
117 WORD Characteristics
;
118 } IMAGE_FILE_HEADER
, *PIMAGE_FILE_HEADER
;
121 #define IMAGE_SIZEOF_FILE_HEADER 20
123 typedef struct _IMAGE_DATA_DIRECTORY
{
124 DWORD VirtualAddress
;
126 } IMAGE_DATA_DIRECTORY
, *PIMAGE_DATA_DIRECTORY
;
129 typedef struct _IMAGE_OPTIONAL_HEADER
{
130 /* Standard fields. */
132 BYTE MajorLinkerVersion
;
133 BYTE MinorLinkerVersion
;
135 DWORD SizeOfInitializedData
;
136 DWORD SizeOfUninitializedData
;
137 DWORD AddressOfEntryPoint
;
139 #ifndef TCC_TARGET_X86_64
142 /* NT additional fields. */
144 DWORD SectionAlignment
;
146 WORD MajorOperatingSystemVersion
;
147 WORD MinorOperatingSystemVersion
;
148 WORD MajorImageVersion
;
149 WORD MinorImageVersion
;
150 WORD MajorSubsystemVersion
;
151 WORD MinorSubsystemVersion
;
152 DWORD Win32VersionValue
;
157 WORD DllCharacteristics
;
158 ADDR3264 SizeOfStackReserve
;
159 ADDR3264 SizeOfStackCommit
;
160 ADDR3264 SizeOfHeapReserve
;
161 ADDR3264 SizeOfHeapCommit
;
163 DWORD NumberOfRvaAndSizes
;
164 IMAGE_DATA_DIRECTORY DataDirectory
[16];
165 } IMAGE_OPTIONAL_HEADER32
, IMAGE_OPTIONAL_HEADER64
, IMAGE_OPTIONAL_HEADER
;
167 #define IMAGE_DIRECTORY_ENTRY_EXPORT 0 /* Export Directory */
168 #define IMAGE_DIRECTORY_ENTRY_IMPORT 1 /* Import Directory */
169 #define IMAGE_DIRECTORY_ENTRY_RESOURCE 2 /* Resource Directory */
170 #define IMAGE_DIRECTORY_ENTRY_EXCEPTION 3 /* Exception Directory */
171 #define IMAGE_DIRECTORY_ENTRY_SECURITY 4 /* Security Directory */
172 #define IMAGE_DIRECTORY_ENTRY_BASERELOC 5 /* Base Relocation Table */
173 #define IMAGE_DIRECTORY_ENTRY_DEBUG 6 /* Debug Directory */
174 /* IMAGE_DIRECTORY_ENTRY_COPYRIGHT 7 (X86 usage) */
175 #define IMAGE_DIRECTORY_ENTRY_ARCHITECTURE 7 /* Architecture Specific Data */
176 #define IMAGE_DIRECTORY_ENTRY_GLOBALPTR 8 /* RVA of GP */
177 #define IMAGE_DIRECTORY_ENTRY_TLS 9 /* TLS Directory */
178 #define IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG 10 /* Load Configuration Directory */
179 #define IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT 11 /* Bound Import Directory in headers */
180 #define IMAGE_DIRECTORY_ENTRY_IAT 12 /* Import Address Table */
181 #define IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT 13 /* Delay Load Import Descriptors */
182 #define IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR 14 /* COM Runtime descriptor */
184 /* Section header format. */
185 #define IMAGE_SIZEOF_SHORT_NAME 8
187 typedef struct _IMAGE_SECTION_HEADER
{
188 BYTE Name
[IMAGE_SIZEOF_SHORT_NAME
];
190 DWORD PhysicalAddress
;
193 DWORD VirtualAddress
;
195 DWORD PointerToRawData
;
196 DWORD PointerToRelocations
;
197 DWORD PointerToLinenumbers
;
198 WORD NumberOfRelocations
;
199 WORD NumberOfLinenumbers
;
200 DWORD Characteristics
;
201 } IMAGE_SECTION_HEADER
, *PIMAGE_SECTION_HEADER
;
203 #define IMAGE_SIZEOF_SECTION_HEADER 40
205 typedef struct _IMAGE_EXPORT_DIRECTORY
{
206 DWORD Characteristics
;
212 DWORD NumberOfFunctions
;
214 DWORD AddressOfFunctions
;
215 DWORD AddressOfNames
;
216 DWORD AddressOfNameOrdinals
;
217 } IMAGE_EXPORT_DIRECTORY
,*PIMAGE_EXPORT_DIRECTORY
;
219 typedef struct _IMAGE_IMPORT_DESCRIPTOR
{
221 DWORD Characteristics
;
222 DWORD OriginalFirstThunk
;
225 DWORD ForwarderChain
;
228 } IMAGE_IMPORT_DESCRIPTOR
;
230 typedef struct _IMAGE_BASE_RELOCATION
{
231 DWORD VirtualAddress
;
233 // WORD TypeOffset[1];
234 } IMAGE_BASE_RELOCATION
;
236 #define IMAGE_SIZEOF_BASE_RELOCATION 8
238 #define IMAGE_REL_BASED_ABSOLUTE 0
239 #define IMAGE_REL_BASED_HIGH 1
240 #define IMAGE_REL_BASED_LOW 2
241 #define IMAGE_REL_BASED_HIGHLOW 3
242 #define IMAGE_REL_BASED_HIGHADJ 4
243 #define IMAGE_REL_BASED_MIPS_JMPADDR 5
244 #define IMAGE_REL_BASED_SECTION 6
245 #define IMAGE_REL_BASED_REL32 7
249 /* ----------------------------------------------------------- */
250 #endif /* ndef IMAGE_NT_SIGNATURE */
251 /* ----------------------------------------------------------- */
252 #pragma pack(push, 1)
256 IMAGE_DOS_HEADER doshdr
;
259 IMAGE_FILE_HEADER filehdr
;
260 #ifdef TCC_TARGET_X86_64
261 IMAGE_OPTIONAL_HEADER64 opthdr
;
264 IMAGE_OPTIONAL_HEADER32 opthdr
;
266 IMAGE_OPTIONAL_HEADER opthdr
;
271 struct pe_reloc_header
{
276 struct pe_rsrc_header
{
277 struct _IMAGE_FILE_HEADER filehdr
;
278 struct _IMAGE_SECTION_HEADER sectionhdr
;
281 struct pe_rsrc_reloc
{
289 /* ------------------------------------------------------------- */
290 /* internal temporary structures */
293 #define IMAGE_SCN_CNT_CODE 0x00000020
294 #define IMAGE_SCN_CNT_INITIALIZED_DATA 0x00000040
295 #define IMAGE_SCN_CNT_UNINITIALIZED_DATA 0x00000080
296 #define IMAGE_SCN_MEM_DISCARDABLE 0x02000000
297 #define IMAGE_SCN_MEM_SHARED 0x10000000
298 #define IMAGE_SCN_MEM_EXECUTE 0x20000000
299 #define IMAGE_SCN_MEM_READ 0x40000000
300 #define IMAGE_SCN_MEM_WRITE 0x80000000
316 static const DWORD pe_sec_flags
[] = {
317 0x60000020, /* ".text" , */
318 0xC0000040, /* ".data" , */
319 0xC0000080, /* ".bss" , */
320 0x40000040, /* ".idata" , */
321 0x40000040, /* ".pdata" , */
322 0xE0000060, /* < other > , */
323 0x40000040, /* ".rsrc" , */
324 0x42000802, /* ".stab" , */
325 0x42000040, /* ".reloc" , */
328 struct section_info
{
336 IMAGE_SECTION_HEADER ish
;
339 struct import_symbol
{
345 struct pe_import_info
{
348 struct import_symbol
**symbols
;
355 const char *filename
;
369 struct section_info
*sec_info
;
371 struct pe_import_info
**imp_info
;
381 /* --------------------------------------------*/
383 static const char *pe_export_name(TCCState
*s1
, ElfW(Sym
) *sym
)
385 const char *name
= symtab_section
->link
->data
+ sym
->st_name
;
386 if (s1
->leading_underscore
&& name
[0] == '_' && !(sym
->st_other
& ST_PE_STDCALL
))
391 static int pe_find_import(TCCState
* s1
, ElfW(Sym
) *sym
)
395 int sym_index
= 0, n
= 0;
398 s
= pe_export_name(s1
, sym
);
401 if (sym
->st_other
& ST_PE_STDCALL
) {
402 /* try w/0 stdcall deco (windows API convention) */
404 if (!p
|| s
[0] != '_')
406 strcpy(buffer
, s
+1)[p
-s
-1] = 0;
407 } else if (s
[0] != '_') { /* try non-ansi function */
408 buffer
[0] = '_', strcpy(buffer
+ 1, s
);
409 } else if (0 == memcmp(s
, "__imp__", 7)) { /* mingw 2.0 */
410 strcpy(buffer
, s
+ 6);
411 } else if (0 == memcmp(s
, "_imp___", 7)) { /* mingw 3.7 */
412 strcpy(buffer
, s
+ 6);
418 sym_index
= find_elf_sym(s1
->dynsymtab_section
, s
);
419 // printf("find (%d) %d %s\n", n, sym_index, s);
420 } while (0 == sym_index
&& ++n
< 2);
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
;
639 pe_header
.opthdr
.AddressOfEntryPoint
= addr
+ pe
->start_addr
;
643 #ifndef TCC_TARGET_X86_64
644 pe_header
.opthdr
.BaseOfData
= addr
;
652 pe_set_datadir(&pe_header
, IMAGE_DIRECTORY_ENTRY_BASERELOC
, addr
, size
);
656 pe_set_datadir(&pe_header
, IMAGE_DIRECTORY_ENTRY_RESOURCE
, addr
, size
);
660 pe_set_datadir(&pe_header
, IMAGE_DIRECTORY_ENTRY_EXCEPTION
, addr
, size
);
667 if (pe
->thunk
== pe
->s1
->sections
[si
->ord
]) {
669 pe_set_datadir(&pe_header
, IMAGE_DIRECTORY_ENTRY_IMPORT
,
670 pe
->imp_offs
+ addr
, pe
->imp_size
);
671 pe_set_datadir(&pe_header
, IMAGE_DIRECTORY_ENTRY_IAT
,
672 pe
->iat_offs
+ addr
, pe
->iat_size
);
675 pe_set_datadir(&pe_header
, IMAGE_DIRECTORY_ENTRY_EXPORT
,
676 pe
->exp_offs
+ addr
, pe
->exp_size
);
680 strncpy((char*)psh
->Name
, sh_name
, sizeof psh
->Name
);
682 psh
->Characteristics
= pe_sec_flags
[si
->cls
];
683 psh
->VirtualAddress
= addr
;
684 psh
->Misc
.VirtualSize
= size
;
685 pe_header
.opthdr
.SizeOfImage
=
686 umax(pe_virtual_align(pe
, size
+ addr
), pe_header
.opthdr
.SizeOfImage
);
689 psh
->PointerToRawData
= file_offset
;
690 file_offset
= pe_file_align(pe
, file_offset
+ si
->data_size
);
691 psh
->SizeOfRawData
= file_offset
- psh
->PointerToRawData
;
695 //pe_header.filehdr.TimeDateStamp = time(NULL);
696 pe_header
.filehdr
.NumberOfSections
= pe
->sec_count
;
697 pe_header
.opthdr
.SizeOfHeaders
= pe
->sizeofheaders
;
698 pe_header
.opthdr
.ImageBase
= pe
->imagebase
;
699 pe_header
.opthdr
.Subsystem
= pe
->subsystem
;
700 if (pe
->s1
->pe_stack_size
)
701 pe_header
.opthdr
.SizeOfStackReserve
= pe
->s1
->pe_stack_size
;
702 if (PE_DLL
== pe
->type
)
703 pe_header
.filehdr
.Characteristics
= CHARACTERISTICS_DLL
;
706 pe_fwrite(&pe_header
, sizeof pe_header
, op
, &sum
);
707 for (i
= 0; i
< pe
->sec_count
; ++i
)
708 pe_fwrite(&pe
->sec_info
[i
].ish
, sizeof(IMAGE_SECTION_HEADER
), op
, &sum
);
709 pe_fpad(op
, pe
->sizeofheaders
);
710 for (i
= 0; i
< pe
->sec_count
; ++i
) {
711 si
= pe
->sec_info
+ i
;
714 pe_fwrite(si
->data
, si
->data_size
, op
, &sum
);
715 file_offset
= psh
->PointerToRawData
+ psh
->SizeOfRawData
;
716 pe_fpad(op
, file_offset
);
720 pe_header
.opthdr
.CheckSum
= sum
+ file_offset
;
721 fseek(op
, offsetof(struct pe_header
, opthdr
.CheckSum
), SEEK_SET
);
722 pe_fwrite(&pe_header
.opthdr
.CheckSum
, sizeof pe_header
.opthdr
.CheckSum
, op
, NULL
);
725 if (2 == pe
->s1
->verbose
)
726 printf("-------------------------------\n");
728 printf("<- %s (%u bytes)\n", pe
->filename
, (unsigned)file_offset
);
733 /*----------------------------------------------------------------------------*/
735 static struct import_symbol
*pe_add_import(struct pe_info
*pe
, int sym_index
)
739 struct pe_import_info
*p
;
740 struct import_symbol
*s
;
743 isym
= (ElfW(Sym
) *)pe
->s1
->dynsymtab_section
->data
+ sym_index
;
744 dll_index
= isym
->st_size
;
746 i
= dynarray_assoc ((void**)pe
->imp_info
, pe
->imp_count
, dll_index
);
751 p
= tcc_mallocz(sizeof *p
);
752 p
->dll_index
= dll_index
;
753 dynarray_add((void***)&pe
->imp_info
, &pe
->imp_count
, p
);
756 i
= dynarray_assoc ((void**)p
->symbols
, p
->sym_count
, sym_index
);
758 return p
->symbols
[i
];
760 s
= tcc_mallocz(sizeof *s
);
761 dynarray_add((void***)&p
->symbols
, &p
->sym_count
, s
);
762 s
->sym_index
= sym_index
;
766 /*----------------------------------------------------------------------------*/
767 static void pe_build_imports(struct pe_info
*pe
)
769 int thk_ptr
, ent_ptr
, dll_ptr
, sym_cnt
, i
;
770 DWORD rva_base
= pe
->thunk
->sh_addr
- pe
->imagebase
;
771 int ndlls
= pe
->imp_count
;
773 for (sym_cnt
= i
= 0; i
< ndlls
; ++i
)
774 sym_cnt
+= pe
->imp_info
[i
]->sym_count
;
779 pe_align_section(pe
->thunk
, 16);
781 pe
->imp_offs
= dll_ptr
= pe
->thunk
->data_offset
;
782 pe
->imp_size
= (ndlls
+ 1) * sizeof(IMAGE_IMPORT_DESCRIPTOR
);
783 pe
->iat_offs
= dll_ptr
+ pe
->imp_size
;
784 pe
->iat_size
= (sym_cnt
+ ndlls
) * sizeof(ADDR3264
);
785 section_ptr_add(pe
->thunk
, pe
->imp_size
+ 2*pe
->iat_size
);
787 thk_ptr
= pe
->iat_offs
;
788 ent_ptr
= pe
->iat_offs
+ pe
->iat_size
;
790 for (i
= 0; i
< pe
->imp_count
; ++i
) {
791 IMAGE_IMPORT_DESCRIPTOR
*hdr
;
794 struct pe_import_info
*p
= pe
->imp_info
[i
];
796 DLLReference
*dllref
;
798 dllindex
= p
->dll_index
;
800 name
= (dllref
= pe
->s1
->loaded_dlls
[dllindex
-1])->name
;
802 name
= "", dllref
= NULL
;
804 /* put the dll name into the import header */
805 v
= put_elf_str(pe
->thunk
, name
);
806 hdr
= (IMAGE_IMPORT_DESCRIPTOR
*)(pe
->thunk
->data
+ dll_ptr
);
807 hdr
->FirstThunk
= thk_ptr
+ rva_base
;
808 hdr
->OriginalFirstThunk
= ent_ptr
+ rva_base
;
809 hdr
->Name
= v
+ rva_base
;
811 for (k
= 0, n
= p
->sym_count
; k
<= n
; ++k
) {
813 int iat_index
= p
->symbols
[k
]->iat_index
;
814 int sym_index
= p
->symbols
[k
]->sym_index
;
815 ElfW(Sym
) *imp_sym
= (ElfW(Sym
) *)pe
->s1
->dynsymtab_section
->data
+ sym_index
;
816 ElfW(Sym
) *org_sym
= (ElfW(Sym
) *)symtab_section
->data
+ iat_index
;
817 const char *name
= pe
->s1
->dynsymtab_section
->link
->data
+ imp_sym
->st_name
;
820 org_sym
->st_value
= thk_ptr
;
821 org_sym
->st_shndx
= pe
->thunk
->sh_num
;
824 v
= 0, ordinal
= imp_sym
->st_value
; /* ordinal from pe_load_def */
826 ordinal
= 0, v
= imp_sym
->st_value
; /* address from tcc_add_symbol() */
829 if (pe
->type
== PE_RUN
) {
831 if ( !dllref
->handle
)
832 dllref
->handle
= LoadLibrary(dllref
->name
);
833 v
= (ADDR3264
)GetProcAddress(dllref
->handle
, ordinal
?(LPCSTR
)NULL
+ordinal
:name
);
836 tcc_error_noabort("can't build symbol '%s'", name
);
840 v
= ordinal
| (ADDR3264
)1 << (sizeof(ADDR3264
)*8 - 1);
842 v
= pe
->thunk
->data_offset
+ rva_base
;
843 section_ptr_add(pe
->thunk
, sizeof(WORD
)); /* hint, not used */
844 put_elf_str(pe
->thunk
, name
);
848 v
= 0; /* last entry is zero */
851 *(ADDR3264
*)(pe
->thunk
->data
+thk_ptr
) =
852 *(ADDR3264
*)(pe
->thunk
->data
+ent_ptr
) = v
;
853 thk_ptr
+= sizeof (ADDR3264
);
854 ent_ptr
+= sizeof (ADDR3264
);
856 dll_ptr
+= sizeof(IMAGE_IMPORT_DESCRIPTOR
);
857 dynarray_reset(&p
->symbols
, &p
->sym_count
);
859 dynarray_reset(&pe
->imp_info
, &pe
->imp_count
);
862 /* ------------------------------------------------------------- */
870 static int sym_cmp(const void *va
, const void *vb
)
872 const char *ca
= (*(struct pe_sort_sym
**)va
)->name
;
873 const char *cb
= (*(struct pe_sort_sym
**)vb
)->name
;
874 return strcmp(ca
, cb
);
877 static void pe_build_exports(struct pe_info
*pe
)
880 int sym_index
, sym_end
;
881 DWORD rva_base
, func_o
, name_o
, ord_o
, str_o
;
882 IMAGE_EXPORT_DIRECTORY
*hdr
;
884 struct pe_sort_sym
**sorted
, *p
;
891 rva_base
= pe
->thunk
->sh_addr
- pe
->imagebase
;
892 sym_count
= 0, sorted
= NULL
, op
= NULL
;
894 sym_end
= symtab_section
->data_offset
/ sizeof(ElfW(Sym
));
895 for (sym_index
= 1; sym_index
< sym_end
; ++sym_index
) {
896 sym
= (ElfW(Sym
)*)symtab_section
->data
+ sym_index
;
897 name
= pe_export_name(pe
->s1
, sym
);
898 if ((sym
->st_other
& ST_PE_EXPORT
)
899 /* export only symbols from actually written sections */
900 && pe
->s1
->sections
[sym
->st_shndx
]->sh_addr
) {
901 p
= tcc_malloc(sizeof *p
);
902 p
->index
= sym_index
;
904 dynarray_add((void***)&sorted
, &sym_count
, p
);
907 if (sym
->st_other
& ST_PE_EXPORT
)
908 printf("export: %s\n", name
);
909 if (sym
->st_other
& ST_PE_STDCALL
)
910 printf("stdcall: %s\n", name
);
917 qsort (sorted
, sym_count
, sizeof *sorted
, sym_cmp
);
919 pe_align_section(pe
->thunk
, 16);
920 dllname
= tcc_basename(pe
->filename
);
922 pe
->exp_offs
= pe
->thunk
->data_offset
;
923 func_o
= pe
->exp_offs
+ sizeof(IMAGE_EXPORT_DIRECTORY
);
924 name_o
= func_o
+ sym_count
* sizeof (DWORD
);
925 ord_o
= name_o
+ sym_count
* sizeof (DWORD
);
926 str_o
= ord_o
+ sym_count
* sizeof(WORD
);
928 hdr
= section_ptr_add(pe
->thunk
, str_o
- pe
->exp_offs
);
929 hdr
->Characteristics
= 0;
931 hdr
->NumberOfFunctions
= sym_count
;
932 hdr
->NumberOfNames
= sym_count
;
933 hdr
->AddressOfFunctions
= func_o
+ rva_base
;
934 hdr
->AddressOfNames
= name_o
+ rva_base
;
935 hdr
->AddressOfNameOrdinals
= ord_o
+ rva_base
;
936 hdr
->Name
= str_o
+ rva_base
;
937 put_elf_str(pe
->thunk
, dllname
);
940 /* automatically write exports to <output-filename>.def */
941 pstrcpy(buf
, sizeof buf
, pe
->filename
);
942 strcpy(tcc_fileextension(buf
), ".def");
943 op
= fopen(buf
, "w");
945 tcc_error_noabort("could not create '%s': %s", buf
, strerror(errno
));
947 fprintf(op
, "LIBRARY %s\n\nEXPORTS\n", dllname
);
949 printf("<- %s (%d symbols)\n", buf
, sym_count
);
953 for (ord
= 0; ord
< sym_count
; ++ord
)
955 p
= sorted
[ord
], sym_index
= p
->index
, name
= p
->name
;
956 /* insert actual address later in pe_relocate_rva */
957 put_elf_reloc(symtab_section
, pe
->thunk
,
958 func_o
, R_XXX_RELATIVE
, sym_index
);
959 *(DWORD
*)(pe
->thunk
->data
+ name_o
)
960 = pe
->thunk
->data_offset
+ rva_base
;
961 *(WORD
*)(pe
->thunk
->data
+ ord_o
)
963 put_elf_str(pe
->thunk
, name
);
964 func_o
+= sizeof (DWORD
);
965 name_o
+= sizeof (DWORD
);
966 ord_o
+= sizeof (WORD
);
968 fprintf(op
, "%s\n", name
);
970 pe
->exp_size
= pe
->thunk
->data_offset
- pe
->exp_offs
;
971 dynarray_reset(&sorted
, &sym_count
);
976 /* ------------------------------------------------------------- */
977 static void pe_build_reloc (struct pe_info
*pe
)
979 DWORD offset
, block_ptr
, addr
;
981 ElfW_Rel
*rel
, *rel_end
;
982 Section
*s
= NULL
, *sr
;
984 offset
= addr
= block_ptr
= count
= i
= 0;
985 rel
= rel_end
= NULL
;
989 int type
= ELFW(R_TYPE
)(rel
->r_info
);
990 addr
= rel
->r_offset
+ s
->sh_addr
;
992 if (type
!= REL_TYPE_DIRECT
)
994 if (count
== 0) { /* new block */
995 block_ptr
= pe
->reloc
->data_offset
;
996 section_ptr_add(pe
->reloc
, sizeof(struct pe_reloc_header
));
997 offset
= addr
& 0xFFFFFFFF<<12;
999 if ((addr
-= offset
) < (1<<12)) { /* one block spans 4k addresses */
1000 WORD
*wp
= section_ptr_add(pe
->reloc
, sizeof (WORD
));
1001 *wp
= addr
| IMAGE_REL_BASED_HIGHLOW
<<12;
1007 } else if (i
< pe
->sec_count
) {
1008 sr
= (s
= pe
->s1
->sections
[pe
->sec_info
[i
++].ord
])->reloc
;
1010 rel
= (ElfW_Rel
*)sr
->data
;
1011 rel_end
= (ElfW_Rel
*)(sr
->data
+ sr
->data_offset
);
1017 /* store the last block and ready for a new one */
1018 struct pe_reloc_header
*hdr
;
1019 if (count
& 1) /* align for DWORDS */
1020 section_ptr_add(pe
->reloc
, sizeof(WORD
)), ++count
;
1021 hdr
= (struct pe_reloc_header
*)(pe
->reloc
->data
+ block_ptr
);
1022 hdr
-> offset
= offset
- pe
->imagebase
;
1023 hdr
-> size
= count
* sizeof(WORD
) + sizeof(struct pe_reloc_header
);
1032 /* ------------------------------------------------------------- */
1033 static int pe_section_class(Section
*s
)
1039 flags
= s
->sh_flags
;
1041 if (flags
& SHF_ALLOC
) {
1042 if (type
== SHT_PROGBITS
) {
1043 if (flags
& SHF_EXECINSTR
)
1045 if (flags
& SHF_WRITE
)
1047 if (0 == strcmp(name
, ".rsrc"))
1049 if (0 == strcmp(name
, ".iedat"))
1051 if (0 == strcmp(name
, ".pdata"))
1054 } else if (type
== SHT_NOBITS
) {
1055 if (flags
& SHF_WRITE
)
1059 if (0 == strcmp(name
, ".reloc"))
1061 if (0 == strncmp(name
, ".stab", 5)) /* .stab and .stabstr */
1067 static int pe_assign_addresses (struct pe_info
*pe
)
1072 struct section_info
*si
;
1075 // pe->thunk = new_section(pe->s1, ".iedat", SHT_PROGBITS, SHF_ALLOC);
1077 section_order
= tcc_malloc(pe
->s1
->nb_sections
* sizeof (int));
1078 for (o
= k
= 0 ; k
< sec_last
; ++k
) {
1079 for (i
= 1; i
< pe
->s1
->nb_sections
; ++i
) {
1080 s
= pe
->s1
->sections
[i
];
1081 if (k
== pe_section_class(s
)) {
1082 // printf("%s %d\n", s->name, k);
1083 s
->sh_addr
= pe
->imagebase
;
1084 section_order
[o
++] = i
;
1089 pe
->sec_info
= tcc_mallocz(o
* sizeof (struct section_info
));
1090 addr
= pe
->imagebase
+ 1;
1092 for (i
= 0; i
< o
; ++i
)
1094 k
= section_order
[i
];
1095 s
= pe
->s1
->sections
[k
];
1096 c
= pe_section_class(s
);
1097 si
= &pe
->sec_info
[pe
->sec_count
];
1099 #ifdef PE_MERGE_DATA
1100 if (c
== sec_bss
&& pe
->sec_count
&& si
[-1].cls
== sec_data
) {
1101 /* append .bss to .data */
1102 s
->sh_addr
= addr
= ((addr
-1) | (s
->sh_addralign
-1)) + 1;
1103 addr
+= s
->data_offset
;
1104 si
[-1].sh_size
= addr
- si
[-1].sh_addr
;
1108 if (c
== sec_stab
&& 0 == pe
->s1
->do_debug
)
1111 strcpy(si
->name
, s
->name
);
1114 si
->sh_addr
= s
->sh_addr
= addr
= pe_virtual_align(pe
, addr
);
1115 si
->sh_flags
= s
->sh_flags
;
1117 if (c
== sec_data
&& NULL
== pe
->thunk
)
1120 if (s
== pe
->thunk
) {
1121 pe_build_imports(pe
);
1122 pe_build_exports(pe
);
1126 pe_build_reloc (pe
);
1130 if (s
->sh_type
!= SHT_NOBITS
) {
1132 si
->data_size
= s
->data_offset
;
1135 addr
+= s
->data_offset
;
1136 si
->sh_size
= s
->data_offset
;
1139 // printf("%08x %05x %s\n", si->sh_addr, si->sh_size, si->name);
1143 for (i
= 1; i
< pe
->s1
->nb_sections
; ++i
) {
1144 Section
*s
= pe
->s1
->sections
[i
];
1145 int type
= s
->sh_type
;
1146 int flags
= s
->sh_flags
;
1147 printf("section %-16s %-10s %5x %s,%s,%s\n",
1149 type
== SHT_PROGBITS
? "progbits" :
1150 type
== SHT_NOBITS
? "nobits" :
1151 type
== SHT_SYMTAB
? "symtab" :
1152 type
== SHT_STRTAB
? "strtab" :
1153 type
== SHT_RELX
? "rel" : "???",
1155 flags
& SHF_ALLOC
? "alloc" : "",
1156 flags
& SHF_WRITE
? "write" : "",
1157 flags
& SHF_EXECINSTR
? "exec" : ""
1160 pe
->s1
->verbose
= 2;
1163 tcc_free(section_order
);
1167 /* ------------------------------------------------------------- */
1168 static void pe_relocate_rva (struct pe_info
*pe
, Section
*s
)
1170 Section
*sr
= s
->reloc
;
1171 ElfW_Rel
*rel
, *rel_end
;
1172 rel_end
= (ElfW_Rel
*)(sr
->data
+ sr
->data_offset
);
1173 for(rel
= (ElfW_Rel
*)sr
->data
; rel
< rel_end
; rel
++) {
1174 if (ELFW(R_TYPE
)(rel
->r_info
) == R_XXX_RELATIVE
) {
1175 int sym_index
= ELFW(R_SYM
)(rel
->r_info
);
1176 DWORD addr
= s
->sh_addr
;
1178 ElfW(Sym
) *sym
= (ElfW(Sym
) *)symtab_section
->data
+ sym_index
;
1179 addr
= sym
->st_value
;
1181 // printf("reloc rva %08x %08x %s\n", (DWORD)rel->r_offset, addr, s->name);
1182 *(DWORD
*)(s
->data
+ rel
->r_offset
) += addr
- pe
->imagebase
;
1187 /*----------------------------------------------------------------------------*/
1189 static int pe_isafunc(int sym_index
)
1191 Section
*sr
= text_section
->reloc
;
1192 ElfW_Rel
*rel
, *rel_end
;
1193 Elf32_Word info
= ELF32_R_INFO(sym_index
, R_386_PC32
);
1196 rel_end
= (ElfW_Rel
*)(sr
->data
+ sr
->data_offset
);
1197 for (rel
= (ElfW_Rel
*)sr
->data
; rel
< rel_end
; rel
++)
1198 if (rel
->r_info
== info
)
1203 /*----------------------------------------------------------------------------*/
1204 static int pe_check_symbols(struct pe_info
*pe
)
1207 int sym_index
, sym_end
;
1210 pe_align_section(text_section
, 8);
1212 sym_end
= symtab_section
->data_offset
/ sizeof(ElfW(Sym
));
1213 for (sym_index
= 1; sym_index
< sym_end
; ++sym_index
) {
1215 sym
= (ElfW(Sym
) *)symtab_section
->data
+ sym_index
;
1216 if (sym
->st_shndx
== SHN_UNDEF
) {
1218 const char *name
= symtab_section
->link
->data
+ sym
->st_name
;
1219 unsigned type
= ELFW(ST_TYPE
)(sym
->st_info
);
1220 int imp_sym
= pe_find_import(pe
->s1
, sym
);
1221 struct import_symbol
*is
;
1226 if (type
== STT_NOTYPE
) {
1227 /* symbols from assembler have no type, find out which */
1228 if (pe_isafunc(sym_index
))
1234 is
= pe_add_import(pe
, imp_sym
);
1236 if (type
== STT_FUNC
) {
1237 unsigned long offset
= is
->thk_offset
;
1239 /* got aliased symbol, like stricmp and _stricmp */
1245 offset
= text_section
->data_offset
;
1246 /* add the 'jmp IAT[x]' instruction */
1247 #ifdef TCC_TARGET_ARM
1248 p
= section_ptr_add(text_section
, 8+4); // room for code and address
1249 (*(DWORD
*)(p
)) = 0xE59FC000; // arm code ldr ip, [pc] ; PC+8+0 = 0001xxxx
1250 (*(DWORD
*)(p
+2)) = 0xE59CF000; // arm code ldr pc, [ip]
1252 p
= section_ptr_add(text_section
, 8);
1254 #ifdef TCC_TARGET_X86_64
1255 *(DWORD
*)(p
+1) = (DWORD
)-4;
1258 /* add a helper symbol, will be patched later in
1260 sprintf(buffer
, "IAT.%s", name
);
1261 is
->iat_index
= put_elf_sym(
1262 symtab_section
, 0, sizeof(DWORD
),
1263 ELFW(ST_INFO
)(STB_GLOBAL
, STT_OBJECT
),
1264 0, SHN_UNDEF
, buffer
);
1265 #ifdef TCC_TARGET_ARM
1266 put_elf_reloc(symtab_section
, text_section
,
1267 offset
+ 8, R_XXX_THUNKFIX
, is
->iat_index
); // offset to IAT position
1269 put_elf_reloc(symtab_section
, text_section
,
1270 offset
+ 2, R_XXX_THUNKFIX
, is
->iat_index
);
1272 is
->thk_offset
= offset
;
1275 /* tcc_realloc might have altered sym's address */
1276 sym
= (ElfW(Sym
) *)symtab_section
->data
+ sym_index
;
1278 /* patch the original symbol */
1279 sym
->st_value
= offset
;
1280 sym
->st_shndx
= text_section
->sh_num
;
1281 sym
->st_other
&= ~ST_PE_EXPORT
; /* do not export */
1285 if (type
== STT_OBJECT
) { /* data, ptr to that should be */
1286 if (0 == is
->iat_index
) {
1287 /* original symbol will be patched later in pe_build_imports */
1288 is
->iat_index
= sym_index
;
1294 tcc_error_noabort("undefined symbol '%s'", name
);
1297 } else if (pe
->s1
->rdynamic
1298 && ELFW(ST_BIND
)(sym
->st_info
) != STB_LOCAL
) {
1299 /* if -rdynamic option, then export all non local symbols */
1300 sym
->st_other
|= ST_PE_EXPORT
;
1306 /*----------------------------------------------------------------------------*/
1307 #ifdef PE_PRINT_SECTIONS
1308 static void pe_print_section(FILE * f
, Section
* s
)
1310 /* just if you'r curious */
1314 e
= s
->data
+ s
->data_offset
;
1317 fprintf(f
, "section \"%s\"", s
->name
);
1319 fprintf(f
, "\nlink \"%s\"", s
->link
->name
);
1321 fprintf(f
, "\nreloc \"%s\"", s
->reloc
->name
);
1322 fprintf(f
, "\nv_addr %08X", (unsigned)s
->sh_addr
);
1323 fprintf(f
, "\ncontents %08X", (unsigned)l
);
1326 if (s
->sh_type
== SHT_NOBITS
)
1332 if (s
->sh_type
== SHT_SYMTAB
)
1333 m
= sizeof(ElfW(Sym
));
1334 else if (s
->sh_type
== SHT_RELX
)
1335 m
= sizeof(ElfW_Rel
);
1339 fprintf(f
, "%-8s", "offset");
1340 for (i
= 0; i
< m
; ++i
)
1341 fprintf(f
, " %02x", i
);
1344 if (s
->sh_type
== SHT_SYMTAB
|| s
->sh_type
== SHT_RELX
) {
1345 const char *fields1
[] = {
1356 const char *fields2
[] = {
1365 if (s
->sh_type
== SHT_SYMTAB
)
1366 p
= fields1
, n
= 106;
1368 p
= fields2
, n
= 58;
1370 for (i
= 0; p
[i
]; ++i
)
1371 fprintf(f
, "%6s", p
[i
]);
1372 fprintf(f
, " symbol");
1376 for (i
= 0; i
< n
; ++i
)
1382 fprintf(f
, "%08X", i
);
1383 for (n
= 0; n
< m
; ++n
) {
1385 fprintf(f
, " %02X", p
[i
+ n
]);
1390 if (s
->sh_type
== SHT_SYMTAB
) {
1391 ElfW(Sym
) *sym
= (ElfW(Sym
) *) (p
+ i
);
1392 const char *name
= s
->link
->data
+ sym
->st_name
;
1393 fprintf(f
, " %04X %04X %04X %02X %02X %02X %04X \"%s\"",
1394 (unsigned)sym
->st_name
,
1395 (unsigned)sym
->st_value
,
1396 (unsigned)sym
->st_size
,
1397 (unsigned)ELFW(ST_BIND
)(sym
->st_info
),
1398 (unsigned)ELFW(ST_TYPE
)(sym
->st_info
),
1399 (unsigned)sym
->st_other
,
1400 (unsigned)sym
->st_shndx
,
1403 } else if (s
->sh_type
== SHT_RELX
) {
1404 ElfW_Rel
*rel
= (ElfW_Rel
*) (p
+ i
);
1406 (ElfW(Sym
) *) s
->link
->data
+ ELFW(R_SYM
)(rel
->r_info
);
1407 const char *name
= s
->link
->link
->data
+ sym
->st_name
;
1408 fprintf(f
, " %04X %02X %04X \"%s\"",
1409 (unsigned)rel
->r_offset
,
1410 (unsigned)ELFW(R_TYPE
)(rel
->r_info
),
1411 (unsigned)ELFW(R_SYM
)(rel
->r_info
),
1415 for (n
= 0; n
< m
; ++n
) {
1418 if (b
< 32 || b
>= 127)
1420 fprintf(f
, "%c", b
);
1430 static void pe_print_sections(TCCState
*s1
, const char *fname
)
1435 f
= fopen(fname
, "w");
1436 for (i
= 1; i
< s1
->nb_sections
; ++i
) {
1437 s
= s1
->sections
[i
];
1438 pe_print_section(f
, s
);
1440 pe_print_section(f
, s1
->dynsymtab_section
);
1445 /* ------------------------------------------------------------- */
1446 /* helper function for load/store to insert one more indirection */
1448 ST_FUNC SValue
*pe_getimport(SValue
*sv
, SValue
*v2
)
1454 if ((sv
->r
& (VT_VALMASK
|VT_SYM
)) != (VT_CONST
|VT_SYM
) || (sv
->r2
!= VT_CONST
))
1457 if ((sym
->type
.t
& (VT_EXTERN
|VT_STATIC
)) != VT_EXTERN
)
1460 put_extern_sym(sym
, NULL
, 0, 0);
1461 esym
= &((ElfW(Sym
) *)symtab_section
->data
)[sym
->c
];
1462 if (!(esym
->st_other
& ST_PE_IMPORT
))
1465 // printf("import %04x %04x %04x %s\n", sv->type.t, sym->type.t, sv->r, get_tok_str(sv->sym->v, NULL));
1467 memset(v2
, 0, sizeof *v2
);
1468 v2
->type
.t
= VT_PTR
;
1469 v2
->r
= VT_CONST
| VT_SYM
| VT_LVAL
;
1472 r2
= get_reg(RC_INT
);
1483 v2
->type
.t
= sv
->type
.t
;
1484 v2
->r
|= sv
->r
& VT_LVAL
;
1488 ST_FUNC
int pe_putimport(TCCState
*s1
, int dllindex
, const char *name
, addr_t value
)
1491 s1
->dynsymtab_section
,
1493 dllindex
, /* st_size */
1494 ELFW(ST_INFO
)(STB_GLOBAL
, STT_NOTYPE
),
1496 value
? SHN_ABS
: SHN_UNDEF
,
1501 static int add_dllref(TCCState
*s1
, const char *dllname
)
1503 DLLReference
*dllref
;
1505 for (i
= 0; i
< s1
->nb_loaded_dlls
; ++i
)
1506 if (0 == strcmp(s1
->loaded_dlls
[i
]->name
, dllname
))
1508 dllref
= tcc_mallocz(sizeof(DLLReference
) + strlen(dllname
));
1509 strcpy(dllref
->name
, dllname
);
1510 dynarray_add((void ***) &s1
->loaded_dlls
, &s1
->nb_loaded_dlls
, dllref
);
1511 return s1
->nb_loaded_dlls
;
1514 /* ------------------------------------------------------------- */
1516 static int read_mem(int fd
, unsigned offset
, void *buffer
, unsigned len
)
1518 lseek(fd
, offset
, SEEK_SET
);
1519 return len
== read(fd
, buffer
, len
);
1522 /* -------------------------------------------------------------
1523 * This is for compiled windows resources in 'coff' format
1524 * as generated by 'windres.exe -O coff ...'.
1527 static int pe_load_res(TCCState
*s1
, int fd
)
1529 struct pe_rsrc_header hdr
;
1530 Section
*rsrc_section
;
1535 if (!read_mem(fd
, 0, &hdr
, sizeof hdr
))
1538 if (hdr
.filehdr
.Machine
!= IMAGE_FILE_MACHINE
1539 || hdr
.filehdr
.NumberOfSections
!= 1
1540 || strcmp(hdr
.sectionhdr
.Name
, ".rsrc") != 0)
1543 rsrc_section
= new_section(s1
, ".rsrc", SHT_PROGBITS
, SHF_ALLOC
);
1544 ptr
= section_ptr_add(rsrc_section
, hdr
.sectionhdr
.SizeOfRawData
);
1545 offs
= hdr
.sectionhdr
.PointerToRawData
;
1546 if (!read_mem(fd
, offs
, ptr
, hdr
.sectionhdr
.SizeOfRawData
))
1548 offs
= hdr
.sectionhdr
.PointerToRelocations
;
1549 for (i
= 0; i
< hdr
.sectionhdr
.NumberOfRelocations
; ++i
)
1551 struct pe_rsrc_reloc rel
;
1552 if (!read_mem(fd
, offs
, &rel
, sizeof rel
))
1554 // printf("rsrc_reloc: %x %x %x\n", rel.offset, rel.size, rel.type);
1555 if (rel
.type
!= RSRC_RELTYPE
)
1557 put_elf_reloc(symtab_section
, rsrc_section
,
1558 rel
.offset
, R_XXX_RELATIVE
, 0);
1566 /* ------------------------------------------------------------- */
1567 static char *trimfront(char *p
)
1569 while (*p
&& (unsigned char)*p
<= ' ')
1574 static char *trimback(char *a
, char *e
)
1576 while (e
> a
&& (unsigned char)e
[-1] <= ' ')
1582 /* ------------------------------------------------------------- */
1583 static int pe_load_def(TCCState
*s1
, int fd
)
1585 int state
= 0, ret
= -1, dllindex
= 0, ord
;
1586 char line
[400], dllname
[80], *p
, *x
;
1589 fp
= fdopen(dup(fd
), "rb");
1590 while (fgets(line
, sizeof line
, fp
))
1592 p
= trimfront(trimback(line
, strchr(line
, 0)));
1593 if (0 == *p
|| ';' == *p
)
1598 if (0 != strnicmp(p
, "LIBRARY", 7))
1600 pstrcpy(dllname
, sizeof dllname
, trimfront(p
+7));
1605 if (0 != stricmp(p
, "EXPORTS"))
1611 dllindex
= add_dllref(s1
, dllname
);
1615 /* get ordinal and will store in sym->st_value */
1619 *x
= 0, x
= strrchr(x
+ 1, '@');
1622 ord
= (int)strtol(x
+ 1, &d
, 10);
1627 pe_putimport(s1
, dllindex
, p
, ord
);
1637 /* ------------------------------------------------------------- */
1638 #define TINY_IMPDEF_GET_EXPORT_NAMES_ONLY
1639 #include "win32/tools/tiny_impdef.c"
1641 static int pe_load_dll(TCCState
*s1
, const char *dllname
, int fd
)
1645 p
= get_export_names(fd
);
1648 index
= add_dllref(s1
, dllname
);
1649 for (q
= p
; *q
; q
+= 1 + strlen(q
))
1650 pe_putimport(s1
, index
, q
, 0);
1655 /* ------------------------------------------------------------- */
1656 ST_FUNC
int pe_load_file(struct TCCState
*s1
, const char *filename
, int fd
)
1660 if (0 == strcmp(tcc_fileextension(filename
), ".def"))
1661 ret
= pe_load_def(s1
, fd
);
1662 else if (pe_load_res(s1
, fd
) == 0)
1664 else if (read_mem(fd
, 0, buf
, sizeof buf
) && 0 == strncmp(buf
, "MZ", 2))
1665 ret
= pe_load_dll(s1
, tcc_basename(filename
), fd
);
1669 /* ------------------------------------------------------------- */
1670 #ifdef TCC_TARGET_X86_64
1671 static unsigned pe_add_uwwind_info(TCCState
*s1
)
1673 if (NULL
== s1
->uw_pdata
) {
1674 s1
->uw_pdata
= find_section(tcc_state
, ".pdata");
1675 s1
->uw_pdata
->sh_addralign
= 4;
1676 s1
->uw_sym
= put_elf_sym(symtab_section
, 0, 0, 0, 0, text_section
->sh_num
, NULL
);
1679 if (0 == s1
->uw_offs
) {
1680 /* As our functions all have the same stackframe, we use one entry for all */
1681 static const unsigned char uw_info
[] = {
1682 0x01, // UBYTE: 3 Version , UBYTE: 5 Flags
1683 0x04, // UBYTE Size of prolog
1684 0x02, // UBYTE Count of unwind codes
1685 0x05, // UBYTE: 4 Frame Register (rbp), UBYTE: 4 Frame Register offset (scaled)
1686 // USHORT * n Unwind codes array
1687 // 0x0b, 0x01, 0xff, 0xff, // stack size
1688 0x04, 0x03, // set frame ptr (mov rsp -> rbp)
1689 0x01, 0x50 // push reg (rbp)
1692 Section
*s
= text_section
;
1695 section_ptr_add(s
, -s
->data_offset
& 3); /* align */
1696 s1
->uw_offs
= s
->data_offset
;
1697 p
= section_ptr_add(s
, sizeof uw_info
);
1698 memcpy(p
, uw_info
, sizeof uw_info
);
1704 ST_FUNC
void pe_add_unwind_data(unsigned start
, unsigned end
, unsigned stack
)
1706 TCCState
*s1
= tcc_state
;
1709 struct /* _RUNTIME_FUNCTION */ {
1715 d
= pe_add_uwwind_info(s1
);
1717 o
= pd
->data_offset
;
1718 p
= section_ptr_add(pd
, sizeof *p
);
1720 /* record this function */
1721 p
->BeginAddress
= start
;
1722 p
->EndAddress
= end
;
1725 /* put relocations on it */
1726 for (n
= o
+ sizeof *p
; o
< n
; o
+= sizeof p
->BeginAddress
)
1727 put_elf_reloc(symtab_section
, pd
, o
, R_X86_64_RELATIVE
, s1
->uw_sym
);
1730 /* ------------------------------------------------------------- */
1731 #ifdef TCC_TARGET_X86_64
1732 #define PE_STDSYM(n,s) n
1734 #define PE_STDSYM(n,s) "_" n s
1737 static void pe_add_runtime(TCCState
*s1
, struct pe_info
*pe
)
1739 const char *start_symbol
;
1742 if (find_elf_sym(symtab_section
, PE_STDSYM("WinMain","@16")))
1745 if (TCC_OUTPUT_DLL
== s1
->output_type
) {
1747 /* need this for 'tccelf.c:relocate_section()' */
1748 s1
->output_type
= TCC_OUTPUT_EXE
;
1754 TCC_OUTPUT_MEMORY
== s1
->output_type
1755 ? PE_GUI
== pe_type
? "__runwinmain" : "_main"
1756 : PE_DLL
== pe_type
? PE_STDSYM("__dllstart","@12")
1757 : PE_GUI
== pe_type
? "__winstart" : "__start"
1760 if (!s1
->leading_underscore
|| strchr(start_symbol
, '@'))
1763 /* grab the startup code from libtcc1 */
1764 if (TCC_OUTPUT_MEMORY
!= s1
->output_type
|| PE_GUI
== pe_type
)
1765 add_elf_sym(symtab_section
,
1767 ELFW(ST_INFO
)(STB_GLOBAL
, STT_NOTYPE
), 0,
1768 SHN_UNDEF
, start_symbol
);
1770 tcc_add_pragma_libs(s1
);
1772 if (0 == s1
->nostdlib
) {
1773 static const char *libs
[] = {
1774 "tcc1", "msvcrt", "kernel32", "", "user32", "gdi32", NULL
1776 const char **pp
, *p
;
1777 for (pp
= libs
; 0 != (p
= *pp
); ++pp
) {
1779 if (PE_DLL
!= pe_type
&& PE_GUI
!= pe_type
)
1781 } else if (tcc_add_library_err(s1
, p
) < 0) {
1787 if (TCC_OUTPUT_MEMORY
== s1
->output_type
) {
1789 #ifdef TCC_IS_NATIVE
1790 s1
->runtime_main
= start_symbol
;
1793 pe
->start_addr
= (DWORD
)(uintptr_t)tcc_get_symbol_err(s1
, start_symbol
);
1799 ST_FUNC
int pe_output_file(TCCState
* s1
, const char *filename
)
1805 memset(&pe
, 0, sizeof pe
);
1806 pe
.filename
= filename
;
1809 pe_add_runtime(s1
, &pe
);
1811 relocate_common_syms(); /* assign bss adresses */
1812 tcc_add_linker_symbols(s1
);
1814 ret
= pe_check_symbols(&pe
);
1817 else if (filename
) {
1818 if (PE_DLL
== pe
.type
) {
1819 pe
.reloc
= new_section(pe
.s1
, ".reloc", SHT_PROGBITS
, 0);
1820 /* XXX: check if is correct for arm-pe target */
1821 pe
.imagebase
= 0x10000000;
1823 #if defined(TCC_TARGET_ARM)
1824 pe
.imagebase
= 0x00010000;
1826 pe
.imagebase
= 0x00400000;
1830 #if defined(TCC_TARGET_ARM)
1831 /* we use "console" subsystem by default */
1834 if (PE_DLL
== pe
.type
|| PE_GUI
== pe
.type
)
1839 /* Allow override via -Wl,-subsystem=... option */
1840 if (s1
->pe_subsystem
!= 0)
1841 pe
.subsystem
= s1
->pe_subsystem
;
1843 /* set default file/section alignment */
1844 if (pe
.subsystem
== 1) {
1845 pe
.section_align
= 0x20;
1846 pe
.file_align
= 0x20;
1848 pe
.section_align
= 0x1000;
1849 pe
.file_align
= 0x200;
1852 if (s1
->section_align
!= 0)
1853 pe
.section_align
= s1
->section_align
;
1854 if (s1
->pe_file_align
!= 0)
1855 pe
.file_align
= s1
->pe_file_align
;
1857 if ((pe
.subsystem
>= 10) && (pe
.subsystem
<= 12))
1860 if (s1
->has_text_addr
)
1861 pe
.imagebase
= s1
->text_addr
;
1863 pe_assign_addresses(&pe
);
1864 relocate_syms(s1
, 0);
1865 for (i
= 1; i
< s1
->nb_sections
; ++i
) {
1866 Section
*s
= s1
->sections
[i
];
1868 relocate_section(s1
, s
);
1869 pe_relocate_rva(&pe
, s
);
1875 ret
= pe_write(&pe
);
1876 tcc_free(pe
.sec_info
);
1878 #ifdef TCC_IS_NATIVE
1879 pe
.thunk
= data_section
;
1880 pe_build_imports(&pe
);
1884 #ifdef PE_PRINT_SECTIONS
1885 pe_print_sections(s1
, "tcc.log");
1890 /* ------------------------------------------------------------- */