2 * TCCPE.C - PE file output for the Tiny C Compiler
4 * Copyright (c) 2005-2007 grischka
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
24 /* #define PE_PRINT_SECTIONS */
27 #define stricmp strcasecmp
28 #define strnicmp strncasecmp
29 #include <sys/stat.h> /* chmod() */
32 #ifdef TCC_TARGET_X86_64
33 # define ADDR3264 ULONGLONG
34 # define PE_IMAGE_REL IMAGE_REL_BASED_DIR64
35 # define REL_TYPE_DIRECT R_X86_64_64
36 # define R_XXX_THUNKFIX R_X86_64_PC32
37 # define R_XXX_RELATIVE R_X86_64_RELATIVE
38 # define IMAGE_FILE_MACHINE 0x8664
39 # define RSRC_RELTYPE 3
41 #elif defined TCC_TARGET_ARM
42 # define ADDR3264 DWORD
43 # define PE_IMAGE_REL IMAGE_REL_BASED_HIGHLOW
44 # define REL_TYPE_DIRECT R_ARM_ABS32
45 # define R_XXX_THUNKFIX R_ARM_ABS32
46 # define R_XXX_RELATIVE R_ARM_RELATIVE
47 # define IMAGE_FILE_MACHINE 0x01C0
48 # define RSRC_RELTYPE 7 /* ??? (not tested) */
50 #elif defined TCC_TARGET_I386
51 # define ADDR3264 DWORD
52 # define PE_IMAGE_REL IMAGE_REL_BASED_HIGHLOW
53 # define REL_TYPE_DIRECT R_386_32
54 # define R_XXX_THUNKFIX R_386_32
55 # define R_XXX_RELATIVE R_386_RELATIVE
56 # define IMAGE_FILE_MACHINE 0x014C
57 # define RSRC_RELTYPE 7 /* DIR32NB */
61 #ifndef IMAGE_NT_SIGNATURE
62 /* ----------------------------------------------------------- */
63 /* definitions below are from winnt.h */
65 typedef unsigned char BYTE
;
66 typedef unsigned short WORD
;
67 typedef unsigned int DWORD
;
68 typedef unsigned long long ULONGLONG
;
71 typedef struct _IMAGE_DOS_HEADER
{ /* DOS .EXE header */
72 WORD e_magic
; /* Magic number */
73 WORD e_cblp
; /* Bytes on last page of file */
74 WORD e_cp
; /* Pages in file */
75 WORD e_crlc
; /* Relocations */
76 WORD e_cparhdr
; /* Size of header in paragraphs */
77 WORD e_minalloc
; /* Minimum extra paragraphs needed */
78 WORD e_maxalloc
; /* Maximum extra paragraphs needed */
79 WORD e_ss
; /* Initial (relative) SS value */
80 WORD e_sp
; /* Initial SP value */
81 WORD e_csum
; /* Checksum */
82 WORD e_ip
; /* Initial IP value */
83 WORD e_cs
; /* Initial (relative) CS value */
84 WORD e_lfarlc
; /* File address of relocation table */
85 WORD e_ovno
; /* Overlay number */
86 WORD e_res
[4]; /* Reserved words */
87 WORD e_oemid
; /* OEM identifier (for e_oeminfo) */
88 WORD e_oeminfo
; /* OEM information; e_oemid specific */
89 WORD e_res2
[10]; /* Reserved words */
90 DWORD e_lfanew
; /* File address of new exe header */
91 } IMAGE_DOS_HEADER
, *PIMAGE_DOS_HEADER
;
93 #define IMAGE_NT_SIGNATURE 0x00004550 /* PE00 */
94 #define SIZE_OF_NT_SIGNATURE 4
96 typedef struct _IMAGE_FILE_HEADER
{
98 WORD NumberOfSections
;
100 DWORD PointerToSymbolTable
;
101 DWORD NumberOfSymbols
;
102 WORD SizeOfOptionalHeader
;
103 WORD Characteristics
;
104 } IMAGE_FILE_HEADER
, *PIMAGE_FILE_HEADER
;
107 #define IMAGE_SIZEOF_FILE_HEADER 20
109 typedef struct _IMAGE_DATA_DIRECTORY
{
110 DWORD VirtualAddress
;
112 } IMAGE_DATA_DIRECTORY
, *PIMAGE_DATA_DIRECTORY
;
115 typedef struct _IMAGE_OPTIONAL_HEADER
{
116 /* Standard fields. */
118 BYTE MajorLinkerVersion
;
119 BYTE MinorLinkerVersion
;
121 DWORD SizeOfInitializedData
;
122 DWORD SizeOfUninitializedData
;
123 DWORD AddressOfEntryPoint
;
125 #ifndef TCC_TARGET_X86_64
128 /* NT additional fields. */
130 DWORD SectionAlignment
;
132 WORD MajorOperatingSystemVersion
;
133 WORD MinorOperatingSystemVersion
;
134 WORD MajorImageVersion
;
135 WORD MinorImageVersion
;
136 WORD MajorSubsystemVersion
;
137 WORD MinorSubsystemVersion
;
138 DWORD Win32VersionValue
;
143 WORD DllCharacteristics
;
144 ADDR3264 SizeOfStackReserve
;
145 ADDR3264 SizeOfStackCommit
;
146 ADDR3264 SizeOfHeapReserve
;
147 ADDR3264 SizeOfHeapCommit
;
149 DWORD NumberOfRvaAndSizes
;
150 IMAGE_DATA_DIRECTORY DataDirectory
[16];
151 } IMAGE_OPTIONAL_HEADER32
, IMAGE_OPTIONAL_HEADER64
, IMAGE_OPTIONAL_HEADER
;
153 #define IMAGE_DIRECTORY_ENTRY_EXPORT 0 /* Export Directory */
154 #define IMAGE_DIRECTORY_ENTRY_IMPORT 1 /* Import Directory */
155 #define IMAGE_DIRECTORY_ENTRY_RESOURCE 2 /* Resource Directory */
156 #define IMAGE_DIRECTORY_ENTRY_EXCEPTION 3 /* Exception Directory */
157 #define IMAGE_DIRECTORY_ENTRY_SECURITY 4 /* Security Directory */
158 #define IMAGE_DIRECTORY_ENTRY_BASERELOC 5 /* Base Relocation Table */
159 #define IMAGE_DIRECTORY_ENTRY_DEBUG 6 /* Debug Directory */
160 /* IMAGE_DIRECTORY_ENTRY_COPYRIGHT 7 (X86 usage) */
161 #define IMAGE_DIRECTORY_ENTRY_ARCHITECTURE 7 /* Architecture Specific Data */
162 #define IMAGE_DIRECTORY_ENTRY_GLOBALPTR 8 /* RVA of GP */
163 #define IMAGE_DIRECTORY_ENTRY_TLS 9 /* TLS Directory */
164 #define IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG 10 /* Load Configuration Directory */
165 #define IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT 11 /* Bound Import Directory in headers */
166 #define IMAGE_DIRECTORY_ENTRY_IAT 12 /* Import Address Table */
167 #define IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT 13 /* Delay Load Import Descriptors */
168 #define IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR 14 /* COM Runtime descriptor */
170 /* Section header format. */
171 #define IMAGE_SIZEOF_SHORT_NAME 8
173 typedef struct _IMAGE_SECTION_HEADER
{
174 BYTE Name
[IMAGE_SIZEOF_SHORT_NAME
];
176 DWORD PhysicalAddress
;
179 DWORD VirtualAddress
;
181 DWORD PointerToRawData
;
182 DWORD PointerToRelocations
;
183 DWORD PointerToLinenumbers
;
184 WORD NumberOfRelocations
;
185 WORD NumberOfLinenumbers
;
186 DWORD Characteristics
;
187 } IMAGE_SECTION_HEADER
, *PIMAGE_SECTION_HEADER
;
189 #define IMAGE_SIZEOF_SECTION_HEADER 40
191 typedef struct _IMAGE_EXPORT_DIRECTORY
{
192 DWORD Characteristics
;
198 DWORD NumberOfFunctions
;
200 DWORD AddressOfFunctions
;
201 DWORD AddressOfNames
;
202 DWORD AddressOfNameOrdinals
;
203 } IMAGE_EXPORT_DIRECTORY
,*PIMAGE_EXPORT_DIRECTORY
;
205 typedef struct _IMAGE_IMPORT_DESCRIPTOR
{
207 DWORD Characteristics
;
208 DWORD OriginalFirstThunk
;
211 DWORD ForwarderChain
;
214 } IMAGE_IMPORT_DESCRIPTOR
;
216 typedef struct _IMAGE_BASE_RELOCATION
{
217 DWORD VirtualAddress
;
219 // WORD TypeOffset[1];
220 } IMAGE_BASE_RELOCATION
;
222 #define IMAGE_SIZEOF_BASE_RELOCATION 8
224 #define IMAGE_REL_BASED_ABSOLUTE 0
225 #define IMAGE_REL_BASED_HIGH 1
226 #define IMAGE_REL_BASED_LOW 2
227 #define IMAGE_REL_BASED_HIGHLOW 3
228 #define IMAGE_REL_BASED_HIGHADJ 4
229 #define IMAGE_REL_BASED_MIPS_JMPADDR 5
230 #define IMAGE_REL_BASED_SECTION 6
231 #define IMAGE_REL_BASED_REL32 7
232 #define IMAGE_REL_BASED_DIR64 10
236 /* ----------------------------------------------------------- */
237 #endif /* ndef IMAGE_NT_SIGNATURE */
238 /* ----------------------------------------------------------- */
240 #ifndef IMAGE_REL_BASED_DIR64
241 # define IMAGE_REL_BASED_DIR64 10
244 #pragma pack(push, 1)
247 IMAGE_DOS_HEADER doshdr
;
250 IMAGE_FILE_HEADER filehdr
;
251 #ifdef TCC_TARGET_X86_64
252 IMAGE_OPTIONAL_HEADER64 opthdr
;
255 IMAGE_OPTIONAL_HEADER32 opthdr
;
257 IMAGE_OPTIONAL_HEADER opthdr
;
262 struct pe_reloc_header
{
267 struct pe_rsrc_header
{
268 struct _IMAGE_FILE_HEADER filehdr
;
269 struct _IMAGE_SECTION_HEADER sectionhdr
;
272 struct pe_rsrc_reloc
{
279 /* ------------------------------------------------------------- */
280 /* internal temporary structures */
283 #define IMAGE_SCN_CNT_CODE 0x00000020
284 #define IMAGE_SCN_CNT_INITIALIZED_DATA 0x00000040
285 #define IMAGE_SCN_CNT_UNINITIALIZED_DATA 0x00000080
286 #define IMAGE_SCN_MEM_DISCARDABLE 0x02000000
287 #define IMAGE_SCN_MEM_SHARED 0x10000000
288 #define IMAGE_SCN_MEM_EXECUTE 0x20000000
289 #define IMAGE_SCN_MEM_READ 0x40000000
290 #define IMAGE_SCN_MEM_WRITE 0x80000000
306 static const DWORD pe_sec_flags
[] = {
307 0x60000020, /* ".text" , */
308 0xC0000040, /* ".data" , */
309 0xC0000080, /* ".bss" , */
310 0x40000040, /* ".idata" , */
311 0x40000040, /* ".pdata" , */
312 0xE0000060, /* < other > , */
313 0x40000040, /* ".rsrc" , */
314 0x42000802, /* ".stab" , */
315 0x42000040, /* ".reloc" , */
318 struct section_info
{
326 IMAGE_SECTION_HEADER ish
;
329 struct import_symbol
{
335 struct pe_import_info
{
338 struct import_symbol
**symbols
;
345 const char *filename
;
349 const char *start_symbol
;
360 struct section_info
*sec_info
;
362 struct pe_import_info
**imp_info
;
372 /* --------------------------------------------*/
374 static const char *pe_export_name(TCCState
*s1
, ElfW(Sym
) *sym
)
376 const char *name
= (char*)symtab_section
->link
->data
+ sym
->st_name
;
377 if (s1
->leading_underscore
&& name
[0] == '_' && !(sym
->st_other
& ST_PE_STDCALL
))
382 static int pe_find_import(TCCState
* s1
, ElfW(Sym
) *sym
)
386 int sym_index
= 0, n
= 0;
390 s
= pe_export_name(s1
, sym
);
394 if (sym
->st_other
& ST_PE_STDCALL
) {
395 /* try w/0 stdcall deco (windows API convention) */
397 if (!p
|| s
[0] != '_')
399 strcpy(buffer
, s
+1)[p
-s
-1] = 0;
400 } else if (s
[0] != '_') { /* try non-ansi function */
401 buffer
[0] = '_', strcpy(buffer
+ 1, s
);
402 } else if (0 == memcmp(s
, "__imp_", 6)) { /* mingw 2.0 */
403 strcpy(buffer
, s
+ 6), a
= 1;
404 } else if (0 == memcmp(s
, "_imp__", 6)) { /* mingw 3.7 */
405 strcpy(buffer
, s
+ 6), a
= 1;
411 sym_index
= find_elf_sym(s1
->dynsymtab_section
, s
);
412 // printf("find (%d) %d %s\n", n, sym_index, s);
414 && ELFW(ST_TYPE
)(sym
->st_info
) == STT_OBJECT
415 && 0 == (sym
->st_other
& ST_PE_IMPORT
)
417 ) err
= -1, sym_index
= 0;
418 } while (0 == sym_index
&& ++n
< 2);
419 return n
== 2 ? err
: sym_index
;
422 /*----------------------------------------------------------------------------*/
424 static int dynarray_assoc(void **pp
, int n
, int key
)
427 for (i
= 0; i
< n
; ++i
, ++pp
)
428 if (key
== **(int **) pp
)
434 ST_FN DWORD
umin(DWORD a
, DWORD b
)
436 return a
< b
? a
: b
;
440 static DWORD
umax(DWORD a
, DWORD b
)
442 return a
< b
? b
: a
;
445 static DWORD
pe_file_align(struct pe_info
*pe
, DWORD n
)
447 return (n
+ (pe
->file_align
- 1)) & ~(pe
->file_align
- 1);
450 static DWORD
pe_virtual_align(struct pe_info
*pe
, DWORD n
)
452 return (n
+ (pe
->section_align
- 1)) & ~(pe
->section_align
- 1);
455 static void pe_align_section(Section
*s
, int a
)
457 int i
= s
->data_offset
& (a
-1);
459 section_ptr_add(s
, a
- i
);
462 static void pe_set_datadir(struct pe_header
*hdr
, int dir
, DWORD addr
, DWORD size
)
464 hdr
->opthdr
.DataDirectory
[dir
].VirtualAddress
= addr
;
465 hdr
->opthdr
.DataDirectory
[dir
].Size
= size
;
468 static int pe_fwrite(void *data
, unsigned len
, FILE *fp
, DWORD
*psum
)
474 for (i
= len
; i
> 0; i
-= 2) {
475 sum
+= (i
>= 2) ? *p
++ : *(BYTE
*)p
;
476 sum
= (sum
+ (sum
>> 16)) & 0xFFFF;
480 return len
== fwrite(data
, 1, len
, fp
) ? 0 : -1;
483 static void pe_fpad(FILE *fp
, DWORD new_pos
)
485 DWORD pos
= ftell(fp
);
486 while (++pos
<= new_pos
)
490 /*----------------------------------------------------------------------------*/
491 static int pe_write(struct pe_info
*pe
)
493 static const struct pe_header pe_template
= {
495 /* IMAGE_DOS_HEADER doshdr */
496 0x5A4D, /*WORD e_magic; Magic number */
497 0x0090, /*WORD e_cblp; Bytes on last page of file */
498 0x0003, /*WORD e_cp; Pages in file */
499 0x0000, /*WORD e_crlc; Relocations */
501 0x0004, /*WORD e_cparhdr; Size of header in paragraphs */
502 0x0000, /*WORD e_minalloc; Minimum extra paragraphs needed */
503 0xFFFF, /*WORD e_maxalloc; Maximum extra paragraphs needed */
504 0x0000, /*WORD e_ss; Initial (relative) SS value */
506 0x00B8, /*WORD e_sp; Initial SP value */
507 0x0000, /*WORD e_csum; Checksum */
508 0x0000, /*WORD e_ip; Initial IP value */
509 0x0000, /*WORD e_cs; Initial (relative) CS value */
510 0x0040, /*WORD e_lfarlc; File address of relocation table */
511 0x0000, /*WORD e_ovno; Overlay number */
512 {0,0,0,0}, /*WORD e_res[4]; Reserved words */
513 0x0000, /*WORD e_oemid; OEM identifier (for e_oeminfo) */
514 0x0000, /*WORD e_oeminfo; OEM information; e_oemid specific */
515 {0,0,0,0,0,0,0,0,0,0}, /*WORD e_res2[10]; Reserved words */
516 0x00000080 /*DWORD e_lfanew; File address of new exe header */
518 /* BYTE dosstub[0x40] */
519 /* 14 code bytes + "This program cannot be run in DOS mode.\r\r\n$" + 6 * 0x00 */
520 0x0e,0x1f,0xba,0x0e,0x00,0xb4,0x09,0xcd,0x21,0xb8,0x01,0x4c,0xcd,0x21,0x54,0x68,
521 0x69,0x73,0x20,0x70,0x72,0x6f,0x67,0x72,0x61,0x6d,0x20,0x63,0x61,0x6e,0x6e,0x6f,
522 0x74,0x20,0x62,0x65,0x20,0x72,0x75,0x6e,0x20,0x69,0x6e,0x20,0x44,0x4f,0x53,0x20,
523 0x6d,0x6f,0x64,0x65,0x2e,0x0d,0x0d,0x0a,0x24,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
525 0x00004550, /* DWORD nt_sig = IMAGE_NT_SIGNATURE */
527 /* IMAGE_FILE_HEADER filehdr */
528 IMAGE_FILE_MACHINE
, /*WORD Machine; */
529 0x0003, /*WORD NumberOfSections; */
530 0x00000000, /*DWORD TimeDateStamp; */
531 0x00000000, /*DWORD PointerToSymbolTable; */
532 0x00000000, /*DWORD NumberOfSymbols; */
533 #if defined(TCC_TARGET_X86_64)
534 0x00F0, /*WORD SizeOfOptionalHeader; */
535 0x022F /*WORD Characteristics; */
536 #define CHARACTERISTICS_DLL 0x222E
537 #elif defined(TCC_TARGET_I386)
538 0x00E0, /*WORD SizeOfOptionalHeader; */
539 0x030F /*WORD Characteristics; */
540 #define CHARACTERISTICS_DLL 0x230E
541 #elif defined(TCC_TARGET_ARM)
542 0x00E0, /*WORD SizeOfOptionalHeader; */
543 0x010F, /*WORD Characteristics; */
544 #define CHARACTERISTICS_DLL 0x230F
547 /* IMAGE_OPTIONAL_HEADER opthdr */
548 /* Standard fields. */
549 #ifdef TCC_TARGET_X86_64
550 0x020B, /*WORD Magic; */
552 0x010B, /*WORD Magic; */
554 0x06, /*BYTE MajorLinkerVersion; */
555 0x00, /*BYTE MinorLinkerVersion; */
556 0x00000000, /*DWORD SizeOfCode; */
557 0x00000000, /*DWORD SizeOfInitializedData; */
558 0x00000000, /*DWORD SizeOfUninitializedData; */
559 0x00000000, /*DWORD AddressOfEntryPoint; */
560 0x00000000, /*DWORD BaseOfCode; */
561 #ifndef TCC_TARGET_X86_64
562 0x00000000, /*DWORD BaseOfData; */
564 /* NT additional fields. */
565 #if defined(TCC_TARGET_ARM)
566 0x00100000, /*DWORD ImageBase; */
568 0x00400000, /*DWORD ImageBase; */
570 0x00001000, /*DWORD SectionAlignment; */
571 0x00000200, /*DWORD FileAlignment; */
572 0x0004, /*WORD MajorOperatingSystemVersion; */
573 0x0000, /*WORD MinorOperatingSystemVersion; */
574 0x0000, /*WORD MajorImageVersion; */
575 0x0000, /*WORD MinorImageVersion; */
576 0x0004, /*WORD MajorSubsystemVersion; */
577 0x0000, /*WORD MinorSubsystemVersion; */
578 0x00000000, /*DWORD Win32VersionValue; */
579 0x00000000, /*DWORD SizeOfImage; */
580 0x00000200, /*DWORD SizeOfHeaders; */
581 0x00000000, /*DWORD CheckSum; */
582 0x0002, /*WORD Subsystem; */
583 0x0000, /*WORD DllCharacteristics; */
584 0x00100000, /*DWORD SizeOfStackReserve; */
585 0x00001000, /*DWORD SizeOfStackCommit; */
586 0x00100000, /*DWORD SizeOfHeapReserve; */
587 0x00001000, /*DWORD SizeOfHeapCommit; */
588 0x00000000, /*DWORD LoaderFlags; */
589 0x00000010, /*DWORD NumberOfRvaAndSizes; */
591 /* IMAGE_DATA_DIRECTORY DataDirectory[16]; */
592 {{0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0},
593 {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}}
596 struct pe_header pe_header
= pe_template
;
600 DWORD file_offset
, sum
;
601 struct section_info
*si
;
602 IMAGE_SECTION_HEADER
*psh
;
604 op
= fopen(pe
->filename
, "wb");
606 tcc_error_noabort("could not write '%s': %s", pe
->filename
, strerror(errno
));
610 pe
->sizeofheaders
= pe_file_align(pe
,
611 sizeof (struct pe_header
)
612 + pe
->sec_count
* sizeof (IMAGE_SECTION_HEADER
)
615 file_offset
= pe
->sizeofheaders
;
617 if (2 == pe
->s1
->verbose
)
618 printf("-------------------------------"
619 "\n virt file size section" "\n");
620 for (i
= 0; i
< pe
->sec_count
; ++i
) {
624 si
= pe
->sec_info
+ i
;
626 addr
= si
->sh_addr
- pe
->imagebase
;
630 if (2 == pe
->s1
->verbose
)
631 printf("%6x %6x %6x %s\n",
632 (unsigned)addr
, (unsigned)file_offset
, (unsigned)size
, sh_name
);
636 pe_header
.opthdr
.BaseOfCode
= addr
;
640 #ifndef TCC_TARGET_X86_64
641 pe_header
.opthdr
.BaseOfData
= addr
;
649 pe_set_datadir(&pe_header
, IMAGE_DIRECTORY_ENTRY_BASERELOC
, addr
, size
);
653 pe_set_datadir(&pe_header
, IMAGE_DIRECTORY_ENTRY_RESOURCE
, addr
, size
);
657 pe_set_datadir(&pe_header
, IMAGE_DIRECTORY_ENTRY_EXCEPTION
, addr
, size
);
664 if (pe
->thunk
== pe
->s1
->sections
[si
->ord
]) {
666 pe_set_datadir(&pe_header
, IMAGE_DIRECTORY_ENTRY_IMPORT
,
667 pe
->imp_offs
+ addr
, pe
->imp_size
);
668 pe_set_datadir(&pe_header
, IMAGE_DIRECTORY_ENTRY_IAT
,
669 pe
->iat_offs
+ addr
, pe
->iat_size
);
672 pe_set_datadir(&pe_header
, IMAGE_DIRECTORY_ENTRY_EXPORT
,
673 pe
->exp_offs
+ addr
, pe
->exp_size
);
677 strncpy((char*)psh
->Name
, sh_name
, sizeof psh
->Name
);
679 psh
->Characteristics
= pe_sec_flags
[si
->cls
];
680 psh
->VirtualAddress
= addr
;
681 psh
->Misc
.VirtualSize
= size
;
682 pe_header
.opthdr
.SizeOfImage
=
683 umax(pe_virtual_align(pe
, size
+ addr
), pe_header
.opthdr
.SizeOfImage
);
686 psh
->PointerToRawData
= file_offset
;
687 file_offset
= pe_file_align(pe
, file_offset
+ si
->data_size
);
688 psh
->SizeOfRawData
= file_offset
- psh
->PointerToRawData
;
689 if (si
->cls
== sec_text
)
690 pe_header
.opthdr
.SizeOfCode
+= psh
->SizeOfRawData
;
692 pe_header
.opthdr
.SizeOfInitializedData
+= psh
->SizeOfRawData
;
696 //pe_header.filehdr.TimeDateStamp = time(NULL);
697 pe_header
.filehdr
.NumberOfSections
= pe
->sec_count
;
698 pe_header
.opthdr
.AddressOfEntryPoint
= pe
->start_addr
;
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 chmod(pe
->filename
, 0777);
731 if (2 == pe
->s1
->verbose
)
732 printf("-------------------------------\n");
734 printf("<- %s (%u bytes)\n", pe
->filename
, (unsigned)file_offset
);
739 /*----------------------------------------------------------------------------*/
741 static struct import_symbol
*pe_add_import(struct pe_info
*pe
, int sym_index
)
745 struct pe_import_info
*p
;
746 struct import_symbol
*s
;
749 isym
= (ElfW(Sym
) *)pe
->s1
->dynsymtab_section
->data
+ sym_index
;
750 dll_index
= isym
->st_size
;
752 i
= dynarray_assoc ((void**)pe
->imp_info
, pe
->imp_count
, dll_index
);
757 p
= tcc_mallocz(sizeof *p
);
758 p
->dll_index
= dll_index
;
759 dynarray_add(&pe
->imp_info
, &pe
->imp_count
, p
);
762 i
= dynarray_assoc ((void**)p
->symbols
, p
->sym_count
, sym_index
);
764 return p
->symbols
[i
];
766 s
= tcc_mallocz(sizeof *s
);
767 dynarray_add(&p
->symbols
, &p
->sym_count
, s
);
768 s
->sym_index
= sym_index
;
772 void pe_free_imports(struct pe_info
*pe
)
775 for (i
= 0; i
< pe
->imp_count
; ++i
) {
776 struct pe_import_info
*p
= pe
->imp_info
[i
];
777 dynarray_reset(&p
->symbols
, &p
->sym_count
);
779 dynarray_reset(&pe
->imp_info
, &pe
->imp_count
);
782 /*----------------------------------------------------------------------------*/
783 static void pe_build_imports(struct pe_info
*pe
)
785 int thk_ptr
, ent_ptr
, dll_ptr
, sym_cnt
, i
;
786 DWORD rva_base
= pe
->thunk
->sh_addr
- pe
->imagebase
;
787 int ndlls
= pe
->imp_count
;
789 for (sym_cnt
= i
= 0; i
< ndlls
; ++i
)
790 sym_cnt
+= pe
->imp_info
[i
]->sym_count
;
795 pe_align_section(pe
->thunk
, 16);
797 pe
->imp_offs
= dll_ptr
= pe
->thunk
->data_offset
;
798 pe
->imp_size
= (ndlls
+ 1) * sizeof(IMAGE_IMPORT_DESCRIPTOR
);
799 pe
->iat_offs
= dll_ptr
+ pe
->imp_size
;
800 pe
->iat_size
= (sym_cnt
+ ndlls
) * sizeof(ADDR3264
);
801 section_ptr_add(pe
->thunk
, pe
->imp_size
+ 2*pe
->iat_size
);
803 thk_ptr
= pe
->iat_offs
;
804 ent_ptr
= pe
->iat_offs
+ pe
->iat_size
;
806 for (i
= 0; i
< pe
->imp_count
; ++i
) {
807 IMAGE_IMPORT_DESCRIPTOR
*hdr
;
810 struct pe_import_info
*p
= pe
->imp_info
[i
];
812 DLLReference
*dllref
;
814 dllindex
= p
->dll_index
;
816 name
= (dllref
= pe
->s1
->loaded_dlls
[dllindex
-1])->name
;
818 name
= "", dllref
= NULL
;
820 /* put the dll name into the import header */
821 v
= put_elf_str(pe
->thunk
, name
);
822 hdr
= (IMAGE_IMPORT_DESCRIPTOR
*)(pe
->thunk
->data
+ dll_ptr
);
823 hdr
->FirstThunk
= thk_ptr
+ rva_base
;
824 hdr
->OriginalFirstThunk
= ent_ptr
+ rva_base
;
825 hdr
->Name
= v
+ rva_base
;
827 for (k
= 0, n
= p
->sym_count
; k
<= n
; ++k
) {
829 int iat_index
= p
->symbols
[k
]->iat_index
;
830 int sym_index
= p
->symbols
[k
]->sym_index
;
831 ElfW(Sym
) *imp_sym
= (ElfW(Sym
) *)pe
->s1
->dynsymtab_section
->data
+ sym_index
;
832 ElfW(Sym
) *org_sym
= (ElfW(Sym
) *)symtab_section
->data
+ iat_index
;
833 const char *name
= (char*)pe
->s1
->dynsymtab_section
->link
->data
+ imp_sym
->st_name
;
836 org_sym
->st_value
= thk_ptr
;
837 org_sym
->st_shndx
= pe
->thunk
->sh_num
;
840 v
= 0, ordinal
= imp_sym
->st_value
; /* ordinal from pe_load_def */
842 ordinal
= 0, v
= imp_sym
->st_value
; /* address from tcc_add_symbol() */
845 if (pe
->type
== PE_RUN
) {
847 if ( !dllref
->handle
)
848 dllref
->handle
= LoadLibrary(dllref
->name
);
849 v
= (ADDR3264
)GetProcAddress(dllref
->handle
, ordinal
?(char*)0+ordinal
:name
);
852 tcc_error_noabort("can't build symbol '%s'", name
);
856 v
= ordinal
| (ADDR3264
)1 << (sizeof(ADDR3264
)*8 - 1);
858 v
= pe
->thunk
->data_offset
+ rva_base
;
859 section_ptr_add(pe
->thunk
, sizeof(WORD
)); /* hint, not used */
860 put_elf_str(pe
->thunk
, name
);
864 v
= 0; /* last entry is zero */
867 *(ADDR3264
*)(pe
->thunk
->data
+thk_ptr
) =
868 *(ADDR3264
*)(pe
->thunk
->data
+ent_ptr
) = v
;
869 thk_ptr
+= sizeof (ADDR3264
);
870 ent_ptr
+= sizeof (ADDR3264
);
872 dll_ptr
+= sizeof(IMAGE_IMPORT_DESCRIPTOR
);
876 /* ------------------------------------------------------------- */
884 static int sym_cmp(const void *va
, const void *vb
)
886 const char *ca
= (*(struct pe_sort_sym
**)va
)->name
;
887 const char *cb
= (*(struct pe_sort_sym
**)vb
)->name
;
888 return strcmp(ca
, cb
);
891 static void pe_build_exports(struct pe_info
*pe
)
894 int sym_index
, sym_end
;
895 DWORD rva_base
, func_o
, name_o
, ord_o
, str_o
;
896 IMAGE_EXPORT_DIRECTORY
*hdr
;
898 struct pe_sort_sym
**sorted
, *p
;
905 rva_base
= pe
->thunk
->sh_addr
- pe
->imagebase
;
906 sym_count
= 0, sorted
= NULL
, op
= NULL
;
908 sym_end
= symtab_section
->data_offset
/ sizeof(ElfW(Sym
));
909 for (sym_index
= 1; sym_index
< sym_end
; ++sym_index
) {
910 sym
= (ElfW(Sym
)*)symtab_section
->data
+ sym_index
;
911 name
= pe_export_name(pe
->s1
, sym
);
912 if ((sym
->st_other
& ST_PE_EXPORT
)
913 /* export only symbols from actually written sections */
914 && pe
->s1
->sections
[sym
->st_shndx
]->sh_addr
) {
915 p
= tcc_malloc(sizeof *p
);
916 p
->index
= sym_index
;
918 dynarray_add(&sorted
, &sym_count
, p
);
921 if (sym
->st_other
& ST_PE_EXPORT
)
922 printf("export: %s\n", name
);
923 if (sym
->st_other
& ST_PE_STDCALL
)
924 printf("stdcall: %s\n", name
);
931 qsort (sorted
, sym_count
, sizeof *sorted
, sym_cmp
);
933 pe_align_section(pe
->thunk
, 16);
934 dllname
= tcc_basename(pe
->filename
);
936 pe
->exp_offs
= pe
->thunk
->data_offset
;
937 func_o
= pe
->exp_offs
+ sizeof(IMAGE_EXPORT_DIRECTORY
);
938 name_o
= func_o
+ sym_count
* sizeof (DWORD
);
939 ord_o
= name_o
+ sym_count
* sizeof (DWORD
);
940 str_o
= ord_o
+ sym_count
* sizeof(WORD
);
942 hdr
= section_ptr_add(pe
->thunk
, str_o
- pe
->exp_offs
);
943 hdr
->Characteristics
= 0;
945 hdr
->NumberOfFunctions
= sym_count
;
946 hdr
->NumberOfNames
= sym_count
;
947 hdr
->AddressOfFunctions
= func_o
+ rva_base
;
948 hdr
->AddressOfNames
= name_o
+ rva_base
;
949 hdr
->AddressOfNameOrdinals
= ord_o
+ rva_base
;
950 hdr
->Name
= str_o
+ rva_base
;
951 put_elf_str(pe
->thunk
, dllname
);
954 /* automatically write exports to <output-filename>.def */
955 pstrcpy(buf
, sizeof buf
, pe
->filename
);
956 strcpy(tcc_fileextension(buf
), ".def");
957 op
= fopen(buf
, "wb");
959 tcc_error_noabort("could not create '%s': %s", buf
, strerror(errno
));
961 fprintf(op
, "LIBRARY %s\n\nEXPORTS\n", dllname
);
963 printf("<- %s (%d symbol%s)\n", buf
, sym_count
, &"s"[sym_count
< 2]);
967 for (ord
= 0; ord
< sym_count
; ++ord
)
969 p
= sorted
[ord
], sym_index
= p
->index
, name
= p
->name
;
970 /* insert actual address later in relocate_section() */
971 put_elf_reloc(symtab_section
, pe
->thunk
,
972 func_o
, R_XXX_RELATIVE
, sym_index
);
973 *(DWORD
*)(pe
->thunk
->data
+ name_o
)
974 = pe
->thunk
->data_offset
+ rva_base
;
975 *(WORD
*)(pe
->thunk
->data
+ ord_o
)
977 put_elf_str(pe
->thunk
, name
);
978 func_o
+= sizeof (DWORD
);
979 name_o
+= sizeof (DWORD
);
980 ord_o
+= sizeof (WORD
);
982 fprintf(op
, "%s\n", name
);
984 pe
->exp_size
= pe
->thunk
->data_offset
- pe
->exp_offs
;
985 dynarray_reset(&sorted
, &sym_count
);
990 /* ------------------------------------------------------------- */
991 static void pe_build_reloc (struct pe_info
*pe
)
993 DWORD offset
, block_ptr
, addr
;
995 ElfW_Rel
*rel
, *rel_end
;
996 Section
*s
= NULL
, *sr
;
998 offset
= addr
= block_ptr
= count
= i
= 0;
999 rel
= rel_end
= NULL
;
1002 if (rel
< rel_end
) {
1003 int type
= ELFW(R_TYPE
)(rel
->r_info
);
1004 addr
= rel
->r_offset
+ s
->sh_addr
;
1006 if (type
!= REL_TYPE_DIRECT
)
1008 if (count
== 0) { /* new block */
1009 block_ptr
= pe
->reloc
->data_offset
;
1010 section_ptr_add(pe
->reloc
, sizeof(struct pe_reloc_header
));
1011 offset
= addr
& 0xFFFFFFFF<<12;
1013 if ((addr
-= offset
) < (1<<12)) { /* one block spans 4k addresses */
1014 WORD
*wp
= section_ptr_add(pe
->reloc
, sizeof (WORD
));
1015 *wp
= addr
| PE_IMAGE_REL
<<12;
1021 } else if (i
< pe
->sec_count
) {
1022 sr
= (s
= pe
->s1
->sections
[pe
->sec_info
[i
++].ord
])->reloc
;
1024 rel
= (ElfW_Rel
*)sr
->data
;
1025 rel_end
= (ElfW_Rel
*)(sr
->data
+ sr
->data_offset
);
1031 /* store the last block and ready for a new one */
1032 struct pe_reloc_header
*hdr
;
1033 if (count
& 1) /* align for DWORDS */
1034 section_ptr_add(pe
->reloc
, sizeof(WORD
)), ++count
;
1035 hdr
= (struct pe_reloc_header
*)(pe
->reloc
->data
+ block_ptr
);
1036 hdr
-> offset
= offset
- pe
->imagebase
;
1037 hdr
-> size
= count
* sizeof(WORD
) + sizeof(struct pe_reloc_header
);
1046 /* ------------------------------------------------------------- */
1047 static int pe_section_class(Section
*s
)
1053 flags
= s
->sh_flags
;
1055 if (flags
& SHF_ALLOC
) {
1056 if (type
== SHT_PROGBITS
) {
1057 if (flags
& SHF_EXECINSTR
)
1059 if (flags
& SHF_WRITE
)
1061 if (0 == strcmp(name
, ".rsrc"))
1063 if (0 == strcmp(name
, ".iedat"))
1065 if (0 == strcmp(name
, ".pdata"))
1068 } else if (type
== SHT_NOBITS
) {
1069 if (flags
& SHF_WRITE
)
1073 if (0 == strcmp(name
, ".reloc"))
1075 if (0 == strncmp(name
, ".stab", 5)) /* .stab and .stabstr */
1081 static int pe_assign_addresses (struct pe_info
*pe
)
1086 struct section_info
*si
;
1089 if (PE_DLL
== pe
->type
)
1090 pe
->reloc
= new_section(pe
->s1
, ".reloc", SHT_PROGBITS
, 0);
1092 // pe->thunk = new_section(pe->s1, ".iedat", SHT_PROGBITS, SHF_ALLOC);
1094 section_order
= tcc_malloc(pe
->s1
->nb_sections
* sizeof (int));
1095 for (o
= k
= 0 ; k
< sec_last
; ++k
) {
1096 for (i
= 1; i
< pe
->s1
->nb_sections
; ++i
) {
1097 s
= pe
->s1
->sections
[i
];
1098 if (k
== pe_section_class(s
)) {
1099 // printf("%s %d\n", s->name, k);
1100 s
->sh_addr
= pe
->imagebase
;
1101 section_order
[o
++] = i
;
1106 pe
->sec_info
= tcc_mallocz(o
* sizeof (struct section_info
));
1107 addr
= pe
->imagebase
+ 1;
1109 for (i
= 0; i
< o
; ++i
)
1111 k
= section_order
[i
];
1112 s
= pe
->s1
->sections
[k
];
1113 c
= pe_section_class(s
);
1114 si
= &pe
->sec_info
[pe
->sec_count
];
1116 #ifdef PE_MERGE_DATA
1117 if (c
== sec_bss
&& pe
->sec_count
&& si
[-1].cls
== sec_data
) {
1118 /* append .bss to .data */
1119 s
->sh_addr
= addr
= ((addr
-1) | (s
->sh_addralign
-1)) + 1;
1120 addr
+= s
->data_offset
;
1121 si
[-1].sh_size
= addr
- si
[-1].sh_addr
;
1125 if (c
== sec_stab
&& 0 == pe
->s1
->do_debug
)
1128 strcpy(si
->name
, s
->name
);
1131 si
->sh_addr
= s
->sh_addr
= addr
= pe_virtual_align(pe
, addr
);
1132 si
->sh_flags
= s
->sh_flags
;
1134 if (c
== sec_data
&& NULL
== pe
->thunk
)
1137 if (s
== pe
->thunk
) {
1138 pe_build_imports(pe
);
1139 pe_build_exports(pe
);
1143 pe_build_reloc (pe
);
1147 if (s
->sh_type
!= SHT_NOBITS
) {
1149 si
->data_size
= s
->data_offset
;
1152 addr
+= s
->data_offset
;
1153 si
->sh_size
= s
->data_offset
;
1156 // printf("%08x %05x %s\n", si->sh_addr, si->sh_size, si->name);
1160 for (i
= 1; i
< pe
->s1
->nb_sections
; ++i
) {
1161 Section
*s
= pe
->s1
->sections
[i
];
1162 int type
= s
->sh_type
;
1163 int flags
= s
->sh_flags
;
1164 printf("section %-16s %-10s %5x %s,%s,%s\n",
1166 type
== SHT_PROGBITS
? "progbits" :
1167 type
== SHT_NOBITS
? "nobits" :
1168 type
== SHT_SYMTAB
? "symtab" :
1169 type
== SHT_STRTAB
? "strtab" :
1170 type
== SHT_RELX
? "rel" : "???",
1172 flags
& SHF_ALLOC
? "alloc" : "",
1173 flags
& SHF_WRITE
? "write" : "",
1174 flags
& SHF_EXECINSTR
? "exec" : ""
1177 pe
->s1
->verbose
= 2;
1180 tcc_free(section_order
);
1184 /*----------------------------------------------------------------------------*/
1186 static int pe_isafunc(int sym_index
)
1188 Section
*sr
= text_section
->reloc
;
1189 ElfW_Rel
*rel
, *rel_end
;
1190 Elf32_Word info
= ELF32_R_INFO(sym_index
, R_386_PC32
);
1193 rel_end
= (ElfW_Rel
*)(sr
->data
+ sr
->data_offset
);
1194 for (rel
= (ElfW_Rel
*)sr
->data
; rel
< rel_end
; rel
++)
1195 if (rel
->r_info
== info
)
1200 /*----------------------------------------------------------------------------*/
1201 static int pe_check_symbols(struct pe_info
*pe
)
1204 int sym_index
, sym_end
;
1207 pe_align_section(text_section
, 8);
1209 sym_end
= symtab_section
->data_offset
/ sizeof(ElfW(Sym
));
1210 for (sym_index
= 1; sym_index
< sym_end
; ++sym_index
) {
1212 sym
= (ElfW(Sym
) *)symtab_section
->data
+ sym_index
;
1213 if (sym
->st_shndx
== SHN_UNDEF
) {
1215 const char *name
= (char*)symtab_section
->link
->data
+ sym
->st_name
;
1216 unsigned type
= ELFW(ST_TYPE
)(sym
->st_info
);
1217 int imp_sym
= pe_find_import(pe
->s1
, sym
);
1218 struct import_symbol
*is
;
1223 if (type
== STT_NOTYPE
) {
1224 /* symbols from assembler have no type, find out which */
1225 if (pe_isafunc(sym_index
))
1231 is
= pe_add_import(pe
, imp_sym
);
1233 if (type
== STT_FUNC
) {
1234 unsigned long offset
= is
->thk_offset
;
1236 /* got aliased symbol, like stricmp and _stricmp */
1242 offset
= text_section
->data_offset
;
1243 /* add the 'jmp IAT[x]' instruction */
1244 #ifdef TCC_TARGET_ARM
1245 p
= section_ptr_add(text_section
, 8+4); // room for code and address
1246 (*(DWORD
*)(p
)) = 0xE59FC000; // arm code ldr ip, [pc] ; PC+8+0 = 0001xxxx
1247 (*(DWORD
*)(p
+2)) = 0xE59CF000; // arm code ldr pc, [ip]
1249 p
= section_ptr_add(text_section
, 8);
1251 #ifdef TCC_TARGET_X86_64
1252 *(DWORD
*)(p
+1) = (DWORD
)-4;
1255 /* add a helper symbol, will be patched later in
1257 sprintf(buffer
, "IAT.%s", name
);
1258 is
->iat_index
= put_elf_sym(
1259 symtab_section
, 0, sizeof(DWORD
),
1260 ELFW(ST_INFO
)(STB_GLOBAL
, STT_OBJECT
),
1261 0, SHN_UNDEF
, buffer
);
1262 #ifdef TCC_TARGET_ARM
1263 put_elf_reloc(symtab_section
, text_section
,
1264 offset
+ 8, R_XXX_THUNKFIX
, is
->iat_index
); // offset to IAT position
1266 put_elf_reloc(symtab_section
, text_section
,
1267 offset
+ 2, R_XXX_THUNKFIX
, is
->iat_index
);
1269 is
->thk_offset
= offset
;
1272 /* tcc_realloc might have altered sym's address */
1273 sym
= (ElfW(Sym
) *)symtab_section
->data
+ sym_index
;
1275 /* patch the original symbol */
1276 sym
->st_value
= offset
;
1277 sym
->st_shndx
= text_section
->sh_num
;
1278 sym
->st_other
&= ~ST_PE_EXPORT
; /* do not export */
1282 if (type
== STT_OBJECT
) { /* data, ptr to that should be */
1283 if (0 == is
->iat_index
) {
1284 /* original symbol will be patched later in pe_build_imports */
1285 is
->iat_index
= sym_index
;
1291 if (ELFW(ST_BIND
)(sym
->st_info
) == STB_WEAK
)
1292 /* STB_WEAK undefined symbols are accepted */
1294 tcc_error_noabort("undefined symbol '%s'%s", name
,
1295 imp_sym
< 0 ? ", missing __declspec(dllimport)?":"");
1298 } else if (pe
->s1
->rdynamic
1299 && ELFW(ST_BIND
)(sym
->st_info
) != STB_LOCAL
) {
1300 /* if -rdynamic option, then export all non local symbols */
1301 sym
->st_other
|= ST_PE_EXPORT
;
1307 /*----------------------------------------------------------------------------*/
1308 #ifdef PE_PRINT_SECTIONS
1309 static void pe_print_section(FILE * f
, Section
* s
)
1311 /* just if you're curious */
1315 e
= s
->data
+ s
->data_offset
;
1318 fprintf(f
, "section \"%s\"", s
->name
);
1320 fprintf(f
, "\nlink \"%s\"", s
->link
->name
);
1322 fprintf(f
, "\nreloc \"%s\"", s
->reloc
->name
);
1323 fprintf(f
, "\nv_addr %08X", (unsigned)s
->sh_addr
);
1324 fprintf(f
, "\ncontents %08X", (unsigned)l
);
1327 if (s
->sh_type
== SHT_NOBITS
)
1333 if (s
->sh_type
== SHT_SYMTAB
)
1334 m
= sizeof(ElfW(Sym
));
1335 else if (s
->sh_type
== SHT_RELX
)
1336 m
= sizeof(ElfW_Rel
);
1340 fprintf(f
, "%-8s", "offset");
1341 for (i
= 0; i
< m
; ++i
)
1342 fprintf(f
, " %02x", i
);
1345 if (s
->sh_type
== SHT_SYMTAB
|| s
->sh_type
== SHT_RELX
) {
1346 const char *fields1
[] = {
1357 const char *fields2
[] = {
1366 if (s
->sh_type
== SHT_SYMTAB
)
1367 p
= fields1
, n
= 106;
1369 p
= fields2
, n
= 58;
1371 for (i
= 0; p
[i
]; ++i
)
1372 fprintf(f
, "%6s", p
[i
]);
1373 fprintf(f
, " symbol");
1377 for (i
= 0; i
< n
; ++i
)
1383 fprintf(f
, "%08X", i
);
1384 for (n
= 0; n
< m
; ++n
) {
1386 fprintf(f
, " %02X", p
[i
+ n
]);
1391 if (s
->sh_type
== SHT_SYMTAB
) {
1392 ElfW(Sym
) *sym
= (ElfW(Sym
) *) (p
+ i
);
1393 const char *name
= s
->link
->data
+ sym
->st_name
;
1394 fprintf(f
, " %04X %04X %04X %02X %02X %02X %04X \"%s\"",
1395 (unsigned)sym
->st_name
,
1396 (unsigned)sym
->st_value
,
1397 (unsigned)sym
->st_size
,
1398 (unsigned)ELFW(ST_BIND
)(sym
->st_info
),
1399 (unsigned)ELFW(ST_TYPE
)(sym
->st_info
),
1400 (unsigned)sym
->st_other
,
1401 (unsigned)sym
->st_shndx
,
1404 } else if (s
->sh_type
== SHT_RELX
) {
1405 ElfW_Rel
*rel
= (ElfW_Rel
*) (p
+ i
);
1407 (ElfW(Sym
) *) s
->link
->data
+ ELFW(R_SYM
)(rel
->r_info
);
1408 const char *name
= s
->link
->link
->data
+ sym
->st_name
;
1409 fprintf(f
, " %04X %02X %04X \"%s\"",
1410 (unsigned)rel
->r_offset
,
1411 (unsigned)ELFW(R_TYPE
)(rel
->r_info
),
1412 (unsigned)ELFW(R_SYM
)(rel
->r_info
),
1416 for (n
= 0; n
< m
; ++n
) {
1419 if (b
< 32 || b
>= 127)
1421 fprintf(f
, "%c", b
);
1431 static void pe_print_sections(TCCState
*s1
, const char *fname
)
1436 f
= fopen(fname
, "w");
1437 for (i
= 1; i
< s1
->nb_sections
; ++i
) {
1438 s
= s1
->sections
[i
];
1439 pe_print_section(f
, s
);
1441 pe_print_section(f
, s1
->dynsymtab_section
);
1446 /* ------------------------------------------------------------- */
1447 /* helper function for load/store to insert one more indirection */
1449 #if defined TCC_TARGET_I386 || defined TCC_TARGET_X86_64
1450 ST_FUNC SValue
*pe_getimport(SValue
*sv
, SValue
*v2
)
1453 if ((sv
->r
& (VT_VALMASK
|VT_SYM
)) != (VT_CONST
|VT_SYM
) || (sv
->r2
!= VT_CONST
))
1455 if (!sv
->sym
->a
.dllimport
)
1457 // printf("import %04x %04x %04x %s\n", sv->type.t, sv->sym->type.t, sv->r, get_tok_str(sv->sym->v, NULL));
1458 memset(v2
, 0, sizeof *v2
);
1459 v2
->type
.t
= VT_PTR
;
1460 v2
->r
= VT_CONST
| VT_SYM
| VT_LVAL
;
1463 r2
= get_reg(RC_INT
);
1466 if ((uint32_t)sv
->c
.i
) {
1472 v2
->type
.t
= sv
->type
.t
;
1473 v2
->r
|= sv
->r
& VT_LVAL
;
1478 ST_FUNC
int pe_putimport(TCCState
*s1
, int dllindex
, const char *name
, addr_t value
)
1481 s1
->dynsymtab_section
,
1483 dllindex
, /* st_size */
1484 ELFW(ST_INFO
)(STB_GLOBAL
, STT_NOTYPE
),
1486 value
? SHN_ABS
: SHN_UNDEF
,
1491 static int add_dllref(TCCState
*s1
, const char *dllname
)
1493 DLLReference
*dllref
;
1495 for (i
= 0; i
< s1
->nb_loaded_dlls
; ++i
)
1496 if (0 == strcmp(s1
->loaded_dlls
[i
]->name
, dllname
))
1498 dllref
= tcc_mallocz(sizeof(DLLReference
) + strlen(dllname
));
1499 strcpy(dllref
->name
, dllname
);
1500 dynarray_add(&s1
->loaded_dlls
, &s1
->nb_loaded_dlls
, dllref
);
1501 return s1
->nb_loaded_dlls
;
1504 /* ------------------------------------------------------------- */
1506 static int read_mem(int fd
, unsigned offset
, void *buffer
, unsigned len
)
1508 lseek(fd
, offset
, SEEK_SET
);
1509 return len
== read(fd
, buffer
, len
);
1512 /* ------------------------------------------------------------- */
1514 PUB_FUNC
int tcc_get_dllexports(const char *filename
, char **pp
)
1516 int l
, i
, n
, n0
, ret
;
1520 IMAGE_SECTION_HEADER ish
;
1521 IMAGE_EXPORT_DIRECTORY ied
;
1522 IMAGE_DOS_HEADER dh
;
1523 IMAGE_FILE_HEADER ih
;
1524 DWORD sig
, ref
, addr
, ptr
, namep
;
1526 int pef_hdroffset
, opt_hdroffset
, sec_hdroffset
;
1532 fd
= open(filename
, O_RDONLY
| O_BINARY
);
1536 if (!read_mem(fd
, 0, &dh
, sizeof dh
))
1538 if (!read_mem(fd
, dh
.e_lfanew
, &sig
, sizeof sig
))
1540 if (sig
!= 0x00004550)
1542 pef_hdroffset
= dh
.e_lfanew
+ sizeof sig
;
1543 if (!read_mem(fd
, pef_hdroffset
, &ih
, sizeof ih
))
1545 opt_hdroffset
= pef_hdroffset
+ sizeof ih
;
1546 if (ih
.Machine
== 0x014C) {
1547 IMAGE_OPTIONAL_HEADER32 oh
;
1548 sec_hdroffset
= opt_hdroffset
+ sizeof oh
;
1549 if (!read_mem(fd
, opt_hdroffset
, &oh
, sizeof oh
))
1551 if (IMAGE_DIRECTORY_ENTRY_EXPORT
>= oh
.NumberOfRvaAndSizes
)
1553 addr
= oh
.DataDirectory
[IMAGE_DIRECTORY_ENTRY_EXPORT
].VirtualAddress
;
1554 } else if (ih
.Machine
== 0x8664) {
1555 IMAGE_OPTIONAL_HEADER64 oh
;
1556 sec_hdroffset
= opt_hdroffset
+ sizeof oh
;
1557 if (!read_mem(fd
, opt_hdroffset
, &oh
, sizeof oh
))
1559 if (IMAGE_DIRECTORY_ENTRY_EXPORT
>= oh
.NumberOfRvaAndSizes
)
1561 addr
= oh
.DataDirectory
[IMAGE_DIRECTORY_ENTRY_EXPORT
].VirtualAddress
;
1565 //printf("addr: %08x\n", addr);
1566 for (i
= 0; i
< ih
.NumberOfSections
; ++i
) {
1567 if (!read_mem(fd
, sec_hdroffset
+ i
* sizeof ish
, &ish
, sizeof ish
))
1569 //printf("vaddr: %08x\n", ish.VirtualAddress);
1570 if (addr
>= ish
.VirtualAddress
&& addr
< ish
.VirtualAddress
+ ish
.SizeOfRawData
)
1576 ref
= ish
.VirtualAddress
- ish
.PointerToRawData
;
1577 if (!read_mem(fd
, addr
- ref
, &ied
, sizeof ied
))
1580 namep
= ied
.AddressOfNames
- ref
;
1581 for (i
= 0; i
< ied
.NumberOfNames
; ++i
) {
1582 if (!read_mem(fd
, namep
, &ptr
, sizeof ptr
))
1584 namep
+= sizeof ptr
;
1587 p
= tcc_realloc(p
, n0
= n0
? n0
* 2 : 256);
1588 if (!read_mem(fd
, ptr
- ref
+ l
++, p
+ n
, 1)) {
1589 tcc_free(p
), p
= NULL
;
1607 /* -------------------------------------------------------------
1608 * This is for compiled windows resources in 'coff' format
1609 * as generated by 'windres.exe -O coff ...'.
1612 static int pe_load_res(TCCState
*s1
, int fd
)
1614 struct pe_rsrc_header hdr
;
1615 Section
*rsrc_section
;
1616 int i
, ret
= -1, sym_index
;
1620 if (!read_mem(fd
, 0, &hdr
, sizeof hdr
))
1623 if (hdr
.filehdr
.Machine
!= IMAGE_FILE_MACHINE
1624 || hdr
.filehdr
.NumberOfSections
!= 1
1625 || strcmp((char*)hdr
.sectionhdr
.Name
, ".rsrc") != 0)
1628 rsrc_section
= new_section(s1
, ".rsrc", SHT_PROGBITS
, SHF_ALLOC
);
1629 ptr
= section_ptr_add(rsrc_section
, hdr
.sectionhdr
.SizeOfRawData
);
1630 offs
= hdr
.sectionhdr
.PointerToRawData
;
1631 if (!read_mem(fd
, offs
, ptr
, hdr
.sectionhdr
.SizeOfRawData
))
1633 offs
= hdr
.sectionhdr
.PointerToRelocations
;
1634 sym_index
= put_elf_sym(symtab_section
, 0, 0, 0, 0, rsrc_section
->sh_num
, ".rsrc");
1635 for (i
= 0; i
< hdr
.sectionhdr
.NumberOfRelocations
; ++i
) {
1636 struct pe_rsrc_reloc rel
;
1637 if (!read_mem(fd
, offs
, &rel
, sizeof rel
))
1639 // printf("rsrc_reloc: %x %x %x\n", rel.offset, rel.size, rel.type);
1640 if (rel
.type
!= RSRC_RELTYPE
)
1642 put_elf_reloc(symtab_section
, rsrc_section
,
1643 rel
.offset
, R_XXX_RELATIVE
, sym_index
);
1651 /* ------------------------------------------------------------- */
1653 static char *trimfront(char *p
)
1655 while (*p
&& (unsigned char)*p
<= ' ')
1660 static char *trimback(char *a
, char *e
)
1662 while (e
> a
&& (unsigned char)e
[-1] <= ' ')
1668 /* ------------------------------------------------------------- */
1669 static int pe_load_def(TCCState
*s1
, int fd
)
1671 int state
= 0, ret
= -1, dllindex
= 0, ord
;
1672 char line
[400], dllname
[80], *p
, *x
;
1675 fp
= fdopen(dup(fd
), "rb");
1676 while (fgets(line
, sizeof line
, fp
))
1678 p
= trimfront(trimback(line
, strchr(line
, 0)));
1679 if (0 == *p
|| ';' == *p
)
1684 if (0 != strnicmp(p
, "LIBRARY", 7))
1686 pstrcpy(dllname
, sizeof dllname
, trimfront(p
+7));
1691 if (0 != stricmp(p
, "EXPORTS"))
1697 dllindex
= add_dllref(s1
, dllname
);
1701 /* get ordinal and will store in sym->st_value */
1705 *x
= 0, x
= strrchr(x
+ 1, '@');
1708 ord
= (int)strtol(x
+ 1, &d
, 10);
1713 pe_putimport(s1
, dllindex
, p
, ord
);
1723 /* ------------------------------------------------------------- */
1724 static int pe_load_dll(TCCState
*s1
, const char *filename
)
1729 ret
= tcc_get_dllexports(filename
, &p
);
1733 index
= add_dllref(s1
, tcc_basename(filename
));
1734 for (q
= p
; *q
; q
+= 1 + strlen(q
))
1735 pe_putimport(s1
, index
, q
, 0);
1741 /* ------------------------------------------------------------- */
1742 ST_FUNC
int pe_load_file(struct TCCState
*s1
, const char *filename
, int fd
)
1746 if (0 == strcmp(tcc_fileextension(filename
), ".def"))
1747 ret
= pe_load_def(s1
, fd
);
1748 else if (pe_load_res(s1
, fd
) == 0)
1750 else if (read_mem(fd
, 0, buf
, 4) && 0 == memcmp(buf
, "MZ", 2))
1751 ret
= pe_load_dll(s1
, filename
);
1755 /* ------------------------------------------------------------- */
1756 #ifdef TCC_TARGET_X86_64
1757 static unsigned pe_add_uwwind_info(TCCState
*s1
)
1759 if (NULL
== s1
->uw_pdata
) {
1760 s1
->uw_pdata
= find_section(tcc_state
, ".pdata");
1761 s1
->uw_pdata
->sh_addralign
= 4;
1763 if (0 == s1
->uw_sym
)
1764 s1
->uw_sym
= put_elf_sym(symtab_section
, 0, 0, 0, 0, text_section
->sh_num
, ".uw_base");
1765 if (0 == s1
->uw_offs
) {
1766 /* As our functions all have the same stackframe, we use one entry for all */
1767 static const unsigned char uw_info
[] = {
1768 0x01, // UBYTE: 3 Version , UBYTE: 5 Flags
1769 0x04, // UBYTE Size of prolog
1770 0x02, // UBYTE Count of unwind codes
1771 0x05, // UBYTE: 4 Frame Register (rbp), UBYTE: 4 Frame Register offset (scaled)
1772 // USHORT * n Unwind codes array
1773 // 0x0b, 0x01, 0xff, 0xff, // stack size
1774 0x04, 0x03, // set frame ptr (mov rsp -> rbp)
1775 0x01, 0x50 // push reg (rbp)
1778 Section
*s
= text_section
;
1781 section_ptr_add(s
, -s
->data_offset
& 3); /* align */
1782 s1
->uw_offs
= s
->data_offset
;
1783 p
= section_ptr_add(s
, sizeof uw_info
);
1784 memcpy(p
, uw_info
, sizeof uw_info
);
1790 ST_FUNC
void pe_add_unwind_data(unsigned start
, unsigned end
, unsigned stack
)
1792 TCCState
*s1
= tcc_state
;
1795 struct /* _RUNTIME_FUNCTION */ {
1801 d
= pe_add_uwwind_info(s1
);
1803 o
= pd
->data_offset
;
1804 p
= section_ptr_add(pd
, sizeof *p
);
1806 /* record this function */
1807 p
->BeginAddress
= start
;
1808 p
->EndAddress
= end
;
1811 /* put relocations on it */
1812 for (n
= o
+ sizeof *p
; o
< n
; o
+= sizeof p
->BeginAddress
)
1813 put_elf_reloc(symtab_section
, pd
, o
, R_XXX_RELATIVE
, s1
->uw_sym
);
1816 /* ------------------------------------------------------------- */
1817 #ifdef TCC_TARGET_X86_64
1818 #define PE_STDSYM(n,s) n
1820 #define PE_STDSYM(n,s) "_" n s
1823 static void pe_add_runtime(TCCState
*s1
, struct pe_info
*pe
)
1825 const char *start_symbol
;
1827 int unicode_entry
= 0;
1829 if (find_elf_sym(symtab_section
, PE_STDSYM("WinMain","@16")))
1832 if (find_elf_sym(symtab_section
, PE_STDSYM("wWinMain","@16"))) {
1834 unicode_entry
= PE_GUI
;
1837 if (TCC_OUTPUT_DLL
== s1
->output_type
) {
1839 /* need this for 'tccelf.c:relocate_section()' */
1840 s1
->output_type
= TCC_OUTPUT_EXE
;
1844 if (find_elf_sym(symtab_section
, "wmain"))
1845 unicode_entry
= PE_EXE
;
1849 TCC_OUTPUT_MEMORY
== s1
->output_type
1850 ? PE_GUI
== pe_type
? (unicode_entry
? "__runwwinmain" : "__runwinmain")
1851 : (unicode_entry
? "__runwmain" : "__runmain")
1852 : PE_DLL
== pe_type
? PE_STDSYM("__dllstart","@12")
1853 : PE_GUI
== pe_type
? (unicode_entry
? "__wwinstart": "__winstart")
1854 : (unicode_entry
? "__wstart" : "__start")
1857 if (!s1
->leading_underscore
|| strchr(start_symbol
, '@'))
1860 /* grab the startup code from libtcc1 */
1861 #ifdef TCC_IS_NATIVE
1862 if (TCC_OUTPUT_MEMORY
!= s1
->output_type
|| s1
->runtime_main
)
1864 set_elf_sym(symtab_section
,
1866 ELFW(ST_INFO
)(STB_GLOBAL
, STT_NOTYPE
), 0,
1867 SHN_UNDEF
, start_symbol
);
1869 if (0 == s1
->nostdlib
) {
1870 static const char *libs
[] = {
1871 TCC_LIBTCC1
, "msvcrt", "kernel32", "", "user32", "gdi32", NULL
1873 const char **pp
, *p
;
1874 for (pp
= libs
; 0 != (p
= *pp
); ++pp
) {
1876 if (PE_DLL
!= pe_type
&& PE_GUI
!= pe_type
)
1878 } else if (pp
== libs
&& tcc_add_dll(s1
, p
, 0) >= 0) {
1881 tcc_add_library_err(s1
, p
);
1886 if (TCC_OUTPUT_MEMORY
== s1
->output_type
)
1889 pe
->start_symbol
= start_symbol
;
1892 static void pe_set_options(TCCState
* s1
, struct pe_info
*pe
)
1894 if (PE_DLL
== pe
->type
) {
1895 /* XXX: check if is correct for arm-pe target */
1896 pe
->imagebase
= 0x10000000;
1898 #if defined(TCC_TARGET_ARM)
1899 pe
->imagebase
= 0x00010000;
1901 pe
->imagebase
= 0x00400000;
1905 #if defined(TCC_TARGET_ARM)
1906 /* we use "console" subsystem by default */
1909 if (PE_DLL
== pe
->type
|| PE_GUI
== pe
->type
)
1914 /* Allow override via -Wl,-subsystem=... option */
1915 if (s1
->pe_subsystem
!= 0)
1916 pe
->subsystem
= s1
->pe_subsystem
;
1918 /* set default file/section alignment */
1919 if (pe
->subsystem
== 1) {
1920 pe
->section_align
= 0x20;
1921 pe
->file_align
= 0x20;
1923 pe
->section_align
= 0x1000;
1924 pe
->file_align
= 0x200;
1927 if (s1
->section_align
!= 0)
1928 pe
->section_align
= s1
->section_align
;
1929 if (s1
->pe_file_align
!= 0)
1930 pe
->file_align
= s1
->pe_file_align
;
1932 if ((pe
->subsystem
>= 10) && (pe
->subsystem
<= 12))
1935 if (s1
->has_text_addr
)
1936 pe
->imagebase
= s1
->text_addr
;
1939 ST_FUNC
int pe_output_file(TCCState
*s1
, const char *filename
)
1945 memset(&pe
, 0, sizeof pe
);
1946 pe
.filename
= filename
;
1949 tcc_add_runtime(s1
);
1950 pe_add_runtime(s1
, &pe
);
1951 resolve_common_syms(s1
);
1952 pe_set_options(s1
, &pe
);
1954 ret
= pe_check_symbols(&pe
);
1957 else if (filename
) {
1958 pe_assign_addresses(&pe
);
1959 relocate_syms(s1
, s1
->symtab
, 0);
1960 s1
->pe_imagebase
= pe
.imagebase
;
1961 for (i
= 1; i
< s1
->nb_sections
; ++i
) {
1962 Section
*s
= s1
->sections
[i
];
1964 relocate_section(s1
, s
);
1967 pe
.start_addr
= (DWORD
)
1968 ((uintptr_t)tcc_get_symbol_err(s1
, pe
.start_symbol
)
1973 ret
= pe_write(&pe
);
1974 tcc_free(pe
.sec_info
);
1976 #ifdef TCC_IS_NATIVE
1977 pe
.thunk
= data_section
;
1978 pe_build_imports(&pe
);
1979 s1
->runtime_main
= pe
.start_symbol
;
1980 #ifdef TCC_TARGET_X86_64
1981 s1
->uw_pdata
= find_section(s1
, ".pdata");
1986 pe_free_imports(&pe
);
1988 #ifdef PE_PRINT_SECTIONS
1989 pe_print_sections(s1
, "tcc.log");
1994 /* ------------------------------------------------------------- */