i386: use __fixdfdi instead of __tcc_cvt_ftol
[tinycc.git] / tccpe.c
blob62df8658e6bda68c898076c85b743e1f34498e26
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 #include "tcc.h"
23 #ifndef _WIN32
24 #define stricmp strcasecmp
25 #define strnicmp strncasecmp
26 #endif
28 #ifndef MAX_PATH
29 #define MAX_PATH 260
30 #endif
32 #define PE_MERGE_DATA
33 /* #define PE_PRINT_SECTIONS */
35 #ifdef TCC_TARGET_X86_64
36 # define ADDR3264 ULONGLONG
37 #else
38 # define ADDR3264 DWORD
39 #endif
41 #ifdef _WIN32
42 void dbg_printf (const char *fmt, ...)
44 char buffer[4000];
45 va_list arg;
46 int x;
47 va_start(arg, fmt);
48 x = vsprintf (buffer, fmt, arg);
49 strcpy(buffer+x, "\n");
50 OutputDebugString(buffer);
52 #endif
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;
63 #pragma pack(push, 1)
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 {
91 WORD Machine;
92 WORD NumberOfSections;
93 DWORD TimeDateStamp;
94 DWORD PointerToSymbolTable;
95 DWORD NumberOfSymbols;
96 WORD SizeOfOptionalHeader;
97 WORD Characteristics;
98 } IMAGE_FILE_HEADER, *PIMAGE_FILE_HEADER;
101 #define IMAGE_SIZEOF_FILE_HEADER 20
103 typedef struct _IMAGE_DATA_DIRECTORY {
104 DWORD VirtualAddress;
105 DWORD Size;
106 } IMAGE_DATA_DIRECTORY, *PIMAGE_DATA_DIRECTORY;
109 typedef struct _IMAGE_OPTIONAL_HEADER {
110 /* Standard fields. */
111 WORD Magic;
112 BYTE MajorLinkerVersion;
113 BYTE MinorLinkerVersion;
114 DWORD SizeOfCode;
115 DWORD SizeOfInitializedData;
116 DWORD SizeOfUninitializedData;
117 DWORD AddressOfEntryPoint;
118 DWORD BaseOfCode;
119 #ifndef TCC_TARGET_X86_64
120 DWORD BaseOfData;
121 #endif
122 /* NT additional fields. */
123 ADDR3264 ImageBase;
124 DWORD SectionAlignment;
125 DWORD FileAlignment;
126 WORD MajorOperatingSystemVersion;
127 WORD MinorOperatingSystemVersion;
128 WORD MajorImageVersion;
129 WORD MinorImageVersion;
130 WORD MajorSubsystemVersion;
131 WORD MinorSubsystemVersion;
132 DWORD Win32VersionValue;
133 DWORD SizeOfImage;
134 DWORD SizeOfHeaders;
135 DWORD CheckSum;
136 WORD Subsystem;
137 WORD DllCharacteristics;
138 ADDR3264 SizeOfStackReserve;
139 ADDR3264 SizeOfStackCommit;
140 ADDR3264 SizeOfHeapReserve;
141 ADDR3264 SizeOfHeapCommit;
142 DWORD LoaderFlags;
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];
169 union {
170 DWORD PhysicalAddress;
171 DWORD VirtualSize;
172 } Misc;
173 DWORD VirtualAddress;
174 DWORD SizeOfRawData;
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;
187 DWORD TimeDateStamp;
188 WORD MajorVersion;
189 WORD MinorVersion;
190 DWORD Name;
191 DWORD Base;
192 DWORD NumberOfFunctions;
193 DWORD NumberOfNames;
194 DWORD AddressOfFunctions;
195 DWORD AddressOfNames;
196 DWORD AddressOfNameOrdinals;
197 } IMAGE_EXPORT_DIRECTORY,*PIMAGE_EXPORT_DIRECTORY;
199 typedef struct _IMAGE_IMPORT_DESCRIPTOR {
200 union {
201 DWORD Characteristics;
202 DWORD OriginalFirstThunk;
204 DWORD TimeDateStamp;
205 DWORD ForwarderChain;
206 DWORD Name;
207 DWORD FirstThunk;
208 } IMAGE_IMPORT_DESCRIPTOR;
210 typedef struct _IMAGE_BASE_RELOCATION {
211 DWORD VirtualAddress;
212 DWORD SizeOfBlock;
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
227 #pragma pack(pop)
229 /* ----------------------------------------------------------- */
230 #endif /* ndef IMAGE_NT_SIGNATURE */
231 /* ----------------------------------------------------------- */
232 #pragma pack(push, 1)
234 struct pe_header
236 IMAGE_DOS_HEADER doshdr;
237 BYTE dosstub[0x40];
238 DWORD nt_sig;
239 IMAGE_FILE_HEADER filehdr;
240 #ifdef TCC_TARGET_X86_64
241 IMAGE_OPTIONAL_HEADER64 opthdr;
242 #else
243 #ifdef _WIN64
244 IMAGE_OPTIONAL_HEADER32 opthdr;
245 #else
246 IMAGE_OPTIONAL_HEADER opthdr;
247 #endif
248 #endif
251 struct pe_reloc_header {
252 DWORD offset;
253 DWORD size;
256 struct pe_rsrc_header {
257 struct _IMAGE_FILE_HEADER filehdr;
258 struct _IMAGE_SECTION_HEADER sectionhdr;
261 struct pe_rsrc_reloc {
262 DWORD offset;
263 DWORD size;
264 WORD type;
267 #pragma pack(pop)
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
283 enum {
284 sec_text = 0,
285 sec_data ,
286 sec_bss ,
287 sec_idata ,
288 sec_pdata ,
289 sec_other ,
290 sec_rsrc ,
291 sec_stab ,
292 sec_reloc ,
293 sec_last
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 {
309 int cls, ord;
310 char name[32];
311 DWORD sh_addr;
312 DWORD sh_size;
313 DWORD sh_flags;
314 unsigned char *data;
315 DWORD data_size;
316 IMAGE_SECTION_HEADER ish;
319 struct import_symbol {
320 int sym_index;
321 int iat_index;
322 int thk_offset;
325 struct pe_import_info {
326 int dll_index;
327 int sym_count;
328 struct import_symbol **symbols;
331 struct pe_info {
332 TCCState *s1;
333 Section *reloc;
334 Section *thunk;
335 const char *filename;
336 int type;
337 DWORD sizeofheaders;
338 ADDR3264 imagebase;
339 DWORD start_addr;
340 DWORD imp_offs;
341 DWORD imp_size;
342 DWORD iat_offs;
343 DWORD iat_size;
344 DWORD exp_offs;
345 DWORD exp_size;
346 int subsystem;
347 DWORD section_align;
348 DWORD file_align;
349 struct section_info *sec_info;
350 int sec_count;
351 struct pe_import_info **imp_info;
352 int imp_count;
355 #define PE_NUL 0
356 #define PE_DLL 1
357 #define PE_GUI 2
358 #define PE_EXE 3
359 #define PE_RUN 4
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))
367 return name + 1;
368 return name;
371 static int pe_find_import(TCCState * s1, ElfW(Sym) *sym)
373 char buffer[200];
374 const char *s, *p;
375 int sym_index = 0, n = 0;
377 do {
378 s = pe_export_name(s1, sym);
379 if (n) {
380 /* second try: */
381 if (sym->st_other & 2) {
382 /* try w/0 stdcall deco (windows API convention) */
383 p = strrchr(s, '@');
384 if (!p || s[0] != '_')
385 break;
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);
393 } else {
394 break;
396 s = buffer;
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);
401 return sym_index;
404 /*----------------------------------------------------------------------------*/
406 static int dynarray_assoc(void **pp, int n, int key)
408 int i;
409 for (i = 0; i < n; ++i, ++pp)
410 if (key == **(int **) pp)
411 return i;
412 return -1;
415 #if 0
416 ST_FN DWORD umin(DWORD a, DWORD b)
418 return a < b ? a : b;
420 #endif
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);
440 if (i)
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)
452 if (psum) {
453 DWORD sum = *psum;
454 WORD *p = data;
455 int i;
456 for (i = len; i > 0; i -= 2) {
457 sum += (i >= 2) ? *p++ : *(BYTE*)p;
458 sum = (sum + (sum >> 16)) & 0xFFFF;
460 *psum = sum;
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)
469 fputc(0, fp);
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; */
516 #endif
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
533 #endif
535 /* IMAGE_OPTIONAL_HEADER opthdr */
536 /* Standard fields. */
537 #ifdef TCC_TARGET_X86_64
538 0x020B, /*WORD Magic; */
539 #else
540 0x010B, /*WORD Magic; */
541 #endif
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; */
551 #endif
552 /* NT additional fields. */
553 #if defined(TCC_TARGET_ARM)
554 0x00100000, /*DWORD ImageBase; */
555 #else
556 0x00400000, /*DWORD ImageBase; */
557 #endif
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;
586 int i;
587 FILE *op;
588 DWORD file_offset, sum;
589 struct section_info *si;
590 IMAGE_SECTION_HEADER *psh;
592 op = fopen(pe->filename, "wb");
593 if (NULL == op) {
594 tcc_error_noabort("could not write '%s': %s", pe->filename, strerror(errno));
595 return -1;
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) {
609 DWORD addr, size;
610 const char *sh_name;
612 si = pe->sec_info + i;
613 sh_name = si->name;
614 addr = si->sh_addr - pe->imagebase;
615 size = si->sh_size;
616 psh = &si->ish;
618 if (2 == pe->s1->verbose)
619 printf("%6x %6x %6x %s\n",
620 (unsigned)addr, (unsigned)file_offset, (unsigned)size, sh_name);
622 switch (si->cls) {
623 case sec_text:
624 pe_header.opthdr.BaseOfCode = addr;
625 pe_header.opthdr.AddressOfEntryPoint = addr + pe->start_addr;
626 break;
628 case sec_data:
629 #ifndef TCC_TARGET_X86_64
630 pe_header.opthdr.BaseOfData = addr;
631 #endif
632 break;
634 case sec_bss:
635 break;
637 case sec_reloc:
638 pe_set_datadir(&pe_header, IMAGE_DIRECTORY_ENTRY_BASERELOC, addr, size);
639 break;
641 case sec_rsrc:
642 pe_set_datadir(&pe_header, IMAGE_DIRECTORY_ENTRY_RESOURCE, addr, size);
643 break;
645 case sec_pdata:
646 pe_set_datadir(&pe_header, IMAGE_DIRECTORY_ENTRY_EXCEPTION, addr, size);
647 break;
649 case sec_stab:
650 break;
653 if (pe->thunk == pe->s1->sections[si->ord]) {
654 if (pe->imp_size) {
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);
660 if (pe->exp_size) {
661 pe_set_datadir(&pe_header, IMAGE_DIRECTORY_ENTRY_EXPORT,
662 pe->exp_offs + addr, pe->exp_size);
666 strncpy((char*)psh->Name, sh_name, sizeof psh->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);
674 if (si->data_size) {
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 pe_header.opthdr.Subsystem = pe->subsystem;
686 if (pe->s1->pe_stack_size)
687 pe_header.opthdr.SizeOfStackReserve = pe->s1->pe_stack_size;
688 if (PE_DLL == pe->type)
689 pe_header.filehdr.Characteristics = CHARACTERISTICS_DLL;
691 sum = 0;
692 pe_fwrite(&pe_header, sizeof pe_header, op, &sum);
693 for (i = 0; i < pe->sec_count; ++i)
694 pe_fwrite(&pe->sec_info[i].ish, sizeof(IMAGE_SECTION_HEADER), op, &sum);
695 pe_fpad(op, pe->sizeofheaders);
696 for (i = 0; i < pe->sec_count; ++i) {
697 si = pe->sec_info + i;
698 psh = &si->ish;
699 if (si->data_size) {
700 pe_fwrite(si->data, si->data_size, op, &sum);
701 file_offset = psh->PointerToRawData + psh->SizeOfRawData;
702 pe_fpad(op, file_offset);
706 pe_header.opthdr.CheckSum = sum + file_offset;
707 fseek(op, offsetof(struct pe_header, opthdr.CheckSum), SEEK_SET);
708 pe_fwrite(&pe_header.opthdr.CheckSum, sizeof pe_header.opthdr.CheckSum, op, NULL);
709 fclose (op);
711 if (2 == pe->s1->verbose)
712 printf("-------------------------------\n");
713 if (pe->s1->verbose)
714 printf("<- %s (%u bytes)\n", pe->filename, (unsigned)file_offset);
716 return 0;
719 /*----------------------------------------------------------------------------*/
721 #if defined(TCC_TARGET_X86_64)
722 #define REL_TYPE_DIRECT R_X86_64_64
723 #define R_XXX_THUNKFIX R_X86_64_PC32
724 #define R_XXX_RELATIVE R_X86_64_RELATIVE
726 #elif defined(TCC_TARGET_I386)
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 #elif defined(TCC_TARGET_ARM)
732 #define REL_TYPE_DIRECT R_ARM_ABS32
733 #define R_XXX_THUNKFIX R_ARM_ABS32
734 #define R_XXX_RELATIVE R_ARM_RELATIVE
736 #endif
737 /*----------------------------------------------------------------------------*/
739 static struct import_symbol *pe_add_import(struct pe_info *pe, int sym_index)
741 int i;
742 int dll_index;
743 struct pe_import_info *p;
744 struct import_symbol *s;
745 ElfW(Sym) *isym;
747 isym = (ElfW(Sym) *)pe->s1->dynsymtab_section->data + sym_index;
748 dll_index = isym->st_size;
750 i = dynarray_assoc ((void**)pe->imp_info, pe->imp_count, dll_index);
751 if (-1 != i) {
752 p = pe->imp_info[i];
753 goto found_dll;
755 p = tcc_mallocz(sizeof *p);
756 p->dll_index = dll_index;
757 dynarray_add((void***)&pe->imp_info, &pe->imp_count, p);
759 found_dll:
760 i = dynarray_assoc ((void**)p->symbols, p->sym_count, sym_index);
761 if (-1 != i)
762 return p->symbols[i];
764 s = tcc_mallocz(sizeof *s);
765 dynarray_add((void***)&p->symbols, &p->sym_count, s);
766 s->sym_index = sym_index;
767 return s;
770 /*----------------------------------------------------------------------------*/
771 static void pe_build_imports(struct pe_info *pe)
773 int thk_ptr, ent_ptr, dll_ptr, sym_cnt, i;
774 DWORD rva_base = pe->thunk->sh_addr - pe->imagebase;
775 int ndlls = pe->imp_count;
777 for (sym_cnt = i = 0; i < ndlls; ++i)
778 sym_cnt += pe->imp_info[i]->sym_count;
780 if (0 == sym_cnt)
781 return;
783 pe_align_section(pe->thunk, 16);
785 pe->imp_offs = dll_ptr = pe->thunk->data_offset;
786 pe->imp_size = (ndlls + 1) * sizeof(IMAGE_IMPORT_DESCRIPTOR);
787 pe->iat_offs = dll_ptr + pe->imp_size;
788 pe->iat_size = (sym_cnt + ndlls) * sizeof(ADDR3264);
789 section_ptr_add(pe->thunk, pe->imp_size + 2*pe->iat_size);
791 thk_ptr = pe->iat_offs;
792 ent_ptr = pe->iat_offs + pe->iat_size;
794 for (i = 0; i < pe->imp_count; ++i) {
795 IMAGE_IMPORT_DESCRIPTOR *hdr;
796 int k, n, dllindex;
797 ADDR3264 v;
798 struct pe_import_info *p = pe->imp_info[i];
799 const char *name;
800 DLLReference *dllref;
802 dllindex = p->dll_index;
803 if (dllindex)
804 name = (dllref = pe->s1->loaded_dlls[dllindex-1])->name;
805 else
806 name = "", dllref = NULL;
808 /* put the dll name into the import header */
809 v = put_elf_str(pe->thunk, name);
810 hdr = (IMAGE_IMPORT_DESCRIPTOR*)(pe->thunk->data + dll_ptr);
811 hdr->FirstThunk = thk_ptr + rva_base;
812 hdr->OriginalFirstThunk = ent_ptr + rva_base;
813 hdr->Name = v + rva_base;
815 for (k = 0, n = p->sym_count; k <= n; ++k) {
816 int ordinal = 0;
817 if (k < n) {
818 int iat_index = p->symbols[k]->iat_index;
819 int sym_index = p->symbols[k]->sym_index;
820 ElfW(Sym) *imp_sym = (ElfW(Sym) *)pe->s1->dynsymtab_section->data + sym_index;
821 ElfW(Sym) *org_sym = (ElfW(Sym) *)symtab_section->data + iat_index;
822 const char *name = pe->s1->dynsymtab_section->link->data + imp_sym->st_name;
824 org_sym->st_value = thk_ptr;
825 org_sym->st_shndx = pe->thunk->sh_num;
826 v = pe->thunk->data_offset + rva_base;
828 /* ordinal or name */
829 ordinal = imp_sym->st_value; /* from pe_load_def, temperary use */
830 //if (ordinal) printf("ordinal: %d\n", ordinal);
831 if (!ordinal) {
832 section_ptr_add(pe->thunk, sizeof(WORD)); /* hint, not used */
833 put_elf_str(pe->thunk, name);
835 #ifdef TCC_IS_NATIVE
836 if (pe->type == PE_RUN) {
837 v = imp_sym->st_value;
838 if (dllref) {
839 if ( !dllref->handle )
840 dllref->handle = LoadLibrary(dllref->name);
841 v = (ADDR3264)GetProcAddress(dllref->handle, ordinal?(LPCSTR)NULL+ordinal:name);
843 if (!v)
844 tcc_error_noabort("can't build symbol '%s'", name);
846 #endif
847 } else {
848 v = 0; /* last entry is zero */
850 *(ADDR3264*)(pe->thunk->data+thk_ptr) =
851 *(ADDR3264*)(pe->thunk->data+ent_ptr) = (ordinal && pe->type != PE_RUN)?(ADDR3264)1<<(sizeof(ADDR3264)*8-1)|ordinal:v;
852 thk_ptr += sizeof (ADDR3264);
853 ent_ptr += sizeof (ADDR3264);
855 dll_ptr += sizeof(IMAGE_IMPORT_DESCRIPTOR);
856 dynarray_reset(&p->symbols, &p->sym_count);
858 dynarray_reset(&pe->imp_info, &pe->imp_count);
861 /* ------------------------------------------------------------- */
863 struct pe_sort_sym
865 int index;
866 const char *name;
869 static int sym_cmp(const void *va, const void *vb)
871 const char *ca = (*(struct pe_sort_sym**)va)->name;
872 const char *cb = (*(struct pe_sort_sym**)vb)->name;
873 return strcmp(ca, cb);
876 static void pe_build_exports(struct pe_info *pe)
878 ElfW(Sym) *sym;
879 int sym_index, sym_end;
880 DWORD rva_base, func_o, name_o, ord_o, str_o;
881 IMAGE_EXPORT_DIRECTORY *hdr;
882 int sym_count, ord;
883 struct pe_sort_sym **sorted, *p;
885 FILE *op;
886 char buf[MAX_PATH];
887 const char *dllname;
888 const char *name;
890 rva_base = pe->thunk->sh_addr - pe->imagebase;
891 sym_count = 0, sorted = NULL, op = NULL;
893 sym_end = symtab_section->data_offset / sizeof(ElfW(Sym));
894 for (sym_index = 1; sym_index < sym_end; ++sym_index) {
895 sym = (ElfW(Sym)*)symtab_section->data + sym_index;
896 name = pe_export_name(pe->s1, sym);
897 if ((sym->st_other & 1)
898 /* export only symbols from actually written sections */
899 && pe->s1->sections[sym->st_shndx]->sh_addr) {
900 p = tcc_malloc(sizeof *p);
901 p->index = sym_index;
902 p->name = name;
903 dynarray_add((void***)&sorted, &sym_count, p);
905 #if 0
906 if (sym->st_other & 1)
907 printf("export: %s\n", name);
908 if (sym->st_other & 2)
909 printf("stdcall: %s\n", name);
910 #endif
913 if (0 == sym_count)
914 return;
916 qsort (sorted, sym_count, sizeof *sorted, sym_cmp);
918 pe_align_section(pe->thunk, 16);
919 dllname = tcc_basename(pe->filename);
921 pe->exp_offs = pe->thunk->data_offset;
922 func_o = pe->exp_offs + sizeof(IMAGE_EXPORT_DIRECTORY);
923 name_o = func_o + sym_count * sizeof (DWORD);
924 ord_o = name_o + sym_count * sizeof (DWORD);
925 str_o = ord_o + sym_count * sizeof(WORD);
927 hdr = section_ptr_add(pe->thunk, str_o - pe->exp_offs);
928 hdr->Characteristics = 0;
929 hdr->Base = 1;
930 hdr->NumberOfFunctions = sym_count;
931 hdr->NumberOfNames = sym_count;
932 hdr->AddressOfFunctions = func_o + rva_base;
933 hdr->AddressOfNames = name_o + rva_base;
934 hdr->AddressOfNameOrdinals = ord_o + rva_base;
935 hdr->Name = str_o + rva_base;
936 put_elf_str(pe->thunk, dllname);
938 #if 1
939 /* automatically write exports to <output-filename>.def */
940 pstrcpy(buf, sizeof buf, pe->filename);
941 strcpy(tcc_fileextension(buf), ".def");
942 op = fopen(buf, "w");
943 if (NULL == op) {
944 tcc_error_noabort("could not create '%s': %s", buf, strerror(errno));
945 } else {
946 fprintf(op, "LIBRARY %s\n\nEXPORTS\n", dllname);
947 if (pe->s1->verbose)
948 printf("<- %s (%d symbols)\n", buf, sym_count);
950 #endif
952 for (ord = 0; ord < sym_count; ++ord)
954 p = sorted[ord], sym_index = p->index, name = p->name;
955 /* insert actual address later in pe_relocate_rva */
956 put_elf_reloc(symtab_section, pe->thunk,
957 func_o, R_XXX_RELATIVE, sym_index);
958 *(DWORD*)(pe->thunk->data + name_o)
959 = pe->thunk->data_offset + rva_base;
960 *(WORD*)(pe->thunk->data + ord_o)
961 = ord;
962 put_elf_str(pe->thunk, name);
963 func_o += sizeof (DWORD);
964 name_o += sizeof (DWORD);
965 ord_o += sizeof (WORD);
966 if (op)
967 fprintf(op, "%s\n", name);
969 pe->exp_size = pe->thunk->data_offset - pe->exp_offs;
970 dynarray_reset(&sorted, &sym_count);
971 if (op)
972 fclose(op);
975 /* ------------------------------------------------------------- */
976 static void pe_build_reloc (struct pe_info *pe)
978 DWORD offset, block_ptr, addr;
979 int count, i;
980 ElfW_Rel *rel, *rel_end;
981 Section *s = NULL, *sr;
983 offset = addr = block_ptr = count = i = 0;
984 rel = rel_end = NULL;
986 for(;;) {
987 if (rel < rel_end) {
988 int type = ELFW(R_TYPE)(rel->r_info);
989 addr = rel->r_offset + s->sh_addr;
990 ++ rel;
991 if (type != REL_TYPE_DIRECT)
992 continue;
993 if (count == 0) { /* new block */
994 block_ptr = pe->reloc->data_offset;
995 section_ptr_add(pe->reloc, sizeof(struct pe_reloc_header));
996 offset = addr & 0xFFFFFFFF<<12;
998 if ((addr -= offset) < (1<<12)) { /* one block spans 4k addresses */
999 WORD *wp = section_ptr_add(pe->reloc, sizeof (WORD));
1000 *wp = addr | IMAGE_REL_BASED_HIGHLOW<<12;
1001 ++count;
1002 continue;
1004 -- rel;
1006 } else if (i < pe->sec_count) {
1007 sr = (s = pe->s1->sections[pe->sec_info[i++].ord])->reloc;
1008 if (sr) {
1009 rel = (ElfW_Rel *)sr->data;
1010 rel_end = (ElfW_Rel *)(sr->data + sr->data_offset);
1012 continue;
1015 if (count) {
1016 /* store the last block and ready for a new one */
1017 struct pe_reloc_header *hdr;
1018 if (count & 1) /* align for DWORDS */
1019 section_ptr_add(pe->reloc, sizeof(WORD)), ++count;
1020 hdr = (struct pe_reloc_header *)(pe->reloc->data + block_ptr);
1021 hdr -> offset = offset - pe->imagebase;
1022 hdr -> size = count * sizeof(WORD) + sizeof(struct pe_reloc_header);
1023 count = 0;
1026 if (rel >= rel_end)
1027 break;
1031 /* ------------------------------------------------------------- */
1032 static int pe_section_class(Section *s)
1034 int type, flags;
1035 const char *name;
1037 type = s->sh_type;
1038 flags = s->sh_flags;
1039 name = s->name;
1040 if (flags & SHF_ALLOC) {
1041 if (type == SHT_PROGBITS) {
1042 if (flags & SHF_EXECINSTR)
1043 return sec_text;
1044 if (flags & SHF_WRITE)
1045 return sec_data;
1046 if (0 == strcmp(name, ".rsrc"))
1047 return sec_rsrc;
1048 if (0 == strcmp(name, ".iedat"))
1049 return sec_idata;
1050 if (0 == strcmp(name, ".pdata"))
1051 return sec_pdata;
1052 return sec_other;
1053 } else if (type == SHT_NOBITS) {
1054 if (flags & SHF_WRITE)
1055 return sec_bss;
1057 } else {
1058 if (0 == strcmp(name, ".reloc"))
1059 return sec_reloc;
1060 if (0 == strncmp(name, ".stab", 5)) /* .stab and .stabstr */
1061 return sec_stab;
1063 return -1;
1066 static int pe_assign_addresses (struct pe_info *pe)
1068 int i, k, o, c;
1069 DWORD addr;
1070 int *section_order;
1071 struct section_info *si;
1072 Section *s;
1074 // pe->thunk = new_section(pe->s1, ".iedat", SHT_PROGBITS, SHF_ALLOC);
1076 section_order = tcc_malloc(pe->s1->nb_sections * sizeof (int));
1077 for (o = k = 0 ; k < sec_last; ++k) {
1078 for (i = 1; i < pe->s1->nb_sections; ++i) {
1079 s = pe->s1->sections[i];
1080 if (k == pe_section_class(s)) {
1081 // printf("%s %d\n", s->name, k);
1082 s->sh_addr = pe->imagebase;
1083 section_order[o++] = i;
1088 pe->sec_info = tcc_mallocz(o * sizeof (struct section_info));
1089 addr = pe->imagebase + 1;
1091 for (i = 0; i < o; ++i)
1093 k = section_order[i];
1094 s = pe->s1->sections[k];
1095 c = pe_section_class(s);
1096 si = &pe->sec_info[pe->sec_count];
1098 #ifdef PE_MERGE_DATA
1099 if (c == sec_bss && pe->sec_count && si[-1].cls == sec_data) {
1100 /* append .bss to .data */
1101 s->sh_addr = addr = ((addr-1) | (s->sh_addralign-1)) + 1;
1102 addr += s->data_offset;
1103 si[-1].sh_size = addr - si[-1].sh_addr;
1104 continue;
1106 #endif
1107 if (c == sec_stab && 0 == pe->s1->do_debug)
1108 continue;
1110 strcpy(si->name, s->name);
1111 si->cls = c;
1112 si->ord = k;
1113 si->sh_addr = s->sh_addr = addr = pe_virtual_align(pe, addr);
1114 si->sh_flags = s->sh_flags;
1116 if (c == sec_data && NULL == pe->thunk)
1117 pe->thunk = s;
1119 if (s == pe->thunk) {
1120 pe_build_imports(pe);
1121 pe_build_exports(pe);
1124 if (c == sec_reloc)
1125 pe_build_reloc (pe);
1127 if (s->data_offset)
1129 if (s->sh_type != SHT_NOBITS) {
1130 si->data = s->data;
1131 si->data_size = s->data_offset;
1134 addr += s->data_offset;
1135 si->sh_size = s->data_offset;
1136 ++pe->sec_count;
1138 // printf("%08x %05x %s\n", si->sh_addr, si->sh_size, si->name);
1141 #if 0
1142 for (i = 1; i < pe->s1->nb_sections; ++i) {
1143 Section *s = pe->s1->sections[i];
1144 int type = s->sh_type;
1145 int flags = s->sh_flags;
1146 printf("section %-16s %-10s %5x %s,%s,%s\n",
1147 s->name,
1148 type == SHT_PROGBITS ? "progbits" :
1149 type == SHT_NOBITS ? "nobits" :
1150 type == SHT_SYMTAB ? "symtab" :
1151 type == SHT_STRTAB ? "strtab" :
1152 type == SHT_RELX ? "rel" : "???",
1153 s->data_offset,
1154 flags & SHF_ALLOC ? "alloc" : "",
1155 flags & SHF_WRITE ? "write" : "",
1156 flags & SHF_EXECINSTR ? "exec" : ""
1159 pe->s1->verbose = 2;
1160 #endif
1162 tcc_free(section_order);
1163 return 0;
1166 /* ------------------------------------------------------------- */
1167 static void pe_relocate_rva (struct pe_info *pe, Section *s)
1169 Section *sr = s->reloc;
1170 ElfW_Rel *rel, *rel_end;
1171 rel_end = (ElfW_Rel *)(sr->data + sr->data_offset);
1172 for(rel = (ElfW_Rel *)sr->data; rel < rel_end; rel++) {
1173 if (ELFW(R_TYPE)(rel->r_info) == R_XXX_RELATIVE) {
1174 int sym_index = ELFW(R_SYM)(rel->r_info);
1175 DWORD addr = s->sh_addr;
1176 if (sym_index) {
1177 ElfW(Sym) *sym = (ElfW(Sym) *)symtab_section->data + sym_index;
1178 addr = sym->st_value;
1180 // printf("reloc rva %08x %08x %s\n", (DWORD)rel->r_offset, addr, s->name);
1181 *(DWORD*)(s->data + rel->r_offset) += addr - pe->imagebase;
1186 /*----------------------------------------------------------------------------*/
1188 static int pe_isafunc(int sym_index)
1190 Section *sr = text_section->reloc;
1191 ElfW_Rel *rel, *rel_end;
1192 Elf32_Word info = ELF32_R_INFO(sym_index, R_386_PC32);
1193 if (!sr)
1194 return 0;
1195 rel_end = (ElfW_Rel *)(sr->data + sr->data_offset);
1196 for (rel = (ElfW_Rel *)sr->data; rel < rel_end; rel++)
1197 if (rel->r_info == info)
1198 return 1;
1199 return 0;
1202 /*----------------------------------------------------------------------------*/
1203 static int pe_check_symbols(struct pe_info *pe)
1205 ElfW(Sym) *sym;
1206 int sym_index, sym_end;
1207 int ret = 0;
1209 pe_align_section(text_section, 8);
1211 sym_end = symtab_section->data_offset / sizeof(ElfW(Sym));
1212 for (sym_index = 1; sym_index < sym_end; ++sym_index) {
1214 sym = (ElfW(Sym) *)symtab_section->data + sym_index;
1215 if (sym->st_shndx == SHN_UNDEF) {
1217 const char *name = symtab_section->link->data + sym->st_name;
1218 unsigned type = ELFW(ST_TYPE)(sym->st_info);
1219 int imp_sym = pe_find_import(pe->s1, sym);
1220 struct import_symbol *is;
1222 if (0 == imp_sym)
1223 goto not_found;
1225 if (type == STT_NOTYPE) {
1226 /* symbols from assembler have no type, find out which */
1227 if (pe_isafunc(sym_index))
1228 type = STT_FUNC;
1229 else
1230 type = STT_OBJECT;
1233 is = pe_add_import(pe, imp_sym);
1235 if (type == STT_FUNC) {
1236 unsigned long offset = is->thk_offset;
1237 if (offset) {
1238 /* got aliased symbol, like stricmp and _stricmp */
1240 } else {
1241 char buffer[100];
1242 WORD *p;
1244 offset = text_section->data_offset;
1245 /* add the 'jmp IAT[x]' instruction */
1246 #ifdef TCC_TARGET_ARM
1247 p = section_ptr_add(text_section, 8+4); // room for code and address
1248 (*(DWORD*)(p)) = 0xE59FC000; // arm code ldr ip, [pc] ; PC+8+0 = 0001xxxx
1249 (*(DWORD*)(p+2)) = 0xE59CF000; // arm code ldr pc, [ip]
1250 #else
1251 p = section_ptr_add(text_section, 8);
1252 *p = 0x25FF;
1253 #ifdef TCC_TARGET_X86_64
1254 *(DWORD*)(p+1) = (DWORD)-4;
1255 #endif
1256 #endif
1257 /* add a helper symbol, will be patched later in
1258 pe_build_imports */
1259 sprintf(buffer, "IAT.%s", name);
1260 is->iat_index = put_elf_sym(
1261 symtab_section, 0, sizeof(DWORD),
1262 ELFW(ST_INFO)(STB_GLOBAL, STT_OBJECT),
1263 0, SHN_UNDEF, buffer);
1264 #ifdef TCC_TARGET_ARM
1265 put_elf_reloc(symtab_section, text_section,
1266 offset + 8, R_XXX_THUNKFIX, is->iat_index); // offset to IAT position
1267 #else
1268 put_elf_reloc(symtab_section, text_section,
1269 offset + 2, R_XXX_THUNKFIX, is->iat_index);
1270 #endif
1271 is->thk_offset = offset;
1274 /* tcc_realloc might have altered sym's address */
1275 sym = (ElfW(Sym) *)symtab_section->data + sym_index;
1277 /* patch the original symbol */
1278 sym->st_value = offset;
1279 sym->st_shndx = text_section->sh_num;
1280 sym->st_other &= ~1; /* do not export */
1281 continue;
1284 if (type == STT_OBJECT) { /* data, ptr to that should be */
1285 if (0 == is->iat_index) {
1286 /* original symbol will be patched later in pe_build_imports */
1287 is->iat_index = sym_index;
1288 continue;
1292 not_found:
1293 tcc_error_noabort("undefined symbol '%s'", name);
1294 ret = -1;
1296 } else if (pe->s1->rdynamic
1297 && ELFW(ST_BIND)(sym->st_info) != STB_LOCAL) {
1298 /* if -rdynamic option, then export all non local symbols */
1299 sym->st_other |= 1;
1302 return ret;
1305 /*----------------------------------------------------------------------------*/
1306 #ifdef PE_PRINT_SECTIONS
1307 static void pe_print_section(FILE * f, Section * s)
1309 /* just if you'r curious */
1310 BYTE *p, *e, b;
1311 int i, n, l, m;
1312 p = s->data;
1313 e = s->data + s->data_offset;
1314 l = e - p;
1316 fprintf(f, "section \"%s\"", s->name);
1317 if (s->link)
1318 fprintf(f, "\nlink \"%s\"", s->link->name);
1319 if (s->reloc)
1320 fprintf(f, "\nreloc \"%s\"", s->reloc->name);
1321 fprintf(f, "\nv_addr %08X", (unsigned)s->sh_addr);
1322 fprintf(f, "\ncontents %08X", (unsigned)l);
1323 fprintf(f, "\n\n");
1325 if (s->sh_type == SHT_NOBITS)
1326 return;
1328 if (0 == l)
1329 return;
1331 if (s->sh_type == SHT_SYMTAB)
1332 m = sizeof(ElfW(Sym));
1333 else if (s->sh_type == SHT_RELX)
1334 m = sizeof(ElfW_Rel);
1335 else
1336 m = 16;
1338 fprintf(f, "%-8s", "offset");
1339 for (i = 0; i < m; ++i)
1340 fprintf(f, " %02x", i);
1341 n = 56;
1343 if (s->sh_type == SHT_SYMTAB || s->sh_type == SHT_RELX) {
1344 const char *fields1[] = {
1345 "name",
1346 "value",
1347 "size",
1348 "bind",
1349 "type",
1350 "other",
1351 "shndx",
1352 NULL
1355 const char *fields2[] = {
1356 "offs",
1357 "type",
1358 "symb",
1359 NULL
1362 const char **p;
1364 if (s->sh_type == SHT_SYMTAB)
1365 p = fields1, n = 106;
1366 else
1367 p = fields2, n = 58;
1369 for (i = 0; p[i]; ++i)
1370 fprintf(f, "%6s", p[i]);
1371 fprintf(f, " symbol");
1374 fprintf(f, "\n");
1375 for (i = 0; i < n; ++i)
1376 fprintf(f, "-");
1377 fprintf(f, "\n");
1379 for (i = 0; i < l;)
1381 fprintf(f, "%08X", i);
1382 for (n = 0; n < m; ++n) {
1383 if (n + i < l)
1384 fprintf(f, " %02X", p[i + n]);
1385 else
1386 fprintf(f, " ");
1389 if (s->sh_type == SHT_SYMTAB) {
1390 ElfW(Sym) *sym = (ElfW(Sym) *) (p + i);
1391 const char *name = s->link->data + sym->st_name;
1392 fprintf(f, " %04X %04X %04X %02X %02X %02X %04X \"%s\"",
1393 (unsigned)sym->st_name,
1394 (unsigned)sym->st_value,
1395 (unsigned)sym->st_size,
1396 (unsigned)ELFW(ST_BIND)(sym->st_info),
1397 (unsigned)ELFW(ST_TYPE)(sym->st_info),
1398 (unsigned)sym->st_other,
1399 (unsigned)sym->st_shndx,
1400 name);
1402 } else if (s->sh_type == SHT_RELX) {
1403 ElfW_Rel *rel = (ElfW_Rel *) (p + i);
1404 ElfW(Sym) *sym =
1405 (ElfW(Sym) *) s->link->data + ELFW(R_SYM)(rel->r_info);
1406 const char *name = s->link->link->data + sym->st_name;
1407 fprintf(f, " %04X %02X %04X \"%s\"",
1408 (unsigned)rel->r_offset,
1409 (unsigned)ELFW(R_TYPE)(rel->r_info),
1410 (unsigned)ELFW(R_SYM)(rel->r_info),
1411 name);
1412 } else {
1413 fprintf(f, " ");
1414 for (n = 0; n < m; ++n) {
1415 if (n + i < l) {
1416 b = p[i + n];
1417 if (b < 32 || b >= 127)
1418 b = '.';
1419 fprintf(f, "%c", b);
1423 i += m;
1424 fprintf(f, "\n");
1426 fprintf(f, "\n\n");
1429 static void pe_print_sections(TCCState *s1, const char *fname)
1431 Section *s;
1432 FILE *f;
1433 int i;
1434 f = fopen(fname, "w");
1435 for (i = 1; i < s1->nb_sections; ++i) {
1436 s = s1->sections[i];
1437 pe_print_section(f, s);
1439 pe_print_section(f, s1->dynsymtab_section);
1440 fclose(f);
1442 #endif
1444 /* ------------------------------------------------------------- */
1445 /* helper function for load/store to insert one more indirection */
1447 ST_FUNC SValue *pe_getimport(SValue *sv, SValue *v2)
1449 Sym *sym;
1450 ElfW(Sym) *esym;
1451 int r2;
1453 if ((sv->r & (VT_VALMASK|VT_SYM)) != (VT_CONST|VT_SYM) || (sv->r2 != VT_CONST))
1454 return sv;
1455 sym = sv->sym;
1456 if ((sym->type.t & (VT_EXTERN|VT_STATIC)) != VT_EXTERN)
1457 return sv;
1458 if (!sym->c)
1459 put_extern_sym(sym, NULL, 0, 0);
1460 esym = &((ElfW(Sym) *)symtab_section->data)[sym->c];
1461 if (!(esym->st_other & 4))
1462 return sv;
1464 // printf("import %04x %04x %04x %s\n", sv->type.t, sym->type.t, sv->r, get_tok_str(sv->sym->v, NULL));
1466 memset(v2, 0, sizeof *v2);
1467 v2->type.t = VT_PTR;
1468 v2->r = VT_CONST | VT_SYM | VT_LVAL;
1469 v2->sym = sv->sym;
1471 r2 = get_reg(RC_INT);
1472 load(r2, v2);
1473 v2->r = r2;
1475 if (sv->c.ui) {
1476 vpushv(v2);
1477 vpushi(sv->c.ui);
1478 gen_opi('+');
1479 *v2 = *vtop--;
1482 v2->type.t = sv->type.t;
1483 v2->r |= sv->r & VT_LVAL;
1484 return v2;
1487 ST_FUNC int pe_putimport(TCCState *s1, int dllindex, const char *name, addr_t value)
1489 return add_elf_sym(
1490 s1->dynsymtab_section,
1491 value,
1492 dllindex, /* st_size */
1493 ELFW(ST_INFO)(STB_GLOBAL, STT_NOTYPE),
1495 value ? SHN_ABS : SHN_UNDEF,
1496 name
1500 static int add_dllref(TCCState *s1, const char *dllname)
1502 DLLReference *dllref;
1503 int i;
1504 for (i = 0; i < s1->nb_loaded_dlls; ++i)
1505 if (0 == strcmp(s1->loaded_dlls[i]->name, dllname))
1506 return i + 1;
1507 dllref = tcc_mallocz(sizeof(DLLReference) + strlen(dllname));
1508 strcpy(dllref->name, dllname);
1509 dynarray_add((void ***) &s1->loaded_dlls, &s1->nb_loaded_dlls, dllref);
1510 return s1->nb_loaded_dlls;
1513 /* ------------------------------------------------------------- */
1515 static int read_mem(int fd, unsigned offset, void *buffer, unsigned len)
1517 lseek(fd, offset, SEEK_SET);
1518 return len == read(fd, buffer, len);
1521 /* -------------------------------------------------------------
1522 * This is for compiled windows resources in 'coff' format
1523 * as generated by 'windres.exe -O coff ...'.
1526 static int pe_load_res(TCCState *s1, int fd)
1528 struct pe_rsrc_header hdr;
1529 Section *rsrc_section;
1530 int i, ret = -1;
1531 BYTE *ptr;
1532 unsigned offs;
1534 if (!read_mem(fd, 0, &hdr, sizeof hdr))
1535 goto quit;
1537 if (hdr.filehdr.Machine != 0x014C
1538 || hdr.filehdr.NumberOfSections != 1
1539 || strcmp(hdr.sectionhdr.Name, ".rsrc") != 0)
1540 goto quit;
1542 rsrc_section = new_section(s1, ".rsrc", SHT_PROGBITS, SHF_ALLOC);
1543 ptr = section_ptr_add(rsrc_section, hdr.sectionhdr.SizeOfRawData);
1544 offs = hdr.sectionhdr.PointerToRawData;
1545 if (!read_mem(fd, offs, ptr, hdr.sectionhdr.SizeOfRawData))
1546 goto quit;
1547 offs = hdr.sectionhdr.PointerToRelocations;
1548 for (i = 0; i < hdr.sectionhdr.NumberOfRelocations; ++i)
1550 struct pe_rsrc_reloc rel;
1551 if (!read_mem(fd, offs, &rel, sizeof rel))
1552 goto quit;
1553 // printf("rsrc_reloc: %x %x %x\n", rel.offset, rel.size, rel.type);
1554 if (rel.type != 7) /* DIR32NB */
1555 goto quit;
1556 put_elf_reloc(symtab_section, rsrc_section,
1557 rel.offset, R_XXX_RELATIVE, 0);
1558 offs += sizeof rel;
1560 ret = 0;
1561 quit:
1562 return ret;
1565 /* ------------------------------------------------------------- */
1566 static char *trimfront(char *p)
1568 while (*p && (unsigned char)*p <= ' ')
1569 ++p;
1570 return p;
1573 static char *trimback(char *a, char *e)
1575 while (e > a && (unsigned char)e[-1] <= ' ')
1576 --e;
1577 *e = 0;;
1578 return a;
1581 static char *get_line(char *line, int size, int fd)
1583 int n;
1584 for (n = 0; n < size - 1; )
1585 if (read(fd, line + n, 1) < 1 || line[n++] == '\n')
1586 break;
1587 if (0 == n)
1588 return NULL;
1589 trimback(line, line + n);
1590 return trimfront(line);
1593 /* ------------------------------------------------------------- */
1594 static int pe_load_def(TCCState *s1, int fd)
1596 int state = 0, ret = -1, dllindex = 0;
1597 char line[400], dllname[80], *p;
1599 for (;;) {
1600 int ord = 0;
1601 char *x, *d, idxstr[8];
1602 p = get_line(line, sizeof line, fd);
1603 if (NULL == p)
1604 break;
1605 if (0 == *p || ';' == *p)
1606 continue;
1607 switch (state) {
1608 case 0:
1609 if (0 != strnicmp(p, "LIBRARY", 7))
1610 goto quit;
1611 pstrcpy(dllname, sizeof dllname, trimfront(p+7));
1612 ++state;
1613 continue;
1615 case 1:
1616 if (0 != stricmp(p, "EXPORTS"))
1617 goto quit;
1618 ++state;
1619 continue;
1621 case 2:
1622 dllindex = add_dllref(s1, dllname);
1623 ++state;
1625 default:
1626 /* get ordianl and will store in sym->st_value */
1627 d = NULL;
1628 x = strchr(line, ' ');
1629 if (x) x = strchr(line, '@');
1630 while (x != NULL) {
1631 d =x;
1632 x = strchr(x+1, '@');
1634 if (d) {
1635 ord = atoi(d+1);
1636 itoa(ord, idxstr, 10);
1637 if (strcmp(idxstr, d+1) == 0) {
1638 memset(d, 0, 1);
1639 trimback(p, d);
1640 } else
1641 ord = 0;
1643 pe_putimport(s1, dllindex, p, ord);
1644 continue;
1647 ret = 0;
1648 quit:
1649 return ret;
1652 /* ------------------------------------------------------------- */
1653 #define TINY_IMPDEF_GET_EXPORT_NAMES_ONLY
1654 #include "win32/tools/tiny_impdef.c"
1656 static int pe_load_dll(TCCState *s1, const char *dllname, int fd)
1658 char *p, *q;
1659 int index;
1660 p = get_export_names(fd);
1661 if (!p)
1662 return -1;
1663 index = add_dllref(s1, dllname);
1664 for (q = p; *q; q += 1 + strlen(q))
1665 pe_putimport(s1, index, q, 0);
1666 tcc_free(p);
1667 return 0;
1670 /* ------------------------------------------------------------- */
1671 ST_FUNC int pe_load_file(struct TCCState *s1, const char *filename, int fd)
1673 int ret = -1;
1674 char buf[10];
1675 if (0 == strcmp(tcc_fileextension(filename), ".def"))
1676 ret = pe_load_def(s1, fd);
1677 else if (pe_load_res(s1, fd) == 0)
1678 ret = 0;
1679 else if (read_mem(fd, 0, buf, sizeof buf) && 0 == strncmp(buf, "MZ", 2))
1680 ret = pe_load_dll(s1, tcc_basename(filename), fd);
1681 return ret;
1684 /* ------------------------------------------------------------- */
1685 #ifdef TCC_TARGET_X86_64
1686 static unsigned pe_add_uwwind_info(TCCState *s1)
1688 if (NULL == s1->uw_pdata) {
1689 s1->uw_pdata = find_section(tcc_state, ".pdata");
1690 s1->uw_pdata->sh_addralign = 4;
1691 s1->uw_sym = put_elf_sym(symtab_section, 0, 0, 0, 0, text_section->sh_num, NULL);
1694 if (0 == s1->uw_offs) {
1695 /* As our functions all have the same stackframe, we use one entry for all */
1696 static const unsigned char uw_info[] = {
1697 0x01, // UBYTE: 3 Version , UBYTE: 5 Flags
1698 0x04, // UBYTE Size of prolog
1699 0x02, // UBYTE Count of unwind codes
1700 0x05, // UBYTE: 4 Frame Register (rbp), UBYTE: 4 Frame Register offset (scaled)
1701 // USHORT * n Unwind codes array
1702 // 0x0b, 0x01, 0xff, 0xff, // stack size
1703 0x04, 0x03, // set frame ptr (mov rsp -> rbp)
1704 0x01, 0x50 // push reg (rbp)
1707 Section *s = text_section;
1708 unsigned char *p;
1710 section_ptr_add(s, -s->data_offset & 3); /* align */
1711 s1->uw_offs = s->data_offset;
1712 p = section_ptr_add(s, sizeof uw_info);
1713 memcpy(p, uw_info, sizeof uw_info);
1716 return s1->uw_offs;
1719 ST_FUNC void pe_add_unwind_data(unsigned start, unsigned end, unsigned stack)
1721 TCCState *s1 = tcc_state;
1722 Section *pd;
1723 unsigned o, n, d;
1724 struct /* _RUNTIME_FUNCTION */ {
1725 DWORD BeginAddress;
1726 DWORD EndAddress;
1727 DWORD UnwindData;
1728 } *p;
1730 d = pe_add_uwwind_info(s1);
1731 pd = s1->uw_pdata;
1732 o = pd->data_offset;
1733 p = section_ptr_add(pd, sizeof *p);
1735 /* record this function */
1736 p->BeginAddress = start;
1737 p->EndAddress = end;
1738 p->UnwindData = d;
1740 /* put relocations on it */
1741 for (n = o + sizeof *p; o < n; o += sizeof p->BeginAddress)
1742 put_elf_reloc(symtab_section, pd, o, R_X86_64_RELATIVE, s1->uw_sym);
1744 #endif
1745 /* ------------------------------------------------------------- */
1746 #ifdef TCC_TARGET_X86_64
1747 #define PE_STDSYM(n,s) n
1748 #else
1749 #define PE_STDSYM(n,s) "_" n s
1750 #endif
1752 static void pe_add_runtime(TCCState *s1, struct pe_info *pe)
1754 const char *start_symbol;
1755 int pe_type = 0;
1757 if (find_elf_sym(symtab_section, PE_STDSYM("WinMain","@16")))
1758 pe_type = PE_GUI;
1759 else
1760 if (TCC_OUTPUT_DLL == s1->output_type) {
1761 pe_type = PE_DLL;
1762 /* need this for 'tccelf.c:relocate_section()' */
1763 s1->output_type = TCC_OUTPUT_EXE;
1765 else
1766 pe_type = PE_EXE;
1768 start_symbol =
1769 TCC_OUTPUT_MEMORY == s1->output_type
1770 ? PE_GUI == pe_type ? "__runwinmain" : "_main"
1771 : PE_DLL == pe_type ? PE_STDSYM("__dllstart","@12")
1772 : PE_GUI == pe_type ? "__winstart" : "__start"
1775 if (!s1->leading_underscore || strchr(start_symbol, '@'))
1776 ++start_symbol;
1778 /* grab the startup code from libtcc1 */
1779 if (TCC_OUTPUT_MEMORY != s1->output_type || PE_GUI == pe_type)
1780 add_elf_sym(symtab_section,
1781 0, 0,
1782 ELFW(ST_INFO)(STB_GLOBAL, STT_NOTYPE), 0,
1783 SHN_UNDEF, start_symbol);
1785 if (0 == s1->nostdlib) {
1786 static const char *libs[] = {
1787 "libtcc1.a", "msvcrt", "kernel32", "", "user32", "gdi32", NULL
1789 const char **pp, *p;
1790 for (pp = libs; 0 != (p = *pp); ++pp) {
1791 if (0 == *p) {
1792 if (PE_DLL != pe_type && PE_GUI != pe_type)
1793 break;
1794 } else if (pp == libs ? tcc_add_dll(s1, p, 0) : tcc_add_library(s1, p)) {
1795 tcc_error_noabort("cannot find library: %s", p);
1796 break;
1801 if (TCC_OUTPUT_MEMORY == s1->output_type) {
1802 pe_type = PE_RUN;
1803 #ifdef TCC_IS_NATIVE
1804 s1->runtime_main = start_symbol;
1805 #endif
1806 } else {
1807 pe->start_addr = (DWORD)tcc_get_symbol_err(s1, start_symbol);
1810 pe->type = pe_type;
1813 ST_FUNC int pe_output_file(TCCState * s1, const char *filename)
1815 int ret;
1816 struct pe_info pe;
1817 int i;
1819 memset(&pe, 0, sizeof pe);
1820 pe.filename = filename;
1821 pe.s1 = s1;
1823 tcc_add_bcheck(s1);
1824 pe_add_runtime(s1, &pe);
1825 relocate_common_syms(); /* assign bss adresses */
1826 tcc_add_linker_symbols(s1);
1828 ret = pe_check_symbols(&pe);
1829 if (ret)
1831 else if (filename) {
1832 if (PE_DLL == pe.type) {
1833 pe.reloc = new_section(pe.s1, ".reloc", SHT_PROGBITS, 0);
1834 /* XXX: check if is correct for arm-pe target */
1835 pe.imagebase = 0x10000000;
1836 } else {
1837 #if defined(TCC_TARGET_ARM)
1838 pe.imagebase = 0x00010000;
1839 #else
1840 pe.imagebase = 0x00400000;
1841 #endif
1844 #if defined(TCC_TARGET_ARM)
1845 /* we use "console" subsystem by default */
1846 pe.subsystem = 9;
1847 #else
1848 if (PE_DLL == pe.type || PE_GUI == pe.type)
1849 pe.subsystem = 2;
1850 else
1851 pe.subsystem = 3;
1852 #endif
1853 /* Allow override via -Wl,-subsystem=... option */
1854 if (s1->pe_subsystem != 0)
1855 pe.subsystem = s1->pe_subsystem;
1857 /* set default file/section alignment */
1858 if (pe.subsystem == 1) {
1859 pe.section_align = 0x20;
1860 pe.file_align = 0x20;
1861 } else {
1862 pe.section_align = 0x1000;
1863 pe.file_align = 0x200;
1866 if (s1->section_align != 0)
1867 pe.section_align = s1->section_align;
1868 if (s1->pe_file_align != 0)
1869 pe.file_align = s1->pe_file_align;
1871 if ((pe.subsystem >= 10) && (pe.subsystem <= 12))
1872 pe.imagebase = 0;
1874 if (s1->has_text_addr)
1875 pe.imagebase = s1->text_addr;
1877 pe_assign_addresses(&pe);
1878 relocate_syms(s1, 0);
1879 for (i = 1; i < s1->nb_sections; ++i) {
1880 Section *s = s1->sections[i];
1881 if (s->reloc) {
1882 relocate_section(s1, s);
1883 pe_relocate_rva(&pe, s);
1886 if (s1->nb_errors)
1887 ret = -1;
1888 else
1889 ret = pe_write(&pe);
1890 tcc_free(pe.sec_info);
1891 } else {
1892 #ifdef TCC_IS_NATIVE
1893 pe.thunk = data_section;
1894 pe_build_imports(&pe);
1895 #endif
1898 #ifdef PE_PRINT_SECTIONS
1899 pe_print_sections(s1, "tcc.log");
1900 #endif
1901 return ret;
1904 /* ------------------------------------------------------------- */