various fixes and new options for PE format
[tinycc.git] / tccpe.c
blobd53782da362bb068aa0392ffaf4ea97654ec8f71
1 /*
2 * TCCPE.C - PE file output for the Tiny C Compiler
4 * Copyright (c) 2005-2007 grischka
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
21 #ifdef TCC_TARGET_PE
23 #define ST_FN static
24 #define ST_DATA static
25 #define PUB_FN
27 #ifndef _WIN32
28 #define stricmp strcasecmp
29 #define strnicmp strncasecmp
30 #endif
32 #ifndef MAX_PATH
33 #define MAX_PATH 260
34 #endif
36 #define PE_MERGE_DATA
37 // #define PE_PRINT_SECTIONS
39 #ifdef TCC_TARGET_X86_64
40 # define ADDR3264 ULONGLONG
41 #else
42 # define ADDR3264 DWORD
43 #endif
45 #if defined _WIN32 && (defined _WIN64) == (defined TCC_TARGET_X86_64)
46 #define TCC_IS_NATIVE
47 #endif
49 #ifdef _WIN32
50 void dbg_printf (const char *fmt, ...)
52 char buffer[4000];
53 va_list arg;
54 int x;
55 va_start(arg, fmt);
56 x = vsprintf (buffer, fmt, arg);
57 strcpy(buffer+x, "\n");
58 OutputDebugString(buffer);
60 #endif
62 /* ----------------------------------------------------------- */
63 #ifndef IMAGE_NT_SIGNATURE
64 /* ----------------------------------------------------------- */
65 /* definitions below are from winnt.h */
67 typedef unsigned char BYTE;
68 typedef unsigned short WORD;
69 typedef unsigned long DWORD;
70 typedef unsigned long long ULONGLONG;
71 #pragma pack(push, 1)
73 typedef struct _IMAGE_DOS_HEADER { /* DOS .EXE header */
74 WORD e_magic; /* Magic number */
75 WORD e_cblp; /* Bytes on last page of file */
76 WORD e_cp; /* Pages in file */
77 WORD e_crlc; /* Relocations */
78 WORD e_cparhdr; /* Size of header in paragraphs */
79 WORD e_minalloc; /* Minimum extra paragraphs needed */
80 WORD e_maxalloc; /* Maximum extra paragraphs needed */
81 WORD e_ss; /* Initial (relative) SS value */
82 WORD e_sp; /* Initial SP value */
83 WORD e_csum; /* Checksum */
84 WORD e_ip; /* Initial IP value */
85 WORD e_cs; /* Initial (relative) CS value */
86 WORD e_lfarlc; /* File address of relocation table */
87 WORD e_ovno; /* Overlay number */
88 WORD e_res[4]; /* Reserved words */
89 WORD e_oemid; /* OEM identifier (for e_oeminfo) */
90 WORD e_oeminfo; /* OEM information; e_oemid specific */
91 WORD e_res2[10]; /* Reserved words */
92 DWORD e_lfanew; /* File address of new exe header */
93 } IMAGE_DOS_HEADER, *PIMAGE_DOS_HEADER;
95 #define IMAGE_NT_SIGNATURE 0x00004550 /* PE00 */
96 #define SIZE_OF_NT_SIGNATURE 4
98 typedef struct _IMAGE_FILE_HEADER {
99 WORD Machine;
100 WORD NumberOfSections;
101 DWORD TimeDateStamp;
102 DWORD PointerToSymbolTable;
103 DWORD NumberOfSymbols;
104 WORD SizeOfOptionalHeader;
105 WORD Characteristics;
106 } IMAGE_FILE_HEADER, *PIMAGE_FILE_HEADER;
109 #define IMAGE_SIZEOF_FILE_HEADER 20
111 typedef struct _IMAGE_DATA_DIRECTORY {
112 DWORD VirtualAddress;
113 DWORD Size;
114 } IMAGE_DATA_DIRECTORY, *PIMAGE_DATA_DIRECTORY;
117 typedef struct _IMAGE_OPTIONAL_HEADER {
118 /* Standard fields. */
119 WORD Magic;
120 BYTE MajorLinkerVersion;
121 BYTE MinorLinkerVersion;
122 DWORD SizeOfCode;
123 DWORD SizeOfInitializedData;
124 DWORD SizeOfUninitializedData;
125 DWORD AddressOfEntryPoint;
126 DWORD BaseOfCode;
127 #ifndef TCC_TARGET_X86_64
128 DWORD BaseOfData;
129 #endif
130 /* NT additional fields. */
131 ADDR3264 ImageBase;
132 DWORD SectionAlignment;
133 DWORD FileAlignment;
134 WORD MajorOperatingSystemVersion;
135 WORD MinorOperatingSystemVersion;
136 WORD MajorImageVersion;
137 WORD MinorImageVersion;
138 WORD MajorSubsystemVersion;
139 WORD MinorSubsystemVersion;
140 DWORD Win32VersionValue;
141 DWORD SizeOfImage;
142 DWORD SizeOfHeaders;
143 DWORD CheckSum;
144 WORD Subsystem;
145 WORD DllCharacteristics;
146 ADDR3264 SizeOfStackReserve;
147 ADDR3264 SizeOfStackCommit;
148 ADDR3264 SizeOfHeapReserve;
149 ADDR3264 SizeOfHeapCommit;
150 DWORD LoaderFlags;
151 DWORD NumberOfRvaAndSizes;
152 IMAGE_DATA_DIRECTORY DataDirectory[16];
153 } IMAGE_OPTIONAL_HEADER32, IMAGE_OPTIONAL_HEADER64, IMAGE_OPTIONAL_HEADER;
155 #define IMAGE_DIRECTORY_ENTRY_EXPORT 0 /* Export Directory */
156 #define IMAGE_DIRECTORY_ENTRY_IMPORT 1 /* Import Directory */
157 #define IMAGE_DIRECTORY_ENTRY_RESOURCE 2 /* Resource Directory */
158 #define IMAGE_DIRECTORY_ENTRY_EXCEPTION 3 /* Exception Directory */
159 #define IMAGE_DIRECTORY_ENTRY_SECURITY 4 /* Security Directory */
160 #define IMAGE_DIRECTORY_ENTRY_BASERELOC 5 /* Base Relocation Table */
161 #define IMAGE_DIRECTORY_ENTRY_DEBUG 6 /* Debug Directory */
162 /* IMAGE_DIRECTORY_ENTRY_COPYRIGHT 7 (X86 usage) */
163 #define IMAGE_DIRECTORY_ENTRY_ARCHITECTURE 7 /* Architecture Specific Data */
164 #define IMAGE_DIRECTORY_ENTRY_GLOBALPTR 8 /* RVA of GP */
165 #define IMAGE_DIRECTORY_ENTRY_TLS 9 /* TLS Directory */
166 #define IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG 10 /* Load Configuration Directory */
167 #define IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT 11 /* Bound Import Directory in headers */
168 #define IMAGE_DIRECTORY_ENTRY_IAT 12 /* Import Address Table */
169 #define IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT 13 /* Delay Load Import Descriptors */
170 #define IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR 14 /* COM Runtime descriptor */
172 /* Section header format. */
173 #define IMAGE_SIZEOF_SHORT_NAME 8
175 typedef struct _IMAGE_SECTION_HEADER {
176 BYTE Name[IMAGE_SIZEOF_SHORT_NAME];
177 union {
178 DWORD PhysicalAddress;
179 DWORD VirtualSize;
180 } Misc;
181 DWORD VirtualAddress;
182 DWORD SizeOfRawData;
183 DWORD PointerToRawData;
184 DWORD PointerToRelocations;
185 DWORD PointerToLinenumbers;
186 WORD NumberOfRelocations;
187 WORD NumberOfLinenumbers;
188 DWORD Characteristics;
189 } IMAGE_SECTION_HEADER, *PIMAGE_SECTION_HEADER;
191 #define IMAGE_SIZEOF_SECTION_HEADER 40
193 typedef struct _IMAGE_EXPORT_DIRECTORY {
194 DWORD Characteristics;
195 DWORD TimeDateStamp;
196 WORD MajorVersion;
197 WORD MinorVersion;
198 DWORD Name;
199 DWORD Base;
200 DWORD NumberOfFunctions;
201 DWORD NumberOfNames;
202 DWORD AddressOfFunctions;
203 DWORD AddressOfNames;
204 DWORD AddressOfNameOrdinals;
205 } IMAGE_EXPORT_DIRECTORY,*PIMAGE_EXPORT_DIRECTORY;
207 typedef struct _IMAGE_IMPORT_DESCRIPTOR {
208 union {
209 DWORD Characteristics;
210 DWORD OriginalFirstThunk;
212 DWORD TimeDateStamp;
213 DWORD ForwarderChain;
214 DWORD Name;
215 DWORD FirstThunk;
216 } IMAGE_IMPORT_DESCRIPTOR;
218 typedef struct _IMAGE_BASE_RELOCATION {
219 DWORD VirtualAddress;
220 DWORD SizeOfBlock;
221 // WORD TypeOffset[1];
222 } IMAGE_BASE_RELOCATION;
224 #define IMAGE_SIZEOF_BASE_RELOCATION 8
226 #define IMAGE_REL_BASED_ABSOLUTE 0
227 #define IMAGE_REL_BASED_HIGH 1
228 #define IMAGE_REL_BASED_LOW 2
229 #define IMAGE_REL_BASED_HIGHLOW 3
230 #define IMAGE_REL_BASED_HIGHADJ 4
231 #define IMAGE_REL_BASED_MIPS_JMPADDR 5
232 #define IMAGE_REL_BASED_SECTION 6
233 #define IMAGE_REL_BASED_REL32 7
235 #pragma pack(pop)
237 /* ----------------------------------------------------------- */
238 #endif /* ndef IMAGE_NT_SIGNATURE */
239 /* ----------------------------------------------------------- */
240 #pragma pack(push, 1)
242 struct pe_header
244 IMAGE_DOS_HEADER doshdr;
245 BYTE dosstub[0x40];
246 DWORD nt_sig;
247 IMAGE_FILE_HEADER filehdr;
248 #ifdef TCC_TARGET_X86_64
249 IMAGE_OPTIONAL_HEADER64 opthdr;
250 #else
251 #ifdef _WIN64
252 IMAGE_OPTIONAL_HEADER32 opthdr;
253 #else
254 IMAGE_OPTIONAL_HEADER opthdr;
255 #endif
256 #endif
259 struct pe_reloc_header {
260 DWORD offset;
261 DWORD size;
264 struct pe_rsrc_header {
265 struct _IMAGE_FILE_HEADER filehdr;
266 struct _IMAGE_SECTION_HEADER sectionhdr;
269 struct pe_rsrc_reloc {
270 DWORD offset;
271 DWORD size;
272 WORD type;
275 #pragma pack(pop)
277 /* ------------------------------------------------------------- */
278 /* internal temporary structures */
281 #define IMAGE_SCN_CNT_CODE 0x00000020
282 #define IMAGE_SCN_CNT_INITIALIZED_DATA 0x00000040
283 #define IMAGE_SCN_CNT_UNINITIALIZED_DATA 0x00000080
284 #define IMAGE_SCN_MEM_DISCARDABLE 0x02000000
285 #define IMAGE_SCN_MEM_SHARED 0x10000000
286 #define IMAGE_SCN_MEM_EXECUTE 0x20000000
287 #define IMAGE_SCN_MEM_READ 0x40000000
288 #define IMAGE_SCN_MEM_WRITE 0x80000000
291 enum {
292 sec_text = 0,
293 sec_data ,
294 sec_bss ,
295 sec_idata ,
296 sec_other ,
297 sec_rsrc ,
298 sec_stab ,
299 sec_reloc ,
300 sec_last
303 ST_DATA const DWORD pe_sec_flags[] = {
304 0x60000020, /* ".text" , */
305 0xC0000040, /* ".data" , */
306 0xC0000080, /* ".bss" , */
307 0x40000040, /* ".idata" , */
308 0xE0000060, /* < other > , */
309 0x40000040, /* ".rsrc" , */
310 0x42000802, /* ".stab" , */
311 0x42000040, /* ".reloc" , */
314 struct section_info {
315 int cls, ord;
316 char name[32];
317 DWORD sh_addr;
318 DWORD sh_size;
319 DWORD sh_flags;
320 unsigned char *data;
321 DWORD data_size;
322 IMAGE_SECTION_HEADER ish;
325 struct import_symbol {
326 int sym_index;
327 int iat_index;
328 int thk_offset;
331 struct pe_import_info {
332 int dll_index;
333 int sym_count;
334 struct import_symbol **symbols;
337 struct pe_info {
338 TCCState *s1;
339 Section *reloc;
340 Section *thunk;
341 const char *filename;
342 int type;
343 DWORD sizeofheaders;
344 DWORD imagebase;
345 DWORD start_addr;
346 DWORD imp_offs;
347 DWORD imp_size;
348 DWORD iat_offs;
349 DWORD iat_size;
350 DWORD exp_offs;
351 DWORD exp_size;
352 int subsystem;
353 DWORD section_align;
354 DWORD file_align;
355 struct section_info *sec_info;
356 int sec_count;
357 struct pe_import_info **imp_info;
358 int imp_count;
361 #define PE_NUL 0
362 #define PE_DLL 1
363 #define PE_GUI 2
364 #define PE_EXE 3
365 #define PE_RUN 4
367 /* --------------------------------------------*/
369 ST_FN const char* get_alt_symbol(char *buffer, const char *symbol)
371 const char *p;
372 p = strrchr(symbol, '@');
373 if (p && isnum(p[1]) && symbol[0] == '_') { /* stdcall decor */
374 strcpy(buffer, symbol+1)[p-symbol-1] = 0;
375 } else if (symbol[0] != '_') { /* try non-ansi function */
376 buffer[0] = '_', strcpy(buffer + 1, symbol);
377 } else if (0 == memcmp(symbol, "__imp__", 7)) { /* mingw 2.0 */
378 strcpy(buffer, symbol + 6);
379 } else if (0 == memcmp(symbol, "_imp___", 7)) { /* mingw 3.7 */
380 strcpy(buffer, symbol + 6);
381 } else {
382 return symbol;
384 return buffer;
387 ST_FN int pe_find_import(TCCState * s1, const char *symbol)
389 char buffer[200];
390 const char *s;
391 int sym_index, n = 0;
392 do {
393 s = n ? get_alt_symbol(buffer, symbol) : symbol;
394 sym_index = find_elf_sym(s1->dynsymtab_section, s);
395 // printf("find (%d) %d %s\n", n, sym_index, s);
396 } while (0 == sym_index && ++n < 2);
397 return sym_index;
400 /*----------------------------------------------------------------------------*/
402 ST_FN int dynarray_assoc(void **pp, int n, int key)
404 int i;
405 for (i = 0; i < n; ++i, ++pp)
406 if (key == **(int **) pp)
407 return i;
408 return -1;
411 #if 0
412 ST_FN DWORD umin(DWORD a, DWORD b)
414 return a < b ? a : b;
416 #endif
418 ST_FN DWORD umax(DWORD a, DWORD b)
420 return a < b ? b : a;
423 ST_FN DWORD pe_file_align(struct pe_info *pe, DWORD n)
425 return (n + (pe->file_align - 1)) & ~(pe->file_align - 1);
428 ST_FN DWORD pe_virtual_align(struct pe_info *pe, DWORD n)
430 return (n + (pe->section_align - 1)) & ~(pe->section_align - 1);
433 ST_FN void pe_align_section(Section *s, int a)
435 int i = s->data_offset & (a-1);
436 if (i)
437 section_ptr_add(s, a - i);
440 ST_FN void pe_set_datadir(struct pe_header *hdr, int dir, DWORD addr, DWORD size)
442 hdr->opthdr.DataDirectory[dir].VirtualAddress = addr;
443 hdr->opthdr.DataDirectory[dir].Size = size;
446 ST_FN int pe_fwrite(void *data, unsigned len, FILE *fp, DWORD *psum)
448 if (psum) {
449 DWORD sum = *psum;
450 WORD *p = data;
451 int i;
452 for (i = len; i > 0; i -= 2) {
453 sum += (i >= 2) ? *p++ : *(BYTE*)p;
454 sum = (sum + (sum >> 16)) & 0xFFFF;
456 *psum = sum;
458 return len == fwrite(data, 1, len, fp) ? 0 : -1;
461 ST_FN void pe_fpad(FILE *fp, DWORD new_pos)
463 DWORD pos = ftell(fp);
464 while (++pos <= new_pos)
465 fputc(0, fp);
468 /*----------------------------------------------------------------------------*/
469 ST_FN int pe_write(struct pe_info *pe)
471 static const struct pe_header pe_template = {
473 /* IMAGE_DOS_HEADER doshdr */
474 0x5A4D, /*WORD e_magic; Magic number */
475 0x0090, /*WORD e_cblp; Bytes on last page of file */
476 0x0003, /*WORD e_cp; Pages in file */
477 0x0000, /*WORD e_crlc; Relocations */
479 0x0004, /*WORD e_cparhdr; Size of header in paragraphs */
480 0x0000, /*WORD e_minalloc; Minimum extra paragraphs needed */
481 0xFFFF, /*WORD e_maxalloc; Maximum extra paragraphs needed */
482 0x0000, /*WORD e_ss; Initial (relative) SS value */
484 0x00B8, /*WORD e_sp; Initial SP value */
485 0x0000, /*WORD e_csum; Checksum */
486 0x0000, /*WORD e_ip; Initial IP value */
487 0x0000, /*WORD e_cs; Initial (relative) CS value */
488 0x0040, /*WORD e_lfarlc; File address of relocation table */
489 0x0000, /*WORD e_ovno; Overlay number */
490 {0,0,0,0}, /*WORD e_res[4]; Reserved words */
491 0x0000, /*WORD e_oemid; OEM identifier (for e_oeminfo) */
492 0x0000, /*WORD e_oeminfo; OEM information; e_oemid specific */
493 {0,0,0,0,0,0,0,0,0,0}, /*WORD e_res2[10]; Reserved words */
494 0x00000080 /*DWORD e_lfanew; File address of new exe header */
496 /* BYTE dosstub[0x40] */
497 /* 14 code bytes + "This program cannot be run in DOS mode.\r\r\n$" + 6 * 0x00 */
498 0x0e,0x1f,0xba,0x0e,0x00,0xb4,0x09,0xcd,0x21,0xb8,0x01,0x4c,0xcd,0x21,0x54,0x68,
499 0x69,0x73,0x20,0x70,0x72,0x6f,0x67,0x72,0x61,0x6d,0x20,0x63,0x61,0x6e,0x6e,0x6f,
500 0x74,0x20,0x62,0x65,0x20,0x72,0x75,0x6e,0x20,0x69,0x6e,0x20,0x44,0x4f,0x53,0x20,
501 0x6d,0x6f,0x64,0x65,0x2e,0x0d,0x0d,0x0a,0x24,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
503 0x00004550, /* DWORD nt_sig = IMAGE_NT_SIGNATURE */
505 /* IMAGE_FILE_HEADER filehdr */
506 #ifdef TCC_TARGET_X86_64
507 0x8664, /*WORD Machine; */
508 #else
509 0x014C, /*WORD Machine; */
510 #endif
511 0x0003, /*WORD NumberOfSections; */
512 0x00000000, /*DWORD TimeDateStamp; */
513 0x00000000, /*DWORD PointerToSymbolTable; */
514 0x00000000, /*DWORD NumberOfSymbols; */
515 #ifdef TCC_TARGET_X86_64
516 0x00F0, /*WORD SizeOfOptionalHeader; */
517 0x022F /*WORD Characteristics; */
518 #define CHARACTERISTICS_DLL 0x222E
519 #else
520 0x00E0, /*WORD SizeOfOptionalHeader; */
521 0x030F /*WORD Characteristics; */
522 #define CHARACTERISTICS_DLL 0x230E
523 #endif
525 /* IMAGE_OPTIONAL_HEADER opthdr */
526 /* Standard fields. */
527 #ifdef TCC_TARGET_X86_64
528 0x020B, /*WORD Magic; */
529 #else
530 0x010B, /*WORD Magic; */
531 #endif
532 0x06, /*BYTE MajorLinkerVersion; */
533 0x00, /*BYTE MinorLinkerVersion; */
534 0x00000000, /*DWORD SizeOfCode; */
535 0x00000000, /*DWORD SizeOfInitializedData; */
536 0x00000000, /*DWORD SizeOfUninitializedData; */
537 0x00000000, /*DWORD AddressOfEntryPoint; */
538 0x00000000, /*DWORD BaseOfCode; */
539 #ifndef TCC_TARGET_X86_64
540 0x00000000, /*DWORD BaseOfData; */
541 #endif
542 /* NT additional fields. */
543 0x00400000, /*DWORD ImageBase; */
544 0x00001000, /*DWORD SectionAlignment; */
545 0x00000200, /*DWORD FileAlignment; */
546 0x0004, /*WORD MajorOperatingSystemVersion; */
547 0x0000, /*WORD MinorOperatingSystemVersion; */
548 0x0000, /*WORD MajorImageVersion; */
549 0x0000, /*WORD MinorImageVersion; */
550 0x0004, /*WORD MajorSubsystemVersion; */
551 0x0000, /*WORD MinorSubsystemVersion; */
552 0x00000000, /*DWORD Win32VersionValue; */
553 0x00000000, /*DWORD SizeOfImage; */
554 0x00000200, /*DWORD SizeOfHeaders; */
555 0x00000000, /*DWORD CheckSum; */
556 0x0002, /*WORD Subsystem; */
557 0x0000, /*WORD DllCharacteristics; */
558 0x00100000, /*DWORD SizeOfStackReserve; */
559 0x00001000, /*DWORD SizeOfStackCommit; */
560 0x00100000, /*DWORD SizeOfHeapReserve; */
561 0x00001000, /*DWORD SizeOfHeapCommit; */
562 0x00000000, /*DWORD LoaderFlags; */
563 0x00000010, /*DWORD NumberOfRvaAndSizes; */
565 /* IMAGE_DATA_DIRECTORY DataDirectory[16]; */
566 {{0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0},
567 {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}}
570 struct pe_header pe_header = pe_template;
572 int i;
573 FILE *op;
574 DWORD file_offset, sum;
575 struct section_info *si;
576 IMAGE_SECTION_HEADER *psh;
578 op = fopen(pe->filename, "wb");
579 if (NULL == op) {
580 error_noabort("could not write '%s': %s", pe->filename, strerror(errno));
581 return -1;
584 pe->sizeofheaders = pe_file_align(pe,
585 sizeof (struct pe_header)
586 + pe->sec_count * sizeof (IMAGE_SECTION_HEADER)
589 file_offset = pe->sizeofheaders;
591 if (2 == pe->s1->verbose)
592 printf("-------------------------------"
593 "\n virt file size section" "\n");
594 for (i = 0; i < pe->sec_count; ++i) {
595 unsigned long addr, size;
596 const char *sh_name;
598 si = pe->sec_info + i;
599 sh_name = si->name;
600 addr = si->sh_addr - pe->imagebase;
601 size = si->sh_size;
602 psh = &si->ish;
604 if (2 == pe->s1->verbose)
605 printf("%6lx %6lx %6lx %s\n",
606 addr, file_offset, size, sh_name);
608 switch (si->cls) {
609 case sec_text:
610 pe_header.opthdr.BaseOfCode = addr;
611 pe_header.opthdr.AddressOfEntryPoint = addr + pe->start_addr;
612 break;
614 case sec_data:
615 #ifndef TCC_TARGET_X86_64
616 pe_header.opthdr.BaseOfData = addr;
617 #endif
618 break;
620 case sec_bss:
621 break;
623 case sec_reloc:
624 pe_set_datadir(&pe_header, IMAGE_DIRECTORY_ENTRY_BASERELOC, addr, size);
625 break;
627 case sec_rsrc:
628 pe_set_datadir(&pe_header, IMAGE_DIRECTORY_ENTRY_RESOURCE, addr, size);
629 break;
631 case sec_stab:
632 break;
635 if (pe->thunk == pe->s1->sections[si->ord]) {
636 if (pe->imp_size) {
637 pe_set_datadir(&pe_header, IMAGE_DIRECTORY_ENTRY_IMPORT,
638 pe->imp_offs + addr, pe->imp_size);
639 pe_set_datadir(&pe_header, IMAGE_DIRECTORY_ENTRY_IAT,
640 pe->iat_offs + addr, pe->iat_size);
642 if (pe->exp_size) {
643 pe_set_datadir(&pe_header, IMAGE_DIRECTORY_ENTRY_EXPORT,
644 pe->exp_offs + addr, pe->exp_size);
648 strcpy((char*)psh->Name, sh_name);
650 psh->Characteristics = pe_sec_flags[si->cls];
651 psh->VirtualAddress = addr;
652 psh->Misc.VirtualSize = size;
653 pe_header.opthdr.SizeOfImage =
654 umax(pe_virtual_align(pe, size + addr), pe_header.opthdr.SizeOfImage);
656 if (si->data_size) {
657 psh->PointerToRawData = file_offset;
658 file_offset = pe_file_align(pe, file_offset + si->data_size);
659 psh->SizeOfRawData = file_offset - psh->PointerToRawData;
663 //pe_header.filehdr.TimeDateStamp = time(NULL);
664 pe_header.filehdr.NumberOfSections = pe->sec_count;
665 pe_header.opthdr.SizeOfHeaders = pe->sizeofheaders;
666 pe_header.opthdr.ImageBase = pe->imagebase;
667 if (PE_DLL == pe->type)
668 pe_header.filehdr.Characteristics = CHARACTERISTICS_DLL;
669 else if (PE_GUI != pe->type)
670 pe_header.opthdr.Subsystem = 3;
672 sum = 0;
673 pe_fwrite(&pe_header, sizeof pe_header, op, &sum);
674 for (i = 0; i < pe->sec_count; ++i)
675 pe_fwrite(&pe->sec_info[i].ish, sizeof(IMAGE_SECTION_HEADER), op, &sum);
676 pe_fpad(op, pe->sizeofheaders);
677 for (i = 0; i < pe->sec_count; ++i) {
678 si = pe->sec_info + i;
679 psh = &si->ish;
680 if (si->data_size) {
681 pe_fwrite(si->data, si->data_size, op, &sum);
682 file_offset = psh->PointerToRawData + psh->SizeOfRawData;
683 pe_fpad(op, file_offset);
687 pe_header.opthdr.CheckSum = sum + file_offset;
688 fseek(op, offsetof(struct pe_header, opthdr.CheckSum), SEEK_SET);
689 pe_fwrite(&pe_header.opthdr.CheckSum, sizeof pe_header.opthdr.CheckSum, op, NULL);
690 fclose (op);
692 if (2 == pe->s1->verbose)
693 printf("-------------------------------\n");
694 if (pe->s1->verbose)
695 printf("<- %s (%lu bytes)\n", pe->filename, file_offset);
697 return 0;
700 /*----------------------------------------------------------------------------*/
702 #ifdef TCC_TARGET_X86_64
703 #define ELFW_R_(type) ELF64_R_##type
704 #define ElfW_Rel ElfW(Rela)
706 #define REL_TYPE_DIRECT R_X86_64_64
707 #define R_XXX_THUNKFIX R_X86_64_PC32
708 #define R_XXX_RELATIVE R_X86_64_RELATIVE
710 #define ELFW_ST_BIND ELF64_ST_BIND
711 #define ELFW_ST_TYPE ELF64_ST_TYPE
712 #define ELFW_ST_INFO ELF64_ST_INFO
713 #else
714 #define ELFW_R_(type) ELF32_R_##type
715 #define ElfW_Rel ElfW(Rel)
717 #define REL_TYPE_DIRECT R_386_32
718 #define R_XXX_THUNKFIX R_386_32
719 #define R_XXX_RELATIVE R_386_RELATIVE
721 #define ELFW_ST_BIND ELF32_ST_BIND
722 #define ELFW_ST_TYPE ELF32_ST_TYPE
723 #define ELFW_ST_INFO ELF32_ST_INFO
724 #endif
725 /*----------------------------------------------------------------------------*/
727 ST_FN struct import_symbol *pe_add_import(struct pe_info *pe, int sym_index)
729 int i;
730 int dll_index;
731 struct pe_import_info *p;
732 struct import_symbol *s;
734 dll_index = ((ElfW(Sym) *)pe->s1->dynsymtab_section->data + sym_index)->st_value;
735 if (0 == dll_index)
736 return NULL;
738 i = dynarray_assoc ((void**)pe->imp_info, pe->imp_count, dll_index);
739 if (-1 != i) {
740 p = pe->imp_info[i];
741 goto found_dll;
743 p = tcc_mallocz(sizeof *p);
744 p->dll_index = dll_index;
745 dynarray_add((void***)&pe->imp_info, &pe->imp_count, p);
747 found_dll:
748 i = dynarray_assoc ((void**)p->symbols, p->sym_count, sym_index);
749 if (-1 != i)
750 return p->symbols[i];
752 s = tcc_mallocz(sizeof *s);
753 dynarray_add((void***)&p->symbols, &p->sym_count, s);
754 s->sym_index = sym_index;
755 return s;
758 /*----------------------------------------------------------------------------*/
759 ST_FN void pe_build_imports(struct pe_info *pe)
761 int thk_ptr, ent_ptr, dll_ptr, sym_cnt, i;
762 DWORD rva_base = pe->thunk->sh_addr - pe->imagebase;
763 int ndlls = pe->imp_count;
765 for (sym_cnt = i = 0; i < ndlls; ++i)
766 sym_cnt += pe->imp_info[i]->sym_count;
768 if (0 == sym_cnt)
769 return;
771 pe_align_section(pe->thunk, 16);
773 pe->imp_offs = dll_ptr = pe->thunk->data_offset;
774 pe->imp_size = (ndlls + 1) * sizeof(IMAGE_IMPORT_DESCRIPTOR);
775 pe->iat_offs = dll_ptr + pe->imp_size;
776 pe->iat_size = (sym_cnt + ndlls) * sizeof(ADDR3264);
777 section_ptr_add(pe->thunk, pe->imp_size + 2*pe->iat_size);
779 thk_ptr = pe->iat_offs;
780 ent_ptr = pe->iat_offs + pe->iat_size;
782 for (i = 0; i < pe->imp_count; ++i) {
783 IMAGE_IMPORT_DESCRIPTOR *hdr;
784 int k, n;
785 ADDR3264 v;
786 struct pe_import_info *p = pe->imp_info[i];
787 const char *name = pe->s1->loaded_dlls[p->dll_index-1]->name;
789 /* put the dll name into the import header */
790 v = put_elf_str(pe->thunk, name);
792 hdr = (IMAGE_IMPORT_DESCRIPTOR*)(pe->thunk->data + dll_ptr);
793 hdr->FirstThunk = thk_ptr + rva_base;
794 hdr->OriginalFirstThunk = ent_ptr + rva_base;
795 hdr->Name = v + rva_base;
797 for (k = 0, n = p->sym_count; k <= n; ++k) {
798 if (k < n) {
799 int iat_index = p->symbols[k]->iat_index;
800 int sym_index = p->symbols[k]->sym_index;
801 ElfW(Sym) *imp_sym = (ElfW(Sym) *)pe->s1->dynsymtab_section->data + sym_index;
802 ElfW(Sym) *org_sym = (ElfW(Sym) *)symtab_section->data + iat_index;
803 const char *name = pe->s1->dynsymtab_section->link->data + imp_sym->st_name;
805 org_sym->st_value = thk_ptr;
806 org_sym->st_shndx = pe->thunk->sh_num;
807 v = pe->thunk->data_offset + rva_base;
808 section_ptr_add(pe->thunk, sizeof(WORD)); /* hint, not used */
809 put_elf_str(pe->thunk, name);
810 #ifdef TCC_IS_NATIVE
811 if (pe->type == PE_RUN) {
812 DLLReference *dllref = pe->s1->loaded_dlls[imp_sym->st_value-1];
813 if ( !dllref->handle )
814 dllref->handle = LoadLibrary(dllref->name);
815 v = (ADDR3264)GetProcAddress(dllref->handle, name);
816 if (!v)
817 error_noabort("undefined symbol '%s'", name);
819 #endif
820 } else {
821 v = 0; /* last entry is zero */
823 *(ADDR3264*)(pe->thunk->data+thk_ptr) =
824 *(ADDR3264*)(pe->thunk->data+ent_ptr) = v;
825 thk_ptr += sizeof (ADDR3264);
826 ent_ptr += sizeof (ADDR3264);
828 dll_ptr += sizeof(IMAGE_IMPORT_DESCRIPTOR);
829 dynarray_reset(&p->symbols, &p->sym_count);
831 dynarray_reset(&pe->imp_info, &pe->imp_count);
834 /* ------------------------------------------------------------- */
836 For now only functions are exported. Export of data
837 would work, but import requires compiler support to
838 do an additional indirection.
840 For instance:
841 __declspec(dllimport) extern int something;
843 needs to be translated to:
845 *(int*)something
848 struct pe_sort_sym
850 int index;
851 const char *name;
854 ST_FN int sym_cmp(const void *va, const void *vb)
856 const char *ca = (*(struct pe_sort_sym**)va)->name;
857 const char *cb = (*(struct pe_sort_sym**)vb)->name;
858 return strcmp(ca, cb);
861 ST_FN void pe_build_exports(struct pe_info *pe)
863 ElfW(Sym) *sym;
864 int sym_index, sym_end;
865 DWORD rva_base, func_o, name_o, ord_o, str_o;
866 IMAGE_EXPORT_DIRECTORY *hdr;
867 int sym_count, ord;
868 struct pe_sort_sym **sorted, *p;
870 FILE *op;
871 char buf[MAX_PATH];
872 const char *dllname;
873 const char *name;
875 rva_base = pe->thunk->sh_addr - pe->imagebase;
876 sym_count = 0, sorted = NULL, op = NULL;
878 sym_end = symtab_section->data_offset / sizeof(ElfW(Sym));
879 for (sym_index = 1; sym_index < sym_end; ++sym_index) {
880 sym = (ElfW(Sym)*)symtab_section->data + sym_index;
881 name = symtab_section->link->data + sym->st_name;
882 if ((sym->st_other & 1)
883 /* export only symbols from actually written sections */
884 && pe->s1->sections[sym->st_shndx]->sh_addr) {
885 p = tcc_malloc(sizeof *p);
886 p->index = sym_index;
887 p->name = name;
888 dynarray_add((void***)&sorted, &sym_count, p);
890 #if 0
891 if (sym->st_other & 1)
892 printf("export: %s\n", name);
893 if (sym->st_other & 2)
894 printf("stdcall: %s\n", name);
895 #endif
898 if (0 == sym_count)
899 return;
901 qsort (sorted, sym_count, sizeof *sorted, sym_cmp);
903 pe_align_section(pe->thunk, 16);
904 dllname = tcc_basename(pe->filename);
906 pe->exp_offs = pe->thunk->data_offset;
907 func_o = pe->exp_offs + sizeof(IMAGE_EXPORT_DIRECTORY);
908 name_o = func_o + sym_count * sizeof (DWORD);
909 ord_o = name_o + sym_count * sizeof (DWORD);
910 str_o = ord_o + sym_count * sizeof(WORD);
912 hdr = section_ptr_add(pe->thunk, str_o - pe->exp_offs);
913 hdr->Characteristics = 0;
914 hdr->Base = 1;
915 hdr->NumberOfFunctions = sym_count;
916 hdr->NumberOfNames = sym_count;
917 hdr->AddressOfFunctions = func_o + rva_base;
918 hdr->AddressOfNames = name_o + rva_base;
919 hdr->AddressOfNameOrdinals = ord_o + rva_base;
920 hdr->Name = str_o + rva_base;
921 put_elf_str(pe->thunk, dllname);
923 #if 1
924 /* automatically write exports to <output-filename>.def */
925 strcpy(buf, pe->filename);
926 strcpy(tcc_fileextension(buf), ".def");
927 op = fopen(buf, "w");
928 if (NULL == op) {
929 error_noabort("could not create '%s': %s", buf, strerror(errno));
930 } else {
931 fprintf(op, "LIBRARY %s\n\nEXPORTS\n", dllname);
932 if (pe->s1->verbose)
933 printf("<- %s (%d symbols)\n", buf, sym_count);
935 #endif
937 for (ord = 0; ord < sym_count; ++ord)
939 p = sorted[ord], sym_index = p->index, name = p->name;
940 /* insert actual address later in pe_relocate_rva */
941 put_elf_reloc(symtab_section, pe->thunk,
942 func_o, R_XXX_RELATIVE, sym_index);
943 *(DWORD*)(pe->thunk->data + name_o)
944 = pe->thunk->data_offset + rva_base;
945 *(WORD*)(pe->thunk->data + ord_o)
946 = ord;
947 put_elf_str(pe->thunk, name);
948 func_o += sizeof (DWORD);
949 name_o += sizeof (DWORD);
950 ord_o += sizeof (WORD);
951 if (op)
952 fprintf(op, "%s\n", name);
954 pe->exp_size = pe->thunk->data_offset - pe->exp_offs;
955 dynarray_reset(&sorted, &sym_count);
958 /* ------------------------------------------------------------- */
959 ST_FN void pe_build_reloc (struct pe_info *pe)
961 DWORD offset, block_ptr, addr;
962 int count, i;
963 ElfW_Rel *rel, *rel_end;
964 Section *s = NULL, *sr;
966 offset = addr = block_ptr = count = i = 0;
967 rel = rel_end = NULL;
969 for(;;) {
970 if (rel < rel_end) {
971 int type = ELFW_R_(TYPE)(rel->r_info);
972 addr = rel->r_offset + s->sh_addr;
973 ++ rel;
974 if (type != REL_TYPE_DIRECT)
975 continue;
976 if (count == 0) { /* new block */
977 block_ptr = pe->reloc->data_offset;
978 section_ptr_add(pe->reloc, sizeof(struct pe_reloc_header));
979 offset = addr & 0xFFFFFFFF<<12;
981 if ((addr -= offset) < (1<<12)) { /* one block spans 4k addresses */
982 WORD *wp = section_ptr_add(pe->reloc, sizeof (WORD));
983 *wp = addr | IMAGE_REL_BASED_HIGHLOW<<12;
984 ++count;
985 continue;
987 -- rel;
989 } else if (i < pe->sec_count) {
990 sr = (s = pe->s1->sections[pe->sec_info[i++].ord])->reloc;
991 if (sr) {
992 rel = (ElfW_Rel *)sr->data;
993 rel_end = (ElfW_Rel *)(sr->data + sr->data_offset);
995 continue;
998 if (count) {
999 /* store the last block and ready for a new one */
1000 struct pe_reloc_header *hdr;
1001 if (count & 1) /* align for DWORDS */
1002 section_ptr_add(pe->reloc, sizeof(WORD)), ++count;
1003 hdr = (struct pe_reloc_header *)(pe->reloc->data + block_ptr);
1004 hdr -> offset = offset - pe->imagebase;
1005 hdr -> size = count * sizeof(WORD) + sizeof(struct pe_reloc_header);
1006 count = 0;
1009 if (rel >= rel_end)
1010 break;
1014 /* ------------------------------------------------------------- */
1015 ST_FN int pe_section_class(Section *s)
1017 int type, flags;
1018 const char *name;
1020 type = s->sh_type;
1021 flags = s->sh_flags;
1022 name = s->name;
1023 if (flags & SHF_ALLOC) {
1024 if (type == SHT_PROGBITS) {
1025 if (flags & SHF_EXECINSTR)
1026 return sec_text;
1027 if (flags & SHF_WRITE)
1028 return sec_data;
1029 if (0 == strcmp(name, ".rsrc"))
1030 return sec_rsrc;
1031 if (0 == strcmp(name, ".iedat"))
1032 return sec_idata;
1033 return sec_other;
1034 } else if (type == SHT_NOBITS) {
1035 if (flags & SHF_WRITE)
1036 return sec_bss;
1038 } else {
1039 if (0 == strcmp(name, ".reloc"))
1040 return sec_reloc;
1041 if (0 == strncmp(name, ".stab", 5)) /* .stab and .stabstr */
1042 return sec_stab;
1044 return -1;
1047 ST_FN int pe_assign_addresses (struct pe_info *pe)
1049 int i, k, o, c;
1050 DWORD addr;
1051 int *section_order;
1052 struct section_info *si;
1053 Section *s;
1055 // pe->thunk = new_section(pe->s1, ".iedat", SHT_PROGBITS, SHF_ALLOC);
1057 section_order = tcc_malloc(pe->s1->nb_sections * sizeof (int));
1058 for (o = k = 0 ; k < sec_last; ++k) {
1059 for (i = 1; i < pe->s1->nb_sections; ++i) {
1060 s = pe->s1->sections[i];
1061 if (k == pe_section_class(s)) {
1062 // printf("%s %d\n", s->name, k);
1063 s->sh_addr = pe->imagebase;
1064 section_order[o++] = i;
1069 pe->sec_info = tcc_mallocz(o * sizeof (struct section_info));
1070 addr = pe->imagebase + 1;
1072 for (i = 0; i < o; ++i)
1074 k = section_order[i];
1075 s = pe->s1->sections[k];
1076 c = pe_section_class(s);
1077 si = &pe->sec_info[pe->sec_count];
1079 #ifdef PE_MERGE_DATA
1080 if (c == sec_bss && pe->sec_count && si[-1].cls == sec_data) {
1081 /* append .bss to .data */
1082 s->sh_addr = addr = ((addr-1) | 15) + 1;
1083 addr += s->data_offset;
1084 si[-1].sh_size = addr - si[-1].sh_addr;
1085 continue;
1087 #endif
1088 strcpy(si->name, s->name);
1089 si->cls = c;
1090 si->ord = k;
1091 si->sh_addr = s->sh_addr = addr = pe_virtual_align(pe, addr);
1092 si->sh_flags = s->sh_flags;
1094 if (c == sec_data && NULL == pe->thunk)
1095 pe->thunk = s;
1097 if (s == pe->thunk) {
1098 pe_build_imports(pe);
1099 pe_build_exports(pe);
1102 if (c == sec_reloc)
1103 pe_build_reloc (pe);
1105 if (s->data_offset)
1107 if (s->sh_type != SHT_NOBITS) {
1108 si->data = s->data;
1109 si->data_size = s->data_offset;
1112 addr += s->data_offset;
1113 si->sh_size = s->data_offset;
1114 ++pe->sec_count;
1116 // printf("%08x %05x %s\n", si->sh_addr, si->sh_size, si->name);
1119 #if 0
1120 for (i = 1; i < pe->s1->nb_sections; ++i) {
1121 Section *s = pe->s1->sections[i];
1122 int type = s->sh_type;
1123 int flags = s->sh_flags;
1124 printf("section %-16s %-10s %5x %s,%s,%s\n",
1125 s->name,
1126 type == SHT_PROGBITS ? "progbits" :
1127 type == SHT_NOBITS ? "nobits" :
1128 type == SHT_SYMTAB ? "symtab" :
1129 type == SHT_STRTAB ? "strtab" :
1130 type == SHT_RELX ? "rel" : "???",
1131 s->data_offset,
1132 flags & SHF_ALLOC ? "alloc" : "",
1133 flags & SHF_WRITE ? "write" : "",
1134 flags & SHF_EXECINSTR ? "exec" : ""
1137 pe->s1->verbose = 2;
1138 #endif
1140 tcc_free(section_order);
1141 return 0;
1144 /* ------------------------------------------------------------- */
1145 ST_FN void pe_relocate_rva (struct pe_info *pe, Section *s)
1147 Section *sr = s->reloc;
1148 ElfW_Rel *rel, *rel_end;
1149 rel_end = (ElfW_Rel *)(sr->data + sr->data_offset);
1150 for(rel = (ElfW_Rel *)sr->data; rel < rel_end; rel++) {
1151 if (ELFW_R_(TYPE)(rel->r_info) == R_XXX_RELATIVE) {
1152 int sym_index = ELFW_R_(SYM)(rel->r_info);
1153 DWORD addr = s->sh_addr;
1154 if (sym_index) {
1155 ElfW(Sym) *sym = (ElfW(Sym) *)symtab_section->data + sym_index;
1156 addr = sym->st_value;
1158 // printf("reloc rva %08x %08x\n", (DWORD)rel->r_offset, addr);
1159 *(DWORD*)(s->data + rel->r_offset) += addr - pe->imagebase;
1164 /*----------------------------------------------------------------------------*/
1165 ST_FN int pe_check_symbols(struct pe_info *pe)
1167 ElfW(Sym) *sym;
1168 int sym_index, sym_end;
1169 int ret = 0;
1171 pe_align_section(text_section, 8);
1173 sym_end = symtab_section->data_offset / sizeof(ElfW(Sym));
1174 for (sym_index = 1; sym_index < sym_end; ++sym_index) {
1176 sym = (ElfW(Sym) *)symtab_section->data + sym_index;
1177 if (sym->st_shndx == SHN_UNDEF) {
1179 const char *name = symtab_section->link->data + sym->st_name;
1180 unsigned type = ELFW_ST_TYPE(sym->st_info);
1181 int imp_sym = pe_find_import(pe->s1, name);
1182 struct import_symbol *is;
1184 if (0 == imp_sym)
1185 goto not_found;
1186 is = pe_add_import(pe, imp_sym);
1187 if (!is)
1188 goto not_found;
1190 if (type == STT_FUNC) {
1191 unsigned long offset = is->thk_offset;
1192 if (offset) {
1193 /* got aliased symbol, like stricmp and _stricmp */
1195 } else {
1196 char buffer[100];
1197 WORD *p;
1199 offset = text_section->data_offset;
1200 /* add the 'jmp IAT[x]' instruction */
1201 p = section_ptr_add(text_section, 8);
1202 *p = 0x25FF;
1203 #ifdef TCC_TARGET_X86_64
1204 *(DWORD*)(p+1) = (DWORD)-4;
1205 #endif
1206 /* add a helper symbol, will be patched later in
1207 pe_build_imports */
1208 sprintf(buffer, "IAT.%s", name);
1209 is->iat_index = put_elf_sym(
1210 symtab_section, 0, sizeof(DWORD),
1211 ELFW_ST_INFO(STB_GLOBAL, STT_OBJECT),
1212 0, SHN_UNDEF, buffer);
1213 put_elf_reloc(symtab_section, text_section,
1214 offset + 2, R_XXX_THUNKFIX, is->iat_index);
1215 is->thk_offset = offset;
1218 /* tcc_realloc might have altered sym's address */
1219 sym = (ElfW(Sym) *)symtab_section->data + sym_index;
1221 /* patch the original symbol */
1222 sym->st_value = offset;
1223 sym->st_shndx = text_section->sh_num;
1224 sym->st_other &= ~1; /* do not export */
1225 continue;
1228 if (type == STT_OBJECT) { /* data, ptr to that should be */
1229 if (0 == is->iat_index) {
1230 /* original symbol will be patched later in pe_build_imports */
1231 is->iat_index = sym_index;
1232 continue;
1236 not_found:
1237 error_noabort("undefined symbol '%s'", name);
1238 ret = -1;
1240 } else if (pe->s1->rdynamic
1241 && ELFW_ST_BIND(sym->st_info) != STB_LOCAL) {
1242 /* if -rdynamic option, then export all non local symbols */
1243 sym->st_other |= 1;
1246 return ret;
1249 /*----------------------------------------------------------------------------*/
1250 #ifdef PE_PRINT_SECTIONS
1251 ST_FN void pe_print_section(FILE * f, Section * s)
1253 /* just if you'r curious */
1254 BYTE *p, *e, b;
1255 int i, n, l, m;
1256 p = s->data;
1257 e = s->data + s->data_offset;
1258 l = e - p;
1260 fprintf(f, "section \"%s\"", s->name);
1261 if (s->link)
1262 fprintf(f, "\nlink \"%s\"", s->link->name);
1263 if (s->reloc)
1264 fprintf(f, "\nreloc \"%s\"", s->reloc->name);
1265 fprintf(f, "\nv_addr %08X", (unsigned)s->sh_addr);
1266 fprintf(f, "\ncontents %08X", (unsigned)l);
1267 fprintf(f, "\n\n");
1269 if (s->sh_type == SHT_NOBITS)
1270 return;
1272 if (0 == l)
1273 return;
1275 if (s->sh_type == SHT_SYMTAB)
1276 m = sizeof(ElfW(Sym));
1277 else if (s->sh_type == SHT_RELX)
1278 m = sizeof(ElfW_Rel);
1279 else
1280 m = 16;
1282 fprintf(f, "%-8s", "offset");
1283 for (i = 0; i < m; ++i)
1284 fprintf(f, " %02x", i);
1285 n = 56;
1287 if (s->sh_type == SHT_SYMTAB || s->sh_type == SHT_RELX) {
1288 const char *fields1[] = {
1289 "name",
1290 "value",
1291 "size",
1292 "bind",
1293 "type",
1294 "other",
1295 "shndx",
1296 NULL
1299 const char *fields2[] = {
1300 "offs",
1301 "type",
1302 "symb",
1303 NULL
1306 const char **p;
1308 if (s->sh_type == SHT_SYMTAB)
1309 p = fields1, n = 106;
1310 else
1311 p = fields2, n = 58;
1313 for (i = 0; p[i]; ++i)
1314 fprintf(f, "%6s", p[i]);
1315 fprintf(f, " symbol");
1318 fprintf(f, "\n");
1319 for (i = 0; i < n; ++i)
1320 fprintf(f, "-");
1321 fprintf(f, "\n");
1323 for (i = 0; i < l;)
1325 fprintf(f, "%08X", i);
1326 for (n = 0; n < m; ++n) {
1327 if (n + i < l)
1328 fprintf(f, " %02X", p[i + n]);
1329 else
1330 fprintf(f, " ");
1333 if (s->sh_type == SHT_SYMTAB) {
1334 ElfW(Sym) *sym = (ElfW(Sym) *) (p + i);
1335 const char *name = s->link->data + sym->st_name;
1336 fprintf(f, " %04X %04X %04X %02X %02X %02X %04X \"%s\"",
1337 (unsigned)sym->st_name,
1338 (unsigned)sym->st_value,
1339 (unsigned)sym->st_size,
1340 (unsigned)ELFW_ST_BIND(sym->st_info),
1341 (unsigned)ELFW_ST_TYPE(sym->st_info),
1342 (unsigned)sym->st_other,
1343 (unsigned)sym->st_shndx,
1344 name);
1346 } else if (s->sh_type == SHT_RELX) {
1347 ElfW_Rel *rel = (ElfW_Rel *) (p + i);
1348 ElfW(Sym) *sym =
1349 (ElfW(Sym) *) s->link->data + ELFW_R_(SYM)(rel->r_info);
1350 const char *name = s->link->link->data + sym->st_name;
1351 fprintf(f, " %04X %02X %04X \"%s\"",
1352 (unsigned)rel->r_offset,
1353 (unsigned)ELFW_R_(TYPE)(rel->r_info),
1354 (unsigned)ELFW_R_(SYM)(rel->r_info),
1355 name);
1356 } else {
1357 fprintf(f, " ");
1358 for (n = 0; n < m; ++n) {
1359 if (n + i < l) {
1360 b = p[i + n];
1361 if (b < 32 || b >= 127)
1362 b = '.';
1363 fprintf(f, "%c", b);
1367 i += m;
1368 fprintf(f, "\n");
1370 fprintf(f, "\n\n");
1373 ST_FN void pe_print_sections(TCCState *s1, const char *fname)
1375 Section *s;
1376 FILE *f;
1377 int i;
1378 f = fopen(fname, "w");
1379 for (i = 1; i < s1->nb_sections; ++i) {
1380 s = s1->sections[i];
1381 pe_print_section(f, s);
1383 pe_print_section(f, s1->dynsymtab_section);
1384 fclose(f);
1386 #endif
1388 /* ------------------------------------------------------------- */
1390 ST_FN int read_mem(FILE *fp, unsigned offset, void *buffer, unsigned len)
1392 fseek(fp, offset, 0);
1393 return len == fread(buffer, 1, len, fp);
1396 /* -------------------------------------------------------------
1397 * This is for compiled windows resources in 'coff' format
1398 * as generated by 'windres.exe -O coff ...'.
1401 ST_FN int pe_load_res(TCCState *s1, FILE *fp)
1403 struct pe_rsrc_header hdr;
1404 Section *rsrc_section;
1405 int i, ret = -1;
1406 BYTE *ptr;
1407 unsigned offs;
1409 if (!read_mem(fp, 0, &hdr, sizeof hdr))
1410 goto quit;
1412 if (hdr.filehdr.Machine != 0x014C
1413 || hdr.filehdr.NumberOfSections != 1
1414 || strcmp(hdr.sectionhdr.Name, ".rsrc") != 0)
1415 goto quit;
1417 rsrc_section = new_section(s1, ".rsrc", SHT_PROGBITS, SHF_ALLOC);
1418 ptr = section_ptr_add(rsrc_section, hdr.sectionhdr.SizeOfRawData);
1419 offs = hdr.sectionhdr.PointerToRawData;
1420 if (!read_mem(fp, offs, ptr, hdr.sectionhdr.SizeOfRawData))
1421 goto quit;
1422 offs = hdr.sectionhdr.PointerToRelocations;
1423 for (i = 0; i < hdr.sectionhdr.NumberOfRelocations; ++i)
1425 struct pe_rsrc_reloc rel;
1426 if (!read_mem(fp, offs, &rel, sizeof rel))
1427 goto quit;
1428 // printf("rsrc_reloc: %x %x %x\n", rel.offset, rel.size, rel.type);
1429 if (rel.type != 7) /* DIR32NB */
1430 goto quit;
1431 put_elf_reloc(symtab_section, rsrc_section,
1432 rel.offset, R_XXX_RELATIVE, 0);
1433 offs += sizeof rel;
1435 ret = 0;
1436 quit:
1437 return ret;
1440 /* ------------------------------------------------------------- */
1441 ST_FN char *trimfront(char *p)
1443 while (*p && (unsigned char)*p <= ' ')
1444 ++p;
1445 return p;
1448 ST_FN char *trimback(char *a, char *e)
1450 while (e > a && (unsigned char)e[-1] <= ' ')
1451 --e;
1452 *e = 0;;
1453 return a;
1456 ST_FN char *get_line(char *line, int size, FILE *fp)
1458 if (NULL == fgets(line, size, fp))
1459 return NULL;
1460 trimback(line, strchr(line, 0));
1461 return trimfront(line);
1464 /* ------------------------------------------------------------- */
1465 ST_FN int pe_load_def(TCCState *s1, FILE *fp)
1467 DLLReference *dllref;
1468 int state = 0, ret = -1;
1469 char line[400], dllname[80], *p;
1471 for (;;) {
1472 p = get_line(line, sizeof line, fp);
1473 if (NULL == p)
1474 break;
1475 if (0 == *p || ';' == *p)
1476 continue;
1477 switch (state) {
1478 case 0:
1479 if (0 != strnicmp(p, "LIBRARY", 7))
1480 goto quit;
1481 strcpy(dllname, trimfront(p+7));
1482 ++state;
1483 continue;
1485 case 1:
1486 if (0 != stricmp(p, "EXPORTS"))
1487 goto quit;
1488 ++state;
1489 continue;
1491 case 2:
1492 dllref = tcc_mallocz(sizeof(DLLReference) + strlen(dllname));
1493 strcpy(dllref->name, dllname);
1494 dynarray_add((void ***) &s1->loaded_dlls, &s1->nb_loaded_dlls, dllref);
1495 ++state;
1497 default:
1498 add_elf_sym(s1->dynsymtab_section,
1499 s1->nb_loaded_dlls, 0,
1500 ELFW_ST_INFO(STB_GLOBAL, STT_FUNC), 0,
1501 text_section->sh_num, p);
1502 continue;
1505 ret = 0;
1506 quit:
1507 return ret;
1510 /* ------------------------------------------------------------- */
1511 #define TINY_IMPDEF_GET_EXPORT_NAMES_ONLY
1512 #include "win32/tools/tiny_impdef.c"
1514 ST_FN int pe_load_dll(TCCState *s1, const char *dllname, FILE *fp)
1516 int i = 0;
1517 char *p, *q;
1518 p = get_export_names(fp);
1519 if (p) {
1520 DLLReference *dllref;
1521 dllref = tcc_mallocz(sizeof(DLLReference) + strlen(dllname));
1522 strcpy(dllref->name, dllname);
1523 dynarray_add((void ***) &s1->loaded_dlls, &s1->nb_loaded_dlls, dllref);
1524 for (q = p, i = 0; *q; ++i) {
1525 add_elf_sym(s1->dynsymtab_section,
1526 s1->nb_loaded_dlls, 0,
1527 ELFW_ST_INFO(STB_GLOBAL, STT_FUNC), 0,
1528 text_section->sh_num, q);
1529 q += 1 + strlen(q);
1531 tcc_free(p);
1533 return i ? 0 : -1;
1536 /* ------------------------------------------------------------- */
1537 PUB_FN int pe_load_file(struct TCCState *s1, const char *filename, int fd)
1539 FILE *fp = fdopen(dup(fd), "rb");
1540 int ret = -1;
1541 char buf[10];
1542 if (fp) {
1543 if (0 == strcmp(tcc_fileextension(filename), ".def"))
1544 ret = pe_load_def(s1, fp);
1545 else if (pe_load_res(s1, fp) == 0)
1546 ret = 0;
1547 else if (read_mem(fp, 0, buf, sizeof buf) && 0 == strncmp(buf, "MZ", 2))
1548 ret = pe_load_dll(s1, tcc_basename(filename), fp);
1549 fclose(fp);
1551 return ret;
1554 int pe_add_dll(struct TCCState *s, const char *libraryname)
1556 char buf[MAX_PATH];
1557 snprintf(buf, sizeof(buf), "%s.def", libraryname);
1558 if (tcc_add_dll(s, buf, 0) == 0)
1559 return 0;
1560 snprintf(buf, sizeof(buf), "%s.dll", libraryname);
1561 if (tcc_add_dll(s, buf, 0) == 0)
1562 return 0;
1563 return -1;
1566 /* ------------------------------------------------------------- */
1567 #ifdef TCC_TARGET_X86_64
1568 #define PE_STDSYM(n,s) n
1569 #else
1570 #define PE_STDSYM(n,s) "_" n s
1571 #endif
1573 ST_FN void pe_add_runtime_ex(TCCState *s1, struct pe_info *pe)
1575 const char *start_symbol;
1576 unsigned long addr = 0;
1577 int pe_type = 0;
1579 if (find_elf_sym(symtab_section, PE_STDSYM("WinMain","@16")))
1580 pe_type = PE_GUI;
1581 else
1582 if (TCC_OUTPUT_DLL == s1->output_type) {
1583 pe_type = PE_DLL;
1584 /* need this for 'tccelf.c:relocate_section()' */
1585 s1->output_type = TCC_OUTPUT_EXE;
1588 start_symbol =
1589 TCC_OUTPUT_MEMORY == s1->output_type
1590 ? PE_GUI == pe_type ? "_runwinmain" : NULL
1591 : PE_DLL == pe_type ? PE_STDSYM("_dllstart","@12")
1592 : PE_GUI == pe_type ? "_winstart" : "_start"
1595 /* grab the startup code from libtcc1 */
1596 if (start_symbol)
1597 add_elf_sym(symtab_section,
1598 0, 0,
1599 ELFW_ST_INFO(STB_GLOBAL, STT_NOTYPE), 0,
1600 SHN_UNDEF, start_symbol);
1602 if (0 == s1->nostdlib) {
1603 static const char *libs[] = {
1604 "tcc1", "msvcrt", "kernel32", "", "user32", "gdi32", NULL
1606 const char **pp, *p;
1607 for (pp = libs; 0 != (p = *pp); ++pp) {
1608 if (0 == *p) {
1609 if (PE_DLL != pe_type && PE_GUI != pe_type)
1610 break;
1611 } else if (tcc_add_library(s1, p) < 0)
1612 error_noabort("cannot find library: %s", p);
1616 if (start_symbol) {
1617 addr = (uplong)tcc_get_symbol_err(s1, start_symbol);
1618 if (s1->output_type == TCC_OUTPUT_MEMORY && addr)
1619 /* for -run GUI's, put '_runwinmain' instead of 'main' */
1620 add_elf_sym(symtab_section,
1621 addr, 0,
1622 ELFW_ST_INFO(STB_GLOBAL, STT_NOTYPE), 0,
1623 text_section->sh_num, "main");
1626 pe->type = pe_type;
1627 pe->start_addr = addr;
1630 PUB_FN int pe_output_file(TCCState * s1, const char *filename)
1632 int ret;
1633 struct pe_info pe;
1634 int i;
1636 memset(&pe, 0, sizeof pe);
1637 pe.filename = filename;
1638 pe.s1 = s1;
1640 pe_add_runtime_ex(s1, &pe);
1641 relocate_common_syms(); /* assign bss adresses */
1642 tcc_add_linker_symbols(s1);
1644 ret = pe_check_symbols(&pe);
1645 if (ret)
1646 return ret;
1648 if (filename) {
1649 if (PE_DLL == pe.type) {
1650 pe.reloc = new_section(pe.s1, ".reloc", SHT_PROGBITS, 0);
1651 pe.imagebase = 0x10000000;
1652 } else {
1653 pe.imagebase = 0x00400000;
1656 /* if no subsystem specified, we use "console" subsystem by default */
1657 if (s1->pe_subsystem != 0)
1658 pe.subsystem = s1->pe_subsystem;
1659 else
1660 pe.subsystem = 3;
1662 /* set default file/section alignment */
1663 if (pe.subsystem == 1) {
1664 pe.section_align = 0x20;
1665 pe.file_align = 0x20;
1666 } else {
1667 pe.section_align = 0x1000;
1668 pe.file_align = 0x200;
1671 if (s1->section_align != 0)
1672 pe.section_align = s1->section_align;
1673 if (s1->pe_file_align != 0)
1674 pe.file_align = s1->pe_file_align;
1676 if ((pe.subsystem >= 10) && (pe.subsystem <= 12))
1677 pe.imagebase = 0;
1679 if (s1->has_text_addr)
1680 pe.imagebase = s1->text_addr;
1682 pe_assign_addresses(&pe);
1683 relocate_syms(s1, 0);
1684 for (i = 1; i < s1->nb_sections; ++i) {
1685 Section *s = s1->sections[i];
1686 if (s->reloc) {
1687 relocate_section(s1, s);
1688 pe_relocate_rva(&pe, s);
1691 if (s1->nb_errors)
1692 ret = -1;
1693 else
1694 ret = pe_write(&pe);
1695 tcc_free(pe.sec_info);
1696 } else {
1697 #ifndef TCC_IS_NATIVE
1698 error_noabort("-run supported only on native platform");
1699 #endif
1700 pe.type = PE_RUN;
1701 pe.thunk = data_section;
1702 pe_build_imports(&pe);
1705 #ifdef PE_PRINT_SECTIONS
1706 pe_print_sections(s1, "tcc.log");
1707 #endif
1708 return ret;
1711 /* ------------------------------------------------------------- */
1712 #endif /* def TCC_TARGET_PE */
1713 /* ------------------------------------------------------------- */