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
25 #define ST_DATA static
29 #define stricmp strcasecmp
30 #define strnicmp strncasecmp
38 // #define PE_PRINT_SECTIONS
40 #ifdef TCC_TARGET_X86_64
41 # define ADDR3264 ULONGLONG
43 # define ADDR3264 DWORD
46 #if defined _WIN32 && (defined _WIN64) == (defined TCC_TARGET_X86_64)
51 void dbg_printf (const char *fmt
, ...)
57 x
= vsprintf (buffer
, fmt
, arg
);
58 strcpy(buffer
+x
, "\n");
59 OutputDebugString(buffer
);
63 /* ----------------------------------------------------------- */
64 #ifndef IMAGE_NT_SIGNATURE
65 /* ----------------------------------------------------------- */
66 /* definitions below are from winnt.h */
68 typedef unsigned char BYTE
;
69 typedef unsigned short WORD
;
70 typedef unsigned long DWORD
;
71 typedef unsigned long long ULONGLONG
;
74 typedef struct _IMAGE_DOS_HEADER
{ /* DOS .EXE header */
75 WORD e_magic
; /* Magic number */
76 WORD e_cblp
; /* Bytes on last page of file */
77 WORD e_cp
; /* Pages in file */
78 WORD e_crlc
; /* Relocations */
79 WORD e_cparhdr
; /* Size of header in paragraphs */
80 WORD e_minalloc
; /* Minimum extra paragraphs needed */
81 WORD e_maxalloc
; /* Maximum extra paragraphs needed */
82 WORD e_ss
; /* Initial (relative) SS value */
83 WORD e_sp
; /* Initial SP value */
84 WORD e_csum
; /* Checksum */
85 WORD e_ip
; /* Initial IP value */
86 WORD e_cs
; /* Initial (relative) CS value */
87 WORD e_lfarlc
; /* File address of relocation table */
88 WORD e_ovno
; /* Overlay number */
89 WORD e_res
[4]; /* Reserved words */
90 WORD e_oemid
; /* OEM identifier (for e_oeminfo) */
91 WORD e_oeminfo
; /* OEM information; e_oemid specific */
92 WORD e_res2
[10]; /* Reserved words */
93 DWORD e_lfanew
; /* File address of new exe header */
94 } IMAGE_DOS_HEADER
, *PIMAGE_DOS_HEADER
;
96 #define IMAGE_NT_SIGNATURE 0x00004550 /* PE00 */
97 #define SIZE_OF_NT_SIGNATURE 4
99 typedef struct _IMAGE_FILE_HEADER
{
101 WORD NumberOfSections
;
103 DWORD PointerToSymbolTable
;
104 DWORD NumberOfSymbols
;
105 WORD SizeOfOptionalHeader
;
106 WORD Characteristics
;
107 } IMAGE_FILE_HEADER
, *PIMAGE_FILE_HEADER
;
110 #define IMAGE_SIZEOF_FILE_HEADER 20
112 typedef struct _IMAGE_DATA_DIRECTORY
{
113 DWORD VirtualAddress
;
115 } IMAGE_DATA_DIRECTORY
, *PIMAGE_DATA_DIRECTORY
;
118 typedef struct _IMAGE_OPTIONAL_HEADER
{
119 /* Standard fields. */
121 BYTE MajorLinkerVersion
;
122 BYTE MinorLinkerVersion
;
124 DWORD SizeOfInitializedData
;
125 DWORD SizeOfUninitializedData
;
126 DWORD AddressOfEntryPoint
;
128 #ifndef TCC_TARGET_X86_64
131 /* NT additional fields. */
133 DWORD SectionAlignment
;
135 WORD MajorOperatingSystemVersion
;
136 WORD MinorOperatingSystemVersion
;
137 WORD MajorImageVersion
;
138 WORD MinorImageVersion
;
139 WORD MajorSubsystemVersion
;
140 WORD MinorSubsystemVersion
;
141 DWORD Win32VersionValue
;
146 WORD DllCharacteristics
;
147 ADDR3264 SizeOfStackReserve
;
148 ADDR3264 SizeOfStackCommit
;
149 ADDR3264 SizeOfHeapReserve
;
150 ADDR3264 SizeOfHeapCommit
;
152 DWORD NumberOfRvaAndSizes
;
153 IMAGE_DATA_DIRECTORY DataDirectory
[16];
154 } IMAGE_OPTIONAL_HEADER32
, IMAGE_OPTIONAL_HEADER64
, IMAGE_OPTIONAL_HEADER
;
156 #define IMAGE_DIRECTORY_ENTRY_EXPORT 0 /* Export Directory */
157 #define IMAGE_DIRECTORY_ENTRY_IMPORT 1 /* Import Directory */
158 #define IMAGE_DIRECTORY_ENTRY_RESOURCE 2 /* Resource Directory */
159 #define IMAGE_DIRECTORY_ENTRY_EXCEPTION 3 /* Exception Directory */
160 #define IMAGE_DIRECTORY_ENTRY_SECURITY 4 /* Security Directory */
161 #define IMAGE_DIRECTORY_ENTRY_BASERELOC 5 /* Base Relocation Table */
162 #define IMAGE_DIRECTORY_ENTRY_DEBUG 6 /* Debug Directory */
163 /* IMAGE_DIRECTORY_ENTRY_COPYRIGHT 7 (X86 usage) */
164 #define IMAGE_DIRECTORY_ENTRY_ARCHITECTURE 7 /* Architecture Specific Data */
165 #define IMAGE_DIRECTORY_ENTRY_GLOBALPTR 8 /* RVA of GP */
166 #define IMAGE_DIRECTORY_ENTRY_TLS 9 /* TLS Directory */
167 #define IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG 10 /* Load Configuration Directory */
168 #define IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT 11 /* Bound Import Directory in headers */
169 #define IMAGE_DIRECTORY_ENTRY_IAT 12 /* Import Address Table */
170 #define IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT 13 /* Delay Load Import Descriptors */
171 #define IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR 14 /* COM Runtime descriptor */
173 /* Section header format. */
174 #define IMAGE_SIZEOF_SHORT_NAME 8
176 typedef struct _IMAGE_SECTION_HEADER
{
177 BYTE Name
[IMAGE_SIZEOF_SHORT_NAME
];
179 DWORD PhysicalAddress
;
182 DWORD VirtualAddress
;
184 DWORD PointerToRawData
;
185 DWORD PointerToRelocations
;
186 DWORD PointerToLinenumbers
;
187 WORD NumberOfRelocations
;
188 WORD NumberOfLinenumbers
;
189 DWORD Characteristics
;
190 } IMAGE_SECTION_HEADER
, *PIMAGE_SECTION_HEADER
;
192 #define IMAGE_SIZEOF_SECTION_HEADER 40
194 typedef struct _IMAGE_EXPORT_DIRECTORY
{
195 DWORD Characteristics
;
201 DWORD NumberOfFunctions
;
203 DWORD AddressOfFunctions
;
204 DWORD AddressOfNames
;
205 DWORD AddressOfNameOrdinals
;
206 } IMAGE_EXPORT_DIRECTORY
,*PIMAGE_EXPORT_DIRECTORY
;
208 typedef struct _IMAGE_IMPORT_DESCRIPTOR
{
210 DWORD Characteristics
;
211 DWORD OriginalFirstThunk
;
214 DWORD ForwarderChain
;
217 } IMAGE_IMPORT_DESCRIPTOR
;
219 typedef struct _IMAGE_BASE_RELOCATION
{
220 DWORD VirtualAddress
;
222 // WORD TypeOffset[1];
223 } IMAGE_BASE_RELOCATION
;
225 #define IMAGE_SIZEOF_BASE_RELOCATION 8
227 #define IMAGE_REL_BASED_ABSOLUTE 0
228 #define IMAGE_REL_BASED_HIGH 1
229 #define IMAGE_REL_BASED_LOW 2
230 #define IMAGE_REL_BASED_HIGHLOW 3
231 #define IMAGE_REL_BASED_HIGHADJ 4
232 #define IMAGE_REL_BASED_MIPS_JMPADDR 5
233 #define IMAGE_REL_BASED_SECTION 6
234 #define IMAGE_REL_BASED_REL32 7
238 /* ----------------------------------------------------------- */
239 #endif /* ndef IMAGE_NT_SIGNATURE */
240 /* ----------------------------------------------------------- */
241 #pragma pack(push, 1)
245 IMAGE_DOS_HEADER doshdr
;
248 IMAGE_FILE_HEADER filehdr
;
249 #ifdef TCC_TARGET_X86_64
250 IMAGE_OPTIONAL_HEADER64 opthdr
;
253 IMAGE_OPTIONAL_HEADER32 opthdr
;
255 IMAGE_OPTIONAL_HEADER opthdr
;
260 struct pe_reloc_header
{
265 struct pe_rsrc_header
{
266 struct _IMAGE_FILE_HEADER filehdr
;
267 struct _IMAGE_SECTION_HEADER sectionhdr
;
270 struct pe_rsrc_reloc
{
278 /* ------------------------------------------------------------- */
279 /* internal temporary structures */
282 #define IMAGE_SCN_CNT_CODE 0x00000020
283 #define IMAGE_SCN_CNT_INITIALIZED_DATA 0x00000040
284 #define IMAGE_SCN_CNT_UNINITIALIZED_DATA 0x00000080
285 #define IMAGE_SCN_MEM_DISCARDABLE 0x02000000
286 #define IMAGE_SCN_MEM_SHARED 0x10000000
287 #define IMAGE_SCN_MEM_EXECUTE 0x20000000
288 #define IMAGE_SCN_MEM_READ 0x40000000
289 #define IMAGE_SCN_MEM_WRITE 0x80000000
304 ST_DATA
const DWORD pe_sec_flags
[] = {
305 0x60000020, /* ".text" , */
306 0xC0000040, /* ".data" , */
307 0xC0000080, /* ".bss" , */
308 0x40000040, /* ".idata" , */
309 0xE0000060, /* < other > , */
310 0x40000040, /* ".rsrc" , */
311 0x42000802, /* ".stab" , */
312 0x42000040, /* ".reloc" , */
315 struct section_info
{
323 IMAGE_SECTION_HEADER ish
;
326 struct import_symbol
{
332 struct pe_import_info
{
335 struct import_symbol
**symbols
;
342 const char *filename
;
356 struct section_info
*sec_info
;
358 struct pe_import_info
**imp_info
;
368 /* --------------------------------------------*/
370 ST_FN
const char* get_alt_symbol(char *buffer
, const char *symbol
)
373 p
= strrchr(symbol
, '@');
374 if (p
&& isnum(p
[1]) && symbol
[0] == '_') { /* stdcall decor */
375 strcpy(buffer
, symbol
+1)[p
-symbol
-1] = 0;
376 } else if (symbol
[0] != '_') { /* try non-ansi function */
377 buffer
[0] = '_', strcpy(buffer
+ 1, symbol
);
378 } else if (0 == memcmp(symbol
, "__imp__", 7)) { /* mingw 2.0 */
379 strcpy(buffer
, symbol
+ 6);
380 } else if (0 == memcmp(symbol
, "_imp___", 7)) { /* mingw 3.7 */
381 strcpy(buffer
, symbol
+ 6);
388 ST_FN
int pe_find_import(TCCState
* s1
, const char *symbol
)
392 int sym_index
, n
= 0;
394 s
= n
? get_alt_symbol(buffer
, symbol
) : symbol
;
395 sym_index
= find_elf_sym(s1
->dynsymtab_section
, s
);
396 // printf("find (%d) %d %s\n", n, sym_index, s);
397 } while (0 == sym_index
&& ++n
< 2);
401 /*----------------------------------------------------------------------------*/
403 ST_FN
int dynarray_assoc(void **pp
, int n
, int key
)
406 for (i
= 0; i
< n
; ++i
, ++pp
)
407 if (key
== **(int **) pp
)
413 ST_FN DWORD
umin(DWORD a
, DWORD b
)
415 return a
< b
? a
: b
;
419 ST_FN DWORD
umax(DWORD a
, DWORD b
)
421 return a
< b
? b
: a
;
424 ST_FN DWORD
pe_file_align(struct pe_info
*pe
, DWORD n
)
426 return (n
+ (pe
->file_align
- 1)) & ~(pe
->file_align
- 1);
429 ST_FN DWORD
pe_virtual_align(struct pe_info
*pe
, DWORD n
)
431 return (n
+ (pe
->section_align
- 1)) & ~(pe
->section_align
- 1);
434 ST_FN
void pe_align_section(Section
*s
, int a
)
436 int i
= s
->data_offset
& (a
-1);
438 section_ptr_add(s
, a
- i
);
441 ST_FN
void pe_set_datadir(struct pe_header
*hdr
, int dir
, DWORD addr
, DWORD size
)
443 hdr
->opthdr
.DataDirectory
[dir
].VirtualAddress
= addr
;
444 hdr
->opthdr
.DataDirectory
[dir
].Size
= size
;
447 ST_FN
int pe_fwrite(void *data
, unsigned len
, FILE *fp
, DWORD
*psum
)
453 for (i
= len
; i
> 0; i
-= 2) {
454 sum
+= (i
>= 2) ? *p
++ : *(BYTE
*)p
;
455 sum
= (sum
+ (sum
>> 16)) & 0xFFFF;
459 return len
== fwrite(data
, 1, len
, fp
) ? 0 : -1;
462 ST_FN
void pe_fpad(FILE *fp
, DWORD new_pos
)
464 DWORD pos
= ftell(fp
);
465 while (++pos
<= new_pos
)
469 /*----------------------------------------------------------------------------*/
470 ST_FN
int pe_write(struct pe_info
*pe
)
472 static const struct pe_header pe_template
= {
474 /* IMAGE_DOS_HEADER doshdr */
475 0x5A4D, /*WORD e_magic; Magic number */
476 0x0090, /*WORD e_cblp; Bytes on last page of file */
477 0x0003, /*WORD e_cp; Pages in file */
478 0x0000, /*WORD e_crlc; Relocations */
480 0x0004, /*WORD e_cparhdr; Size of header in paragraphs */
481 0x0000, /*WORD e_minalloc; Minimum extra paragraphs needed */
482 0xFFFF, /*WORD e_maxalloc; Maximum extra paragraphs needed */
483 0x0000, /*WORD e_ss; Initial (relative) SS value */
485 0x00B8, /*WORD e_sp; Initial SP value */
486 0x0000, /*WORD e_csum; Checksum */
487 0x0000, /*WORD e_ip; Initial IP value */
488 0x0000, /*WORD e_cs; Initial (relative) CS value */
489 0x0040, /*WORD e_lfarlc; File address of relocation table */
490 0x0000, /*WORD e_ovno; Overlay number */
491 {0,0,0,0}, /*WORD e_res[4]; Reserved words */
492 0x0000, /*WORD e_oemid; OEM identifier (for e_oeminfo) */
493 0x0000, /*WORD e_oeminfo; OEM information; e_oemid specific */
494 {0,0,0,0,0,0,0,0,0,0}, /*WORD e_res2[10]; Reserved words */
495 0x00000080 /*DWORD e_lfanew; File address of new exe header */
497 /* BYTE dosstub[0x40] */
498 /* 14 code bytes + "This program cannot be run in DOS mode.\r\r\n$" + 6 * 0x00 */
499 0x0e,0x1f,0xba,0x0e,0x00,0xb4,0x09,0xcd,0x21,0xb8,0x01,0x4c,0xcd,0x21,0x54,0x68,
500 0x69,0x73,0x20,0x70,0x72,0x6f,0x67,0x72,0x61,0x6d,0x20,0x63,0x61,0x6e,0x6e,0x6f,
501 0x74,0x20,0x62,0x65,0x20,0x72,0x75,0x6e,0x20,0x69,0x6e,0x20,0x44,0x4f,0x53,0x20,
502 0x6d,0x6f,0x64,0x65,0x2e,0x0d,0x0d,0x0a,0x24,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
504 0x00004550, /* DWORD nt_sig = IMAGE_NT_SIGNATURE */
506 /* IMAGE_FILE_HEADER filehdr */
507 #if defined(TCC_TARGET_I386)
508 0x014C, /*WORD Machine; */
509 #elif defined(TCC_TARGET_X86_64)
510 0x8664, /*WORD Machine; */
511 #elif defined(TCC_TARGET_ARM)
512 0x01C0, /*WORD Machine; */
514 0x0003, /*WORD NumberOfSections; */
515 0x00000000, /*DWORD TimeDateStamp; */
516 0x00000000, /*DWORD PointerToSymbolTable; */
517 0x00000000, /*DWORD NumberOfSymbols; */
518 #if defined(TCC_TARGET_X86_64)
519 0x00F0, /*WORD SizeOfOptionalHeader; */
520 0x022F /*WORD Characteristics; */
521 #define CHARACTERISTICS_DLL 0x222E
522 #elif defined(TCC_TARGET_I386)
523 0x00E0, /*WORD SizeOfOptionalHeader; */
524 0x030F /*WORD Characteristics; */
525 #define CHARACTERISTICS_DLL 0x230E
526 #elif defined(TCC_TARGET_ARM)
527 0x00E0, /*WORD SizeOfOptionalHeader; */
528 0x010F, /*WORD Characteristics; */
529 #define CHARACTERISTICS_DLL 0x230F
532 /* IMAGE_OPTIONAL_HEADER opthdr */
533 /* Standard fields. */
534 #ifdef TCC_TARGET_X86_64
535 0x020B, /*WORD Magic; */
537 0x010B, /*WORD Magic; */
539 0x06, /*BYTE MajorLinkerVersion; */
540 0x00, /*BYTE MinorLinkerVersion; */
541 0x00000000, /*DWORD SizeOfCode; */
542 0x00000000, /*DWORD SizeOfInitializedData; */
543 0x00000000, /*DWORD SizeOfUninitializedData; */
544 0x00000000, /*DWORD AddressOfEntryPoint; */
545 0x00000000, /*DWORD BaseOfCode; */
546 #ifndef TCC_TARGET_X86_64
547 0x00000000, /*DWORD BaseOfData; */
549 /* NT additional fields. */
550 #if defined(TCC_TARGET_ARM)
551 0x00100000, /*DWORD ImageBase; */
553 0x00400000, /*DWORD ImageBase; */
555 0x00001000, /*DWORD SectionAlignment; */
556 0x00000200, /*DWORD FileAlignment; */
557 0x0004, /*WORD MajorOperatingSystemVersion; */
558 0x0000, /*WORD MinorOperatingSystemVersion; */
559 0x0000, /*WORD MajorImageVersion; */
560 0x0000, /*WORD MinorImageVersion; */
561 0x0004, /*WORD MajorSubsystemVersion; */
562 0x0000, /*WORD MinorSubsystemVersion; */
563 0x00000000, /*DWORD Win32VersionValue; */
564 0x00000000, /*DWORD SizeOfImage; */
565 0x00000200, /*DWORD SizeOfHeaders; */
566 0x00000000, /*DWORD CheckSum; */
567 0x0002, /*WORD Subsystem; */
568 0x0000, /*WORD DllCharacteristics; */
569 0x00100000, /*DWORD SizeOfStackReserve; */
570 0x00001000, /*DWORD SizeOfStackCommit; */
571 0x00100000, /*DWORD SizeOfHeapReserve; */
572 0x00001000, /*DWORD SizeOfHeapCommit; */
573 0x00000000, /*DWORD LoaderFlags; */
574 0x00000010, /*DWORD NumberOfRvaAndSizes; */
576 /* IMAGE_DATA_DIRECTORY DataDirectory[16]; */
577 {{0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0},
578 {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}}
581 struct pe_header pe_header
= pe_template
;
585 DWORD file_offset
, sum
;
586 struct section_info
*si
;
587 IMAGE_SECTION_HEADER
*psh
;
589 op
= fopen(pe
->filename
, "wb");
591 error_noabort("could not write '%s': %s", pe
->filename
, strerror(errno
));
595 pe
->sizeofheaders
= pe_file_align(pe
,
596 sizeof (struct pe_header
)
597 + pe
->sec_count
* sizeof (IMAGE_SECTION_HEADER
)
600 file_offset
= pe
->sizeofheaders
;
602 if (2 == pe
->s1
->verbose
)
603 printf("-------------------------------"
604 "\n virt file size section" "\n");
605 for (i
= 0; i
< pe
->sec_count
; ++i
) {
606 unsigned long addr
, size
;
609 si
= pe
->sec_info
+ i
;
611 addr
= si
->sh_addr
- pe
->imagebase
;
615 if (2 == pe
->s1
->verbose
)
616 printf("%6lx %6lx %6lx %s\n",
617 addr
, file_offset
, size
, sh_name
);
621 pe_header
.opthdr
.BaseOfCode
= addr
;
622 pe_header
.opthdr
.AddressOfEntryPoint
= addr
+ pe
->start_addr
;
626 #ifndef TCC_TARGET_X86_64
627 pe_header
.opthdr
.BaseOfData
= addr
;
635 pe_set_datadir(&pe_header
, IMAGE_DIRECTORY_ENTRY_BASERELOC
, addr
, size
);
639 pe_set_datadir(&pe_header
, IMAGE_DIRECTORY_ENTRY_RESOURCE
, addr
, size
);
646 if (pe
->thunk
== pe
->s1
->sections
[si
->ord
]) {
648 pe_set_datadir(&pe_header
, IMAGE_DIRECTORY_ENTRY_IMPORT
,
649 pe
->imp_offs
+ addr
, pe
->imp_size
);
650 pe_set_datadir(&pe_header
, IMAGE_DIRECTORY_ENTRY_IAT
,
651 pe
->iat_offs
+ addr
, pe
->iat_size
);
654 pe_set_datadir(&pe_header
, IMAGE_DIRECTORY_ENTRY_EXPORT
,
655 pe
->exp_offs
+ addr
, pe
->exp_size
);
659 strcpy((char*)psh
->Name
, sh_name
);
661 psh
->Characteristics
= pe_sec_flags
[si
->cls
];
662 psh
->VirtualAddress
= addr
;
663 psh
->Misc
.VirtualSize
= size
;
664 pe_header
.opthdr
.SizeOfImage
=
665 umax(pe_virtual_align(pe
, size
+ addr
), pe_header
.opthdr
.SizeOfImage
);
668 psh
->PointerToRawData
= file_offset
;
669 file_offset
= pe_file_align(pe
, file_offset
+ si
->data_size
);
670 psh
->SizeOfRawData
= file_offset
- psh
->PointerToRawData
;
674 //pe_header.filehdr.TimeDateStamp = time(NULL);
675 pe_header
.filehdr
.NumberOfSections
= pe
->sec_count
;
676 pe_header
.opthdr
.SizeOfHeaders
= pe
->sizeofheaders
;
677 pe_header
.opthdr
.ImageBase
= pe
->imagebase
;
678 if (PE_DLL
== pe
->type
)
679 pe_header
.filehdr
.Characteristics
= CHARACTERISTICS_DLL
;
680 else if (PE_GUI
!= pe
->type
)
681 pe_header
.opthdr
.Subsystem
= 3;
684 pe_fwrite(&pe_header
, sizeof pe_header
, op
, &sum
);
685 for (i
= 0; i
< pe
->sec_count
; ++i
)
686 pe_fwrite(&pe
->sec_info
[i
].ish
, sizeof(IMAGE_SECTION_HEADER
), op
, &sum
);
687 pe_fpad(op
, pe
->sizeofheaders
);
688 for (i
= 0; i
< pe
->sec_count
; ++i
) {
689 si
= pe
->sec_info
+ i
;
692 pe_fwrite(si
->data
, si
->data_size
, op
, &sum
);
693 file_offset
= psh
->PointerToRawData
+ psh
->SizeOfRawData
;
694 pe_fpad(op
, file_offset
);
698 pe_header
.opthdr
.CheckSum
= sum
+ file_offset
;
699 fseek(op
, offsetof(struct pe_header
, opthdr
.CheckSum
), SEEK_SET
);
700 pe_fwrite(&pe_header
.opthdr
.CheckSum
, sizeof pe_header
.opthdr
.CheckSum
, op
, NULL
);
703 if (2 == pe
->s1
->verbose
)
704 printf("-------------------------------\n");
706 printf("<- %s (%lu bytes)\n", pe
->filename
, file_offset
);
711 /*----------------------------------------------------------------------------*/
713 #if defined(TCC_TARGET_X86_64)
714 #define ELFW_R_(type) ELF64_R_##type
715 #define ElfW_Rel ElfW(Rela)
717 #define REL_TYPE_DIRECT R_X86_64_64
718 #define R_XXX_THUNKFIX R_X86_64_PC32
719 #define R_XXX_RELATIVE R_X86_64_RELATIVE
721 #define ELFW_ST_BIND ELF64_ST_BIND
722 #define ELFW_ST_TYPE ELF64_ST_TYPE
723 #define ELFW_ST_INFO ELF64_ST_INFO
724 #elif defined(TCC_TARGET_I386)
725 #define ELFW_R_(type) ELF32_R_##type
726 #define ElfW_Rel ElfW(Rel)
728 #define REL_TYPE_DIRECT R_386_32
729 #define R_XXX_THUNKFIX R_386_32
730 #define R_XXX_RELATIVE R_386_RELATIVE
732 #define ELFW_ST_BIND ELF32_ST_BIND
733 #define ELFW_ST_TYPE ELF32_ST_TYPE
734 #define ELFW_ST_INFO ELF32_ST_INFO
735 #elif defined(TCC_TARGET_ARM)
736 #define ELFW_R_(type) ELF32_R_##type
737 #define ElfW_Rel ElfW(Rel)
739 #define REL_TYPE_DIRECT R_ARM_ABS32
740 #define R_XXX_THUNKFIX R_ARM_ABS32
741 #define R_XXX_RELATIVE R_ARM_RELATIVE
743 #define ELFW_ST_BIND ELF32_ST_BIND
744 #define ELFW_ST_TYPE ELF32_ST_TYPE
745 #define ELFW_ST_INFO ELF32_ST_INFO
747 /*----------------------------------------------------------------------------*/
749 ST_FN
struct import_symbol
*pe_add_import(struct pe_info
*pe
, int sym_index
)
753 struct pe_import_info
*p
;
754 struct import_symbol
*s
;
756 dll_index
= ((ElfW(Sym
) *)pe
->s1
->dynsymtab_section
->data
+ sym_index
)->st_value
;
760 i
= dynarray_assoc ((void**)pe
->imp_info
, pe
->imp_count
, dll_index
);
765 p
= tcc_mallocz(sizeof *p
);
766 p
->dll_index
= dll_index
;
767 dynarray_add((void***)&pe
->imp_info
, &pe
->imp_count
, p
);
770 i
= dynarray_assoc ((void**)p
->symbols
, p
->sym_count
, sym_index
);
772 return p
->symbols
[i
];
774 s
= tcc_mallocz(sizeof *s
);
775 dynarray_add((void***)&p
->symbols
, &p
->sym_count
, s
);
776 s
->sym_index
= sym_index
;
780 /*----------------------------------------------------------------------------*/
781 ST_FN
void pe_build_imports(struct pe_info
*pe
)
783 int thk_ptr
, ent_ptr
, dll_ptr
, sym_cnt
, i
;
784 DWORD rva_base
= pe
->thunk
->sh_addr
- pe
->imagebase
;
785 int ndlls
= pe
->imp_count
;
787 for (sym_cnt
= i
= 0; i
< ndlls
; ++i
)
788 sym_cnt
+= pe
->imp_info
[i
]->sym_count
;
793 pe_align_section(pe
->thunk
, 16);
795 pe
->imp_offs
= dll_ptr
= pe
->thunk
->data_offset
;
796 pe
->imp_size
= (ndlls
+ 1) * sizeof(IMAGE_IMPORT_DESCRIPTOR
);
797 pe
->iat_offs
= dll_ptr
+ pe
->imp_size
;
798 pe
->iat_size
= (sym_cnt
+ ndlls
) * sizeof(ADDR3264
);
799 section_ptr_add(pe
->thunk
, pe
->imp_size
+ 2*pe
->iat_size
);
801 thk_ptr
= pe
->iat_offs
;
802 ent_ptr
= pe
->iat_offs
+ pe
->iat_size
;
804 for (i
= 0; i
< pe
->imp_count
; ++i
) {
805 IMAGE_IMPORT_DESCRIPTOR
*hdr
;
808 struct pe_import_info
*p
= pe
->imp_info
[i
];
809 const char *name
= pe
->s1
->loaded_dlls
[p
->dll_index
-1]->name
;
811 /* put the dll name into the import header */
812 v
= put_elf_str(pe
->thunk
, name
);
814 hdr
= (IMAGE_IMPORT_DESCRIPTOR
*)(pe
->thunk
->data
+ dll_ptr
);
815 hdr
->FirstThunk
= thk_ptr
+ rva_base
;
816 hdr
->OriginalFirstThunk
= ent_ptr
+ rva_base
;
817 hdr
->Name
= v
+ rva_base
;
819 for (k
= 0, n
= p
->sym_count
; k
<= n
; ++k
) {
821 int iat_index
= p
->symbols
[k
]->iat_index
;
822 int sym_index
= p
->symbols
[k
]->sym_index
;
823 ElfW(Sym
) *imp_sym
= (ElfW(Sym
) *)pe
->s1
->dynsymtab_section
->data
+ sym_index
;
824 ElfW(Sym
) *org_sym
= (ElfW(Sym
) *)symtab_section
->data
+ iat_index
;
825 const char *name
= pe
->s1
->dynsymtab_section
->link
->data
+ imp_sym
->st_name
;
827 org_sym
->st_value
= thk_ptr
;
828 org_sym
->st_shndx
= pe
->thunk
->sh_num
;
829 v
= pe
->thunk
->data_offset
+ rva_base
;
830 section_ptr_add(pe
->thunk
, sizeof(WORD
)); /* hint, not used */
831 put_elf_str(pe
->thunk
, name
);
833 if (pe
->type
== PE_RUN
) {
834 DLLReference
*dllref
= pe
->s1
->loaded_dlls
[imp_sym
->st_value
-1];
835 if ( !dllref
->handle
)
836 dllref
->handle
= LoadLibrary(dllref
->name
);
837 v
= (ADDR3264
)GetProcAddress(dllref
->handle
, name
);
839 error_noabort("undefined symbol '%s'", name
);
843 v
= 0; /* last entry is zero */
845 *(ADDR3264
*)(pe
->thunk
->data
+thk_ptr
) =
846 *(ADDR3264
*)(pe
->thunk
->data
+ent_ptr
) = v
;
847 thk_ptr
+= sizeof (ADDR3264
);
848 ent_ptr
+= sizeof (ADDR3264
);
850 dll_ptr
+= sizeof(IMAGE_IMPORT_DESCRIPTOR
);
851 dynarray_reset(&p
->symbols
, &p
->sym_count
);
853 dynarray_reset(&pe
->imp_info
, &pe
->imp_count
);
856 /* ------------------------------------------------------------- */
858 For now only functions are exported. Export of data
859 would work, but import requires compiler support to
860 do an additional indirection.
863 __declspec(dllimport) extern int something;
865 needs to be translated to:
876 ST_FN
int sym_cmp(const void *va
, const void *vb
)
878 const char *ca
= (*(struct pe_sort_sym
**)va
)->name
;
879 const char *cb
= (*(struct pe_sort_sym
**)vb
)->name
;
880 return strcmp(ca
, cb
);
883 ST_FN
void pe_build_exports(struct pe_info
*pe
)
886 int sym_index
, sym_end
;
887 DWORD rva_base
, func_o
, name_o
, ord_o
, str_o
;
888 IMAGE_EXPORT_DIRECTORY
*hdr
;
890 struct pe_sort_sym
**sorted
, *p
;
897 rva_base
= pe
->thunk
->sh_addr
- pe
->imagebase
;
898 sym_count
= 0, sorted
= NULL
, op
= NULL
;
900 sym_end
= symtab_section
->data_offset
/ sizeof(ElfW(Sym
));
901 for (sym_index
= 1; sym_index
< sym_end
; ++sym_index
) {
902 sym
= (ElfW(Sym
)*)symtab_section
->data
+ sym_index
;
903 name
= symtab_section
->link
->data
+ sym
->st_name
;
904 if ((sym
->st_other
& 1)
905 /* export only symbols from actually written sections */
906 && pe
->s1
->sections
[sym
->st_shndx
]->sh_addr
) {
907 p
= tcc_malloc(sizeof *p
);
908 p
->index
= sym_index
;
910 dynarray_add((void***)&sorted
, &sym_count
, p
);
913 if (sym
->st_other
& 1)
914 printf("export: %s\n", name
);
915 if (sym
->st_other
& 2)
916 printf("stdcall: %s\n", name
);
923 qsort (sorted
, sym_count
, sizeof *sorted
, sym_cmp
);
925 pe_align_section(pe
->thunk
, 16);
926 dllname
= tcc_basename(pe
->filename
);
928 pe
->exp_offs
= pe
->thunk
->data_offset
;
929 func_o
= pe
->exp_offs
+ sizeof(IMAGE_EXPORT_DIRECTORY
);
930 name_o
= func_o
+ sym_count
* sizeof (DWORD
);
931 ord_o
= name_o
+ sym_count
* sizeof (DWORD
);
932 str_o
= ord_o
+ sym_count
* sizeof(WORD
);
934 hdr
= section_ptr_add(pe
->thunk
, str_o
- pe
->exp_offs
);
935 hdr
->Characteristics
= 0;
937 hdr
->NumberOfFunctions
= sym_count
;
938 hdr
->NumberOfNames
= sym_count
;
939 hdr
->AddressOfFunctions
= func_o
+ rva_base
;
940 hdr
->AddressOfNames
= name_o
+ rva_base
;
941 hdr
->AddressOfNameOrdinals
= ord_o
+ rva_base
;
942 hdr
->Name
= str_o
+ rva_base
;
943 put_elf_str(pe
->thunk
, dllname
);
946 /* automatically write exports to <output-filename>.def */
947 strcpy(buf
, pe
->filename
);
948 strcpy(tcc_fileextension(buf
), ".def");
949 op
= fopen(buf
, "w");
951 error_noabort("could not create '%s': %s", buf
, strerror(errno
));
953 fprintf(op
, "LIBRARY %s\n\nEXPORTS\n", dllname
);
955 printf("<- %s (%d symbols)\n", buf
, sym_count
);
959 for (ord
= 0; ord
< sym_count
; ++ord
)
961 p
= sorted
[ord
], sym_index
= p
->index
, name
= p
->name
;
962 /* insert actual address later in pe_relocate_rva */
963 put_elf_reloc(symtab_section
, pe
->thunk
,
964 func_o
, R_XXX_RELATIVE
, sym_index
);
965 *(DWORD
*)(pe
->thunk
->data
+ name_o
)
966 = pe
->thunk
->data_offset
+ rva_base
;
967 *(WORD
*)(pe
->thunk
->data
+ ord_o
)
969 put_elf_str(pe
->thunk
, name
);
970 func_o
+= sizeof (DWORD
);
971 name_o
+= sizeof (DWORD
);
972 ord_o
+= sizeof (WORD
);
974 fprintf(op
, "%s\n", name
);
976 pe
->exp_size
= pe
->thunk
->data_offset
- pe
->exp_offs
;
977 dynarray_reset(&sorted
, &sym_count
);
982 /* ------------------------------------------------------------- */
983 ST_FN
void pe_build_reloc (struct pe_info
*pe
)
985 DWORD offset
, block_ptr
, addr
;
987 ElfW_Rel
*rel
, *rel_end
;
988 Section
*s
= NULL
, *sr
;
990 offset
= addr
= block_ptr
= count
= i
= 0;
991 rel
= rel_end
= NULL
;
995 int type
= ELFW_R_(TYPE
)(rel
->r_info
);
996 addr
= rel
->r_offset
+ s
->sh_addr
;
998 if (type
!= REL_TYPE_DIRECT
)
1000 if (count
== 0) { /* new block */
1001 block_ptr
= pe
->reloc
->data_offset
;
1002 section_ptr_add(pe
->reloc
, sizeof(struct pe_reloc_header
));
1003 offset
= addr
& 0xFFFFFFFF<<12;
1005 if ((addr
-= offset
) < (1<<12)) { /* one block spans 4k addresses */
1006 WORD
*wp
= section_ptr_add(pe
->reloc
, sizeof (WORD
));
1007 *wp
= addr
| IMAGE_REL_BASED_HIGHLOW
<<12;
1013 } else if (i
< pe
->sec_count
) {
1014 sr
= (s
= pe
->s1
->sections
[pe
->sec_info
[i
++].ord
])->reloc
;
1016 rel
= (ElfW_Rel
*)sr
->data
;
1017 rel_end
= (ElfW_Rel
*)(sr
->data
+ sr
->data_offset
);
1023 /* store the last block and ready for a new one */
1024 struct pe_reloc_header
*hdr
;
1025 if (count
& 1) /* align for DWORDS */
1026 section_ptr_add(pe
->reloc
, sizeof(WORD
)), ++count
;
1027 hdr
= (struct pe_reloc_header
*)(pe
->reloc
->data
+ block_ptr
);
1028 hdr
-> offset
= offset
- pe
->imagebase
;
1029 hdr
-> size
= count
* sizeof(WORD
) + sizeof(struct pe_reloc_header
);
1038 /* ------------------------------------------------------------- */
1039 ST_FN
int pe_section_class(Section
*s
)
1045 flags
= s
->sh_flags
;
1047 if (flags
& SHF_ALLOC
) {
1048 if (type
== SHT_PROGBITS
) {
1049 if (flags
& SHF_EXECINSTR
)
1051 if (flags
& SHF_WRITE
)
1053 if (0 == strcmp(name
, ".rsrc"))
1055 if (0 == strcmp(name
, ".iedat"))
1058 } else if (type
== SHT_NOBITS
) {
1059 if (flags
& SHF_WRITE
)
1063 if (0 == strcmp(name
, ".reloc"))
1065 if (0 == strncmp(name
, ".stab", 5)) /* .stab and .stabstr */
1071 ST_FN
int pe_assign_addresses (struct pe_info
*pe
)
1076 struct section_info
*si
;
1079 // pe->thunk = new_section(pe->s1, ".iedat", SHT_PROGBITS, SHF_ALLOC);
1081 section_order
= tcc_malloc(pe
->s1
->nb_sections
* sizeof (int));
1082 for (o
= k
= 0 ; k
< sec_last
; ++k
) {
1083 for (i
= 1; i
< pe
->s1
->nb_sections
; ++i
) {
1084 s
= pe
->s1
->sections
[i
];
1085 if (k
== pe_section_class(s
)) {
1086 // printf("%s %d\n", s->name, k);
1087 s
->sh_addr
= pe
->imagebase
;
1088 section_order
[o
++] = i
;
1093 pe
->sec_info
= tcc_mallocz(o
* sizeof (struct section_info
));
1094 addr
= pe
->imagebase
+ 1;
1096 for (i
= 0; i
< o
; ++i
)
1098 k
= section_order
[i
];
1099 s
= pe
->s1
->sections
[k
];
1100 c
= pe_section_class(s
);
1101 si
= &pe
->sec_info
[pe
->sec_count
];
1103 #ifdef PE_MERGE_DATA
1104 if (c
== sec_bss
&& pe
->sec_count
&& si
[-1].cls
== sec_data
) {
1105 /* append .bss to .data */
1106 s
->sh_addr
= addr
= ((addr
-1) | 15) + 1;
1107 addr
+= s
->data_offset
;
1108 si
[-1].sh_size
= addr
- si
[-1].sh_addr
;
1112 strcpy(si
->name
, s
->name
);
1115 si
->sh_addr
= s
->sh_addr
= addr
= pe_virtual_align(pe
, addr
);
1116 si
->sh_flags
= s
->sh_flags
;
1118 if (c
== sec_data
&& NULL
== pe
->thunk
)
1121 if (s
== pe
->thunk
) {
1122 pe_build_imports(pe
);
1123 pe_build_exports(pe
);
1127 pe_build_reloc (pe
);
1131 if (s
->sh_type
!= SHT_NOBITS
) {
1133 si
->data_size
= s
->data_offset
;
1136 addr
+= s
->data_offset
;
1137 si
->sh_size
= s
->data_offset
;
1140 // printf("%08x %05x %s\n", si->sh_addr, si->sh_size, si->name);
1144 for (i
= 1; i
< pe
->s1
->nb_sections
; ++i
) {
1145 Section
*s
= pe
->s1
->sections
[i
];
1146 int type
= s
->sh_type
;
1147 int flags
= s
->sh_flags
;
1148 printf("section %-16s %-10s %5x %s,%s,%s\n",
1150 type
== SHT_PROGBITS
? "progbits" :
1151 type
== SHT_NOBITS
? "nobits" :
1152 type
== SHT_SYMTAB
? "symtab" :
1153 type
== SHT_STRTAB
? "strtab" :
1154 type
== SHT_RELX
? "rel" : "???",
1156 flags
& SHF_ALLOC
? "alloc" : "",
1157 flags
& SHF_WRITE
? "write" : "",
1158 flags
& SHF_EXECINSTR
? "exec" : ""
1161 pe
->s1
->verbose
= 2;
1164 tcc_free(section_order
);
1168 /* ------------------------------------------------------------- */
1169 ST_FN
void pe_relocate_rva (struct pe_info
*pe
, Section
*s
)
1171 Section
*sr
= s
->reloc
;
1172 ElfW_Rel
*rel
, *rel_end
;
1173 rel_end
= (ElfW_Rel
*)(sr
->data
+ sr
->data_offset
);
1174 for(rel
= (ElfW_Rel
*)sr
->data
; rel
< rel_end
; rel
++) {
1175 if (ELFW_R_(TYPE
)(rel
->r_info
) == R_XXX_RELATIVE
) {
1176 int sym_index
= ELFW_R_(SYM
)(rel
->r_info
);
1177 DWORD addr
= s
->sh_addr
;
1179 ElfW(Sym
) *sym
= (ElfW(Sym
) *)symtab_section
->data
+ sym_index
;
1180 addr
= sym
->st_value
;
1182 // printf("reloc rva %08x %08x\n", (DWORD)rel->r_offset, addr);
1183 *(DWORD
*)(s
->data
+ rel
->r_offset
) += addr
- pe
->imagebase
;
1188 /*----------------------------------------------------------------------------*/
1189 ST_FN
int pe_check_symbols(struct pe_info
*pe
)
1192 int sym_index
, sym_end
;
1195 pe_align_section(text_section
, 8);
1197 sym_end
= symtab_section
->data_offset
/ sizeof(ElfW(Sym
));
1198 for (sym_index
= 1; sym_index
< sym_end
; ++sym_index
) {
1200 sym
= (ElfW(Sym
) *)symtab_section
->data
+ sym_index
;
1201 if (sym
->st_shndx
== SHN_UNDEF
) {
1203 const char *name
= symtab_section
->link
->data
+ sym
->st_name
;
1204 unsigned type
= ELFW_ST_TYPE(sym
->st_info
);
1205 int imp_sym
= pe_find_import(pe
->s1
, name
);
1206 struct import_symbol
*is
;
1210 is
= pe_add_import(pe
, imp_sym
);
1214 if (type
== STT_FUNC
) {
1215 unsigned long offset
= is
->thk_offset
;
1217 /* got aliased symbol, like stricmp and _stricmp */
1223 offset
= text_section
->data_offset
;
1224 /* add the 'jmp IAT[x]' instruction */
1225 p
= section_ptr_add(text_section
, 8);
1227 #ifdef TCC_TARGET_X86_64
1228 *(DWORD
*)(p
+1) = (DWORD
)-4;
1230 /* add a helper symbol, will be patched later in
1232 sprintf(buffer
, "IAT.%s", name
);
1233 is
->iat_index
= put_elf_sym(
1234 symtab_section
, 0, sizeof(DWORD
),
1235 ELFW_ST_INFO(STB_GLOBAL
, STT_OBJECT
),
1236 0, SHN_UNDEF
, buffer
);
1237 put_elf_reloc(symtab_section
, text_section
,
1238 offset
+ 2, R_XXX_THUNKFIX
, is
->iat_index
);
1239 is
->thk_offset
= offset
;
1242 /* tcc_realloc might have altered sym's address */
1243 sym
= (ElfW(Sym
) *)symtab_section
->data
+ sym_index
;
1245 /* patch the original symbol */
1246 sym
->st_value
= offset
;
1247 sym
->st_shndx
= text_section
->sh_num
;
1248 sym
->st_other
&= ~1; /* do not export */
1252 if (type
== STT_OBJECT
) { /* data, ptr to that should be */
1253 if (0 == is
->iat_index
) {
1254 /* original symbol will be patched later in pe_build_imports */
1255 is
->iat_index
= sym_index
;
1261 error_noabort("undefined symbol '%s'", name
);
1264 } else if (pe
->s1
->rdynamic
1265 && ELFW_ST_BIND(sym
->st_info
) != STB_LOCAL
) {
1266 /* if -rdynamic option, then export all non local symbols */
1273 /*----------------------------------------------------------------------------*/
1274 #ifdef PE_PRINT_SECTIONS
1275 ST_FN
void pe_print_section(FILE * f
, Section
* s
)
1277 /* just if you'r curious */
1281 e
= s
->data
+ s
->data_offset
;
1284 fprintf(f
, "section \"%s\"", s
->name
);
1286 fprintf(f
, "\nlink \"%s\"", s
->link
->name
);
1288 fprintf(f
, "\nreloc \"%s\"", s
->reloc
->name
);
1289 fprintf(f
, "\nv_addr %08X", (unsigned)s
->sh_addr
);
1290 fprintf(f
, "\ncontents %08X", (unsigned)l
);
1293 if (s
->sh_type
== SHT_NOBITS
)
1299 if (s
->sh_type
== SHT_SYMTAB
)
1300 m
= sizeof(ElfW(Sym
));
1301 else if (s
->sh_type
== SHT_RELX
)
1302 m
= sizeof(ElfW_Rel
);
1306 fprintf(f
, "%-8s", "offset");
1307 for (i
= 0; i
< m
; ++i
)
1308 fprintf(f
, " %02x", i
);
1311 if (s
->sh_type
== SHT_SYMTAB
|| s
->sh_type
== SHT_RELX
) {
1312 const char *fields1
[] = {
1323 const char *fields2
[] = {
1332 if (s
->sh_type
== SHT_SYMTAB
)
1333 p
= fields1
, n
= 106;
1335 p
= fields2
, n
= 58;
1337 for (i
= 0; p
[i
]; ++i
)
1338 fprintf(f
, "%6s", p
[i
]);
1339 fprintf(f
, " symbol");
1343 for (i
= 0; i
< n
; ++i
)
1349 fprintf(f
, "%08X", i
);
1350 for (n
= 0; n
< m
; ++n
) {
1352 fprintf(f
, " %02X", p
[i
+ n
]);
1357 if (s
->sh_type
== SHT_SYMTAB
) {
1358 ElfW(Sym
) *sym
= (ElfW(Sym
) *) (p
+ i
);
1359 const char *name
= s
->link
->data
+ sym
->st_name
;
1360 fprintf(f
, " %04X %04X %04X %02X %02X %02X %04X \"%s\"",
1361 (unsigned)sym
->st_name
,
1362 (unsigned)sym
->st_value
,
1363 (unsigned)sym
->st_size
,
1364 (unsigned)ELFW_ST_BIND(sym
->st_info
),
1365 (unsigned)ELFW_ST_TYPE(sym
->st_info
),
1366 (unsigned)sym
->st_other
,
1367 (unsigned)sym
->st_shndx
,
1370 } else if (s
->sh_type
== SHT_RELX
) {
1371 ElfW_Rel
*rel
= (ElfW_Rel
*) (p
+ i
);
1373 (ElfW(Sym
) *) s
->link
->data
+ ELFW_R_(SYM
)(rel
->r_info
);
1374 const char *name
= s
->link
->link
->data
+ sym
->st_name
;
1375 fprintf(f
, " %04X %02X %04X \"%s\"",
1376 (unsigned)rel
->r_offset
,
1377 (unsigned)ELFW_R_(TYPE
)(rel
->r_info
),
1378 (unsigned)ELFW_R_(SYM
)(rel
->r_info
),
1382 for (n
= 0; n
< m
; ++n
) {
1385 if (b
< 32 || b
>= 127)
1387 fprintf(f
, "%c", b
);
1397 ST_FN
void pe_print_sections(TCCState
*s1
, const char *fname
)
1402 f
= fopen(fname
, "w");
1403 for (i
= 1; i
< s1
->nb_sections
; ++i
) {
1404 s
= s1
->sections
[i
];
1405 pe_print_section(f
, s
);
1407 pe_print_section(f
, s1
->dynsymtab_section
);
1412 /* ------------------------------------------------------------- */
1414 ST_FN
int read_mem(FILE *fp
, unsigned offset
, void *buffer
, unsigned len
)
1416 fseek(fp
, offset
, 0);
1417 return len
== fread(buffer
, 1, len
, fp
);
1420 /* -------------------------------------------------------------
1421 * This is for compiled windows resources in 'coff' format
1422 * as generated by 'windres.exe -O coff ...'.
1425 ST_FN
int pe_load_res(TCCState
*s1
, FILE *fp
)
1427 struct pe_rsrc_header hdr
;
1428 Section
*rsrc_section
;
1433 if (!read_mem(fp
, 0, &hdr
, sizeof hdr
))
1436 if (hdr
.filehdr
.Machine
!= 0x014C
1437 || hdr
.filehdr
.NumberOfSections
!= 1
1438 || strcmp(hdr
.sectionhdr
.Name
, ".rsrc") != 0)
1441 rsrc_section
= new_section(s1
, ".rsrc", SHT_PROGBITS
, SHF_ALLOC
);
1442 ptr
= section_ptr_add(rsrc_section
, hdr
.sectionhdr
.SizeOfRawData
);
1443 offs
= hdr
.sectionhdr
.PointerToRawData
;
1444 if (!read_mem(fp
, offs
, ptr
, hdr
.sectionhdr
.SizeOfRawData
))
1446 offs
= hdr
.sectionhdr
.PointerToRelocations
;
1447 for (i
= 0; i
< hdr
.sectionhdr
.NumberOfRelocations
; ++i
)
1449 struct pe_rsrc_reloc rel
;
1450 if (!read_mem(fp
, offs
, &rel
, sizeof rel
))
1452 // printf("rsrc_reloc: %x %x %x\n", rel.offset, rel.size, rel.type);
1453 if (rel
.type
!= 7) /* DIR32NB */
1455 put_elf_reloc(symtab_section
, rsrc_section
,
1456 rel
.offset
, R_XXX_RELATIVE
, 0);
1464 /* ------------------------------------------------------------- */
1465 ST_FN
char *trimfront(char *p
)
1467 while (*p
&& (unsigned char)*p
<= ' ')
1472 ST_FN
char *trimback(char *a
, char *e
)
1474 while (e
> a
&& (unsigned char)e
[-1] <= ' ')
1480 ST_FN
char *get_line(char *line
, int size
, FILE *fp
)
1482 if (NULL
== fgets(line
, size
, fp
))
1484 trimback(line
, strchr(line
, 0));
1485 return trimfront(line
);
1488 /* ------------------------------------------------------------- */
1489 ST_FN
int pe_load_def(TCCState
*s1
, FILE *fp
)
1491 DLLReference
*dllref
;
1492 int state
= 0, ret
= -1;
1493 char line
[400], dllname
[80], *p
;
1496 p
= get_line(line
, sizeof line
, fp
);
1499 if (0 == *p
|| ';' == *p
)
1503 if (0 != strnicmp(p
, "LIBRARY", 7))
1505 strcpy(dllname
, trimfront(p
+7));
1510 if (0 != stricmp(p
, "EXPORTS"))
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
);
1522 add_elf_sym(s1
->dynsymtab_section
,
1523 s1
->nb_loaded_dlls
, 0,
1524 ELFW_ST_INFO(STB_GLOBAL
, STT_FUNC
), 0,
1525 text_section
->sh_num
, p
);
1534 /* ------------------------------------------------------------- */
1535 #define TINY_IMPDEF_GET_EXPORT_NAMES_ONLY
1536 #include "win32/tools/tiny_impdef.c"
1538 ST_FN
int pe_load_dll(TCCState
*s1
, const char *dllname
, FILE *fp
)
1542 p
= get_export_names(fp
);
1544 DLLReference
*dllref
;
1545 dllref
= tcc_mallocz(sizeof(DLLReference
) + strlen(dllname
));
1546 strcpy(dllref
->name
, dllname
);
1547 dynarray_add((void ***) &s1
->loaded_dlls
, &s1
->nb_loaded_dlls
, dllref
);
1548 for (q
= p
, i
= 0; *q
; ++i
) {
1549 add_elf_sym(s1
->dynsymtab_section
,
1550 s1
->nb_loaded_dlls
, 0,
1551 ELFW_ST_INFO(STB_GLOBAL
, STT_FUNC
), 0,
1552 text_section
->sh_num
, q
);
1560 /* ------------------------------------------------------------- */
1561 PUB_FN
int pe_load_file(struct TCCState
*s1
, const char *filename
, int fd
)
1563 FILE *fp
= fdopen(dup(fd
), "rb");
1567 if (0 == strcmp(tcc_fileextension(filename
), ".def"))
1568 ret
= pe_load_def(s1
, fp
);
1569 else if (pe_load_res(s1
, fp
) == 0)
1571 else if (read_mem(fp
, 0, buf
, sizeof buf
) && 0 == strncmp(buf
, "MZ", 2))
1572 ret
= pe_load_dll(s1
, tcc_basename(filename
), fp
);
1578 int pe_add_dll(struct TCCState
*s
, const char *libraryname
)
1581 snprintf(buf
, sizeof(buf
), "%s.def", libraryname
);
1582 if (tcc_add_dll(s
, buf
, 0) == 0)
1584 snprintf(buf
, sizeof(buf
), "%s.dll", libraryname
);
1585 if (tcc_add_dll(s
, buf
, 0) == 0)
1590 /* ------------------------------------------------------------- */
1591 #ifdef TCC_TARGET_X86_64
1592 #define PE_STDSYM(n,s) n
1594 #define PE_STDSYM(n,s) "_" n s
1597 ST_FN
void pe_add_runtime_ex(TCCState
*s1
, struct pe_info
*pe
)
1599 const char *start_symbol
;
1600 unsigned long addr
= 0;
1603 if (find_elf_sym(symtab_section
, PE_STDSYM("WinMain","@16")))
1606 if (TCC_OUTPUT_DLL
== s1
->output_type
) {
1608 /* need this for 'tccelf.c:relocate_section()' */
1609 s1
->output_type
= TCC_OUTPUT_EXE
;
1613 TCC_OUTPUT_MEMORY
== s1
->output_type
1614 ? PE_GUI
== pe_type
? "_runwinmain" : NULL
1615 : PE_DLL
== pe_type
? PE_STDSYM("_dllstart","@12")
1616 : PE_GUI
== pe_type
? "_winstart" : "_start"
1619 /* grab the startup code from libtcc1 */
1621 add_elf_sym(symtab_section
,
1623 ELFW_ST_INFO(STB_GLOBAL
, STT_NOTYPE
), 0,
1624 SHN_UNDEF
, start_symbol
);
1626 if (0 == s1
->nostdlib
) {
1627 static const char *libs
[] = {
1628 "tcc1", "msvcrt", "kernel32", "", "user32", "gdi32", NULL
1630 const char **pp
, *p
;
1631 for (pp
= libs
; 0 != (p
= *pp
); ++pp
) {
1633 if (PE_DLL
!= pe_type
&& PE_GUI
!= pe_type
)
1635 } else if (tcc_add_library(s1
, p
) < 0)
1636 error_noabort("cannot find library: %s", p
);
1641 addr
= (uplong
)tcc_get_symbol_err(s1
, start_symbol
);
1642 if (s1
->output_type
== TCC_OUTPUT_MEMORY
&& addr
)
1643 /* for -run GUI's, put '_runwinmain' instead of 'main' */
1644 add_elf_sym(symtab_section
,
1646 ELFW_ST_INFO(STB_GLOBAL
, STT_NOTYPE
), 0,
1647 text_section
->sh_num
, "main");
1651 pe
->start_addr
= addr
;
1654 PUB_FN
int pe_output_file(TCCState
* s1
, const char *filename
)
1660 memset(&pe
, 0, sizeof pe
);
1661 pe
.filename
= filename
;
1664 pe_add_runtime_ex(s1
, &pe
);
1665 relocate_common_syms(); /* assign bss adresses */
1666 tcc_add_linker_symbols(s1
);
1668 ret
= pe_check_symbols(&pe
);
1673 if (PE_DLL
== pe
.type
) {
1674 pe
.reloc
= new_section(pe
.s1
, ".reloc", SHT_PROGBITS
, 0);
1675 /* XXX: check if is correct for arm-pe target */
1676 pe
.imagebase
= 0x10000000;
1678 #if defined(TCC_TARGET_ARM)
1679 pe
.imagebase
= 0x00010000;
1681 pe
.imagebase
= 0x00400000;
1685 /* if no subsystem specified, we use "console" subsystem by default */
1686 if (s1
->pe_subsystem
!= 0)
1687 pe
.subsystem
= s1
->pe_subsystem
;
1689 #if defined(TCC_TARGET_ARM)
1694 /* set default file/section alignment */
1695 if (pe
.subsystem
== 1) {
1696 pe
.section_align
= 0x20;
1697 pe
.file_align
= 0x20;
1699 pe
.section_align
= 0x1000;
1700 pe
.file_align
= 0x200;
1703 if (s1
->section_align
!= 0)
1704 pe
.section_align
= s1
->section_align
;
1705 if (s1
->pe_file_align
!= 0)
1706 pe
.file_align
= s1
->pe_file_align
;
1708 if ((pe
.subsystem
>= 10) && (pe
.subsystem
<= 12))
1711 if (s1
->has_text_addr
)
1712 pe
.imagebase
= s1
->text_addr
;
1714 pe_assign_addresses(&pe
);
1715 relocate_syms(s1
, 0);
1716 for (i
= 1; i
< s1
->nb_sections
; ++i
) {
1717 Section
*s
= s1
->sections
[i
];
1719 relocate_section(s1
, s
);
1720 pe_relocate_rva(&pe
, s
);
1726 ret
= pe_write(&pe
);
1727 tcc_free(pe
.sec_info
);
1729 #ifndef TCC_IS_NATIVE
1730 error_noabort("-run supported only on native platform");
1733 pe
.thunk
= data_section
;
1734 pe_build_imports(&pe
);
1737 #ifdef PE_PRINT_SECTIONS
1738 pe_print_sections(s1
, "tcc.log");
1743 /* ------------------------------------------------------------- */
1744 #endif /* def TCC_TARGET_PE */
1745 /* ------------------------------------------------------------- */