tccpe: support pe32+ (x86_64) target
[tinycc/k1w1.git] / tccpe.c
blob911744d03efc605d3c0b299f614bf8d7b7e6663b
1 /*
2 * TCCPE.C - PE file output for the Tiny C Compiler
4 * Copyright (c) 2005-2007 grischka
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
21 #ifdef TCC_TARGET_PE
23 #define ST_FN static
24 #define ST_DATA static
25 #define PUB_FN
27 #ifndef _WIN32
28 #define stricmp strcasecmp
29 #define strnicmp strncasecmp
30 #endif
32 #ifndef MAX_PATH
33 #define MAX_PATH 260
34 #endif
36 #define PE_MERGE_DATA
37 // #define PE_PRINT_SECTIONS
39 #ifdef TCC_TARGET_X86_64
40 # define ADDR3264 ULONGLONG
41 #else
42 # define ADDR3264 DWORD
43 #endif
45 #if defined _WIN32 && (defined _WIN64) == (defined TCC_TARGET_X86_64)
46 #define TCC_IS_NATIVE
47 #endif
49 /* ----------------------------------------------------------- */
50 #ifndef IMAGE_NT_SIGNATURE
51 /* ----------------------------------------------------------- */
52 /* definitions below are from winnt.h */
54 typedef unsigned char BYTE;
55 typedef unsigned short WORD;
56 typedef unsigned long DWORD;
57 typedef unsigned long long ULONGLONG;
58 #pragma pack(push, 1)
60 typedef struct _IMAGE_DOS_HEADER { /* DOS .EXE header */
61 WORD e_magic; /* Magic number */
62 WORD e_cblp; /* Bytes on last page of file */
63 WORD e_cp; /* Pages in file */
64 WORD e_crlc; /* Relocations */
65 WORD e_cparhdr; /* Size of header in paragraphs */
66 WORD e_minalloc; /* Minimum extra paragraphs needed */
67 WORD e_maxalloc; /* Maximum extra paragraphs needed */
68 WORD e_ss; /* Initial (relative) SS value */
69 WORD e_sp; /* Initial SP value */
70 WORD e_csum; /* Checksum */
71 WORD e_ip; /* Initial IP value */
72 WORD e_cs; /* Initial (relative) CS value */
73 WORD e_lfarlc; /* File address of relocation table */
74 WORD e_ovno; /* Overlay number */
75 WORD e_res[4]; /* Reserved words */
76 WORD e_oemid; /* OEM identifier (for e_oeminfo) */
77 WORD e_oeminfo; /* OEM information; e_oemid specific */
78 WORD e_res2[10]; /* Reserved words */
79 DWORD e_lfanew; /* File address of new exe header */
80 } IMAGE_DOS_HEADER, *PIMAGE_DOS_HEADER;
82 #define IMAGE_NT_SIGNATURE 0x00004550 /* PE00 */
83 #define SIZE_OF_NT_SIGNATURE 4
85 typedef struct _IMAGE_FILE_HEADER {
86 WORD Machine;
87 WORD NumberOfSections;
88 DWORD TimeDateStamp;
89 DWORD PointerToSymbolTable;
90 DWORD NumberOfSymbols;
91 WORD SizeOfOptionalHeader;
92 WORD Characteristics;
93 } IMAGE_FILE_HEADER, *PIMAGE_FILE_HEADER;
96 #define IMAGE_SIZEOF_FILE_HEADER 20
98 typedef struct _IMAGE_DATA_DIRECTORY {
99 DWORD VirtualAddress;
100 DWORD Size;
101 } IMAGE_DATA_DIRECTORY, *PIMAGE_DATA_DIRECTORY;
104 typedef struct _IMAGE_OPTIONAL_HEADER {
105 /* Standard fields. */
106 WORD Magic;
107 BYTE MajorLinkerVersion;
108 BYTE MinorLinkerVersion;
109 DWORD SizeOfCode;
110 DWORD SizeOfInitializedData;
111 DWORD SizeOfUninitializedData;
112 DWORD AddressOfEntryPoint;
113 DWORD BaseOfCode;
114 #ifndef TCC_TARGET_X86_64
115 DWORD BaseOfData;
116 #endif
117 /* NT additional fields. */
118 ADDR3264 ImageBase;
119 DWORD SectionAlignment;
120 DWORD FileAlignment;
121 WORD MajorOperatingSystemVersion;
122 WORD MinorOperatingSystemVersion;
123 WORD MajorImageVersion;
124 WORD MinorImageVersion;
125 WORD MajorSubsystemVersion;
126 WORD MinorSubsystemVersion;
127 DWORD Win32VersionValue;
128 DWORD SizeOfImage;
129 DWORD SizeOfHeaders;
130 DWORD CheckSum;
131 WORD Subsystem;
132 WORD DllCharacteristics;
133 ADDR3264 SizeOfStackReserve;
134 ADDR3264 SizeOfStackCommit;
135 ADDR3264 SizeOfHeapReserve;
136 ADDR3264 SizeOfHeapCommit;
137 DWORD LoaderFlags;
138 DWORD NumberOfRvaAndSizes;
139 IMAGE_DATA_DIRECTORY DataDirectory[16];
140 } IMAGE_OPTIONAL_HEADER32, IMAGE_OPTIONAL_HEADER64, IMAGE_OPTIONAL_HEADER;
142 #define IMAGE_DIRECTORY_ENTRY_EXPORT 0 /* Export Directory */
143 #define IMAGE_DIRECTORY_ENTRY_IMPORT 1 /* Import Directory */
144 #define IMAGE_DIRECTORY_ENTRY_RESOURCE 2 /* Resource Directory */
145 #define IMAGE_DIRECTORY_ENTRY_EXCEPTION 3 /* Exception Directory */
146 #define IMAGE_DIRECTORY_ENTRY_SECURITY 4 /* Security Directory */
147 #define IMAGE_DIRECTORY_ENTRY_BASERELOC 5 /* Base Relocation Table */
148 #define IMAGE_DIRECTORY_ENTRY_DEBUG 6 /* Debug Directory */
149 /* IMAGE_DIRECTORY_ENTRY_COPYRIGHT 7 (X86 usage) */
150 #define IMAGE_DIRECTORY_ENTRY_ARCHITECTURE 7 /* Architecture Specific Data */
151 #define IMAGE_DIRECTORY_ENTRY_GLOBALPTR 8 /* RVA of GP */
152 #define IMAGE_DIRECTORY_ENTRY_TLS 9 /* TLS Directory */
153 #define IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG 10 /* Load Configuration Directory */
154 #define IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT 11 /* Bound Import Directory in headers */
155 #define IMAGE_DIRECTORY_ENTRY_IAT 12 /* Import Address Table */
156 #define IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT 13 /* Delay Load Import Descriptors */
157 #define IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR 14 /* COM Runtime descriptor */
159 /* Section header format. */
160 #define IMAGE_SIZEOF_SHORT_NAME 8
162 typedef struct _IMAGE_SECTION_HEADER {
163 BYTE Name[IMAGE_SIZEOF_SHORT_NAME];
164 union {
165 DWORD PhysicalAddress;
166 DWORD VirtualSize;
167 } Misc;
168 DWORD VirtualAddress;
169 DWORD SizeOfRawData;
170 DWORD PointerToRawData;
171 DWORD PointerToRelocations;
172 DWORD PointerToLinenumbers;
173 WORD NumberOfRelocations;
174 WORD NumberOfLinenumbers;
175 DWORD Characteristics;
176 } IMAGE_SECTION_HEADER, *PIMAGE_SECTION_HEADER;
178 #define IMAGE_SIZEOF_SECTION_HEADER 40
180 typedef struct _IMAGE_BASE_RELOCATION {
181 DWORD VirtualAddress;
182 DWORD SizeOfBlock;
183 // WORD TypeOffset[1];
184 } IMAGE_BASE_RELOCATION;
186 #define IMAGE_SIZEOF_BASE_RELOCATION 8
188 #define IMAGE_REL_BASED_ABSOLUTE 0
189 #define IMAGE_REL_BASED_HIGH 1
190 #define IMAGE_REL_BASED_LOW 2
191 #define IMAGE_REL_BASED_HIGHLOW 3
192 #define IMAGE_REL_BASED_HIGHADJ 4
193 #define IMAGE_REL_BASED_MIPS_JMPADDR 5
194 #define IMAGE_REL_BASED_SECTION 6
195 #define IMAGE_REL_BASED_REL32 7
197 #pragma pack(pop)
199 /* ----------------------------------------------------------- */
200 #endif /* ndef IMAGE_NT_SIGNATURE */
201 /* ----------------------------------------------------------- */
202 #pragma pack(push, 1)
204 struct pe_header
206 IMAGE_DOS_HEADER doshdr;
207 BYTE dosstub[0x40];
208 DWORD nt_sig;
209 IMAGE_FILE_HEADER filehdr;
210 #ifdef TCC_TARGET_X86_64
211 IMAGE_OPTIONAL_HEADER64 opthdr;
212 #else
213 #ifdef _WIN64
214 IMAGE_OPTIONAL_HEADER32 opthdr;
215 #else
216 IMAGE_OPTIONAL_HEADER opthdr;
217 #endif
218 #endif
221 struct pe_import_header {
222 DWORD first_entry;
223 DWORD time_date;
224 DWORD forwarder;
225 DWORD lib_name_offset;
226 DWORD first_thunk;
229 struct pe_export_header {
230 DWORD Characteristics;
231 DWORD TimeDateStamp;
232 DWORD Version;
233 DWORD Name;
234 DWORD Base;
235 DWORD NumberOfFunctions;
236 DWORD NumberOfNames;
237 DWORD AddressOfFunctions;
238 DWORD AddressOfNames;
239 DWORD AddressOfNameOrdinals;
242 struct pe_reloc_header {
243 DWORD offset;
244 DWORD size;
247 struct pe_rsrc_header {
248 struct _IMAGE_FILE_HEADER filehdr;
249 struct _IMAGE_SECTION_HEADER sectionhdr;
252 struct pe_rsrc_reloc {
253 DWORD offset;
254 DWORD size;
255 WORD type;
258 #pragma pack(pop)
260 /* ----------------------------------------------------------- */
261 ST_DATA struct pe_header pe_header = {
263 /* IMAGE_DOS_HEADER doshdr */
264 0x5A4D, /*WORD e_magic; Magic number */
265 0x0090, /*WORD e_cblp; Bytes on last page of file */
266 0x0003, /*WORD e_cp; Pages in file */
267 0x0000, /*WORD e_crlc; Relocations */
269 0x0004, /*WORD e_cparhdr; Size of header in paragraphs */
270 0x0000, /*WORD e_minalloc; Minimum extra paragraphs needed */
271 0xFFFF, /*WORD e_maxalloc; Maximum extra paragraphs needed */
272 0x0000, /*WORD e_ss; Initial (relative) SS value */
274 0x00B8, /*WORD e_sp; Initial SP value */
275 0x0000, /*WORD e_csum; Checksum */
276 0x0000, /*WORD e_ip; Initial IP value */
277 0x0000, /*WORD e_cs; Initial (relative) CS value */
278 0x0040, /*WORD e_lfarlc; File address of relocation table */
279 0x0000, /*WORD e_ovno; Overlay number */
280 {0,0,0,0}, /*WORD e_res[4]; Reserved words */
281 0x0000, /*WORD e_oemid; OEM identifier (for e_oeminfo) */
282 0x0000, /*WORD e_oeminfo; OEM information; e_oemid specific */
283 {0,0,0,0,0,0,0,0,0,0}, /*WORD e_res2[10]; Reserved words */
284 0x00000080 /*DWORD e_lfanew; File address of new exe header */
286 /* BYTE dosstub[0x40] */
287 /* 14 code bytes + "This program cannot be run in DOS mode.\r\r\n$" + 6 * 0x00 */
288 0x0e,0x1f,0xba,0x0e,0x00,0xb4,0x09,0xcd,0x21,0xb8,0x01,0x4c,0xcd,0x21,0x54,0x68,
289 0x69,0x73,0x20,0x70,0x72,0x6f,0x67,0x72,0x61,0x6d,0x20,0x63,0x61,0x6e,0x6e,0x6f,
290 0x74,0x20,0x62,0x65,0x20,0x72,0x75,0x6e,0x20,0x69,0x6e,0x20,0x44,0x4f,0x53,0x20,
291 0x6d,0x6f,0x64,0x65,0x2e,0x0d,0x0d,0x0a,0x24,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
293 0x00004550, /* DWORD nt_sig = IMAGE_NT_SIGNATURE */
295 /* IMAGE_FILE_HEADER filehdr */
296 #ifdef TCC_TARGET_X86_64
297 0x8664, /*WORD Machine; */
298 #else
299 0x014C, /*WORD Machine; */
300 #endif
301 0x0003, /*WORD NumberOfSections; */
302 0x00000000, /*DWORD TimeDateStamp; */
303 0x00000000, /*DWORD PointerToSymbolTable; */
304 0x00000000, /*DWORD NumberOfSymbols; */
305 #ifdef TCC_TARGET_X86_64
306 0x00F0, /*WORD SizeOfOptionalHeader; */
307 0x022F /*WORD Characteristics; */
308 #define CHARACTERISTICS_DLL 0x222E
309 #else
310 0x00E0, /*WORD SizeOfOptionalHeader; */
311 0x030F /*WORD Characteristics; */
312 #define CHARACTERISTICS_DLL 0x230E
313 #endif
315 /* IMAGE_OPTIONAL_HEADER opthdr */
316 /* Standard fields. */
317 #ifdef TCC_TARGET_X86_64
318 0x020B, /*WORD Magic; */
319 #else
320 0x010B, /*WORD Magic; */
321 #endif
322 0x06, /*BYTE MajorLinkerVersion; */
323 0x00, /*BYTE MinorLinkerVersion; */
324 0x00000000, /*DWORD SizeOfCode; */
325 0x00000000, /*DWORD SizeOfInitializedData; */
326 0x00000000, /*DWORD SizeOfUninitializedData; */
327 0x00000000, /*DWORD AddressOfEntryPoint; */
328 0x00000000, /*DWORD BaseOfCode; */
329 #ifndef TCC_TARGET_X86_64
330 0x00000000, /*DWORD BaseOfData; */
331 #endif
332 /* NT additional fields. */
333 0x00400000, /*DWORD ImageBase; */
334 0x00001000, /*DWORD SectionAlignment; */
335 0x00000200, /*DWORD FileAlignment; */
336 0x0004, /*WORD MajorOperatingSystemVersion; */
337 0x0000, /*WORD MinorOperatingSystemVersion; */
338 0x0000, /*WORD MajorImageVersion; */
339 0x0000, /*WORD MinorImageVersion; */
340 0x0004, /*WORD MajorSubsystemVersion; */
341 0x0000, /*WORD MinorSubsystemVersion; */
342 0x00000000, /*DWORD Win32VersionValue; */
343 0x00000000, /*DWORD SizeOfImage; */
344 0x00000200, /*DWORD SizeOfHeaders; */
345 0x00000000, /*DWORD CheckSum; */
346 0x0002, /*WORD Subsystem; */
347 0x0000, /*WORD DllCharacteristics; */
348 0x00100000, /*DWORD SizeOfStackReserve; */
349 #ifdef TCC_TARGET_X86_64
350 // need to have a __chkstk eventually
351 0x00008000, /*DWORD SizeOfStackCommit; */
352 #else
353 0x00001000, /*DWORD SizeOfStackCommit; */
354 #endif
355 0x00100000, /*DWORD SizeOfHeapReserve; */
356 0x00001000, /*DWORD SizeOfHeapCommit; */
357 0x00000000, /*DWORD LoaderFlags; */
358 0x00000010, /*DWORD NumberOfRvaAndSizes; */
360 /* IMAGE_DATA_DIRECTORY DataDirectory[16]; */
361 {{0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0},
362 {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}}
365 /* ------------------------------------------------------------- */
366 /* internal temporary structures */
369 #define IMAGE_SCN_CNT_CODE 0x00000020
370 #define IMAGE_SCN_CNT_INITIALIZED_DATA 0x00000040
371 #define IMAGE_SCN_CNT_UNINITIALIZED_DATA 0x00000080
372 #define IMAGE_SCN_MEM_DISCARDABLE 0x02000000
373 #define IMAGE_SCN_MEM_SHARED 0x10000000
374 #define IMAGE_SCN_MEM_EXECUTE 0x20000000
375 #define IMAGE_SCN_MEM_READ 0x40000000
376 #define IMAGE_SCN_MEM_WRITE 0x80000000
379 enum {
380 sec_text = 0,
381 sec_data ,
382 sec_bss ,
383 sec_idata ,
384 sec_other ,
385 sec_rsrc ,
386 sec_stab ,
387 sec_reloc ,
388 sec_last
391 ST_DATA DWORD pe_sec_flags[] = {
392 0x60000020, /* ".text" , */
393 0xC0000040, /* ".data" , */
394 0xC0000080, /* ".bss" , */
395 0x40000040, /* ".idata" , */
396 0xE0000060, /* < other > , */
397 0x40000040, /* ".rsrc" , */
398 0x42000802, /* ".stab" , */
399 0x42000040, /* ".reloc" , */
402 struct section_info {
403 int cls, ord;
404 char name[32];
405 DWORD sh_addr;
406 DWORD sh_size;
407 DWORD sh_flags;
408 unsigned char *data;
409 DWORD data_size;
410 IMAGE_SECTION_HEADER ish;
413 struct import_symbol {
414 int sym_index;
415 int iat_index;
416 int thk_offset;
419 struct pe_import_info {
420 int dll_index;
421 int sym_count;
422 struct import_symbol **symbols;
425 struct pe_info {
426 TCCState *s1;
427 Section *reloc;
428 Section *thunk;
429 const char *filename;
430 int type;
431 DWORD sizeofheaders;
432 DWORD imagebase;
433 DWORD start_addr;
434 DWORD imp_offs;
435 DWORD imp_size;
436 DWORD iat_offs;
437 DWORD iat_size;
438 DWORD exp_offs;
439 DWORD exp_size;
440 struct section_info *sec_info;
441 int sec_count;
442 struct pe_import_info **imp_info;
443 int imp_count;
446 /* ------------------------------------------------------------- */
448 #define PE_NUL 0
449 #define PE_DLL 1
450 #define PE_GUI 2
451 #define PE_EXE 3
452 #define PE_RUN 4
454 void error_noabort(const char *, ...);
456 #ifdef _WIN32
457 void dbg_printf (const char *fmt, ...)
459 char buffer[4000];
460 va_list arg;
461 int x;
462 va_start(arg, fmt);
463 x = vsprintf (buffer, fmt, arg);
464 strcpy(buffer+x, "\n");
465 OutputDebugString(buffer);
467 #endif
469 /* --------------------------------------------*/
471 ST_FN const char* get_alt_symbol(char *buffer, const char *symbol)
473 const char *p;
474 p = strrchr(symbol, '@');
475 if (p && isnum(p[1]) && symbol[0] == '_') { /* stdcall decor */
476 strcpy(buffer, symbol+1)[p-symbol-1] = 0;
477 } else if (symbol[0] != '_') { /* try non-ansi function */
478 buffer[0] = '_', strcpy(buffer + 1, symbol);
479 } else if (0 == memcmp(symbol, "__imp__", 7)) { /* mingw 2.0 */
480 strcpy(buffer, symbol + 6);
481 } else if (0 == memcmp(symbol, "_imp___", 7)) { /* mingw 3.7 */
482 strcpy(buffer, symbol + 6);
483 } else {
484 return symbol;
486 return buffer;
489 ST_FN int pe_find_import(TCCState * s1, const char *symbol)
491 char buffer[200];
492 const char *s;
493 int sym_index, n = 0;
494 do {
495 s = n ? get_alt_symbol(buffer, symbol) : symbol;
496 sym_index = find_elf_sym(s1->dynsymtab_section, s);
497 // printf("find (%d) %d %s\n", n, sym_index, s);
498 } while (0 == sym_index && ++n < 2);
499 return sym_index;
502 /*----------------------------------------------------------------------------*/
504 ST_FN int dynarray_assoc(void **pp, int n, int key)
506 int i;
507 for (i = 0; i < n; ++i, ++pp)
508 if (key == **(int **) pp)
509 return i;
510 return -1;
513 #if 0
514 ST_FN DWORD umin(DWORD a, DWORD b)
516 return a < b ? a : b;
518 #endif
520 ST_FN DWORD umax(DWORD a, DWORD b)
522 return a < b ? b : a;
525 ST_FN void pe_fpad(FILE *fp, DWORD new_pos)
527 DWORD pos = ftell(fp);
528 while (++pos <= new_pos)
529 fputc(0, fp);
532 ST_FN DWORD pe_file_align(DWORD n)
534 return (n + (0x200 - 1)) & ~(0x200 - 1);
537 ST_FN DWORD pe_virtual_align(DWORD n)
539 return (n + (0x1000 - 1)) & ~(0x1000 - 1);
542 ST_FN void pe_align_section(Section *s, int a)
544 int i = s->data_offset & (a-1);
545 if (i)
546 section_ptr_add(s, a - i);
549 ST_FN void pe_set_datadir(int dir, DWORD addr, DWORD size)
551 pe_header.opthdr.DataDirectory[dir].VirtualAddress = addr;
552 pe_header.opthdr.DataDirectory[dir].Size = size;
555 /*----------------------------------------------------------------------------*/
556 ST_FN int pe_write(struct pe_info *pe)
558 int i;
559 FILE *op;
560 DWORD file_offset, r;
562 op = fopen(pe->filename, "wb");
563 if (NULL == op) {
564 error_noabort("could not write '%s': %s", pe->filename, strerror(errno));
565 return 1;
568 pe->sizeofheaders = pe_file_align(
569 sizeof pe_header
570 + pe->sec_count * sizeof (IMAGE_SECTION_HEADER)
573 file_offset = pe->sizeofheaders;
574 pe_fpad(op, file_offset);
576 if (2 == pe->s1->verbose)
577 printf("-------------------------------"
578 "\n virt file size section" "\n");
580 for (i = 0; i < pe->sec_count; ++i) {
581 struct section_info *si = pe->sec_info + i;
582 const char *sh_name = si->name;
583 unsigned long addr = si->sh_addr - pe->imagebase;
584 unsigned long size = si->sh_size;
585 IMAGE_SECTION_HEADER *psh = &si->ish;
587 if (2 == pe->s1->verbose)
588 printf("%6lx %6lx %6lx %s\n",
589 addr, file_offset, size, sh_name);
591 switch (si->cls) {
592 case sec_text:
593 pe_header.opthdr.BaseOfCode = addr;
594 pe_header.opthdr.AddressOfEntryPoint = addr + pe->start_addr;
595 break;
597 case sec_data:
598 #ifndef TCC_TARGET_X86_64
599 pe_header.opthdr.BaseOfData = addr;
600 #endif
601 break;
603 case sec_bss:
604 break;
606 case sec_reloc:
607 pe_set_datadir(IMAGE_DIRECTORY_ENTRY_BASERELOC, addr, size);
608 break;
610 case sec_rsrc:
611 pe_set_datadir(IMAGE_DIRECTORY_ENTRY_RESOURCE, addr, size);
612 break;
614 case sec_stab:
615 break;
618 if (pe->thunk == pe->s1->sections[si->ord]) {
619 if (pe->imp_size) {
620 pe_set_datadir(IMAGE_DIRECTORY_ENTRY_IMPORT,
621 pe->imp_offs + addr, pe->imp_size);
622 pe_set_datadir(IMAGE_DIRECTORY_ENTRY_IAT,
623 pe->iat_offs + addr, pe->iat_size);
625 if (pe->exp_size) {
626 pe_set_datadir(IMAGE_DIRECTORY_ENTRY_EXPORT,
627 pe->exp_offs + addr, pe->exp_size);
631 strcpy((char*)psh->Name, sh_name);
633 psh->Characteristics = pe_sec_flags[si->cls];
634 psh->VirtualAddress = addr;
635 psh->Misc.VirtualSize = size;
636 pe_header.opthdr.SizeOfImage =
637 umax(pe_virtual_align(size + addr), pe_header.opthdr.SizeOfImage);
639 if (si->data_size) {
640 psh->PointerToRawData = r = file_offset;
641 fwrite(si->data, 1, si->data_size, op);
642 file_offset = pe_file_align(file_offset + si->data_size);
643 psh->SizeOfRawData = file_offset - r;
644 pe_fpad(op, file_offset);
648 // pe_header.filehdr.TimeDateStamp = time(NULL);
649 pe_header.filehdr.NumberOfSections = pe->sec_count;
650 pe_header.opthdr.SizeOfHeaders = pe->sizeofheaders;
651 pe_header.opthdr.ImageBase = pe->imagebase;
652 if (PE_DLL == pe->type)
653 pe_header.filehdr.Characteristics = CHARACTERISTICS_DLL;
654 else if (PE_GUI != pe->type)
655 pe_header.opthdr.Subsystem = 3;
657 fseek(op, SEEK_SET, 0);
658 fwrite(&pe_header, 1, sizeof pe_header, op);
659 for (i = 0; i < pe->sec_count; ++i)
660 fwrite(&pe->sec_info[i].ish, 1, sizeof(IMAGE_SECTION_HEADER), op);
661 fclose (op);
663 if (2 == pe->s1->verbose)
664 printf("-------------------------------\n");
665 if (pe->s1->verbose)
666 printf("<- %s (%lu bytes)\n", pe->filename, file_offset);
668 return 0;
671 /*----------------------------------------------------------------------------*/
673 #ifdef TCC_TARGET_X86_64
674 #define ELFW_R_(type) ELF64_R_##type
675 #define ElfW_Rel ElfW(Rela)
677 #define REL_TYPE_DIRECT R_X86_64_64
678 #define R_XXX_THUNKFIX R_X86_64_PC32
679 #define R_XXX_RELATIVE R_X86_64_RELATIVE
681 #define ELFW_ST_BIND ELF64_ST_BIND
682 #define ELFW_ST_TYPE ELF64_ST_TYPE
683 #define ELFW_ST_INFO ELF64_ST_INFO
684 #else
685 #define ELFW_R_(type) ELF32_R_##type
686 #define ElfW_Rel ElfW(Rel)
688 #define REL_TYPE_DIRECT R_386_32
689 #define R_XXX_THUNKFIX R_386_32
690 #define R_XXX_RELATIVE R_386_RELATIVE
692 #define ELFW_ST_BIND ELF32_ST_BIND
693 #define ELFW_ST_TYPE ELF32_ST_TYPE
694 #define ELFW_ST_INFO ELF32_ST_INFO
695 #endif
696 /*----------------------------------------------------------------------------*/
698 ST_FN struct import_symbol *pe_add_import(struct pe_info *pe, int sym_index)
700 int i;
701 int dll_index;
702 struct pe_import_info *p;
703 struct import_symbol *s;
705 dll_index = ((ElfW(Sym) *)pe->s1->dynsymtab_section->data + sym_index)->st_value;
706 if (0 == dll_index)
707 return NULL;
709 i = dynarray_assoc ((void**)pe->imp_info, pe->imp_count, dll_index);
710 if (-1 != i) {
711 p = pe->imp_info[i];
712 goto found_dll;
714 p = tcc_mallocz(sizeof *p);
715 p->dll_index = dll_index;
716 dynarray_add((void***)&pe->imp_info, &pe->imp_count, p);
718 found_dll:
719 i = dynarray_assoc ((void**)p->symbols, p->sym_count, sym_index);
720 if (-1 != i)
721 return p->symbols[i];
723 s = tcc_mallocz(sizeof *s);
724 dynarray_add((void***)&p->symbols, &p->sym_count, s);
725 s->sym_index = sym_index;
726 return s;
729 /*----------------------------------------------------------------------------*/
730 ST_FN void pe_build_imports(struct pe_info *pe)
732 int thk_ptr, ent_ptr, dll_ptr, sym_cnt, i;
733 DWORD rva_base = pe->thunk->sh_addr - pe->imagebase;
734 int ndlls = pe->imp_count;
736 for (sym_cnt = i = 0; i < ndlls; ++i)
737 sym_cnt += pe->imp_info[i]->sym_count;
739 if (0 == sym_cnt)
740 return;
742 pe_align_section(pe->thunk, 16);
744 pe->imp_offs = dll_ptr = pe->thunk->data_offset;
745 pe->imp_size = (ndlls + 1) * sizeof(struct pe_import_header);
746 pe->iat_offs = dll_ptr + pe->imp_size;
747 pe->iat_size = (sym_cnt + ndlls) * sizeof(ADDR3264);
748 section_ptr_add(pe->thunk, pe->imp_size + 2*pe->iat_size);
750 thk_ptr = pe->iat_offs;
751 ent_ptr = pe->iat_offs + pe->iat_size;
753 for (i = 0; i < pe->imp_count; ++i) {
754 struct pe_import_header *hdr;
755 int k, n;
756 ADDR3264 v;
757 struct pe_import_info *p = pe->imp_info[i];
758 const char *name = pe->s1->loaded_dlls[p->dll_index-1]->name;
760 /* put the dll name into the import header */
761 v = put_elf_str(pe->thunk, name);
763 hdr = (struct pe_import_header*)(pe->thunk->data + dll_ptr);
764 hdr->first_thunk = thk_ptr + rva_base;
765 hdr->first_entry = ent_ptr + rva_base;
766 hdr->lib_name_offset = v + rva_base;
768 for (k = 0, n = p->sym_count; k <= n; ++k) {
769 if (k < n) {
770 int iat_index = p->symbols[k]->iat_index;
771 int sym_index = p->symbols[k]->sym_index;
772 ElfW(Sym) *imp_sym = (ElfW(Sym) *)pe->s1->dynsymtab_section->data + sym_index;
773 ElfW(Sym) *org_sym = (ElfW(Sym) *)symtab_section->data + iat_index;
774 const char *name = pe->s1->dynsymtab_section->link->data + imp_sym->st_name;
776 org_sym->st_value = thk_ptr;
777 org_sym->st_shndx = pe->thunk->sh_num;
778 v = pe->thunk->data_offset + rva_base;
779 section_ptr_add(pe->thunk, sizeof(WORD)); /* hint, not used */
780 put_elf_str(pe->thunk, name);
781 #ifdef TCC_IS_NATIVE
782 if (pe->type == PE_RUN) {
783 DLLReference *dllref = pe->s1->loaded_dlls[imp_sym->st_value-1];
784 if ( !dllref->handle )
785 dllref->handle = LoadLibrary(dllref->name);
786 v = (ADDR3264)GetProcAddress(dllref->handle, name);
787 if (!v)
788 error_noabort("undefined symbol '%s'", name);
790 #endif
791 } else {
792 v = 0; /* last entry is zero */
794 *(ADDR3264*)(pe->thunk->data+thk_ptr) =
795 *(ADDR3264*)(pe->thunk->data+ent_ptr) = v;
796 thk_ptr += sizeof (ADDR3264);
797 ent_ptr += sizeof (ADDR3264);
799 dll_ptr += sizeof(struct pe_import_header);
800 dynarray_reset(&p->symbols, &p->sym_count);
802 dynarray_reset(&pe->imp_info, &pe->imp_count);
805 /* ------------------------------------------------------------- */
807 For now only functions are exported. Export of data
808 would work, but import requires compiler support to
809 do an additional indirection.
811 For instance:
812 __declspec(dllimport) extern int something;
814 needs to be translated to:
816 *(int*)something
819 struct pe_sort_sym
821 int index;
822 const char *name;
825 ST_FN int sym_cmp(const void *va, const void *vb)
827 const char *ca = (*(struct pe_sort_sym**)va)->name;
828 const char *cb = (*(struct pe_sort_sym**)vb)->name;
829 return strcmp(ca, cb);
832 ST_FN void pe_build_exports(struct pe_info *pe)
834 ElfW(Sym) *sym;
835 int sym_index, sym_end;
836 DWORD rva_base, func_o, name_o, ord_o, str_o;
837 struct pe_export_header *hdr;
838 int sym_count, ord;
839 struct pe_sort_sym **sorted, *p;
841 FILE *op;
842 char buf[MAX_PATH];
843 const char *dllname;
844 const char *name;
846 rva_base = pe->thunk->sh_addr - pe->imagebase;
847 sym_count = 0, sorted = NULL, op = NULL;
849 sym_end = symtab_section->data_offset / sizeof(ElfW(Sym));
850 for (sym_index = 1; sym_index < sym_end; ++sym_index) {
851 sym = (ElfW(Sym)*)symtab_section->data + sym_index;
852 name = symtab_section->link->data + sym->st_name;
853 if ((sym->st_other & 1)
854 /* export only symbols from actually written sections */
855 && pe->s1->sections[sym->st_shndx]->sh_addr) {
856 p = tcc_malloc(sizeof *p);
857 p->index = sym_index;
858 p->name = name;
859 dynarray_add((void***)&sorted, &sym_count, p);
861 #if 0
862 if (sym->st_other & 1)
863 printf("export: %s\n", name);
864 if (sym->st_other & 2)
865 printf("stdcall: %s\n", name);
866 #endif
869 if (0 == sym_count)
870 return;
872 qsort (sorted, sym_count, sizeof *sorted, sym_cmp);
874 pe_align_section(pe->thunk, 16);
875 dllname = tcc_basename(pe->filename);
877 pe->exp_offs = pe->thunk->data_offset;
878 func_o = pe->exp_offs + sizeof(struct pe_export_header);
879 name_o = func_o + sym_count * sizeof (DWORD);
880 ord_o = name_o + sym_count * sizeof (DWORD);
881 str_o = ord_o + sym_count * sizeof(WORD);
883 hdr = section_ptr_add(pe->thunk, str_o - pe->exp_offs);
884 hdr->Characteristics = 0;
885 hdr->Base = 1;
886 hdr->NumberOfFunctions = sym_count;
887 hdr->NumberOfNames = sym_count;
888 hdr->AddressOfFunctions = func_o + rva_base;
889 hdr->AddressOfNames = name_o + rva_base;
890 hdr->AddressOfNameOrdinals = ord_o + rva_base;
891 hdr->Name = str_o + rva_base;
892 put_elf_str(pe->thunk, dllname);
894 #if 1
895 /* automatically write exports to <output-filename>.def */
896 strcpy(buf, pe->filename);
897 strcpy(tcc_fileextension(buf), ".def");
898 op = fopen(buf, "w");
899 if (NULL == op) {
900 error_noabort("could not create '%s': %s", buf, strerror(errno));
901 } else {
902 fprintf(op, "LIBRARY %s\n\nEXPORTS\n", dllname);
903 if (pe->s1->verbose)
904 printf("<- %s (%d symbols)\n", buf, sym_count);
906 #endif
908 for (ord = 0; ord < sym_count; ++ord)
910 p = sorted[ord], sym_index = p->index, name = p->name;
911 /* insert actual address later in pe_relocate_rva */
912 put_elf_reloc(symtab_section, pe->thunk,
913 func_o, R_XXX_RELATIVE, sym_index);
914 *(DWORD*)(pe->thunk->data + name_o)
915 = pe->thunk->data_offset + rva_base;
916 *(WORD*)(pe->thunk->data + ord_o)
917 = ord;
918 put_elf_str(pe->thunk, name);
919 func_o += sizeof (DWORD);
920 name_o += sizeof (DWORD);
921 ord_o += sizeof (WORD);
922 if (op)
923 fprintf(op, "%s\n", name);
925 pe->exp_size = pe->thunk->data_offset - pe->exp_offs;
926 dynarray_reset(&sorted, &sym_count);
929 /* ------------------------------------------------------------- */
930 ST_FN void pe_build_reloc (struct pe_info *pe)
932 DWORD offset, block_ptr, addr;
933 int count, i;
934 ElfW_Rel *rel, *rel_end;
935 Section *s = NULL, *sr;
937 offset = addr = block_ptr = count = i = 0;
938 rel = rel_end = NULL;
940 for(;;) {
941 if (rel < rel_end) {
942 int type = ELFW_R_(TYPE)(rel->r_info);
943 addr = rel->r_offset + s->sh_addr;
944 ++ rel;
945 if (type != REL_TYPE_DIRECT)
946 continue;
947 if (count == 0) { /* new block */
948 block_ptr = pe->reloc->data_offset;
949 section_ptr_add(pe->reloc, sizeof(struct pe_reloc_header));
950 offset = addr & 0xFFFFFFFF<<12;
952 if ((addr -= offset) < (1<<12)) { /* one block spans 4k addresses */
953 WORD *wp = section_ptr_add(pe->reloc, sizeof (WORD));
954 *wp = addr | IMAGE_REL_BASED_HIGHLOW<<12;
955 ++count;
956 continue;
958 -- rel;
960 } else if (i < pe->sec_count) {
961 sr = (s = pe->s1->sections[pe->sec_info[i++].ord])->reloc;
962 if (sr) {
963 rel = (ElfW_Rel *)sr->data;
964 rel_end = (ElfW_Rel *)(sr->data + sr->data_offset);
966 continue;
969 if (count) {
970 /* store the last block and ready for a new one */
971 struct pe_reloc_header *hdr;
972 if (count & 1) /* align for DWORDS */
973 section_ptr_add(pe->reloc, sizeof(WORD)), ++count;
974 hdr = (struct pe_reloc_header *)(pe->reloc->data + block_ptr);
975 hdr -> offset = offset - pe->imagebase;
976 hdr -> size = count * sizeof(WORD) + sizeof(struct pe_reloc_header);
977 count = 0;
980 if (rel >= rel_end)
981 break;
985 /* ------------------------------------------------------------- */
986 ST_FN int pe_section_class(Section *s)
988 int type, flags;
989 const char *name;
991 type = s->sh_type;
992 flags = s->sh_flags;
993 name = s->name;
994 if (flags & SHF_ALLOC) {
995 if (type == SHT_PROGBITS) {
996 if (flags & SHF_EXECINSTR)
997 return sec_text;
998 if (flags & SHF_WRITE)
999 return sec_data;
1000 if (0 == strcmp(name, ".rsrc"))
1001 return sec_rsrc;
1002 if (0 == strcmp(name, ".iedat"))
1003 return sec_idata;
1004 return sec_other;
1005 } else if (type == SHT_NOBITS) {
1006 if (flags & SHF_WRITE)
1007 return sec_bss;
1009 } else {
1010 if (0 == strcmp(name, ".reloc"))
1011 return sec_reloc;
1012 if (0 == strncmp(name, ".stab", 5)) /* .stab and .stabstr */
1013 return sec_stab;
1015 return -1;
1018 ST_FN int pe_assign_addresses (struct pe_info *pe)
1020 int i, k, o, c;
1021 DWORD addr;
1022 int *section_order;
1023 struct section_info *si;
1024 Section *s;
1026 // pe->thunk = new_section(pe->s1, ".iedat", SHT_PROGBITS, SHF_ALLOC);
1028 section_order = tcc_malloc(pe->s1->nb_sections * sizeof (int));
1029 for (o = k = 0 ; k < sec_last; ++k) {
1030 for (i = 1; i < pe->s1->nb_sections; ++i) {
1031 s = pe->s1->sections[i];
1032 if (k == pe_section_class(s)) {
1033 // printf("%s %d\n", s->name, k);
1034 s->sh_addr = pe->imagebase;
1035 section_order[o++] = i;
1040 pe->sec_info = tcc_mallocz(o * sizeof (struct section_info));
1041 addr = pe->imagebase + 1;
1043 for (i = 0; i < o; ++i)
1045 k = section_order[i];
1046 s = pe->s1->sections[k];
1047 c = pe_section_class(s);
1048 si = &pe->sec_info[pe->sec_count];
1050 #ifdef PE_MERGE_DATA
1051 if (c == sec_bss && pe->sec_count && si[-1].cls == sec_data) {
1052 /* append .bss to .data */
1053 s->sh_addr = addr = ((addr-1) | 15) + 1;
1054 addr += s->data_offset;
1055 si[-1].sh_size = addr - si[-1].sh_addr;
1056 continue;
1058 #endif
1059 strcpy(si->name, s->name);
1060 si->cls = c;
1061 si->ord = k;
1062 si->sh_addr = s->sh_addr = addr = pe_virtual_align(addr);
1063 si->sh_flags = s->sh_flags;
1065 if (c == sec_data && NULL == pe->thunk)
1066 pe->thunk = s;
1068 if (s == pe->thunk) {
1069 pe_build_imports(pe);
1070 pe_build_exports(pe);
1073 if (c == sec_reloc)
1074 pe_build_reloc (pe);
1076 if (s->data_offset)
1078 if (s->sh_type != SHT_NOBITS) {
1079 si->data = s->data;
1080 si->data_size = s->data_offset;
1083 addr += s->data_offset;
1084 si->sh_size = s->data_offset;
1085 ++pe->sec_count;
1087 // printf("%08x %05x %s\n", si->sh_addr, si->sh_size, si->name);
1090 #if 0
1091 for (i = 1; i < pe->s1->nb_sections; ++i) {
1092 Section *s = pe->s1->sections[i];
1093 int type = s->sh_type;
1094 int flags = s->sh_flags;
1095 printf("section %-16s %-10s %5x %s,%s,%s\n",
1096 s->name,
1097 type == SHT_PROGBITS ? "progbits" :
1098 type == SHT_NOBITS ? "nobits" :
1099 type == SHT_SYMTAB ? "symtab" :
1100 type == SHT_STRTAB ? "strtab" :
1101 type == SHT_RELX ? "rel" : "???",
1102 s->data_offset,
1103 flags & SHF_ALLOC ? "alloc" : "",
1104 flags & SHF_WRITE ? "write" : "",
1105 flags & SHF_EXECINSTR ? "exec" : ""
1108 pe->s1->verbose = 2;
1109 #endif
1111 tcc_free(section_order);
1112 return 0;
1115 /* ------------------------------------------------------------- */
1116 ST_FN void pe_relocate_rva (struct pe_info *pe, Section *s)
1118 Section *sr = s->reloc;
1119 ElfW_Rel *rel, *rel_end;
1120 rel_end = (ElfW_Rel *)(sr->data + sr->data_offset);
1121 for(rel = (ElfW_Rel *)sr->data; rel < rel_end; rel++) {
1122 if (ELFW_R_(TYPE)(rel->r_info) == R_XXX_RELATIVE) {
1123 int sym_index = ELFW_R_(SYM)(rel->r_info);
1124 DWORD addr = s->sh_addr;
1125 if (sym_index) {
1126 ElfW(Sym) *sym = (ElfW(Sym) *)symtab_section->data + sym_index;
1127 addr = sym->st_value;
1129 // printf("reloc rva %08x %08x\n", (DWORD)rel->r_offset, addr);
1130 *(DWORD*)(s->data + rel->r_offset) += addr - pe->imagebase;
1135 /*----------------------------------------------------------------------------*/
1136 ST_FN int pe_check_symbols(struct pe_info *pe)
1138 ElfW(Sym) *sym;
1139 int sym_index, sym_end;
1140 int ret = 0;
1142 pe_align_section(text_section, 8);
1144 sym_end = symtab_section->data_offset / sizeof(ElfW(Sym));
1145 for (sym_index = 1; sym_index < sym_end; ++sym_index) {
1147 sym = (ElfW(Sym) *)symtab_section->data + sym_index;
1148 if (sym->st_shndx == SHN_UNDEF) {
1150 const char *name = symtab_section->link->data + sym->st_name;
1151 unsigned type = ELFW_ST_TYPE(sym->st_info);
1152 int imp_sym = pe_find_import(pe->s1, name);
1153 struct import_symbol *is;
1155 if (0 == imp_sym)
1156 goto not_found;
1157 is = pe_add_import(pe, imp_sym);
1158 if (!is)
1159 goto not_found;
1161 if (type == STT_FUNC) {
1162 unsigned long offset = is->thk_offset;
1163 if (offset) {
1164 /* got aliased symbol, like stricmp and _stricmp */
1166 } else {
1167 char buffer[100];
1168 WORD *p;
1170 offset = text_section->data_offset;
1171 /* add the 'jmp IAT[x]' instruction */
1172 p = section_ptr_add(text_section, 8);
1173 *p = 0x25FF;
1174 #ifdef TCC_TARGET_X86_64
1175 *(DWORD*)(p+1) = (DWORD)-4;
1176 #endif
1177 /* add a helper symbol, will be patched later in
1178 pe_build_imports */
1179 sprintf(buffer, "IAT.%s", name);
1180 is->iat_index = put_elf_sym(
1181 symtab_section, 0, sizeof(DWORD),
1182 ELFW_ST_INFO(STB_GLOBAL, STT_OBJECT),
1183 0, SHN_UNDEF, buffer);
1184 put_elf_reloc(symtab_section, text_section,
1185 offset + 2, R_XXX_THUNKFIX, is->iat_index);
1186 is->thk_offset = offset;
1189 /* tcc_realloc might have altered sym's address */
1190 sym = (ElfW(Sym) *)symtab_section->data + sym_index;
1192 /* patch the original symbol */
1193 sym->st_value = offset;
1194 sym->st_shndx = text_section->sh_num;
1195 sym->st_other &= ~1; /* do not export */
1196 continue;
1199 if (type == STT_OBJECT) { /* data, ptr to that should be */
1200 if (0 == is->iat_index) {
1201 /* original symbol will be patched later in pe_build_imports */
1202 is->iat_index = sym_index;
1203 continue;
1207 not_found:
1208 error_noabort("undefined symbol '%s'", name);
1209 ret = 1;
1211 } else if (pe->s1->rdynamic
1212 && ELFW_ST_BIND(sym->st_info) != STB_LOCAL) {
1213 /* if -rdynamic option, then export all non local symbols */
1214 sym->st_other |= 1;
1217 return ret;
1220 /*----------------------------------------------------------------------------*/
1221 #ifdef PE_PRINT_SECTIONS
1222 ST_FN void pe_print_section(FILE * f, Section * s)
1224 /* just if you'r curious */
1225 BYTE *p, *e, b;
1226 int i, n, l, m;
1227 p = s->data;
1228 e = s->data + s->data_offset;
1229 l = e - p;
1231 fprintf(f, "section \"%s\"", s->name);
1232 if (s->link)
1233 fprintf(f, "\nlink \"%s\"", s->link->name);
1234 if (s->reloc)
1235 fprintf(f, "\nreloc \"%s\"", s->reloc->name);
1236 fprintf(f, "\nv_addr %08X", (unsigned)s->sh_addr);
1237 fprintf(f, "\ncontents %08X", (unsigned)l);
1238 fprintf(f, "\n\n");
1240 if (s->sh_type == SHT_NOBITS)
1241 return;
1243 if (0 == l)
1244 return;
1246 if (s->sh_type == SHT_SYMTAB)
1247 m = sizeof(ElfW(Sym));
1248 else if (s->sh_type == SHT_RELX)
1249 m = sizeof(ElfW_Rel);
1250 else
1251 m = 16;
1253 fprintf(f, "%-8s", "offset");
1254 for (i = 0; i < m; ++i)
1255 fprintf(f, " %02x", i);
1256 n = 56;
1258 if (s->sh_type == SHT_SYMTAB || s->sh_type == SHT_RELX) {
1259 const char *fields1[] = {
1260 "name",
1261 "value",
1262 "size",
1263 "bind",
1264 "type",
1265 "other",
1266 "shndx",
1267 NULL
1270 const char *fields2[] = {
1271 "offs",
1272 "type",
1273 "symb",
1274 NULL
1277 const char **p;
1279 if (s->sh_type == SHT_SYMTAB)
1280 p = fields1, n = 106;
1281 else
1282 p = fields2, n = 58;
1284 for (i = 0; p[i]; ++i)
1285 fprintf(f, "%6s", p[i]);
1286 fprintf(f, " symbol");
1289 fprintf(f, "\n");
1290 for (i = 0; i < n; ++i)
1291 fprintf(f, "-");
1292 fprintf(f, "\n");
1294 for (i = 0; i < l;)
1296 fprintf(f, "%08X", i);
1297 for (n = 0; n < m; ++n) {
1298 if (n + i < l)
1299 fprintf(f, " %02X", p[i + n]);
1300 else
1301 fprintf(f, " ");
1304 if (s->sh_type == SHT_SYMTAB) {
1305 ElfW(Sym) *sym = (ElfW(Sym) *) (p + i);
1306 const char *name = s->link->data + sym->st_name;
1307 fprintf(f, " %04X %04X %04X %02X %02X %02X %04X \"%s\"",
1308 (unsigned)sym->st_name,
1309 (unsigned)sym->st_value,
1310 (unsigned)sym->st_size,
1311 (unsigned)ELFW_ST_BIND(sym->st_info),
1312 (unsigned)ELFW_ST_TYPE(sym->st_info),
1313 (unsigned)sym->st_other,
1314 (unsigned)sym->st_shndx,
1315 name);
1317 } else if (s->sh_type == SHT_RELX) {
1318 ElfW_Rel *rel = (ElfW_Rel *) (p + i);
1319 ElfW(Sym) *sym =
1320 (ElfW(Sym) *) s->link->data + ELFW_R_(SYM)(rel->r_info);
1321 const char *name = s->link->link->data + sym->st_name;
1322 fprintf(f, " %04X %02X %04X \"%s\"",
1323 (unsigned)rel->r_offset,
1324 (unsigned)ELFW_R_(TYPE)(rel->r_info),
1325 (unsigned)ELFW_R_(SYM)(rel->r_info),
1326 name);
1327 } else {
1328 fprintf(f, " ");
1329 for (n = 0; n < m; ++n) {
1330 if (n + i < l) {
1331 b = p[i + n];
1332 if (b < 32 || b >= 127)
1333 b = '.';
1334 fprintf(f, "%c", b);
1338 i += m;
1339 fprintf(f, "\n");
1341 fprintf(f, "\n\n");
1344 ST_FN void pe_print_sections(TCCState *s1, const char *fname)
1346 Section *s;
1347 FILE *f;
1348 int i;
1349 f = fopen(fname, "w");
1350 for (i = 1; i < s1->nb_sections; ++i) {
1351 s = s1->sections[i];
1352 pe_print_section(f, s);
1354 pe_print_section(f, s1->dynsymtab_section);
1355 fclose(f);
1357 #endif
1359 /* -------------------------------------------------------------
1360 * This is for compiled windows resources in 'coff' format
1361 * as generated by 'windres.exe -O coff ...'.
1364 PUB_FN int pe_test_res_file(void *v, int size)
1366 struct pe_rsrc_header *p = (struct pe_rsrc_header *)v;
1367 return
1368 size >= IMAGE_SIZEOF_FILE_HEADER + IMAGE_SIZEOF_SHORT_NAME /* = 28 */
1369 && p->filehdr.Machine == 0x014C
1370 && 1 == p->filehdr.NumberOfSections
1371 && 0 == strcmp(p->sectionhdr.Name, ".rsrc")
1375 ST_FN int read_n(int fd, void *ptr, unsigned size)
1377 return size == read(fd, ptr, size);
1380 PUB_FN int pe_load_res_file(TCCState *s1, int fd)
1382 struct pe_rsrc_header hdr;
1383 Section *rsrc_section;
1384 int i, ret = -1;
1385 BYTE *ptr;
1387 lseek (fd, 0, SEEK_SET);
1388 if (!read_n(fd, &hdr, sizeof hdr))
1389 goto quit;
1390 if (!pe_test_res_file(&hdr, sizeof hdr))
1391 goto quit;
1393 rsrc_section = new_section(s1, ".rsrc", SHT_PROGBITS, SHF_ALLOC);
1394 ptr = section_ptr_add(rsrc_section, hdr.sectionhdr.SizeOfRawData);
1395 lseek (fd, hdr.sectionhdr.PointerToRawData, SEEK_SET);
1396 if (!read_n(fd, ptr, hdr.sectionhdr.SizeOfRawData))
1397 goto quit;
1399 lseek (fd, hdr.sectionhdr.PointerToRelocations, SEEK_SET);
1400 for (i = 0; i < hdr.sectionhdr.NumberOfRelocations; ++i)
1402 struct pe_rsrc_reloc rel;
1403 if (!read_n(fd, &rel, sizeof rel))
1404 goto quit;
1405 // printf("rsrc_reloc: %x %x %x\n", rel.offset, rel.size, rel.type);
1406 if (rel.type != 7) /* DIR32NB */
1407 goto quit;
1408 put_elf_reloc(symtab_section, rsrc_section,
1409 rel.offset, R_XXX_RELATIVE, 0);
1411 ret = 0;
1412 quit:
1413 if (ret)
1414 error_noabort("unrecognized resource file format");
1415 return ret;
1418 /* ------------------------------------------------------------- */
1419 ST_FN char *trimfront(char *p)
1421 while (*p && (unsigned char)*p <= ' ')
1422 ++p;
1423 return p;
1426 ST_FN char *trimback(char *a, char *e)
1428 while (e > a && (unsigned char)e[-1] <= ' ')
1429 --e;
1430 *e = 0;;
1431 return a;
1434 ST_FN char *get_line(char *line, int size, FILE *fp)
1436 if (NULL == fgets(line, size, fp))
1437 return NULL;
1438 trimback(line, strchr(line, 0));
1439 return trimfront(line);
1442 /* ------------------------------------------------------------- */
1443 PUB_FN int pe_load_def_file(TCCState *s1, int fd)
1445 DLLReference *dllref;
1446 int state = 0, ret = -1;
1447 char line[400], dllname[80], *p;
1448 FILE *fp = fdopen(dup(fd), "rb");
1450 if (NULL == fp)
1451 goto quit;
1453 for (;;) {
1454 p = get_line(line, sizeof line, fp);
1455 if (NULL == p)
1456 break;
1457 if (0 == *p || ';' == *p)
1458 continue;
1459 switch (state) {
1460 case 0:
1461 if (0 != strnicmp(p, "LIBRARY", 7))
1462 goto quit;
1463 strcpy(dllname, trimfront(p+7));
1464 ++state;
1465 continue;
1467 case 1:
1468 if (0 != stricmp(p, "EXPORTS"))
1469 goto quit;
1470 ++state;
1471 continue;
1473 case 2:
1474 dllref = tcc_mallocz(sizeof(DLLReference) + strlen(dllname));
1475 strcpy(dllref->name, dllname);
1476 dynarray_add((void ***) &s1->loaded_dlls, &s1->nb_loaded_dlls, dllref);
1477 ++state;
1479 default:
1480 add_elf_sym(s1->dynsymtab_section,
1481 s1->nb_loaded_dlls, 0,
1482 ELFW_ST_INFO(STB_GLOBAL, STT_FUNC), 0,
1483 text_section->sh_num, p);
1484 continue;
1487 ret = 0;
1488 quit:
1489 if (fp)
1490 fclose(fp);
1491 if (ret)
1492 error_noabort("unrecognized export definition file format");
1493 return ret;
1496 /* ------------------------------------------------------------- */
1497 #ifdef TCC_TARGET_X86_64
1498 #define PE_STDSYM(n,s) n
1499 #else
1500 #define PE_STDSYM(n,s) "_" n s
1501 #endif
1503 ST_FN void pe_add_runtime_ex(TCCState *s1, struct pe_info *pe)
1505 const char *start_symbol;
1506 unsigned long addr = 0;
1507 int pe_type = 0;
1509 if (find_elf_sym(symtab_section, PE_STDSYM("WinMain","@16")))
1510 pe_type = PE_GUI;
1511 else
1512 if (TCC_OUTPUT_DLL == s1->output_type) {
1513 pe_type = PE_DLL;
1514 /* need this for 'tccelf.c:relocate_section()' */
1515 s1->output_type = TCC_OUTPUT_EXE;
1518 start_symbol =
1519 TCC_OUTPUT_MEMORY == s1->output_type
1520 ? PE_GUI == pe_type ? "_runwinmain" : NULL
1521 : PE_DLL == pe_type ? PE_STDSYM("_dllstart","@12")
1522 : PE_GUI == pe_type ? "_winstart" : "_start"
1525 /* grab the startup code from libtcc1 */
1526 if (start_symbol)
1527 add_elf_sym(symtab_section,
1528 0, 0,
1529 ELFW_ST_INFO(STB_GLOBAL, STT_NOTYPE), 0,
1530 SHN_UNDEF, start_symbol);
1532 if (0 == s1->nostdlib) {
1533 static const char *libs[] = {
1534 "tcc1", "msvcrt", "kernel32", "", "user32", "gdi32", NULL
1536 const char **pp, *p;
1537 for (pp = libs; 0 != (p = *pp); ++pp) {
1538 if (0 == *p) {
1539 if (PE_DLL != pe_type && PE_GUI != pe_type)
1540 break;
1541 } else if (tcc_add_library(s1, p) < 0)
1542 error_noabort("cannot find library: %s", p);
1546 if (start_symbol) {
1547 addr = (ADDR3264)tcc_get_symbol_err(s1, start_symbol);
1548 if (s1->output_type == TCC_OUTPUT_MEMORY && addr)
1549 /* for -run GUI's, put '_runwinmain' instead of 'main' */
1550 add_elf_sym(symtab_section,
1551 addr, 0,
1552 ELFW_ST_INFO(STB_GLOBAL, STT_NOTYPE), 0,
1553 text_section->sh_num, "main");
1556 pe->type = pe_type;
1557 pe->start_addr = addr;
1560 PUB_FN int pe_output_file(TCCState * s1, const char *filename)
1562 int ret;
1563 struct pe_info pe;
1564 int i;
1566 memset(&pe, 0, sizeof pe);
1567 pe.filename = filename;
1568 pe.s1 = s1;
1570 pe_add_runtime_ex(s1, &pe);
1571 relocate_common_syms(); /* assign bss adresses */
1572 tcc_add_linker_symbols(s1);
1574 ret = pe_check_symbols(&pe);
1575 if (ret)
1576 return ret;
1578 if (filename) {
1579 if (PE_DLL == pe.type) {
1580 pe.reloc = new_section(pe.s1, ".reloc", SHT_PROGBITS, 0);
1581 pe.imagebase = 0x10000000;
1582 } else {
1583 pe.imagebase = 0x00400000;
1585 pe_assign_addresses(&pe);
1586 relocate_syms(s1, 0);
1587 for (i = 1; i < s1->nb_sections; ++i) {
1588 Section *s = s1->sections[i];
1589 if (s->reloc) {
1590 relocate_section(s1, s);
1591 pe_relocate_rva(&pe, s);
1594 if (s1->nb_errors)
1595 ret = 1;
1596 else
1597 ret = pe_write(&pe);
1598 tcc_free(pe.sec_info);
1599 } else {
1600 #ifndef TCC_IS_NATIVE
1601 error_noabort("-run supported only on native platform");
1602 #endif
1603 pe.type = PE_RUN;
1604 pe.thunk = data_section;
1605 pe_build_imports(&pe);
1608 #ifdef PE_PRINT_SECTIONS
1609 pe_print_sections(s1, "tcc.log");
1610 #endif
1611 return ret;
1614 /* ------------------------------------------------------------- */
1615 #endif /* def TCC_TARGET_PE */
1616 /* ------------------------------------------------------------- */