Added missing file.
[tinycc/k1w1.git] / tccpe.c
blob2e5c6e20d8e7813ea5756cd0d57ec4b49a16f4bc
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
20 #include "tcc.h"
22 #ifdef TCC_TARGET_PE
24 #define ST_FN static
25 #define ST_DATA static
26 #define PUB_FN
28 #ifndef _WIN32
29 #define stricmp strcasecmp
30 #define strnicmp strncasecmp
31 #endif
33 #ifndef MAX_PATH
34 #define MAX_PATH 260
35 #endif
37 #define PE_MERGE_DATA
38 // #define PE_PRINT_SECTIONS
40 #ifdef TCC_TARGET_X86_64
41 # define ADDR3264 ULONGLONG
42 #else
43 # define ADDR3264 DWORD
44 #endif
46 #if defined _WIN32 && (defined _WIN64) == (defined TCC_TARGET_X86_64)
47 #define TCC_IS_NATIVE
48 #endif
50 #ifdef _WIN32
51 void dbg_printf (const char *fmt, ...)
53 char buffer[4000];
54 va_list arg;
55 int x;
56 va_start(arg, fmt);
57 x = vsprintf (buffer, fmt, arg);
58 strcpy(buffer+x, "\n");
59 OutputDebugString(buffer);
61 #endif
63 /* ----------------------------------------------------------- */
64 #ifndef IMAGE_NT_SIGNATURE
65 /* ----------------------------------------------------------- */
66 /* definitions below are from winnt.h */
68 typedef unsigned char BYTE;
69 typedef unsigned short WORD;
70 typedef unsigned long DWORD;
71 typedef unsigned long long ULONGLONG;
72 #pragma pack(push, 1)
74 typedef struct _IMAGE_DOS_HEADER { /* DOS .EXE header */
75 WORD e_magic; /* Magic number */
76 WORD e_cblp; /* Bytes on last page of file */
77 WORD e_cp; /* Pages in file */
78 WORD e_crlc; /* Relocations */
79 WORD e_cparhdr; /* Size of header in paragraphs */
80 WORD e_minalloc; /* Minimum extra paragraphs needed */
81 WORD e_maxalloc; /* Maximum extra paragraphs needed */
82 WORD e_ss; /* Initial (relative) SS value */
83 WORD e_sp; /* Initial SP value */
84 WORD e_csum; /* Checksum */
85 WORD e_ip; /* Initial IP value */
86 WORD e_cs; /* Initial (relative) CS value */
87 WORD e_lfarlc; /* File address of relocation table */
88 WORD e_ovno; /* Overlay number */
89 WORD e_res[4]; /* Reserved words */
90 WORD e_oemid; /* OEM identifier (for e_oeminfo) */
91 WORD e_oeminfo; /* OEM information; e_oemid specific */
92 WORD e_res2[10]; /* Reserved words */
93 DWORD e_lfanew; /* File address of new exe header */
94 } IMAGE_DOS_HEADER, *PIMAGE_DOS_HEADER;
96 #define IMAGE_NT_SIGNATURE 0x00004550 /* PE00 */
97 #define SIZE_OF_NT_SIGNATURE 4
99 typedef struct _IMAGE_FILE_HEADER {
100 WORD Machine;
101 WORD NumberOfSections;
102 DWORD TimeDateStamp;
103 DWORD PointerToSymbolTable;
104 DWORD NumberOfSymbols;
105 WORD SizeOfOptionalHeader;
106 WORD Characteristics;
107 } IMAGE_FILE_HEADER, *PIMAGE_FILE_HEADER;
110 #define IMAGE_SIZEOF_FILE_HEADER 20
112 typedef struct _IMAGE_DATA_DIRECTORY {
113 DWORD VirtualAddress;
114 DWORD Size;
115 } IMAGE_DATA_DIRECTORY, *PIMAGE_DATA_DIRECTORY;
118 typedef struct _IMAGE_OPTIONAL_HEADER {
119 /* Standard fields. */
120 WORD Magic;
121 BYTE MajorLinkerVersion;
122 BYTE MinorLinkerVersion;
123 DWORD SizeOfCode;
124 DWORD SizeOfInitializedData;
125 DWORD SizeOfUninitializedData;
126 DWORD AddressOfEntryPoint;
127 DWORD BaseOfCode;
128 #ifndef TCC_TARGET_X86_64
129 DWORD BaseOfData;
130 #endif
131 /* NT additional fields. */
132 ADDR3264 ImageBase;
133 DWORD SectionAlignment;
134 DWORD FileAlignment;
135 WORD MajorOperatingSystemVersion;
136 WORD MinorOperatingSystemVersion;
137 WORD MajorImageVersion;
138 WORD MinorImageVersion;
139 WORD MajorSubsystemVersion;
140 WORD MinorSubsystemVersion;
141 DWORD Win32VersionValue;
142 DWORD SizeOfImage;
143 DWORD SizeOfHeaders;
144 DWORD CheckSum;
145 WORD Subsystem;
146 WORD DllCharacteristics;
147 ADDR3264 SizeOfStackReserve;
148 ADDR3264 SizeOfStackCommit;
149 ADDR3264 SizeOfHeapReserve;
150 ADDR3264 SizeOfHeapCommit;
151 DWORD LoaderFlags;
152 DWORD NumberOfRvaAndSizes;
153 IMAGE_DATA_DIRECTORY DataDirectory[16];
154 } IMAGE_OPTIONAL_HEADER32, IMAGE_OPTIONAL_HEADER64, IMAGE_OPTIONAL_HEADER;
156 #define IMAGE_DIRECTORY_ENTRY_EXPORT 0 /* Export Directory */
157 #define IMAGE_DIRECTORY_ENTRY_IMPORT 1 /* Import Directory */
158 #define IMAGE_DIRECTORY_ENTRY_RESOURCE 2 /* Resource Directory */
159 #define IMAGE_DIRECTORY_ENTRY_EXCEPTION 3 /* Exception Directory */
160 #define IMAGE_DIRECTORY_ENTRY_SECURITY 4 /* Security Directory */
161 #define IMAGE_DIRECTORY_ENTRY_BASERELOC 5 /* Base Relocation Table */
162 #define IMAGE_DIRECTORY_ENTRY_DEBUG 6 /* Debug Directory */
163 /* IMAGE_DIRECTORY_ENTRY_COPYRIGHT 7 (X86 usage) */
164 #define IMAGE_DIRECTORY_ENTRY_ARCHITECTURE 7 /* Architecture Specific Data */
165 #define IMAGE_DIRECTORY_ENTRY_GLOBALPTR 8 /* RVA of GP */
166 #define IMAGE_DIRECTORY_ENTRY_TLS 9 /* TLS Directory */
167 #define IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG 10 /* Load Configuration Directory */
168 #define IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT 11 /* Bound Import Directory in headers */
169 #define IMAGE_DIRECTORY_ENTRY_IAT 12 /* Import Address Table */
170 #define IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT 13 /* Delay Load Import Descriptors */
171 #define IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR 14 /* COM Runtime descriptor */
173 /* Section header format. */
174 #define IMAGE_SIZEOF_SHORT_NAME 8
176 typedef struct _IMAGE_SECTION_HEADER {
177 BYTE Name[IMAGE_SIZEOF_SHORT_NAME];
178 union {
179 DWORD PhysicalAddress;
180 DWORD VirtualSize;
181 } Misc;
182 DWORD VirtualAddress;
183 DWORD SizeOfRawData;
184 DWORD PointerToRawData;
185 DWORD PointerToRelocations;
186 DWORD PointerToLinenumbers;
187 WORD NumberOfRelocations;
188 WORD NumberOfLinenumbers;
189 DWORD Characteristics;
190 } IMAGE_SECTION_HEADER, *PIMAGE_SECTION_HEADER;
192 #define IMAGE_SIZEOF_SECTION_HEADER 40
194 typedef struct _IMAGE_EXPORT_DIRECTORY {
195 DWORD Characteristics;
196 DWORD TimeDateStamp;
197 WORD MajorVersion;
198 WORD MinorVersion;
199 DWORD Name;
200 DWORD Base;
201 DWORD NumberOfFunctions;
202 DWORD NumberOfNames;
203 DWORD AddressOfFunctions;
204 DWORD AddressOfNames;
205 DWORD AddressOfNameOrdinals;
206 } IMAGE_EXPORT_DIRECTORY,*PIMAGE_EXPORT_DIRECTORY;
208 typedef struct _IMAGE_IMPORT_DESCRIPTOR {
209 union {
210 DWORD Characteristics;
211 DWORD OriginalFirstThunk;
213 DWORD TimeDateStamp;
214 DWORD ForwarderChain;
215 DWORD Name;
216 DWORD FirstThunk;
217 } IMAGE_IMPORT_DESCRIPTOR;
219 typedef struct _IMAGE_BASE_RELOCATION {
220 DWORD VirtualAddress;
221 DWORD SizeOfBlock;
222 // WORD TypeOffset[1];
223 } IMAGE_BASE_RELOCATION;
225 #define IMAGE_SIZEOF_BASE_RELOCATION 8
227 #define IMAGE_REL_BASED_ABSOLUTE 0
228 #define IMAGE_REL_BASED_HIGH 1
229 #define IMAGE_REL_BASED_LOW 2
230 #define IMAGE_REL_BASED_HIGHLOW 3
231 #define IMAGE_REL_BASED_HIGHADJ 4
232 #define IMAGE_REL_BASED_MIPS_JMPADDR 5
233 #define IMAGE_REL_BASED_SECTION 6
234 #define IMAGE_REL_BASED_REL32 7
236 #pragma pack(pop)
238 /* ----------------------------------------------------------- */
239 #endif /* ndef IMAGE_NT_SIGNATURE */
240 /* ----------------------------------------------------------- */
241 #pragma pack(push, 1)
243 struct pe_header
245 IMAGE_DOS_HEADER doshdr;
246 BYTE dosstub[0x40];
247 DWORD nt_sig;
248 IMAGE_FILE_HEADER filehdr;
249 #ifdef TCC_TARGET_X86_64
250 IMAGE_OPTIONAL_HEADER64 opthdr;
251 #else
252 #ifdef _WIN64
253 IMAGE_OPTIONAL_HEADER32 opthdr;
254 #else
255 IMAGE_OPTIONAL_HEADER opthdr;
256 #endif
257 #endif
260 struct pe_reloc_header {
261 DWORD offset;
262 DWORD size;
265 struct pe_rsrc_header {
266 struct _IMAGE_FILE_HEADER filehdr;
267 struct _IMAGE_SECTION_HEADER sectionhdr;
270 struct pe_rsrc_reloc {
271 DWORD offset;
272 DWORD size;
273 WORD type;
276 #pragma pack(pop)
278 /* ------------------------------------------------------------- */
279 /* internal temporary structures */
282 #define IMAGE_SCN_CNT_CODE 0x00000020
283 #define IMAGE_SCN_CNT_INITIALIZED_DATA 0x00000040
284 #define IMAGE_SCN_CNT_UNINITIALIZED_DATA 0x00000080
285 #define IMAGE_SCN_MEM_DISCARDABLE 0x02000000
286 #define IMAGE_SCN_MEM_SHARED 0x10000000
287 #define IMAGE_SCN_MEM_EXECUTE 0x20000000
288 #define IMAGE_SCN_MEM_READ 0x40000000
289 #define IMAGE_SCN_MEM_WRITE 0x80000000
292 enum {
293 sec_text = 0,
294 sec_data ,
295 sec_bss ,
296 sec_idata ,
297 sec_other ,
298 sec_rsrc ,
299 sec_stab ,
300 sec_reloc ,
301 sec_last
304 ST_DATA const DWORD pe_sec_flags[] = {
305 0x60000020, /* ".text" , */
306 0xC0000040, /* ".data" , */
307 0xC0000080, /* ".bss" , */
308 0x40000040, /* ".idata" , */
309 0xE0000060, /* < other > , */
310 0x40000040, /* ".rsrc" , */
311 0x42000802, /* ".stab" , */
312 0x42000040, /* ".reloc" , */
315 struct section_info {
316 int cls, ord;
317 char name[32];
318 DWORD sh_addr;
319 DWORD sh_size;
320 DWORD sh_flags;
321 unsigned char *data;
322 DWORD data_size;
323 IMAGE_SECTION_HEADER ish;
326 struct import_symbol {
327 int sym_index;
328 int iat_index;
329 int thk_offset;
332 struct pe_import_info {
333 int dll_index;
334 int sym_count;
335 struct import_symbol **symbols;
338 struct pe_info {
339 TCCState *s1;
340 Section *reloc;
341 Section *thunk;
342 const char *filename;
343 int type;
344 DWORD sizeofheaders;
345 DWORD imagebase;
346 DWORD start_addr;
347 DWORD imp_offs;
348 DWORD imp_size;
349 DWORD iat_offs;
350 DWORD iat_size;
351 DWORD exp_offs;
352 DWORD exp_size;
353 int subsystem;
354 DWORD section_align;
355 DWORD file_align;
356 struct section_info *sec_info;
357 int sec_count;
358 struct pe_import_info **imp_info;
359 int imp_count;
362 #define PE_NUL 0
363 #define PE_DLL 1
364 #define PE_GUI 2
365 #define PE_EXE 3
366 #define PE_RUN 4
368 /* --------------------------------------------*/
370 ST_FN const char* get_alt_symbol(char *buffer, const char *symbol)
372 const char *p;
373 p = strrchr(symbol, '@');
374 if (p && isnum(p[1]) && symbol[0] == '_') { /* stdcall decor */
375 strcpy(buffer, symbol+1)[p-symbol-1] = 0;
376 } else if (symbol[0] != '_') { /* try non-ansi function */
377 buffer[0] = '_', strcpy(buffer + 1, symbol);
378 } else if (0 == memcmp(symbol, "__imp__", 7)) { /* mingw 2.0 */
379 strcpy(buffer, symbol + 6);
380 } else if (0 == memcmp(symbol, "_imp___", 7)) { /* mingw 3.7 */
381 strcpy(buffer, symbol + 6);
382 } else {
383 return symbol;
385 return buffer;
388 ST_FN int pe_find_import(TCCState * s1, const char *symbol)
390 char buffer[200];
391 const char *s;
392 int sym_index, n = 0;
393 do {
394 s = n ? get_alt_symbol(buffer, symbol) : symbol;
395 sym_index = find_elf_sym(s1->dynsymtab_section, s);
396 // printf("find (%d) %d %s\n", n, sym_index, s);
397 } while (0 == sym_index && ++n < 2);
398 return sym_index;
401 /*----------------------------------------------------------------------------*/
403 ST_FN int dynarray_assoc(void **pp, int n, int key)
405 int i;
406 for (i = 0; i < n; ++i, ++pp)
407 if (key == **(int **) pp)
408 return i;
409 return -1;
412 #if 0
413 ST_FN DWORD umin(DWORD a, DWORD b)
415 return a < b ? a : b;
417 #endif
419 ST_FN DWORD umax(DWORD a, DWORD b)
421 return a < b ? b : a;
424 ST_FN DWORD pe_file_align(struct pe_info *pe, DWORD n)
426 return (n + (pe->file_align - 1)) & ~(pe->file_align - 1);
429 ST_FN DWORD pe_virtual_align(struct pe_info *pe, DWORD n)
431 return (n + (pe->section_align - 1)) & ~(pe->section_align - 1);
434 ST_FN void pe_align_section(Section *s, int a)
436 int i = s->data_offset & (a-1);
437 if (i)
438 section_ptr_add(s, a - i);
441 ST_FN void pe_set_datadir(struct pe_header *hdr, int dir, DWORD addr, DWORD size)
443 hdr->opthdr.DataDirectory[dir].VirtualAddress = addr;
444 hdr->opthdr.DataDirectory[dir].Size = size;
447 ST_FN int pe_fwrite(void *data, unsigned len, FILE *fp, DWORD *psum)
449 if (psum) {
450 DWORD sum = *psum;
451 WORD *p = data;
452 int i;
453 for (i = len; i > 0; i -= 2) {
454 sum += (i >= 2) ? *p++ : *(BYTE*)p;
455 sum = (sum + (sum >> 16)) & 0xFFFF;
457 *psum = sum;
459 return len == fwrite(data, 1, len, fp) ? 0 : -1;
462 ST_FN void pe_fpad(FILE *fp, DWORD new_pos)
464 DWORD pos = ftell(fp);
465 while (++pos <= new_pos)
466 fputc(0, fp);
469 /*----------------------------------------------------------------------------*/
470 ST_FN int pe_write(struct pe_info *pe)
472 static const struct pe_header pe_template = {
474 /* IMAGE_DOS_HEADER doshdr */
475 0x5A4D, /*WORD e_magic; Magic number */
476 0x0090, /*WORD e_cblp; Bytes on last page of file */
477 0x0003, /*WORD e_cp; Pages in file */
478 0x0000, /*WORD e_crlc; Relocations */
480 0x0004, /*WORD e_cparhdr; Size of header in paragraphs */
481 0x0000, /*WORD e_minalloc; Minimum extra paragraphs needed */
482 0xFFFF, /*WORD e_maxalloc; Maximum extra paragraphs needed */
483 0x0000, /*WORD e_ss; Initial (relative) SS value */
485 0x00B8, /*WORD e_sp; Initial SP value */
486 0x0000, /*WORD e_csum; Checksum */
487 0x0000, /*WORD e_ip; Initial IP value */
488 0x0000, /*WORD e_cs; Initial (relative) CS value */
489 0x0040, /*WORD e_lfarlc; File address of relocation table */
490 0x0000, /*WORD e_ovno; Overlay number */
491 {0,0,0,0}, /*WORD e_res[4]; Reserved words */
492 0x0000, /*WORD e_oemid; OEM identifier (for e_oeminfo) */
493 0x0000, /*WORD e_oeminfo; OEM information; e_oemid specific */
494 {0,0,0,0,0,0,0,0,0,0}, /*WORD e_res2[10]; Reserved words */
495 0x00000080 /*DWORD e_lfanew; File address of new exe header */
497 /* BYTE dosstub[0x40] */
498 /* 14 code bytes + "This program cannot be run in DOS mode.\r\r\n$" + 6 * 0x00 */
499 0x0e,0x1f,0xba,0x0e,0x00,0xb4,0x09,0xcd,0x21,0xb8,0x01,0x4c,0xcd,0x21,0x54,0x68,
500 0x69,0x73,0x20,0x70,0x72,0x6f,0x67,0x72,0x61,0x6d,0x20,0x63,0x61,0x6e,0x6e,0x6f,
501 0x74,0x20,0x62,0x65,0x20,0x72,0x75,0x6e,0x20,0x69,0x6e,0x20,0x44,0x4f,0x53,0x20,
502 0x6d,0x6f,0x64,0x65,0x2e,0x0d,0x0d,0x0a,0x24,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
504 0x00004550, /* DWORD nt_sig = IMAGE_NT_SIGNATURE */
506 /* IMAGE_FILE_HEADER filehdr */
507 #if defined(TCC_TARGET_I386)
508 0x014C, /*WORD Machine; */
509 #elif defined(TCC_TARGET_X86_64)
510 0x8664, /*WORD Machine; */
511 #elif defined(TCC_TARGET_ARM)
512 0x01C0, /*WORD Machine; */
513 #endif
514 0x0003, /*WORD NumberOfSections; */
515 0x00000000, /*DWORD TimeDateStamp; */
516 0x00000000, /*DWORD PointerToSymbolTable; */
517 0x00000000, /*DWORD NumberOfSymbols; */
518 #if defined(TCC_TARGET_X86_64)
519 0x00F0, /*WORD SizeOfOptionalHeader; */
520 0x022F /*WORD Characteristics; */
521 #define CHARACTERISTICS_DLL 0x222E
522 #elif defined(TCC_TARGET_I386)
523 0x00E0, /*WORD SizeOfOptionalHeader; */
524 0x030F /*WORD Characteristics; */
525 #define CHARACTERISTICS_DLL 0x230E
526 #elif defined(TCC_TARGET_ARM)
527 0x00E0, /*WORD SizeOfOptionalHeader; */
528 0x010F, /*WORD Characteristics; */
529 #define CHARACTERISTICS_DLL 0x230F
530 #endif
532 /* IMAGE_OPTIONAL_HEADER opthdr */
533 /* Standard fields. */
534 #ifdef TCC_TARGET_X86_64
535 0x020B, /*WORD Magic; */
536 #else
537 0x010B, /*WORD Magic; */
538 #endif
539 0x06, /*BYTE MajorLinkerVersion; */
540 0x00, /*BYTE MinorLinkerVersion; */
541 0x00000000, /*DWORD SizeOfCode; */
542 0x00000000, /*DWORD SizeOfInitializedData; */
543 0x00000000, /*DWORD SizeOfUninitializedData; */
544 0x00000000, /*DWORD AddressOfEntryPoint; */
545 0x00000000, /*DWORD BaseOfCode; */
546 #ifndef TCC_TARGET_X86_64
547 0x00000000, /*DWORD BaseOfData; */
548 #endif
549 /* NT additional fields. */
550 #if defined(TCC_TARGET_ARM)
551 0x00100000, /*DWORD ImageBase; */
552 #else
553 0x00400000, /*DWORD ImageBase; */
554 #endif
555 0x00001000, /*DWORD SectionAlignment; */
556 0x00000200, /*DWORD FileAlignment; */
557 0x0004, /*WORD MajorOperatingSystemVersion; */
558 0x0000, /*WORD MinorOperatingSystemVersion; */
559 0x0000, /*WORD MajorImageVersion; */
560 0x0000, /*WORD MinorImageVersion; */
561 0x0004, /*WORD MajorSubsystemVersion; */
562 0x0000, /*WORD MinorSubsystemVersion; */
563 0x00000000, /*DWORD Win32VersionValue; */
564 0x00000000, /*DWORD SizeOfImage; */
565 0x00000200, /*DWORD SizeOfHeaders; */
566 0x00000000, /*DWORD CheckSum; */
567 0x0002, /*WORD Subsystem; */
568 0x0000, /*WORD DllCharacteristics; */
569 0x00100000, /*DWORD SizeOfStackReserve; */
570 0x00001000, /*DWORD SizeOfStackCommit; */
571 0x00100000, /*DWORD SizeOfHeapReserve; */
572 0x00001000, /*DWORD SizeOfHeapCommit; */
573 0x00000000, /*DWORD LoaderFlags; */
574 0x00000010, /*DWORD NumberOfRvaAndSizes; */
576 /* IMAGE_DATA_DIRECTORY DataDirectory[16]; */
577 {{0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0},
578 {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}}
581 struct pe_header pe_header = pe_template;
583 int i;
584 FILE *op;
585 DWORD file_offset, sum;
586 struct section_info *si;
587 IMAGE_SECTION_HEADER *psh;
589 op = fopen(pe->filename, "wb");
590 if (NULL == op) {
591 error_noabort("could not write '%s': %s", pe->filename, strerror(errno));
592 return -1;
595 pe->sizeofheaders = pe_file_align(pe,
596 sizeof (struct pe_header)
597 + pe->sec_count * sizeof (IMAGE_SECTION_HEADER)
600 file_offset = pe->sizeofheaders;
602 if (2 == pe->s1->verbose)
603 printf("-------------------------------"
604 "\n virt file size section" "\n");
605 for (i = 0; i < pe->sec_count; ++i) {
606 unsigned long addr, size;
607 const char *sh_name;
609 si = pe->sec_info + i;
610 sh_name = si->name;
611 addr = si->sh_addr - pe->imagebase;
612 size = si->sh_size;
613 psh = &si->ish;
615 if (2 == pe->s1->verbose)
616 printf("%6lx %6lx %6lx %s\n",
617 addr, file_offset, size, sh_name);
619 switch (si->cls) {
620 case sec_text:
621 pe_header.opthdr.BaseOfCode = addr;
622 pe_header.opthdr.AddressOfEntryPoint = addr + pe->start_addr;
623 break;
625 case sec_data:
626 #ifndef TCC_TARGET_X86_64
627 pe_header.opthdr.BaseOfData = addr;
628 #endif
629 break;
631 case sec_bss:
632 break;
634 case sec_reloc:
635 pe_set_datadir(&pe_header, IMAGE_DIRECTORY_ENTRY_BASERELOC, addr, size);
636 break;
638 case sec_rsrc:
639 pe_set_datadir(&pe_header, IMAGE_DIRECTORY_ENTRY_RESOURCE, addr, size);
640 break;
642 case sec_stab:
643 break;
646 if (pe->thunk == pe->s1->sections[si->ord]) {
647 if (pe->imp_size) {
648 pe_set_datadir(&pe_header, IMAGE_DIRECTORY_ENTRY_IMPORT,
649 pe->imp_offs + addr, pe->imp_size);
650 pe_set_datadir(&pe_header, IMAGE_DIRECTORY_ENTRY_IAT,
651 pe->iat_offs + addr, pe->iat_size);
653 if (pe->exp_size) {
654 pe_set_datadir(&pe_header, IMAGE_DIRECTORY_ENTRY_EXPORT,
655 pe->exp_offs + addr, pe->exp_size);
659 strcpy((char*)psh->Name, sh_name);
661 psh->Characteristics = pe_sec_flags[si->cls];
662 psh->VirtualAddress = addr;
663 psh->Misc.VirtualSize = size;
664 pe_header.opthdr.SizeOfImage =
665 umax(pe_virtual_align(pe, size + addr), pe_header.opthdr.SizeOfImage);
667 if (si->data_size) {
668 psh->PointerToRawData = file_offset;
669 file_offset = pe_file_align(pe, file_offset + si->data_size);
670 psh->SizeOfRawData = file_offset - psh->PointerToRawData;
674 //pe_header.filehdr.TimeDateStamp = time(NULL);
675 pe_header.filehdr.NumberOfSections = pe->sec_count;
676 pe_header.opthdr.SizeOfHeaders = pe->sizeofheaders;
677 pe_header.opthdr.ImageBase = pe->imagebase;
678 if (PE_DLL == pe->type)
679 pe_header.filehdr.Characteristics = CHARACTERISTICS_DLL;
680 else if (PE_GUI != pe->type)
681 pe_header.opthdr.Subsystem = 3;
683 sum = 0;
684 pe_fwrite(&pe_header, sizeof pe_header, op, &sum);
685 for (i = 0; i < pe->sec_count; ++i)
686 pe_fwrite(&pe->sec_info[i].ish, sizeof(IMAGE_SECTION_HEADER), op, &sum);
687 pe_fpad(op, pe->sizeofheaders);
688 for (i = 0; i < pe->sec_count; ++i) {
689 si = pe->sec_info + i;
690 psh = &si->ish;
691 if (si->data_size) {
692 pe_fwrite(si->data, si->data_size, op, &sum);
693 file_offset = psh->PointerToRawData + psh->SizeOfRawData;
694 pe_fpad(op, file_offset);
698 pe_header.opthdr.CheckSum = sum + file_offset;
699 fseek(op, offsetof(struct pe_header, opthdr.CheckSum), SEEK_SET);
700 pe_fwrite(&pe_header.opthdr.CheckSum, sizeof pe_header.opthdr.CheckSum, op, NULL);
701 fclose (op);
703 if (2 == pe->s1->verbose)
704 printf("-------------------------------\n");
705 if (pe->s1->verbose)
706 printf("<- %s (%lu bytes)\n", pe->filename, file_offset);
708 return 0;
711 /*----------------------------------------------------------------------------*/
713 #if defined(TCC_TARGET_X86_64)
714 #define ELFW_R_(type) ELF64_R_##type
715 #define ElfW_Rel ElfW(Rela)
717 #define REL_TYPE_DIRECT R_X86_64_64
718 #define R_XXX_THUNKFIX R_X86_64_PC32
719 #define R_XXX_RELATIVE R_X86_64_RELATIVE
721 #define ELFW_ST_BIND ELF64_ST_BIND
722 #define ELFW_ST_TYPE ELF64_ST_TYPE
723 #define ELFW_ST_INFO ELF64_ST_INFO
724 #elif defined(TCC_TARGET_I386)
725 #define ELFW_R_(type) ELF32_R_##type
726 #define ElfW_Rel ElfW(Rel)
728 #define REL_TYPE_DIRECT R_386_32
729 #define R_XXX_THUNKFIX R_386_32
730 #define R_XXX_RELATIVE R_386_RELATIVE
732 #define ELFW_ST_BIND ELF32_ST_BIND
733 #define ELFW_ST_TYPE ELF32_ST_TYPE
734 #define ELFW_ST_INFO ELF32_ST_INFO
735 #elif defined(TCC_TARGET_ARM)
736 #define ELFW_R_(type) ELF32_R_##type
737 #define ElfW_Rel ElfW(Rel)
739 #define REL_TYPE_DIRECT R_ARM_ABS32
740 #define R_XXX_THUNKFIX R_ARM_ABS32
741 #define R_XXX_RELATIVE R_ARM_RELATIVE
743 #define ELFW_ST_BIND ELF32_ST_BIND
744 #define ELFW_ST_TYPE ELF32_ST_TYPE
745 #define ELFW_ST_INFO ELF32_ST_INFO
746 #endif
747 /*----------------------------------------------------------------------------*/
749 ST_FN struct import_symbol *pe_add_import(struct pe_info *pe, int sym_index)
751 int i;
752 int dll_index;
753 struct pe_import_info *p;
754 struct import_symbol *s;
756 dll_index = ((ElfW(Sym) *)pe->s1->dynsymtab_section->data + sym_index)->st_value;
757 if (0 == dll_index)
758 return NULL;
760 i = dynarray_assoc ((void**)pe->imp_info, pe->imp_count, dll_index);
761 if (-1 != i) {
762 p = pe->imp_info[i];
763 goto found_dll;
765 p = tcc_mallocz(sizeof *p);
766 p->dll_index = dll_index;
767 dynarray_add((void***)&pe->imp_info, &pe->imp_count, p);
769 found_dll:
770 i = dynarray_assoc ((void**)p->symbols, p->sym_count, sym_index);
771 if (-1 != i)
772 return p->symbols[i];
774 s = tcc_mallocz(sizeof *s);
775 dynarray_add((void***)&p->symbols, &p->sym_count, s);
776 s->sym_index = sym_index;
777 return s;
780 /*----------------------------------------------------------------------------*/
781 ST_FN void pe_build_imports(struct pe_info *pe)
783 int thk_ptr, ent_ptr, dll_ptr, sym_cnt, i;
784 DWORD rva_base = pe->thunk->sh_addr - pe->imagebase;
785 int ndlls = pe->imp_count;
787 for (sym_cnt = i = 0; i < ndlls; ++i)
788 sym_cnt += pe->imp_info[i]->sym_count;
790 if (0 == sym_cnt)
791 return;
793 pe_align_section(pe->thunk, 16);
795 pe->imp_offs = dll_ptr = pe->thunk->data_offset;
796 pe->imp_size = (ndlls + 1) * sizeof(IMAGE_IMPORT_DESCRIPTOR);
797 pe->iat_offs = dll_ptr + pe->imp_size;
798 pe->iat_size = (sym_cnt + ndlls) * sizeof(ADDR3264);
799 section_ptr_add(pe->thunk, pe->imp_size + 2*pe->iat_size);
801 thk_ptr = pe->iat_offs;
802 ent_ptr = pe->iat_offs + pe->iat_size;
804 for (i = 0; i < pe->imp_count; ++i) {
805 IMAGE_IMPORT_DESCRIPTOR *hdr;
806 int k, n;
807 ADDR3264 v;
808 struct pe_import_info *p = pe->imp_info[i];
809 const char *name = pe->s1->loaded_dlls[p->dll_index-1]->name;
811 /* put the dll name into the import header */
812 v = put_elf_str(pe->thunk, name);
814 hdr = (IMAGE_IMPORT_DESCRIPTOR*)(pe->thunk->data + dll_ptr);
815 hdr->FirstThunk = thk_ptr + rva_base;
816 hdr->OriginalFirstThunk = ent_ptr + rva_base;
817 hdr->Name = v + rva_base;
819 for (k = 0, n = p->sym_count; k <= n; ++k) {
820 if (k < n) {
821 int iat_index = p->symbols[k]->iat_index;
822 int sym_index = p->symbols[k]->sym_index;
823 ElfW(Sym) *imp_sym = (ElfW(Sym) *)pe->s1->dynsymtab_section->data + sym_index;
824 ElfW(Sym) *org_sym = (ElfW(Sym) *)symtab_section->data + iat_index;
825 const char *name = pe->s1->dynsymtab_section->link->data + imp_sym->st_name;
827 org_sym->st_value = thk_ptr;
828 org_sym->st_shndx = pe->thunk->sh_num;
829 v = pe->thunk->data_offset + rva_base;
830 section_ptr_add(pe->thunk, sizeof(WORD)); /* hint, not used */
831 put_elf_str(pe->thunk, name);
832 #ifdef TCC_IS_NATIVE
833 if (pe->type == PE_RUN) {
834 DLLReference *dllref = pe->s1->loaded_dlls[imp_sym->st_value-1];
835 if ( !dllref->handle )
836 dllref->handle = LoadLibrary(dllref->name);
837 v = (ADDR3264)GetProcAddress(dllref->handle, name);
838 if (!v)
839 error_noabort("undefined symbol '%s'", name);
841 #endif
842 } else {
843 v = 0; /* last entry is zero */
845 *(ADDR3264*)(pe->thunk->data+thk_ptr) =
846 *(ADDR3264*)(pe->thunk->data+ent_ptr) = v;
847 thk_ptr += sizeof (ADDR3264);
848 ent_ptr += sizeof (ADDR3264);
850 dll_ptr += sizeof(IMAGE_IMPORT_DESCRIPTOR);
851 dynarray_reset(&p->symbols, &p->sym_count);
853 dynarray_reset(&pe->imp_info, &pe->imp_count);
856 /* ------------------------------------------------------------- */
858 For now only functions are exported. Export of data
859 would work, but import requires compiler support to
860 do an additional indirection.
862 For instance:
863 __declspec(dllimport) extern int something;
865 needs to be translated to:
867 *(int*)something
870 struct pe_sort_sym
872 int index;
873 const char *name;
876 ST_FN int sym_cmp(const void *va, const void *vb)
878 const char *ca = (*(struct pe_sort_sym**)va)->name;
879 const char *cb = (*(struct pe_sort_sym**)vb)->name;
880 return strcmp(ca, cb);
883 ST_FN void pe_build_exports(struct pe_info *pe)
885 ElfW(Sym) *sym;
886 int sym_index, sym_end;
887 DWORD rva_base, func_o, name_o, ord_o, str_o;
888 IMAGE_EXPORT_DIRECTORY *hdr;
889 int sym_count, ord;
890 struct pe_sort_sym **sorted, *p;
892 FILE *op;
893 char buf[MAX_PATH];
894 const char *dllname;
895 const char *name;
897 rva_base = pe->thunk->sh_addr - pe->imagebase;
898 sym_count = 0, sorted = NULL, op = NULL;
900 sym_end = symtab_section->data_offset / sizeof(ElfW(Sym));
901 for (sym_index = 1; sym_index < sym_end; ++sym_index) {
902 sym = (ElfW(Sym)*)symtab_section->data + sym_index;
903 name = symtab_section->link->data + sym->st_name;
904 if ((sym->st_other & 1)
905 /* export only symbols from actually written sections */
906 && pe->s1->sections[sym->st_shndx]->sh_addr) {
907 p = tcc_malloc(sizeof *p);
908 p->index = sym_index;
909 p->name = name;
910 dynarray_add((void***)&sorted, &sym_count, p);
912 #if 0
913 if (sym->st_other & 1)
914 printf("export: %s\n", name);
915 if (sym->st_other & 2)
916 printf("stdcall: %s\n", name);
917 #endif
920 if (0 == sym_count)
921 return;
923 qsort (sorted, sym_count, sizeof *sorted, sym_cmp);
925 pe_align_section(pe->thunk, 16);
926 dllname = tcc_basename(pe->filename);
928 pe->exp_offs = pe->thunk->data_offset;
929 func_o = pe->exp_offs + sizeof(IMAGE_EXPORT_DIRECTORY);
930 name_o = func_o + sym_count * sizeof (DWORD);
931 ord_o = name_o + sym_count * sizeof (DWORD);
932 str_o = ord_o + sym_count * sizeof(WORD);
934 hdr = section_ptr_add(pe->thunk, str_o - pe->exp_offs);
935 hdr->Characteristics = 0;
936 hdr->Base = 1;
937 hdr->NumberOfFunctions = sym_count;
938 hdr->NumberOfNames = sym_count;
939 hdr->AddressOfFunctions = func_o + rva_base;
940 hdr->AddressOfNames = name_o + rva_base;
941 hdr->AddressOfNameOrdinals = ord_o + rva_base;
942 hdr->Name = str_o + rva_base;
943 put_elf_str(pe->thunk, dllname);
945 #if 1
946 /* automatically write exports to <output-filename>.def */
947 strcpy(buf, pe->filename);
948 strcpy(tcc_fileextension(buf), ".def");
949 op = fopen(buf, "w");
950 if (NULL == op) {
951 error_noabort("could not create '%s': %s", buf, strerror(errno));
952 } else {
953 fprintf(op, "LIBRARY %s\n\nEXPORTS\n", dllname);
954 if (pe->s1->verbose)
955 printf("<- %s (%d symbols)\n", buf, sym_count);
957 #endif
959 for (ord = 0; ord < sym_count; ++ord)
961 p = sorted[ord], sym_index = p->index, name = p->name;
962 /* insert actual address later in pe_relocate_rva */
963 put_elf_reloc(symtab_section, pe->thunk,
964 func_o, R_XXX_RELATIVE, sym_index);
965 *(DWORD*)(pe->thunk->data + name_o)
966 = pe->thunk->data_offset + rva_base;
967 *(WORD*)(pe->thunk->data + ord_o)
968 = ord;
969 put_elf_str(pe->thunk, name);
970 func_o += sizeof (DWORD);
971 name_o += sizeof (DWORD);
972 ord_o += sizeof (WORD);
973 if (op)
974 fprintf(op, "%s\n", name);
976 pe->exp_size = pe->thunk->data_offset - pe->exp_offs;
977 dynarray_reset(&sorted, &sym_count);
978 if (op)
979 fclose(op);
982 /* ------------------------------------------------------------- */
983 ST_FN void pe_build_reloc (struct pe_info *pe)
985 DWORD offset, block_ptr, addr;
986 int count, i;
987 ElfW_Rel *rel, *rel_end;
988 Section *s = NULL, *sr;
990 offset = addr = block_ptr = count = i = 0;
991 rel = rel_end = NULL;
993 for(;;) {
994 if (rel < rel_end) {
995 int type = ELFW_R_(TYPE)(rel->r_info);
996 addr = rel->r_offset + s->sh_addr;
997 ++ rel;
998 if (type != REL_TYPE_DIRECT)
999 continue;
1000 if (count == 0) { /* new block */
1001 block_ptr = pe->reloc->data_offset;
1002 section_ptr_add(pe->reloc, sizeof(struct pe_reloc_header));
1003 offset = addr & 0xFFFFFFFF<<12;
1005 if ((addr -= offset) < (1<<12)) { /* one block spans 4k addresses */
1006 WORD *wp = section_ptr_add(pe->reloc, sizeof (WORD));
1007 *wp = addr | IMAGE_REL_BASED_HIGHLOW<<12;
1008 ++count;
1009 continue;
1011 -- rel;
1013 } else if (i < pe->sec_count) {
1014 sr = (s = pe->s1->sections[pe->sec_info[i++].ord])->reloc;
1015 if (sr) {
1016 rel = (ElfW_Rel *)sr->data;
1017 rel_end = (ElfW_Rel *)(sr->data + sr->data_offset);
1019 continue;
1022 if (count) {
1023 /* store the last block and ready for a new one */
1024 struct pe_reloc_header *hdr;
1025 if (count & 1) /* align for DWORDS */
1026 section_ptr_add(pe->reloc, sizeof(WORD)), ++count;
1027 hdr = (struct pe_reloc_header *)(pe->reloc->data + block_ptr);
1028 hdr -> offset = offset - pe->imagebase;
1029 hdr -> size = count * sizeof(WORD) + sizeof(struct pe_reloc_header);
1030 count = 0;
1033 if (rel >= rel_end)
1034 break;
1038 /* ------------------------------------------------------------- */
1039 ST_FN int pe_section_class(Section *s)
1041 int type, flags;
1042 const char *name;
1044 type = s->sh_type;
1045 flags = s->sh_flags;
1046 name = s->name;
1047 if (flags & SHF_ALLOC) {
1048 if (type == SHT_PROGBITS) {
1049 if (flags & SHF_EXECINSTR)
1050 return sec_text;
1051 if (flags & SHF_WRITE)
1052 return sec_data;
1053 if (0 == strcmp(name, ".rsrc"))
1054 return sec_rsrc;
1055 if (0 == strcmp(name, ".iedat"))
1056 return sec_idata;
1057 return sec_other;
1058 } else if (type == SHT_NOBITS) {
1059 if (flags & SHF_WRITE)
1060 return sec_bss;
1062 } else {
1063 if (0 == strcmp(name, ".reloc"))
1064 return sec_reloc;
1065 if (0 == strncmp(name, ".stab", 5)) /* .stab and .stabstr */
1066 return sec_stab;
1068 return -1;
1071 ST_FN int pe_assign_addresses (struct pe_info *pe)
1073 int i, k, o, c;
1074 DWORD addr;
1075 int *section_order;
1076 struct section_info *si;
1077 Section *s;
1079 // pe->thunk = new_section(pe->s1, ".iedat", SHT_PROGBITS, SHF_ALLOC);
1081 section_order = tcc_malloc(pe->s1->nb_sections * sizeof (int));
1082 for (o = k = 0 ; k < sec_last; ++k) {
1083 for (i = 1; i < pe->s1->nb_sections; ++i) {
1084 s = pe->s1->sections[i];
1085 if (k == pe_section_class(s)) {
1086 // printf("%s %d\n", s->name, k);
1087 s->sh_addr = pe->imagebase;
1088 section_order[o++] = i;
1093 pe->sec_info = tcc_mallocz(o * sizeof (struct section_info));
1094 addr = pe->imagebase + 1;
1096 for (i = 0; i < o; ++i)
1098 k = section_order[i];
1099 s = pe->s1->sections[k];
1100 c = pe_section_class(s);
1101 si = &pe->sec_info[pe->sec_count];
1103 #ifdef PE_MERGE_DATA
1104 if (c == sec_bss && pe->sec_count && si[-1].cls == sec_data) {
1105 /* append .bss to .data */
1106 s->sh_addr = addr = ((addr-1) | 15) + 1;
1107 addr += s->data_offset;
1108 si[-1].sh_size = addr - si[-1].sh_addr;
1109 continue;
1111 #endif
1112 strcpy(si->name, s->name);
1113 si->cls = c;
1114 si->ord = k;
1115 si->sh_addr = s->sh_addr = addr = pe_virtual_align(pe, addr);
1116 si->sh_flags = s->sh_flags;
1118 if (c == sec_data && NULL == pe->thunk)
1119 pe->thunk = s;
1121 if (s == pe->thunk) {
1122 pe_build_imports(pe);
1123 pe_build_exports(pe);
1126 if (c == sec_reloc)
1127 pe_build_reloc (pe);
1129 if (s->data_offset)
1131 if (s->sh_type != SHT_NOBITS) {
1132 si->data = s->data;
1133 si->data_size = s->data_offset;
1136 addr += s->data_offset;
1137 si->sh_size = s->data_offset;
1138 ++pe->sec_count;
1140 // printf("%08x %05x %s\n", si->sh_addr, si->sh_size, si->name);
1143 #if 0
1144 for (i = 1; i < pe->s1->nb_sections; ++i) {
1145 Section *s = pe->s1->sections[i];
1146 int type = s->sh_type;
1147 int flags = s->sh_flags;
1148 printf("section %-16s %-10s %5x %s,%s,%s\n",
1149 s->name,
1150 type == SHT_PROGBITS ? "progbits" :
1151 type == SHT_NOBITS ? "nobits" :
1152 type == SHT_SYMTAB ? "symtab" :
1153 type == SHT_STRTAB ? "strtab" :
1154 type == SHT_RELX ? "rel" : "???",
1155 s->data_offset,
1156 flags & SHF_ALLOC ? "alloc" : "",
1157 flags & SHF_WRITE ? "write" : "",
1158 flags & SHF_EXECINSTR ? "exec" : ""
1161 pe->s1->verbose = 2;
1162 #endif
1164 tcc_free(section_order);
1165 return 0;
1168 /* ------------------------------------------------------------- */
1169 ST_FN void pe_relocate_rva (struct pe_info *pe, Section *s)
1171 Section *sr = s->reloc;
1172 ElfW_Rel *rel, *rel_end;
1173 rel_end = (ElfW_Rel *)(sr->data + sr->data_offset);
1174 for(rel = (ElfW_Rel *)sr->data; rel < rel_end; rel++) {
1175 if (ELFW_R_(TYPE)(rel->r_info) == R_XXX_RELATIVE) {
1176 int sym_index = ELFW_R_(SYM)(rel->r_info);
1177 DWORD addr = s->sh_addr;
1178 if (sym_index) {
1179 ElfW(Sym) *sym = (ElfW(Sym) *)symtab_section->data + sym_index;
1180 addr = sym->st_value;
1182 // printf("reloc rva %08x %08x\n", (DWORD)rel->r_offset, addr);
1183 *(DWORD*)(s->data + rel->r_offset) += addr - pe->imagebase;
1188 /*----------------------------------------------------------------------------*/
1189 ST_FN int pe_check_symbols(struct pe_info *pe)
1191 ElfW(Sym) *sym;
1192 int sym_index, sym_end;
1193 int ret = 0;
1195 pe_align_section(text_section, 8);
1197 sym_end = symtab_section->data_offset / sizeof(ElfW(Sym));
1198 for (sym_index = 1; sym_index < sym_end; ++sym_index) {
1200 sym = (ElfW(Sym) *)symtab_section->data + sym_index;
1201 if (sym->st_shndx == SHN_UNDEF) {
1203 const char *name = symtab_section->link->data + sym->st_name;
1204 unsigned type = ELFW_ST_TYPE(sym->st_info);
1205 int imp_sym = pe_find_import(pe->s1, name);
1206 struct import_symbol *is;
1208 if (0 == imp_sym)
1209 goto not_found;
1210 is = pe_add_import(pe, imp_sym);
1211 if (!is)
1212 goto not_found;
1214 if (type == STT_FUNC) {
1215 unsigned long offset = is->thk_offset;
1216 if (offset) {
1217 /* got aliased symbol, like stricmp and _stricmp */
1219 } else {
1220 char buffer[100];
1221 WORD *p;
1223 offset = text_section->data_offset;
1224 /* add the 'jmp IAT[x]' instruction */
1225 p = section_ptr_add(text_section, 8);
1226 *p = 0x25FF;
1227 #ifdef TCC_TARGET_X86_64
1228 *(DWORD*)(p+1) = (DWORD)-4;
1229 #endif
1230 /* add a helper symbol, will be patched later in
1231 pe_build_imports */
1232 sprintf(buffer, "IAT.%s", name);
1233 is->iat_index = put_elf_sym(
1234 symtab_section, 0, sizeof(DWORD),
1235 ELFW_ST_INFO(STB_GLOBAL, STT_OBJECT),
1236 0, SHN_UNDEF, buffer);
1237 put_elf_reloc(symtab_section, text_section,
1238 offset + 2, R_XXX_THUNKFIX, is->iat_index);
1239 is->thk_offset = offset;
1242 /* tcc_realloc might have altered sym's address */
1243 sym = (ElfW(Sym) *)symtab_section->data + sym_index;
1245 /* patch the original symbol */
1246 sym->st_value = offset;
1247 sym->st_shndx = text_section->sh_num;
1248 sym->st_other &= ~1; /* do not export */
1249 continue;
1252 if (type == STT_OBJECT) { /* data, ptr to that should be */
1253 if (0 == is->iat_index) {
1254 /* original symbol will be patched later in pe_build_imports */
1255 is->iat_index = sym_index;
1256 continue;
1260 not_found:
1261 error_noabort("undefined symbol '%s'", name);
1262 ret = -1;
1264 } else if (pe->s1->rdynamic
1265 && ELFW_ST_BIND(sym->st_info) != STB_LOCAL) {
1266 /* if -rdynamic option, then export all non local symbols */
1267 sym->st_other |= 1;
1270 return ret;
1273 /*----------------------------------------------------------------------------*/
1274 #ifdef PE_PRINT_SECTIONS
1275 ST_FN void pe_print_section(FILE * f, Section * s)
1277 /* just if you'r curious */
1278 BYTE *p, *e, b;
1279 int i, n, l, m;
1280 p = s->data;
1281 e = s->data + s->data_offset;
1282 l = e - p;
1284 fprintf(f, "section \"%s\"", s->name);
1285 if (s->link)
1286 fprintf(f, "\nlink \"%s\"", s->link->name);
1287 if (s->reloc)
1288 fprintf(f, "\nreloc \"%s\"", s->reloc->name);
1289 fprintf(f, "\nv_addr %08X", (unsigned)s->sh_addr);
1290 fprintf(f, "\ncontents %08X", (unsigned)l);
1291 fprintf(f, "\n\n");
1293 if (s->sh_type == SHT_NOBITS)
1294 return;
1296 if (0 == l)
1297 return;
1299 if (s->sh_type == SHT_SYMTAB)
1300 m = sizeof(ElfW(Sym));
1301 else if (s->sh_type == SHT_RELX)
1302 m = sizeof(ElfW_Rel);
1303 else
1304 m = 16;
1306 fprintf(f, "%-8s", "offset");
1307 for (i = 0; i < m; ++i)
1308 fprintf(f, " %02x", i);
1309 n = 56;
1311 if (s->sh_type == SHT_SYMTAB || s->sh_type == SHT_RELX) {
1312 const char *fields1[] = {
1313 "name",
1314 "value",
1315 "size",
1316 "bind",
1317 "type",
1318 "other",
1319 "shndx",
1320 NULL
1323 const char *fields2[] = {
1324 "offs",
1325 "type",
1326 "symb",
1327 NULL
1330 const char **p;
1332 if (s->sh_type == SHT_SYMTAB)
1333 p = fields1, n = 106;
1334 else
1335 p = fields2, n = 58;
1337 for (i = 0; p[i]; ++i)
1338 fprintf(f, "%6s", p[i]);
1339 fprintf(f, " symbol");
1342 fprintf(f, "\n");
1343 for (i = 0; i < n; ++i)
1344 fprintf(f, "-");
1345 fprintf(f, "\n");
1347 for (i = 0; i < l;)
1349 fprintf(f, "%08X", i);
1350 for (n = 0; n < m; ++n) {
1351 if (n + i < l)
1352 fprintf(f, " %02X", p[i + n]);
1353 else
1354 fprintf(f, " ");
1357 if (s->sh_type == SHT_SYMTAB) {
1358 ElfW(Sym) *sym = (ElfW(Sym) *) (p + i);
1359 const char *name = s->link->data + sym->st_name;
1360 fprintf(f, " %04X %04X %04X %02X %02X %02X %04X \"%s\"",
1361 (unsigned)sym->st_name,
1362 (unsigned)sym->st_value,
1363 (unsigned)sym->st_size,
1364 (unsigned)ELFW_ST_BIND(sym->st_info),
1365 (unsigned)ELFW_ST_TYPE(sym->st_info),
1366 (unsigned)sym->st_other,
1367 (unsigned)sym->st_shndx,
1368 name);
1370 } else if (s->sh_type == SHT_RELX) {
1371 ElfW_Rel *rel = (ElfW_Rel *) (p + i);
1372 ElfW(Sym) *sym =
1373 (ElfW(Sym) *) s->link->data + ELFW_R_(SYM)(rel->r_info);
1374 const char *name = s->link->link->data + sym->st_name;
1375 fprintf(f, " %04X %02X %04X \"%s\"",
1376 (unsigned)rel->r_offset,
1377 (unsigned)ELFW_R_(TYPE)(rel->r_info),
1378 (unsigned)ELFW_R_(SYM)(rel->r_info),
1379 name);
1380 } else {
1381 fprintf(f, " ");
1382 for (n = 0; n < m; ++n) {
1383 if (n + i < l) {
1384 b = p[i + n];
1385 if (b < 32 || b >= 127)
1386 b = '.';
1387 fprintf(f, "%c", b);
1391 i += m;
1392 fprintf(f, "\n");
1394 fprintf(f, "\n\n");
1397 ST_FN void pe_print_sections(TCCState *s1, const char *fname)
1399 Section *s;
1400 FILE *f;
1401 int i;
1402 f = fopen(fname, "w");
1403 for (i = 1; i < s1->nb_sections; ++i) {
1404 s = s1->sections[i];
1405 pe_print_section(f, s);
1407 pe_print_section(f, s1->dynsymtab_section);
1408 fclose(f);
1410 #endif
1412 /* ------------------------------------------------------------- */
1414 ST_FN int read_mem(FILE *fp, unsigned offset, void *buffer, unsigned len)
1416 fseek(fp, offset, 0);
1417 return len == fread(buffer, 1, len, fp);
1420 /* -------------------------------------------------------------
1421 * This is for compiled windows resources in 'coff' format
1422 * as generated by 'windres.exe -O coff ...'.
1425 ST_FN int pe_load_res(TCCState *s1, FILE *fp)
1427 struct pe_rsrc_header hdr;
1428 Section *rsrc_section;
1429 int i, ret = -1;
1430 BYTE *ptr;
1431 unsigned offs;
1433 if (!read_mem(fp, 0, &hdr, sizeof hdr))
1434 goto quit;
1436 if (hdr.filehdr.Machine != 0x014C
1437 || hdr.filehdr.NumberOfSections != 1
1438 || strcmp(hdr.sectionhdr.Name, ".rsrc") != 0)
1439 goto quit;
1441 rsrc_section = new_section(s1, ".rsrc", SHT_PROGBITS, SHF_ALLOC);
1442 ptr = section_ptr_add(rsrc_section, hdr.sectionhdr.SizeOfRawData);
1443 offs = hdr.sectionhdr.PointerToRawData;
1444 if (!read_mem(fp, offs, ptr, hdr.sectionhdr.SizeOfRawData))
1445 goto quit;
1446 offs = hdr.sectionhdr.PointerToRelocations;
1447 for (i = 0; i < hdr.sectionhdr.NumberOfRelocations; ++i)
1449 struct pe_rsrc_reloc rel;
1450 if (!read_mem(fp, offs, &rel, sizeof rel))
1451 goto quit;
1452 // printf("rsrc_reloc: %x %x %x\n", rel.offset, rel.size, rel.type);
1453 if (rel.type != 7) /* DIR32NB */
1454 goto quit;
1455 put_elf_reloc(symtab_section, rsrc_section,
1456 rel.offset, R_XXX_RELATIVE, 0);
1457 offs += sizeof rel;
1459 ret = 0;
1460 quit:
1461 return ret;
1464 /* ------------------------------------------------------------- */
1465 ST_FN char *trimfront(char *p)
1467 while (*p && (unsigned char)*p <= ' ')
1468 ++p;
1469 return p;
1472 ST_FN char *trimback(char *a, char *e)
1474 while (e > a && (unsigned char)e[-1] <= ' ')
1475 --e;
1476 *e = 0;;
1477 return a;
1480 ST_FN char *get_line(char *line, int size, FILE *fp)
1482 if (NULL == fgets(line, size, fp))
1483 return NULL;
1484 trimback(line, strchr(line, 0));
1485 return trimfront(line);
1488 /* ------------------------------------------------------------- */
1489 ST_FN int pe_load_def(TCCState *s1, FILE *fp)
1491 DLLReference *dllref;
1492 int state = 0, ret = -1;
1493 char line[400], dllname[80], *p;
1495 for (;;) {
1496 p = get_line(line, sizeof line, fp);
1497 if (NULL == p)
1498 break;
1499 if (0 == *p || ';' == *p)
1500 continue;
1501 switch (state) {
1502 case 0:
1503 if (0 != strnicmp(p, "LIBRARY", 7))
1504 goto quit;
1505 strcpy(dllname, trimfront(p+7));
1506 ++state;
1507 continue;
1509 case 1:
1510 if (0 != stricmp(p, "EXPORTS"))
1511 goto quit;
1512 ++state;
1513 continue;
1515 case 2:
1516 dllref = tcc_mallocz(sizeof(DLLReference) + strlen(dllname));
1517 strcpy(dllref->name, dllname);
1518 dynarray_add((void ***) &s1->loaded_dlls, &s1->nb_loaded_dlls, dllref);
1519 ++state;
1521 default:
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, p);
1526 continue;
1529 ret = 0;
1530 quit:
1531 return ret;
1534 /* ------------------------------------------------------------- */
1535 #define TINY_IMPDEF_GET_EXPORT_NAMES_ONLY
1536 #include "win32/tools/tiny_impdef.c"
1538 ST_FN int pe_load_dll(TCCState *s1, const char *dllname, FILE *fp)
1540 int i = 0;
1541 char *p, *q;
1542 p = get_export_names(fp);
1543 if (p) {
1544 DLLReference *dllref;
1545 dllref = tcc_mallocz(sizeof(DLLReference) + strlen(dllname));
1546 strcpy(dllref->name, dllname);
1547 dynarray_add((void ***) &s1->loaded_dlls, &s1->nb_loaded_dlls, dllref);
1548 for (q = p, i = 0; *q; ++i) {
1549 add_elf_sym(s1->dynsymtab_section,
1550 s1->nb_loaded_dlls, 0,
1551 ELFW_ST_INFO(STB_GLOBAL, STT_FUNC), 0,
1552 text_section->sh_num, q);
1553 q += 1 + strlen(q);
1555 tcc_free(p);
1557 return i ? 0 : -1;
1560 /* ------------------------------------------------------------- */
1561 PUB_FN int pe_load_file(struct TCCState *s1, const char *filename, int fd)
1563 FILE *fp = fdopen(dup(fd), "rb");
1564 int ret = -1;
1565 char buf[10];
1566 if (fp) {
1567 if (0 == strcmp(tcc_fileextension(filename), ".def"))
1568 ret = pe_load_def(s1, fp);
1569 else if (pe_load_res(s1, fp) == 0)
1570 ret = 0;
1571 else if (read_mem(fp, 0, buf, sizeof buf) && 0 == strncmp(buf, "MZ", 2))
1572 ret = pe_load_dll(s1, tcc_basename(filename), fp);
1573 fclose(fp);
1575 return ret;
1578 int pe_add_dll(struct TCCState *s, const char *libraryname)
1580 char buf[MAX_PATH];
1581 snprintf(buf, sizeof(buf), "%s.def", libraryname);
1582 if (tcc_add_dll(s, buf, 0) == 0)
1583 return 0;
1584 snprintf(buf, sizeof(buf), "%s.dll", libraryname);
1585 if (tcc_add_dll(s, buf, 0) == 0)
1586 return 0;
1587 return -1;
1590 /* ------------------------------------------------------------- */
1591 #ifdef TCC_TARGET_X86_64
1592 #define PE_STDSYM(n,s) n
1593 #else
1594 #define PE_STDSYM(n,s) "_" n s
1595 #endif
1597 ST_FN void pe_add_runtime_ex(TCCState *s1, struct pe_info *pe)
1599 const char *start_symbol;
1600 unsigned long addr = 0;
1601 int pe_type = 0;
1603 if (find_elf_sym(symtab_section, PE_STDSYM("WinMain","@16")))
1604 pe_type = PE_GUI;
1605 else
1606 if (TCC_OUTPUT_DLL == s1->output_type) {
1607 pe_type = PE_DLL;
1608 /* need this for 'tccelf.c:relocate_section()' */
1609 s1->output_type = TCC_OUTPUT_EXE;
1612 start_symbol =
1613 TCC_OUTPUT_MEMORY == s1->output_type
1614 ? PE_GUI == pe_type ? "_runwinmain" : NULL
1615 : PE_DLL == pe_type ? PE_STDSYM("_dllstart","@12")
1616 : PE_GUI == pe_type ? "_winstart" : "_start"
1619 /* grab the startup code from libtcc1 */
1620 if (start_symbol)
1621 add_elf_sym(symtab_section,
1622 0, 0,
1623 ELFW_ST_INFO(STB_GLOBAL, STT_NOTYPE), 0,
1624 SHN_UNDEF, start_symbol);
1626 if (0 == s1->nostdlib) {
1627 static const char *libs[] = {
1628 "tcc1", "msvcrt", "kernel32", "", "user32", "gdi32", NULL
1630 const char **pp, *p;
1631 for (pp = libs; 0 != (p = *pp); ++pp) {
1632 if (0 == *p) {
1633 if (PE_DLL != pe_type && PE_GUI != pe_type)
1634 break;
1635 } else if (tcc_add_library(s1, p) < 0)
1636 error_noabort("cannot find library: %s", p);
1640 if (start_symbol) {
1641 addr = (uplong)tcc_get_symbol_err(s1, start_symbol);
1642 if (s1->output_type == TCC_OUTPUT_MEMORY && addr)
1643 /* for -run GUI's, put '_runwinmain' instead of 'main' */
1644 add_elf_sym(symtab_section,
1645 addr, 0,
1646 ELFW_ST_INFO(STB_GLOBAL, STT_NOTYPE), 0,
1647 text_section->sh_num, "main");
1650 pe->type = pe_type;
1651 pe->start_addr = addr;
1654 PUB_FN int pe_output_file(TCCState * s1, const char *filename)
1656 int ret;
1657 struct pe_info pe;
1658 int i;
1660 memset(&pe, 0, sizeof pe);
1661 pe.filename = filename;
1662 pe.s1 = s1;
1664 pe_add_runtime_ex(s1, &pe);
1665 relocate_common_syms(); /* assign bss adresses */
1666 tcc_add_linker_symbols(s1);
1668 ret = pe_check_symbols(&pe);
1669 if (ret)
1670 return ret;
1672 if (filename) {
1673 if (PE_DLL == pe.type) {
1674 pe.reloc = new_section(pe.s1, ".reloc", SHT_PROGBITS, 0);
1675 /* XXX: check if is correct for arm-pe target */
1676 pe.imagebase = 0x10000000;
1677 } else {
1678 #if defined(TCC_TARGET_ARM)
1679 pe.imagebase = 0x00010000;
1680 #else
1681 pe.imagebase = 0x00400000;
1682 #endif
1685 /* if no subsystem specified, we use "console" subsystem by default */
1686 if (s1->pe_subsystem != 0)
1687 pe.subsystem = s1->pe_subsystem;
1688 else
1689 #if defined(TCC_TARGET_ARM)
1690 pe.subsystem = 3;
1691 #else
1692 pe.subsystem = 9;
1693 #endif
1694 /* set default file/section alignment */
1695 if (pe.subsystem == 1) {
1696 pe.section_align = 0x20;
1697 pe.file_align = 0x20;
1698 } else {
1699 pe.section_align = 0x1000;
1700 pe.file_align = 0x200;
1703 if (s1->section_align != 0)
1704 pe.section_align = s1->section_align;
1705 if (s1->pe_file_align != 0)
1706 pe.file_align = s1->pe_file_align;
1708 if ((pe.subsystem >= 10) && (pe.subsystem <= 12))
1709 pe.imagebase = 0;
1711 if (s1->has_text_addr)
1712 pe.imagebase = s1->text_addr;
1714 pe_assign_addresses(&pe);
1715 relocate_syms(s1, 0);
1716 for (i = 1; i < s1->nb_sections; ++i) {
1717 Section *s = s1->sections[i];
1718 if (s->reloc) {
1719 relocate_section(s1, s);
1720 pe_relocate_rva(&pe, s);
1723 if (s1->nb_errors)
1724 ret = -1;
1725 else
1726 ret = pe_write(&pe);
1727 tcc_free(pe.sec_info);
1728 } else {
1729 #ifndef TCC_IS_NATIVE
1730 error_noabort("-run supported only on native platform");
1731 #endif
1732 pe.type = PE_RUN;
1733 pe.thunk = data_section;
1734 pe_build_imports(&pe);
1737 #ifdef PE_PRINT_SECTIONS
1738 pe_print_sections(s1, "tcc.log");
1739 #endif
1740 return ret;
1743 /* ------------------------------------------------------------- */
1744 #endif /* def TCC_TARGET_PE */
1745 /* ------------------------------------------------------------- */