tccpp: signal missing #endif error
[tinycc/kirr.git] / tccpe.c
blobe8321dc37fa35be33da8cdff549540bd9596a394
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 #if defined _WIN32 && (defined _WIN64) == (defined TCC_TARGET_X86_64)
42 #define TCC_IS_NATIVE
43 #endif
45 #ifdef _WIN32
46 void dbg_printf (const char *fmt, ...)
48 char buffer[4000];
49 va_list arg;
50 int x;
51 va_start(arg, fmt);
52 x = vsprintf (buffer, fmt, arg);
53 strcpy(buffer+x, "\n");
54 OutputDebugString(buffer);
56 #endif
58 /* ----------------------------------------------------------- */
59 #ifndef IMAGE_NT_SIGNATURE
60 /* ----------------------------------------------------------- */
61 /* definitions below are from winnt.h */
63 typedef unsigned char BYTE;
64 typedef unsigned short WORD;
65 typedef unsigned long DWORD;
66 typedef unsigned long long ULONGLONG;
67 #pragma pack(push, 1)
69 typedef struct _IMAGE_DOS_HEADER { /* DOS .EXE header */
70 WORD e_magic; /* Magic number */
71 WORD e_cblp; /* Bytes on last page of file */
72 WORD e_cp; /* Pages in file */
73 WORD e_crlc; /* Relocations */
74 WORD e_cparhdr; /* Size of header in paragraphs */
75 WORD e_minalloc; /* Minimum extra paragraphs needed */
76 WORD e_maxalloc; /* Maximum extra paragraphs needed */
77 WORD e_ss; /* Initial (relative) SS value */
78 WORD e_sp; /* Initial SP value */
79 WORD e_csum; /* Checksum */
80 WORD e_ip; /* Initial IP value */
81 WORD e_cs; /* Initial (relative) CS value */
82 WORD e_lfarlc; /* File address of relocation table */
83 WORD e_ovno; /* Overlay number */
84 WORD e_res[4]; /* Reserved words */
85 WORD e_oemid; /* OEM identifier (for e_oeminfo) */
86 WORD e_oeminfo; /* OEM information; e_oemid specific */
87 WORD e_res2[10]; /* Reserved words */
88 DWORD e_lfanew; /* File address of new exe header */
89 } IMAGE_DOS_HEADER, *PIMAGE_DOS_HEADER;
91 #define IMAGE_NT_SIGNATURE 0x00004550 /* PE00 */
92 #define SIZE_OF_NT_SIGNATURE 4
94 typedef struct _IMAGE_FILE_HEADER {
95 WORD Machine;
96 WORD NumberOfSections;
97 DWORD TimeDateStamp;
98 DWORD PointerToSymbolTable;
99 DWORD NumberOfSymbols;
100 WORD SizeOfOptionalHeader;
101 WORD Characteristics;
102 } IMAGE_FILE_HEADER, *PIMAGE_FILE_HEADER;
105 #define IMAGE_SIZEOF_FILE_HEADER 20
107 typedef struct _IMAGE_DATA_DIRECTORY {
108 DWORD VirtualAddress;
109 DWORD Size;
110 } IMAGE_DATA_DIRECTORY, *PIMAGE_DATA_DIRECTORY;
113 typedef struct _IMAGE_OPTIONAL_HEADER {
114 /* Standard fields. */
115 WORD Magic;
116 BYTE MajorLinkerVersion;
117 BYTE MinorLinkerVersion;
118 DWORD SizeOfCode;
119 DWORD SizeOfInitializedData;
120 DWORD SizeOfUninitializedData;
121 DWORD AddressOfEntryPoint;
122 DWORD BaseOfCode;
123 #ifndef TCC_TARGET_X86_64
124 DWORD BaseOfData;
125 #endif
126 /* NT additional fields. */
127 ADDR3264 ImageBase;
128 DWORD SectionAlignment;
129 DWORD FileAlignment;
130 WORD MajorOperatingSystemVersion;
131 WORD MinorOperatingSystemVersion;
132 WORD MajorImageVersion;
133 WORD MinorImageVersion;
134 WORD MajorSubsystemVersion;
135 WORD MinorSubsystemVersion;
136 DWORD Win32VersionValue;
137 DWORD SizeOfImage;
138 DWORD SizeOfHeaders;
139 DWORD CheckSum;
140 WORD Subsystem;
141 WORD DllCharacteristics;
142 ADDR3264 SizeOfStackReserve;
143 ADDR3264 SizeOfStackCommit;
144 ADDR3264 SizeOfHeapReserve;
145 ADDR3264 SizeOfHeapCommit;
146 DWORD LoaderFlags;
147 DWORD NumberOfRvaAndSizes;
148 IMAGE_DATA_DIRECTORY DataDirectory[16];
149 } IMAGE_OPTIONAL_HEADER32, IMAGE_OPTIONAL_HEADER64, IMAGE_OPTIONAL_HEADER;
151 #define IMAGE_DIRECTORY_ENTRY_EXPORT 0 /* Export Directory */
152 #define IMAGE_DIRECTORY_ENTRY_IMPORT 1 /* Import Directory */
153 #define IMAGE_DIRECTORY_ENTRY_RESOURCE 2 /* Resource Directory */
154 #define IMAGE_DIRECTORY_ENTRY_EXCEPTION 3 /* Exception Directory */
155 #define IMAGE_DIRECTORY_ENTRY_SECURITY 4 /* Security Directory */
156 #define IMAGE_DIRECTORY_ENTRY_BASERELOC 5 /* Base Relocation Table */
157 #define IMAGE_DIRECTORY_ENTRY_DEBUG 6 /* Debug Directory */
158 /* IMAGE_DIRECTORY_ENTRY_COPYRIGHT 7 (X86 usage) */
159 #define IMAGE_DIRECTORY_ENTRY_ARCHITECTURE 7 /* Architecture Specific Data */
160 #define IMAGE_DIRECTORY_ENTRY_GLOBALPTR 8 /* RVA of GP */
161 #define IMAGE_DIRECTORY_ENTRY_TLS 9 /* TLS Directory */
162 #define IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG 10 /* Load Configuration Directory */
163 #define IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT 11 /* Bound Import Directory in headers */
164 #define IMAGE_DIRECTORY_ENTRY_IAT 12 /* Import Address Table */
165 #define IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT 13 /* Delay Load Import Descriptors */
166 #define IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR 14 /* COM Runtime descriptor */
168 /* Section header format. */
169 #define IMAGE_SIZEOF_SHORT_NAME 8
171 typedef struct _IMAGE_SECTION_HEADER {
172 BYTE Name[IMAGE_SIZEOF_SHORT_NAME];
173 union {
174 DWORD PhysicalAddress;
175 DWORD VirtualSize;
176 } Misc;
177 DWORD VirtualAddress;
178 DWORD SizeOfRawData;
179 DWORD PointerToRawData;
180 DWORD PointerToRelocations;
181 DWORD PointerToLinenumbers;
182 WORD NumberOfRelocations;
183 WORD NumberOfLinenumbers;
184 DWORD Characteristics;
185 } IMAGE_SECTION_HEADER, *PIMAGE_SECTION_HEADER;
187 #define IMAGE_SIZEOF_SECTION_HEADER 40
189 typedef struct _IMAGE_EXPORT_DIRECTORY {
190 DWORD Characteristics;
191 DWORD TimeDateStamp;
192 WORD MajorVersion;
193 WORD MinorVersion;
194 DWORD Name;
195 DWORD Base;
196 DWORD NumberOfFunctions;
197 DWORD NumberOfNames;
198 DWORD AddressOfFunctions;
199 DWORD AddressOfNames;
200 DWORD AddressOfNameOrdinals;
201 } IMAGE_EXPORT_DIRECTORY,*PIMAGE_EXPORT_DIRECTORY;
203 typedef struct _IMAGE_IMPORT_DESCRIPTOR {
204 union {
205 DWORD Characteristics;
206 DWORD OriginalFirstThunk;
208 DWORD TimeDateStamp;
209 DWORD ForwarderChain;
210 DWORD Name;
211 DWORD FirstThunk;
212 } IMAGE_IMPORT_DESCRIPTOR;
214 typedef struct _IMAGE_BASE_RELOCATION {
215 DWORD VirtualAddress;
216 DWORD SizeOfBlock;
217 // WORD TypeOffset[1];
218 } IMAGE_BASE_RELOCATION;
220 #define IMAGE_SIZEOF_BASE_RELOCATION 8
222 #define IMAGE_REL_BASED_ABSOLUTE 0
223 #define IMAGE_REL_BASED_HIGH 1
224 #define IMAGE_REL_BASED_LOW 2
225 #define IMAGE_REL_BASED_HIGHLOW 3
226 #define IMAGE_REL_BASED_HIGHADJ 4
227 #define IMAGE_REL_BASED_MIPS_JMPADDR 5
228 #define IMAGE_REL_BASED_SECTION 6
229 #define IMAGE_REL_BASED_REL32 7
231 #pragma pack(pop)
233 /* ----------------------------------------------------------- */
234 #endif /* ndef IMAGE_NT_SIGNATURE */
235 /* ----------------------------------------------------------- */
236 #pragma pack(push, 1)
238 struct pe_header
240 IMAGE_DOS_HEADER doshdr;
241 BYTE dosstub[0x40];
242 DWORD nt_sig;
243 IMAGE_FILE_HEADER filehdr;
244 #ifdef TCC_TARGET_X86_64
245 IMAGE_OPTIONAL_HEADER64 opthdr;
246 #else
247 #ifdef _WIN64
248 IMAGE_OPTIONAL_HEADER32 opthdr;
249 #else
250 IMAGE_OPTIONAL_HEADER opthdr;
251 #endif
252 #endif
255 struct pe_reloc_header {
256 DWORD offset;
257 DWORD size;
260 struct pe_rsrc_header {
261 struct _IMAGE_FILE_HEADER filehdr;
262 struct _IMAGE_SECTION_HEADER sectionhdr;
265 struct pe_rsrc_reloc {
266 DWORD offset;
267 DWORD size;
268 WORD type;
271 #pragma pack(pop)
273 /* ------------------------------------------------------------- */
274 /* internal temporary structures */
277 #define IMAGE_SCN_CNT_CODE 0x00000020
278 #define IMAGE_SCN_CNT_INITIALIZED_DATA 0x00000040
279 #define IMAGE_SCN_CNT_UNINITIALIZED_DATA 0x00000080
280 #define IMAGE_SCN_MEM_DISCARDABLE 0x02000000
281 #define IMAGE_SCN_MEM_SHARED 0x10000000
282 #define IMAGE_SCN_MEM_EXECUTE 0x20000000
283 #define IMAGE_SCN_MEM_READ 0x40000000
284 #define IMAGE_SCN_MEM_WRITE 0x80000000
287 enum {
288 sec_text = 0,
289 sec_data ,
290 sec_bss ,
291 sec_idata ,
292 sec_pdata ,
293 sec_other ,
294 sec_rsrc ,
295 sec_stab ,
296 sec_reloc ,
297 sec_last
300 static const DWORD pe_sec_flags[] = {
301 0x60000020, /* ".text" , */
302 0xC0000040, /* ".data" , */
303 0xC0000080, /* ".bss" , */
304 0x40000040, /* ".idata" , */
305 0x40000040, /* ".pdata" , */
306 0xE0000060, /* < other > , */
307 0x40000040, /* ".rsrc" , */
308 0x42000802, /* ".stab" , */
309 0x42000040, /* ".reloc" , */
312 struct section_info {
313 int cls, ord;
314 char name[32];
315 DWORD sh_addr;
316 DWORD sh_size;
317 DWORD sh_flags;
318 unsigned char *data;
319 DWORD data_size;
320 IMAGE_SECTION_HEADER ish;
323 struct import_symbol {
324 int sym_index;
325 int iat_index;
326 int thk_offset;
329 struct pe_import_info {
330 int dll_index;
331 int sym_count;
332 struct import_symbol **symbols;
335 struct pe_info {
336 TCCState *s1;
337 Section *reloc;
338 Section *thunk;
339 const char *filename;
340 int type;
341 DWORD sizeofheaders;
342 DWORD imagebase;
343 DWORD start_addr;
344 DWORD imp_offs;
345 DWORD imp_size;
346 DWORD iat_offs;
347 DWORD iat_size;
348 DWORD exp_offs;
349 DWORD exp_size;
350 int subsystem;
351 DWORD section_align;
352 DWORD file_align;
353 struct section_info *sec_info;
354 int sec_count;
355 struct pe_import_info **imp_info;
356 int imp_count;
359 #define PE_NUL 0
360 #define PE_DLL 1
361 #define PE_GUI 2
362 #define PE_EXE 3
363 #define PE_RUN 4
365 /* --------------------------------------------*/
367 static const char* get_alt_symbol(char *buffer, const char *symbol)
369 const char *p;
370 p = strrchr(symbol, '@');
371 if (p && isnum(p[1]) && symbol[0] == '_') { /* stdcall decor */
372 strcpy(buffer, symbol+1)[p-symbol-1] = 0;
373 } else if (symbol[0] != '_') { /* try non-ansi function */
374 buffer[0] = '_', strcpy(buffer + 1, symbol);
375 } else if (0 == memcmp(symbol, "__imp__", 7)) { /* mingw 2.0 */
376 strcpy(buffer, symbol + 6);
377 } else if (0 == memcmp(symbol, "_imp___", 7)) { /* mingw 3.7 */
378 strcpy(buffer, symbol + 6);
379 } else {
380 return symbol;
382 return buffer;
385 static int pe_find_import(TCCState * s1, const char *symbol)
387 char buffer[200];
388 const char *s;
389 int sym_index, n = 0;
390 do {
391 s = n ? get_alt_symbol(buffer, symbol) : symbol;
392 sym_index = find_elf_sym(s1->dynsymtab_section, s);
393 // printf("find (%d) %d %s\n", n, sym_index, s);
394 } while (0 == sym_index && ++n < 2);
395 return sym_index;
398 /*----------------------------------------------------------------------------*/
400 static int dynarray_assoc(void **pp, int n, int key)
402 int i;
403 for (i = 0; i < n; ++i, ++pp)
404 if (key == **(int **) pp)
405 return i;
406 return -1;
409 #if 0
410 ST_FN DWORD umin(DWORD a, DWORD b)
412 return a < b ? a : b;
414 #endif
416 static DWORD umax(DWORD a, DWORD b)
418 return a < b ? b : a;
421 static DWORD pe_file_align(struct pe_info *pe, DWORD n)
423 return (n + (pe->file_align - 1)) & ~(pe->file_align - 1);
426 static DWORD pe_virtual_align(struct pe_info *pe, DWORD n)
428 return (n + (pe->section_align - 1)) & ~(pe->section_align - 1);
431 static void pe_align_section(Section *s, int a)
433 int i = s->data_offset & (a-1);
434 if (i)
435 section_ptr_add(s, a - i);
438 static void pe_set_datadir(struct pe_header *hdr, int dir, DWORD addr, DWORD size)
440 hdr->opthdr.DataDirectory[dir].VirtualAddress = addr;
441 hdr->opthdr.DataDirectory[dir].Size = size;
444 static int pe_fwrite(void *data, unsigned len, FILE *fp, DWORD *psum)
446 if (psum) {
447 DWORD sum = *psum;
448 WORD *p = data;
449 int i;
450 for (i = len; i > 0; i -= 2) {
451 sum += (i >= 2) ? *p++ : *(BYTE*)p;
452 sum = (sum + (sum >> 16)) & 0xFFFF;
454 *psum = sum;
456 return len == fwrite(data, 1, len, fp) ? 0 : -1;
459 static void pe_fpad(FILE *fp, DWORD new_pos)
461 DWORD pos = ftell(fp);
462 while (++pos <= new_pos)
463 fputc(0, fp);
466 /*----------------------------------------------------------------------------*/
467 static int pe_write(struct pe_info *pe)
469 static const struct pe_header pe_template = {
471 /* IMAGE_DOS_HEADER doshdr */
472 0x5A4D, /*WORD e_magic; Magic number */
473 0x0090, /*WORD e_cblp; Bytes on last page of file */
474 0x0003, /*WORD e_cp; Pages in file */
475 0x0000, /*WORD e_crlc; Relocations */
477 0x0004, /*WORD e_cparhdr; Size of header in paragraphs */
478 0x0000, /*WORD e_minalloc; Minimum extra paragraphs needed */
479 0xFFFF, /*WORD e_maxalloc; Maximum extra paragraphs needed */
480 0x0000, /*WORD e_ss; Initial (relative) SS value */
482 0x00B8, /*WORD e_sp; Initial SP value */
483 0x0000, /*WORD e_csum; Checksum */
484 0x0000, /*WORD e_ip; Initial IP value */
485 0x0000, /*WORD e_cs; Initial (relative) CS value */
486 0x0040, /*WORD e_lfarlc; File address of relocation table */
487 0x0000, /*WORD e_ovno; Overlay number */
488 {0,0,0,0}, /*WORD e_res[4]; Reserved words */
489 0x0000, /*WORD e_oemid; OEM identifier (for e_oeminfo) */
490 0x0000, /*WORD e_oeminfo; OEM information; e_oemid specific */
491 {0,0,0,0,0,0,0,0,0,0}, /*WORD e_res2[10]; Reserved words */
492 0x00000080 /*DWORD e_lfanew; File address of new exe header */
494 /* BYTE dosstub[0x40] */
495 /* 14 code bytes + "This program cannot be run in DOS mode.\r\r\n$" + 6 * 0x00 */
496 0x0e,0x1f,0xba,0x0e,0x00,0xb4,0x09,0xcd,0x21,0xb8,0x01,0x4c,0xcd,0x21,0x54,0x68,
497 0x69,0x73,0x20,0x70,0x72,0x6f,0x67,0x72,0x61,0x6d,0x20,0x63,0x61,0x6e,0x6e,0x6f,
498 0x74,0x20,0x62,0x65,0x20,0x72,0x75,0x6e,0x20,0x69,0x6e,0x20,0x44,0x4f,0x53,0x20,
499 0x6d,0x6f,0x64,0x65,0x2e,0x0d,0x0d,0x0a,0x24,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
501 0x00004550, /* DWORD nt_sig = IMAGE_NT_SIGNATURE */
503 /* IMAGE_FILE_HEADER filehdr */
504 #if defined(TCC_TARGET_I386)
505 0x014C, /*WORD Machine; */
506 #elif defined(TCC_TARGET_X86_64)
507 0x8664, /*WORD Machine; */
508 #elif defined(TCC_TARGET_ARM)
509 0x01C0, /*WORD Machine; */
510 #endif
511 0x0003, /*WORD NumberOfSections; */
512 0x00000000, /*DWORD TimeDateStamp; */
513 0x00000000, /*DWORD PointerToSymbolTable; */
514 0x00000000, /*DWORD NumberOfSymbols; */
515 #if defined(TCC_TARGET_X86_64)
516 0x00F0, /*WORD SizeOfOptionalHeader; */
517 0x022F /*WORD Characteristics; */
518 #define CHARACTERISTICS_DLL 0x222E
519 #elif defined(TCC_TARGET_I386)
520 0x00E0, /*WORD SizeOfOptionalHeader; */
521 0x030F /*WORD Characteristics; */
522 #define CHARACTERISTICS_DLL 0x230E
523 #elif defined(TCC_TARGET_ARM)
524 0x00E0, /*WORD SizeOfOptionalHeader; */
525 0x010F, /*WORD Characteristics; */
526 #define CHARACTERISTICS_DLL 0x230F
527 #endif
529 /* IMAGE_OPTIONAL_HEADER opthdr */
530 /* Standard fields. */
531 #ifdef TCC_TARGET_X86_64
532 0x020B, /*WORD Magic; */
533 #else
534 0x010B, /*WORD Magic; */
535 #endif
536 0x06, /*BYTE MajorLinkerVersion; */
537 0x00, /*BYTE MinorLinkerVersion; */
538 0x00000000, /*DWORD SizeOfCode; */
539 0x00000000, /*DWORD SizeOfInitializedData; */
540 0x00000000, /*DWORD SizeOfUninitializedData; */
541 0x00000000, /*DWORD AddressOfEntryPoint; */
542 0x00000000, /*DWORD BaseOfCode; */
543 #ifndef TCC_TARGET_X86_64
544 0x00000000, /*DWORD BaseOfData; */
545 #endif
546 /* NT additional fields. */
547 #if defined(TCC_TARGET_ARM)
548 0x00100000, /*DWORD ImageBase; */
549 #else
550 0x00400000, /*DWORD ImageBase; */
551 #endif
552 0x00001000, /*DWORD SectionAlignment; */
553 0x00000200, /*DWORD FileAlignment; */
554 0x0004, /*WORD MajorOperatingSystemVersion; */
555 0x0000, /*WORD MinorOperatingSystemVersion; */
556 0x0000, /*WORD MajorImageVersion; */
557 0x0000, /*WORD MinorImageVersion; */
558 0x0004, /*WORD MajorSubsystemVersion; */
559 0x0000, /*WORD MinorSubsystemVersion; */
560 0x00000000, /*DWORD Win32VersionValue; */
561 0x00000000, /*DWORD SizeOfImage; */
562 0x00000200, /*DWORD SizeOfHeaders; */
563 0x00000000, /*DWORD CheckSum; */
564 0x0002, /*WORD Subsystem; */
565 0x0000, /*WORD DllCharacteristics; */
566 0x00100000, /*DWORD SizeOfStackReserve; */
567 0x00001000, /*DWORD SizeOfStackCommit; */
568 0x00100000, /*DWORD SizeOfHeapReserve; */
569 0x00001000, /*DWORD SizeOfHeapCommit; */
570 0x00000000, /*DWORD LoaderFlags; */
571 0x00000010, /*DWORD NumberOfRvaAndSizes; */
573 /* IMAGE_DATA_DIRECTORY DataDirectory[16]; */
574 {{0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0},
575 {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}}
578 struct pe_header pe_header = pe_template;
580 int i;
581 FILE *op;
582 DWORD file_offset, sum;
583 struct section_info *si;
584 IMAGE_SECTION_HEADER *psh;
586 op = fopen(pe->filename, "wb");
587 if (NULL == op) {
588 error_noabort("could not write '%s': %s", pe->filename, strerror(errno));
589 return -1;
592 pe->sizeofheaders = pe_file_align(pe,
593 sizeof (struct pe_header)
594 + pe->sec_count * sizeof (IMAGE_SECTION_HEADER)
597 file_offset = pe->sizeofheaders;
599 if (2 == pe->s1->verbose)
600 printf("-------------------------------"
601 "\n virt file size section" "\n");
602 for (i = 0; i < pe->sec_count; ++i) {
603 unsigned long addr, size;
604 const char *sh_name;
606 si = pe->sec_info + i;
607 sh_name = si->name;
608 addr = si->sh_addr - pe->imagebase;
609 size = si->sh_size;
610 psh = &si->ish;
612 if (2 == pe->s1->verbose)
613 printf("%6lx %6lx %6lx %s\n",
614 addr, file_offset, size, sh_name);
616 switch (si->cls) {
617 case sec_text:
618 pe_header.opthdr.BaseOfCode = addr;
619 pe_header.opthdr.AddressOfEntryPoint = addr + pe->start_addr;
620 break;
622 case sec_data:
623 #ifndef TCC_TARGET_X86_64
624 pe_header.opthdr.BaseOfData = addr;
625 #endif
626 break;
628 case sec_bss:
629 break;
631 case sec_reloc:
632 pe_set_datadir(&pe_header, IMAGE_DIRECTORY_ENTRY_BASERELOC, addr, size);
633 break;
635 case sec_rsrc:
636 pe_set_datadir(&pe_header, IMAGE_DIRECTORY_ENTRY_RESOURCE, addr, size);
637 break;
639 case sec_pdata:
640 pe_set_datadir(&pe_header, IMAGE_DIRECTORY_ENTRY_EXCEPTION, addr, size);
641 break;
643 case sec_stab:
644 break;
647 if (pe->thunk == pe->s1->sections[si->ord]) {
648 if (pe->imp_size) {
649 pe_set_datadir(&pe_header, IMAGE_DIRECTORY_ENTRY_IMPORT,
650 pe->imp_offs + addr, pe->imp_size);
651 pe_set_datadir(&pe_header, IMAGE_DIRECTORY_ENTRY_IAT,
652 pe->iat_offs + addr, pe->iat_size);
654 if (pe->exp_size) {
655 pe_set_datadir(&pe_header, IMAGE_DIRECTORY_ENTRY_EXPORT,
656 pe->exp_offs + addr, pe->exp_size);
660 strcpy((char*)psh->Name, sh_name);
662 psh->Characteristics = pe_sec_flags[si->cls];
663 psh->VirtualAddress = addr;
664 psh->Misc.VirtualSize = size;
665 pe_header.opthdr.SizeOfImage =
666 umax(pe_virtual_align(pe, size + addr), pe_header.opthdr.SizeOfImage);
668 if (si->data_size) {
669 psh->PointerToRawData = file_offset;
670 file_offset = pe_file_align(pe, file_offset + si->data_size);
671 psh->SizeOfRawData = file_offset - psh->PointerToRawData;
675 //pe_header.filehdr.TimeDateStamp = time(NULL);
676 pe_header.filehdr.NumberOfSections = pe->sec_count;
677 pe_header.opthdr.SizeOfHeaders = pe->sizeofheaders;
678 pe_header.opthdr.ImageBase = pe->imagebase;
679 if (PE_DLL == pe->type)
680 pe_header.filehdr.Characteristics = CHARACTERISTICS_DLL;
681 else if (PE_GUI != pe->type)
682 pe_header.opthdr.Subsystem = 3;
684 sum = 0;
685 pe_fwrite(&pe_header, sizeof pe_header, op, &sum);
686 for (i = 0; i < pe->sec_count; ++i)
687 pe_fwrite(&pe->sec_info[i].ish, sizeof(IMAGE_SECTION_HEADER), op, &sum);
688 pe_fpad(op, pe->sizeofheaders);
689 for (i = 0; i < pe->sec_count; ++i) {
690 si = pe->sec_info + i;
691 psh = &si->ish;
692 if (si->data_size) {
693 pe_fwrite(si->data, si->data_size, op, &sum);
694 file_offset = psh->PointerToRawData + psh->SizeOfRawData;
695 pe_fpad(op, file_offset);
699 pe_header.opthdr.CheckSum = sum + file_offset;
700 fseek(op, offsetof(struct pe_header, opthdr.CheckSum), SEEK_SET);
701 pe_fwrite(&pe_header.opthdr.CheckSum, sizeof pe_header.opthdr.CheckSum, op, NULL);
702 fclose (op);
704 if (2 == pe->s1->verbose)
705 printf("-------------------------------\n");
706 if (pe->s1->verbose)
707 printf("<- %s (%lu bytes)\n", pe->filename, file_offset);
709 return 0;
712 /*----------------------------------------------------------------------------*/
714 #if defined(TCC_TARGET_X86_64)
715 #define ELFW_R_(type) ELF64_R_##type
716 #define ElfW_Rel ElfW(Rela)
718 #define REL_TYPE_DIRECT R_X86_64_64
719 #define R_XXX_THUNKFIX R_X86_64_PC32
720 #define R_XXX_RELATIVE R_X86_64_RELATIVE
722 #define ELFW_ST_BIND ELF64_ST_BIND
723 #define ELFW_ST_TYPE ELF64_ST_TYPE
724 #define ELFW_ST_INFO ELF64_ST_INFO
725 #elif defined(TCC_TARGET_I386)
726 #define ELFW_R_(type) ELF32_R_##type
727 #define ElfW_Rel ElfW(Rel)
729 #define REL_TYPE_DIRECT R_386_32
730 #define R_XXX_THUNKFIX R_386_32
731 #define R_XXX_RELATIVE R_386_RELATIVE
733 #define ELFW_ST_BIND ELF32_ST_BIND
734 #define ELFW_ST_TYPE ELF32_ST_TYPE
735 #define ELFW_ST_INFO ELF32_ST_INFO
736 #elif defined(TCC_TARGET_ARM)
737 #define ELFW_R_(type) ELF32_R_##type
738 #define ElfW_Rel ElfW(Rel)
740 #define REL_TYPE_DIRECT R_ARM_ABS32
741 #define R_XXX_THUNKFIX R_ARM_ABS32
742 #define R_XXX_RELATIVE R_ARM_RELATIVE
744 #define ELFW_ST_BIND ELF32_ST_BIND
745 #define ELFW_ST_TYPE ELF32_ST_TYPE
746 #define ELFW_ST_INFO ELF32_ST_INFO
747 #endif
748 /*----------------------------------------------------------------------------*/
750 static struct import_symbol *pe_add_import(struct pe_info *pe, int sym_index)
752 int i;
753 int dll_index;
754 struct pe_import_info *p;
755 struct import_symbol *s;
756 ElfW(Sym) *isym;
758 isym = (ElfW(Sym) *)pe->s1->dynsymtab_section->data + sym_index;
759 dll_index = isym->st_size;
761 i = dynarray_assoc ((void**)pe->imp_info, pe->imp_count, dll_index);
762 if (-1 != i) {
763 p = pe->imp_info[i];
764 goto found_dll;
766 p = tcc_mallocz(sizeof *p);
767 p->dll_index = dll_index;
768 dynarray_add((void***)&pe->imp_info, &pe->imp_count, p);
770 found_dll:
771 i = dynarray_assoc ((void**)p->symbols, p->sym_count, sym_index);
772 if (-1 != i)
773 return p->symbols[i];
775 s = tcc_mallocz(sizeof *s);
776 dynarray_add((void***)&p->symbols, &p->sym_count, s);
777 s->sym_index = sym_index;
778 return s;
781 /*----------------------------------------------------------------------------*/
782 static void pe_build_imports(struct pe_info *pe)
784 int thk_ptr, ent_ptr, dll_ptr, sym_cnt, i;
785 DWORD rva_base = pe->thunk->sh_addr - pe->imagebase;
786 int ndlls = pe->imp_count;
788 for (sym_cnt = i = 0; i < ndlls; ++i)
789 sym_cnt += pe->imp_info[i]->sym_count;
791 if (0 == sym_cnt)
792 return;
794 pe_align_section(pe->thunk, 16);
796 pe->imp_offs = dll_ptr = pe->thunk->data_offset;
797 pe->imp_size = (ndlls + 1) * sizeof(IMAGE_IMPORT_DESCRIPTOR);
798 pe->iat_offs = dll_ptr + pe->imp_size;
799 pe->iat_size = (sym_cnt + ndlls) * sizeof(ADDR3264);
800 section_ptr_add(pe->thunk, pe->imp_size + 2*pe->iat_size);
802 thk_ptr = pe->iat_offs;
803 ent_ptr = pe->iat_offs + pe->iat_size;
805 for (i = 0; i < pe->imp_count; ++i) {
806 IMAGE_IMPORT_DESCRIPTOR *hdr;
807 int k, n, dllindex;
808 ADDR3264 v;
809 struct pe_import_info *p = pe->imp_info[i];
810 const char *name;
811 DLLReference *dllref;
813 dllindex = p->dll_index;
814 if (dllindex)
815 name = (dllref = pe->s1->loaded_dlls[dllindex-1])->name;
816 else
817 name = "", dllref = NULL;
819 /* put the dll name into the import header */
820 v = put_elf_str(pe->thunk, name);
821 hdr = (IMAGE_IMPORT_DESCRIPTOR*)(pe->thunk->data + dll_ptr);
822 hdr->FirstThunk = thk_ptr + rva_base;
823 hdr->OriginalFirstThunk = ent_ptr + rva_base;
824 hdr->Name = v + rva_base;
826 for (k = 0, n = p->sym_count; k <= n; ++k) {
827 if (k < n) {
828 int iat_index = p->symbols[k]->iat_index;
829 int sym_index = p->symbols[k]->sym_index;
830 ElfW(Sym) *imp_sym = (ElfW(Sym) *)pe->s1->dynsymtab_section->data + sym_index;
831 ElfW(Sym) *org_sym = (ElfW(Sym) *)symtab_section->data + iat_index;
832 const char *name = pe->s1->dynsymtab_section->link->data + imp_sym->st_name;
834 org_sym->st_value = thk_ptr;
835 org_sym->st_shndx = pe->thunk->sh_num;
836 v = pe->thunk->data_offset + rva_base;
837 section_ptr_add(pe->thunk, sizeof(WORD)); /* hint, not used */
838 put_elf_str(pe->thunk, name);
839 #ifdef TCC_IS_NATIVE
840 if (pe->type == PE_RUN) {
841 v = imp_sym->st_value;
842 if (dllref) {
843 if ( !dllref->handle )
844 dllref->handle = LoadLibrary(dllref->name);
845 v = (ADDR3264)GetProcAddress(dllref->handle, name);
847 if (!v)
848 error_noabort("undefined symbol '%s'", name);
850 #endif
851 } else {
852 v = 0; /* last entry is zero */
854 *(ADDR3264*)(pe->thunk->data+thk_ptr) =
855 *(ADDR3264*)(pe->thunk->data+ent_ptr) = v;
856 thk_ptr += sizeof (ADDR3264);
857 ent_ptr += sizeof (ADDR3264);
859 dll_ptr += sizeof(IMAGE_IMPORT_DESCRIPTOR);
860 dynarray_reset(&p->symbols, &p->sym_count);
862 dynarray_reset(&pe->imp_info, &pe->imp_count);
865 /* ------------------------------------------------------------- */
867 struct pe_sort_sym
869 int index;
870 const char *name;
873 static int sym_cmp(const void *va, const void *vb)
875 const char *ca = (*(struct pe_sort_sym**)va)->name;
876 const char *cb = (*(struct pe_sort_sym**)vb)->name;
877 return strcmp(ca, cb);
880 static void pe_build_exports(struct pe_info *pe)
882 ElfW(Sym) *sym;
883 int sym_index, sym_end;
884 DWORD rva_base, func_o, name_o, ord_o, str_o;
885 IMAGE_EXPORT_DIRECTORY *hdr;
886 int sym_count, ord;
887 struct pe_sort_sym **sorted, *p;
889 FILE *op;
890 char buf[MAX_PATH];
891 const char *dllname;
892 const char *name;
894 rva_base = pe->thunk->sh_addr - pe->imagebase;
895 sym_count = 0, sorted = NULL, op = NULL;
897 sym_end = symtab_section->data_offset / sizeof(ElfW(Sym));
898 for (sym_index = 1; sym_index < sym_end; ++sym_index) {
899 sym = (ElfW(Sym)*)symtab_section->data + sym_index;
900 name = symtab_section->link->data + sym->st_name;
901 if ((sym->st_other & 1)
902 /* export only symbols from actually written sections */
903 && pe->s1->sections[sym->st_shndx]->sh_addr) {
904 p = tcc_malloc(sizeof *p);
905 p->index = sym_index;
906 p->name = name;
907 dynarray_add((void***)&sorted, &sym_count, p);
909 #if 0
910 if (sym->st_other & 1)
911 printf("export: %s\n", name);
912 if (sym->st_other & 2)
913 printf("stdcall: %s\n", name);
914 #endif
917 if (0 == sym_count)
918 return;
920 qsort (sorted, sym_count, sizeof *sorted, sym_cmp);
922 pe_align_section(pe->thunk, 16);
923 dllname = tcc_basename(pe->filename);
925 pe->exp_offs = pe->thunk->data_offset;
926 func_o = pe->exp_offs + sizeof(IMAGE_EXPORT_DIRECTORY);
927 name_o = func_o + sym_count * sizeof (DWORD);
928 ord_o = name_o + sym_count * sizeof (DWORD);
929 str_o = ord_o + sym_count * sizeof(WORD);
931 hdr = section_ptr_add(pe->thunk, str_o - pe->exp_offs);
932 hdr->Characteristics = 0;
933 hdr->Base = 1;
934 hdr->NumberOfFunctions = sym_count;
935 hdr->NumberOfNames = sym_count;
936 hdr->AddressOfFunctions = func_o + rva_base;
937 hdr->AddressOfNames = name_o + rva_base;
938 hdr->AddressOfNameOrdinals = ord_o + rva_base;
939 hdr->Name = str_o + rva_base;
940 put_elf_str(pe->thunk, dllname);
942 #if 1
943 /* automatically write exports to <output-filename>.def */
944 strcpy(buf, pe->filename);
945 strcpy(tcc_fileextension(buf), ".def");
946 op = fopen(buf, "w");
947 if (NULL == op) {
948 error_noabort("could not create '%s': %s", buf, strerror(errno));
949 } else {
950 fprintf(op, "LIBRARY %s\n\nEXPORTS\n", dllname);
951 if (pe->s1->verbose)
952 printf("<- %s (%d symbols)\n", buf, sym_count);
954 #endif
956 for (ord = 0; ord < sym_count; ++ord)
958 p = sorted[ord], sym_index = p->index, name = p->name;
959 /* insert actual address later in pe_relocate_rva */
960 put_elf_reloc(symtab_section, pe->thunk,
961 func_o, R_XXX_RELATIVE, sym_index);
962 *(DWORD*)(pe->thunk->data + name_o)
963 = pe->thunk->data_offset + rva_base;
964 *(WORD*)(pe->thunk->data + ord_o)
965 = ord;
966 put_elf_str(pe->thunk, name);
967 func_o += sizeof (DWORD);
968 name_o += sizeof (DWORD);
969 ord_o += sizeof (WORD);
970 if (op)
971 fprintf(op, "%s\n", name);
973 pe->exp_size = pe->thunk->data_offset - pe->exp_offs;
974 dynarray_reset(&sorted, &sym_count);
975 if (op)
976 fclose(op);
979 /* ------------------------------------------------------------- */
980 static void pe_build_reloc (struct pe_info *pe)
982 DWORD offset, block_ptr, addr;
983 int count, i;
984 ElfW_Rel *rel, *rel_end;
985 Section *s = NULL, *sr;
987 offset = addr = block_ptr = count = i = 0;
988 rel = rel_end = NULL;
990 for(;;) {
991 if (rel < rel_end) {
992 int type = ELFW_R_(TYPE)(rel->r_info);
993 addr = rel->r_offset + s->sh_addr;
994 ++ rel;
995 if (type != REL_TYPE_DIRECT)
996 continue;
997 if (count == 0) { /* new block */
998 block_ptr = pe->reloc->data_offset;
999 section_ptr_add(pe->reloc, sizeof(struct pe_reloc_header));
1000 offset = addr & 0xFFFFFFFF<<12;
1002 if ((addr -= offset) < (1<<12)) { /* one block spans 4k addresses */
1003 WORD *wp = section_ptr_add(pe->reloc, sizeof (WORD));
1004 *wp = addr | IMAGE_REL_BASED_HIGHLOW<<12;
1005 ++count;
1006 continue;
1008 -- rel;
1010 } else if (i < pe->sec_count) {
1011 sr = (s = pe->s1->sections[pe->sec_info[i++].ord])->reloc;
1012 if (sr) {
1013 rel = (ElfW_Rel *)sr->data;
1014 rel_end = (ElfW_Rel *)(sr->data + sr->data_offset);
1016 continue;
1019 if (count) {
1020 /* store the last block and ready for a new one */
1021 struct pe_reloc_header *hdr;
1022 if (count & 1) /* align for DWORDS */
1023 section_ptr_add(pe->reloc, sizeof(WORD)), ++count;
1024 hdr = (struct pe_reloc_header *)(pe->reloc->data + block_ptr);
1025 hdr -> offset = offset - pe->imagebase;
1026 hdr -> size = count * sizeof(WORD) + sizeof(struct pe_reloc_header);
1027 count = 0;
1030 if (rel >= rel_end)
1031 break;
1035 /* ------------------------------------------------------------- */
1036 static int pe_section_class(Section *s)
1038 int type, flags;
1039 const char *name;
1041 type = s->sh_type;
1042 flags = s->sh_flags;
1043 name = s->name;
1044 if (flags & SHF_ALLOC) {
1045 if (type == SHT_PROGBITS) {
1046 if (flags & SHF_EXECINSTR)
1047 return sec_text;
1048 if (flags & SHF_WRITE)
1049 return sec_data;
1050 if (0 == strcmp(name, ".rsrc"))
1051 return sec_rsrc;
1052 if (0 == strcmp(name, ".iedat"))
1053 return sec_idata;
1054 if (0 == strcmp(name, ".pdata"))
1055 return sec_pdata;
1056 return sec_other;
1057 } else if (type == SHT_NOBITS) {
1058 if (flags & SHF_WRITE)
1059 return sec_bss;
1061 } else {
1062 if (0 == strcmp(name, ".reloc"))
1063 return sec_reloc;
1064 if (0 == strncmp(name, ".stab", 5)) /* .stab and .stabstr */
1065 return sec_stab;
1067 return -1;
1070 static int pe_assign_addresses (struct pe_info *pe)
1072 int i, k, o, c;
1073 DWORD addr;
1074 int *section_order;
1075 struct section_info *si;
1076 Section *s;
1078 // pe->thunk = new_section(pe->s1, ".iedat", SHT_PROGBITS, SHF_ALLOC);
1080 section_order = tcc_malloc(pe->s1->nb_sections * sizeof (int));
1081 for (o = k = 0 ; k < sec_last; ++k) {
1082 for (i = 1; i < pe->s1->nb_sections; ++i) {
1083 s = pe->s1->sections[i];
1084 if (k == pe_section_class(s)) {
1085 // printf("%s %d\n", s->name, k);
1086 s->sh_addr = pe->imagebase;
1087 section_order[o++] = i;
1092 pe->sec_info = tcc_mallocz(o * sizeof (struct section_info));
1093 addr = pe->imagebase + 1;
1095 for (i = 0; i < o; ++i)
1097 k = section_order[i];
1098 s = pe->s1->sections[k];
1099 c = pe_section_class(s);
1100 si = &pe->sec_info[pe->sec_count];
1102 #ifdef PE_MERGE_DATA
1103 if (c == sec_bss && pe->sec_count && si[-1].cls == sec_data) {
1104 /* append .bss to .data */
1105 s->sh_addr = addr = ((addr-1) | (s->sh_addralign-1)) + 1;
1106 addr += s->data_offset;
1107 si[-1].sh_size = addr - si[-1].sh_addr;
1108 continue;
1110 #endif
1111 strcpy(si->name, s->name);
1112 si->cls = c;
1113 si->ord = k;
1114 si->sh_addr = s->sh_addr = addr = pe_virtual_align(pe, addr);
1115 si->sh_flags = s->sh_flags;
1117 if (c == sec_data && NULL == pe->thunk)
1118 pe->thunk = s;
1120 if (s == pe->thunk) {
1121 pe_build_imports(pe);
1122 pe_build_exports(pe);
1125 if (c == sec_reloc)
1126 pe_build_reloc (pe);
1128 if (s->data_offset)
1130 if (s->sh_type != SHT_NOBITS) {
1131 si->data = s->data;
1132 si->data_size = s->data_offset;
1135 addr += s->data_offset;
1136 si->sh_size = s->data_offset;
1137 ++pe->sec_count;
1139 // printf("%08x %05x %s\n", si->sh_addr, si->sh_size, si->name);
1142 #if 0
1143 for (i = 1; i < pe->s1->nb_sections; ++i) {
1144 Section *s = pe->s1->sections[i];
1145 int type = s->sh_type;
1146 int flags = s->sh_flags;
1147 printf("section %-16s %-10s %5x %s,%s,%s\n",
1148 s->name,
1149 type == SHT_PROGBITS ? "progbits" :
1150 type == SHT_NOBITS ? "nobits" :
1151 type == SHT_SYMTAB ? "symtab" :
1152 type == SHT_STRTAB ? "strtab" :
1153 type == SHT_RELX ? "rel" : "???",
1154 s->data_offset,
1155 flags & SHF_ALLOC ? "alloc" : "",
1156 flags & SHF_WRITE ? "write" : "",
1157 flags & SHF_EXECINSTR ? "exec" : ""
1160 pe->s1->verbose = 2;
1161 #endif
1163 tcc_free(section_order);
1164 return 0;
1167 /* ------------------------------------------------------------- */
1168 static void pe_relocate_rva (struct pe_info *pe, Section *s)
1170 Section *sr = s->reloc;
1171 ElfW_Rel *rel, *rel_end;
1172 rel_end = (ElfW_Rel *)(sr->data + sr->data_offset);
1173 for(rel = (ElfW_Rel *)sr->data; rel < rel_end; rel++) {
1174 if (ELFW_R_(TYPE)(rel->r_info) == R_XXX_RELATIVE) {
1175 int sym_index = ELFW_R_(SYM)(rel->r_info);
1176 DWORD addr = s->sh_addr;
1177 if (sym_index) {
1178 ElfW(Sym) *sym = (ElfW(Sym) *)symtab_section->data + sym_index;
1179 addr = sym->st_value;
1181 // printf("reloc rva %08x %08x %s\n", (DWORD)rel->r_offset, addr, s->name);
1182 *(DWORD*)(s->data + rel->r_offset) += addr - pe->imagebase;
1187 /*----------------------------------------------------------------------------*/
1189 static int pe_isafunc(int sym_index)
1191 Section *sr = text_section->reloc;
1192 ElfW_Rel *rel, *rel_end;
1193 Elf32_Word info = ELF32_R_INFO(sym_index, R_386_PC32);
1194 if (!sr)
1195 return 0;
1196 rel_end = (ElfW_Rel *)(sr->data + sr->data_offset);
1197 for (rel = (ElfW_Rel *)sr->data; rel < rel_end; rel++)
1198 if (rel->r_info == info)
1199 return 1;
1200 return 0;
1203 /*----------------------------------------------------------------------------*/
1204 static int pe_check_symbols(struct pe_info *pe)
1206 ElfW(Sym) *sym;
1207 int sym_index, sym_end;
1208 int ret = 0;
1210 pe_align_section(text_section, 8);
1212 sym_end = symtab_section->data_offset / sizeof(ElfW(Sym));
1213 for (sym_index = 1; sym_index < sym_end; ++sym_index) {
1215 sym = (ElfW(Sym) *)symtab_section->data + sym_index;
1216 if (sym->st_shndx == SHN_UNDEF) {
1218 const char *name = symtab_section->link->data + sym->st_name;
1219 unsigned type = ELFW_ST_TYPE(sym->st_info);
1220 int imp_sym = pe_find_import(pe->s1, name);
1221 struct import_symbol *is;
1223 if (0 == imp_sym)
1224 goto not_found;
1226 if (type == STT_NOTYPE) {
1227 /* symbols from assembler have no type, find out which */
1228 if (pe_isafunc(sym_index))
1229 type = STT_FUNC;
1230 else
1231 type = STT_OBJECT;
1234 is = pe_add_import(pe, imp_sym);
1236 if (type == STT_FUNC) {
1237 unsigned long offset = is->thk_offset;
1238 if (offset) {
1239 /* got aliased symbol, like stricmp and _stricmp */
1241 } else {
1242 char buffer[100];
1243 WORD *p;
1245 offset = text_section->data_offset;
1246 /* add the 'jmp IAT[x]' instruction */
1247 p = section_ptr_add(text_section, 8);
1248 *p = 0x25FF;
1249 #ifdef TCC_TARGET_X86_64
1250 *(DWORD*)(p+1) = (DWORD)-4;
1251 #endif
1252 /* add a helper symbol, will be patched later in
1253 pe_build_imports */
1254 sprintf(buffer, "IAT.%s", name);
1255 is->iat_index = put_elf_sym(
1256 symtab_section, 0, sizeof(DWORD),
1257 ELFW_ST_INFO(STB_GLOBAL, STT_OBJECT),
1258 0, SHN_UNDEF, buffer);
1259 put_elf_reloc(symtab_section, text_section,
1260 offset + 2, R_XXX_THUNKFIX, is->iat_index);
1261 is->thk_offset = offset;
1264 /* tcc_realloc might have altered sym's address */
1265 sym = (ElfW(Sym) *)symtab_section->data + sym_index;
1267 /* patch the original symbol */
1268 sym->st_value = offset;
1269 sym->st_shndx = text_section->sh_num;
1270 sym->st_other &= ~1; /* do not export */
1271 continue;
1274 if (type == STT_OBJECT) { /* data, ptr to that should be */
1275 if (0 == is->iat_index) {
1276 /* original symbol will be patched later in pe_build_imports */
1277 is->iat_index = sym_index;
1278 continue;
1282 not_found:
1283 error_noabort("undefined symbol '%s'", name);
1284 ret = -1;
1286 } else if (pe->s1->rdynamic
1287 && ELFW_ST_BIND(sym->st_info) != STB_LOCAL) {
1288 /* if -rdynamic option, then export all non local symbols */
1289 sym->st_other |= 1;
1292 return ret;
1295 /*----------------------------------------------------------------------------*/
1296 #ifdef PE_PRINT_SECTIONS
1297 static void pe_print_section(FILE * f, Section * s)
1299 /* just if you'r curious */
1300 BYTE *p, *e, b;
1301 int i, n, l, m;
1302 p = s->data;
1303 e = s->data + s->data_offset;
1304 l = e - p;
1306 fprintf(f, "section \"%s\"", s->name);
1307 if (s->link)
1308 fprintf(f, "\nlink \"%s\"", s->link->name);
1309 if (s->reloc)
1310 fprintf(f, "\nreloc \"%s\"", s->reloc->name);
1311 fprintf(f, "\nv_addr %08X", (unsigned)s->sh_addr);
1312 fprintf(f, "\ncontents %08X", (unsigned)l);
1313 fprintf(f, "\n\n");
1315 if (s->sh_type == SHT_NOBITS)
1316 return;
1318 if (0 == l)
1319 return;
1321 if (s->sh_type == SHT_SYMTAB)
1322 m = sizeof(ElfW(Sym));
1323 else if (s->sh_type == SHT_RELX)
1324 m = sizeof(ElfW_Rel);
1325 else
1326 m = 16;
1328 fprintf(f, "%-8s", "offset");
1329 for (i = 0; i < m; ++i)
1330 fprintf(f, " %02x", i);
1331 n = 56;
1333 if (s->sh_type == SHT_SYMTAB || s->sh_type == SHT_RELX) {
1334 const char *fields1[] = {
1335 "name",
1336 "value",
1337 "size",
1338 "bind",
1339 "type",
1340 "other",
1341 "shndx",
1342 NULL
1345 const char *fields2[] = {
1346 "offs",
1347 "type",
1348 "symb",
1349 NULL
1352 const char **p;
1354 if (s->sh_type == SHT_SYMTAB)
1355 p = fields1, n = 106;
1356 else
1357 p = fields2, n = 58;
1359 for (i = 0; p[i]; ++i)
1360 fprintf(f, "%6s", p[i]);
1361 fprintf(f, " symbol");
1364 fprintf(f, "\n");
1365 for (i = 0; i < n; ++i)
1366 fprintf(f, "-");
1367 fprintf(f, "\n");
1369 for (i = 0; i < l;)
1371 fprintf(f, "%08X", i);
1372 for (n = 0; n < m; ++n) {
1373 if (n + i < l)
1374 fprintf(f, " %02X", p[i + n]);
1375 else
1376 fprintf(f, " ");
1379 if (s->sh_type == SHT_SYMTAB) {
1380 ElfW(Sym) *sym = (ElfW(Sym) *) (p + i);
1381 const char *name = s->link->data + sym->st_name;
1382 fprintf(f, " %04X %04X %04X %02X %02X %02X %04X \"%s\"",
1383 (unsigned)sym->st_name,
1384 (unsigned)sym->st_value,
1385 (unsigned)sym->st_size,
1386 (unsigned)ELFW_ST_BIND(sym->st_info),
1387 (unsigned)ELFW_ST_TYPE(sym->st_info),
1388 (unsigned)sym->st_other,
1389 (unsigned)sym->st_shndx,
1390 name);
1392 } else if (s->sh_type == SHT_RELX) {
1393 ElfW_Rel *rel = (ElfW_Rel *) (p + i);
1394 ElfW(Sym) *sym =
1395 (ElfW(Sym) *) s->link->data + ELFW_R_(SYM)(rel->r_info);
1396 const char *name = s->link->link->data + sym->st_name;
1397 fprintf(f, " %04X %02X %04X \"%s\"",
1398 (unsigned)rel->r_offset,
1399 (unsigned)ELFW_R_(TYPE)(rel->r_info),
1400 (unsigned)ELFW_R_(SYM)(rel->r_info),
1401 name);
1402 } else {
1403 fprintf(f, " ");
1404 for (n = 0; n < m; ++n) {
1405 if (n + i < l) {
1406 b = p[i + n];
1407 if (b < 32 || b >= 127)
1408 b = '.';
1409 fprintf(f, "%c", b);
1413 i += m;
1414 fprintf(f, "\n");
1416 fprintf(f, "\n\n");
1419 static void pe_print_sections(TCCState *s1, const char *fname)
1421 Section *s;
1422 FILE *f;
1423 int i;
1424 f = fopen(fname, "w");
1425 for (i = 1; i < s1->nb_sections; ++i) {
1426 s = s1->sections[i];
1427 pe_print_section(f, s);
1429 pe_print_section(f, s1->dynsymtab_section);
1430 fclose(f);
1432 #endif
1434 /* ------------------------------------------------------------- */
1435 /* helper function for load/store to insert one more indirection */
1437 ST_FUNC SValue *pe_getimport(SValue *sv, SValue *v2)
1439 Sym *sym;
1440 ElfW(Sym) *esym;
1441 int r2;
1443 if ((sv->r & (VT_VALMASK|VT_SYM)) != (VT_CONST|VT_SYM) || (sv->r2 != VT_CONST))
1444 return sv;
1445 sym = sv->sym;
1446 if ((sym->type.t & (VT_EXTERN|VT_STATIC)) != VT_EXTERN)
1447 return sv;
1448 if (!sym->c)
1449 put_extern_sym(sym, NULL, 0, 0);
1450 esym = &((ElfW(Sym) *)symtab_section->data)[sym->c];
1451 if (!(esym->st_other & 4))
1452 return sv;
1454 // printf("import %04x %04x %04x %s\n", sv->type.t, sym->type.t, sv->r, get_tok_str(sv->sym->v, NULL));
1456 memset(v2, 0, sizeof *v2);
1457 v2->type.t = VT_PTR;
1458 v2->r = VT_CONST | VT_SYM | VT_LVAL;
1459 v2->sym = sv->sym;
1461 r2 = get_reg(RC_INT);
1462 load(r2, v2);
1463 v2->r = r2;
1465 if (sv->c.ui) {
1466 vpushv(v2);
1467 vpushi(sv->c.ui);
1468 gen_opi('+');
1469 *v2 = *vtop--;
1472 v2->type.t = sv->type.t;
1473 v2->r |= sv->r & VT_LVAL;
1474 return v2;
1477 ST_FUNC int pe_putimport(TCCState *s1, int dllindex, const char *name, const void *value)
1479 return add_elf_sym(
1480 s1->dynsymtab_section,
1481 (uplong)value,
1482 dllindex, /* st_size */
1483 ELFW_ST_INFO(STB_GLOBAL, STT_NOTYPE),
1485 value ? SHN_ABS : SHN_UNDEF,
1486 name
1490 static int add_dllref(TCCState *s1, const char *dllname)
1492 DLLReference *dllref;
1493 int i;
1494 for (i = 0; i < s1->nb_loaded_dlls; ++i)
1495 if (0 == strcmp(s1->loaded_dlls[i]->name, dllname))
1496 return i + 1;
1497 dllref = tcc_mallocz(sizeof(DLLReference) + strlen(dllname));
1498 strcpy(dllref->name, dllname);
1499 dynarray_add((void ***) &s1->loaded_dlls, &s1->nb_loaded_dlls, dllref);
1500 return s1->nb_loaded_dlls;
1503 /* ------------------------------------------------------------- */
1505 static int read_mem(FILE *fp, unsigned offset, void *buffer, unsigned len)
1507 fseek(fp, offset, 0);
1508 return len == fread(buffer, 1, len, fp);
1511 /* -------------------------------------------------------------
1512 * This is for compiled windows resources in 'coff' format
1513 * as generated by 'windres.exe -O coff ...'.
1516 static int pe_load_res(TCCState *s1, FILE *fp)
1518 struct pe_rsrc_header hdr;
1519 Section *rsrc_section;
1520 int i, ret = -1;
1521 BYTE *ptr;
1522 unsigned offs;
1524 if (!read_mem(fp, 0, &hdr, sizeof hdr))
1525 goto quit;
1527 if (hdr.filehdr.Machine != 0x014C
1528 || hdr.filehdr.NumberOfSections != 1
1529 || strcmp(hdr.sectionhdr.Name, ".rsrc") != 0)
1530 goto quit;
1532 rsrc_section = new_section(s1, ".rsrc", SHT_PROGBITS, SHF_ALLOC);
1533 ptr = section_ptr_add(rsrc_section, hdr.sectionhdr.SizeOfRawData);
1534 offs = hdr.sectionhdr.PointerToRawData;
1535 if (!read_mem(fp, offs, ptr, hdr.sectionhdr.SizeOfRawData))
1536 goto quit;
1537 offs = hdr.sectionhdr.PointerToRelocations;
1538 for (i = 0; i < hdr.sectionhdr.NumberOfRelocations; ++i)
1540 struct pe_rsrc_reloc rel;
1541 if (!read_mem(fp, offs, &rel, sizeof rel))
1542 goto quit;
1543 // printf("rsrc_reloc: %x %x %x\n", rel.offset, rel.size, rel.type);
1544 if (rel.type != 7) /* DIR32NB */
1545 goto quit;
1546 put_elf_reloc(symtab_section, rsrc_section,
1547 rel.offset, R_XXX_RELATIVE, 0);
1548 offs += sizeof rel;
1550 ret = 0;
1551 quit:
1552 return ret;
1555 /* ------------------------------------------------------------- */
1556 static char *trimfront(char *p)
1558 while (*p && (unsigned char)*p <= ' ')
1559 ++p;
1560 return p;
1563 static char *trimback(char *a, char *e)
1565 while (e > a && (unsigned char)e[-1] <= ' ')
1566 --e;
1567 *e = 0;;
1568 return a;
1571 static char *get_line(char *line, int size, FILE *fp)
1573 if (NULL == fgets(line, size, fp))
1574 return NULL;
1575 trimback(line, strchr(line, 0));
1576 return trimfront(line);
1579 /* ------------------------------------------------------------- */
1580 static int pe_load_def(TCCState *s1, FILE *fp)
1582 int state = 0, ret = -1, dllindex = 0;
1583 char line[400], dllname[80], *p;
1585 for (;;) {
1586 p = get_line(line, sizeof line, fp);
1587 if (NULL == p)
1588 break;
1589 if (0 == *p || ';' == *p)
1590 continue;
1591 switch (state) {
1592 case 0:
1593 if (0 != strnicmp(p, "LIBRARY", 7))
1594 goto quit;
1595 strcpy(dllname, trimfront(p+7));
1596 ++state;
1597 continue;
1599 case 1:
1600 if (0 != stricmp(p, "EXPORTS"))
1601 goto quit;
1602 ++state;
1603 continue;
1605 case 2:
1606 dllindex = add_dllref(s1, dllname);
1607 ++state;
1609 default:
1610 pe_putimport(s1, dllindex, p, NULL);
1611 continue;
1614 ret = 0;
1615 quit:
1616 return ret;
1619 /* ------------------------------------------------------------- */
1620 #define TINY_IMPDEF_GET_EXPORT_NAMES_ONLY
1621 #include "win32/tools/tiny_impdef.c"
1623 static int pe_load_dll(TCCState *s1, const char *dllname, FILE *fp)
1625 char *p, *q;
1626 int index;
1627 p = get_export_names(fp);
1628 if (!p)
1629 return -1;
1630 index = add_dllref(s1, dllname);
1631 for (q = p; *q; q += 1 + strlen(q))
1632 pe_putimport(s1, index, q, NULL);
1633 tcc_free(p);
1634 return 0;
1637 /* ------------------------------------------------------------- */
1638 ST_FUNC int pe_load_file(struct TCCState *s1, const char *filename, int fd)
1640 FILE *fp = fdopen(dup(fd), "rb");
1641 int ret = -1;
1642 char buf[10];
1643 if (fp) {
1644 if (0 == strcmp(tcc_fileextension(filename), ".def"))
1645 ret = pe_load_def(s1, fp);
1646 else if (pe_load_res(s1, fp) == 0)
1647 ret = 0;
1648 else if (read_mem(fp, 0, buf, sizeof buf) && 0 == strncmp(buf, "MZ", 2))
1649 ret = pe_load_dll(s1, tcc_basename(filename), fp);
1650 fclose(fp);
1652 return ret;
1655 ST_FUNC int pe_add_dll(struct TCCState *s, const char *libname)
1657 static const char *pat[] = {
1658 "%s.def", "lib%s.def", "%s.dll", "lib%s.dll", NULL
1660 const char **p = pat;
1661 do {
1662 char buf[MAX_PATH];
1663 snprintf(buf, sizeof(buf), *p, libname);
1664 if (tcc_add_dll(s, buf, 0) == 0)
1665 return 0;
1666 } while (*++p);
1667 return -1;
1670 /* ------------------------------------------------------------- */
1671 #ifdef TCC_TARGET_X86_64
1672 ST_FUNC void pe_add_unwind_data(unsigned start, unsigned end, unsigned stack)
1674 static const char uw_info[] = {
1675 0x01, // UBYTE: 3 Version , UBYTE: 5 Flags
1676 0x04, // UBYTE Size of prolog
1677 0x02, // UBYTE Count of unwind codes
1678 0x05, // UBYTE: 4 Frame Register (rbp), UBYTE: 4 Frame Register offset (scaled)
1679 // USHORT * n Unwind codes array
1680 // 0x0b, 0x01, 0xff, 0xff, // stack size
1681 0x04, 0x03, // set frame ptr (mov rsp -> rbp)
1682 0x01, 0x50 // push reg (rbp)
1685 struct pe_uw *pe_uw = &tcc_state->pe_unwind;
1687 Section *uw, *pd;
1688 WORD *p1;
1689 DWORD *p2;
1690 unsigned o2;
1692 uw = data_section;
1693 pd = pe_uw->pdata;
1694 if (NULL == pd)
1696 pe_uw->pdata = pd = find_section(tcc_state, ".pdata");
1697 pe_uw->pdata->sh_addralign = 4;
1698 section_ptr_add(uw, -uw->data_offset & 3);
1699 pe_uw->offs_1 = uw->data_offset;
1700 p1 = section_ptr_add(uw, sizeof uw_info);
1701 /* use one common entry for all functions */
1702 memcpy(p1, uw_info, sizeof uw_info);
1703 pe_uw->sym_1 = put_elf_sym(symtab_section, 0, 0, 0, 0, text_section->sh_num, NULL);
1704 pe_uw->sym_2 = put_elf_sym(symtab_section, 0, 0, 0, 0, uw->sh_num, NULL);
1707 o2 = pd->data_offset;
1708 p2 = section_ptr_add(pd, 3 * sizeof (DWORD));
1709 /* record this function */
1710 p2[0] = start;
1711 p2[1] = end;
1712 p2[2] = pe_uw->offs_1;
1713 /* put relocations on it */
1714 put_elf_reloc(symtab_section, pd, o2, R_X86_64_RELATIVE, pe_uw->sym_1);
1715 put_elf_reloc(symtab_section, pd, o2+4, R_X86_64_RELATIVE, pe_uw->sym_1);
1716 put_elf_reloc(symtab_section, pd, o2+8, R_X86_64_RELATIVE, pe_uw->sym_2);
1718 #endif
1720 /* ------------------------------------------------------------- */
1721 #ifdef TCC_TARGET_X86_64
1722 #define PE_STDSYM(n,s) n
1723 #else
1724 #define PE_STDSYM(n,s) "_" n s
1725 #endif
1727 static void pe_add_runtime_ex(TCCState *s1, struct pe_info *pe)
1729 const char *start_symbol;
1730 unsigned long addr = 0;
1731 int pe_type = 0;
1733 if (find_elf_sym(symtab_section, PE_STDSYM("WinMain","@16")))
1734 pe_type = PE_GUI;
1735 else
1736 if (TCC_OUTPUT_DLL == s1->output_type) {
1737 pe_type = PE_DLL;
1738 /* need this for 'tccelf.c:relocate_section()' */
1739 s1->output_type = TCC_OUTPUT_EXE;
1741 else
1742 pe_type = PE_EXE;
1744 start_symbol =
1745 TCC_OUTPUT_MEMORY == s1->output_type
1746 ? PE_GUI == pe_type ? "_runwinmain" : NULL
1747 : PE_DLL == pe_type ? PE_STDSYM("_dllstart","@12")
1748 : PE_GUI == pe_type ? "_winstart" : "_start"
1751 /* grab the startup code from libtcc1 */
1752 if (start_symbol)
1753 add_elf_sym(symtab_section,
1754 0, 0,
1755 ELFW_ST_INFO(STB_GLOBAL, STT_NOTYPE), 0,
1756 SHN_UNDEF, start_symbol);
1758 if (0 == s1->nostdlib) {
1759 static const char *libs[] = {
1760 "tcc1", "msvcrt", "kernel32", "", "user32", "gdi32", NULL
1762 const char **pp, *p;
1763 for (pp = libs; 0 != (p = *pp); ++pp) {
1764 if (0 == *p) {
1765 if (PE_DLL != pe_type && PE_GUI != pe_type)
1766 break;
1767 } else if (tcc_add_library(s1, p) < 0)
1768 error_noabort("cannot find library: %s", p);
1772 if (TCC_OUTPUT_MEMORY == s1->output_type)
1773 pe_type = PE_RUN;
1775 if (start_symbol) {
1776 addr = (uplong)tcc_get_symbol_err(s1, start_symbol);
1777 if (PE_RUN == pe_type && addr)
1778 /* for -run GUI's, put '_runwinmain' instead of 'main' */
1779 add_elf_sym(symtab_section,
1780 addr, 0,
1781 ELFW_ST_INFO(STB_GLOBAL, STT_NOTYPE), 0,
1782 text_section->sh_num, "main");
1785 pe->type = pe_type;
1786 pe->start_addr = addr;
1789 ST_FUNC int pe_output_file(TCCState * s1, const char *filename)
1791 int ret;
1792 struct pe_info pe;
1793 int i;
1795 memset(&pe, 0, sizeof pe);
1796 pe.filename = filename;
1797 pe.s1 = s1;
1799 tcc_add_bcheck(s1);
1800 pe_add_runtime_ex(s1, &pe);
1801 relocate_common_syms(); /* assign bss adresses */
1802 tcc_add_linker_symbols(s1);
1804 ret = pe_check_symbols(&pe);
1805 if (ret)
1807 else if (filename) {
1808 if (PE_DLL == pe.type) {
1809 pe.reloc = new_section(pe.s1, ".reloc", SHT_PROGBITS, 0);
1810 /* XXX: check if is correct for arm-pe target */
1811 pe.imagebase = 0x10000000;
1812 } else {
1813 #if defined(TCC_TARGET_ARM)
1814 pe.imagebase = 0x00010000;
1815 #else
1816 pe.imagebase = 0x00400000;
1817 #endif
1820 /* if no subsystem specified, we use "console" subsystem by default */
1821 if (s1->pe_subsystem != 0)
1822 pe.subsystem = s1->pe_subsystem;
1823 else
1824 #if defined(TCC_TARGET_ARM)
1825 pe.subsystem = 3;
1826 #else
1827 pe.subsystem = 9;
1828 #endif
1829 /* set default file/section alignment */
1830 if (pe.subsystem == 1) {
1831 pe.section_align = 0x20;
1832 pe.file_align = 0x20;
1833 } else {
1834 pe.section_align = 0x1000;
1835 pe.file_align = 0x200;
1838 if (s1->section_align != 0)
1839 pe.section_align = s1->section_align;
1840 if (s1->pe_file_align != 0)
1841 pe.file_align = s1->pe_file_align;
1843 if ((pe.subsystem >= 10) && (pe.subsystem <= 12))
1844 pe.imagebase = 0;
1846 if (s1->has_text_addr)
1847 pe.imagebase = s1->text_addr;
1849 pe_assign_addresses(&pe);
1850 relocate_syms(s1, 0);
1851 for (i = 1; i < s1->nb_sections; ++i) {
1852 Section *s = s1->sections[i];
1853 if (s->reloc) {
1854 relocate_section(s1, s);
1855 pe_relocate_rva(&pe, s);
1858 if (s1->nb_errors)
1859 ret = -1;
1860 else
1861 ret = pe_write(&pe);
1862 tcc_free(pe.sec_info);
1863 } else {
1864 #ifndef TCC_IS_NATIVE
1865 error_noabort("-run supported only on native platform");
1866 #endif
1867 pe.thunk = data_section;
1868 pe_build_imports(&pe);
1871 #ifdef PE_PRINT_SECTIONS
1872 pe_print_sections(s1, "tcc.log");
1873 #endif
1874 return ret;
1877 /* ------------------------------------------------------------- */