win32: enable bounds checker & exception handler
[tinycc.git] / tccpe.c
blobd603a5e7e54a438124f98d11927f2cfefd3352a1
1 /*
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
21 #ifdef TCC_TARGET_PE
23 #define ST_FN static
24 #define ST_DATA static
25 #define PUB_FN
27 #ifndef _WIN32
28 #define stricmp strcasecmp
29 #define strnicmp strncasecmp
30 #endif
32 #ifndef MAX_PATH
33 #define MAX_PATH 260
34 #endif
36 #define PE_MERGE_DATA
37 // #define PE_PRINT_SECTIONS
39 #ifdef TCC_TARGET_X86_64
40 # define ADDR3264 ULONGLONG
41 #else
42 # define ADDR3264 DWORD
43 #endif
45 #if defined _WIN32 && (defined _WIN64) == (defined TCC_TARGET_X86_64)
46 #define TCC_IS_NATIVE
47 #endif
49 #ifdef _WIN32
50 void dbg_printf (const char *fmt, ...)
52 char buffer[4000];
53 va_list arg;
54 int x;
55 va_start(arg, fmt);
56 x = vsprintf (buffer, fmt, arg);
57 strcpy(buffer+x, "\n");
58 OutputDebugString(buffer);
60 #endif
62 /* ----------------------------------------------------------- */
63 #ifndef IMAGE_NT_SIGNATURE
64 /* ----------------------------------------------------------- */
65 /* definitions below are from winnt.h */
67 typedef unsigned char BYTE;
68 typedef unsigned short WORD;
69 typedef unsigned long DWORD;
70 typedef unsigned long long ULONGLONG;
71 #pragma pack(push, 1)
73 typedef struct _IMAGE_DOS_HEADER { /* DOS .EXE header */
74 WORD e_magic; /* Magic number */
75 WORD e_cblp; /* Bytes on last page of file */
76 WORD e_cp; /* Pages in file */
77 WORD e_crlc; /* Relocations */
78 WORD e_cparhdr; /* Size of header in paragraphs */
79 WORD e_minalloc; /* Minimum extra paragraphs needed */
80 WORD e_maxalloc; /* Maximum extra paragraphs needed */
81 WORD e_ss; /* Initial (relative) SS value */
82 WORD e_sp; /* Initial SP value */
83 WORD e_csum; /* Checksum */
84 WORD e_ip; /* Initial IP value */
85 WORD e_cs; /* Initial (relative) CS value */
86 WORD e_lfarlc; /* File address of relocation table */
87 WORD e_ovno; /* Overlay number */
88 WORD e_res[4]; /* Reserved words */
89 WORD e_oemid; /* OEM identifier (for e_oeminfo) */
90 WORD e_oeminfo; /* OEM information; e_oemid specific */
91 WORD e_res2[10]; /* Reserved words */
92 DWORD e_lfanew; /* File address of new exe header */
93 } IMAGE_DOS_HEADER, *PIMAGE_DOS_HEADER;
95 #define IMAGE_NT_SIGNATURE 0x00004550 /* PE00 */
96 #define SIZE_OF_NT_SIGNATURE 4
98 typedef struct _IMAGE_FILE_HEADER {
99 WORD Machine;
100 WORD NumberOfSections;
101 DWORD TimeDateStamp;
102 DWORD PointerToSymbolTable;
103 DWORD NumberOfSymbols;
104 WORD SizeOfOptionalHeader;
105 WORD Characteristics;
106 } IMAGE_FILE_HEADER, *PIMAGE_FILE_HEADER;
109 #define IMAGE_SIZEOF_FILE_HEADER 20
111 typedef struct _IMAGE_DATA_DIRECTORY {
112 DWORD VirtualAddress;
113 DWORD Size;
114 } IMAGE_DATA_DIRECTORY, *PIMAGE_DATA_DIRECTORY;
117 typedef struct _IMAGE_OPTIONAL_HEADER {
118 /* Standard fields. */
119 WORD Magic;
120 BYTE MajorLinkerVersion;
121 BYTE MinorLinkerVersion;
122 DWORD SizeOfCode;
123 DWORD SizeOfInitializedData;
124 DWORD SizeOfUninitializedData;
125 DWORD AddressOfEntryPoint;
126 DWORD BaseOfCode;
127 #ifndef TCC_TARGET_X86_64
128 DWORD BaseOfData;
129 #endif
130 /* NT additional fields. */
131 ADDR3264 ImageBase;
132 DWORD SectionAlignment;
133 DWORD FileAlignment;
134 WORD MajorOperatingSystemVersion;
135 WORD MinorOperatingSystemVersion;
136 WORD MajorImageVersion;
137 WORD MinorImageVersion;
138 WORD MajorSubsystemVersion;
139 WORD MinorSubsystemVersion;
140 DWORD Win32VersionValue;
141 DWORD SizeOfImage;
142 DWORD SizeOfHeaders;
143 DWORD CheckSum;
144 WORD Subsystem;
145 WORD DllCharacteristics;
146 ADDR3264 SizeOfStackReserve;
147 ADDR3264 SizeOfStackCommit;
148 ADDR3264 SizeOfHeapReserve;
149 ADDR3264 SizeOfHeapCommit;
150 DWORD LoaderFlags;
151 DWORD NumberOfRvaAndSizes;
152 IMAGE_DATA_DIRECTORY DataDirectory[16];
153 } IMAGE_OPTIONAL_HEADER32, IMAGE_OPTIONAL_HEADER64, IMAGE_OPTIONAL_HEADER;
155 #define IMAGE_DIRECTORY_ENTRY_EXPORT 0 /* Export Directory */
156 #define IMAGE_DIRECTORY_ENTRY_IMPORT 1 /* Import Directory */
157 #define IMAGE_DIRECTORY_ENTRY_RESOURCE 2 /* Resource Directory */
158 #define IMAGE_DIRECTORY_ENTRY_EXCEPTION 3 /* Exception Directory */
159 #define IMAGE_DIRECTORY_ENTRY_SECURITY 4 /* Security Directory */
160 #define IMAGE_DIRECTORY_ENTRY_BASERELOC 5 /* Base Relocation Table */
161 #define IMAGE_DIRECTORY_ENTRY_DEBUG 6 /* Debug Directory */
162 /* IMAGE_DIRECTORY_ENTRY_COPYRIGHT 7 (X86 usage) */
163 #define IMAGE_DIRECTORY_ENTRY_ARCHITECTURE 7 /* Architecture Specific Data */
164 #define IMAGE_DIRECTORY_ENTRY_GLOBALPTR 8 /* RVA of GP */
165 #define IMAGE_DIRECTORY_ENTRY_TLS 9 /* TLS Directory */
166 #define IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG 10 /* Load Configuration Directory */
167 #define IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT 11 /* Bound Import Directory in headers */
168 #define IMAGE_DIRECTORY_ENTRY_IAT 12 /* Import Address Table */
169 #define IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT 13 /* Delay Load Import Descriptors */
170 #define IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR 14 /* COM Runtime descriptor */
172 /* Section header format. */
173 #define IMAGE_SIZEOF_SHORT_NAME 8
175 typedef struct _IMAGE_SECTION_HEADER {
176 BYTE Name[IMAGE_SIZEOF_SHORT_NAME];
177 union {
178 DWORD PhysicalAddress;
179 DWORD VirtualSize;
180 } Misc;
181 DWORD VirtualAddress;
182 DWORD SizeOfRawData;
183 DWORD PointerToRawData;
184 DWORD PointerToRelocations;
185 DWORD PointerToLinenumbers;
186 WORD NumberOfRelocations;
187 WORD NumberOfLinenumbers;
188 DWORD Characteristics;
189 } IMAGE_SECTION_HEADER, *PIMAGE_SECTION_HEADER;
191 #define IMAGE_SIZEOF_SECTION_HEADER 40
193 typedef struct _IMAGE_EXPORT_DIRECTORY {
194 DWORD Characteristics;
195 DWORD TimeDateStamp;
196 WORD MajorVersion;
197 WORD MinorVersion;
198 DWORD Name;
199 DWORD Base;
200 DWORD NumberOfFunctions;
201 DWORD NumberOfNames;
202 DWORD AddressOfFunctions;
203 DWORD AddressOfNames;
204 DWORD AddressOfNameOrdinals;
205 } IMAGE_EXPORT_DIRECTORY,*PIMAGE_EXPORT_DIRECTORY;
207 typedef struct _IMAGE_IMPORT_DESCRIPTOR {
208 union {
209 DWORD Characteristics;
210 DWORD OriginalFirstThunk;
212 DWORD TimeDateStamp;
213 DWORD ForwarderChain;
214 DWORD Name;
215 DWORD FirstThunk;
216 } IMAGE_IMPORT_DESCRIPTOR;
218 typedef struct _IMAGE_BASE_RELOCATION {
219 DWORD VirtualAddress;
220 DWORD SizeOfBlock;
221 // WORD TypeOffset[1];
222 } IMAGE_BASE_RELOCATION;
224 #define IMAGE_SIZEOF_BASE_RELOCATION 8
226 #define IMAGE_REL_BASED_ABSOLUTE 0
227 #define IMAGE_REL_BASED_HIGH 1
228 #define IMAGE_REL_BASED_LOW 2
229 #define IMAGE_REL_BASED_HIGHLOW 3
230 #define IMAGE_REL_BASED_HIGHADJ 4
231 #define IMAGE_REL_BASED_MIPS_JMPADDR 5
232 #define IMAGE_REL_BASED_SECTION 6
233 #define IMAGE_REL_BASED_REL32 7
235 #pragma pack(pop)
237 /* ----------------------------------------------------------- */
238 #endif /* ndef IMAGE_NT_SIGNATURE */
239 /* ----------------------------------------------------------- */
240 #pragma pack(push, 1)
242 struct pe_header
244 IMAGE_DOS_HEADER doshdr;
245 BYTE dosstub[0x40];
246 DWORD nt_sig;
247 IMAGE_FILE_HEADER filehdr;
248 #ifdef TCC_TARGET_X86_64
249 IMAGE_OPTIONAL_HEADER64 opthdr;
250 #else
251 #ifdef _WIN64
252 IMAGE_OPTIONAL_HEADER32 opthdr;
253 #else
254 IMAGE_OPTIONAL_HEADER opthdr;
255 #endif
256 #endif
259 struct pe_reloc_header {
260 DWORD offset;
261 DWORD size;
264 struct pe_rsrc_header {
265 struct _IMAGE_FILE_HEADER filehdr;
266 struct _IMAGE_SECTION_HEADER sectionhdr;
269 struct pe_rsrc_reloc {
270 DWORD offset;
271 DWORD size;
272 WORD type;
275 #pragma pack(pop)
277 /* ------------------------------------------------------------- */
278 /* internal temporary structures */
281 #define IMAGE_SCN_CNT_CODE 0x00000020
282 #define IMAGE_SCN_CNT_INITIALIZED_DATA 0x00000040
283 #define IMAGE_SCN_CNT_UNINITIALIZED_DATA 0x00000080
284 #define IMAGE_SCN_MEM_DISCARDABLE 0x02000000
285 #define IMAGE_SCN_MEM_SHARED 0x10000000
286 #define IMAGE_SCN_MEM_EXECUTE 0x20000000
287 #define IMAGE_SCN_MEM_READ 0x40000000
288 #define IMAGE_SCN_MEM_WRITE 0x80000000
291 enum {
292 sec_text = 0,
293 sec_data ,
294 sec_bss ,
295 sec_idata ,
296 sec_other ,
297 sec_rsrc ,
298 sec_stab ,
299 sec_reloc ,
300 sec_last
303 ST_DATA const DWORD pe_sec_flags[] = {
304 0x60000020, /* ".text" , */
305 0xC0000040, /* ".data" , */
306 0xC0000080, /* ".bss" , */
307 0x40000040, /* ".idata" , */
308 0xE0000060, /* < other > , */
309 0x40000040, /* ".rsrc" , */
310 0x42000802, /* ".stab" , */
311 0x42000040, /* ".reloc" , */
314 struct section_info {
315 int cls, ord;
316 char name[32];
317 DWORD sh_addr;
318 DWORD sh_size;
319 DWORD sh_flags;
320 unsigned char *data;
321 DWORD data_size;
322 IMAGE_SECTION_HEADER ish;
325 struct import_symbol {
326 int sym_index;
327 int iat_index;
328 int thk_offset;
331 struct pe_import_info {
332 int dll_index;
333 int sym_count;
334 struct import_symbol **symbols;
337 struct pe_info {
338 TCCState *s1;
339 Section *reloc;
340 Section *thunk;
341 const char *filename;
342 int type;
343 DWORD sizeofheaders;
344 DWORD imagebase;
345 DWORD start_addr;
346 DWORD imp_offs;
347 DWORD imp_size;
348 DWORD iat_offs;
349 DWORD iat_size;
350 DWORD exp_offs;
351 DWORD exp_size;
352 int subsystem;
353 DWORD section_align;
354 DWORD file_align;
355 struct section_info *sec_info;
356 int sec_count;
357 struct pe_import_info **imp_info;
358 int imp_count;
361 #define PE_NUL 0
362 #define PE_DLL 1
363 #define PE_GUI 2
364 #define PE_EXE 3
365 #define PE_RUN 4
367 /* --------------------------------------------*/
369 ST_FN const char* get_alt_symbol(char *buffer, const char *symbol)
371 const char *p;
372 p = strrchr(symbol, '@');
373 if (p && isnum(p[1]) && symbol[0] == '_') { /* stdcall decor */
374 strcpy(buffer, symbol+1)[p-symbol-1] = 0;
375 } else if (symbol[0] != '_') { /* try non-ansi function */
376 buffer[0] = '_', strcpy(buffer + 1, symbol);
377 } else if (0 == memcmp(symbol, "__imp__", 7)) { /* mingw 2.0 */
378 strcpy(buffer, symbol + 6);
379 } else if (0 == memcmp(symbol, "_imp___", 7)) { /* mingw 3.7 */
380 strcpy(buffer, symbol + 6);
381 } else {
382 return symbol;
384 return buffer;
387 ST_FN int pe_find_import(TCCState * s1, const char *symbol)
389 char buffer[200];
390 const char *s;
391 int sym_index, n = 0;
392 do {
393 s = n ? get_alt_symbol(buffer, symbol) : symbol;
394 sym_index = find_elf_sym(s1->dynsymtab_section, s);
395 // printf("find (%d) %d %s\n", n, sym_index, s);
396 } while (0 == sym_index && ++n < 2);
397 return sym_index;
400 /*----------------------------------------------------------------------------*/
402 ST_FN int dynarray_assoc(void **pp, int n, int key)
404 int i;
405 for (i = 0; i < n; ++i, ++pp)
406 if (key == **(int **) pp)
407 return i;
408 return -1;
411 #if 0
412 ST_FN DWORD umin(DWORD a, DWORD b)
414 return a < b ? a : b;
416 #endif
418 ST_FN DWORD umax(DWORD a, DWORD b)
420 return a < b ? b : a;
423 ST_FN DWORD pe_file_align(struct pe_info *pe, DWORD n)
425 return (n + (pe->file_align - 1)) & ~(pe->file_align - 1);
428 ST_FN DWORD pe_virtual_align(struct pe_info *pe, DWORD n)
430 return (n + (pe->section_align - 1)) & ~(pe->section_align - 1);
433 ST_FN void pe_align_section(Section *s, int a)
435 int i = s->data_offset & (a-1);
436 if (i)
437 section_ptr_add(s, a - i);
440 ST_FN void pe_set_datadir(struct pe_header *hdr, int dir, DWORD addr, DWORD size)
442 hdr->opthdr.DataDirectory[dir].VirtualAddress = addr;
443 hdr->opthdr.DataDirectory[dir].Size = size;
446 ST_FN int pe_fwrite(void *data, unsigned len, FILE *fp, DWORD *psum)
448 if (psum) {
449 DWORD sum = *psum;
450 WORD *p = data;
451 int i;
452 for (i = len; i > 0; i -= 2) {
453 sum += (i >= 2) ? *p++ : *(BYTE*)p;
454 sum = (sum + (sum >> 16)) & 0xFFFF;
456 *psum = sum;
458 return len == fwrite(data, 1, len, fp) ? 0 : -1;
461 ST_FN void pe_fpad(FILE *fp, DWORD new_pos)
463 DWORD pos = ftell(fp);
464 while (++pos <= new_pos)
465 fputc(0, fp);
468 /*----------------------------------------------------------------------------*/
469 ST_FN int pe_write(struct pe_info *pe)
471 static const struct pe_header pe_template = {
473 /* IMAGE_DOS_HEADER doshdr */
474 0x5A4D, /*WORD e_magic; Magic number */
475 0x0090, /*WORD e_cblp; Bytes on last page of file */
476 0x0003, /*WORD e_cp; Pages in file */
477 0x0000, /*WORD e_crlc; Relocations */
479 0x0004, /*WORD e_cparhdr; Size of header in paragraphs */
480 0x0000, /*WORD e_minalloc; Minimum extra paragraphs needed */
481 0xFFFF, /*WORD e_maxalloc; Maximum extra paragraphs needed */
482 0x0000, /*WORD e_ss; Initial (relative) SS value */
484 0x00B8, /*WORD e_sp; Initial SP value */
485 0x0000, /*WORD e_csum; Checksum */
486 0x0000, /*WORD e_ip; Initial IP value */
487 0x0000, /*WORD e_cs; Initial (relative) CS value */
488 0x0040, /*WORD e_lfarlc; File address of relocation table */
489 0x0000, /*WORD e_ovno; Overlay number */
490 {0,0,0,0}, /*WORD e_res[4]; Reserved words */
491 0x0000, /*WORD e_oemid; OEM identifier (for e_oeminfo) */
492 0x0000, /*WORD e_oeminfo; OEM information; e_oemid specific */
493 {0,0,0,0,0,0,0,0,0,0}, /*WORD e_res2[10]; Reserved words */
494 0x00000080 /*DWORD e_lfanew; File address of new exe header */
496 /* BYTE dosstub[0x40] */
497 /* 14 code bytes + "This program cannot be run in DOS mode.\r\r\n$" + 6 * 0x00 */
498 0x0e,0x1f,0xba,0x0e,0x00,0xb4,0x09,0xcd,0x21,0xb8,0x01,0x4c,0xcd,0x21,0x54,0x68,
499 0x69,0x73,0x20,0x70,0x72,0x6f,0x67,0x72,0x61,0x6d,0x20,0x63,0x61,0x6e,0x6e,0x6f,
500 0x74,0x20,0x62,0x65,0x20,0x72,0x75,0x6e,0x20,0x69,0x6e,0x20,0x44,0x4f,0x53,0x20,
501 0x6d,0x6f,0x64,0x65,0x2e,0x0d,0x0d,0x0a,0x24,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
503 0x00004550, /* DWORD nt_sig = IMAGE_NT_SIGNATURE */
505 /* IMAGE_FILE_HEADER filehdr */
506 #if defined(TCC_TARGET_I386)
507 0x014C, /*WORD Machine; */
508 #elif defined(TCC_TARGET_X86_64)
509 0x8664, /*WORD Machine; */
510 #elif defined(TCC_TARGET_ARM)
511 0x01C0, /*WORD Machine; */
512 #endif
513 0x0003, /*WORD NumberOfSections; */
514 0x00000000, /*DWORD TimeDateStamp; */
515 0x00000000, /*DWORD PointerToSymbolTable; */
516 0x00000000, /*DWORD NumberOfSymbols; */
517 #if defined(TCC_TARGET_X86_64)
518 0x00F0, /*WORD SizeOfOptionalHeader; */
519 0x022F /*WORD Characteristics; */
520 #define CHARACTERISTICS_DLL 0x222E
521 #elif defined(TCC_TARGET_I386)
522 0x00E0, /*WORD SizeOfOptionalHeader; */
523 0x030F /*WORD Characteristics; */
524 #define CHARACTERISTICS_DLL 0x230E
525 #elif defined(TCC_TARGET_ARM)
526 0x00E0, /*WORD SizeOfOptionalHeader; */
527 0x010F, /*WORD Characteristics; */
528 #define CHARACTERISTICS_DLL 0x230F
529 #endif
531 /* IMAGE_OPTIONAL_HEADER opthdr */
532 /* Standard fields. */
533 #ifdef TCC_TARGET_X86_64
534 0x020B, /*WORD Magic; */
535 #else
536 0x010B, /*WORD Magic; */
537 #endif
538 0x06, /*BYTE MajorLinkerVersion; */
539 0x00, /*BYTE MinorLinkerVersion; */
540 0x00000000, /*DWORD SizeOfCode; */
541 0x00000000, /*DWORD SizeOfInitializedData; */
542 0x00000000, /*DWORD SizeOfUninitializedData; */
543 0x00000000, /*DWORD AddressOfEntryPoint; */
544 0x00000000, /*DWORD BaseOfCode; */
545 #ifndef TCC_TARGET_X86_64
546 0x00000000, /*DWORD BaseOfData; */
547 #endif
548 /* NT additional fields. */
549 #if defined(TCC_TARGET_ARM)
550 0x00100000, /*DWORD ImageBase; */
551 #else
552 0x00400000, /*DWORD ImageBase; */
553 #endif
554 0x00001000, /*DWORD SectionAlignment; */
555 0x00000200, /*DWORD FileAlignment; */
556 0x0004, /*WORD MajorOperatingSystemVersion; */
557 0x0000, /*WORD MinorOperatingSystemVersion; */
558 0x0000, /*WORD MajorImageVersion; */
559 0x0000, /*WORD MinorImageVersion; */
560 0x0004, /*WORD MajorSubsystemVersion; */
561 0x0000, /*WORD MinorSubsystemVersion; */
562 0x00000000, /*DWORD Win32VersionValue; */
563 0x00000000, /*DWORD SizeOfImage; */
564 0x00000200, /*DWORD SizeOfHeaders; */
565 0x00000000, /*DWORD CheckSum; */
566 0x0002, /*WORD Subsystem; */
567 0x0000, /*WORD DllCharacteristics; */
568 0x00100000, /*DWORD SizeOfStackReserve; */
569 0x00001000, /*DWORD SizeOfStackCommit; */
570 0x00100000, /*DWORD SizeOfHeapReserve; */
571 0x00001000, /*DWORD SizeOfHeapCommit; */
572 0x00000000, /*DWORD LoaderFlags; */
573 0x00000010, /*DWORD NumberOfRvaAndSizes; */
575 /* IMAGE_DATA_DIRECTORY DataDirectory[16]; */
576 {{0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0},
577 {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}}
580 struct pe_header pe_header = pe_template;
582 int i;
583 FILE *op;
584 DWORD file_offset, sum;
585 struct section_info *si;
586 IMAGE_SECTION_HEADER *psh;
588 op = fopen(pe->filename, "wb");
589 if (NULL == op) {
590 error_noabort("could not write '%s': %s", pe->filename, strerror(errno));
591 return -1;
594 pe->sizeofheaders = pe_file_align(pe,
595 sizeof (struct pe_header)
596 + pe->sec_count * sizeof (IMAGE_SECTION_HEADER)
599 file_offset = pe->sizeofheaders;
601 if (2 == pe->s1->verbose)
602 printf("-------------------------------"
603 "\n virt file size section" "\n");
604 for (i = 0; i < pe->sec_count; ++i) {
605 unsigned long addr, size;
606 const char *sh_name;
608 si = pe->sec_info + i;
609 sh_name = si->name;
610 addr = si->sh_addr - pe->imagebase;
611 size = si->sh_size;
612 psh = &si->ish;
614 if (2 == pe->s1->verbose)
615 printf("%6lx %6lx %6lx %s\n",
616 addr, file_offset, size, sh_name);
618 switch (si->cls) {
619 case sec_text:
620 pe_header.opthdr.BaseOfCode = addr;
621 pe_header.opthdr.AddressOfEntryPoint = addr + pe->start_addr;
622 break;
624 case sec_data:
625 #ifndef TCC_TARGET_X86_64
626 pe_header.opthdr.BaseOfData = addr;
627 #endif
628 break;
630 case sec_bss:
631 break;
633 case sec_reloc:
634 pe_set_datadir(&pe_header, IMAGE_DIRECTORY_ENTRY_BASERELOC, addr, size);
635 break;
637 case sec_rsrc:
638 pe_set_datadir(&pe_header, IMAGE_DIRECTORY_ENTRY_RESOURCE, addr, size);
639 break;
641 case sec_stab:
642 break;
645 if (pe->thunk == pe->s1->sections[si->ord]) {
646 if (pe->imp_size) {
647 pe_set_datadir(&pe_header, IMAGE_DIRECTORY_ENTRY_IMPORT,
648 pe->imp_offs + addr, pe->imp_size);
649 pe_set_datadir(&pe_header, IMAGE_DIRECTORY_ENTRY_IAT,
650 pe->iat_offs + addr, pe->iat_size);
652 if (pe->exp_size) {
653 pe_set_datadir(&pe_header, IMAGE_DIRECTORY_ENTRY_EXPORT,
654 pe->exp_offs + addr, pe->exp_size);
658 strcpy((char*)psh->Name, sh_name);
660 psh->Characteristics = pe_sec_flags[si->cls];
661 psh->VirtualAddress = addr;
662 psh->Misc.VirtualSize = size;
663 pe_header.opthdr.SizeOfImage =
664 umax(pe_virtual_align(pe, size + addr), pe_header.opthdr.SizeOfImage);
666 if (si->data_size) {
667 psh->PointerToRawData = file_offset;
668 file_offset = pe_file_align(pe, file_offset + si->data_size);
669 psh->SizeOfRawData = file_offset - psh->PointerToRawData;
673 //pe_header.filehdr.TimeDateStamp = time(NULL);
674 pe_header.filehdr.NumberOfSections = pe->sec_count;
675 pe_header.opthdr.SizeOfHeaders = pe->sizeofheaders;
676 pe_header.opthdr.ImageBase = pe->imagebase;
677 if (PE_DLL == pe->type)
678 pe_header.filehdr.Characteristics = CHARACTERISTICS_DLL;
679 else if (PE_GUI != pe->type)
680 pe_header.opthdr.Subsystem = 3;
682 sum = 0;
683 pe_fwrite(&pe_header, sizeof pe_header, op, &sum);
684 for (i = 0; i < pe->sec_count; ++i)
685 pe_fwrite(&pe->sec_info[i].ish, sizeof(IMAGE_SECTION_HEADER), op, &sum);
686 pe_fpad(op, pe->sizeofheaders);
687 for (i = 0; i < pe->sec_count; ++i) {
688 si = pe->sec_info + i;
689 psh = &si->ish;
690 if (si->data_size) {
691 pe_fwrite(si->data, si->data_size, op, &sum);
692 file_offset = psh->PointerToRawData + psh->SizeOfRawData;
693 pe_fpad(op, file_offset);
697 pe_header.opthdr.CheckSum = sum + file_offset;
698 fseek(op, offsetof(struct pe_header, opthdr.CheckSum), SEEK_SET);
699 pe_fwrite(&pe_header.opthdr.CheckSum, sizeof pe_header.opthdr.CheckSum, op, NULL);
700 fclose (op);
702 if (2 == pe->s1->verbose)
703 printf("-------------------------------\n");
704 if (pe->s1->verbose)
705 printf("<- %s (%lu bytes)\n", pe->filename, file_offset);
707 return 0;
710 /*----------------------------------------------------------------------------*/
712 #if defined(TCC_TARGET_X86_64)
713 #define ELFW_R_(type) ELF64_R_##type
714 #define ElfW_Rel ElfW(Rela)
716 #define REL_TYPE_DIRECT R_X86_64_64
717 #define R_XXX_THUNKFIX R_X86_64_PC32
718 #define R_XXX_RELATIVE R_X86_64_RELATIVE
720 #define ELFW_ST_BIND ELF64_ST_BIND
721 #define ELFW_ST_TYPE ELF64_ST_TYPE
722 #define ELFW_ST_INFO ELF64_ST_INFO
723 #elif defined(TCC_TARGET_I386)
724 #define ELFW_R_(type) ELF32_R_##type
725 #define ElfW_Rel ElfW(Rel)
727 #define REL_TYPE_DIRECT R_386_32
728 #define R_XXX_THUNKFIX R_386_32
729 #define R_XXX_RELATIVE R_386_RELATIVE
731 #define ELFW_ST_BIND ELF32_ST_BIND
732 #define ELFW_ST_TYPE ELF32_ST_TYPE
733 #define ELFW_ST_INFO ELF32_ST_INFO
734 #elif defined(TCC_TARGET_ARM)
735 #define ELFW_R_(type) ELF32_R_##type
736 #define ElfW_Rel ElfW(Rel)
738 #define REL_TYPE_DIRECT R_ARM_ABS32
739 #define R_XXX_THUNKFIX R_ARM_ABS32
740 #define R_XXX_RELATIVE R_ARM_RELATIVE
742 #define ELFW_ST_BIND ELF32_ST_BIND
743 #define ELFW_ST_TYPE ELF32_ST_TYPE
744 #define ELFW_ST_INFO ELF32_ST_INFO
745 #endif
746 /*----------------------------------------------------------------------------*/
748 ST_FN struct import_symbol *pe_add_import(struct pe_info *pe, int sym_index)
750 int i;
751 int dll_index;
752 struct pe_import_info *p;
753 struct import_symbol *s;
755 dll_index = ((ElfW(Sym) *)pe->s1->dynsymtab_section->data + sym_index)->st_value;
756 if (0 == dll_index)
757 return NULL;
759 i = dynarray_assoc ((void**)pe->imp_info, pe->imp_count, dll_index);
760 if (-1 != i) {
761 p = pe->imp_info[i];
762 goto found_dll;
764 p = tcc_mallocz(sizeof *p);
765 p->dll_index = dll_index;
766 dynarray_add((void***)&pe->imp_info, &pe->imp_count, p);
768 found_dll:
769 i = dynarray_assoc ((void**)p->symbols, p->sym_count, sym_index);
770 if (-1 != i)
771 return p->symbols[i];
773 s = tcc_mallocz(sizeof *s);
774 dynarray_add((void***)&p->symbols, &p->sym_count, s);
775 s->sym_index = sym_index;
776 return s;
779 /*----------------------------------------------------------------------------*/
780 ST_FN void pe_build_imports(struct pe_info *pe)
782 int thk_ptr, ent_ptr, dll_ptr, sym_cnt, i;
783 DWORD rva_base = pe->thunk->sh_addr - pe->imagebase;
784 int ndlls = pe->imp_count;
786 for (sym_cnt = i = 0; i < ndlls; ++i)
787 sym_cnt += pe->imp_info[i]->sym_count;
789 if (0 == sym_cnt)
790 return;
792 pe_align_section(pe->thunk, 16);
794 pe->imp_offs = dll_ptr = pe->thunk->data_offset;
795 pe->imp_size = (ndlls + 1) * sizeof(IMAGE_IMPORT_DESCRIPTOR);
796 pe->iat_offs = dll_ptr + pe->imp_size;
797 pe->iat_size = (sym_cnt + ndlls) * sizeof(ADDR3264);
798 section_ptr_add(pe->thunk, pe->imp_size + 2*pe->iat_size);
800 thk_ptr = pe->iat_offs;
801 ent_ptr = pe->iat_offs + pe->iat_size;
803 for (i = 0; i < pe->imp_count; ++i) {
804 IMAGE_IMPORT_DESCRIPTOR *hdr;
805 int k, n;
806 ADDR3264 v;
807 struct pe_import_info *p = pe->imp_info[i];
808 const char *name = pe->s1->loaded_dlls[p->dll_index-1]->name;
810 /* put the dll name into the import header */
811 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) {
819 if (k < n) {
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);
831 #ifdef TCC_IS_NATIVE
832 if (pe->type == PE_RUN) {
833 DLLReference *dllref = pe->s1->loaded_dlls[imp_sym->st_value-1];
834 if ( !dllref->handle )
835 dllref->handle = LoadLibrary(dllref->name);
836 v = (ADDR3264)GetProcAddress(dllref->handle, name);
837 if (!v)
838 error_noabort("undefined symbol '%s'", name);
840 #endif
841 } else {
842 v = 0; /* last entry is zero */
844 *(ADDR3264*)(pe->thunk->data+thk_ptr) =
845 *(ADDR3264*)(pe->thunk->data+ent_ptr) = v;
846 thk_ptr += sizeof (ADDR3264);
847 ent_ptr += sizeof (ADDR3264);
849 dll_ptr += sizeof(IMAGE_IMPORT_DESCRIPTOR);
850 dynarray_reset(&p->symbols, &p->sym_count);
852 dynarray_reset(&pe->imp_info, &pe->imp_count);
855 /* ------------------------------------------------------------- */
857 struct pe_sort_sym
859 int index;
860 const char *name;
863 ST_FN int sym_cmp(const void *va, const void *vb)
865 const char *ca = (*(struct pe_sort_sym**)va)->name;
866 const char *cb = (*(struct pe_sort_sym**)vb)->name;
867 return strcmp(ca, cb);
870 ST_FN void pe_build_exports(struct pe_info *pe)
872 ElfW(Sym) *sym;
873 int sym_index, sym_end;
874 DWORD rva_base, func_o, name_o, ord_o, str_o;
875 IMAGE_EXPORT_DIRECTORY *hdr;
876 int sym_count, ord;
877 struct pe_sort_sym **sorted, *p;
879 FILE *op;
880 char buf[MAX_PATH];
881 const char *dllname;
882 const char *name;
884 rva_base = pe->thunk->sh_addr - pe->imagebase;
885 sym_count = 0, sorted = NULL, op = NULL;
887 sym_end = symtab_section->data_offset / sizeof(ElfW(Sym));
888 for (sym_index = 1; sym_index < sym_end; ++sym_index) {
889 sym = (ElfW(Sym)*)symtab_section->data + sym_index;
890 name = symtab_section->link->data + sym->st_name;
891 if ((sym->st_other & 1)
892 /* export only symbols from actually written sections */
893 && pe->s1->sections[sym->st_shndx]->sh_addr) {
894 p = tcc_malloc(sizeof *p);
895 p->index = sym_index;
896 p->name = name;
897 dynarray_add((void***)&sorted, &sym_count, p);
899 #if 0
900 if (sym->st_other & 1)
901 printf("export: %s\n", name);
902 if (sym->st_other & 2)
903 printf("stdcall: %s\n", name);
904 #endif
907 if (0 == sym_count)
908 return;
910 qsort (sorted, sym_count, sizeof *sorted, sym_cmp);
912 pe_align_section(pe->thunk, 16);
913 dllname = tcc_basename(pe->filename);
915 pe->exp_offs = pe->thunk->data_offset;
916 func_o = pe->exp_offs + sizeof(IMAGE_EXPORT_DIRECTORY);
917 name_o = func_o + sym_count * sizeof (DWORD);
918 ord_o = name_o + sym_count * sizeof (DWORD);
919 str_o = ord_o + sym_count * sizeof(WORD);
921 hdr = section_ptr_add(pe->thunk, str_o - pe->exp_offs);
922 hdr->Characteristics = 0;
923 hdr->Base = 1;
924 hdr->NumberOfFunctions = sym_count;
925 hdr->NumberOfNames = sym_count;
926 hdr->AddressOfFunctions = func_o + rva_base;
927 hdr->AddressOfNames = name_o + rva_base;
928 hdr->AddressOfNameOrdinals = ord_o + rva_base;
929 hdr->Name = str_o + rva_base;
930 put_elf_str(pe->thunk, dllname);
932 #if 1
933 /* automatically write exports to <output-filename>.def */
934 strcpy(buf, pe->filename);
935 strcpy(tcc_fileextension(buf), ".def");
936 op = fopen(buf, "w");
937 if (NULL == op) {
938 error_noabort("could not create '%s': %s", buf, strerror(errno));
939 } else {
940 fprintf(op, "LIBRARY %s\n\nEXPORTS\n", dllname);
941 if (pe->s1->verbose)
942 printf("<- %s (%d symbols)\n", buf, sym_count);
944 #endif
946 for (ord = 0; ord < sym_count; ++ord)
948 p = sorted[ord], sym_index = p->index, name = p->name;
949 /* insert actual address later in pe_relocate_rva */
950 put_elf_reloc(symtab_section, pe->thunk,
951 func_o, R_XXX_RELATIVE, sym_index);
952 *(DWORD*)(pe->thunk->data + name_o)
953 = pe->thunk->data_offset + rva_base;
954 *(WORD*)(pe->thunk->data + ord_o)
955 = ord;
956 put_elf_str(pe->thunk, name);
957 func_o += sizeof (DWORD);
958 name_o += sizeof (DWORD);
959 ord_o += sizeof (WORD);
960 if (op)
961 fprintf(op, "%s\n", name);
963 pe->exp_size = pe->thunk->data_offset - pe->exp_offs;
964 dynarray_reset(&sorted, &sym_count);
965 if (op)
966 fclose(op);
969 /* ------------------------------------------------------------- */
970 ST_FN void pe_build_reloc (struct pe_info *pe)
972 DWORD offset, block_ptr, addr;
973 int count, i;
974 ElfW_Rel *rel, *rel_end;
975 Section *s = NULL, *sr;
977 offset = addr = block_ptr = count = i = 0;
978 rel = rel_end = NULL;
980 for(;;) {
981 if (rel < rel_end) {
982 int type = ELFW_R_(TYPE)(rel->r_info);
983 addr = rel->r_offset + s->sh_addr;
984 ++ rel;
985 if (type != REL_TYPE_DIRECT)
986 continue;
987 if (count == 0) { /* new block */
988 block_ptr = pe->reloc->data_offset;
989 section_ptr_add(pe->reloc, sizeof(struct pe_reloc_header));
990 offset = addr & 0xFFFFFFFF<<12;
992 if ((addr -= offset) < (1<<12)) { /* one block spans 4k addresses */
993 WORD *wp = section_ptr_add(pe->reloc, sizeof (WORD));
994 *wp = addr | IMAGE_REL_BASED_HIGHLOW<<12;
995 ++count;
996 continue;
998 -- rel;
1000 } else if (i < pe->sec_count) {
1001 sr = (s = pe->s1->sections[pe->sec_info[i++].ord])->reloc;
1002 if (sr) {
1003 rel = (ElfW_Rel *)sr->data;
1004 rel_end = (ElfW_Rel *)(sr->data + sr->data_offset);
1006 continue;
1009 if (count) {
1010 /* store the last block and ready for a new one */
1011 struct pe_reloc_header *hdr;
1012 if (count & 1) /* align for DWORDS */
1013 section_ptr_add(pe->reloc, sizeof(WORD)), ++count;
1014 hdr = (struct pe_reloc_header *)(pe->reloc->data + block_ptr);
1015 hdr -> offset = offset - pe->imagebase;
1016 hdr -> size = count * sizeof(WORD) + sizeof(struct pe_reloc_header);
1017 count = 0;
1020 if (rel >= rel_end)
1021 break;
1025 /* ------------------------------------------------------------- */
1026 ST_FN int pe_section_class(Section *s)
1028 int type, flags;
1029 const char *name;
1031 type = s->sh_type;
1032 flags = s->sh_flags;
1033 name = s->name;
1034 if (flags & SHF_ALLOC) {
1035 if (type == SHT_PROGBITS) {
1036 if (flags & SHF_EXECINSTR)
1037 return sec_text;
1038 if (flags & SHF_WRITE)
1039 return sec_data;
1040 if (0 == strcmp(name, ".rsrc"))
1041 return sec_rsrc;
1042 if (0 == strcmp(name, ".iedat"))
1043 return sec_idata;
1044 return sec_other;
1045 } else if (type == SHT_NOBITS) {
1046 if (flags & SHF_WRITE)
1047 return sec_bss;
1049 } else {
1050 if (0 == strcmp(name, ".reloc"))
1051 return sec_reloc;
1052 if (0 == strncmp(name, ".stab", 5)) /* .stab and .stabstr */
1053 return sec_stab;
1055 return -1;
1058 ST_FN int pe_assign_addresses (struct pe_info *pe)
1060 int i, k, o, c;
1061 DWORD addr;
1062 int *section_order;
1063 struct section_info *si;
1064 Section *s;
1066 // pe->thunk = new_section(pe->s1, ".iedat", SHT_PROGBITS, SHF_ALLOC);
1068 section_order = tcc_malloc(pe->s1->nb_sections * sizeof (int));
1069 for (o = k = 0 ; k < sec_last; ++k) {
1070 for (i = 1; i < pe->s1->nb_sections; ++i) {
1071 s = pe->s1->sections[i];
1072 if (k == pe_section_class(s)) {
1073 // printf("%s %d\n", s->name, k);
1074 s->sh_addr = pe->imagebase;
1075 section_order[o++] = i;
1080 pe->sec_info = tcc_mallocz(o * sizeof (struct section_info));
1081 addr = pe->imagebase + 1;
1083 for (i = 0; i < o; ++i)
1085 k = section_order[i];
1086 s = pe->s1->sections[k];
1087 c = pe_section_class(s);
1088 si = &pe->sec_info[pe->sec_count];
1090 #ifdef PE_MERGE_DATA
1091 if (c == sec_bss && pe->sec_count && si[-1].cls == sec_data) {
1092 /* append .bss to .data */
1093 s->sh_addr = addr = ((addr-1) | 15) + 1;
1094 addr += s->data_offset;
1095 si[-1].sh_size = addr - si[-1].sh_addr;
1096 continue;
1098 #endif
1099 strcpy(si->name, s->name);
1100 si->cls = c;
1101 si->ord = k;
1102 si->sh_addr = s->sh_addr = addr = pe_virtual_align(pe, addr);
1103 si->sh_flags = s->sh_flags;
1105 if (c == sec_data && NULL == pe->thunk)
1106 pe->thunk = s;
1108 if (s == pe->thunk) {
1109 pe_build_imports(pe);
1110 pe_build_exports(pe);
1113 if (c == sec_reloc)
1114 pe_build_reloc (pe);
1116 if (s->data_offset)
1118 if (s->sh_type != SHT_NOBITS) {
1119 si->data = s->data;
1120 si->data_size = s->data_offset;
1123 addr += s->data_offset;
1124 si->sh_size = s->data_offset;
1125 ++pe->sec_count;
1127 // printf("%08x %05x %s\n", si->sh_addr, si->sh_size, si->name);
1130 #if 0
1131 for (i = 1; i < pe->s1->nb_sections; ++i) {
1132 Section *s = pe->s1->sections[i];
1133 int type = s->sh_type;
1134 int flags = s->sh_flags;
1135 printf("section %-16s %-10s %5x %s,%s,%s\n",
1136 s->name,
1137 type == SHT_PROGBITS ? "progbits" :
1138 type == SHT_NOBITS ? "nobits" :
1139 type == SHT_SYMTAB ? "symtab" :
1140 type == SHT_STRTAB ? "strtab" :
1141 type == SHT_RELX ? "rel" : "???",
1142 s->data_offset,
1143 flags & SHF_ALLOC ? "alloc" : "",
1144 flags & SHF_WRITE ? "write" : "",
1145 flags & SHF_EXECINSTR ? "exec" : ""
1148 pe->s1->verbose = 2;
1149 #endif
1151 tcc_free(section_order);
1152 return 0;
1155 /* ------------------------------------------------------------- */
1156 ST_FN void pe_relocate_rva (struct pe_info *pe, Section *s)
1158 Section *sr = s->reloc;
1159 ElfW_Rel *rel, *rel_end;
1160 rel_end = (ElfW_Rel *)(sr->data + sr->data_offset);
1161 for(rel = (ElfW_Rel *)sr->data; rel < rel_end; rel++) {
1162 if (ELFW_R_(TYPE)(rel->r_info) == R_XXX_RELATIVE) {
1163 int sym_index = ELFW_R_(SYM)(rel->r_info);
1164 DWORD addr = s->sh_addr;
1165 if (sym_index) {
1166 ElfW(Sym) *sym = (ElfW(Sym) *)symtab_section->data + sym_index;
1167 addr = sym->st_value;
1169 // printf("reloc rva %08x %08x\n", (DWORD)rel->r_offset, addr);
1170 *(DWORD*)(s->data + rel->r_offset) += addr - pe->imagebase;
1175 /*----------------------------------------------------------------------------*/
1176 static int pe_isafunc(int sym_index)
1178 Section *sr = text_section->reloc;
1179 ElfW_Rel *rel, *rel_end;
1180 Elf32_Word info = ELF32_R_INFO(sym_index, R_386_PC32);
1181 if (!sr)
1182 return 0;
1183 rel_end = (ElfW_Rel *)(sr->data + sr->data_offset);
1184 for (rel = (ElfW_Rel *)sr->data; rel < rel_end; rel++)
1185 if (rel->r_info == info)
1186 return 1;
1187 return 0;
1190 /*----------------------------------------------------------------------------*/
1191 ST_FN int pe_check_symbols(struct pe_info *pe)
1193 ElfW(Sym) *sym;
1194 int sym_index, sym_end;
1195 int ret = 0;
1197 pe_align_section(text_section, 8);
1199 sym_end = symtab_section->data_offset / sizeof(ElfW(Sym));
1200 for (sym_index = 1; sym_index < sym_end; ++sym_index) {
1202 sym = (ElfW(Sym) *)symtab_section->data + sym_index;
1203 if (sym->st_shndx == SHN_UNDEF) {
1205 const char *name = symtab_section->link->data + sym->st_name;
1206 unsigned type = ELFW_ST_TYPE(sym->st_info);
1207 int imp_sym = pe_find_import(pe->s1, name);
1208 struct import_symbol *is;
1210 if (0 == imp_sym)
1211 goto not_found;
1212 is = pe_add_import(pe, imp_sym);
1213 if (!is)
1214 goto not_found;
1216 if (type == STT_NOTYPE) {
1217 /* symbols from assembler have no type, find out which */
1218 if (pe_isafunc(sym_index))
1219 type = STT_FUNC;
1220 else
1221 type = STT_OBJECT;
1224 if (type == STT_FUNC) {
1225 unsigned long offset = is->thk_offset;
1226 if (offset) {
1227 /* got aliased symbol, like stricmp and _stricmp */
1229 } else {
1230 char buffer[100];
1231 WORD *p;
1233 offset = text_section->data_offset;
1234 /* add the 'jmp IAT[x]' instruction */
1235 p = section_ptr_add(text_section, 8);
1236 *p = 0x25FF;
1237 #ifdef TCC_TARGET_X86_64
1238 *(DWORD*)(p+1) = (DWORD)-4;
1239 #endif
1240 /* add a helper symbol, will be patched later in
1241 pe_build_imports */
1242 sprintf(buffer, "IAT.%s", name);
1243 is->iat_index = put_elf_sym(
1244 symtab_section, 0, sizeof(DWORD),
1245 ELFW_ST_INFO(STB_GLOBAL, STT_OBJECT),
1246 0, SHN_UNDEF, buffer);
1247 put_elf_reloc(symtab_section, text_section,
1248 offset + 2, R_XXX_THUNKFIX, is->iat_index);
1249 is->thk_offset = offset;
1252 /* tcc_realloc might have altered sym's address */
1253 sym = (ElfW(Sym) *)symtab_section->data + sym_index;
1255 /* patch the original symbol */
1256 sym->st_value = offset;
1257 sym->st_shndx = text_section->sh_num;
1258 sym->st_other &= ~1; /* do not export */
1259 continue;
1262 if (type == STT_OBJECT) { /* data, ptr to that should be */
1263 if (0 == is->iat_index) {
1264 /* original symbol will be patched later in pe_build_imports */
1265 is->iat_index = sym_index;
1266 continue;
1270 not_found:
1271 error_noabort("undefined symbol '%s'", name);
1272 ret = -1;
1274 } else if (pe->s1->rdynamic
1275 && ELFW_ST_BIND(sym->st_info) != STB_LOCAL) {
1276 /* if -rdynamic option, then export all non local symbols */
1277 sym->st_other |= 1;
1280 return ret;
1283 /*----------------------------------------------------------------------------*/
1284 #ifdef PE_PRINT_SECTIONS
1285 ST_FN void pe_print_section(FILE * f, Section * s)
1287 /* just if you'r curious */
1288 BYTE *p, *e, b;
1289 int i, n, l, m;
1290 p = s->data;
1291 e = s->data + s->data_offset;
1292 l = e - p;
1294 fprintf(f, "section \"%s\"", s->name);
1295 if (s->link)
1296 fprintf(f, "\nlink \"%s\"", s->link->name);
1297 if (s->reloc)
1298 fprintf(f, "\nreloc \"%s\"", s->reloc->name);
1299 fprintf(f, "\nv_addr %08X", (unsigned)s->sh_addr);
1300 fprintf(f, "\ncontents %08X", (unsigned)l);
1301 fprintf(f, "\n\n");
1303 if (s->sh_type == SHT_NOBITS)
1304 return;
1306 if (0 == l)
1307 return;
1309 if (s->sh_type == SHT_SYMTAB)
1310 m = sizeof(ElfW(Sym));
1311 else if (s->sh_type == SHT_RELX)
1312 m = sizeof(ElfW_Rel);
1313 else
1314 m = 16;
1316 fprintf(f, "%-8s", "offset");
1317 for (i = 0; i < m; ++i)
1318 fprintf(f, " %02x", i);
1319 n = 56;
1321 if (s->sh_type == SHT_SYMTAB || s->sh_type == SHT_RELX) {
1322 const char *fields1[] = {
1323 "name",
1324 "value",
1325 "size",
1326 "bind",
1327 "type",
1328 "other",
1329 "shndx",
1330 NULL
1333 const char *fields2[] = {
1334 "offs",
1335 "type",
1336 "symb",
1337 NULL
1340 const char **p;
1342 if (s->sh_type == SHT_SYMTAB)
1343 p = fields1, n = 106;
1344 else
1345 p = fields2, n = 58;
1347 for (i = 0; p[i]; ++i)
1348 fprintf(f, "%6s", p[i]);
1349 fprintf(f, " symbol");
1352 fprintf(f, "\n");
1353 for (i = 0; i < n; ++i)
1354 fprintf(f, "-");
1355 fprintf(f, "\n");
1357 for (i = 0; i < l;)
1359 fprintf(f, "%08X", i);
1360 for (n = 0; n < m; ++n) {
1361 if (n + i < l)
1362 fprintf(f, " %02X", p[i + n]);
1363 else
1364 fprintf(f, " ");
1367 if (s->sh_type == SHT_SYMTAB) {
1368 ElfW(Sym) *sym = (ElfW(Sym) *) (p + i);
1369 const char *name = s->link->data + sym->st_name;
1370 fprintf(f, " %04X %04X %04X %02X %02X %02X %04X \"%s\"",
1371 (unsigned)sym->st_name,
1372 (unsigned)sym->st_value,
1373 (unsigned)sym->st_size,
1374 (unsigned)ELFW_ST_BIND(sym->st_info),
1375 (unsigned)ELFW_ST_TYPE(sym->st_info),
1376 (unsigned)sym->st_other,
1377 (unsigned)sym->st_shndx,
1378 name);
1380 } else if (s->sh_type == SHT_RELX) {
1381 ElfW_Rel *rel = (ElfW_Rel *) (p + i);
1382 ElfW(Sym) *sym =
1383 (ElfW(Sym) *) s->link->data + ELFW_R_(SYM)(rel->r_info);
1384 const char *name = s->link->link->data + sym->st_name;
1385 fprintf(f, " %04X %02X %04X \"%s\"",
1386 (unsigned)rel->r_offset,
1387 (unsigned)ELFW_R_(TYPE)(rel->r_info),
1388 (unsigned)ELFW_R_(SYM)(rel->r_info),
1389 name);
1390 } else {
1391 fprintf(f, " ");
1392 for (n = 0; n < m; ++n) {
1393 if (n + i < l) {
1394 b = p[i + n];
1395 if (b < 32 || b >= 127)
1396 b = '.';
1397 fprintf(f, "%c", b);
1401 i += m;
1402 fprintf(f, "\n");
1404 fprintf(f, "\n\n");
1407 ST_FN void pe_print_sections(TCCState *s1, const char *fname)
1409 Section *s;
1410 FILE *f;
1411 int i;
1412 f = fopen(fname, "w");
1413 for (i = 1; i < s1->nb_sections; ++i) {
1414 s = s1->sections[i];
1415 pe_print_section(f, s);
1417 pe_print_section(f, s1->dynsymtab_section);
1418 fclose(f);
1420 #endif
1422 /* ------------------------------------------------------------- */
1423 /* helper function for load/store to insert one more indirection */
1425 int pe_dllimport(int r, SValue *sv, void (*fn)(int r, SValue *sv))
1427 int t;
1428 if ((sv->r & (VT_VALMASK|VT_SYM|VT_CONST)) != (VT_SYM|VT_CONST))
1429 return 0;
1430 t = sv->sym->type.t;
1431 if (0 == (t & VT_IMPORT))
1432 return 0;
1434 sv->sym->type.t = t & ~VT_IMPORT;
1435 //printf("import %x %04x %s\n", t, ind, get_tok_str(sv->sym->v, NULL));
1437 *++vtop = *sv;
1438 vtop->type.t &= ~(VT_ARRAY|VT_IMPORT);
1439 mk_pointer(&vtop->type);
1440 indir();
1441 fn(r, vtop);
1442 --vtop;
1444 sv->sym->type.t = t;
1445 return 1;
1448 /* ------------------------------------------------------------- */
1450 ST_FN int read_mem(FILE *fp, unsigned offset, void *buffer, unsigned len)
1452 fseek(fp, offset, 0);
1453 return len == fread(buffer, 1, len, fp);
1456 /* -------------------------------------------------------------
1457 * This is for compiled windows resources in 'coff' format
1458 * as generated by 'windres.exe -O coff ...'.
1461 ST_FN int pe_load_res(TCCState *s1, FILE *fp)
1463 struct pe_rsrc_header hdr;
1464 Section *rsrc_section;
1465 int i, ret = -1;
1466 BYTE *ptr;
1467 unsigned offs;
1469 if (!read_mem(fp, 0, &hdr, sizeof hdr))
1470 goto quit;
1472 if (hdr.filehdr.Machine != 0x014C
1473 || hdr.filehdr.NumberOfSections != 1
1474 || strcmp(hdr.sectionhdr.Name, ".rsrc") != 0)
1475 goto quit;
1477 rsrc_section = new_section(s1, ".rsrc", SHT_PROGBITS, SHF_ALLOC);
1478 ptr = section_ptr_add(rsrc_section, hdr.sectionhdr.SizeOfRawData);
1479 offs = hdr.sectionhdr.PointerToRawData;
1480 if (!read_mem(fp, offs, ptr, hdr.sectionhdr.SizeOfRawData))
1481 goto quit;
1482 offs = hdr.sectionhdr.PointerToRelocations;
1483 for (i = 0; i < hdr.sectionhdr.NumberOfRelocations; ++i)
1485 struct pe_rsrc_reloc rel;
1486 if (!read_mem(fp, offs, &rel, sizeof rel))
1487 goto quit;
1488 // printf("rsrc_reloc: %x %x %x\n", rel.offset, rel.size, rel.type);
1489 if (rel.type != 7) /* DIR32NB */
1490 goto quit;
1491 put_elf_reloc(symtab_section, rsrc_section,
1492 rel.offset, R_XXX_RELATIVE, 0);
1493 offs += sizeof rel;
1495 ret = 0;
1496 quit:
1497 return ret;
1500 /* ------------------------------------------------------------- */
1501 ST_FN char *trimfront(char *p)
1503 while (*p && (unsigned char)*p <= ' ')
1504 ++p;
1505 return p;
1508 ST_FN char *trimback(char *a, char *e)
1510 while (e > a && (unsigned char)e[-1] <= ' ')
1511 --e;
1512 *e = 0;;
1513 return a;
1516 ST_FN char *get_line(char *line, int size, FILE *fp)
1518 if (NULL == fgets(line, size, fp))
1519 return NULL;
1520 trimback(line, strchr(line, 0));
1521 return trimfront(line);
1524 /* ------------------------------------------------------------- */
1525 ST_FN int pe_load_def(TCCState *s1, FILE *fp)
1527 DLLReference *dllref;
1528 int state = 0, ret = -1;
1529 char line[400], dllname[80], *p;
1531 for (;;) {
1532 p = get_line(line, sizeof line, fp);
1533 if (NULL == p)
1534 break;
1535 if (0 == *p || ';' == *p)
1536 continue;
1537 switch (state) {
1538 case 0:
1539 if (0 != strnicmp(p, "LIBRARY", 7))
1540 goto quit;
1541 strcpy(dllname, trimfront(p+7));
1542 ++state;
1543 continue;
1545 case 1:
1546 if (0 != stricmp(p, "EXPORTS"))
1547 goto quit;
1548 ++state;
1549 continue;
1551 case 2:
1552 dllref = tcc_mallocz(sizeof(DLLReference) + strlen(dllname));
1553 strcpy(dllref->name, dllname);
1554 dynarray_add((void ***) &s1->loaded_dlls, &s1->nb_loaded_dlls, dllref);
1555 ++state;
1557 default:
1558 add_elf_sym(s1->dynsymtab_section,
1559 s1->nb_loaded_dlls, 0,
1560 ELFW_ST_INFO(STB_GLOBAL, STT_FUNC), 0,
1561 text_section->sh_num, p);
1562 continue;
1565 ret = 0;
1566 quit:
1567 return ret;
1570 /* ------------------------------------------------------------- */
1571 #define TINY_IMPDEF_GET_EXPORT_NAMES_ONLY
1572 #include "win32/tools/tiny_impdef.c"
1574 ST_FN int pe_load_dll(TCCState *s1, const char *dllname, FILE *fp)
1576 int i = 0;
1577 char *p, *q;
1578 p = get_export_names(fp);
1579 if (p) {
1580 DLLReference *dllref;
1581 dllref = tcc_mallocz(sizeof(DLLReference) + strlen(dllname));
1582 strcpy(dllref->name, dllname);
1583 dynarray_add((void ***) &s1->loaded_dlls, &s1->nb_loaded_dlls, dllref);
1584 for (q = p, i = 0; *q; ++i) {
1585 add_elf_sym(s1->dynsymtab_section,
1586 s1->nb_loaded_dlls, 0,
1587 ELFW_ST_INFO(STB_GLOBAL, STT_FUNC), 0,
1588 text_section->sh_num, q);
1589 q += 1 + strlen(q);
1591 tcc_free(p);
1593 return i ? 0 : -1;
1596 /* ------------------------------------------------------------- */
1597 PUB_FN int pe_load_file(struct TCCState *s1, const char *filename, int fd)
1599 FILE *fp = fdopen(dup(fd), "rb");
1600 int ret = -1;
1601 char buf[10];
1602 if (fp) {
1603 if (0 == strcmp(tcc_fileextension(filename), ".def"))
1604 ret = pe_load_def(s1, fp);
1605 else if (pe_load_res(s1, fp) == 0)
1606 ret = 0;
1607 else if (read_mem(fp, 0, buf, sizeof buf) && 0 == strncmp(buf, "MZ", 2))
1608 ret = pe_load_dll(s1, tcc_basename(filename), fp);
1609 fclose(fp);
1611 return ret;
1614 int pe_add_dll(struct TCCState *s, const char *libname)
1616 static const char *pat[] = {
1617 "%s.def", "lib%s.def", "%s.dll", "lib%s.dll", NULL
1619 const char **p = pat;
1620 do {
1621 char buf[MAX_PATH];
1622 snprintf(buf, sizeof(buf), *p, libname);
1623 if (tcc_add_dll(s, buf, 0) == 0)
1624 return 0;
1625 } while (*++p);
1626 return -1;
1629 /* ------------------------------------------------------------- */
1630 #ifdef TCC_TARGET_X86_64
1631 #define PE_STDSYM(n,s) n
1632 #else
1633 #define PE_STDSYM(n,s) "_" n s
1634 #endif
1636 ST_FN void pe_add_runtime_ex(TCCState *s1, struct pe_info *pe)
1638 const char *start_symbol;
1639 unsigned long addr = 0;
1640 int pe_type = 0;
1642 if (find_elf_sym(symtab_section, PE_STDSYM("WinMain","@16")))
1643 pe_type = PE_GUI;
1644 else
1645 if (TCC_OUTPUT_DLL == s1->output_type) {
1646 pe_type = PE_DLL;
1647 /* need this for 'tccelf.c:relocate_section()' */
1648 s1->output_type = TCC_OUTPUT_EXE;
1651 start_symbol =
1652 TCC_OUTPUT_MEMORY == s1->output_type
1653 ? PE_GUI == pe_type ? "_runwinmain" : NULL
1654 : PE_DLL == pe_type ? PE_STDSYM("_dllstart","@12")
1655 : PE_GUI == pe_type ? "_winstart" : "_start"
1658 /* grab the startup code from libtcc1 */
1659 if (start_symbol)
1660 add_elf_sym(symtab_section,
1661 0, 0,
1662 ELFW_ST_INFO(STB_GLOBAL, STT_NOTYPE), 0,
1663 SHN_UNDEF, start_symbol);
1665 if (0 == s1->nostdlib) {
1666 static const char *libs[] = {
1667 "tcc1", "msvcrt", "kernel32", "", "user32", "gdi32", NULL
1669 const char **pp, *p;
1670 for (pp = libs; 0 != (p = *pp); ++pp) {
1671 if (0 == *p) {
1672 if (PE_DLL != pe_type && PE_GUI != pe_type)
1673 break;
1674 } else if (tcc_add_library(s1, p) < 0)
1675 error_noabort("cannot find library: %s", p);
1679 if (start_symbol) {
1680 addr = (uplong)tcc_get_symbol_err(s1, start_symbol);
1681 if (s1->output_type == TCC_OUTPUT_MEMORY && addr)
1682 /* for -run GUI's, put '_runwinmain' instead of 'main' */
1683 add_elf_sym(symtab_section,
1684 addr, 0,
1685 ELFW_ST_INFO(STB_GLOBAL, STT_NOTYPE), 0,
1686 text_section->sh_num, "main");
1689 pe->type = pe_type;
1690 pe->start_addr = addr;
1693 PUB_FN int pe_output_file(TCCState * s1, const char *filename)
1695 int ret;
1696 struct pe_info pe;
1697 int i;
1699 memset(&pe, 0, sizeof pe);
1700 pe.filename = filename;
1701 pe.s1 = s1;
1703 tcc_add_bcheck(s1);
1704 pe_add_runtime_ex(s1, &pe);
1705 relocate_common_syms(); /* assign bss adresses */
1706 tcc_add_linker_symbols(s1);
1708 ret = pe_check_symbols(&pe);
1709 if (ret)
1711 else if (filename) {
1712 if (PE_DLL == pe.type) {
1713 pe.reloc = new_section(pe.s1, ".reloc", SHT_PROGBITS, 0);
1714 /* XXX: check if is correct for arm-pe target */
1715 pe.imagebase = 0x10000000;
1716 } else {
1717 #if defined(TCC_TARGET_ARM)
1718 pe.imagebase = 0x00010000;
1719 #else
1720 pe.imagebase = 0x00400000;
1721 #endif
1724 /* if no subsystem specified, we use "console" subsystem by default */
1725 if (s1->pe_subsystem != 0)
1726 pe.subsystem = s1->pe_subsystem;
1727 else
1728 #if defined(TCC_TARGET_ARM)
1729 pe.subsystem = 3;
1730 #else
1731 pe.subsystem = 9;
1732 #endif
1733 /* set default file/section alignment */
1734 if (pe.subsystem == 1) {
1735 pe.section_align = 0x20;
1736 pe.file_align = 0x20;
1737 } else {
1738 pe.section_align = 0x1000;
1739 pe.file_align = 0x200;
1742 if (s1->section_align != 0)
1743 pe.section_align = s1->section_align;
1744 if (s1->pe_file_align != 0)
1745 pe.file_align = s1->pe_file_align;
1747 if ((pe.subsystem >= 10) && (pe.subsystem <= 12))
1748 pe.imagebase = 0;
1750 if (s1->has_text_addr)
1751 pe.imagebase = s1->text_addr;
1753 pe_assign_addresses(&pe);
1754 relocate_syms(s1, 0);
1755 for (i = 1; i < s1->nb_sections; ++i) {
1756 Section *s = s1->sections[i];
1757 if (s->reloc) {
1758 relocate_section(s1, s);
1759 pe_relocate_rva(&pe, s);
1762 if (s1->nb_errors)
1763 ret = -1;
1764 else
1765 ret = pe_write(&pe);
1766 tcc_free(pe.sec_info);
1767 } else {
1768 #ifndef TCC_IS_NATIVE
1769 error_noabort("-run supported only on native platform");
1770 #endif
1771 pe.type = PE_RUN;
1772 pe.thunk = data_section;
1773 pe_build_imports(&pe);
1776 #ifdef PE_PRINT_SECTIONS
1777 pe_print_sections(s1, "tcc.log");
1778 #endif
1779 return ret;
1782 /* ------------------------------------------------------------- */
1783 #endif /* def TCC_TARGET_PE */
1784 /* ------------------------------------------------------------- */