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
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 */
63 void dbg_printf (const char *fmt
, ...)
69 x
= vsprintf (buffer
, fmt
, arg
);
70 strcpy(buffer
+x
, "\n");
71 OutputDebugString(buffer
);
76 /* ----------------------------------------------------------- */
77 #ifndef IMAGE_NT_SIGNATURE
78 /* ----------------------------------------------------------- */
79 /* definitions below are from winnt.h */
81 typedef unsigned char BYTE
;
82 typedef unsigned short WORD
;
83 typedef unsigned int DWORD
;
84 typedef unsigned long long ULONGLONG
;
87 typedef struct _IMAGE_DOS_HEADER
{ /* DOS .EXE header */
88 WORD e_magic
; /* Magic number */
89 WORD e_cblp
; /* Bytes on last page of file */
90 WORD e_cp
; /* Pages in file */
91 WORD e_crlc
; /* Relocations */
92 WORD e_cparhdr
; /* Size of header in paragraphs */
93 WORD e_minalloc
; /* Minimum extra paragraphs needed */
94 WORD e_maxalloc
; /* Maximum extra paragraphs needed */
95 WORD e_ss
; /* Initial (relative) SS value */
96 WORD e_sp
; /* Initial SP value */
97 WORD e_csum
; /* Checksum */
98 WORD e_ip
; /* Initial IP value */
99 WORD e_cs
; /* Initial (relative) CS value */
100 WORD e_lfarlc
; /* File address of relocation table */
101 WORD e_ovno
; /* Overlay number */
102 WORD e_res
[4]; /* Reserved words */
103 WORD e_oemid
; /* OEM identifier (for e_oeminfo) */
104 WORD e_oeminfo
; /* OEM information; e_oemid specific */
105 WORD e_res2
[10]; /* Reserved words */
106 DWORD e_lfanew
; /* File address of new exe header */
107 } IMAGE_DOS_HEADER
, *PIMAGE_DOS_HEADER
;
109 #define IMAGE_NT_SIGNATURE 0x00004550 /* PE00 */
110 #define SIZE_OF_NT_SIGNATURE 4
112 typedef struct _IMAGE_FILE_HEADER
{
114 WORD NumberOfSections
;
116 DWORD PointerToSymbolTable
;
117 DWORD NumberOfSymbols
;
118 WORD SizeOfOptionalHeader
;
119 WORD Characteristics
;
120 } IMAGE_FILE_HEADER
, *PIMAGE_FILE_HEADER
;
123 #define IMAGE_SIZEOF_FILE_HEADER 20
125 typedef struct _IMAGE_DATA_DIRECTORY
{
126 DWORD VirtualAddress
;
128 } IMAGE_DATA_DIRECTORY
, *PIMAGE_DATA_DIRECTORY
;
131 typedef struct _IMAGE_OPTIONAL_HEADER
{
132 /* Standard fields. */
134 BYTE MajorLinkerVersion
;
135 BYTE MinorLinkerVersion
;
137 DWORD SizeOfInitializedData
;
138 DWORD SizeOfUninitializedData
;
139 DWORD AddressOfEntryPoint
;
141 #ifndef TCC_TARGET_X86_64
144 /* NT additional fields. */
146 DWORD SectionAlignment
;
148 WORD MajorOperatingSystemVersion
;
149 WORD MinorOperatingSystemVersion
;
150 WORD MajorImageVersion
;
151 WORD MinorImageVersion
;
152 WORD MajorSubsystemVersion
;
153 WORD MinorSubsystemVersion
;
154 DWORD Win32VersionValue
;
159 WORD DllCharacteristics
;
160 ADDR3264 SizeOfStackReserve
;
161 ADDR3264 SizeOfStackCommit
;
162 ADDR3264 SizeOfHeapReserve
;
163 ADDR3264 SizeOfHeapCommit
;
165 DWORD NumberOfRvaAndSizes
;
166 IMAGE_DATA_DIRECTORY DataDirectory
[16];
167 } IMAGE_OPTIONAL_HEADER32
, IMAGE_OPTIONAL_HEADER64
, IMAGE_OPTIONAL_HEADER
;
169 #define IMAGE_DIRECTORY_ENTRY_EXPORT 0 /* Export Directory */
170 #define IMAGE_DIRECTORY_ENTRY_IMPORT 1 /* Import Directory */
171 #define IMAGE_DIRECTORY_ENTRY_RESOURCE 2 /* Resource Directory */
172 #define IMAGE_DIRECTORY_ENTRY_EXCEPTION 3 /* Exception Directory */
173 #define IMAGE_DIRECTORY_ENTRY_SECURITY 4 /* Security Directory */
174 #define IMAGE_DIRECTORY_ENTRY_BASERELOC 5 /* Base Relocation Table */
175 #define IMAGE_DIRECTORY_ENTRY_DEBUG 6 /* Debug Directory */
176 /* IMAGE_DIRECTORY_ENTRY_COPYRIGHT 7 (X86 usage) */
177 #define IMAGE_DIRECTORY_ENTRY_ARCHITECTURE 7 /* Architecture Specific Data */
178 #define IMAGE_DIRECTORY_ENTRY_GLOBALPTR 8 /* RVA of GP */
179 #define IMAGE_DIRECTORY_ENTRY_TLS 9 /* TLS Directory */
180 #define IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG 10 /* Load Configuration Directory */
181 #define IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT 11 /* Bound Import Directory in headers */
182 #define IMAGE_DIRECTORY_ENTRY_IAT 12 /* Import Address Table */
183 #define IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT 13 /* Delay Load Import Descriptors */
184 #define IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR 14 /* COM Runtime descriptor */
186 /* Section header format. */
187 #define IMAGE_SIZEOF_SHORT_NAME 8
189 typedef struct _IMAGE_SECTION_HEADER
{
190 BYTE Name
[IMAGE_SIZEOF_SHORT_NAME
];
192 DWORD PhysicalAddress
;
195 DWORD VirtualAddress
;
197 DWORD PointerToRawData
;
198 DWORD PointerToRelocations
;
199 DWORD PointerToLinenumbers
;
200 WORD NumberOfRelocations
;
201 WORD NumberOfLinenumbers
;
202 DWORD Characteristics
;
203 } IMAGE_SECTION_HEADER
, *PIMAGE_SECTION_HEADER
;
205 #define IMAGE_SIZEOF_SECTION_HEADER 40
207 typedef struct _IMAGE_EXPORT_DIRECTORY
{
208 DWORD Characteristics
;
214 DWORD NumberOfFunctions
;
216 DWORD AddressOfFunctions
;
217 DWORD AddressOfNames
;
218 DWORD AddressOfNameOrdinals
;
219 } IMAGE_EXPORT_DIRECTORY
,*PIMAGE_EXPORT_DIRECTORY
;
221 typedef struct _IMAGE_IMPORT_DESCRIPTOR
{
223 DWORD Characteristics
;
224 DWORD OriginalFirstThunk
;
227 DWORD ForwarderChain
;
230 } IMAGE_IMPORT_DESCRIPTOR
;
232 typedef struct _IMAGE_BASE_RELOCATION
{
233 DWORD VirtualAddress
;
235 // WORD TypeOffset[1];
236 } IMAGE_BASE_RELOCATION
;
238 #define IMAGE_SIZEOF_BASE_RELOCATION 8
240 #define IMAGE_REL_BASED_ABSOLUTE 0
241 #define IMAGE_REL_BASED_HIGH 1
242 #define IMAGE_REL_BASED_LOW 2
243 #define IMAGE_REL_BASED_HIGHLOW 3
244 #define IMAGE_REL_BASED_HIGHADJ 4
245 #define IMAGE_REL_BASED_MIPS_JMPADDR 5
246 #define IMAGE_REL_BASED_SECTION 6
247 #define IMAGE_REL_BASED_REL32 7
251 /* ----------------------------------------------------------- */
252 #endif /* ndef IMAGE_NT_SIGNATURE */
253 /* ----------------------------------------------------------- */
254 #pragma pack(push, 1)
258 IMAGE_DOS_HEADER doshdr
;
261 IMAGE_FILE_HEADER filehdr
;
262 #ifdef TCC_TARGET_X86_64
263 IMAGE_OPTIONAL_HEADER64 opthdr
;
266 IMAGE_OPTIONAL_HEADER32 opthdr
;
268 IMAGE_OPTIONAL_HEADER opthdr
;
273 struct pe_reloc_header
{
278 struct pe_rsrc_header
{
279 struct _IMAGE_FILE_HEADER filehdr
;
280 struct _IMAGE_SECTION_HEADER sectionhdr
;
283 struct pe_rsrc_reloc
{
291 /* ------------------------------------------------------------- */
292 /* internal temporary structures */
295 #define IMAGE_SCN_CNT_CODE 0x00000020
296 #define IMAGE_SCN_CNT_INITIALIZED_DATA 0x00000040
297 #define IMAGE_SCN_CNT_UNINITIALIZED_DATA 0x00000080
298 #define IMAGE_SCN_MEM_DISCARDABLE 0x02000000
299 #define IMAGE_SCN_MEM_SHARED 0x10000000
300 #define IMAGE_SCN_MEM_EXECUTE 0x20000000
301 #define IMAGE_SCN_MEM_READ 0x40000000
302 #define IMAGE_SCN_MEM_WRITE 0x80000000
318 static const DWORD pe_sec_flags
[] = {
319 0x60000020, /* ".text" , */
320 0xC0000040, /* ".data" , */
321 0xC0000080, /* ".bss" , */
322 0x40000040, /* ".idata" , */
323 0x40000040, /* ".pdata" , */
324 0xE0000060, /* < other > , */
325 0x40000040, /* ".rsrc" , */
326 0x42000802, /* ".stab" , */
327 0x42000040, /* ".reloc" , */
330 struct section_info
{
338 IMAGE_SECTION_HEADER ish
;
341 struct import_symbol
{
347 struct pe_import_info
{
350 struct import_symbol
**symbols
;
357 const char *filename
;
371 struct section_info
*sec_info
;
373 struct pe_import_info
**imp_info
;
383 /* --------------------------------------------*/
385 static const char *pe_export_name(TCCState
*s1
, ElfW(Sym
) *sym
)
387 const char *name
= symtab_section
->link
->data
+ sym
->st_name
;
388 if (s1
->leading_underscore
&& name
[0] == '_' && !(sym
->st_other
& ST_PE_STDCALL
))
393 static int pe_find_import(TCCState
* s1
, ElfW(Sym
) *sym
)
397 int sym_index
= 0, n
= 0;
400 s
= pe_export_name(s1
, sym
);
403 if (sym
->st_other
& ST_PE_STDCALL
) {
404 /* try w/0 stdcall deco (windows API convention) */
406 if (!p
|| s
[0] != '_')
408 strcpy(buffer
, s
+1)[p
-s
-1] = 0;
409 } else if (s
[0] != '_') { /* try non-ansi function */
410 buffer
[0] = '_', strcpy(buffer
+ 1, s
);
411 } else if (0 == memcmp(s
, "__imp__", 7)) { /* mingw 2.0 */
412 strcpy(buffer
, s
+ 6);
413 } else if (0 == memcmp(s
, "_imp___", 7)) { /* mingw 3.7 */
414 strcpy(buffer
, s
+ 6);
420 sym_index
= find_elf_sym(s1
->dynsymtab_section
, s
);
421 // printf("find (%d) %d %s\n", n, sym_index, s);
422 } while (0 == sym_index
&& ++n
< 2);
426 /*----------------------------------------------------------------------------*/
428 static int dynarray_assoc(void **pp
, int n
, int key
)
431 for (i
= 0; i
< n
; ++i
, ++pp
)
432 if (key
== **(int **) pp
)
438 ST_FN DWORD
umin(DWORD a
, DWORD b
)
440 return a
< b
? a
: b
;
444 static DWORD
umax(DWORD a
, DWORD b
)
446 return a
< b
? b
: a
;
449 static DWORD
pe_file_align(struct pe_info
*pe
, DWORD n
)
451 return (n
+ (pe
->file_align
- 1)) & ~(pe
->file_align
- 1);
454 static DWORD
pe_virtual_align(struct pe_info
*pe
, DWORD n
)
456 return (n
+ (pe
->section_align
- 1)) & ~(pe
->section_align
- 1);
459 static void pe_align_section(Section
*s
, int a
)
461 int i
= s
->data_offset
& (a
-1);
463 section_ptr_add(s
, a
- i
);
466 static void pe_set_datadir(struct pe_header
*hdr
, int dir
, DWORD addr
, DWORD size
)
468 hdr
->opthdr
.DataDirectory
[dir
].VirtualAddress
= addr
;
469 hdr
->opthdr
.DataDirectory
[dir
].Size
= size
;
472 static int pe_fwrite(void *data
, unsigned len
, FILE *fp
, DWORD
*psum
)
478 for (i
= len
; i
> 0; i
-= 2) {
479 sum
+= (i
>= 2) ? *p
++ : *(BYTE
*)p
;
480 sum
= (sum
+ (sum
>> 16)) & 0xFFFF;
484 return len
== fwrite(data
, 1, len
, fp
) ? 0 : -1;
487 static void pe_fpad(FILE *fp
, DWORD new_pos
)
489 DWORD pos
= ftell(fp
);
490 while (++pos
<= new_pos
)
494 /*----------------------------------------------------------------------------*/
495 static int pe_write(struct pe_info
*pe
)
497 static const struct pe_header pe_template
= {
499 /* IMAGE_DOS_HEADER doshdr */
500 0x5A4D, /*WORD e_magic; Magic number */
501 0x0090, /*WORD e_cblp; Bytes on last page of file */
502 0x0003, /*WORD e_cp; Pages in file */
503 0x0000, /*WORD e_crlc; Relocations */
505 0x0004, /*WORD e_cparhdr; Size of header in paragraphs */
506 0x0000, /*WORD e_minalloc; Minimum extra paragraphs needed */
507 0xFFFF, /*WORD e_maxalloc; Maximum extra paragraphs needed */
508 0x0000, /*WORD e_ss; Initial (relative) SS value */
510 0x00B8, /*WORD e_sp; Initial SP value */
511 0x0000, /*WORD e_csum; Checksum */
512 0x0000, /*WORD e_ip; Initial IP value */
513 0x0000, /*WORD e_cs; Initial (relative) CS value */
514 0x0040, /*WORD e_lfarlc; File address of relocation table */
515 0x0000, /*WORD e_ovno; Overlay number */
516 {0,0,0,0}, /*WORD e_res[4]; Reserved words */
517 0x0000, /*WORD e_oemid; OEM identifier (for e_oeminfo) */
518 0x0000, /*WORD e_oeminfo; OEM information; e_oemid specific */
519 {0,0,0,0,0,0,0,0,0,0}, /*WORD e_res2[10]; Reserved words */
520 0x00000080 /*DWORD e_lfanew; File address of new exe header */
522 /* BYTE dosstub[0x40] */
523 /* 14 code bytes + "This program cannot be run in DOS mode.\r\r\n$" + 6 * 0x00 */
524 0x0e,0x1f,0xba,0x0e,0x00,0xb4,0x09,0xcd,0x21,0xb8,0x01,0x4c,0xcd,0x21,0x54,0x68,
525 0x69,0x73,0x20,0x70,0x72,0x6f,0x67,0x72,0x61,0x6d,0x20,0x63,0x61,0x6e,0x6e,0x6f,
526 0x74,0x20,0x62,0x65,0x20,0x72,0x75,0x6e,0x20,0x69,0x6e,0x20,0x44,0x4f,0x53,0x20,
527 0x6d,0x6f,0x64,0x65,0x2e,0x0d,0x0d,0x0a,0x24,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
529 0x00004550, /* DWORD nt_sig = IMAGE_NT_SIGNATURE */
531 /* IMAGE_FILE_HEADER filehdr */
532 IMAGE_FILE_MACHINE
, /*WORD Machine; */
533 0x0003, /*WORD NumberOfSections; */
534 0x00000000, /*DWORD TimeDateStamp; */
535 0x00000000, /*DWORD PointerToSymbolTable; */
536 0x00000000, /*DWORD NumberOfSymbols; */
537 #if defined(TCC_TARGET_X86_64)
538 0x00F0, /*WORD SizeOfOptionalHeader; */
539 0x022F /*WORD Characteristics; */
540 #define CHARACTERISTICS_DLL 0x222E
541 #elif defined(TCC_TARGET_I386)
542 0x00E0, /*WORD SizeOfOptionalHeader; */
543 0x030F /*WORD Characteristics; */
544 #define CHARACTERISTICS_DLL 0x230E
545 #elif defined(TCC_TARGET_ARM)
546 0x00E0, /*WORD SizeOfOptionalHeader; */
547 0x010F, /*WORD Characteristics; */
548 #define CHARACTERISTICS_DLL 0x230F
551 /* IMAGE_OPTIONAL_HEADER opthdr */
552 /* Standard fields. */
553 #ifdef TCC_TARGET_X86_64
554 0x020B, /*WORD Magic; */
556 0x010B, /*WORD Magic; */
558 0x06, /*BYTE MajorLinkerVersion; */
559 0x00, /*BYTE MinorLinkerVersion; */
560 0x00000000, /*DWORD SizeOfCode; */
561 0x00000000, /*DWORD SizeOfInitializedData; */
562 0x00000000, /*DWORD SizeOfUninitializedData; */
563 0x00000000, /*DWORD AddressOfEntryPoint; */
564 0x00000000, /*DWORD BaseOfCode; */
565 #ifndef TCC_TARGET_X86_64
566 0x00000000, /*DWORD BaseOfData; */
568 /* NT additional fields. */
569 #if defined(TCC_TARGET_ARM)
570 0x00100000, /*DWORD ImageBase; */
572 0x00400000, /*DWORD ImageBase; */
574 0x00001000, /*DWORD SectionAlignment; */
575 0x00000200, /*DWORD FileAlignment; */
576 0x0004, /*WORD MajorOperatingSystemVersion; */
577 0x0000, /*WORD MinorOperatingSystemVersion; */
578 0x0000, /*WORD MajorImageVersion; */
579 0x0000, /*WORD MinorImageVersion; */
580 0x0004, /*WORD MajorSubsystemVersion; */
581 0x0000, /*WORD MinorSubsystemVersion; */
582 0x00000000, /*DWORD Win32VersionValue; */
583 0x00000000, /*DWORD SizeOfImage; */
584 0x00000200, /*DWORD SizeOfHeaders; */
585 0x00000000, /*DWORD CheckSum; */
586 0x0002, /*WORD Subsystem; */
587 0x0000, /*WORD DllCharacteristics; */
588 0x00100000, /*DWORD SizeOfStackReserve; */
589 0x00001000, /*DWORD SizeOfStackCommit; */
590 0x00100000, /*DWORD SizeOfHeapReserve; */
591 0x00001000, /*DWORD SizeOfHeapCommit; */
592 0x00000000, /*DWORD LoaderFlags; */
593 0x00000010, /*DWORD NumberOfRvaAndSizes; */
595 /* IMAGE_DATA_DIRECTORY DataDirectory[16]; */
596 {{0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0},
597 {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}}
600 struct pe_header pe_header
= pe_template
;
604 DWORD file_offset
, sum
;
605 struct section_info
*si
;
606 IMAGE_SECTION_HEADER
*psh
;
608 op
= fopen(pe
->filename
, "wb");
610 tcc_error_noabort("could not write '%s': %s", pe
->filename
, strerror(errno
));
614 pe
->sizeofheaders
= pe_file_align(pe
,
615 sizeof (struct pe_header
)
616 + pe
->sec_count
* sizeof (IMAGE_SECTION_HEADER
)
619 file_offset
= pe
->sizeofheaders
;
621 if (2 == pe
->s1
->verbose
)
622 printf("-------------------------------"
623 "\n virt file size section" "\n");
624 for (i
= 0; i
< pe
->sec_count
; ++i
) {
628 si
= pe
->sec_info
+ i
;
630 addr
= si
->sh_addr
- pe
->imagebase
;
634 if (2 == pe
->s1
->verbose
)
635 printf("%6x %6x %6x %s\n",
636 (unsigned)addr
, (unsigned)file_offset
, (unsigned)size
, sh_name
);
640 pe_header
.opthdr
.BaseOfCode
= addr
;
641 pe_header
.opthdr
.AddressOfEntryPoint
= addr
+ pe
->start_addr
;
645 #ifndef TCC_TARGET_X86_64
646 pe_header
.opthdr
.BaseOfData
= addr
;
654 pe_set_datadir(&pe_header
, IMAGE_DIRECTORY_ENTRY_BASERELOC
, addr
, size
);
658 pe_set_datadir(&pe_header
, IMAGE_DIRECTORY_ENTRY_RESOURCE
, addr
, size
);
662 pe_set_datadir(&pe_header
, IMAGE_DIRECTORY_ENTRY_EXCEPTION
, addr
, size
);
669 if (pe
->thunk
== pe
->s1
->sections
[si
->ord
]) {
671 pe_set_datadir(&pe_header
, IMAGE_DIRECTORY_ENTRY_IMPORT
,
672 pe
->imp_offs
+ addr
, pe
->imp_size
);
673 pe_set_datadir(&pe_header
, IMAGE_DIRECTORY_ENTRY_IAT
,
674 pe
->iat_offs
+ addr
, pe
->iat_size
);
677 pe_set_datadir(&pe_header
, IMAGE_DIRECTORY_ENTRY_EXPORT
,
678 pe
->exp_offs
+ addr
, pe
->exp_size
);
682 strncpy((char*)psh
->Name
, sh_name
, sizeof psh
->Name
);
684 psh
->Characteristics
= pe_sec_flags
[si
->cls
];
685 psh
->VirtualAddress
= addr
;
686 psh
->Misc
.VirtualSize
= size
;
687 pe_header
.opthdr
.SizeOfImage
=
688 umax(pe_virtual_align(pe
, size
+ addr
), pe_header
.opthdr
.SizeOfImage
);
691 psh
->PointerToRawData
= file_offset
;
692 file_offset
= pe_file_align(pe
, file_offset
+ si
->data_size
);
693 psh
->SizeOfRawData
= file_offset
- psh
->PointerToRawData
;
697 //pe_header.filehdr.TimeDateStamp = time(NULL);
698 pe_header
.filehdr
.NumberOfSections
= pe
->sec_count
;
699 pe_header
.opthdr
.SizeOfHeaders
= pe
->sizeofheaders
;
700 pe_header
.opthdr
.ImageBase
= pe
->imagebase
;
701 pe_header
.opthdr
.Subsystem
= pe
->subsystem
;
702 if (pe
->s1
->pe_stack_size
)
703 pe_header
.opthdr
.SizeOfStackReserve
= pe
->s1
->pe_stack_size
;
704 if (PE_DLL
== pe
->type
)
705 pe_header
.filehdr
.Characteristics
= CHARACTERISTICS_DLL
;
706 pe_header
.filehdr
.Characteristics
|= pe
->s1
->pe_characteristics
;
709 pe_fwrite(&pe_header
, sizeof pe_header
, op
, &sum
);
710 for (i
= 0; i
< pe
->sec_count
; ++i
)
711 pe_fwrite(&pe
->sec_info
[i
].ish
, sizeof(IMAGE_SECTION_HEADER
), op
, &sum
);
712 pe_fpad(op
, pe
->sizeofheaders
);
713 for (i
= 0; i
< pe
->sec_count
; ++i
) {
714 si
= pe
->sec_info
+ i
;
717 pe_fwrite(si
->data
, si
->data_size
, op
, &sum
);
718 file_offset
= psh
->PointerToRawData
+ psh
->SizeOfRawData
;
719 pe_fpad(op
, file_offset
);
723 pe_header
.opthdr
.CheckSum
= sum
+ file_offset
;
724 fseek(op
, offsetof(struct pe_header
, opthdr
.CheckSum
), SEEK_SET
);
725 pe_fwrite(&pe_header
.opthdr
.CheckSum
, sizeof pe_header
.opthdr
.CheckSum
, op
, NULL
);
728 if (2 == pe
->s1
->verbose
)
729 printf("-------------------------------\n");
731 printf("<- %s (%u bytes)\n", pe
->filename
, (unsigned)file_offset
);
736 /*----------------------------------------------------------------------------*/
738 static struct import_symbol
*pe_add_import(struct pe_info
*pe
, int sym_index
)
742 struct pe_import_info
*p
;
743 struct import_symbol
*s
;
746 isym
= (ElfW(Sym
) *)pe
->s1
->dynsymtab_section
->data
+ sym_index
;
747 dll_index
= isym
->st_size
;
749 i
= dynarray_assoc ((void**)pe
->imp_info
, pe
->imp_count
, dll_index
);
754 p
= tcc_mallocz(sizeof *p
);
755 p
->dll_index
= dll_index
;
756 dynarray_add((void***)&pe
->imp_info
, &pe
->imp_count
, p
);
759 i
= dynarray_assoc ((void**)p
->symbols
, p
->sym_count
, sym_index
);
761 return p
->symbols
[i
];
763 s
= tcc_mallocz(sizeof *s
);
764 dynarray_add((void***)&p
->symbols
, &p
->sym_count
, s
);
765 s
->sym_index
= sym_index
;
769 /*----------------------------------------------------------------------------*/
770 static void pe_build_imports(struct pe_info
*pe
)
772 int thk_ptr
, ent_ptr
, dll_ptr
, sym_cnt
, i
;
773 DWORD rva_base
= pe
->thunk
->sh_addr
- pe
->imagebase
;
774 int ndlls
= pe
->imp_count
;
776 for (sym_cnt
= i
= 0; i
< ndlls
; ++i
)
777 sym_cnt
+= pe
->imp_info
[i
]->sym_count
;
782 pe_align_section(pe
->thunk
, 16);
784 pe
->imp_offs
= dll_ptr
= pe
->thunk
->data_offset
;
785 pe
->imp_size
= (ndlls
+ 1) * sizeof(IMAGE_IMPORT_DESCRIPTOR
);
786 pe
->iat_offs
= dll_ptr
+ pe
->imp_size
;
787 pe
->iat_size
= (sym_cnt
+ ndlls
) * sizeof(ADDR3264
);
788 section_ptr_add(pe
->thunk
, pe
->imp_size
+ 2*pe
->iat_size
);
790 thk_ptr
= pe
->iat_offs
;
791 ent_ptr
= pe
->iat_offs
+ pe
->iat_size
;
793 for (i
= 0; i
< pe
->imp_count
; ++i
) {
794 IMAGE_IMPORT_DESCRIPTOR
*hdr
;
797 struct pe_import_info
*p
= pe
->imp_info
[i
];
799 DLLReference
*dllref
;
801 dllindex
= p
->dll_index
;
803 name
= (dllref
= pe
->s1
->loaded_dlls
[dllindex
-1])->name
;
805 name
= "", dllref
= NULL
;
807 /* put the dll name into the import header */
808 v
= put_elf_str(pe
->thunk
, name
);
809 hdr
= (IMAGE_IMPORT_DESCRIPTOR
*)(pe
->thunk
->data
+ dll_ptr
);
810 hdr
->FirstThunk
= thk_ptr
+ rva_base
;
811 hdr
->OriginalFirstThunk
= ent_ptr
+ rva_base
;
812 hdr
->Name
= v
+ rva_base
;
814 for (k
= 0, n
= p
->sym_count
; k
<= n
; ++k
) {
816 int iat_index
= p
->symbols
[k
]->iat_index
;
817 int sym_index
= p
->symbols
[k
]->sym_index
;
818 ElfW(Sym
) *imp_sym
= (ElfW(Sym
) *)pe
->s1
->dynsymtab_section
->data
+ sym_index
;
819 ElfW(Sym
) *org_sym
= (ElfW(Sym
) *)symtab_section
->data
+ iat_index
;
820 const char *name
= pe
->s1
->dynsymtab_section
->link
->data
+ imp_sym
->st_name
;
823 org_sym
->st_value
= thk_ptr
;
824 org_sym
->st_shndx
= pe
->thunk
->sh_num
;
827 v
= 0, ordinal
= imp_sym
->st_value
; /* ordinal from pe_load_def */
829 ordinal
= 0, v
= imp_sym
->st_value
; /* address from tcc_add_symbol() */
832 if (pe
->type
== PE_RUN
) {
834 if ( !dllref
->handle
)
835 dllref
->handle
= LoadLibrary(dllref
->name
);
836 v
= (ADDR3264
)GetProcAddress(dllref
->handle
, ordinal
?(char*)0+ordinal
:name
);
839 tcc_error_noabort("can't build symbol '%s'", name
);
843 v
= ordinal
| (ADDR3264
)1 << (sizeof(ADDR3264
)*8 - 1);
845 v
= pe
->thunk
->data_offset
+ rva_base
;
846 section_ptr_add(pe
->thunk
, sizeof(WORD
)); /* hint, not used */
847 put_elf_str(pe
->thunk
, name
);
851 v
= 0; /* last entry is zero */
854 *(ADDR3264
*)(pe
->thunk
->data
+thk_ptr
) =
855 *(ADDR3264
*)(pe
->thunk
->data
+ent_ptr
) = v
;
856 thk_ptr
+= sizeof (ADDR3264
);
857 ent_ptr
+= sizeof (ADDR3264
);
859 dll_ptr
+= sizeof(IMAGE_IMPORT_DESCRIPTOR
);
860 dynarray_reset(&p
->symbols
, &p
->sym_count
);
862 dynarray_reset(&pe
->imp_info
, &pe
->imp_count
);
865 /* ------------------------------------------------------------- */
873 static int sym_cmp(const void *va
, const void *vb
)
875 const char *ca
= (*(struct pe_sort_sym
**)va
)->name
;
876 const char *cb
= (*(struct pe_sort_sym
**)vb
)->name
;
877 return strcmp(ca
, cb
);
880 static void pe_build_exports(struct pe_info
*pe
)
883 int sym_index
, sym_end
;
884 DWORD rva_base
, func_o
, name_o
, ord_o
, str_o
;
885 IMAGE_EXPORT_DIRECTORY
*hdr
;
887 struct pe_sort_sym
**sorted
, *p
;
894 rva_base
= pe
->thunk
->sh_addr
- pe
->imagebase
;
895 sym_count
= 0, sorted
= NULL
, op
= NULL
;
897 sym_end
= symtab_section
->data_offset
/ sizeof(ElfW(Sym
));
898 for (sym_index
= 1; sym_index
< sym_end
; ++sym_index
) {
899 sym
= (ElfW(Sym
)*)symtab_section
->data
+ sym_index
;
900 name
= pe_export_name(pe
->s1
, sym
);
901 if ((sym
->st_other
& ST_PE_EXPORT
)
902 /* export only symbols from actually written sections */
903 && pe
->s1
->sections
[sym
->st_shndx
]->sh_addr
) {
904 p
= tcc_malloc(sizeof *p
);
905 p
->index
= sym_index
;
907 dynarray_add((void***)&sorted
, &sym_count
, p
);
910 if (sym
->st_other
& ST_PE_EXPORT
)
911 printf("export: %s\n", name
);
912 if (sym
->st_other
& ST_PE_STDCALL
)
913 printf("stdcall: %s\n", name
);
920 qsort (sorted
, sym_count
, sizeof *sorted
, sym_cmp
);
922 pe_align_section(pe
->thunk
, 16);
923 dllname
= tcc_basename(pe
->filename
);
925 pe
->exp_offs
= pe
->thunk
->data_offset
;
926 func_o
= pe
->exp_offs
+ sizeof(IMAGE_EXPORT_DIRECTORY
);
927 name_o
= func_o
+ sym_count
* sizeof (DWORD
);
928 ord_o
= name_o
+ sym_count
* sizeof (DWORD
);
929 str_o
= ord_o
+ sym_count
* sizeof(WORD
);
931 hdr
= section_ptr_add(pe
->thunk
, str_o
- pe
->exp_offs
);
932 hdr
->Characteristics
= 0;
934 hdr
->NumberOfFunctions
= sym_count
;
935 hdr
->NumberOfNames
= sym_count
;
936 hdr
->AddressOfFunctions
= func_o
+ rva_base
;
937 hdr
->AddressOfNames
= name_o
+ rva_base
;
938 hdr
->AddressOfNameOrdinals
= ord_o
+ rva_base
;
939 hdr
->Name
= str_o
+ rva_base
;
940 put_elf_str(pe
->thunk
, dllname
);
943 /* automatically write exports to <output-filename>.def */
944 pstrcpy(buf
, sizeof buf
, pe
->filename
);
945 strcpy(tcc_fileextension(buf
), ".def");
946 op
= fopen(buf
, "w");
948 tcc_error_noabort("could not create '%s': %s", buf
, strerror(errno
));
950 fprintf(op
, "LIBRARY %s\n\nEXPORTS\n", dllname
);
952 printf("<- %s (%d symbols)\n", buf
, sym_count
);
956 for (ord
= 0; ord
< sym_count
; ++ord
)
958 p
= sorted
[ord
], sym_index
= p
->index
, name
= p
->name
;
959 /* insert actual address later in pe_relocate_rva */
960 put_elf_reloc(symtab_section
, pe
->thunk
,
961 func_o
, R_XXX_RELATIVE
, sym_index
);
962 *(DWORD
*)(pe
->thunk
->data
+ name_o
)
963 = pe
->thunk
->data_offset
+ rva_base
;
964 *(WORD
*)(pe
->thunk
->data
+ ord_o
)
966 put_elf_str(pe
->thunk
, name
);
967 func_o
+= sizeof (DWORD
);
968 name_o
+= sizeof (DWORD
);
969 ord_o
+= sizeof (WORD
);
971 fprintf(op
, "%s\n", name
);
973 pe
->exp_size
= pe
->thunk
->data_offset
- pe
->exp_offs
;
974 dynarray_reset(&sorted
, &sym_count
);
979 /* ------------------------------------------------------------- */
980 static void pe_build_reloc (struct pe_info
*pe
)
982 DWORD offset
, block_ptr
, addr
;
984 ElfW_Rel
*rel
, *rel_end
;
985 Section
*s
= NULL
, *sr
;
987 offset
= addr
= block_ptr
= count
= i
= 0;
988 rel
= rel_end
= NULL
;
992 int type
= ELFW(R_TYPE
)(rel
->r_info
);
993 addr
= rel
->r_offset
+ s
->sh_addr
;
995 if (type
!= REL_TYPE_DIRECT
)
997 if (count
== 0) { /* new block */
998 block_ptr
= pe
->reloc
->data_offset
;
999 section_ptr_add(pe
->reloc
, sizeof(struct pe_reloc_header
));
1000 offset
= addr
& 0xFFFFFFFF<<12;
1002 if ((addr
-= offset
) < (1<<12)) { /* one block spans 4k addresses */
1003 WORD
*wp
= section_ptr_add(pe
->reloc
, sizeof (WORD
));
1004 *wp
= addr
| IMAGE_REL_BASED_HIGHLOW
<<12;
1010 } else if (i
< pe
->sec_count
) {
1011 sr
= (s
= pe
->s1
->sections
[pe
->sec_info
[i
++].ord
])->reloc
;
1013 rel
= (ElfW_Rel
*)sr
->data
;
1014 rel_end
= (ElfW_Rel
*)(sr
->data
+ sr
->data_offset
);
1020 /* store the last block and ready for a new one */
1021 struct pe_reloc_header
*hdr
;
1022 if (count
& 1) /* align for DWORDS */
1023 section_ptr_add(pe
->reloc
, sizeof(WORD
)), ++count
;
1024 hdr
= (struct pe_reloc_header
*)(pe
->reloc
->data
+ block_ptr
);
1025 hdr
-> offset
= offset
- pe
->imagebase
;
1026 hdr
-> size
= count
* sizeof(WORD
) + sizeof(struct pe_reloc_header
);
1035 /* ------------------------------------------------------------- */
1036 static int pe_section_class(Section
*s
)
1042 flags
= s
->sh_flags
;
1044 if (flags
& SHF_ALLOC
) {
1045 if (type
== SHT_PROGBITS
) {
1046 if (flags
& SHF_EXECINSTR
)
1048 if (flags
& SHF_WRITE
)
1050 if (0 == strcmp(name
, ".rsrc"))
1052 if (0 == strcmp(name
, ".iedat"))
1054 if (0 == strcmp(name
, ".pdata"))
1057 } else if (type
== SHT_NOBITS
) {
1058 if (flags
& SHF_WRITE
)
1062 if (0 == strcmp(name
, ".reloc"))
1064 if (0 == strncmp(name
, ".stab", 5)) /* .stab and .stabstr */
1070 static int pe_assign_addresses (struct pe_info
*pe
)
1075 struct section_info
*si
;
1078 if (PE_DLL
== pe
->type
)
1079 pe
->reloc
= new_section(pe
->s1
, ".reloc", SHT_PROGBITS
, 0);
1081 // pe->thunk = new_section(pe->s1, ".iedat", SHT_PROGBITS, SHF_ALLOC);
1083 section_order
= tcc_malloc(pe
->s1
->nb_sections
* sizeof (int));
1084 for (o
= k
= 0 ; k
< sec_last
; ++k
) {
1085 for (i
= 1; i
< pe
->s1
->nb_sections
; ++i
) {
1086 s
= pe
->s1
->sections
[i
];
1087 if (k
== pe_section_class(s
)) {
1088 // printf("%s %d\n", s->name, k);
1089 s
->sh_addr
= pe
->imagebase
;
1090 section_order
[o
++] = i
;
1095 pe
->sec_info
= tcc_mallocz(o
* sizeof (struct section_info
));
1096 addr
= pe
->imagebase
+ 1;
1098 for (i
= 0; i
< o
; ++i
)
1100 k
= section_order
[i
];
1101 s
= pe
->s1
->sections
[k
];
1102 c
= pe_section_class(s
);
1103 si
= &pe
->sec_info
[pe
->sec_count
];
1105 #ifdef PE_MERGE_DATA
1106 if (c
== sec_bss
&& pe
->sec_count
&& si
[-1].cls
== sec_data
) {
1107 /* append .bss to .data */
1108 s
->sh_addr
= addr
= ((addr
-1) | (s
->sh_addralign
-1)) + 1;
1109 addr
+= s
->data_offset
;
1110 si
[-1].sh_size
= addr
- si
[-1].sh_addr
;
1114 if (c
== sec_stab
&& 0 == pe
->s1
->do_debug
)
1117 strcpy(si
->name
, s
->name
);
1120 si
->sh_addr
= s
->sh_addr
= addr
= pe_virtual_align(pe
, addr
);
1121 si
->sh_flags
= s
->sh_flags
;
1123 if (c
== sec_data
&& NULL
== pe
->thunk
)
1126 if (s
== pe
->thunk
) {
1127 pe_build_imports(pe
);
1128 pe_build_exports(pe
);
1132 pe_build_reloc (pe
);
1136 if (s
->sh_type
!= SHT_NOBITS
) {
1138 si
->data_size
= s
->data_offset
;
1141 addr
+= s
->data_offset
;
1142 si
->sh_size
= s
->data_offset
;
1145 // printf("%08x %05x %s\n", si->sh_addr, si->sh_size, si->name);
1149 for (i
= 1; i
< pe
->s1
->nb_sections
; ++i
) {
1150 Section
*s
= pe
->s1
->sections
[i
];
1151 int type
= s
->sh_type
;
1152 int flags
= s
->sh_flags
;
1153 printf("section %-16s %-10s %5x %s,%s,%s\n",
1155 type
== SHT_PROGBITS
? "progbits" :
1156 type
== SHT_NOBITS
? "nobits" :
1157 type
== SHT_SYMTAB
? "symtab" :
1158 type
== SHT_STRTAB
? "strtab" :
1159 type
== SHT_RELX
? "rel" : "???",
1161 flags
& SHF_ALLOC
? "alloc" : "",
1162 flags
& SHF_WRITE
? "write" : "",
1163 flags
& SHF_EXECINSTR
? "exec" : ""
1166 pe
->s1
->verbose
= 2;
1169 tcc_free(section_order
);
1173 /* ------------------------------------------------------------- */
1174 static void pe_relocate_rva (struct pe_info
*pe
, Section
*s
)
1176 Section
*sr
= s
->reloc
;
1177 ElfW_Rel
*rel
, *rel_end
;
1178 rel_end
= (ElfW_Rel
*)(sr
->data
+ sr
->data_offset
);
1179 for(rel
= (ElfW_Rel
*)sr
->data
; rel
< rel_end
; rel
++) {
1180 if (ELFW(R_TYPE
)(rel
->r_info
) == R_XXX_RELATIVE
) {
1181 int sym_index
= ELFW(R_SYM
)(rel
->r_info
);
1182 DWORD addr
= s
->sh_addr
;
1184 ElfW(Sym
) *sym
= (ElfW(Sym
) *)symtab_section
->data
+ sym_index
;
1185 addr
= sym
->st_value
;
1187 // printf("reloc rva %08x %08x %s\n", (DWORD)rel->r_offset, addr, s->name);
1188 *(DWORD
*)(s
->data
+ rel
->r_offset
) += addr
- pe
->imagebase
;
1193 /*----------------------------------------------------------------------------*/
1195 static int pe_isafunc(int sym_index
)
1197 Section
*sr
= text_section
->reloc
;
1198 ElfW_Rel
*rel
, *rel_end
;
1199 Elf32_Word info
= ELF32_R_INFO(sym_index
, R_386_PC32
);
1202 rel_end
= (ElfW_Rel
*)(sr
->data
+ sr
->data_offset
);
1203 for (rel
= (ElfW_Rel
*)sr
->data
; rel
< rel_end
; rel
++)
1204 if (rel
->r_info
== info
)
1209 /*----------------------------------------------------------------------------*/
1210 static int pe_check_symbols(struct pe_info
*pe
)
1213 int sym_index
, sym_end
;
1216 pe_align_section(text_section
, 8);
1218 sym_end
= symtab_section
->data_offset
/ sizeof(ElfW(Sym
));
1219 for (sym_index
= 1; sym_index
< sym_end
; ++sym_index
) {
1221 sym
= (ElfW(Sym
) *)symtab_section
->data
+ sym_index
;
1222 if (sym
->st_shndx
== SHN_UNDEF
) {
1224 const char *name
= symtab_section
->link
->data
+ sym
->st_name
;
1225 unsigned type
= ELFW(ST_TYPE
)(sym
->st_info
);
1226 int imp_sym
= pe_find_import(pe
->s1
, sym
);
1227 struct import_symbol
*is
;
1232 if (type
== STT_NOTYPE
) {
1233 /* symbols from assembler have no type, find out which */
1234 if (pe_isafunc(sym_index
))
1240 is
= pe_add_import(pe
, imp_sym
);
1242 if (type
== STT_FUNC
) {
1243 unsigned long offset
= is
->thk_offset
;
1245 /* got aliased symbol, like stricmp and _stricmp */
1251 offset
= text_section
->data_offset
;
1252 /* add the 'jmp IAT[x]' instruction */
1253 #ifdef TCC_TARGET_ARM
1254 p
= section_ptr_add(text_section
, 8+4); // room for code and address
1255 (*(DWORD
*)(p
)) = 0xE59FC000; // arm code ldr ip, [pc] ; PC+8+0 = 0001xxxx
1256 (*(DWORD
*)(p
+2)) = 0xE59CF000; // arm code ldr pc, [ip]
1258 p
= section_ptr_add(text_section
, 8);
1260 #ifdef TCC_TARGET_X86_64
1261 *(DWORD
*)(p
+1) = (DWORD
)-4;
1264 /* add a helper symbol, will be patched later in
1266 sprintf(buffer
, "IAT.%s", name
);
1267 is
->iat_index
= put_elf_sym(
1268 symtab_section
, 0, sizeof(DWORD
),
1269 ELFW(ST_INFO
)(STB_GLOBAL
, STT_OBJECT
),
1270 0, SHN_UNDEF
, buffer
);
1271 #ifdef TCC_TARGET_ARM
1272 put_elf_reloc(symtab_section
, text_section
,
1273 offset
+ 8, R_XXX_THUNKFIX
, is
->iat_index
); // offset to IAT position
1275 put_elf_reloc(symtab_section
, text_section
,
1276 offset
+ 2, R_XXX_THUNKFIX
, is
->iat_index
);
1278 is
->thk_offset
= offset
;
1281 /* tcc_realloc might have altered sym's address */
1282 sym
= (ElfW(Sym
) *)symtab_section
->data
+ sym_index
;
1284 /* patch the original symbol */
1285 sym
->st_value
= offset
;
1286 sym
->st_shndx
= text_section
->sh_num
;
1287 sym
->st_other
&= ~ST_PE_EXPORT
; /* do not export */
1291 if (type
== STT_OBJECT
) { /* data, ptr to that should be */
1292 if (0 == is
->iat_index
) {
1293 /* original symbol will be patched later in pe_build_imports */
1294 is
->iat_index
= sym_index
;
1300 tcc_error_noabort("undefined symbol '%s'", name
);
1303 } else if (pe
->s1
->rdynamic
1304 && ELFW(ST_BIND
)(sym
->st_info
) != STB_LOCAL
) {
1305 /* if -rdynamic option, then export all non local symbols */
1306 sym
->st_other
|= ST_PE_EXPORT
;
1312 /*----------------------------------------------------------------------------*/
1313 #ifdef PE_PRINT_SECTIONS
1314 static void pe_print_section(FILE * f
, Section
* s
)
1316 /* just if you'r curious */
1320 e
= s
->data
+ s
->data_offset
;
1323 fprintf(f
, "section \"%s\"", s
->name
);
1325 fprintf(f
, "\nlink \"%s\"", s
->link
->name
);
1327 fprintf(f
, "\nreloc \"%s\"", s
->reloc
->name
);
1328 fprintf(f
, "\nv_addr %08X", (unsigned)s
->sh_addr
);
1329 fprintf(f
, "\ncontents %08X", (unsigned)l
);
1332 if (s
->sh_type
== SHT_NOBITS
)
1338 if (s
->sh_type
== SHT_SYMTAB
)
1339 m
= sizeof(ElfW(Sym
));
1340 else if (s
->sh_type
== SHT_RELX
)
1341 m
= sizeof(ElfW_Rel
);
1345 fprintf(f
, "%-8s", "offset");
1346 for (i
= 0; i
< m
; ++i
)
1347 fprintf(f
, " %02x", i
);
1350 if (s
->sh_type
== SHT_SYMTAB
|| s
->sh_type
== SHT_RELX
) {
1351 const char *fields1
[] = {
1362 const char *fields2
[] = {
1371 if (s
->sh_type
== SHT_SYMTAB
)
1372 p
= fields1
, n
= 106;
1374 p
= fields2
, n
= 58;
1376 for (i
= 0; p
[i
]; ++i
)
1377 fprintf(f
, "%6s", p
[i
]);
1378 fprintf(f
, " symbol");
1382 for (i
= 0; i
< n
; ++i
)
1388 fprintf(f
, "%08X", i
);
1389 for (n
= 0; n
< m
; ++n
) {
1391 fprintf(f
, " %02X", p
[i
+ n
]);
1396 if (s
->sh_type
== SHT_SYMTAB
) {
1397 ElfW(Sym
) *sym
= (ElfW(Sym
) *) (p
+ i
);
1398 const char *name
= s
->link
->data
+ sym
->st_name
;
1399 fprintf(f
, " %04X %04X %04X %02X %02X %02X %04X \"%s\"",
1400 (unsigned)sym
->st_name
,
1401 (unsigned)sym
->st_value
,
1402 (unsigned)sym
->st_size
,
1403 (unsigned)ELFW(ST_BIND
)(sym
->st_info
),
1404 (unsigned)ELFW(ST_TYPE
)(sym
->st_info
),
1405 (unsigned)sym
->st_other
,
1406 (unsigned)sym
->st_shndx
,
1409 } else if (s
->sh_type
== SHT_RELX
) {
1410 ElfW_Rel
*rel
= (ElfW_Rel
*) (p
+ i
);
1412 (ElfW(Sym
) *) s
->link
->data
+ ELFW(R_SYM
)(rel
->r_info
);
1413 const char *name
= s
->link
->link
->data
+ sym
->st_name
;
1414 fprintf(f
, " %04X %02X %04X \"%s\"",
1415 (unsigned)rel
->r_offset
,
1416 (unsigned)ELFW(R_TYPE
)(rel
->r_info
),
1417 (unsigned)ELFW(R_SYM
)(rel
->r_info
),
1421 for (n
= 0; n
< m
; ++n
) {
1424 if (b
< 32 || b
>= 127)
1426 fprintf(f
, "%c", b
);
1436 static void pe_print_sections(TCCState
*s1
, const char *fname
)
1441 f
= fopen(fname
, "w");
1442 for (i
= 1; i
< s1
->nb_sections
; ++i
) {
1443 s
= s1
->sections
[i
];
1444 pe_print_section(f
, s
);
1446 pe_print_section(f
, s1
->dynsymtab_section
);
1451 /* ------------------------------------------------------------- */
1452 /* helper function for load/store to insert one more indirection */
1454 #ifndef TCC_TARGET_ARM
1455 ST_FUNC SValue
*pe_getimport(SValue
*sv
, SValue
*v2
)
1461 if ((sv
->r
& (VT_VALMASK
|VT_SYM
)) != (VT_CONST
|VT_SYM
) || (sv
->r2
!= VT_CONST
))
1464 if ((sym
->type
.t
& (VT_EXTERN
|VT_STATIC
)) != VT_EXTERN
)
1467 put_extern_sym(sym
, NULL
, 0, 0);
1468 esym
= &((ElfW(Sym
) *)symtab_section
->data
)[sym
->c
];
1469 if (!(esym
->st_other
& ST_PE_IMPORT
))
1472 // printf("import %04x %04x %04x %s\n", sv->type.t, sym->type.t, sv->r, get_tok_str(sv->sym->v, NULL));
1474 memset(v2
, 0, sizeof *v2
);
1475 v2
->type
.t
= VT_PTR
;
1476 v2
->r
= VT_CONST
| VT_SYM
| VT_LVAL
;
1479 r2
= get_reg(RC_INT
);
1483 if ((uint32_t)sv
->c
.i
) {
1490 v2
->type
.t
= sv
->type
.t
;
1491 v2
->r
|= sv
->r
& VT_LVAL
;
1496 ST_FUNC
int pe_putimport(TCCState
*s1
, int dllindex
, const char *name
, addr_t value
)
1499 s1
->dynsymtab_section
,
1501 dllindex
, /* st_size */
1502 ELFW(ST_INFO
)(STB_GLOBAL
, STT_NOTYPE
),
1504 value
? SHN_ABS
: SHN_UNDEF
,
1509 static int add_dllref(TCCState
*s1
, const char *dllname
)
1511 DLLReference
*dllref
;
1513 for (i
= 0; i
< s1
->nb_loaded_dlls
; ++i
)
1514 if (0 == strcmp(s1
->loaded_dlls
[i
]->name
, dllname
))
1516 dllref
= tcc_mallocz(sizeof(DLLReference
) + strlen(dllname
));
1517 strcpy(dllref
->name
, dllname
);
1518 dynarray_add((void ***) &s1
->loaded_dlls
, &s1
->nb_loaded_dlls
, dllref
);
1519 return s1
->nb_loaded_dlls
;
1522 /* ------------------------------------------------------------- */
1524 static int read_mem(int fd
, unsigned offset
, void *buffer
, unsigned len
)
1526 lseek(fd
, offset
, SEEK_SET
);
1527 return len
== read(fd
, buffer
, len
);
1530 /* -------------------------------------------------------------
1531 * This is for compiled windows resources in 'coff' format
1532 * as generated by 'windres.exe -O coff ...'.
1535 static int pe_load_res(TCCState
*s1
, int fd
)
1537 struct pe_rsrc_header hdr
;
1538 Section
*rsrc_section
;
1543 if (!read_mem(fd
, 0, &hdr
, sizeof hdr
))
1546 if (hdr
.filehdr
.Machine
!= IMAGE_FILE_MACHINE
1547 || hdr
.filehdr
.NumberOfSections
!= 1
1548 || strcmp(hdr
.sectionhdr
.Name
, ".rsrc") != 0)
1551 rsrc_section
= new_section(s1
, ".rsrc", SHT_PROGBITS
, SHF_ALLOC
);
1552 ptr
= section_ptr_add(rsrc_section
, hdr
.sectionhdr
.SizeOfRawData
);
1553 offs
= hdr
.sectionhdr
.PointerToRawData
;
1554 if (!read_mem(fd
, offs
, ptr
, hdr
.sectionhdr
.SizeOfRawData
))
1556 offs
= hdr
.sectionhdr
.PointerToRelocations
;
1557 for (i
= 0; i
< hdr
.sectionhdr
.NumberOfRelocations
; ++i
)
1559 struct pe_rsrc_reloc rel
;
1560 if (!read_mem(fd
, offs
, &rel
, sizeof rel
))
1562 // printf("rsrc_reloc: %x %x %x\n", rel.offset, rel.size, rel.type);
1563 if (rel
.type
!= RSRC_RELTYPE
)
1565 put_elf_reloc(symtab_section
, rsrc_section
,
1566 rel
.offset
, R_XXX_RELATIVE
, 0);
1574 /* ------------------------------------------------------------- */
1576 static char *trimfront(char *p
)
1578 while (*p
&& (unsigned char)*p
<= ' ')
1583 static char *trimback(char *a
, char *e
)
1585 while (e
> a
&& (unsigned char)e
[-1] <= ' ')
1591 /* ------------------------------------------------------------- */
1592 static int pe_load_def(TCCState
*s1
, int fd
)
1594 int state
= 0, ret
= -1, dllindex
= 0, ord
;
1595 char line
[400], dllname
[80], *p
, *x
;
1598 fp
= fdopen(dup(fd
), "rb");
1599 while (fgets(line
, sizeof line
, fp
))
1601 p
= trimfront(trimback(line
, strchr(line
, 0)));
1602 if (0 == *p
|| ';' == *p
)
1607 if (0 != strnicmp(p
, "LIBRARY", 7))
1609 pstrcpy(dllname
, sizeof dllname
, trimfront(p
+7));
1614 if (0 != stricmp(p
, "EXPORTS"))
1620 dllindex
= add_dllref(s1
, dllname
);
1624 /* get ordinal and will store in sym->st_value */
1628 *x
= 0, x
= strrchr(x
+ 1, '@');
1631 ord
= (int)strtol(x
+ 1, &d
, 10);
1636 pe_putimport(s1
, dllindex
, p
, ord
);
1646 /* ------------------------------------------------------------- */
1647 #define TINY_IMPDEF_GET_EXPORT_NAMES_ONLY
1648 #include "win32/tools/tiny_impdef.c"
1650 static int pe_load_dll(TCCState
*s1
, const char *dllname
, int fd
)
1654 p
= get_export_names(fd
);
1657 index
= add_dllref(s1
, dllname
);
1658 for (q
= p
; *q
; q
+= 1 + strlen(q
))
1659 pe_putimport(s1
, index
, q
, 0);
1664 /* ------------------------------------------------------------- */
1665 ST_FUNC
int pe_load_file(struct TCCState
*s1
, const char *filename
, int fd
)
1669 if (0 == strcmp(tcc_fileextension(filename
), ".def"))
1670 ret
= pe_load_def(s1
, fd
);
1671 else if (pe_load_res(s1
, fd
) == 0)
1673 else if (read_mem(fd
, 0, buf
, 4) && 0 == memcmp(buf
, "MZ\220", 4))
1674 ret
= pe_load_dll(s1
, tcc_basename(filename
), fd
);
1678 /* ------------------------------------------------------------- */
1679 #ifdef TCC_TARGET_X86_64
1680 static unsigned pe_add_uwwind_info(TCCState
*s1
)
1682 if (NULL
== s1
->uw_pdata
) {
1683 s1
->uw_pdata
= find_section(tcc_state
, ".pdata");
1684 s1
->uw_pdata
->sh_addralign
= 4;
1685 s1
->uw_sym
= put_elf_sym(symtab_section
, 0, 0, 0, 0, text_section
->sh_num
, NULL
);
1688 if (0 == s1
->uw_offs
) {
1689 /* As our functions all have the same stackframe, we use one entry for all */
1690 static const unsigned char uw_info
[] = {
1691 0x01, // UBYTE: 3 Version , UBYTE: 5 Flags
1692 0x04, // UBYTE Size of prolog
1693 0x02, // UBYTE Count of unwind codes
1694 0x05, // UBYTE: 4 Frame Register (rbp), UBYTE: 4 Frame Register offset (scaled)
1695 // USHORT * n Unwind codes array
1696 // 0x0b, 0x01, 0xff, 0xff, // stack size
1697 0x04, 0x03, // set frame ptr (mov rsp -> rbp)
1698 0x01, 0x50 // push reg (rbp)
1701 Section
*s
= text_section
;
1704 section_ptr_add(s
, -s
->data_offset
& 3); /* align */
1705 s1
->uw_offs
= s
->data_offset
;
1706 p
= section_ptr_add(s
, sizeof uw_info
);
1707 memcpy(p
, uw_info
, sizeof uw_info
);
1713 ST_FUNC
void pe_add_unwind_data(unsigned start
, unsigned end
, unsigned stack
)
1715 TCCState
*s1
= tcc_state
;
1718 struct /* _RUNTIME_FUNCTION */ {
1724 d
= pe_add_uwwind_info(s1
);
1726 o
= pd
->data_offset
;
1727 p
= section_ptr_add(pd
, sizeof *p
);
1729 /* record this function */
1730 p
->BeginAddress
= start
;
1731 p
->EndAddress
= end
;
1734 /* put relocations on it */
1735 for (n
= o
+ sizeof *p
; o
< n
; o
+= sizeof p
->BeginAddress
)
1736 put_elf_reloc(symtab_section
, pd
, o
, R_X86_64_RELATIVE
, s1
->uw_sym
);
1739 /* ------------------------------------------------------------- */
1740 #ifdef TCC_TARGET_X86_64
1741 #define PE_STDSYM(n,s) n
1743 #define PE_STDSYM(n,s) "_" n s
1746 static void pe_add_runtime(TCCState
*s1
, struct pe_info
*pe
)
1748 const char *start_symbol
;
1751 if (find_elf_sym(symtab_section
, PE_STDSYM("WinMain","@16")))
1754 if (TCC_OUTPUT_DLL
== s1
->output_type
) {
1756 /* need this for 'tccelf.c:relocate_section()' */
1757 s1
->output_type
= TCC_OUTPUT_EXE
;
1763 TCC_OUTPUT_MEMORY
== s1
->output_type
1764 ? PE_GUI
== pe_type
? "__runwinmain" : "_main"
1765 : PE_DLL
== pe_type
? PE_STDSYM("__dllstart","@12")
1766 : PE_GUI
== pe_type
? "__winstart" : "__start"
1769 if (!s1
->leading_underscore
|| strchr(start_symbol
, '@'))
1772 /* grab the startup code from libtcc1 */
1773 if (TCC_OUTPUT_MEMORY
!= s1
->output_type
|| PE_GUI
== pe_type
)
1774 set_elf_sym(symtab_section
,
1776 ELFW(ST_INFO
)(STB_GLOBAL
, STT_NOTYPE
), 0,
1777 SHN_UNDEF
, start_symbol
);
1779 tcc_add_pragma_libs(s1
);
1781 if (0 == s1
->nostdlib
) {
1782 static const char *libs
[] = {
1783 "tcc1", "msvcrt", "kernel32", "", "user32", "gdi32", NULL
1785 const char **pp
, *p
;
1786 for (pp
= libs
; 0 != (p
= *pp
); ++pp
) {
1788 if (PE_DLL
!= pe_type
&& PE_GUI
!= pe_type
)
1790 } else if (tcc_add_library_err(s1
, p
) < 0) {
1796 if (TCC_OUTPUT_MEMORY
== s1
->output_type
) {
1798 #ifdef TCC_IS_NATIVE
1799 s1
->runtime_main
= start_symbol
;
1802 pe
->start_addr
= (DWORD
)(uintptr_t)tcc_get_symbol_err(s1
, start_symbol
);
1808 static void pe_set_options(TCCState
* s1
, struct pe_info
*pe
)
1810 if (PE_DLL
== pe
->type
) {
1811 /* XXX: check if is correct for arm-pe target */
1812 pe
->imagebase
= 0x10000000;
1814 #if defined(TCC_TARGET_ARM)
1815 pe
->imagebase
= 0x00010000;
1817 pe
->imagebase
= 0x00400000;
1821 #if defined(TCC_TARGET_ARM)
1822 /* we use "console" subsystem by default */
1825 if (PE_DLL
== pe
->type
|| PE_GUI
== pe
->type
)
1830 /* Allow override via -Wl,-subsystem=... option */
1831 if (s1
->pe_subsystem
!= 0)
1832 pe
->subsystem
= s1
->pe_subsystem
;
1834 /* set default file/section alignment */
1835 if (pe
->subsystem
== 1) {
1836 pe
->section_align
= 0x20;
1837 pe
->file_align
= 0x20;
1839 pe
->section_align
= 0x1000;
1840 pe
->file_align
= 0x200;
1843 if (s1
->section_align
!= 0)
1844 pe
->section_align
= s1
->section_align
;
1845 if (s1
->pe_file_align
!= 0)
1846 pe
->file_align
= s1
->pe_file_align
;
1848 if ((pe
->subsystem
>= 10) && (pe
->subsystem
<= 12))
1851 if (s1
->has_text_addr
)
1852 pe
->imagebase
= s1
->text_addr
;
1855 ST_FUNC
int pe_output_file(TCCState
*s1
, const char *filename
)
1861 memset(&pe
, 0, sizeof pe
);
1862 pe
.filename
= filename
;
1866 pe_add_runtime(s1
, &pe
);
1867 relocate_common_syms(); /* assign bss adresses */
1868 tcc_add_linker_symbols(s1
);
1869 pe_set_options(s1
, &pe
);
1871 ret
= pe_check_symbols(&pe
);
1874 else if (filename
) {
1875 pe_assign_addresses(&pe
);
1876 relocate_syms(s1
, s1
->symtab
, 0);
1877 for (i
= 1; i
< s1
->nb_sections
; ++i
) {
1878 Section
*s
= s1
->sections
[i
];
1880 relocate_section(s1
, s
);
1881 pe_relocate_rva(&pe
, s
);
1887 ret
= pe_write(&pe
);
1888 tcc_free(pe
.sec_info
);
1890 #ifdef TCC_IS_NATIVE
1891 pe
.thunk
= data_section
;
1892 pe_build_imports(&pe
);
1896 #ifdef PE_PRINT_SECTIONS
1897 pe_print_sections(s1
, "tcc.log");
1902 /* ------------------------------------------------------------- */