x86-64: change the type of size_t and ptrdiff_t.
[tinycc/kirr.git] / tccpe.c
blobd16df507a85e432dc6f23e6bc0426bd59f7b5be8
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 struct section_info *sec_info;
353 int sec_count;
354 struct pe_import_info **imp_info;
355 int imp_count;
358 #define PE_NUL 0
359 #define PE_DLL 1
360 #define PE_GUI 2
361 #define PE_EXE 3
362 #define PE_RUN 4
364 /* --------------------------------------------*/
366 ST_FN const char* get_alt_symbol(char *buffer, const char *symbol)
368 const char *p;
369 p = strrchr(symbol, '@');
370 if (p && isnum(p[1]) && symbol[0] == '_') { /* stdcall decor */
371 strcpy(buffer, symbol+1)[p-symbol-1] = 0;
372 } else if (symbol[0] != '_') { /* try non-ansi function */
373 buffer[0] = '_', strcpy(buffer + 1, symbol);
374 } else if (0 == memcmp(symbol, "__imp__", 7)) { /* mingw 2.0 */
375 strcpy(buffer, symbol + 6);
376 } else if (0 == memcmp(symbol, "_imp___", 7)) { /* mingw 3.7 */
377 strcpy(buffer, symbol + 6);
378 } else {
379 return symbol;
381 return buffer;
384 ST_FN int pe_find_import(TCCState * s1, const char *symbol)
386 char buffer[200];
387 const char *s;
388 int sym_index, n = 0;
389 do {
390 s = n ? get_alt_symbol(buffer, symbol) : symbol;
391 sym_index = find_elf_sym(s1->dynsymtab_section, s);
392 // printf("find (%d) %d %s\n", n, sym_index, s);
393 } while (0 == sym_index && ++n < 2);
394 return sym_index;
397 /*----------------------------------------------------------------------------*/
399 ST_FN int dynarray_assoc(void **pp, int n, int key)
401 int i;
402 for (i = 0; i < n; ++i, ++pp)
403 if (key == **(int **) pp)
404 return i;
405 return -1;
408 #if 0
409 ST_FN DWORD umin(DWORD a, DWORD b)
411 return a < b ? a : b;
413 #endif
415 ST_FN DWORD umax(DWORD a, DWORD b)
417 return a < b ? b : a;
420 ST_FN DWORD pe_file_align(DWORD n)
422 return (n + (0x200 - 1)) & ~(0x200 - 1);
425 ST_FN DWORD pe_virtual_align(DWORD n)
427 return (n + (0x1000 - 1)) & ~(0x1000 - 1);
430 ST_FN void pe_align_section(Section *s, int a)
432 int i = s->data_offset & (a-1);
433 if (i)
434 section_ptr_add(s, a - i);
437 ST_FN void pe_set_datadir(struct pe_header *hdr, int dir, DWORD addr, DWORD size)
439 hdr->opthdr.DataDirectory[dir].VirtualAddress = addr;
440 hdr->opthdr.DataDirectory[dir].Size = size;
443 ST_FN int pe_fwrite(void *data, unsigned len, FILE *fp, DWORD *psum)
445 if (psum) {
446 DWORD sum = *psum;
447 WORD *p = data;
448 int i;
449 for (i = len; i > 0; i -= 2) {
450 sum += (i >= 2) ? *p++ : *(BYTE*)p;
451 sum = (sum + (sum >> 16)) & 0xFFFF;
453 *psum = sum;
455 return len == fwrite(data, 1, len, fp) ? 0 : -1;
458 ST_FN void pe_fpad(FILE *fp, DWORD new_pos)
460 DWORD pos = ftell(fp);
461 while (++pos <= new_pos)
462 fputc(0, fp);
465 /*----------------------------------------------------------------------------*/
466 ST_FN int pe_write(struct pe_info *pe)
468 static const struct pe_header pe_template = {
470 /* IMAGE_DOS_HEADER doshdr */
471 0x5A4D, /*WORD e_magic; Magic number */
472 0x0090, /*WORD e_cblp; Bytes on last page of file */
473 0x0003, /*WORD e_cp; Pages in file */
474 0x0000, /*WORD e_crlc; Relocations */
476 0x0004, /*WORD e_cparhdr; Size of header in paragraphs */
477 0x0000, /*WORD e_minalloc; Minimum extra paragraphs needed */
478 0xFFFF, /*WORD e_maxalloc; Maximum extra paragraphs needed */
479 0x0000, /*WORD e_ss; Initial (relative) SS value */
481 0x00B8, /*WORD e_sp; Initial SP value */
482 0x0000, /*WORD e_csum; Checksum */
483 0x0000, /*WORD e_ip; Initial IP value */
484 0x0000, /*WORD e_cs; Initial (relative) CS value */
485 0x0040, /*WORD e_lfarlc; File address of relocation table */
486 0x0000, /*WORD e_ovno; Overlay number */
487 {0,0,0,0}, /*WORD e_res[4]; Reserved words */
488 0x0000, /*WORD e_oemid; OEM identifier (for e_oeminfo) */
489 0x0000, /*WORD e_oeminfo; OEM information; e_oemid specific */
490 {0,0,0,0,0,0,0,0,0,0}, /*WORD e_res2[10]; Reserved words */
491 0x00000080 /*DWORD e_lfanew; File address of new exe header */
493 /* BYTE dosstub[0x40] */
494 /* 14 code bytes + "This program cannot be run in DOS mode.\r\r\n$" + 6 * 0x00 */
495 0x0e,0x1f,0xba,0x0e,0x00,0xb4,0x09,0xcd,0x21,0xb8,0x01,0x4c,0xcd,0x21,0x54,0x68,
496 0x69,0x73,0x20,0x70,0x72,0x6f,0x67,0x72,0x61,0x6d,0x20,0x63,0x61,0x6e,0x6e,0x6f,
497 0x74,0x20,0x62,0x65,0x20,0x72,0x75,0x6e,0x20,0x69,0x6e,0x20,0x44,0x4f,0x53,0x20,
498 0x6d,0x6f,0x64,0x65,0x2e,0x0d,0x0d,0x0a,0x24,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
500 0x00004550, /* DWORD nt_sig = IMAGE_NT_SIGNATURE */
502 /* IMAGE_FILE_HEADER filehdr */
503 #ifdef TCC_TARGET_X86_64
504 0x8664, /*WORD Machine; */
505 #else
506 0x014C, /*WORD Machine; */
507 #endif
508 0x0003, /*WORD NumberOfSections; */
509 0x00000000, /*DWORD TimeDateStamp; */
510 0x00000000, /*DWORD PointerToSymbolTable; */
511 0x00000000, /*DWORD NumberOfSymbols; */
512 #ifdef TCC_TARGET_X86_64
513 0x00F0, /*WORD SizeOfOptionalHeader; */
514 0x022F /*WORD Characteristics; */
515 #define CHARACTERISTICS_DLL 0x222E
516 #else
517 0x00E0, /*WORD SizeOfOptionalHeader; */
518 0x030F /*WORD Characteristics; */
519 #define CHARACTERISTICS_DLL 0x230E
520 #endif
522 /* IMAGE_OPTIONAL_HEADER opthdr */
523 /* Standard fields. */
524 #ifdef TCC_TARGET_X86_64
525 0x020B, /*WORD Magic; */
526 #else
527 0x010B, /*WORD Magic; */
528 #endif
529 0x06, /*BYTE MajorLinkerVersion; */
530 0x00, /*BYTE MinorLinkerVersion; */
531 0x00000000, /*DWORD SizeOfCode; */
532 0x00000000, /*DWORD SizeOfInitializedData; */
533 0x00000000, /*DWORD SizeOfUninitializedData; */
534 0x00000000, /*DWORD AddressOfEntryPoint; */
535 0x00000000, /*DWORD BaseOfCode; */
536 #ifndef TCC_TARGET_X86_64
537 0x00000000, /*DWORD BaseOfData; */
538 #endif
539 /* NT additional fields. */
540 0x00400000, /*DWORD ImageBase; */
541 0x00001000, /*DWORD SectionAlignment; */
542 0x00000200, /*DWORD FileAlignment; */
543 0x0004, /*WORD MajorOperatingSystemVersion; */
544 0x0000, /*WORD MinorOperatingSystemVersion; */
545 0x0000, /*WORD MajorImageVersion; */
546 0x0000, /*WORD MinorImageVersion; */
547 0x0004, /*WORD MajorSubsystemVersion; */
548 0x0000, /*WORD MinorSubsystemVersion; */
549 0x00000000, /*DWORD Win32VersionValue; */
550 0x00000000, /*DWORD SizeOfImage; */
551 0x00000200, /*DWORD SizeOfHeaders; */
552 0x00000000, /*DWORD CheckSum; */
553 0x0002, /*WORD Subsystem; */
554 0x0000, /*WORD DllCharacteristics; */
555 0x00100000, /*DWORD SizeOfStackReserve; */
556 0x00001000, /*DWORD SizeOfStackCommit; */
557 0x00100000, /*DWORD SizeOfHeapReserve; */
558 0x00001000, /*DWORD SizeOfHeapCommit; */
559 0x00000000, /*DWORD LoaderFlags; */
560 0x00000010, /*DWORD NumberOfRvaAndSizes; */
562 /* IMAGE_DATA_DIRECTORY DataDirectory[16]; */
563 {{0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0},
564 {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}}
567 struct pe_header pe_header = pe_template;
569 int i;
570 FILE *op;
571 DWORD file_offset, sum;
572 struct section_info *si;
573 IMAGE_SECTION_HEADER *psh;
575 op = fopen(pe->filename, "wb");
576 if (NULL == op) {
577 error_noabort("could not write '%s': %s", pe->filename, strerror(errno));
578 return -1;
581 pe->sizeofheaders = pe_file_align(
582 sizeof (struct pe_header)
583 + pe->sec_count * sizeof (IMAGE_SECTION_HEADER)
586 file_offset = pe->sizeofheaders;
588 if (2 == pe->s1->verbose)
589 printf("-------------------------------"
590 "\n virt file size section" "\n");
591 for (i = 0; i < pe->sec_count; ++i) {
592 unsigned long addr, size;
593 const char *sh_name;
595 si = pe->sec_info + i;
596 sh_name = si->name;
597 addr = si->sh_addr - pe->imagebase;
598 size = si->sh_size;
599 psh = &si->ish;
601 if (2 == pe->s1->verbose)
602 printf("%6lx %6lx %6lx %s\n",
603 addr, file_offset, size, sh_name);
605 switch (si->cls) {
606 case sec_text:
607 pe_header.opthdr.BaseOfCode = addr;
608 pe_header.opthdr.AddressOfEntryPoint = addr + pe->start_addr;
609 break;
611 case sec_data:
612 #ifndef TCC_TARGET_X86_64
613 pe_header.opthdr.BaseOfData = addr;
614 #endif
615 break;
617 case sec_bss:
618 break;
620 case sec_reloc:
621 pe_set_datadir(&pe_header, IMAGE_DIRECTORY_ENTRY_BASERELOC, addr, size);
622 break;
624 case sec_rsrc:
625 pe_set_datadir(&pe_header, IMAGE_DIRECTORY_ENTRY_RESOURCE, addr, size);
626 break;
628 case sec_stab:
629 break;
632 if (pe->thunk == pe->s1->sections[si->ord]) {
633 if (pe->imp_size) {
634 pe_set_datadir(&pe_header, IMAGE_DIRECTORY_ENTRY_IMPORT,
635 pe->imp_offs + addr, pe->imp_size);
636 pe_set_datadir(&pe_header, IMAGE_DIRECTORY_ENTRY_IAT,
637 pe->iat_offs + addr, pe->iat_size);
639 if (pe->exp_size) {
640 pe_set_datadir(&pe_header, IMAGE_DIRECTORY_ENTRY_EXPORT,
641 pe->exp_offs + addr, pe->exp_size);
645 strcpy((char*)psh->Name, sh_name);
647 psh->Characteristics = pe_sec_flags[si->cls];
648 psh->VirtualAddress = addr;
649 psh->Misc.VirtualSize = size;
650 pe_header.opthdr.SizeOfImage =
651 umax(pe_virtual_align(size + addr), pe_header.opthdr.SizeOfImage);
653 if (si->data_size) {
654 psh->PointerToRawData = file_offset;
655 file_offset = pe_file_align(file_offset + si->data_size);
656 psh->SizeOfRawData = file_offset - psh->PointerToRawData;
660 //pe_header.filehdr.TimeDateStamp = time(NULL);
661 pe_header.filehdr.NumberOfSections = pe->sec_count;
662 pe_header.opthdr.SizeOfHeaders = pe->sizeofheaders;
663 pe_header.opthdr.ImageBase = pe->imagebase;
664 if (PE_DLL == pe->type)
665 pe_header.filehdr.Characteristics = CHARACTERISTICS_DLL;
666 else if (PE_GUI != pe->type)
667 pe_header.opthdr.Subsystem = 3;
669 sum = 0;
670 pe_fwrite(&pe_header, sizeof pe_header, op, &sum);
671 for (i = 0; i < pe->sec_count; ++i)
672 pe_fwrite(&pe->sec_info[i].ish, sizeof(IMAGE_SECTION_HEADER), op, &sum);
673 pe_fpad(op, pe->sizeofheaders);
674 for (i = 0; i < pe->sec_count; ++i) {
675 si = pe->sec_info + i;
676 psh = &si->ish;
677 if (si->data_size) {
678 pe_fwrite(si->data, si->data_size, op, &sum);
679 file_offset = psh->PointerToRawData + psh->SizeOfRawData;
680 pe_fpad(op, file_offset);
684 pe_header.opthdr.CheckSum = sum + file_offset;
685 fseek(op, offsetof(struct pe_header, opthdr.CheckSum), SEEK_SET);
686 pe_fwrite(&pe_header.opthdr.CheckSum, sizeof pe_header.opthdr.CheckSum, op, NULL);
687 fclose (op);
689 if (2 == pe->s1->verbose)
690 printf("-------------------------------\n");
691 if (pe->s1->verbose)
692 printf("<- %s (%lu bytes)\n", pe->filename, file_offset);
694 return 0;
697 /*----------------------------------------------------------------------------*/
699 #ifdef TCC_TARGET_X86_64
700 #define ELFW_R_(type) ELF64_R_##type
701 #define ElfW_Rel ElfW(Rela)
703 #define REL_TYPE_DIRECT R_X86_64_64
704 #define R_XXX_THUNKFIX R_X86_64_PC32
705 #define R_XXX_RELATIVE R_X86_64_RELATIVE
707 #define ELFW_ST_BIND ELF64_ST_BIND
708 #define ELFW_ST_TYPE ELF64_ST_TYPE
709 #define ELFW_ST_INFO ELF64_ST_INFO
710 #else
711 #define ELFW_R_(type) ELF32_R_##type
712 #define ElfW_Rel ElfW(Rel)
714 #define REL_TYPE_DIRECT R_386_32
715 #define R_XXX_THUNKFIX R_386_32
716 #define R_XXX_RELATIVE R_386_RELATIVE
718 #define ELFW_ST_BIND ELF32_ST_BIND
719 #define ELFW_ST_TYPE ELF32_ST_TYPE
720 #define ELFW_ST_INFO ELF32_ST_INFO
721 #endif
722 /*----------------------------------------------------------------------------*/
724 ST_FN struct import_symbol *pe_add_import(struct pe_info *pe, int sym_index)
726 int i;
727 int dll_index;
728 struct pe_import_info *p;
729 struct import_symbol *s;
731 dll_index = ((ElfW(Sym) *)pe->s1->dynsymtab_section->data + sym_index)->st_value;
732 if (0 == dll_index)
733 return NULL;
735 i = dynarray_assoc ((void**)pe->imp_info, pe->imp_count, dll_index);
736 if (-1 != i) {
737 p = pe->imp_info[i];
738 goto found_dll;
740 p = tcc_mallocz(sizeof *p);
741 p->dll_index = dll_index;
742 dynarray_add((void***)&pe->imp_info, &pe->imp_count, p);
744 found_dll:
745 i = dynarray_assoc ((void**)p->symbols, p->sym_count, sym_index);
746 if (-1 != i)
747 return p->symbols[i];
749 s = tcc_mallocz(sizeof *s);
750 dynarray_add((void***)&p->symbols, &p->sym_count, s);
751 s->sym_index = sym_index;
752 return s;
755 /*----------------------------------------------------------------------------*/
756 ST_FN void pe_build_imports(struct pe_info *pe)
758 int thk_ptr, ent_ptr, dll_ptr, sym_cnt, i;
759 DWORD rva_base = pe->thunk->sh_addr - pe->imagebase;
760 int ndlls = pe->imp_count;
762 for (sym_cnt = i = 0; i < ndlls; ++i)
763 sym_cnt += pe->imp_info[i]->sym_count;
765 if (0 == sym_cnt)
766 return;
768 pe_align_section(pe->thunk, 16);
770 pe->imp_offs = dll_ptr = pe->thunk->data_offset;
771 pe->imp_size = (ndlls + 1) * sizeof(IMAGE_IMPORT_DESCRIPTOR);
772 pe->iat_offs = dll_ptr + pe->imp_size;
773 pe->iat_size = (sym_cnt + ndlls) * sizeof(ADDR3264);
774 section_ptr_add(pe->thunk, pe->imp_size + 2*pe->iat_size);
776 thk_ptr = pe->iat_offs;
777 ent_ptr = pe->iat_offs + pe->iat_size;
779 for (i = 0; i < pe->imp_count; ++i) {
780 IMAGE_IMPORT_DESCRIPTOR *hdr;
781 int k, n;
782 ADDR3264 v;
783 struct pe_import_info *p = pe->imp_info[i];
784 const char *name = pe->s1->loaded_dlls[p->dll_index-1]->name;
786 /* put the dll name into the import header */
787 v = put_elf_str(pe->thunk, name);
789 hdr = (IMAGE_IMPORT_DESCRIPTOR*)(pe->thunk->data + dll_ptr);
790 hdr->FirstThunk = thk_ptr + rva_base;
791 hdr->OriginalFirstThunk = ent_ptr + rva_base;
792 hdr->Name = v + rva_base;
794 for (k = 0, n = p->sym_count; k <= n; ++k) {
795 if (k < n) {
796 int iat_index = p->symbols[k]->iat_index;
797 int sym_index = p->symbols[k]->sym_index;
798 ElfW(Sym) *imp_sym = (ElfW(Sym) *)pe->s1->dynsymtab_section->data + sym_index;
799 ElfW(Sym) *org_sym = (ElfW(Sym) *)symtab_section->data + iat_index;
800 const char *name = pe->s1->dynsymtab_section->link->data + imp_sym->st_name;
802 org_sym->st_value = thk_ptr;
803 org_sym->st_shndx = pe->thunk->sh_num;
804 v = pe->thunk->data_offset + rva_base;
805 section_ptr_add(pe->thunk, sizeof(WORD)); /* hint, not used */
806 put_elf_str(pe->thunk, name);
807 #ifdef TCC_IS_NATIVE
808 if (pe->type == PE_RUN) {
809 DLLReference *dllref = pe->s1->loaded_dlls[imp_sym->st_value-1];
810 if ( !dllref->handle )
811 dllref->handle = LoadLibrary(dllref->name);
812 v = (ADDR3264)GetProcAddress(dllref->handle, name);
813 if (!v)
814 error_noabort("undefined symbol '%s'", name);
816 #endif
817 } else {
818 v = 0; /* last entry is zero */
820 *(ADDR3264*)(pe->thunk->data+thk_ptr) =
821 *(ADDR3264*)(pe->thunk->data+ent_ptr) = v;
822 thk_ptr += sizeof (ADDR3264);
823 ent_ptr += sizeof (ADDR3264);
825 dll_ptr += sizeof(IMAGE_IMPORT_DESCRIPTOR);
826 dynarray_reset(&p->symbols, &p->sym_count);
828 dynarray_reset(&pe->imp_info, &pe->imp_count);
831 /* ------------------------------------------------------------- */
833 For now only functions are exported. Export of data
834 would work, but import requires compiler support to
835 do an additional indirection.
837 For instance:
838 __declspec(dllimport) extern int something;
840 needs to be translated to:
842 *(int*)something
845 struct pe_sort_sym
847 int index;
848 const char *name;
851 ST_FN int sym_cmp(const void *va, const void *vb)
853 const char *ca = (*(struct pe_sort_sym**)va)->name;
854 const char *cb = (*(struct pe_sort_sym**)vb)->name;
855 return strcmp(ca, cb);
858 ST_FN void pe_build_exports(struct pe_info *pe)
860 ElfW(Sym) *sym;
861 int sym_index, sym_end;
862 DWORD rva_base, func_o, name_o, ord_o, str_o;
863 IMAGE_EXPORT_DIRECTORY *hdr;
864 int sym_count, ord;
865 struct pe_sort_sym **sorted, *p;
867 FILE *op;
868 char buf[MAX_PATH];
869 const char *dllname;
870 const char *name;
872 rva_base = pe->thunk->sh_addr - pe->imagebase;
873 sym_count = 0, sorted = NULL, op = NULL;
875 sym_end = symtab_section->data_offset / sizeof(ElfW(Sym));
876 for (sym_index = 1; sym_index < sym_end; ++sym_index) {
877 sym = (ElfW(Sym)*)symtab_section->data + sym_index;
878 name = symtab_section->link->data + sym->st_name;
879 if ((sym->st_other & 1)
880 /* export only symbols from actually written sections */
881 && pe->s1->sections[sym->st_shndx]->sh_addr) {
882 p = tcc_malloc(sizeof *p);
883 p->index = sym_index;
884 p->name = name;
885 dynarray_add((void***)&sorted, &sym_count, p);
887 #if 0
888 if (sym->st_other & 1)
889 printf("export: %s\n", name);
890 if (sym->st_other & 2)
891 printf("stdcall: %s\n", name);
892 #endif
895 if (0 == sym_count)
896 return;
898 qsort (sorted, sym_count, sizeof *sorted, sym_cmp);
900 pe_align_section(pe->thunk, 16);
901 dllname = tcc_basename(pe->filename);
903 pe->exp_offs = pe->thunk->data_offset;
904 func_o = pe->exp_offs + sizeof(IMAGE_EXPORT_DIRECTORY);
905 name_o = func_o + sym_count * sizeof (DWORD);
906 ord_o = name_o + sym_count * sizeof (DWORD);
907 str_o = ord_o + sym_count * sizeof(WORD);
909 hdr = section_ptr_add(pe->thunk, str_o - pe->exp_offs);
910 hdr->Characteristics = 0;
911 hdr->Base = 1;
912 hdr->NumberOfFunctions = sym_count;
913 hdr->NumberOfNames = sym_count;
914 hdr->AddressOfFunctions = func_o + rva_base;
915 hdr->AddressOfNames = name_o + rva_base;
916 hdr->AddressOfNameOrdinals = ord_o + rva_base;
917 hdr->Name = str_o + rva_base;
918 put_elf_str(pe->thunk, dllname);
920 #if 1
921 /* automatically write exports to <output-filename>.def */
922 strcpy(buf, pe->filename);
923 strcpy(tcc_fileextension(buf), ".def");
924 op = fopen(buf, "w");
925 if (NULL == op) {
926 error_noabort("could not create '%s': %s", buf, strerror(errno));
927 } else {
928 fprintf(op, "LIBRARY %s\n\nEXPORTS\n", dllname);
929 if (pe->s1->verbose)
930 printf("<- %s (%d symbols)\n", buf, sym_count);
932 #endif
934 for (ord = 0; ord < sym_count; ++ord)
936 p = sorted[ord], sym_index = p->index, name = p->name;
937 /* insert actual address later in pe_relocate_rva */
938 put_elf_reloc(symtab_section, pe->thunk,
939 func_o, R_XXX_RELATIVE, sym_index);
940 *(DWORD*)(pe->thunk->data + name_o)
941 = pe->thunk->data_offset + rva_base;
942 *(WORD*)(pe->thunk->data + ord_o)
943 = ord;
944 put_elf_str(pe->thunk, name);
945 func_o += sizeof (DWORD);
946 name_o += sizeof (DWORD);
947 ord_o += sizeof (WORD);
948 if (op)
949 fprintf(op, "%s\n", name);
951 pe->exp_size = pe->thunk->data_offset - pe->exp_offs;
952 dynarray_reset(&sorted, &sym_count);
955 /* ------------------------------------------------------------- */
956 ST_FN void pe_build_reloc (struct pe_info *pe)
958 DWORD offset, block_ptr, addr;
959 int count, i;
960 ElfW_Rel *rel, *rel_end;
961 Section *s = NULL, *sr;
963 offset = addr = block_ptr = count = i = 0;
964 rel = rel_end = NULL;
966 for(;;) {
967 if (rel < rel_end) {
968 int type = ELFW_R_(TYPE)(rel->r_info);
969 addr = rel->r_offset + s->sh_addr;
970 ++ rel;
971 if (type != REL_TYPE_DIRECT)
972 continue;
973 if (count == 0) { /* new block */
974 block_ptr = pe->reloc->data_offset;
975 section_ptr_add(pe->reloc, sizeof(struct pe_reloc_header));
976 offset = addr & 0xFFFFFFFF<<12;
978 if ((addr -= offset) < (1<<12)) { /* one block spans 4k addresses */
979 WORD *wp = section_ptr_add(pe->reloc, sizeof (WORD));
980 *wp = addr | IMAGE_REL_BASED_HIGHLOW<<12;
981 ++count;
982 continue;
984 -- rel;
986 } else if (i < pe->sec_count) {
987 sr = (s = pe->s1->sections[pe->sec_info[i++].ord])->reloc;
988 if (sr) {
989 rel = (ElfW_Rel *)sr->data;
990 rel_end = (ElfW_Rel *)(sr->data + sr->data_offset);
992 continue;
995 if (count) {
996 /* store the last block and ready for a new one */
997 struct pe_reloc_header *hdr;
998 if (count & 1) /* align for DWORDS */
999 section_ptr_add(pe->reloc, sizeof(WORD)), ++count;
1000 hdr = (struct pe_reloc_header *)(pe->reloc->data + block_ptr);
1001 hdr -> offset = offset - pe->imagebase;
1002 hdr -> size = count * sizeof(WORD) + sizeof(struct pe_reloc_header);
1003 count = 0;
1006 if (rel >= rel_end)
1007 break;
1011 /* ------------------------------------------------------------- */
1012 ST_FN int pe_section_class(Section *s)
1014 int type, flags;
1015 const char *name;
1017 type = s->sh_type;
1018 flags = s->sh_flags;
1019 name = s->name;
1020 if (flags & SHF_ALLOC) {
1021 if (type == SHT_PROGBITS) {
1022 if (flags & SHF_EXECINSTR)
1023 return sec_text;
1024 if (flags & SHF_WRITE)
1025 return sec_data;
1026 if (0 == strcmp(name, ".rsrc"))
1027 return sec_rsrc;
1028 if (0 == strcmp(name, ".iedat"))
1029 return sec_idata;
1030 return sec_other;
1031 } else if (type == SHT_NOBITS) {
1032 if (flags & SHF_WRITE)
1033 return sec_bss;
1035 } else {
1036 if (0 == strcmp(name, ".reloc"))
1037 return sec_reloc;
1038 if (0 == strncmp(name, ".stab", 5)) /* .stab and .stabstr */
1039 return sec_stab;
1041 return -1;
1044 ST_FN int pe_assign_addresses (struct pe_info *pe)
1046 int i, k, o, c;
1047 DWORD addr;
1048 int *section_order;
1049 struct section_info *si;
1050 Section *s;
1052 // pe->thunk = new_section(pe->s1, ".iedat", SHT_PROGBITS, SHF_ALLOC);
1054 section_order = tcc_malloc(pe->s1->nb_sections * sizeof (int));
1055 for (o = k = 0 ; k < sec_last; ++k) {
1056 for (i = 1; i < pe->s1->nb_sections; ++i) {
1057 s = pe->s1->sections[i];
1058 if (k == pe_section_class(s)) {
1059 // printf("%s %d\n", s->name, k);
1060 s->sh_addr = pe->imagebase;
1061 section_order[o++] = i;
1066 pe->sec_info = tcc_mallocz(o * sizeof (struct section_info));
1067 addr = pe->imagebase + 1;
1069 for (i = 0; i < o; ++i)
1071 k = section_order[i];
1072 s = pe->s1->sections[k];
1073 c = pe_section_class(s);
1074 si = &pe->sec_info[pe->sec_count];
1076 #ifdef PE_MERGE_DATA
1077 if (c == sec_bss && pe->sec_count && si[-1].cls == sec_data) {
1078 /* append .bss to .data */
1079 s->sh_addr = addr = ((addr-1) | 15) + 1;
1080 addr += s->data_offset;
1081 si[-1].sh_size = addr - si[-1].sh_addr;
1082 continue;
1084 #endif
1085 strcpy(si->name, s->name);
1086 si->cls = c;
1087 si->ord = k;
1088 si->sh_addr = s->sh_addr = addr = pe_virtual_align(addr);
1089 si->sh_flags = s->sh_flags;
1091 if (c == sec_data && NULL == pe->thunk)
1092 pe->thunk = s;
1094 if (s == pe->thunk) {
1095 pe_build_imports(pe);
1096 pe_build_exports(pe);
1099 if (c == sec_reloc)
1100 pe_build_reloc (pe);
1102 if (s->data_offset)
1104 if (s->sh_type != SHT_NOBITS) {
1105 si->data = s->data;
1106 si->data_size = s->data_offset;
1109 addr += s->data_offset;
1110 si->sh_size = s->data_offset;
1111 ++pe->sec_count;
1113 // printf("%08x %05x %s\n", si->sh_addr, si->sh_size, si->name);
1116 #if 0
1117 for (i = 1; i < pe->s1->nb_sections; ++i) {
1118 Section *s = pe->s1->sections[i];
1119 int type = s->sh_type;
1120 int flags = s->sh_flags;
1121 printf("section %-16s %-10s %5x %s,%s,%s\n",
1122 s->name,
1123 type == SHT_PROGBITS ? "progbits" :
1124 type == SHT_NOBITS ? "nobits" :
1125 type == SHT_SYMTAB ? "symtab" :
1126 type == SHT_STRTAB ? "strtab" :
1127 type == SHT_RELX ? "rel" : "???",
1128 s->data_offset,
1129 flags & SHF_ALLOC ? "alloc" : "",
1130 flags & SHF_WRITE ? "write" : "",
1131 flags & SHF_EXECINSTR ? "exec" : ""
1134 pe->s1->verbose = 2;
1135 #endif
1137 tcc_free(section_order);
1138 return 0;
1141 /* ------------------------------------------------------------- */
1142 ST_FN void pe_relocate_rva (struct pe_info *pe, Section *s)
1144 Section *sr = s->reloc;
1145 ElfW_Rel *rel, *rel_end;
1146 rel_end = (ElfW_Rel *)(sr->data + sr->data_offset);
1147 for(rel = (ElfW_Rel *)sr->data; rel < rel_end; rel++) {
1148 if (ELFW_R_(TYPE)(rel->r_info) == R_XXX_RELATIVE) {
1149 int sym_index = ELFW_R_(SYM)(rel->r_info);
1150 DWORD addr = s->sh_addr;
1151 if (sym_index) {
1152 ElfW(Sym) *sym = (ElfW(Sym) *)symtab_section->data + sym_index;
1153 addr = sym->st_value;
1155 // printf("reloc rva %08x %08x\n", (DWORD)rel->r_offset, addr);
1156 *(DWORD*)(s->data + rel->r_offset) += addr - pe->imagebase;
1161 /*----------------------------------------------------------------------------*/
1162 ST_FN int pe_check_symbols(struct pe_info *pe)
1164 ElfW(Sym) *sym;
1165 int sym_index, sym_end;
1166 int ret = 0;
1168 pe_align_section(text_section, 8);
1170 sym_end = symtab_section->data_offset / sizeof(ElfW(Sym));
1171 for (sym_index = 1; sym_index < sym_end; ++sym_index) {
1173 sym = (ElfW(Sym) *)symtab_section->data + sym_index;
1174 if (sym->st_shndx == SHN_UNDEF) {
1176 const char *name = symtab_section->link->data + sym->st_name;
1177 unsigned type = ELFW_ST_TYPE(sym->st_info);
1178 int imp_sym = pe_find_import(pe->s1, name);
1179 struct import_symbol *is;
1181 if (0 == imp_sym)
1182 goto not_found;
1183 is = pe_add_import(pe, imp_sym);
1184 if (!is)
1185 goto not_found;
1187 if (type == STT_FUNC) {
1188 unsigned long offset = is->thk_offset;
1189 if (offset) {
1190 /* got aliased symbol, like stricmp and _stricmp */
1192 } else {
1193 char buffer[100];
1194 WORD *p;
1196 offset = text_section->data_offset;
1197 /* add the 'jmp IAT[x]' instruction */
1198 p = section_ptr_add(text_section, 8);
1199 *p = 0x25FF;
1200 #ifdef TCC_TARGET_X86_64
1201 *(DWORD*)(p+1) = (DWORD)-4;
1202 #endif
1203 /* add a helper symbol, will be patched later in
1204 pe_build_imports */
1205 sprintf(buffer, "IAT.%s", name);
1206 is->iat_index = put_elf_sym(
1207 symtab_section, 0, sizeof(DWORD),
1208 ELFW_ST_INFO(STB_GLOBAL, STT_OBJECT),
1209 0, SHN_UNDEF, buffer);
1210 put_elf_reloc(symtab_section, text_section,
1211 offset + 2, R_XXX_THUNKFIX, is->iat_index);
1212 is->thk_offset = offset;
1215 /* tcc_realloc might have altered sym's address */
1216 sym = (ElfW(Sym) *)symtab_section->data + sym_index;
1218 /* patch the original symbol */
1219 sym->st_value = offset;
1220 sym->st_shndx = text_section->sh_num;
1221 sym->st_other &= ~1; /* do not export */
1222 continue;
1225 if (type == STT_OBJECT) { /* data, ptr to that should be */
1226 if (0 == is->iat_index) {
1227 /* original symbol will be patched later in pe_build_imports */
1228 is->iat_index = sym_index;
1229 continue;
1233 not_found:
1234 error_noabort("undefined symbol '%s'", name);
1235 ret = -1;
1237 } else if (pe->s1->rdynamic
1238 && ELFW_ST_BIND(sym->st_info) != STB_LOCAL) {
1239 /* if -rdynamic option, then export all non local symbols */
1240 sym->st_other |= 1;
1243 return ret;
1246 /*----------------------------------------------------------------------------*/
1247 #ifdef PE_PRINT_SECTIONS
1248 ST_FN void pe_print_section(FILE * f, Section * s)
1250 /* just if you'r curious */
1251 BYTE *p, *e, b;
1252 int i, n, l, m;
1253 p = s->data;
1254 e = s->data + s->data_offset;
1255 l = e - p;
1257 fprintf(f, "section \"%s\"", s->name);
1258 if (s->link)
1259 fprintf(f, "\nlink \"%s\"", s->link->name);
1260 if (s->reloc)
1261 fprintf(f, "\nreloc \"%s\"", s->reloc->name);
1262 fprintf(f, "\nv_addr %08X", (unsigned)s->sh_addr);
1263 fprintf(f, "\ncontents %08X", (unsigned)l);
1264 fprintf(f, "\n\n");
1266 if (s->sh_type == SHT_NOBITS)
1267 return;
1269 if (0 == l)
1270 return;
1272 if (s->sh_type == SHT_SYMTAB)
1273 m = sizeof(ElfW(Sym));
1274 else if (s->sh_type == SHT_RELX)
1275 m = sizeof(ElfW_Rel);
1276 else
1277 m = 16;
1279 fprintf(f, "%-8s", "offset");
1280 for (i = 0; i < m; ++i)
1281 fprintf(f, " %02x", i);
1282 n = 56;
1284 if (s->sh_type == SHT_SYMTAB || s->sh_type == SHT_RELX) {
1285 const char *fields1[] = {
1286 "name",
1287 "value",
1288 "size",
1289 "bind",
1290 "type",
1291 "other",
1292 "shndx",
1293 NULL
1296 const char *fields2[] = {
1297 "offs",
1298 "type",
1299 "symb",
1300 NULL
1303 const char **p;
1305 if (s->sh_type == SHT_SYMTAB)
1306 p = fields1, n = 106;
1307 else
1308 p = fields2, n = 58;
1310 for (i = 0; p[i]; ++i)
1311 fprintf(f, "%6s", p[i]);
1312 fprintf(f, " symbol");
1315 fprintf(f, "\n");
1316 for (i = 0; i < n; ++i)
1317 fprintf(f, "-");
1318 fprintf(f, "\n");
1320 for (i = 0; i < l;)
1322 fprintf(f, "%08X", i);
1323 for (n = 0; n < m; ++n) {
1324 if (n + i < l)
1325 fprintf(f, " %02X", p[i + n]);
1326 else
1327 fprintf(f, " ");
1330 if (s->sh_type == SHT_SYMTAB) {
1331 ElfW(Sym) *sym = (ElfW(Sym) *) (p + i);
1332 const char *name = s->link->data + sym->st_name;
1333 fprintf(f, " %04X %04X %04X %02X %02X %02X %04X \"%s\"",
1334 (unsigned)sym->st_name,
1335 (unsigned)sym->st_value,
1336 (unsigned)sym->st_size,
1337 (unsigned)ELFW_ST_BIND(sym->st_info),
1338 (unsigned)ELFW_ST_TYPE(sym->st_info),
1339 (unsigned)sym->st_other,
1340 (unsigned)sym->st_shndx,
1341 name);
1343 } else if (s->sh_type == SHT_RELX) {
1344 ElfW_Rel *rel = (ElfW_Rel *) (p + i);
1345 ElfW(Sym) *sym =
1346 (ElfW(Sym) *) s->link->data + ELFW_R_(SYM)(rel->r_info);
1347 const char *name = s->link->link->data + sym->st_name;
1348 fprintf(f, " %04X %02X %04X \"%s\"",
1349 (unsigned)rel->r_offset,
1350 (unsigned)ELFW_R_(TYPE)(rel->r_info),
1351 (unsigned)ELFW_R_(SYM)(rel->r_info),
1352 name);
1353 } else {
1354 fprintf(f, " ");
1355 for (n = 0; n < m; ++n) {
1356 if (n + i < l) {
1357 b = p[i + n];
1358 if (b < 32 || b >= 127)
1359 b = '.';
1360 fprintf(f, "%c", b);
1364 i += m;
1365 fprintf(f, "\n");
1367 fprintf(f, "\n\n");
1370 ST_FN void pe_print_sections(TCCState *s1, const char *fname)
1372 Section *s;
1373 FILE *f;
1374 int i;
1375 f = fopen(fname, "w");
1376 for (i = 1; i < s1->nb_sections; ++i) {
1377 s = s1->sections[i];
1378 pe_print_section(f, s);
1380 pe_print_section(f, s1->dynsymtab_section);
1381 fclose(f);
1383 #endif
1385 /* ------------------------------------------------------------- */
1387 ST_FN int read_mem(FILE *fp, unsigned offset, void *buffer, unsigned len)
1389 fseek(fp, offset, 0);
1390 return len == fread(buffer, 1, len, fp);
1393 /* -------------------------------------------------------------
1394 * This is for compiled windows resources in 'coff' format
1395 * as generated by 'windres.exe -O coff ...'.
1398 ST_FN int pe_load_res(TCCState *s1, FILE *fp)
1400 struct pe_rsrc_header hdr;
1401 Section *rsrc_section;
1402 int i, ret = -1;
1403 BYTE *ptr;
1404 unsigned offs;
1406 if (!read_mem(fp, 0, &hdr, sizeof hdr))
1407 goto quit;
1409 if (hdr.filehdr.Machine != 0x014C
1410 || hdr.filehdr.NumberOfSections != 1
1411 || strcmp(hdr.sectionhdr.Name, ".rsrc") != 0)
1412 goto quit;
1414 rsrc_section = new_section(s1, ".rsrc", SHT_PROGBITS, SHF_ALLOC);
1415 ptr = section_ptr_add(rsrc_section, hdr.sectionhdr.SizeOfRawData);
1416 offs = hdr.sectionhdr.PointerToRawData;
1417 if (!read_mem(fp, offs, ptr, hdr.sectionhdr.SizeOfRawData))
1418 goto quit;
1419 offs = hdr.sectionhdr.PointerToRelocations;
1420 for (i = 0; i < hdr.sectionhdr.NumberOfRelocations; ++i)
1422 struct pe_rsrc_reloc rel;
1423 if (!read_mem(fp, offs, &rel, sizeof rel))
1424 goto quit;
1425 // printf("rsrc_reloc: %x %x %x\n", rel.offset, rel.size, rel.type);
1426 if (rel.type != 7) /* DIR32NB */
1427 goto quit;
1428 put_elf_reloc(symtab_section, rsrc_section,
1429 rel.offset, R_XXX_RELATIVE, 0);
1430 offs += sizeof rel;
1432 ret = 0;
1433 quit:
1434 return ret;
1437 /* ------------------------------------------------------------- */
1438 ST_FN char *trimfront(char *p)
1440 while (*p && (unsigned char)*p <= ' ')
1441 ++p;
1442 return p;
1445 ST_FN char *trimback(char *a, char *e)
1447 while (e > a && (unsigned char)e[-1] <= ' ')
1448 --e;
1449 *e = 0;;
1450 return a;
1453 ST_FN char *get_line(char *line, int size, FILE *fp)
1455 if (NULL == fgets(line, size, fp))
1456 return NULL;
1457 trimback(line, strchr(line, 0));
1458 return trimfront(line);
1461 /* ------------------------------------------------------------- */
1462 ST_FN int pe_load_def(TCCState *s1, FILE *fp)
1464 DLLReference *dllref;
1465 int state = 0, ret = -1;
1466 char line[400], dllname[80], *p;
1468 for (;;) {
1469 p = get_line(line, sizeof line, fp);
1470 if (NULL == p)
1471 break;
1472 if (0 == *p || ';' == *p)
1473 continue;
1474 switch (state) {
1475 case 0:
1476 if (0 != strnicmp(p, "LIBRARY", 7))
1477 goto quit;
1478 strcpy(dllname, trimfront(p+7));
1479 ++state;
1480 continue;
1482 case 1:
1483 if (0 != stricmp(p, "EXPORTS"))
1484 goto quit;
1485 ++state;
1486 continue;
1488 case 2:
1489 dllref = tcc_mallocz(sizeof(DLLReference) + strlen(dllname));
1490 strcpy(dllref->name, dllname);
1491 dynarray_add((void ***) &s1->loaded_dlls, &s1->nb_loaded_dlls, dllref);
1492 ++state;
1494 default:
1495 add_elf_sym(s1->dynsymtab_section,
1496 s1->nb_loaded_dlls, 0,
1497 ELFW_ST_INFO(STB_GLOBAL, STT_FUNC), 0,
1498 text_section->sh_num, p);
1499 continue;
1502 ret = 0;
1503 quit:
1504 return ret;
1507 /* ------------------------------------------------------------- */
1508 #define TINY_IMPDEF_GET_EXPORT_NAMES_ONLY
1509 #include "win32/tools/tiny_impdef.c"
1511 ST_FN int pe_load_dll(TCCState *s1, const char *dllname, FILE *fp)
1513 int i = 0;
1514 char *p, *q;
1515 p = get_export_names(fp);
1516 if (p) {
1517 DLLReference *dllref;
1518 dllref = tcc_mallocz(sizeof(DLLReference) + strlen(dllname));
1519 strcpy(dllref->name, dllname);
1520 dynarray_add((void ***) &s1->loaded_dlls, &s1->nb_loaded_dlls, dllref);
1521 for (q = p, i = 0; *q; ++i) {
1522 add_elf_sym(s1->dynsymtab_section,
1523 s1->nb_loaded_dlls, 0,
1524 ELFW_ST_INFO(STB_GLOBAL, STT_FUNC), 0,
1525 text_section->sh_num, q);
1526 q += 1 + strlen(q);
1528 tcc_free(p);
1530 return i ? 0 : -1;
1533 /* ------------------------------------------------------------- */
1534 PUB_FN int pe_load_file(struct TCCState *s1, const char *filename, int fd)
1536 FILE *fp = fdopen(dup(fd), "rb");
1537 int ret = -1;
1538 char buf[10];
1539 if (fp) {
1540 if (0 == strcmp(tcc_fileextension(filename), ".def"))
1541 ret = pe_load_def(s1, fp);
1542 else if (pe_load_res(s1, fp) == 0)
1543 ret = 0;
1544 else if (read_mem(fp, 0, buf, sizeof buf) && 0 == strncmp(buf, "MZ", 2))
1545 ret = pe_load_dll(s1, tcc_basename(filename), fp);
1546 fclose(fp);
1548 return ret;
1551 int pe_add_dll(struct TCCState *s, const char *libraryname)
1553 char buf[MAX_PATH];
1554 snprintf(buf, sizeof(buf), "%s.def", libraryname);
1555 if (tcc_add_dll(s, buf, 0) == 0)
1556 return 0;
1557 snprintf(buf, sizeof(buf), "%s.dll", libraryname);
1558 if (tcc_add_dll(s, buf, 0) == 0)
1559 return 0;
1560 return -1;
1563 /* ------------------------------------------------------------- */
1564 #ifdef TCC_TARGET_X86_64
1565 #define PE_STDSYM(n,s) n
1566 #else
1567 #define PE_STDSYM(n,s) "_" n s
1568 #endif
1570 ST_FN void pe_add_runtime_ex(TCCState *s1, struct pe_info *pe)
1572 const char *start_symbol;
1573 unsigned long addr = 0;
1574 int pe_type = 0;
1576 if (find_elf_sym(symtab_section, PE_STDSYM("WinMain","@16")))
1577 pe_type = PE_GUI;
1578 else
1579 if (TCC_OUTPUT_DLL == s1->output_type) {
1580 pe_type = PE_DLL;
1581 /* need this for 'tccelf.c:relocate_section()' */
1582 s1->output_type = TCC_OUTPUT_EXE;
1585 start_symbol =
1586 TCC_OUTPUT_MEMORY == s1->output_type
1587 ? PE_GUI == pe_type ? "_runwinmain" : NULL
1588 : PE_DLL == pe_type ? PE_STDSYM("_dllstart","@12")
1589 : PE_GUI == pe_type ? "_winstart" : "_start"
1592 /* grab the startup code from libtcc1 */
1593 if (start_symbol)
1594 add_elf_sym(symtab_section,
1595 0, 0,
1596 ELFW_ST_INFO(STB_GLOBAL, STT_NOTYPE), 0,
1597 SHN_UNDEF, start_symbol);
1599 if (0 == s1->nostdlib) {
1600 static const char *libs[] = {
1601 "tcc1", "msvcrt", "kernel32", "", "user32", "gdi32", NULL
1603 const char **pp, *p;
1604 for (pp = libs; 0 != (p = *pp); ++pp) {
1605 if (0 == *p) {
1606 if (PE_DLL != pe_type && PE_GUI != pe_type)
1607 break;
1608 } else if (tcc_add_library(s1, p) < 0)
1609 error_noabort("cannot find library: %s", p);
1613 if (start_symbol) {
1614 addr = (uplong)tcc_get_symbol_err(s1, start_symbol);
1615 if (s1->output_type == TCC_OUTPUT_MEMORY && addr)
1616 /* for -run GUI's, put '_runwinmain' instead of 'main' */
1617 add_elf_sym(symtab_section,
1618 addr, 0,
1619 ELFW_ST_INFO(STB_GLOBAL, STT_NOTYPE), 0,
1620 text_section->sh_num, "main");
1623 pe->type = pe_type;
1624 pe->start_addr = addr;
1627 PUB_FN int pe_output_file(TCCState * s1, const char *filename)
1629 int ret;
1630 struct pe_info pe;
1631 int i;
1633 memset(&pe, 0, sizeof pe);
1634 pe.filename = filename;
1635 pe.s1 = s1;
1637 pe_add_runtime_ex(s1, &pe);
1638 relocate_common_syms(); /* assign bss adresses */
1639 tcc_add_linker_symbols(s1);
1641 ret = pe_check_symbols(&pe);
1642 if (ret)
1643 return ret;
1645 if (filename) {
1646 if (PE_DLL == pe.type) {
1647 pe.reloc = new_section(pe.s1, ".reloc", SHT_PROGBITS, 0);
1648 pe.imagebase = 0x10000000;
1649 } else {
1650 pe.imagebase = 0x00400000;
1652 pe_assign_addresses(&pe);
1653 relocate_syms(s1, 0);
1654 for (i = 1; i < s1->nb_sections; ++i) {
1655 Section *s = s1->sections[i];
1656 if (s->reloc) {
1657 relocate_section(s1, s);
1658 pe_relocate_rva(&pe, s);
1661 if (s1->nb_errors)
1662 ret = -1;
1663 else
1664 ret = pe_write(&pe);
1665 tcc_free(pe.sec_info);
1666 } else {
1667 #ifndef TCC_IS_NATIVE
1668 error_noabort("-run supported only on native platform");
1669 #endif
1670 pe.type = PE_RUN;
1671 pe.thunk = data_section;
1672 pe_build_imports(&pe);
1675 #ifdef PE_PRINT_SECTIONS
1676 pe_print_sections(s1, "tcc.log");
1677 #endif
1678 return ret;
1681 /* ------------------------------------------------------------- */
1682 #endif /* def TCC_TARGET_PE */
1683 /* ------------------------------------------------------------- */