2 * TCCPE.C - PE file output for the TinyC Compiler
4 * Copyright (c) 2005 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
21 typedef unsigned char BYTE
;
22 typedef unsigned short WORD
;
23 typedef unsigned long DWORD
;
26 /* XXX: move that to TCC ? */
29 /* definitions below are from winnt.h */
31 typedef struct _IMAGE_DOS_HEADER
{ /* DOS .EXE header */
32 WORD e_magic
; /* Magic number */
33 WORD e_cblp
; /* Bytes on last page of file */
34 WORD e_cp
; /* Pages in file */
35 WORD e_crlc
; /* Relocations */
36 WORD e_cparhdr
; /* Size of header in paragraphs */
37 WORD e_minalloc
; /* Minimum extra paragraphs needed */
38 WORD e_maxalloc
; /* Maximum extra paragraphs needed */
39 WORD e_ss
; /* Initial (relative) SS value */
40 WORD e_sp
; /* Initial SP value */
41 WORD e_csum
; /* Checksum */
42 WORD e_ip
; /* Initial IP value */
43 WORD e_cs
; /* Initial (relative) CS value */
44 WORD e_lfarlc
; /* File address of relocation table */
45 WORD e_ovno
; /* Overlay number */
46 WORD e_res
[4]; /* Reserved words */
47 WORD e_oemid
; /* OEM identifier (for e_oeminfo) */
48 WORD e_oeminfo
; /* OEM information; e_oemid specific */
49 WORD e_res2
[10]; /* Reserved words */
50 DWORD e_lfanew
; /* File address of new exe header */
53 } IMAGE_DOS_HEADER
, *PIMAGE_DOS_HEADER
;
55 #define IMAGE_NT_SIGNATURE 0x00004550 /* PE00 */
56 #define SIZE_OF_NT_SIGNATURE 4
58 typedef struct _IMAGE_FILE_HEADER
{
60 WORD NumberOfSections
;
62 DWORD PointerToSymbolTable
;
63 DWORD NumberOfSymbols
;
64 WORD SizeOfOptionalHeader
;
66 } IMAGE_FILE_HEADER
, *PIMAGE_FILE_HEADER
;
69 #define IMAGE_SIZEOF_FILE_HEADER 20
71 typedef struct _IMAGE_DATA_DIRECTORY
{
74 } IMAGE_DATA_DIRECTORY
, *PIMAGE_DATA_DIRECTORY
;
77 typedef struct _IMAGE_OPTIONAL_HEADER
{
78 /* Standard fields. */
80 BYTE MajorLinkerVersion
;
81 BYTE MinorLinkerVersion
;
83 DWORD SizeOfInitializedData
;
84 DWORD SizeOfUninitializedData
;
85 DWORD AddressOfEntryPoint
;
89 /* NT additional fields. */
91 DWORD SectionAlignment
;
93 WORD MajorOperatingSystemVersion
;
94 WORD MinorOperatingSystemVersion
;
95 WORD MajorImageVersion
;
96 WORD MinorImageVersion
;
97 WORD MajorSubsystemVersion
;
98 WORD MinorSubsystemVersion
;
99 DWORD Win32VersionValue
;
104 WORD DllCharacteristics
;
105 DWORD SizeOfStackReserve
;
106 DWORD SizeOfStackCommit
;
107 DWORD SizeOfHeapReserve
;
108 DWORD SizeOfHeapCommit
;
110 DWORD NumberOfRvaAndSizes
;
111 IMAGE_DATA_DIRECTORY DataDirectory
[16];
113 } IMAGE_OPTIONAL_HEADER32
, *PIMAGE_OPTIONAL_HEADER32
;
116 #define IMAGE_DIRECTORY_ENTRY_EXPORT 0 /* Export Directory */
117 #define IMAGE_DIRECTORY_ENTRY_IMPORT 1 /* Import Directory */
118 #define IMAGE_DIRECTORY_ENTRY_RESOURCE 2 /* Resource Directory */
119 #define IMAGE_DIRECTORY_ENTRY_EXCEPTION 3 /* Exception Directory */
120 #define IMAGE_DIRECTORY_ENTRY_SECURITY 4 /* Security Directory */
121 #define IMAGE_DIRECTORY_ENTRY_BASERELOC 5 /* Base Relocation Table */
122 #define IMAGE_DIRECTORY_ENTRY_DEBUG 6 /* Debug Directory */
123 /* IMAGE_DIRECTORY_ENTRY_COPYRIGHT 7 (X86 usage) */
124 #define IMAGE_DIRECTORY_ENTRY_ARCHITECTURE 7 /* Architecture Specific Data */
125 #define IMAGE_DIRECTORY_ENTRY_GLOBALPTR 8 /* RVA of GP */
126 #define IMAGE_DIRECTORY_ENTRY_TLS 9 /* TLS Directory */
127 #define IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG 10 /* Load Configuration Directory */
128 #define IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT 11 /* Bound Import Directory in headers */
129 #define IMAGE_DIRECTORY_ENTRY_IAT 12 /* Import Address Table */
130 #define IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT 13 /* Delay Load Import Descriptors */
131 #define IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR 14 /* COM Runtime descriptor */
133 /* Section header format. */
134 #define IMAGE_SIZEOF_SHORT_NAME 8
136 typedef struct _IMAGE_SECTION_HEADER
{
137 BYTE Name
[IMAGE_SIZEOF_SHORT_NAME
];
139 DWORD PhysicalAddress
;
142 DWORD VirtualAddress
;
144 DWORD PointerToRawData
;
145 DWORD PointerToRelocations
;
146 DWORD PointerToLinenumbers
;
147 WORD NumberOfRelocations
;
148 WORD NumberOfLinenumbers
;
149 DWORD Characteristics
;
150 } IMAGE_SECTION_HEADER
, *PIMAGE_SECTION_HEADER
;
152 #define IMAGE_SIZEOF_SECTION_HEADER 40
154 /* ----------------------------------------------------------- */
155 typedef struct _IMAGE_BASE_RELOCATION
{
156 DWORD VirtualAddress
;
158 // WORD TypeOffset[1];
159 } IMAGE_BASE_RELOCATION
;
161 #define IMAGE_SIZEOF_BASE_RELOCATION 8
163 #define IMAGE_REL_BASED_ABSOLUTE 0
164 #define IMAGE_REL_BASED_HIGH 1
165 #define IMAGE_REL_BASED_LOW 2
166 #define IMAGE_REL_BASED_HIGHLOW 3
167 #define IMAGE_REL_BASED_HIGHADJ 4
168 #define IMAGE_REL_BASED_MIPS_JMPADDR 5
169 #define IMAGE_REL_BASED_SECTION 6
170 #define IMAGE_REL_BASED_REL32 7
172 /* ----------------------------------------------------------- */
174 /* ----------------------------------------------------------- */
175 IMAGE_DOS_HEADER pe_dos_hdr
= {
176 0x5A4D, /*WORD e_magic; Magic number */
177 0x0090, /*WORD e_cblp; Bytes on last page of file */
178 0x0003, /*WORD e_cp; Pages in file */
179 0x0000, /*WORD e_crlc; Relocations */
181 0x0004, /*WORD e_cparhdr; Size of header in paragraphs */
182 0x0000, /*WORD e_minalloc; Minimum extra paragraphs needed */
183 0xFFFF, /*WORD e_maxalloc; Maximum extra paragraphs needed */
184 0x0000, /*WORD e_ss; Initial (relative) SS value */
186 0x00B8, /*WORD e_sp; Initial SP value */
187 0x0000, /*WORD e_csum; Checksum */
188 0x0000, /*WORD e_ip; Initial IP value */
189 0x0000, /*WORD e_cs; Initial (relative) CS value */
190 0x0040, /*WORD e_lfarlc; File address of relocation table */
191 0x0000, /*WORD e_ovno; Overlay number */
192 {0, 0, 0, 0}, /*WORD e_res[4]; Reserved words */
193 0x0000, /*WORD e_oemid; OEM identifier (for e_oeminfo) */
194 0x0000, /*WORD e_oeminfo; OEM information; e_oemid specific */
195 {0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, /*WORD e_res2[10]; Reserved words */
196 0x00000080, /*DWORD e_lfanew; File address of new exe header */
197 { /* 14 code bytes + "This program cannot be run in DOS mode.\r\r\n$" + 6 * 0x00 */
198 /*0040 */ 0x0e, 0x1f, 0xba, 0x0e, 0x00, 0xb4, 0x09, 0xcd, 0x21, 0xb8,
199 0x01, 0x4c, 0xcd, 0x21, 0x54, 0x68,
200 /*0050 */ 0x69, 0x73, 0x20, 0x70, 0x72, 0x6f, 0x67, 0x72, 0x61, 0x6d,
201 0x20, 0x63, 0x61, 0x6e, 0x6e, 0x6f,
202 /*0060 */ 0x74, 0x20, 0x62, 0x65, 0x20, 0x72, 0x75, 0x6e, 0x20, 0x69,
203 0x6e, 0x20, 0x44, 0x4f, 0x53, 0x20,
204 /*0070 */ 0x6d, 0x6f, 0x64, 0x65, 0x2e, 0x0d, 0x0d, 0x0a, 0x24, 0x00,
205 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
210 DWORD pe_magic
= IMAGE_NT_SIGNATURE
;
212 IMAGE_FILE_HEADER pe_file_hdr
= {
213 0x014C, /*WORD Machine; */
214 0x0003, /*WORD NumberOfSections; */
215 0x00000000, /*DWORD TimeDateStamp; */
216 0x00000000, /*DWORD PointerToSymbolTable; */
217 0x00000000, /*DWORD NumberOfSymbols; */
218 0x00E0, /*WORD SizeOfOptionalHeader; */
219 0x030F /*WORD Characteristics; */
222 IMAGE_OPTIONAL_HEADER32 pe_opt_hdr
= {
223 /* Standard fields. */
224 0x010B, /*WORD Magic; */
225 0x06, /*BYTE MajorLinkerVersion; */
226 0x00, /*BYTE MinorLinkerVersion; */
227 0x00000000, /*DWORD SizeOfCode; */
228 0x00000000, /*DWORD SizeOfInitializedData; */
229 0x00000000, /*DWORD SizeOfUninitializedData; */
230 0x00000000, /*DWORD AddressOfEntryPoint; */
231 0x00000000, /*DWORD BaseOfCode; */
232 0x00000000, /*DWORD BaseOfData; */
234 /* NT additional fields. */
235 0x00400000, /*DWORD ImageBase; */
236 0x00001000, /*DWORD SectionAlignment; */
237 0x00000200, /*DWORD FileAlignment; */
238 0x0004, /*WORD MajorOperatingSystemVersion; */
239 0x0000, /*WORD MinorOperatingSystemVersion; */
240 0x0000, /*WORD MajorImageVersion; */
241 0x0000, /*WORD MinorImageVersion; */
242 0x0004, /*WORD MajorSubsystemVersion; */
243 0x0000, /*WORD MinorSubsystemVersion; */
244 0x00000000, /*DWORD Win32VersionValue; */
245 0x00000000, /*DWORD SizeOfImage; */
246 0x00000200, /*DWORD SizeOfHeaders; */
247 0x00000000, /*DWORD CheckSum; */
248 0x0002, /*WORD Subsystem; */
249 0x0000, /*WORD DllCharacteristics; */
250 0x00100000, /*DWORD SizeOfStackReserve; */
251 0x00001000, /*DWORD SizeOfStackCommit; */
252 0x00100000, /*DWORD SizeOfHeapReserve; */
253 0x00001000, /*DWORD SizeOfHeapCommit; */
254 0x00000000, /*DWORD LoaderFlags; */
255 0x00000010, /*DWORD NumberOfRvaAndSizes; */
257 /* IMAGE_DATA_DIRECTORY DataDirectory[16]; */
258 {{0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0},
259 {0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}}
262 /*----------------------------------------------------------------------------*/
264 /*----------------------------------------------------------------------------*/
266 struct pe_import_header
{
270 DWORD lib_name_offset
;
274 struct pe_export_header
{
275 DWORD Characteristics
;
280 DWORD NumberOfFunctions
;
282 DWORD AddressOfFunctions
;
283 DWORD AddressOfNames
;
284 DWORD AddressOfNameOrdinals
;
287 struct pe_reloc_header
{
292 /* ------------------------------------------------------------- */
293 /* internal temporary structures */
295 ST
const char *pe_sec_names
[] = {
316 ST DWORD pe_flags
[] = {
317 0x60000020, /* ".text", */
318 0xC0000040, /* ".data", */
319 0xC0000080, /* ".bss", */
320 0x40000040, /* ".rsrc", */
321 0x42000040, /* ".reloc", */
322 0x42000802, /* ".stab", */
323 0x42000802 /* ".stabstr", */
326 struct section_info
{
327 struct section_info
*next
;
335 struct import_symbol
{
340 struct pe_import_info
{
343 struct import_symbol
**symbols
;
347 const char *filename
;
357 struct section_info sh_info
[pe_sec_number
];
359 struct pe_import_info
**imp_info
;
366 /* ------------------------------------------------------------- */
367 #define PE_MERGE_DATA
368 // #define PE_PRINT_SECTIONS
374 void error_noabort(const char *, ...);
383 ST
int pe_find_import(TCCState
* s1
, const char *symbol
, char *ret
)
385 int sym_index
= find_elf_sym(s1
->dynsymtab_section
, symbol
);
386 if (0 == sym_index
&&
387 !memcmp(symbol
, "__imp__", 7)) {
388 /* Hm, maybe it's '_symbol' instead of '__imp__symbol' */
390 sym_index
= find_elf_sym(s1
->dynsymtab_section
, symbol
);
401 void *resolve_sym(struct TCCState
*s1
, const char *symbol
, int type
)
403 char buffer
[100], *p
= buffer
;
405 int sym_index
= pe_find_import(s1
, symbol
, p
);
407 const char *dll_name
;
411 dll_index
= ((Elf32_Sym
*) s1
->dynsymtab_section
->data
)[sym_index
].
413 dll_name
= s1
->loaded_dlls
[dll_index
]->name
;
414 hm
= GetModuleHandleA(dll_name
);
416 hm
= LoadLibraryA(dll_name
);
418 a
= GetProcAddress(hm
, buffer
);
419 if (a
&& STT_OBJECT
== type
) {
420 // need to return a pointer to the address for data objects
421 dynarray_add(&pe_imp
, &nb_pe_imp
, a
);
422 a
= &pe_imp
[nb_pe_imp
- 1];
430 #define for_sym_in_symtab(sym) \
431 for (sym = (Elf32_Sym *)symtab_section->data + 1; \
432 sym < (Elf32_Sym *)(symtab_section->data + \
433 symtab_section->data_offset); \
436 #define pe_set_datadir(dir,addr,size) \
437 pe_opt_hdr.DataDirectory[dir].VirtualAddress = addr, \
438 pe_opt_hdr.DataDirectory[dir].Size = size
440 /*----------------------------------------------------------------------------*/
441 ST
void dynarray_reset(void ***pp
, int *n
)
444 for (i
= 0; i
< *n
; ++i
)
451 ST
int dynarray_assoc(void **pp
, int n
, int key
)
454 for (i
= 0; i
< n
; ++i
, ++pp
)
455 if (key
== **(int **) pp
)
461 ST DWORD
umin(DWORD a
, DWORD b
)
463 return a
< b
? a
: b
;
467 ST DWORD
umax(DWORD a
, DWORD b
)
469 return a
< b
? b
: a
;
472 ST
void pe_fpad(FILE * fp
, DWORD new_pos
)
474 DWORD pos
= ftell(fp
);
475 while (++pos
<= new_pos
)
479 ST DWORD
pe_file_align(DWORD n
)
481 return (n
+ (0x200 - 1)) & ~(0x200 - 1);
484 ST DWORD
pe_virtual_align(DWORD n
)
486 return (n
+ (0x1000 - 1)) & ~(0x1000 - 1);
489 ST
void pe_align_section(Section
* s
, int a
)
491 int i
= s
->data_offset
& (a
- 1);
493 section_ptr_add(s
, a
- i
);
497 /*----------------------------------------------------------------------------*/
498 ST
int pe_write_pe(struct pe_info
*pe
)
503 IMAGE_SECTION_HEADER ish
[pe_sec_number
], *psh
;
506 op
= fopen(pe
->filename
, "wb");
508 error_noabort("could not create file: %s", pe
->filename
);
512 memset(&ish
, 0, sizeof ish
);
514 pe
->sizeofheaders
= pe_file_align(sizeof pe_dos_hdr
520 sizeof(IMAGE_SECTION_HEADER
)
523 file_offset
= pe
->sizeofheaders
;
524 pe_fpad(op
, file_offset
);
527 printf("-------------------------------"
528 "\n virt file size section" "\n");
530 for (i
= 0; i
< pe
->sec_count
; ++i
) {
531 struct section_info
*si
= pe
->sh_info
+ i
;
532 const char *sh_name
= pe_sec_names
[si
->id
];
533 unsigned long addr
= si
->sh_addr
- pe
->imagebase
;
534 unsigned long size
= si
->sh_size
;
537 printf("%6lx %6lx %6lx %s\n",
538 addr
, file_offset
, size
, sh_name
);
542 pe_opt_hdr
.BaseOfCode
= addr
;
543 pe_opt_hdr
.AddressOfEntryPoint
= addr
+ pe
->start_addr
;
547 pe_opt_hdr
.BaseOfData
= addr
;
549 pe_set_datadir(IMAGE_DIRECTORY_ENTRY_IMPORT
,
550 pe
->imp_offs
+ addr
, pe
->imp_size
);
551 pe_set_datadir(IMAGE_DIRECTORY_ENTRY_IAT
,
552 pe
->iat_offs
+ addr
, pe
->iat_size
);
555 pe_set_datadir(IMAGE_DIRECTORY_ENTRY_EXPORT
,
556 pe
->exp_offs
+ addr
, pe
->exp_size
);
564 pe_set_datadir(IMAGE_DIRECTORY_ENTRY_BASERELOC
, addr
, size
);
568 pe_set_datadir(IMAGE_DIRECTORY_ENTRY_RESOURCE
, addr
, size
);
578 psh
= &ish
[sec_index
++];
579 strcpy((char *) psh
->Name
, sh_name
);
581 psh
->Characteristics
= pe_flags
[si
->id
];
582 psh
->VirtualAddress
= addr
;
583 psh
->Misc
.VirtualSize
= size
;
584 pe_opt_hdr
.SizeOfImage
=
585 umax(psh
->VirtualAddress
+ psh
->Misc
.VirtualSize
,
586 pe_opt_hdr
.SizeOfImage
);
589 psh
->PointerToRawData
= file_offset
;
590 fwrite(si
->data
, 1, si
->data_size
, op
);
591 file_offset
= pe_file_align(file_offset
+ si
->data_size
);
592 psh
->SizeOfRawData
= file_offset
- psh
->PointerToRawData
;
593 pe_fpad(op
, file_offset
);
597 /*----------------------------------------------------- */
599 pe_file_hdr
.NumberOfSections
= sec_index
;
600 pe_opt_hdr
.SizeOfHeaders
= pe
->sizeofheaders
;
601 pe_opt_hdr
.ImageBase
= pe
->imagebase
;
602 if (PE_DLL
== pe_type
)
603 pe_file_hdr
.Characteristics
= 0x230E;
604 else if (PE_GUI
!= pe_type
)
605 pe_opt_hdr
.Subsystem
= 3;
607 fseek(op
, SEEK_SET
, 0);
608 fwrite(&pe_dos_hdr
, 1, sizeof pe_dos_hdr
, op
);
609 fwrite(&pe_magic
, 1, sizeof pe_magic
, op
);
610 fwrite(&pe_file_hdr
, 1, sizeof pe_file_hdr
, op
);
611 fwrite(&pe_opt_hdr
, 1, sizeof pe_opt_hdr
, op
);
612 for (i
= 0; i
< sec_index
; ++i
)
613 fwrite(&ish
[i
], 1, sizeof(IMAGE_SECTION_HEADER
), op
);
617 printf("-------------------------------\n");
619 printf("<-- %s (%lu bytes)\n", pe
->filename
, file_offset
);
624 /*----------------------------------------------------------------------------*/
625 ST
int pe_add_import(struct pe_info
*pe
, int sym_index
, DWORD offset
)
629 struct pe_import_info
*p
;
630 struct import_symbol
*s
;
633 ((Elf32_Sym
*) pe
->s1
->dynsymtab_section
->data
)[sym_index
].
635 i
= dynarray_assoc((void **) pe
->imp_info
, pe
->imp_count
, dll_index
);
640 p
= tcc_mallocz(sizeof *p
);
641 p
->dll_index
= dll_index
;
642 dynarray_add((void ***) &pe
->imp_info
, &pe
->imp_count
, p
);
645 i
= dynarray_assoc((void **) p
->symbols
, p
->sym_count
, sym_index
);
648 s
= tcc_mallocz(sizeof *s
);
649 s
->sym_index
= sym_index
;
651 dynarray_add((void ***) &p
->symbols
, &p
->sym_count
, s
);
657 /*----------------------------------------------------------------------------*/
658 ST
void pe_build_imports(struct pe_info
*pe
)
660 int thk_ptr
, ent_ptr
, dll_ptr
, sym_cnt
, i
;
661 DWORD voffset
= pe
->thunk
->sh_addr
- pe
->imagebase
;
662 int ndlls
= pe
->imp_count
;
664 for (sym_cnt
= i
= 0; i
< ndlls
; ++i
)
665 sym_cnt
+= pe
->imp_info
[i
]->sym_count
;
670 pe_align_section(pe
->thunk
, 16);
672 pe
->imp_offs
= dll_ptr
= pe
->thunk
->data_offset
;
673 pe
->imp_size
= (ndlls
+ 1) * sizeof(struct pe_import_header
);
674 pe
->iat_offs
= dll_ptr
+ pe
->imp_size
;
675 pe
->iat_size
= (sym_cnt
+ ndlls
) * sizeof(DWORD
);
676 section_ptr_add(pe
->thunk
, pe
->imp_size
+ 2 * pe
->iat_size
);
678 thk_ptr
= pe
->iat_offs
;
679 ent_ptr
= pe
->iat_offs
+ pe
->iat_size
;
680 for (i
= 0; i
< pe
->imp_count
; ++i
) {
681 struct pe_import_header
*hdr
;
683 struct pe_import_info
*p
= pe
->imp_info
[i
];
684 const char *name
= pe
->s1
->loaded_dlls
[p
->dll_index
]->name
;
686 /* put the dll name into the import header */
687 if (0 == strncmp(name
, "lib", 3))
689 v
= put_elf_str(pe
->thunk
, name
);
691 hdr
= (struct pe_import_header
*) (pe
->thunk
->data
+ dll_ptr
);
692 hdr
->first_thunk
= thk_ptr
+ voffset
;
693 hdr
->first_entry
= ent_ptr
+ voffset
;
694 hdr
->lib_name_offset
= v
+ voffset
;
696 for (k
= 0, n
= p
->sym_count
; k
<= n
; ++k
) {
698 DWORD offset
= p
->symbols
[k
]->offset
;
699 int sym_index
= p
->symbols
[k
]->sym_index
;
701 (Elf32_Sym
*) pe
->s1
->dynsymtab_section
->data
+
704 pe
->s1
->dynsymtab_section
->link
->data
+ sym
->st_name
;
706 if (offset
& 0x80000000) { /* ref to data */
708 &((Elf32_Sym
*) symtab_section
->
709 data
)[offset
& 0x7FFFFFFF];
710 sym
->st_value
= thk_ptr
;
711 sym
->st_shndx
= pe
->thunk
->sh_num
;
712 } else { /* ref to function */
715 sprintf(buffer
, "IAT.%s", name
);
717 put_elf_sym(symtab_section
, thk_ptr
, sizeof(DWORD
),
718 ELF32_ST_INFO(STB_GLOBAL
, STT_OBJECT
),
719 0, pe
->thunk
->sh_num
, buffer
);
721 put_elf_reloc(symtab_section
, text_section
, offset
, R_386_32
, /*R_JMP_SLOT, */
724 v
= pe
->thunk
->data_offset
+ voffset
;
725 section_ptr_add(pe
->thunk
, sizeof(WORD
)); /* hint, not used */
726 put_elf_str(pe
->thunk
, name
);
728 v
= 0; // last entry is zero
730 *(DWORD
*) (pe
->thunk
->data
+ thk_ptr
) =
731 *(DWORD
*) (pe
->thunk
->data
+ ent_ptr
) = v
;
732 thk_ptr
+= sizeof(DWORD
);
733 ent_ptr
+= sizeof(DWORD
);
735 dll_ptr
+= sizeof(struct pe_import_header
);
736 dynarray_reset((void ***) &p
->symbols
, &p
->sym_count
);
738 dynarray_reset((void ***) &pe
->imp_info
, &pe
->imp_count
);
741 /* ------------------------------------------------------------- */
742 ST
int sym_cmp(const void *va
, const void *vb
)
744 Elf32_Sym
*sa
= (Elf32_Sym
*)symtab_section
->data
+ *(int*)va
;
745 Elf32_Sym
*sb
= (Elf32_Sym
*)symtab_section
->data
+ *(int*)vb
;
746 const char *ca
= symtab_section
->link
->data
+ sa
->st_name
;
747 const char *cb
= symtab_section
->link
->data
+ sb
->st_name
;
748 return strcmp(ca
, cb
);
751 ST
void pe_build_exports(struct pe_info
*pe
)
754 DWORD func_offset
, voffset
;
755 struct pe_export_header
*hdr
;
756 int sym_count
, n
, ord
, *sorted
;
758 voffset
= pe
->thunk
->sh_addr
- pe
->imagebase
;
759 sym_count
= 0, n
= 1, sorted
= NULL
;
761 // for simplicity only functions are exported
762 for_sym_in_symtab(sym
)
764 if ((sym
->st_other
& 1)
765 && sym
->st_shndx
== text_section
->sh_num
)
766 dynarray_add((void***)&sorted
, &sym_count
, (void*)n
);
773 qsort (sorted
, sym_count
, sizeof sorted
[0], sym_cmp
);
774 pe_align_section(pe
->thunk
, 16);
776 pe
->exp_offs
= pe
->thunk
->data_offset
;
777 hdr
= section_ptr_add(pe
->thunk
,
778 sizeof(struct pe_export_header
) +
779 sym_count
* (2 * sizeof(DWORD
) + sizeof(WORD
)));
781 func_offset
= pe
->exp_offs
+ sizeof(struct pe_export_header
);
783 hdr
->Characteristics
= 0;
785 hdr
->NumberOfFunctions
= sym_count
;
786 hdr
->NumberOfNames
= sym_count
;
787 hdr
->AddressOfFunctions
= func_offset
+ voffset
;
788 hdr
->AddressOfNames
= hdr
->AddressOfFunctions
+ sym_count
* sizeof(DWORD
);
789 hdr
->AddressOfNameOrdinals
= hdr
->AddressOfNames
+ sym_count
* sizeof(DWORD
);
790 hdr
->Name
= pe
->thunk
->data_offset
+ voffset
;
791 put_elf_str(pe
->thunk
, tcc_basename(pe
->filename
));
793 for (ord
= 0; ord
< sym_count
; ++ord
)
795 char *name
; DWORD
*p
, *pfunc
, *pname
; WORD
*pord
;
796 sym
= (Elf32_Sym
*)symtab_section
->data
+ sorted
[ord
];
797 name
= symtab_section
->link
->data
+ sym
->st_name
;
798 p
= (DWORD
*)(pe
->thunk
->data
+ func_offset
);
800 pname
= p
+ sym_count
+ ord
;
801 pord
= (WORD
*)(p
+ 2*sym_count
) + ord
;
802 *pfunc
= sym
->st_value
+ pe
->s1
->sections
[sym
->st_shndx
]->sh_addr
- pe
->imagebase
;
803 *pname
= pe
->thunk
->data_offset
+ voffset
;
805 put_elf_str(pe
->thunk
, name
);
806 /* printf("export: %s\n", name); */
808 pe
->exp_size
= pe
->thunk
->data_offset
- pe
->exp_offs
;
812 /* ------------------------------------------------------------- */
813 ST
void pe_build_reloc(struct pe_info
*pe
, int *section_order
,
816 DWORD offset
, block_ptr
, addr
;
818 Elf32_Rel
*rel
, *rel_end
;
819 Section
*s
= NULL
, *sr
;
820 offset
= addr
= block_ptr
= count
= i
= 0;
821 rel
= rel_end
= NULL
;
824 int type
= ELF32_R_TYPE(rel
->r_info
);
825 addr
= rel
->r_offset
+ s
->sh_addr
;
827 if (type
!= R_386_32
)
829 if (count
== 0) { /* new block */
830 block_ptr
= pe
->reloc
->data_offset
;
831 section_ptr_add(pe
->reloc
, sizeof(struct pe_reloc_header
));
832 offset
= addr
& 0xFFFFFFFF << 12;
834 if ((addr
-= offset
) < (1 << 12)) { /* one block spans 4k addresses */
835 WORD
*wp
= section_ptr_add(pe
->reloc
, sizeof(WORD
));
836 *wp
= addr
| IMAGE_REL_BASED_HIGHLOW
<< 12;
841 } else if (i
< section_count
) {
842 sr
= (s
= pe
->s1
->sections
[section_order
[i
++]])->reloc
;
844 rel
= (Elf32_Rel
*) sr
->data
;
845 rel_end
= (Elf32_Rel
*) (sr
->data
+ sr
->data_offset
);
850 if (count
) { /* store the last block and ready for a new one */
851 struct pe_reloc_header
*hdr
;
853 section_ptr_add(pe
->reloc
, 2), ++count
;
854 hdr
= (struct pe_reloc_header
*) (pe
->reloc
->data
+ block_ptr
);
855 hdr
->offset
= offset
- pe
->imagebase
;
857 count
* sizeof(WORD
) + sizeof(struct pe_reloc_header
);
865 /* ------------------------------------------------------------- */
866 ST
int pe_assign_addresses(struct pe_info
*pe
)
870 int section_order
[pe_sec_number
];
871 struct section_info
*si_data
= NULL
;
873 pe
->imagebase
= PE_DLL
== pe_type
? 0x10000000 : 0x00400000;
874 addr
= pe
->imagebase
+ 1;
876 if (PE_DLL
== pe_type
)
877 pe
->reloc
= new_section(pe
->s1
, ".reloc", SHT_DYNAMIC
, SHF_ALLOC
);
879 for (n
= k
= 0; n
< pe_sec_number
; ++n
) {
880 for (i
= 1; i
< pe
->s1
->nb_sections
; ++i
) {
881 Section
*s
= pe
->s1
->sections
[i
];
882 if (0 == strcmp(s
->name
, pe_sec_names
[n
])) {
883 struct section_info
*si
= &pe
->sh_info
[pe
->sec_count
];
885 if (n
== sec_bss
&& si_data
) {
886 /* append .bss to .data */
887 s
->sh_addr
= addr
= ((addr
- 1) | 15) + 1;
888 addr
+= s
->data_offset
;
889 si_data
->sh_size
= addr
- si_data
->sh_addr
;
893 si
->sh_addr
= s
->sh_addr
= addr
=
894 pe_virtual_align(addr
);
900 pe_build_imports(pe
);
901 pe_build_exports(pe
);
902 } else if (n
== sec_reloc
) {
903 pe_build_reloc(pe
, section_order
, k
);
906 if (s
->data_offset
) {
909 si
->data_size
= s
->data_offset
;
912 addr
+= s
->data_offset
;
913 si
->sh_size
= s
->data_offset
;
916 //printf("Section %08X %04X %s\n", si->sh_addr, si->data_size, s->name);
918 section_order
[k
] = i
, ++k
;
925 /*----------------------------------------------------------------------------*/
926 ST
int pe_check_symbols(struct pe_info
*pe
)
931 pe_align_section(text_section
, 8);
933 for_sym_in_symtab(sym
) {
934 if (sym
->st_shndx
== SHN_UNDEF
) {
935 const char *symbol
= symtab_section
->link
->data
+ sym
->st_name
;
936 unsigned type
= ELF32_ST_TYPE(sym
->st_info
);
937 int sym_index
= pe_find_import(pe
->s1
, symbol
, NULL
);
939 if (type
== STT_FUNC
) {
940 unsigned long offset
= text_section
->data_offset
;
941 if (pe_add_import(pe
, sym_index
, offset
+ 2)) {
942 /* add the 'jmp IAT[x]' instruction */
943 *(WORD
*) section_ptr_add(text_section
, 8) =
945 /* patch the symbol */
946 sym
->st_shndx
= text_section
->sh_num
;
947 sym
->st_value
= offset
;
950 } else if (type
== STT_OBJECT
) { /* data, ptr to that should be */
951 if (pe_add_import(pe
, sym_index
,
953 (Elf32_Sym
*) symtab_section
->data
) |
958 error_noabort("undefined symbol '%s'", symbol
);
962 && ELF32_ST_BIND(sym
->st_info
) != STB_LOCAL
) {
963 /* if -rdynamic option, then export all non local symbols */
970 /*----------------------------------------------------------------------------*/
971 #ifdef PE_PRINT_SECTIONS
972 ST
void pe_print_section(FILE * f
, Section
* s
)
973 { /* just if you'r curious */
977 e
= s
->data
+ s
->data_offset
;
980 fprintf(f
, "section \"%s\"", s
->name
);
982 fprintf(f
, "\nlink \"%s\"", s
->link
->name
);
984 fprintf(f
, "\nreloc \"%s\"", s
->reloc
->name
);
985 fprintf(f
, "\nv_addr %08X", s
->sh_addr
);
986 fprintf(f
, "\ncontents %08X", l
);
989 if (s
->sh_type
== SHT_NOBITS
)
992 if (s
->sh_type
== SHT_SYMTAB
)
993 m
= sizeof(Elf32_Sym
);
994 if (s
->sh_type
== SHT_REL
)
995 m
= sizeof(Elf32_Rel
);
999 for (i
= 0; i
< l
;) {
1000 fprintf(f
, "%08X", i
);
1001 for (n
= 0; n
< m
; ++n
) {
1003 fprintf(f
, " %02X", p
[i
+ n
]);
1008 if (s
->sh_type
== SHT_SYMTAB
) {
1009 Elf32_Sym
*sym
= (Elf32_Sym
*) (p
+ i
);
1010 const char *name
= s
->link
->data
+ sym
->st_name
;
1023 ELF32_ST_BIND(sym
->st_info
),
1024 ELF32_ST_TYPE(sym
->st_info
),
1025 sym
->st_other
, sym
->st_shndx
, name
);
1026 } else if (s
->sh_type
== SHT_REL
) {
1027 Elf32_Rel
*rel
= (Elf32_Rel
*) (p
+ i
);
1029 (Elf32_Sym
*) s
->link
->data
+ ELF32_R_SYM(rel
->r_info
);
1030 const char *name
= s
->link
->link
->data
+ sym
->st_name
;
1037 ELF32_R_TYPE(rel
->r_info
),
1038 ELF32_R_SYM(rel
->r_info
), name
);
1041 for (n
= 0; n
< m
; ++n
) {
1044 if (b
< 32 || b
>= 127)
1046 fprintf(f
, "%c", b
);
1057 static int pe_test_cmd(const char **pp
, const char *cmd
)
1065 while (*p
!= '\0' && !is_space(*p
)) {
1066 if ((q
- buf
) < sizeof(buf
) - 1)
1071 ret
= !strcmp(buf
, cmd
);
1076 /* ------------------------------------------------------------- */
1077 int pe_load_def_file(TCCState
* s1
, FILE * fp
)
1079 DLLReference
*dllref
;
1080 int f
= 0, sym_index
;
1081 char *p
, line
[120], dllname
[40];
1082 while (fgets(line
, sizeof line
, fp
)) {
1083 p
= strchr(line
, 0);
1084 while (p
> line
&& p
[-1] <= ' ')
1088 while (*p
&& *p
<= ' ')
1091 if (*p
&& ';' != *p
)
1094 if (!pe_test_cmd((const char **)&p
, "LIBRARY"))
1096 while (is_space(*p
))
1098 pstrcpy(dllname
, sizeof(dllname
), p
);
1103 if (!pe_test_cmd((const char **)&p
, "EXPORTS"))
1110 tcc_malloc(sizeof(DLLReference
) + strlen(dllname
));
1111 strcpy(dllref
->name
, dllname
);
1113 dynarray_add((void ***) &s1
->loaded_dlls
,
1114 &s1
->nb_loaded_dlls
, dllref
);
1118 /* tccpe needs to know from what dll it should import
1120 sym_index
= add_elf_sym(s1
->dynsymtab_section
,
1121 0, 0, ELF32_ST_INFO(STB_GLOBAL
,
1123 s1
->nb_loaded_dlls
- 1,
1124 text_section
->sh_num
, p
);
1131 /* ------------------------------------------------------------- */
1132 void pe_guess_outfile(char *objfilename
, int output_type
)
1134 char *ext
= strrchr(objfilename
, '.');
1136 ext
= strchr(objfilename
, 0);
1137 if (output_type
== TCC_OUTPUT_DLL
)
1138 strcpy(ext
, ".dll");
1140 if (output_type
== TCC_OUTPUT_EXE
)
1141 strcpy(ext
, ".exe");
1143 if (output_type
== TCC_OUTPUT_OBJ
&& strcmp(ext
, ".o"))
1146 error("no outputfile given");
1149 /* ------------------------------------------------------------- */
1150 unsigned long pe_add_runtime(TCCState
* s1
)
1152 const char *start_symbol
;
1155 if (find_elf_sym(symtab_section
, "WinMain"))
1158 if (TCC_OUTPUT_DLL
== s1
->output_type
)
1161 // need this for 'tccelf.c:relocate_section()'
1162 s1
->output_type
= TCC_OUTPUT_EXE
;
1166 TCC_OUTPUT_MEMORY
== s1
->output_type
1167 ? PE_GUI
== pe_type
? "_runwinmain" : NULL
1168 : PE_DLL
== pe_type
? "_dllstart"
1169 : PE_GUI
== pe_type
? "_winstart" : "_start";
1171 /* grab the startup code from libtcc1 */
1173 add_elf_sym(symtab_section
,
1175 ELF32_ST_INFO(STB_GLOBAL
, STT_NOTYPE
), 0,
1176 SHN_UNDEF
, start_symbol
);
1178 if (0 == s1
->nostdlib
) {
1179 tcc_add_library(s1
, "tcc1");
1180 tcc_add_library(s1
, "msvcrt");
1181 if (PE_DLL
== pe_type
|| PE_GUI
== pe_type
) {
1182 tcc_add_library(s1
, "kernel32");
1183 tcc_add_library(s1
, "user32");
1184 tcc_add_library(s1
, "gdi32");
1188 addr
= start_symbol
?
1189 (unsigned long) tcc_get_symbol_err(s1
, start_symbol
) : 0;
1191 if (s1
->output_type
== TCC_OUTPUT_MEMORY
&& addr
) {
1192 /* for -run GUI's, put '_runwinmain' instead of 'main' */
1193 add_elf_sym(symtab_section
,
1195 ELF32_ST_INFO(STB_GLOBAL
, STT_NOTYPE
), 0,
1196 text_section
->sh_num
, "main");
1198 /* FreeConsole(); */
1203 int tcc_output_pe(TCCState
* s1
, const char *filename
)
1208 memset(&pe
, 0, sizeof pe
);
1209 pe
.filename
= filename
;
1211 pe
.start_addr
= pe_add_runtime(s1
);
1213 relocate_common_syms(); /* assign bss adresses */
1214 ret
= pe_check_symbols(&pe
);
1216 pe_assign_addresses(&pe
);
1217 relocate_syms(s1
, 0);
1218 for (i
= 1; i
< s1
->nb_sections
; ++i
) {
1219 Section
*s
= s1
->sections
[i
];
1221 relocate_section(s1
, s
);
1223 ret
= pe_write_pe(&pe
);
1225 #ifdef PE_PRINT_SECTIONS
1229 f
= fopen("tccpe.log", "wt");
1230 for (i
= 1; i
< s1
->nb_sections
; ++i
) {
1231 s
= s1
->sections
[i
];
1232 pe_print_section(f
, s
);
1234 pe_print_section(f
, s1
->dynsymtab_section
);
1241 /*----------------------------------------------------------------------------*/