2 * TCCPE.C - PE file output for the Tiny C Compiler
4 * Copyright (c) 2005-2007 grischka
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
24 #define stricmp strcasecmp
25 #define strnicmp strncasecmp
33 // #define PE_PRINT_SECTIONS
35 #ifdef TCC_TARGET_X86_64
36 # define ADDR3264 ULONGLONG
38 # define ADDR3264 DWORD
42 void dbg_printf (const char *fmt
, ...)
48 x
= vsprintf (buffer
, fmt
, arg
);
49 strcpy(buffer
+x
, "\n");
50 OutputDebugString(buffer
);
54 /* ----------------------------------------------------------- */
55 #ifndef IMAGE_NT_SIGNATURE
56 /* ----------------------------------------------------------- */
57 /* definitions below are from winnt.h */
59 typedef unsigned char BYTE
;
60 typedef unsigned short WORD
;
61 typedef unsigned int DWORD
;
62 typedef unsigned long long ULONGLONG
;
65 typedef struct _IMAGE_DOS_HEADER
{ /* DOS .EXE header */
66 WORD e_magic
; /* Magic number */
67 WORD e_cblp
; /* Bytes on last page of file */
68 WORD e_cp
; /* Pages in file */
69 WORD e_crlc
; /* Relocations */
70 WORD e_cparhdr
; /* Size of header in paragraphs */
71 WORD e_minalloc
; /* Minimum extra paragraphs needed */
72 WORD e_maxalloc
; /* Maximum extra paragraphs needed */
73 WORD e_ss
; /* Initial (relative) SS value */
74 WORD e_sp
; /* Initial SP value */
75 WORD e_csum
; /* Checksum */
76 WORD e_ip
; /* Initial IP value */
77 WORD e_cs
; /* Initial (relative) CS value */
78 WORD e_lfarlc
; /* File address of relocation table */
79 WORD e_ovno
; /* Overlay number */
80 WORD e_res
[4]; /* Reserved words */
81 WORD e_oemid
; /* OEM identifier (for e_oeminfo) */
82 WORD e_oeminfo
; /* OEM information; e_oemid specific */
83 WORD e_res2
[10]; /* Reserved words */
84 DWORD e_lfanew
; /* File address of new exe header */
85 } IMAGE_DOS_HEADER
, *PIMAGE_DOS_HEADER
;
87 #define IMAGE_NT_SIGNATURE 0x00004550 /* PE00 */
88 #define SIZE_OF_NT_SIGNATURE 4
90 typedef struct _IMAGE_FILE_HEADER
{
92 WORD NumberOfSections
;
94 DWORD PointerToSymbolTable
;
95 DWORD NumberOfSymbols
;
96 WORD SizeOfOptionalHeader
;
98 } IMAGE_FILE_HEADER
, *PIMAGE_FILE_HEADER
;
101 #define IMAGE_SIZEOF_FILE_HEADER 20
103 typedef struct _IMAGE_DATA_DIRECTORY
{
104 DWORD VirtualAddress
;
106 } IMAGE_DATA_DIRECTORY
, *PIMAGE_DATA_DIRECTORY
;
109 typedef struct _IMAGE_OPTIONAL_HEADER
{
110 /* Standard fields. */
112 BYTE MajorLinkerVersion
;
113 BYTE MinorLinkerVersion
;
115 DWORD SizeOfInitializedData
;
116 DWORD SizeOfUninitializedData
;
117 DWORD AddressOfEntryPoint
;
119 #ifndef TCC_TARGET_X86_64
122 /* NT additional fields. */
124 DWORD SectionAlignment
;
126 WORD MajorOperatingSystemVersion
;
127 WORD MinorOperatingSystemVersion
;
128 WORD MajorImageVersion
;
129 WORD MinorImageVersion
;
130 WORD MajorSubsystemVersion
;
131 WORD MinorSubsystemVersion
;
132 DWORD Win32VersionValue
;
137 WORD DllCharacteristics
;
138 ADDR3264 SizeOfStackReserve
;
139 ADDR3264 SizeOfStackCommit
;
140 ADDR3264 SizeOfHeapReserve
;
141 ADDR3264 SizeOfHeapCommit
;
143 DWORD NumberOfRvaAndSizes
;
144 IMAGE_DATA_DIRECTORY DataDirectory
[16];
145 } IMAGE_OPTIONAL_HEADER32
, IMAGE_OPTIONAL_HEADER64
, IMAGE_OPTIONAL_HEADER
;
147 #define IMAGE_DIRECTORY_ENTRY_EXPORT 0 /* Export Directory */
148 #define IMAGE_DIRECTORY_ENTRY_IMPORT 1 /* Import Directory */
149 #define IMAGE_DIRECTORY_ENTRY_RESOURCE 2 /* Resource Directory */
150 #define IMAGE_DIRECTORY_ENTRY_EXCEPTION 3 /* Exception Directory */
151 #define IMAGE_DIRECTORY_ENTRY_SECURITY 4 /* Security Directory */
152 #define IMAGE_DIRECTORY_ENTRY_BASERELOC 5 /* Base Relocation Table */
153 #define IMAGE_DIRECTORY_ENTRY_DEBUG 6 /* Debug Directory */
154 /* IMAGE_DIRECTORY_ENTRY_COPYRIGHT 7 (X86 usage) */
155 #define IMAGE_DIRECTORY_ENTRY_ARCHITECTURE 7 /* Architecture Specific Data */
156 #define IMAGE_DIRECTORY_ENTRY_GLOBALPTR 8 /* RVA of GP */
157 #define IMAGE_DIRECTORY_ENTRY_TLS 9 /* TLS Directory */
158 #define IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG 10 /* Load Configuration Directory */
159 #define IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT 11 /* Bound Import Directory in headers */
160 #define IMAGE_DIRECTORY_ENTRY_IAT 12 /* Import Address Table */
161 #define IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT 13 /* Delay Load Import Descriptors */
162 #define IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR 14 /* COM Runtime descriptor */
164 /* Section header format. */
165 #define IMAGE_SIZEOF_SHORT_NAME 8
167 typedef struct _IMAGE_SECTION_HEADER
{
168 BYTE Name
[IMAGE_SIZEOF_SHORT_NAME
];
170 DWORD PhysicalAddress
;
173 DWORD VirtualAddress
;
175 DWORD PointerToRawData
;
176 DWORD PointerToRelocations
;
177 DWORD PointerToLinenumbers
;
178 WORD NumberOfRelocations
;
179 WORD NumberOfLinenumbers
;
180 DWORD Characteristics
;
181 } IMAGE_SECTION_HEADER
, *PIMAGE_SECTION_HEADER
;
183 #define IMAGE_SIZEOF_SECTION_HEADER 40
185 typedef struct _IMAGE_EXPORT_DIRECTORY
{
186 DWORD Characteristics
;
192 DWORD NumberOfFunctions
;
194 DWORD AddressOfFunctions
;
195 DWORD AddressOfNames
;
196 DWORD AddressOfNameOrdinals
;
197 } IMAGE_EXPORT_DIRECTORY
,*PIMAGE_EXPORT_DIRECTORY
;
199 typedef struct _IMAGE_IMPORT_DESCRIPTOR
{
201 DWORD Characteristics
;
202 DWORD OriginalFirstThunk
;
205 DWORD ForwarderChain
;
208 } IMAGE_IMPORT_DESCRIPTOR
;
210 typedef struct _IMAGE_BASE_RELOCATION
{
211 DWORD VirtualAddress
;
213 // WORD TypeOffset[1];
214 } IMAGE_BASE_RELOCATION
;
216 #define IMAGE_SIZEOF_BASE_RELOCATION 8
218 #define IMAGE_REL_BASED_ABSOLUTE 0
219 #define IMAGE_REL_BASED_HIGH 1
220 #define IMAGE_REL_BASED_LOW 2
221 #define IMAGE_REL_BASED_HIGHLOW 3
222 #define IMAGE_REL_BASED_HIGHADJ 4
223 #define IMAGE_REL_BASED_MIPS_JMPADDR 5
224 #define IMAGE_REL_BASED_SECTION 6
225 #define IMAGE_REL_BASED_REL32 7
229 /* ----------------------------------------------------------- */
230 #endif /* ndef IMAGE_NT_SIGNATURE */
231 /* ----------------------------------------------------------- */
232 #pragma pack(push, 1)
236 IMAGE_DOS_HEADER doshdr
;
239 IMAGE_FILE_HEADER filehdr
;
240 #ifdef TCC_TARGET_X86_64
241 IMAGE_OPTIONAL_HEADER64 opthdr
;
244 IMAGE_OPTIONAL_HEADER32 opthdr
;
246 IMAGE_OPTIONAL_HEADER opthdr
;
251 struct pe_reloc_header
{
256 struct pe_rsrc_header
{
257 struct _IMAGE_FILE_HEADER filehdr
;
258 struct _IMAGE_SECTION_HEADER sectionhdr
;
261 struct pe_rsrc_reloc
{
269 /* ------------------------------------------------------------- */
270 /* internal temporary structures */
273 #define IMAGE_SCN_CNT_CODE 0x00000020
274 #define IMAGE_SCN_CNT_INITIALIZED_DATA 0x00000040
275 #define IMAGE_SCN_CNT_UNINITIALIZED_DATA 0x00000080
276 #define IMAGE_SCN_MEM_DISCARDABLE 0x02000000
277 #define IMAGE_SCN_MEM_SHARED 0x10000000
278 #define IMAGE_SCN_MEM_EXECUTE 0x20000000
279 #define IMAGE_SCN_MEM_READ 0x40000000
280 #define IMAGE_SCN_MEM_WRITE 0x80000000
296 static const DWORD pe_sec_flags
[] = {
297 0x60000020, /* ".text" , */
298 0xC0000040, /* ".data" , */
299 0xC0000080, /* ".bss" , */
300 0x40000040, /* ".idata" , */
301 0x40000040, /* ".pdata" , */
302 0xE0000060, /* < other > , */
303 0x40000040, /* ".rsrc" , */
304 0x42000802, /* ".stab" , */
305 0x42000040, /* ".reloc" , */
308 struct section_info
{
316 IMAGE_SECTION_HEADER ish
;
319 struct import_symbol
{
325 struct pe_import_info
{
328 struct import_symbol
**symbols
;
335 const char *filename
;
349 struct section_info
*sec_info
;
351 struct pe_import_info
**imp_info
;
361 /* --------------------------------------------*/
363 static const char *pe_export_name(TCCState
*s1
, ElfW(Sym
) *sym
)
365 const char *name
= symtab_section
->link
->data
+ sym
->st_name
;
366 if (s1
->leading_underscore
&& name
[0] == '_' && !(sym
->st_other
& 2))
371 static int pe_find_import(TCCState
* s1
, ElfW(Sym
) *sym
)
375 int sym_index
= 0, n
= 0;
378 s
= pe_export_name(s1
, sym
);
381 if (sym
->st_other
& 2) {
382 /* try w/0 stdcall deco (windows API convention) */
384 if (!p
|| s
[0] != '_')
386 strcpy(buffer
, s
+1)[p
-s
-1] = 0;
387 } else if (s
[0] != '_') { /* try non-ansi function */
388 buffer
[0] = '_', strcpy(buffer
+ 1, s
);
389 } else if (0 == memcmp(s
, "__imp__", 7)) { /* mingw 2.0 */
390 strcpy(buffer
, s
+ 6);
391 } else if (0 == memcmp(s
, "_imp___", 7)) { /* mingw 3.7 */
392 strcpy(buffer
, s
+ 6);
398 sym_index
= find_elf_sym(s1
->dynsymtab_section
, s
);
399 // printf("find (%d) %d %s\n", n, sym_index, s);
400 } while (0 == sym_index
&& ++n
< 2);
404 /*----------------------------------------------------------------------------*/
406 static int dynarray_assoc(void **pp
, int n
, int key
)
409 for (i
= 0; i
< n
; ++i
, ++pp
)
410 if (key
== **(int **) pp
)
416 ST_FN DWORD
umin(DWORD a
, DWORD b
)
418 return a
< b
? a
: b
;
422 static DWORD
umax(DWORD a
, DWORD b
)
424 return a
< b
? b
: a
;
427 static DWORD
pe_file_align(struct pe_info
*pe
, DWORD n
)
429 return (n
+ (pe
->file_align
- 1)) & ~(pe
->file_align
- 1);
432 static DWORD
pe_virtual_align(struct pe_info
*pe
, DWORD n
)
434 return (n
+ (pe
->section_align
- 1)) & ~(pe
->section_align
- 1);
437 static void pe_align_section(Section
*s
, int a
)
439 int i
= s
->data_offset
& (a
-1);
441 section_ptr_add(s
, a
- i
);
444 static void pe_set_datadir(struct pe_header
*hdr
, int dir
, DWORD addr
, DWORD size
)
446 hdr
->opthdr
.DataDirectory
[dir
].VirtualAddress
= addr
;
447 hdr
->opthdr
.DataDirectory
[dir
].Size
= size
;
450 static int pe_fwrite(void *data
, unsigned len
, FILE *fp
, DWORD
*psum
)
456 for (i
= len
; i
> 0; i
-= 2) {
457 sum
+= (i
>= 2) ? *p
++ : *(BYTE
*)p
;
458 sum
= (sum
+ (sum
>> 16)) & 0xFFFF;
462 return len
== fwrite(data
, 1, len
, fp
) ? 0 : -1;
465 static void pe_fpad(FILE *fp
, DWORD new_pos
)
467 DWORD pos
= ftell(fp
);
468 while (++pos
<= new_pos
)
472 /*----------------------------------------------------------------------------*/
473 static int pe_write(struct pe_info
*pe
)
475 static const struct pe_header pe_template
= {
477 /* IMAGE_DOS_HEADER doshdr */
478 0x5A4D, /*WORD e_magic; Magic number */
479 0x0090, /*WORD e_cblp; Bytes on last page of file */
480 0x0003, /*WORD e_cp; Pages in file */
481 0x0000, /*WORD e_crlc; Relocations */
483 0x0004, /*WORD e_cparhdr; Size of header in paragraphs */
484 0x0000, /*WORD e_minalloc; Minimum extra paragraphs needed */
485 0xFFFF, /*WORD e_maxalloc; Maximum extra paragraphs needed */
486 0x0000, /*WORD e_ss; Initial (relative) SS value */
488 0x00B8, /*WORD e_sp; Initial SP value */
489 0x0000, /*WORD e_csum; Checksum */
490 0x0000, /*WORD e_ip; Initial IP value */
491 0x0000, /*WORD e_cs; Initial (relative) CS value */
492 0x0040, /*WORD e_lfarlc; File address of relocation table */
493 0x0000, /*WORD e_ovno; Overlay number */
494 {0,0,0,0}, /*WORD e_res[4]; Reserved words */
495 0x0000, /*WORD e_oemid; OEM identifier (for e_oeminfo) */
496 0x0000, /*WORD e_oeminfo; OEM information; e_oemid specific */
497 {0,0,0,0,0,0,0,0,0,0}, /*WORD e_res2[10]; Reserved words */
498 0x00000080 /*DWORD e_lfanew; File address of new exe header */
500 /* BYTE dosstub[0x40] */
501 /* 14 code bytes + "This program cannot be run in DOS mode.\r\r\n$" + 6 * 0x00 */
502 0x0e,0x1f,0xba,0x0e,0x00,0xb4,0x09,0xcd,0x21,0xb8,0x01,0x4c,0xcd,0x21,0x54,0x68,
503 0x69,0x73,0x20,0x70,0x72,0x6f,0x67,0x72,0x61,0x6d,0x20,0x63,0x61,0x6e,0x6e,0x6f,
504 0x74,0x20,0x62,0x65,0x20,0x72,0x75,0x6e,0x20,0x69,0x6e,0x20,0x44,0x4f,0x53,0x20,
505 0x6d,0x6f,0x64,0x65,0x2e,0x0d,0x0d,0x0a,0x24,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
507 0x00004550, /* DWORD nt_sig = IMAGE_NT_SIGNATURE */
509 /* IMAGE_FILE_HEADER filehdr */
510 #if defined(TCC_TARGET_I386)
511 0x014C, /*WORD Machine; */
512 #elif defined(TCC_TARGET_X86_64)
513 0x8664, /*WORD Machine; */
514 #elif defined(TCC_TARGET_ARM)
515 0x01C0, /*WORD Machine; */
517 0x0003, /*WORD NumberOfSections; */
518 0x00000000, /*DWORD TimeDateStamp; */
519 0x00000000, /*DWORD PointerToSymbolTable; */
520 0x00000000, /*DWORD NumberOfSymbols; */
521 #if defined(TCC_TARGET_X86_64)
522 0x00F0, /*WORD SizeOfOptionalHeader; */
523 0x022F /*WORD Characteristics; */
524 #define CHARACTERISTICS_DLL 0x222E
525 #elif defined(TCC_TARGET_I386)
526 0x00E0, /*WORD SizeOfOptionalHeader; */
527 0x030F /*WORD Characteristics; */
528 #define CHARACTERISTICS_DLL 0x230E
529 #elif defined(TCC_TARGET_ARM)
530 0x00E0, /*WORD SizeOfOptionalHeader; */
531 0x010F, /*WORD Characteristics; */
532 #define CHARACTERISTICS_DLL 0x230F
535 /* IMAGE_OPTIONAL_HEADER opthdr */
536 /* Standard fields. */
537 #ifdef TCC_TARGET_X86_64
538 0x020B, /*WORD Magic; */
540 0x010B, /*WORD Magic; */
542 0x06, /*BYTE MajorLinkerVersion; */
543 0x00, /*BYTE MinorLinkerVersion; */
544 0x00000000, /*DWORD SizeOfCode; */
545 0x00000000, /*DWORD SizeOfInitializedData; */
546 0x00000000, /*DWORD SizeOfUninitializedData; */
547 0x00000000, /*DWORD AddressOfEntryPoint; */
548 0x00000000, /*DWORD BaseOfCode; */
549 #ifndef TCC_TARGET_X86_64
550 0x00000000, /*DWORD BaseOfData; */
552 /* NT additional fields. */
553 #if defined(TCC_TARGET_ARM)
554 0x00100000, /*DWORD ImageBase; */
556 0x00400000, /*DWORD ImageBase; */
558 0x00001000, /*DWORD SectionAlignment; */
559 0x00000200, /*DWORD FileAlignment; */
560 0x0004, /*WORD MajorOperatingSystemVersion; */
561 0x0000, /*WORD MinorOperatingSystemVersion; */
562 0x0000, /*WORD MajorImageVersion; */
563 0x0000, /*WORD MinorImageVersion; */
564 0x0004, /*WORD MajorSubsystemVersion; */
565 0x0000, /*WORD MinorSubsystemVersion; */
566 0x00000000, /*DWORD Win32VersionValue; */
567 0x00000000, /*DWORD SizeOfImage; */
568 0x00000200, /*DWORD SizeOfHeaders; */
569 0x00000000, /*DWORD CheckSum; */
570 0x0002, /*WORD Subsystem; */
571 0x0000, /*WORD DllCharacteristics; */
572 0x00100000, /*DWORD SizeOfStackReserve; */
573 0x00001000, /*DWORD SizeOfStackCommit; */
574 0x00100000, /*DWORD SizeOfHeapReserve; */
575 0x00001000, /*DWORD SizeOfHeapCommit; */
576 0x00000000, /*DWORD LoaderFlags; */
577 0x00000010, /*DWORD NumberOfRvaAndSizes; */
579 /* IMAGE_DATA_DIRECTORY DataDirectory[16]; */
580 {{0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0},
581 {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}}
584 struct pe_header pe_header
= pe_template
;
588 DWORD file_offset
, sum
;
589 struct section_info
*si
;
590 IMAGE_SECTION_HEADER
*psh
;
592 op
= fopen(pe
->filename
, "wb");
594 tcc_error_noabort("could not write '%s': %s", pe
->filename
, strerror(errno
));
598 pe
->sizeofheaders
= pe_file_align(pe
,
599 sizeof (struct pe_header
)
600 + pe
->sec_count
* sizeof (IMAGE_SECTION_HEADER
)
603 file_offset
= pe
->sizeofheaders
;
605 if (2 == pe
->s1
->verbose
)
606 printf("-------------------------------"
607 "\n virt file size section" "\n");
608 for (i
= 0; i
< pe
->sec_count
; ++i
) {
612 si
= pe
->sec_info
+ i
;
614 addr
= si
->sh_addr
- pe
->imagebase
;
618 if (2 == pe
->s1
->verbose
)
619 printf("%6x %6x %6x %s\n",
620 (unsigned)addr
, (unsigned)file_offset
, (unsigned)size
, sh_name
);
624 pe_header
.opthdr
.BaseOfCode
= addr
;
625 pe_header
.opthdr
.AddressOfEntryPoint
= addr
+ pe
->start_addr
;
629 #ifndef TCC_TARGET_X86_64
630 pe_header
.opthdr
.BaseOfData
= addr
;
638 pe_set_datadir(&pe_header
, IMAGE_DIRECTORY_ENTRY_BASERELOC
, addr
, size
);
642 pe_set_datadir(&pe_header
, IMAGE_DIRECTORY_ENTRY_RESOURCE
, addr
, size
);
646 pe_set_datadir(&pe_header
, IMAGE_DIRECTORY_ENTRY_EXCEPTION
, addr
, size
);
653 if (pe
->thunk
== pe
->s1
->sections
[si
->ord
]) {
655 pe_set_datadir(&pe_header
, IMAGE_DIRECTORY_ENTRY_IMPORT
,
656 pe
->imp_offs
+ addr
, pe
->imp_size
);
657 pe_set_datadir(&pe_header
, IMAGE_DIRECTORY_ENTRY_IAT
,
658 pe
->iat_offs
+ addr
, pe
->iat_size
);
661 pe_set_datadir(&pe_header
, IMAGE_DIRECTORY_ENTRY_EXPORT
,
662 pe
->exp_offs
+ addr
, pe
->exp_size
);
666 strcpy((char*)psh
->Name
, sh_name
);
668 psh
->Characteristics
= pe_sec_flags
[si
->cls
];
669 psh
->VirtualAddress
= addr
;
670 psh
->Misc
.VirtualSize
= size
;
671 pe_header
.opthdr
.SizeOfImage
=
672 umax(pe_virtual_align(pe
, size
+ addr
), pe_header
.opthdr
.SizeOfImage
);
675 psh
->PointerToRawData
= file_offset
;
676 file_offset
= pe_file_align(pe
, file_offset
+ si
->data_size
);
677 psh
->SizeOfRawData
= file_offset
- psh
->PointerToRawData
;
681 //pe_header.filehdr.TimeDateStamp = time(NULL);
682 pe_header
.filehdr
.NumberOfSections
= pe
->sec_count
;
683 pe_header
.opthdr
.SizeOfHeaders
= pe
->sizeofheaders
;
684 pe_header
.opthdr
.ImageBase
= pe
->imagebase
;
685 if (pe
->s1
->pe_stack_size
)
686 pe_header
.opthdr
.SizeOfStackReserve
= pe
->s1
->pe_stack_size
;
687 if (PE_DLL
== pe
->type
)
688 pe_header
.filehdr
.Characteristics
= CHARACTERISTICS_DLL
;
689 else if (PE_GUI
!= pe
->type
)
690 pe_header
.opthdr
.Subsystem
= 3;
691 if (pe
->subsystem
== 9) // WinCE
692 pe_header
.opthdr
.Subsystem
= 9;
695 pe_fwrite(&pe_header
, sizeof pe_header
, op
, &sum
);
696 for (i
= 0; i
< pe
->sec_count
; ++i
)
697 pe_fwrite(&pe
->sec_info
[i
].ish
, sizeof(IMAGE_SECTION_HEADER
), op
, &sum
);
698 pe_fpad(op
, pe
->sizeofheaders
);
699 for (i
= 0; i
< pe
->sec_count
; ++i
) {
700 si
= pe
->sec_info
+ i
;
703 pe_fwrite(si
->data
, si
->data_size
, op
, &sum
);
704 file_offset
= psh
->PointerToRawData
+ psh
->SizeOfRawData
;
705 pe_fpad(op
, file_offset
);
709 pe_header
.opthdr
.CheckSum
= sum
+ file_offset
;
710 fseek(op
, offsetof(struct pe_header
, opthdr
.CheckSum
), SEEK_SET
);
711 pe_fwrite(&pe_header
.opthdr
.CheckSum
, sizeof pe_header
.opthdr
.CheckSum
, op
, NULL
);
714 if (2 == pe
->s1
->verbose
)
715 printf("-------------------------------\n");
717 printf("<- %s (%u bytes)\n", pe
->filename
, (unsigned)file_offset
);
722 /*----------------------------------------------------------------------------*/
724 #if defined(TCC_TARGET_X86_64)
725 #define REL_TYPE_DIRECT R_X86_64_64
726 #define R_XXX_THUNKFIX R_X86_64_PC32
727 #define R_XXX_RELATIVE R_X86_64_RELATIVE
729 #elif defined(TCC_TARGET_I386)
730 #define REL_TYPE_DIRECT R_386_32
731 #define R_XXX_THUNKFIX R_386_32
732 #define R_XXX_RELATIVE R_386_RELATIVE
734 #elif defined(TCC_TARGET_ARM)
735 #define REL_TYPE_DIRECT R_ARM_ABS32
736 #define R_XXX_THUNKFIX R_ARM_ABS32
737 #define R_XXX_RELATIVE R_ARM_RELATIVE
740 /*----------------------------------------------------------------------------*/
742 static struct import_symbol
*pe_add_import(struct pe_info
*pe
, int sym_index
)
746 struct pe_import_info
*p
;
747 struct import_symbol
*s
;
750 isym
= (ElfW(Sym
) *)pe
->s1
->dynsymtab_section
->data
+ sym_index
;
751 dll_index
= isym
->st_size
;
753 i
= dynarray_assoc ((void**)pe
->imp_info
, pe
->imp_count
, dll_index
);
758 p
= tcc_mallocz(sizeof *p
);
759 p
->dll_index
= dll_index
;
760 dynarray_add((void***)&pe
->imp_info
, &pe
->imp_count
, p
);
763 i
= dynarray_assoc ((void**)p
->symbols
, p
->sym_count
, sym_index
);
765 return p
->symbols
[i
];
767 s
= tcc_mallocz(sizeof *s
);
768 dynarray_add((void***)&p
->symbols
, &p
->sym_count
, s
);
769 s
->sym_index
= sym_index
;
773 /*----------------------------------------------------------------------------*/
774 static void pe_build_imports(struct pe_info
*pe
)
776 int thk_ptr
, ent_ptr
, dll_ptr
, sym_cnt
, i
;
777 DWORD rva_base
= pe
->thunk
->sh_addr
- pe
->imagebase
;
778 int ndlls
= pe
->imp_count
;
780 for (sym_cnt
= i
= 0; i
< ndlls
; ++i
)
781 sym_cnt
+= pe
->imp_info
[i
]->sym_count
;
786 pe_align_section(pe
->thunk
, 16);
788 pe
->imp_offs
= dll_ptr
= pe
->thunk
->data_offset
;
789 pe
->imp_size
= (ndlls
+ 1) * sizeof(IMAGE_IMPORT_DESCRIPTOR
);
790 pe
->iat_offs
= dll_ptr
+ pe
->imp_size
;
791 pe
->iat_size
= (sym_cnt
+ ndlls
) * sizeof(ADDR3264
);
792 section_ptr_add(pe
->thunk
, pe
->imp_size
+ 2*pe
->iat_size
);
794 thk_ptr
= pe
->iat_offs
;
795 ent_ptr
= pe
->iat_offs
+ pe
->iat_size
;
797 for (i
= 0; i
< pe
->imp_count
; ++i
) {
798 IMAGE_IMPORT_DESCRIPTOR
*hdr
;
801 struct pe_import_info
*p
= pe
->imp_info
[i
];
803 DLLReference
*dllref
;
805 dllindex
= p
->dll_index
;
807 name
= (dllref
= pe
->s1
->loaded_dlls
[dllindex
-1])->name
;
809 name
= "", dllref
= NULL
;
811 /* put the dll name into the import header */
812 v
= put_elf_str(pe
->thunk
, name
);
813 hdr
= (IMAGE_IMPORT_DESCRIPTOR
*)(pe
->thunk
->data
+ dll_ptr
);
814 hdr
->FirstThunk
= thk_ptr
+ rva_base
;
815 hdr
->OriginalFirstThunk
= ent_ptr
+ rva_base
;
816 hdr
->Name
= v
+ rva_base
;
818 for (k
= 0, n
= p
->sym_count
; k
<= n
; ++k
) {
820 int iat_index
= p
->symbols
[k
]->iat_index
;
821 int sym_index
= p
->symbols
[k
]->sym_index
;
822 ElfW(Sym
) *imp_sym
= (ElfW(Sym
) *)pe
->s1
->dynsymtab_section
->data
+ sym_index
;
823 ElfW(Sym
) *org_sym
= (ElfW(Sym
) *)symtab_section
->data
+ iat_index
;
824 const char *name
= pe
->s1
->dynsymtab_section
->link
->data
+ imp_sym
->st_name
;
826 org_sym
->st_value
= thk_ptr
;
827 org_sym
->st_shndx
= pe
->thunk
->sh_num
;
828 v
= pe
->thunk
->data_offset
+ rva_base
;
829 section_ptr_add(pe
->thunk
, sizeof(WORD
)); /* hint, not used */
830 put_elf_str(pe
->thunk
, name
);
832 if (pe
->type
== PE_RUN
) {
833 v
= imp_sym
->st_value
;
835 if ( !dllref
->handle
)
836 dllref
->handle
= LoadLibrary(dllref
->name
);
837 v
= (ADDR3264
)GetProcAddress(dllref
->handle
, name
);
840 tcc_error_noabort("undefined symbol '%s'", name
);
844 v
= 0; /* last entry is zero */
846 *(ADDR3264
*)(pe
->thunk
->data
+thk_ptr
) =
847 *(ADDR3264
*)(pe
->thunk
->data
+ent_ptr
) = v
;
848 thk_ptr
+= sizeof (ADDR3264
);
849 ent_ptr
+= sizeof (ADDR3264
);
851 dll_ptr
+= sizeof(IMAGE_IMPORT_DESCRIPTOR
);
852 dynarray_reset(&p
->symbols
, &p
->sym_count
);
854 dynarray_reset(&pe
->imp_info
, &pe
->imp_count
);
857 /* ------------------------------------------------------------- */
865 static int sym_cmp(const void *va
, const void *vb
)
867 const char *ca
= (*(struct pe_sort_sym
**)va
)->name
;
868 const char *cb
= (*(struct pe_sort_sym
**)vb
)->name
;
869 return strcmp(ca
, cb
);
872 static void pe_build_exports(struct pe_info
*pe
)
875 int sym_index
, sym_end
;
876 DWORD rva_base
, func_o
, name_o
, ord_o
, str_o
;
877 IMAGE_EXPORT_DIRECTORY
*hdr
;
879 struct pe_sort_sym
**sorted
, *p
;
886 rva_base
= pe
->thunk
->sh_addr
- pe
->imagebase
;
887 sym_count
= 0, sorted
= NULL
, op
= NULL
;
889 sym_end
= symtab_section
->data_offset
/ sizeof(ElfW(Sym
));
890 for (sym_index
= 1; sym_index
< sym_end
; ++sym_index
) {
891 sym
= (ElfW(Sym
)*)symtab_section
->data
+ sym_index
;
892 name
= pe_export_name(pe
->s1
, sym
);
893 if ((sym
->st_other
& 1)
894 /* export only symbols from actually written sections */
895 && pe
->s1
->sections
[sym
->st_shndx
]->sh_addr
) {
896 p
= tcc_malloc(sizeof *p
);
897 p
->index
= sym_index
;
899 dynarray_add((void***)&sorted
, &sym_count
, p
);
902 if (sym
->st_other
& 1)
903 printf("export: %s\n", name
);
904 if (sym
->st_other
& 2)
905 printf("stdcall: %s\n", name
);
912 qsort (sorted
, sym_count
, sizeof *sorted
, sym_cmp
);
914 pe_align_section(pe
->thunk
, 16);
915 dllname
= tcc_basename(pe
->filename
);
917 pe
->exp_offs
= pe
->thunk
->data_offset
;
918 func_o
= pe
->exp_offs
+ sizeof(IMAGE_EXPORT_DIRECTORY
);
919 name_o
= func_o
+ sym_count
* sizeof (DWORD
);
920 ord_o
= name_o
+ sym_count
* sizeof (DWORD
);
921 str_o
= ord_o
+ sym_count
* sizeof(WORD
);
923 hdr
= section_ptr_add(pe
->thunk
, str_o
- pe
->exp_offs
);
924 hdr
->Characteristics
= 0;
926 hdr
->NumberOfFunctions
= sym_count
;
927 hdr
->NumberOfNames
= sym_count
;
928 hdr
->AddressOfFunctions
= func_o
+ rva_base
;
929 hdr
->AddressOfNames
= name_o
+ rva_base
;
930 hdr
->AddressOfNameOrdinals
= ord_o
+ rva_base
;
931 hdr
->Name
= str_o
+ rva_base
;
932 put_elf_str(pe
->thunk
, dllname
);
935 /* automatically write exports to <output-filename>.def */
936 strcpy(buf
, pe
->filename
);
937 strcpy(tcc_fileextension(buf
), ".def");
938 op
= fopen(buf
, "w");
940 tcc_error_noabort("could not create '%s': %s", buf
, strerror(errno
));
942 fprintf(op
, "LIBRARY %s\n\nEXPORTS\n", dllname
);
944 printf("<- %s (%d symbols)\n", buf
, sym_count
);
948 for (ord
= 0; ord
< sym_count
; ++ord
)
950 p
= sorted
[ord
], sym_index
= p
->index
, name
= p
->name
;
951 /* insert actual address later in pe_relocate_rva */
952 put_elf_reloc(symtab_section
, pe
->thunk
,
953 func_o
, R_XXX_RELATIVE
, sym_index
);
954 *(DWORD
*)(pe
->thunk
->data
+ name_o
)
955 = pe
->thunk
->data_offset
+ rva_base
;
956 *(WORD
*)(pe
->thunk
->data
+ ord_o
)
958 put_elf_str(pe
->thunk
, name
);
959 func_o
+= sizeof (DWORD
);
960 name_o
+= sizeof (DWORD
);
961 ord_o
+= sizeof (WORD
);
963 fprintf(op
, "%s\n", name
);
965 pe
->exp_size
= pe
->thunk
->data_offset
- pe
->exp_offs
;
966 dynarray_reset(&sorted
, &sym_count
);
971 /* ------------------------------------------------------------- */
972 static void pe_build_reloc (struct pe_info
*pe
)
974 DWORD offset
, block_ptr
, addr
;
976 ElfW_Rel
*rel
, *rel_end
;
977 Section
*s
= NULL
, *sr
;
979 offset
= addr
= block_ptr
= count
= i
= 0;
980 rel
= rel_end
= NULL
;
984 int type
= ELFW(R_TYPE
)(rel
->r_info
);
985 addr
= rel
->r_offset
+ s
->sh_addr
;
987 if (type
!= REL_TYPE_DIRECT
)
989 if (count
== 0) { /* new block */
990 block_ptr
= pe
->reloc
->data_offset
;
991 section_ptr_add(pe
->reloc
, sizeof(struct pe_reloc_header
));
992 offset
= addr
& 0xFFFFFFFF<<12;
994 if ((addr
-= offset
) < (1<<12)) { /* one block spans 4k addresses */
995 WORD
*wp
= section_ptr_add(pe
->reloc
, sizeof (WORD
));
996 *wp
= addr
| IMAGE_REL_BASED_HIGHLOW
<<12;
1002 } else if (i
< pe
->sec_count
) {
1003 sr
= (s
= pe
->s1
->sections
[pe
->sec_info
[i
++].ord
])->reloc
;
1005 rel
= (ElfW_Rel
*)sr
->data
;
1006 rel_end
= (ElfW_Rel
*)(sr
->data
+ sr
->data_offset
);
1012 /* store the last block and ready for a new one */
1013 struct pe_reloc_header
*hdr
;
1014 if (count
& 1) /* align for DWORDS */
1015 section_ptr_add(pe
->reloc
, sizeof(WORD
)), ++count
;
1016 hdr
= (struct pe_reloc_header
*)(pe
->reloc
->data
+ block_ptr
);
1017 hdr
-> offset
= offset
- pe
->imagebase
;
1018 hdr
-> size
= count
* sizeof(WORD
) + sizeof(struct pe_reloc_header
);
1027 /* ------------------------------------------------------------- */
1028 static int pe_section_class(Section
*s
)
1034 flags
= s
->sh_flags
;
1036 if (flags
& SHF_ALLOC
) {
1037 if (type
== SHT_PROGBITS
) {
1038 if (flags
& SHF_EXECINSTR
)
1040 if (flags
& SHF_WRITE
)
1042 if (0 == strcmp(name
, ".rsrc"))
1044 if (0 == strcmp(name
, ".iedat"))
1046 if (0 == strcmp(name
, ".pdata"))
1049 } else if (type
== SHT_NOBITS
) {
1050 if (flags
& SHF_WRITE
)
1054 if (0 == strcmp(name
, ".reloc"))
1056 if (0 == strncmp(name
, ".stab", 5)) /* .stab and .stabstr */
1062 static int pe_assign_addresses (struct pe_info
*pe
)
1067 struct section_info
*si
;
1070 // pe->thunk = new_section(pe->s1, ".iedat", SHT_PROGBITS, SHF_ALLOC);
1072 section_order
= tcc_malloc(pe
->s1
->nb_sections
* sizeof (int));
1073 for (o
= k
= 0 ; k
< sec_last
; ++k
) {
1074 for (i
= 1; i
< pe
->s1
->nb_sections
; ++i
) {
1075 s
= pe
->s1
->sections
[i
];
1076 if (k
== pe_section_class(s
)) {
1077 // printf("%s %d\n", s->name, k);
1078 s
->sh_addr
= pe
->imagebase
;
1079 section_order
[o
++] = i
;
1084 pe
->sec_info
= tcc_mallocz(o
* sizeof (struct section_info
));
1085 addr
= pe
->imagebase
+ 1;
1087 for (i
= 0; i
< o
; ++i
)
1089 k
= section_order
[i
];
1090 s
= pe
->s1
->sections
[k
];
1091 c
= pe_section_class(s
);
1092 si
= &pe
->sec_info
[pe
->sec_count
];
1094 #ifdef PE_MERGE_DATA
1095 if (c
== sec_bss
&& pe
->sec_count
&& si
[-1].cls
== sec_data
) {
1096 /* append .bss to .data */
1097 s
->sh_addr
= addr
= ((addr
-1) | (s
->sh_addralign
-1)) + 1;
1098 addr
+= s
->data_offset
;
1099 si
[-1].sh_size
= addr
- si
[-1].sh_addr
;
1103 strcpy(si
->name
, s
->name
);
1106 si
->sh_addr
= s
->sh_addr
= addr
= pe_virtual_align(pe
, addr
);
1107 si
->sh_flags
= s
->sh_flags
;
1109 if (c
== sec_data
&& NULL
== pe
->thunk
)
1112 if (s
== pe
->thunk
) {
1113 pe_build_imports(pe
);
1114 pe_build_exports(pe
);
1118 pe_build_reloc (pe
);
1122 if (s
->sh_type
!= SHT_NOBITS
) {
1124 si
->data_size
= s
->data_offset
;
1127 addr
+= s
->data_offset
;
1128 si
->sh_size
= s
->data_offset
;
1131 // printf("%08x %05x %s\n", si->sh_addr, si->sh_size, si->name);
1135 for (i
= 1; i
< pe
->s1
->nb_sections
; ++i
) {
1136 Section
*s
= pe
->s1
->sections
[i
];
1137 int type
= s
->sh_type
;
1138 int flags
= s
->sh_flags
;
1139 printf("section %-16s %-10s %5x %s,%s,%s\n",
1141 type
== SHT_PROGBITS
? "progbits" :
1142 type
== SHT_NOBITS
? "nobits" :
1143 type
== SHT_SYMTAB
? "symtab" :
1144 type
== SHT_STRTAB
? "strtab" :
1145 type
== SHT_RELX
? "rel" : "???",
1147 flags
& SHF_ALLOC
? "alloc" : "",
1148 flags
& SHF_WRITE
? "write" : "",
1149 flags
& SHF_EXECINSTR
? "exec" : ""
1152 pe
->s1
->verbose
= 2;
1155 tcc_free(section_order
);
1159 /* ------------------------------------------------------------- */
1160 static void pe_relocate_rva (struct pe_info
*pe
, Section
*s
)
1162 Section
*sr
= s
->reloc
;
1163 ElfW_Rel
*rel
, *rel_end
;
1164 rel_end
= (ElfW_Rel
*)(sr
->data
+ sr
->data_offset
);
1165 for(rel
= (ElfW_Rel
*)sr
->data
; rel
< rel_end
; rel
++) {
1166 if (ELFW(R_TYPE
)(rel
->r_info
) == R_XXX_RELATIVE
) {
1167 int sym_index
= ELFW(R_SYM
)(rel
->r_info
);
1168 DWORD addr
= s
->sh_addr
;
1170 ElfW(Sym
) *sym
= (ElfW(Sym
) *)symtab_section
->data
+ sym_index
;
1171 addr
= sym
->st_value
;
1173 // printf("reloc rva %08x %08x %s\n", (DWORD)rel->r_offset, addr, s->name);
1174 *(DWORD
*)(s
->data
+ rel
->r_offset
) += addr
- pe
->imagebase
;
1179 /*----------------------------------------------------------------------------*/
1181 static int pe_isafunc(int sym_index
)
1183 Section
*sr
= text_section
->reloc
;
1184 ElfW_Rel
*rel
, *rel_end
;
1185 Elf32_Word info
= ELF32_R_INFO(sym_index
, R_386_PC32
);
1188 rel_end
= (ElfW_Rel
*)(sr
->data
+ sr
->data_offset
);
1189 for (rel
= (ElfW_Rel
*)sr
->data
; rel
< rel_end
; rel
++)
1190 if (rel
->r_info
== info
)
1195 /*----------------------------------------------------------------------------*/
1196 static int pe_check_symbols(struct pe_info
*pe
)
1199 int sym_index
, sym_end
;
1202 pe_align_section(text_section
, 8);
1204 sym_end
= symtab_section
->data_offset
/ sizeof(ElfW(Sym
));
1205 for (sym_index
= 1; sym_index
< sym_end
; ++sym_index
) {
1207 sym
= (ElfW(Sym
) *)symtab_section
->data
+ sym_index
;
1208 if (sym
->st_shndx
== SHN_UNDEF
) {
1210 const char *name
= symtab_section
->link
->data
+ sym
->st_name
;
1211 unsigned type
= ELFW(ST_TYPE
)(sym
->st_info
);
1212 int imp_sym
= pe_find_import(pe
->s1
, sym
);
1213 struct import_symbol
*is
;
1218 if (type
== STT_NOTYPE
) {
1219 /* symbols from assembler have no type, find out which */
1220 if (pe_isafunc(sym_index
))
1226 is
= pe_add_import(pe
, imp_sym
);
1228 if (type
== STT_FUNC
) {
1229 unsigned long offset
= is
->thk_offset
;
1231 /* got aliased symbol, like stricmp and _stricmp */
1237 offset
= text_section
->data_offset
;
1238 /* add the 'jmp IAT[x]' instruction */
1239 #ifdef TCC_TARGET_ARM
1240 p
= section_ptr_add(text_section
, 8+4); // room for code and address
1241 (*(DWORD
*)(p
)) = 0xE59FC000; // arm code ldr ip, [pc] ; PC+8+0 = 0001xxxx
1242 (*(DWORD
*)(p
+2)) = 0xE59CF000; // arm code ldr pc, [ip]
1244 p
= section_ptr_add(text_section
, 8);
1246 #ifdef TCC_TARGET_X86_64
1247 *(DWORD
*)(p
+1) = (DWORD
)-4;
1250 /* add a helper symbol, will be patched later in
1252 sprintf(buffer
, "IAT.%s", name
);
1253 is
->iat_index
= put_elf_sym(
1254 symtab_section
, 0, sizeof(DWORD
),
1255 ELFW(ST_INFO
)(STB_GLOBAL
, STT_OBJECT
),
1256 0, SHN_UNDEF
, buffer
);
1257 #ifdef TCC_TARGET_ARM
1258 put_elf_reloc(symtab_section
, text_section
,
1259 offset
+ 8, R_XXX_THUNKFIX
, is
->iat_index
); // offset to IAT position
1261 put_elf_reloc(symtab_section
, text_section
,
1262 offset
+ 2, R_XXX_THUNKFIX
, is
->iat_index
);
1264 is
->thk_offset
= offset
;
1267 /* tcc_realloc might have altered sym's address */
1268 sym
= (ElfW(Sym
) *)symtab_section
->data
+ sym_index
;
1270 /* patch the original symbol */
1271 sym
->st_value
= offset
;
1272 sym
->st_shndx
= text_section
->sh_num
;
1273 sym
->st_other
&= ~1; /* do not export */
1277 if (type
== STT_OBJECT
) { /* data, ptr to that should be */
1278 if (0 == is
->iat_index
) {
1279 /* original symbol will be patched later in pe_build_imports */
1280 is
->iat_index
= sym_index
;
1286 tcc_error_noabort("undefined symbol '%s'", name
);
1289 } else if (pe
->s1
->rdynamic
1290 && ELFW(ST_BIND
)(sym
->st_info
) != STB_LOCAL
) {
1291 /* if -rdynamic option, then export all non local symbols */
1298 /*----------------------------------------------------------------------------*/
1299 #ifdef PE_PRINT_SECTIONS
1300 static void pe_print_section(FILE * f
, Section
* s
)
1302 /* just if you'r curious */
1306 e
= s
->data
+ s
->data_offset
;
1309 fprintf(f
, "section \"%s\"", s
->name
);
1311 fprintf(f
, "\nlink \"%s\"", s
->link
->name
);
1313 fprintf(f
, "\nreloc \"%s\"", s
->reloc
->name
);
1314 fprintf(f
, "\nv_addr %08X", (unsigned)s
->sh_addr
);
1315 fprintf(f
, "\ncontents %08X", (unsigned)l
);
1318 if (s
->sh_type
== SHT_NOBITS
)
1324 if (s
->sh_type
== SHT_SYMTAB
)
1325 m
= sizeof(ElfW(Sym
));
1326 else if (s
->sh_type
== SHT_RELX
)
1327 m
= sizeof(ElfW_Rel
);
1331 fprintf(f
, "%-8s", "offset");
1332 for (i
= 0; i
< m
; ++i
)
1333 fprintf(f
, " %02x", i
);
1336 if (s
->sh_type
== SHT_SYMTAB
|| s
->sh_type
== SHT_RELX
) {
1337 const char *fields1
[] = {
1348 const char *fields2
[] = {
1357 if (s
->sh_type
== SHT_SYMTAB
)
1358 p
= fields1
, n
= 106;
1360 p
= fields2
, n
= 58;
1362 for (i
= 0; p
[i
]; ++i
)
1363 fprintf(f
, "%6s", p
[i
]);
1364 fprintf(f
, " symbol");
1368 for (i
= 0; i
< n
; ++i
)
1374 fprintf(f
, "%08X", i
);
1375 for (n
= 0; n
< m
; ++n
) {
1377 fprintf(f
, " %02X", p
[i
+ n
]);
1382 if (s
->sh_type
== SHT_SYMTAB
) {
1383 ElfW(Sym
) *sym
= (ElfW(Sym
) *) (p
+ i
);
1384 const char *name
= s
->link
->data
+ sym
->st_name
;
1385 fprintf(f
, " %04X %04X %04X %02X %02X %02X %04X \"%s\"",
1386 (unsigned)sym
->st_name
,
1387 (unsigned)sym
->st_value
,
1388 (unsigned)sym
->st_size
,
1389 (unsigned)ELFW(ST_BIND
)(sym
->st_info
),
1390 (unsigned)ELFW(ST_TYPE
)(sym
->st_info
),
1391 (unsigned)sym
->st_other
,
1392 (unsigned)sym
->st_shndx
,
1395 } else if (s
->sh_type
== SHT_RELX
) {
1396 ElfW_Rel
*rel
= (ElfW_Rel
*) (p
+ i
);
1398 (ElfW(Sym
) *) s
->link
->data
+ ELFW(R_SYM
)(rel
->r_info
);
1399 const char *name
= s
->link
->link
->data
+ sym
->st_name
;
1400 fprintf(f
, " %04X %02X %04X \"%s\"",
1401 (unsigned)rel
->r_offset
,
1402 (unsigned)ELFW(R_TYPE
)(rel
->r_info
),
1403 (unsigned)ELFW(R_SYM
)(rel
->r_info
),
1407 for (n
= 0; n
< m
; ++n
) {
1410 if (b
< 32 || b
>= 127)
1412 fprintf(f
, "%c", b
);
1422 static void pe_print_sections(TCCState
*s1
, const char *fname
)
1427 f
= fopen(fname
, "w");
1428 for (i
= 1; i
< s1
->nb_sections
; ++i
) {
1429 s
= s1
->sections
[i
];
1430 pe_print_section(f
, s
);
1432 pe_print_section(f
, s1
->dynsymtab_section
);
1437 /* ------------------------------------------------------------- */
1438 /* helper function for load/store to insert one more indirection */
1440 ST_FUNC SValue
*pe_getimport(SValue
*sv
, SValue
*v2
)
1446 if ((sv
->r
& (VT_VALMASK
|VT_SYM
)) != (VT_CONST
|VT_SYM
) || (sv
->r2
!= VT_CONST
))
1449 if ((sym
->type
.t
& (VT_EXTERN
|VT_STATIC
)) != VT_EXTERN
)
1452 put_extern_sym(sym
, NULL
, 0, 0);
1453 esym
= &((ElfW(Sym
) *)symtab_section
->data
)[sym
->c
];
1454 if (!(esym
->st_other
& 4))
1457 // printf("import %04x %04x %04x %s\n", sv->type.t, sym->type.t, sv->r, get_tok_str(sv->sym->v, NULL));
1459 memset(v2
, 0, sizeof *v2
);
1460 v2
->type
.t
= VT_PTR
;
1461 v2
->r
= VT_CONST
| VT_SYM
| VT_LVAL
;
1464 r2
= get_reg(RC_INT
);
1475 v2
->type
.t
= sv
->type
.t
;
1476 v2
->r
|= sv
->r
& VT_LVAL
;
1480 ST_FUNC
int pe_putimport(TCCState
*s1
, int dllindex
, const char *name
, const void *value
)
1483 s1
->dynsymtab_section
,
1485 dllindex
, /* st_size */
1486 ELFW(ST_INFO
)(STB_GLOBAL
, STT_NOTYPE
),
1488 value
? SHN_ABS
: SHN_UNDEF
,
1493 static int add_dllref(TCCState
*s1
, const char *dllname
)
1495 DLLReference
*dllref
;
1497 for (i
= 0; i
< s1
->nb_loaded_dlls
; ++i
)
1498 if (0 == strcmp(s1
->loaded_dlls
[i
]->name
, dllname
))
1500 dllref
= tcc_mallocz(sizeof(DLLReference
) + strlen(dllname
));
1501 strcpy(dllref
->name
, dllname
);
1502 dynarray_add((void ***) &s1
->loaded_dlls
, &s1
->nb_loaded_dlls
, dllref
);
1503 return s1
->nb_loaded_dlls
;
1506 /* ------------------------------------------------------------- */
1508 static int read_mem(FILE *fp
, unsigned offset
, void *buffer
, unsigned len
)
1510 fseek(fp
, offset
, 0);
1511 return len
== fread(buffer
, 1, len
, fp
);
1514 /* -------------------------------------------------------------
1515 * This is for compiled windows resources in 'coff' format
1516 * as generated by 'windres.exe -O coff ...'.
1519 static int pe_load_res(TCCState
*s1
, FILE *fp
)
1521 struct pe_rsrc_header hdr
;
1522 Section
*rsrc_section
;
1527 if (!read_mem(fp
, 0, &hdr
, sizeof hdr
))
1530 if (hdr
.filehdr
.Machine
!= 0x014C
1531 || hdr
.filehdr
.NumberOfSections
!= 1
1532 || strcmp(hdr
.sectionhdr
.Name
, ".rsrc") != 0)
1535 rsrc_section
= new_section(s1
, ".rsrc", SHT_PROGBITS
, SHF_ALLOC
);
1536 ptr
= section_ptr_add(rsrc_section
, hdr
.sectionhdr
.SizeOfRawData
);
1537 offs
= hdr
.sectionhdr
.PointerToRawData
;
1538 if (!read_mem(fp
, offs
, ptr
, hdr
.sectionhdr
.SizeOfRawData
))
1540 offs
= hdr
.sectionhdr
.PointerToRelocations
;
1541 for (i
= 0; i
< hdr
.sectionhdr
.NumberOfRelocations
; ++i
)
1543 struct pe_rsrc_reloc rel
;
1544 if (!read_mem(fp
, offs
, &rel
, sizeof rel
))
1546 // printf("rsrc_reloc: %x %x %x\n", rel.offset, rel.size, rel.type);
1547 if (rel
.type
!= 7) /* DIR32NB */
1549 put_elf_reloc(symtab_section
, rsrc_section
,
1550 rel
.offset
, R_XXX_RELATIVE
, 0);
1558 /* ------------------------------------------------------------- */
1559 static char *trimfront(char *p
)
1561 while (*p
&& (unsigned char)*p
<= ' ')
1566 static char *trimback(char *a
, char *e
)
1568 while (e
> a
&& (unsigned char)e
[-1] <= ' ')
1574 static char *get_line(char *line
, int size
, FILE *fp
)
1576 if (NULL
== fgets(line
, size
, fp
))
1578 trimback(line
, strchr(line
, 0));
1579 return trimfront(line
);
1582 /* ------------------------------------------------------------- */
1583 static int pe_load_def(TCCState
*s1
, FILE *fp
)
1585 int state
= 0, ret
= -1, dllindex
= 0;
1586 char line
[400], dllname
[80], *p
;
1589 p
= get_line(line
, sizeof line
, fp
);
1592 if (0 == *p
|| ';' == *p
)
1596 if (0 != strnicmp(p
, "LIBRARY", 7))
1598 strcpy(dllname
, trimfront(p
+7));
1603 if (0 != stricmp(p
, "EXPORTS"))
1609 dllindex
= add_dllref(s1
, dllname
);
1613 pe_putimport(s1
, dllindex
, p
, NULL
);
1622 /* ------------------------------------------------------------- */
1623 #define TINY_IMPDEF_GET_EXPORT_NAMES_ONLY
1624 #include "win32/tools/tiny_impdef.c"
1626 static int pe_load_dll(TCCState
*s1
, const char *dllname
, FILE *fp
)
1630 p
= get_export_names(fp
);
1633 index
= add_dllref(s1
, dllname
);
1634 for (q
= p
; *q
; q
+= 1 + strlen(q
))
1635 pe_putimport(s1
, index
, q
, NULL
);
1640 /* ------------------------------------------------------------- */
1641 ST_FUNC
int pe_load_file(struct TCCState
*s1
, const char *filename
, int fd
)
1643 FILE *fp
= fdopen(dup(fd
), "rb");
1647 if (0 == strcmp(tcc_fileextension(filename
), ".def"))
1648 ret
= pe_load_def(s1
, fp
);
1649 else if (pe_load_res(s1
, fp
) == 0)
1651 else if (read_mem(fp
, 0, buf
, sizeof buf
) && 0 == strncmp(buf
, "MZ", 2))
1652 ret
= pe_load_dll(s1
, tcc_basename(filename
), fp
);
1658 /* ------------------------------------------------------------- */
1659 #ifdef TCC_TARGET_X86_64
1660 static unsigned pe_add_uwwind_info(TCCState
*s1
)
1662 if (NULL
== s1
->uw_pdata
) {
1663 s1
->uw_pdata
= find_section(tcc_state
, ".pdata");
1664 s1
->uw_pdata
->sh_addralign
= 4;
1665 s1
->uw_sym
= put_elf_sym(symtab_section
, 0, 0, 0, 0, text_section
->sh_num
, NULL
);
1668 if (0 == s1
->uw_offs
) {
1669 /* As our functions all have the same stackframe, we use one entry for all */
1670 static const unsigned char uw_info
[] = {
1671 0x01, // UBYTE: 3 Version , UBYTE: 5 Flags
1672 0x04, // UBYTE Size of prolog
1673 0x02, // UBYTE Count of unwind codes
1674 0x05, // UBYTE: 4 Frame Register (rbp), UBYTE: 4 Frame Register offset (scaled)
1675 // USHORT * n Unwind codes array
1676 // 0x0b, 0x01, 0xff, 0xff, // stack size
1677 0x04, 0x03, // set frame ptr (mov rsp -> rbp)
1678 0x01, 0x50 // push reg (rbp)
1681 Section
*s
= text_section
;
1684 section_ptr_add(s
, -s
->data_offset
& 3); /* align */
1685 s1
->uw_offs
= s
->data_offset
;
1686 p
= section_ptr_add(s
, sizeof uw_info
);
1687 memcpy(p
, uw_info
, sizeof uw_info
);
1693 ST_FUNC
void pe_add_unwind_data(unsigned start
, unsigned end
, unsigned stack
)
1695 TCCState
*s1
= tcc_state
;
1698 struct /* _RUNTIME_FUNCTION */ {
1704 d
= pe_add_uwwind_info(s1
);
1706 o
= pd
->data_offset
;
1707 p
= section_ptr_add(pd
, sizeof *p
);
1709 /* record this function */
1710 p
->BeginAddress
= start
;
1711 p
->EndAddress
= end
;
1714 /* put relocations on it */
1715 for (n
= o
+ sizeof *p
; o
< n
; o
+= sizeof p
->BeginAddress
)
1716 put_elf_reloc(symtab_section
, pd
, o
, R_X86_64_RELATIVE
, s1
->uw_sym
);
1719 /* ------------------------------------------------------------- */
1720 #ifdef TCC_TARGET_X86_64
1721 #define PE_STDSYM(n,s) n
1723 #define PE_STDSYM(n,s) "_" n s
1726 static void pe_add_runtime_ex(TCCState
*s1
, struct pe_info
*pe
)
1728 const char *start_symbol
;
1729 unsigned long addr
= 0;
1732 if (find_elf_sym(symtab_section
, PE_STDSYM("WinMain","@16")))
1735 if (TCC_OUTPUT_DLL
== s1
->output_type
) {
1737 /* need this for 'tccelf.c:relocate_section()' */
1738 s1
->output_type
= TCC_OUTPUT_EXE
;
1744 TCC_OUTPUT_MEMORY
== s1
->output_type
1745 ? PE_GUI
== pe_type
? "__runwinmain" : "_main"
1746 : PE_DLL
== pe_type
? PE_STDSYM("__dllstart","@12")
1747 : PE_GUI
== pe_type
? "__winstart" : "__start"
1750 if (!s1
->leading_underscore
|| strchr(start_symbol
, '@')) {
1752 if (start_symbol
[0] != '_')
1753 start_symbol
= NULL
;
1756 /* grab the startup code from libtcc1 */
1758 add_elf_sym(symtab_section
,
1760 ELFW(ST_INFO
)(STB_GLOBAL
, STT_NOTYPE
), 0,
1761 SHN_UNDEF
, start_symbol
);
1763 if (0 == s1
->nostdlib
) {
1764 static const char *libs
[] = {
1765 "tcc1", "msvcrt", "kernel32", "user32", "gdi32", NULL
1767 const char **pp
, *p
;
1768 for (pp
= libs
; 0 != (p
= *pp
); ++pp
) {
1770 if (PE_DLL
!= pe_type
&& PE_GUI
!= pe_type
)
1772 } else if (tcc_add_library(s1
, p
) < 0)
1773 tcc_error_noabort("cannot find library: %s", p
);
1777 if (TCC_OUTPUT_MEMORY
== s1
->output_type
)
1781 addr
= (uplong
)tcc_get_symbol_err(s1
, start_symbol
);
1782 if (PE_RUN
== pe_type
&& addr
)
1783 /* for -run GUI's, put '_runwinmain' instead of 'main' */
1784 add_elf_sym(symtab_section
,
1786 ELFW(ST_INFO
)(STB_GLOBAL
, STT_NOTYPE
), 0,
1787 text_section
->sh_num
, "main");
1791 pe
->start_addr
= addr
;
1794 ST_FUNC
int pe_output_file(TCCState
* s1
, const char *filename
)
1800 memset(&pe
, 0, sizeof pe
);
1801 pe
.filename
= filename
;
1805 pe_add_runtime_ex(s1
, &pe
);
1806 relocate_common_syms(); /* assign bss adresses */
1807 tcc_add_linker_symbols(s1
);
1809 ret
= pe_check_symbols(&pe
);
1812 else if (filename
) {
1813 if (PE_DLL
== pe
.type
) {
1814 pe
.reloc
= new_section(pe
.s1
, ".reloc", SHT_PROGBITS
, 0);
1815 /* XXX: check if is correct for arm-pe target */
1816 pe
.imagebase
= 0x10000000;
1818 #if defined(TCC_TARGET_ARM)
1819 pe
.imagebase
= 0x00010000;
1821 pe
.imagebase
= 0x00400000;
1825 /* if no subsystem specified, we use "console" subsystem by default */
1826 if (s1
->pe_subsystem
!= 0)
1827 pe
.subsystem
= s1
->pe_subsystem
;
1829 #if defined(TCC_TARGET_ARM)
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
;
1854 pe_assign_addresses(&pe
);
1855 relocate_syms(s1
, 0);
1856 for (i
= 1; i
< s1
->nb_sections
; ++i
) {
1857 Section
*s
= s1
->sections
[i
];
1859 relocate_section(s1
, s
);
1860 pe_relocate_rva(&pe
, s
);
1866 ret
= pe_write(&pe
);
1867 tcc_free(pe
.sec_info
);
1869 #ifdef TCC_IS_NATIVE
1870 pe
.thunk
= data_section
;
1871 pe_build_imports(&pe
);
1875 #ifdef PE_PRINT_SECTIONS
1876 pe_print_sections(s1
, "tcc.log");
1881 /* ------------------------------------------------------------- */