allow tcc be build from separate objects
[tinycc.git] / tccpe.c
blob1b2724d6a387fcd2aacc48bc8a055c03cbdb5c1e
1 /*
2 * TCCPE.C - PE file output for the Tiny C Compiler
4 * Copyright (c) 2005-2007 grischka
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
21 #include "tcc.h"
23 #ifndef _WIN32
24 #define stricmp strcasecmp
25 #define strnicmp strncasecmp
26 #endif
28 #ifndef MAX_PATH
29 #define MAX_PATH 260
30 #endif
32 #define PE_MERGE_DATA
33 // #define PE_PRINT_SECTIONS
35 #ifdef TCC_TARGET_X86_64
36 # define ADDR3264 ULONGLONG
37 #else
38 # define ADDR3264 DWORD
39 #endif
41 #if defined _WIN32 && (defined _WIN64) == (defined TCC_TARGET_X86_64)
42 #define TCC_IS_NATIVE
43 #endif
45 #ifdef _WIN32
46 void dbg_printf (const char *fmt, ...)
48 char buffer[4000];
49 va_list arg;
50 int x;
51 va_start(arg, fmt);
52 x = vsprintf (buffer, fmt, arg);
53 strcpy(buffer+x, "\n");
54 OutputDebugString(buffer);
56 #endif
58 /* ----------------------------------------------------------- */
59 #ifndef IMAGE_NT_SIGNATURE
60 /* ----------------------------------------------------------- */
61 /* definitions below are from winnt.h */
63 typedef unsigned char BYTE;
64 typedef unsigned short WORD;
65 typedef unsigned long DWORD;
66 typedef unsigned long long ULONGLONG;
67 #pragma pack(push, 1)
69 typedef struct _IMAGE_DOS_HEADER { /* DOS .EXE header */
70 WORD e_magic; /* Magic number */
71 WORD e_cblp; /* Bytes on last page of file */
72 WORD e_cp; /* Pages in file */
73 WORD e_crlc; /* Relocations */
74 WORD e_cparhdr; /* Size of header in paragraphs */
75 WORD e_minalloc; /* Minimum extra paragraphs needed */
76 WORD e_maxalloc; /* Maximum extra paragraphs needed */
77 WORD e_ss; /* Initial (relative) SS value */
78 WORD e_sp; /* Initial SP value */
79 WORD e_csum; /* Checksum */
80 WORD e_ip; /* Initial IP value */
81 WORD e_cs; /* Initial (relative) CS value */
82 WORD e_lfarlc; /* File address of relocation table */
83 WORD e_ovno; /* Overlay number */
84 WORD e_res[4]; /* Reserved words */
85 WORD e_oemid; /* OEM identifier (for e_oeminfo) */
86 WORD e_oeminfo; /* OEM information; e_oemid specific */
87 WORD e_res2[10]; /* Reserved words */
88 DWORD e_lfanew; /* File address of new exe header */
89 } IMAGE_DOS_HEADER, *PIMAGE_DOS_HEADER;
91 #define IMAGE_NT_SIGNATURE 0x00004550 /* PE00 */
92 #define SIZE_OF_NT_SIGNATURE 4
94 typedef struct _IMAGE_FILE_HEADER {
95 WORD Machine;
96 WORD NumberOfSections;
97 DWORD TimeDateStamp;
98 DWORD PointerToSymbolTable;
99 DWORD NumberOfSymbols;
100 WORD SizeOfOptionalHeader;
101 WORD Characteristics;
102 } IMAGE_FILE_HEADER, *PIMAGE_FILE_HEADER;
105 #define IMAGE_SIZEOF_FILE_HEADER 20
107 typedef struct _IMAGE_DATA_DIRECTORY {
108 DWORD VirtualAddress;
109 DWORD Size;
110 } IMAGE_DATA_DIRECTORY, *PIMAGE_DATA_DIRECTORY;
113 typedef struct _IMAGE_OPTIONAL_HEADER {
114 /* Standard fields. */
115 WORD Magic;
116 BYTE MajorLinkerVersion;
117 BYTE MinorLinkerVersion;
118 DWORD SizeOfCode;
119 DWORD SizeOfInitializedData;
120 DWORD SizeOfUninitializedData;
121 DWORD AddressOfEntryPoint;
122 DWORD BaseOfCode;
123 #ifndef TCC_TARGET_X86_64
124 DWORD BaseOfData;
125 #endif
126 /* NT additional fields. */
127 ADDR3264 ImageBase;
128 DWORD SectionAlignment;
129 DWORD FileAlignment;
130 WORD MajorOperatingSystemVersion;
131 WORD MinorOperatingSystemVersion;
132 WORD MajorImageVersion;
133 WORD MinorImageVersion;
134 WORD MajorSubsystemVersion;
135 WORD MinorSubsystemVersion;
136 DWORD Win32VersionValue;
137 DWORD SizeOfImage;
138 DWORD SizeOfHeaders;
139 DWORD CheckSum;
140 WORD Subsystem;
141 WORD DllCharacteristics;
142 ADDR3264 SizeOfStackReserve;
143 ADDR3264 SizeOfStackCommit;
144 ADDR3264 SizeOfHeapReserve;
145 ADDR3264 SizeOfHeapCommit;
146 DWORD LoaderFlags;
147 DWORD NumberOfRvaAndSizes;
148 IMAGE_DATA_DIRECTORY DataDirectory[16];
149 } IMAGE_OPTIONAL_HEADER32, IMAGE_OPTIONAL_HEADER64, IMAGE_OPTIONAL_HEADER;
151 #define IMAGE_DIRECTORY_ENTRY_EXPORT 0 /* Export Directory */
152 #define IMAGE_DIRECTORY_ENTRY_IMPORT 1 /* Import Directory */
153 #define IMAGE_DIRECTORY_ENTRY_RESOURCE 2 /* Resource Directory */
154 #define IMAGE_DIRECTORY_ENTRY_EXCEPTION 3 /* Exception Directory */
155 #define IMAGE_DIRECTORY_ENTRY_SECURITY 4 /* Security Directory */
156 #define IMAGE_DIRECTORY_ENTRY_BASERELOC 5 /* Base Relocation Table */
157 #define IMAGE_DIRECTORY_ENTRY_DEBUG 6 /* Debug Directory */
158 /* IMAGE_DIRECTORY_ENTRY_COPYRIGHT 7 (X86 usage) */
159 #define IMAGE_DIRECTORY_ENTRY_ARCHITECTURE 7 /* Architecture Specific Data */
160 #define IMAGE_DIRECTORY_ENTRY_GLOBALPTR 8 /* RVA of GP */
161 #define IMAGE_DIRECTORY_ENTRY_TLS 9 /* TLS Directory */
162 #define IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG 10 /* Load Configuration Directory */
163 #define IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT 11 /* Bound Import Directory in headers */
164 #define IMAGE_DIRECTORY_ENTRY_IAT 12 /* Import Address Table */
165 #define IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT 13 /* Delay Load Import Descriptors */
166 #define IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR 14 /* COM Runtime descriptor */
168 /* Section header format. */
169 #define IMAGE_SIZEOF_SHORT_NAME 8
171 typedef struct _IMAGE_SECTION_HEADER {
172 BYTE Name[IMAGE_SIZEOF_SHORT_NAME];
173 union {
174 DWORD PhysicalAddress;
175 DWORD VirtualSize;
176 } Misc;
177 DWORD VirtualAddress;
178 DWORD SizeOfRawData;
179 DWORD PointerToRawData;
180 DWORD PointerToRelocations;
181 DWORD PointerToLinenumbers;
182 WORD NumberOfRelocations;
183 WORD NumberOfLinenumbers;
184 DWORD Characteristics;
185 } IMAGE_SECTION_HEADER, *PIMAGE_SECTION_HEADER;
187 #define IMAGE_SIZEOF_SECTION_HEADER 40
189 typedef struct _IMAGE_EXPORT_DIRECTORY {
190 DWORD Characteristics;
191 DWORD TimeDateStamp;
192 WORD MajorVersion;
193 WORD MinorVersion;
194 DWORD Name;
195 DWORD Base;
196 DWORD NumberOfFunctions;
197 DWORD NumberOfNames;
198 DWORD AddressOfFunctions;
199 DWORD AddressOfNames;
200 DWORD AddressOfNameOrdinals;
201 } IMAGE_EXPORT_DIRECTORY,*PIMAGE_EXPORT_DIRECTORY;
203 typedef struct _IMAGE_IMPORT_DESCRIPTOR {
204 union {
205 DWORD Characteristics;
206 DWORD OriginalFirstThunk;
208 DWORD TimeDateStamp;
209 DWORD ForwarderChain;
210 DWORD Name;
211 DWORD FirstThunk;
212 } IMAGE_IMPORT_DESCRIPTOR;
214 typedef struct _IMAGE_BASE_RELOCATION {
215 DWORD VirtualAddress;
216 DWORD SizeOfBlock;
217 // WORD TypeOffset[1];
218 } IMAGE_BASE_RELOCATION;
220 #define IMAGE_SIZEOF_BASE_RELOCATION 8
222 #define IMAGE_REL_BASED_ABSOLUTE 0
223 #define IMAGE_REL_BASED_HIGH 1
224 #define IMAGE_REL_BASED_LOW 2
225 #define IMAGE_REL_BASED_HIGHLOW 3
226 #define IMAGE_REL_BASED_HIGHADJ 4
227 #define IMAGE_REL_BASED_MIPS_JMPADDR 5
228 #define IMAGE_REL_BASED_SECTION 6
229 #define IMAGE_REL_BASED_REL32 7
231 #pragma pack(pop)
233 /* ----------------------------------------------------------- */
234 #endif /* ndef IMAGE_NT_SIGNATURE */
235 /* ----------------------------------------------------------- */
236 #pragma pack(push, 1)
238 struct pe_header
240 IMAGE_DOS_HEADER doshdr;
241 BYTE dosstub[0x40];
242 DWORD nt_sig;
243 IMAGE_FILE_HEADER filehdr;
244 #ifdef TCC_TARGET_X86_64
245 IMAGE_OPTIONAL_HEADER64 opthdr;
246 #else
247 #ifdef _WIN64
248 IMAGE_OPTIONAL_HEADER32 opthdr;
249 #else
250 IMAGE_OPTIONAL_HEADER opthdr;
251 #endif
252 #endif
255 struct pe_reloc_header {
256 DWORD offset;
257 DWORD size;
260 struct pe_rsrc_header {
261 struct _IMAGE_FILE_HEADER filehdr;
262 struct _IMAGE_SECTION_HEADER sectionhdr;
265 struct pe_rsrc_reloc {
266 DWORD offset;
267 DWORD size;
268 WORD type;
271 #pragma pack(pop)
273 /* ------------------------------------------------------------- */
274 /* internal temporary structures */
277 #define IMAGE_SCN_CNT_CODE 0x00000020
278 #define IMAGE_SCN_CNT_INITIALIZED_DATA 0x00000040
279 #define IMAGE_SCN_CNT_UNINITIALIZED_DATA 0x00000080
280 #define IMAGE_SCN_MEM_DISCARDABLE 0x02000000
281 #define IMAGE_SCN_MEM_SHARED 0x10000000
282 #define IMAGE_SCN_MEM_EXECUTE 0x20000000
283 #define IMAGE_SCN_MEM_READ 0x40000000
284 #define IMAGE_SCN_MEM_WRITE 0x80000000
287 enum {
288 sec_text = 0,
289 sec_data ,
290 sec_bss ,
291 sec_idata ,
292 sec_other ,
293 sec_rsrc ,
294 sec_stab ,
295 sec_reloc ,
296 sec_last
299 static const DWORD pe_sec_flags[] = {
300 0x60000020, /* ".text" , */
301 0xC0000040, /* ".data" , */
302 0xC0000080, /* ".bss" , */
303 0x40000040, /* ".idata" , */
304 0xE0000060, /* < other > , */
305 0x40000040, /* ".rsrc" , */
306 0x42000802, /* ".stab" , */
307 0x42000040, /* ".reloc" , */
310 struct section_info {
311 int cls, ord;
312 char name[32];
313 DWORD sh_addr;
314 DWORD sh_size;
315 DWORD sh_flags;
316 unsigned char *data;
317 DWORD data_size;
318 IMAGE_SECTION_HEADER ish;
321 struct import_symbol {
322 int sym_index;
323 int iat_index;
324 int thk_offset;
327 struct pe_import_info {
328 int dll_index;
329 int sym_count;
330 struct import_symbol **symbols;
333 struct pe_info {
334 TCCState *s1;
335 Section *reloc;
336 Section *thunk;
337 const char *filename;
338 int type;
339 DWORD sizeofheaders;
340 DWORD imagebase;
341 DWORD start_addr;
342 DWORD imp_offs;
343 DWORD imp_size;
344 DWORD iat_offs;
345 DWORD iat_size;
346 DWORD exp_offs;
347 DWORD exp_size;
348 int subsystem;
349 DWORD section_align;
350 DWORD file_align;
351 struct section_info *sec_info;
352 int sec_count;
353 struct pe_import_info **imp_info;
354 int imp_count;
357 #define PE_NUL 0
358 #define PE_DLL 1
359 #define PE_GUI 2
360 #define PE_EXE 3
361 #define PE_RUN 4
363 /* --------------------------------------------*/
365 static const char* get_alt_symbol(char *buffer, const char *symbol)
367 const char *p;
368 p = strrchr(symbol, '@');
369 if (p && isnum(p[1]) && symbol[0] == '_') { /* stdcall decor */
370 strcpy(buffer, symbol+1)[p-symbol-1] = 0;
371 } else if (symbol[0] != '_') { /* try non-ansi function */
372 buffer[0] = '_', strcpy(buffer + 1, symbol);
373 } else if (0 == memcmp(symbol, "__imp__", 7)) { /* mingw 2.0 */
374 strcpy(buffer, symbol + 6);
375 } else if (0 == memcmp(symbol, "_imp___", 7)) { /* mingw 3.7 */
376 strcpy(buffer, symbol + 6);
377 } else {
378 return symbol;
380 return buffer;
383 static int pe_find_import(TCCState * s1, const char *symbol)
385 char buffer[200];
386 const char *s;
387 int sym_index, n = 0;
388 do {
389 s = n ? get_alt_symbol(buffer, symbol) : symbol;
390 sym_index = find_elf_sym(s1->dynsymtab_section, s);
391 // printf("find (%d) %d %s\n", n, sym_index, s);
392 } while (0 == sym_index && ++n < 2);
393 return sym_index;
396 /*----------------------------------------------------------------------------*/
398 static int dynarray_assoc(void **pp, int n, int key)
400 int i;
401 for (i = 0; i < n; ++i, ++pp)
402 if (key == **(int **) pp)
403 return i;
404 return -1;
407 #if 0
408 ST_FN DWORD umin(DWORD a, DWORD b)
410 return a < b ? a : b;
412 #endif
414 static DWORD umax(DWORD a, DWORD b)
416 return a < b ? b : a;
419 static DWORD pe_file_align(struct pe_info *pe, DWORD n)
421 return (n + (pe->file_align - 1)) & ~(pe->file_align - 1);
424 static DWORD pe_virtual_align(struct pe_info *pe, DWORD n)
426 return (n + (pe->section_align - 1)) & ~(pe->section_align - 1);
429 static void pe_align_section(Section *s, int a)
431 int i = s->data_offset & (a-1);
432 if (i)
433 section_ptr_add(s, a - i);
436 static void pe_set_datadir(struct pe_header *hdr, int dir, DWORD addr, DWORD size)
438 hdr->opthdr.DataDirectory[dir].VirtualAddress = addr;
439 hdr->opthdr.DataDirectory[dir].Size = size;
442 static int pe_fwrite(void *data, unsigned len, FILE *fp, DWORD *psum)
444 if (psum) {
445 DWORD sum = *psum;
446 WORD *p = data;
447 int i;
448 for (i = len; i > 0; i -= 2) {
449 sum += (i >= 2) ? *p++ : *(BYTE*)p;
450 sum = (sum + (sum >> 16)) & 0xFFFF;
452 *psum = sum;
454 return len == fwrite(data, 1, len, fp) ? 0 : -1;
457 static void pe_fpad(FILE *fp, DWORD new_pos)
459 DWORD pos = ftell(fp);
460 while (++pos <= new_pos)
461 fputc(0, fp);
464 /*----------------------------------------------------------------------------*/
465 static int pe_write(struct pe_info *pe)
467 static const struct pe_header pe_template = {
469 /* IMAGE_DOS_HEADER doshdr */
470 0x5A4D, /*WORD e_magic; Magic number */
471 0x0090, /*WORD e_cblp; Bytes on last page of file */
472 0x0003, /*WORD e_cp; Pages in file */
473 0x0000, /*WORD e_crlc; Relocations */
475 0x0004, /*WORD e_cparhdr; Size of header in paragraphs */
476 0x0000, /*WORD e_minalloc; Minimum extra paragraphs needed */
477 0xFFFF, /*WORD e_maxalloc; Maximum extra paragraphs needed */
478 0x0000, /*WORD e_ss; Initial (relative) SS value */
480 0x00B8, /*WORD e_sp; Initial SP value */
481 0x0000, /*WORD e_csum; Checksum */
482 0x0000, /*WORD e_ip; Initial IP value */
483 0x0000, /*WORD e_cs; Initial (relative) CS value */
484 0x0040, /*WORD e_lfarlc; File address of relocation table */
485 0x0000, /*WORD e_ovno; Overlay number */
486 {0,0,0,0}, /*WORD e_res[4]; Reserved words */
487 0x0000, /*WORD e_oemid; OEM identifier (for e_oeminfo) */
488 0x0000, /*WORD e_oeminfo; OEM information; e_oemid specific */
489 {0,0,0,0,0,0,0,0,0,0}, /*WORD e_res2[10]; Reserved words */
490 0x00000080 /*DWORD e_lfanew; File address of new exe header */
492 /* BYTE dosstub[0x40] */
493 /* 14 code bytes + "This program cannot be run in DOS mode.\r\r\n$" + 6 * 0x00 */
494 0x0e,0x1f,0xba,0x0e,0x00,0xb4,0x09,0xcd,0x21,0xb8,0x01,0x4c,0xcd,0x21,0x54,0x68,
495 0x69,0x73,0x20,0x70,0x72,0x6f,0x67,0x72,0x61,0x6d,0x20,0x63,0x61,0x6e,0x6e,0x6f,
496 0x74,0x20,0x62,0x65,0x20,0x72,0x75,0x6e,0x20,0x69,0x6e,0x20,0x44,0x4f,0x53,0x20,
497 0x6d,0x6f,0x64,0x65,0x2e,0x0d,0x0d,0x0a,0x24,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
499 0x00004550, /* DWORD nt_sig = IMAGE_NT_SIGNATURE */
501 /* IMAGE_FILE_HEADER filehdr */
502 #if defined(TCC_TARGET_I386)
503 0x014C, /*WORD Machine; */
504 #elif defined(TCC_TARGET_X86_64)
505 0x8664, /*WORD Machine; */
506 #elif defined(TCC_TARGET_ARM)
507 0x01C0, /*WORD Machine; */
508 #endif
509 0x0003, /*WORD NumberOfSections; */
510 0x00000000, /*DWORD TimeDateStamp; */
511 0x00000000, /*DWORD PointerToSymbolTable; */
512 0x00000000, /*DWORD NumberOfSymbols; */
513 #if defined(TCC_TARGET_X86_64)
514 0x00F0, /*WORD SizeOfOptionalHeader; */
515 0x022F /*WORD Characteristics; */
516 #define CHARACTERISTICS_DLL 0x222E
517 #elif defined(TCC_TARGET_I386)
518 0x00E0, /*WORD SizeOfOptionalHeader; */
519 0x030F /*WORD Characteristics; */
520 #define CHARACTERISTICS_DLL 0x230E
521 #elif defined(TCC_TARGET_ARM)
522 0x00E0, /*WORD SizeOfOptionalHeader; */
523 0x010F, /*WORD Characteristics; */
524 #define CHARACTERISTICS_DLL 0x230F
525 #endif
527 /* IMAGE_OPTIONAL_HEADER opthdr */
528 /* Standard fields. */
529 #ifdef TCC_TARGET_X86_64
530 0x020B, /*WORD Magic; */
531 #else
532 0x010B, /*WORD Magic; */
533 #endif
534 0x06, /*BYTE MajorLinkerVersion; */
535 0x00, /*BYTE MinorLinkerVersion; */
536 0x00000000, /*DWORD SizeOfCode; */
537 0x00000000, /*DWORD SizeOfInitializedData; */
538 0x00000000, /*DWORD SizeOfUninitializedData; */
539 0x00000000, /*DWORD AddressOfEntryPoint; */
540 0x00000000, /*DWORD BaseOfCode; */
541 #ifndef TCC_TARGET_X86_64
542 0x00000000, /*DWORD BaseOfData; */
543 #endif
544 /* NT additional fields. */
545 #if defined(TCC_TARGET_ARM)
546 0x00100000, /*DWORD ImageBase; */
547 #else
548 0x00400000, /*DWORD ImageBase; */
549 #endif
550 0x00001000, /*DWORD SectionAlignment; */
551 0x00000200, /*DWORD FileAlignment; */
552 0x0004, /*WORD MajorOperatingSystemVersion; */
553 0x0000, /*WORD MinorOperatingSystemVersion; */
554 0x0000, /*WORD MajorImageVersion; */
555 0x0000, /*WORD MinorImageVersion; */
556 0x0004, /*WORD MajorSubsystemVersion; */
557 0x0000, /*WORD MinorSubsystemVersion; */
558 0x00000000, /*DWORD Win32VersionValue; */
559 0x00000000, /*DWORD SizeOfImage; */
560 0x00000200, /*DWORD SizeOfHeaders; */
561 0x00000000, /*DWORD CheckSum; */
562 0x0002, /*WORD Subsystem; */
563 0x0000, /*WORD DllCharacteristics; */
564 0x00100000, /*DWORD SizeOfStackReserve; */
565 0x00001000, /*DWORD SizeOfStackCommit; */
566 0x00100000, /*DWORD SizeOfHeapReserve; */
567 0x00001000, /*DWORD SizeOfHeapCommit; */
568 0x00000000, /*DWORD LoaderFlags; */
569 0x00000010, /*DWORD NumberOfRvaAndSizes; */
571 /* IMAGE_DATA_DIRECTORY DataDirectory[16]; */
572 {{0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0},
573 {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}}
576 struct pe_header pe_header = pe_template;
578 int i;
579 FILE *op;
580 DWORD file_offset, sum;
581 struct section_info *si;
582 IMAGE_SECTION_HEADER *psh;
584 op = fopen(pe->filename, "wb");
585 if (NULL == op) {
586 error_noabort("could not write '%s': %s", pe->filename, strerror(errno));
587 return -1;
590 pe->sizeofheaders = pe_file_align(pe,
591 sizeof (struct pe_header)
592 + pe->sec_count * sizeof (IMAGE_SECTION_HEADER)
595 file_offset = pe->sizeofheaders;
597 if (2 == pe->s1->verbose)
598 printf("-------------------------------"
599 "\n virt file size section" "\n");
600 for (i = 0; i < pe->sec_count; ++i) {
601 unsigned long addr, size;
602 const char *sh_name;
604 si = pe->sec_info + i;
605 sh_name = si->name;
606 addr = si->sh_addr - pe->imagebase;
607 size = si->sh_size;
608 psh = &si->ish;
610 if (2 == pe->s1->verbose)
611 printf("%6lx %6lx %6lx %s\n",
612 addr, file_offset, size, sh_name);
614 switch (si->cls) {
615 case sec_text:
616 pe_header.opthdr.BaseOfCode = addr;
617 pe_header.opthdr.AddressOfEntryPoint = addr + pe->start_addr;
618 break;
620 case sec_data:
621 #ifndef TCC_TARGET_X86_64
622 pe_header.opthdr.BaseOfData = addr;
623 #endif
624 break;
626 case sec_bss:
627 break;
629 case sec_reloc:
630 pe_set_datadir(&pe_header, IMAGE_DIRECTORY_ENTRY_BASERELOC, addr, size);
631 break;
633 case sec_rsrc:
634 pe_set_datadir(&pe_header, IMAGE_DIRECTORY_ENTRY_RESOURCE, addr, size);
635 break;
637 case sec_stab:
638 break;
641 if (pe->thunk == pe->s1->sections[si->ord]) {
642 if (pe->imp_size) {
643 pe_set_datadir(&pe_header, IMAGE_DIRECTORY_ENTRY_IMPORT,
644 pe->imp_offs + addr, pe->imp_size);
645 pe_set_datadir(&pe_header, IMAGE_DIRECTORY_ENTRY_IAT,
646 pe->iat_offs + addr, pe->iat_size);
648 if (pe->exp_size) {
649 pe_set_datadir(&pe_header, IMAGE_DIRECTORY_ENTRY_EXPORT,
650 pe->exp_offs + addr, pe->exp_size);
654 strcpy((char*)psh->Name, sh_name);
656 psh->Characteristics = pe_sec_flags[si->cls];
657 psh->VirtualAddress = addr;
658 psh->Misc.VirtualSize = size;
659 pe_header.opthdr.SizeOfImage =
660 umax(pe_virtual_align(pe, size + addr), pe_header.opthdr.SizeOfImage);
662 if (si->data_size) {
663 psh->PointerToRawData = file_offset;
664 file_offset = pe_file_align(pe, file_offset + si->data_size);
665 psh->SizeOfRawData = file_offset - psh->PointerToRawData;
669 //pe_header.filehdr.TimeDateStamp = time(NULL);
670 pe_header.filehdr.NumberOfSections = pe->sec_count;
671 pe_header.opthdr.SizeOfHeaders = pe->sizeofheaders;
672 pe_header.opthdr.ImageBase = pe->imagebase;
673 if (PE_DLL == pe->type)
674 pe_header.filehdr.Characteristics = CHARACTERISTICS_DLL;
675 else if (PE_GUI != pe->type)
676 pe_header.opthdr.Subsystem = 3;
678 sum = 0;
679 pe_fwrite(&pe_header, sizeof pe_header, op, &sum);
680 for (i = 0; i < pe->sec_count; ++i)
681 pe_fwrite(&pe->sec_info[i].ish, sizeof(IMAGE_SECTION_HEADER), op, &sum);
682 pe_fpad(op, pe->sizeofheaders);
683 for (i = 0; i < pe->sec_count; ++i) {
684 si = pe->sec_info + i;
685 psh = &si->ish;
686 if (si->data_size) {
687 pe_fwrite(si->data, si->data_size, op, &sum);
688 file_offset = psh->PointerToRawData + psh->SizeOfRawData;
689 pe_fpad(op, file_offset);
693 pe_header.opthdr.CheckSum = sum + file_offset;
694 fseek(op, offsetof(struct pe_header, opthdr.CheckSum), SEEK_SET);
695 pe_fwrite(&pe_header.opthdr.CheckSum, sizeof pe_header.opthdr.CheckSum, op, NULL);
696 fclose (op);
698 if (2 == pe->s1->verbose)
699 printf("-------------------------------\n");
700 if (pe->s1->verbose)
701 printf("<- %s (%lu bytes)\n", pe->filename, file_offset);
703 return 0;
706 /*----------------------------------------------------------------------------*/
708 #if defined(TCC_TARGET_X86_64)
709 #define ELFW_R_(type) ELF64_R_##type
710 #define ElfW_Rel ElfW(Rela)
712 #define REL_TYPE_DIRECT R_X86_64_64
713 #define R_XXX_THUNKFIX R_X86_64_PC32
714 #define R_XXX_RELATIVE R_X86_64_RELATIVE
716 #define ELFW_ST_BIND ELF64_ST_BIND
717 #define ELFW_ST_TYPE ELF64_ST_TYPE
718 #define ELFW_ST_INFO ELF64_ST_INFO
719 #elif defined(TCC_TARGET_I386)
720 #define ELFW_R_(type) ELF32_R_##type
721 #define ElfW_Rel ElfW(Rel)
723 #define REL_TYPE_DIRECT R_386_32
724 #define R_XXX_THUNKFIX R_386_32
725 #define R_XXX_RELATIVE R_386_RELATIVE
727 #define ELFW_ST_BIND ELF32_ST_BIND
728 #define ELFW_ST_TYPE ELF32_ST_TYPE
729 #define ELFW_ST_INFO ELF32_ST_INFO
730 #elif defined(TCC_TARGET_ARM)
731 #define ELFW_R_(type) ELF32_R_##type
732 #define ElfW_Rel ElfW(Rel)
734 #define REL_TYPE_DIRECT R_ARM_ABS32
735 #define R_XXX_THUNKFIX R_ARM_ABS32
736 #define R_XXX_RELATIVE R_ARM_RELATIVE
738 #define ELFW_ST_BIND ELF32_ST_BIND
739 #define ELFW_ST_TYPE ELF32_ST_TYPE
740 #define ELFW_ST_INFO ELF32_ST_INFO
741 #endif
742 /*----------------------------------------------------------------------------*/
744 static struct import_symbol *pe_add_import(struct pe_info *pe, int sym_index)
746 int i;
747 int dll_index;
748 struct pe_import_info *p;
749 struct import_symbol *s;
751 dll_index = ((ElfW(Sym) *)pe->s1->dynsymtab_section->data + sym_index)->st_value;
752 if (0 == dll_index)
753 return NULL;
755 i = dynarray_assoc ((void**)pe->imp_info, pe->imp_count, dll_index);
756 if (-1 != i) {
757 p = pe->imp_info[i];
758 goto found_dll;
760 p = tcc_mallocz(sizeof *p);
761 p->dll_index = dll_index;
762 dynarray_add((void***)&pe->imp_info, &pe->imp_count, p);
764 found_dll:
765 i = dynarray_assoc ((void**)p->symbols, p->sym_count, sym_index);
766 if (-1 != i)
767 return p->symbols[i];
769 s = tcc_mallocz(sizeof *s);
770 dynarray_add((void***)&p->symbols, &p->sym_count, s);
771 s->sym_index = sym_index;
772 return s;
775 /*----------------------------------------------------------------------------*/
776 static void pe_build_imports(struct pe_info *pe)
778 int thk_ptr, ent_ptr, dll_ptr, sym_cnt, i;
779 DWORD rva_base = pe->thunk->sh_addr - pe->imagebase;
780 int ndlls = pe->imp_count;
782 for (sym_cnt = i = 0; i < ndlls; ++i)
783 sym_cnt += pe->imp_info[i]->sym_count;
785 if (0 == sym_cnt)
786 return;
788 pe_align_section(pe->thunk, 16);
790 pe->imp_offs = dll_ptr = pe->thunk->data_offset;
791 pe->imp_size = (ndlls + 1) * sizeof(IMAGE_IMPORT_DESCRIPTOR);
792 pe->iat_offs = dll_ptr + pe->imp_size;
793 pe->iat_size = (sym_cnt + ndlls) * sizeof(ADDR3264);
794 section_ptr_add(pe->thunk, pe->imp_size + 2*pe->iat_size);
796 thk_ptr = pe->iat_offs;
797 ent_ptr = pe->iat_offs + pe->iat_size;
799 for (i = 0; i < pe->imp_count; ++i) {
800 IMAGE_IMPORT_DESCRIPTOR *hdr;
801 int k, n;
802 ADDR3264 v;
803 struct pe_import_info *p = pe->imp_info[i];
804 const char *name = pe->s1->loaded_dlls[p->dll_index-1]->name;
806 /* put the dll name into the import header */
807 v = put_elf_str(pe->thunk, name);
809 hdr = (IMAGE_IMPORT_DESCRIPTOR*)(pe->thunk->data + dll_ptr);
810 hdr->FirstThunk = thk_ptr + rva_base;
811 hdr->OriginalFirstThunk = ent_ptr + rva_base;
812 hdr->Name = v + rva_base;
814 for (k = 0, n = p->sym_count; k <= n; ++k) {
815 if (k < n) {
816 int iat_index = p->symbols[k]->iat_index;
817 int sym_index = p->symbols[k]->sym_index;
818 ElfW(Sym) *imp_sym = (ElfW(Sym) *)pe->s1->dynsymtab_section->data + sym_index;
819 ElfW(Sym) *org_sym = (ElfW(Sym) *)symtab_section->data + iat_index;
820 const char *name = pe->s1->dynsymtab_section->link->data + imp_sym->st_name;
822 org_sym->st_value = thk_ptr;
823 org_sym->st_shndx = pe->thunk->sh_num;
824 v = pe->thunk->data_offset + rva_base;
825 section_ptr_add(pe->thunk, sizeof(WORD)); /* hint, not used */
826 put_elf_str(pe->thunk, name);
827 #ifdef TCC_IS_NATIVE
828 if (pe->type == PE_RUN) {
829 DLLReference *dllref = pe->s1->loaded_dlls[imp_sym->st_value-1];
830 if ( !dllref->handle )
831 dllref->handle = LoadLibrary(dllref->name);
832 v = (ADDR3264)GetProcAddress(dllref->handle, name);
833 if (!v)
834 error_noabort("undefined symbol '%s'", name);
836 #endif
837 } else {
838 v = 0; /* last entry is zero */
840 *(ADDR3264*)(pe->thunk->data+thk_ptr) =
841 *(ADDR3264*)(pe->thunk->data+ent_ptr) = v;
842 thk_ptr += sizeof (ADDR3264);
843 ent_ptr += sizeof (ADDR3264);
845 dll_ptr += sizeof(IMAGE_IMPORT_DESCRIPTOR);
846 dynarray_reset(&p->symbols, &p->sym_count);
848 dynarray_reset(&pe->imp_info, &pe->imp_count);
851 /* ------------------------------------------------------------- */
853 struct pe_sort_sym
855 int index;
856 const char *name;
859 static int sym_cmp(const void *va, const void *vb)
861 const char *ca = (*(struct pe_sort_sym**)va)->name;
862 const char *cb = (*(struct pe_sort_sym**)vb)->name;
863 return strcmp(ca, cb);
866 static void pe_build_exports(struct pe_info *pe)
868 ElfW(Sym) *sym;
869 int sym_index, sym_end;
870 DWORD rva_base, func_o, name_o, ord_o, str_o;
871 IMAGE_EXPORT_DIRECTORY *hdr;
872 int sym_count, ord;
873 struct pe_sort_sym **sorted, *p;
875 FILE *op;
876 char buf[MAX_PATH];
877 const char *dllname;
878 const char *name;
880 rva_base = pe->thunk->sh_addr - pe->imagebase;
881 sym_count = 0, sorted = NULL, op = NULL;
883 sym_end = symtab_section->data_offset / sizeof(ElfW(Sym));
884 for (sym_index = 1; sym_index < sym_end; ++sym_index) {
885 sym = (ElfW(Sym)*)symtab_section->data + sym_index;
886 name = symtab_section->link->data + sym->st_name;
887 if ((sym->st_other & 1)
888 /* export only symbols from actually written sections */
889 && pe->s1->sections[sym->st_shndx]->sh_addr) {
890 p = tcc_malloc(sizeof *p);
891 p->index = sym_index;
892 p->name = name;
893 dynarray_add((void***)&sorted, &sym_count, p);
895 #if 0
896 if (sym->st_other & 1)
897 printf("export: %s\n", name);
898 if (sym->st_other & 2)
899 printf("stdcall: %s\n", name);
900 #endif
903 if (0 == sym_count)
904 return;
906 qsort (sorted, sym_count, sizeof *sorted, sym_cmp);
908 pe_align_section(pe->thunk, 16);
909 dllname = tcc_basename(pe->filename);
911 pe->exp_offs = pe->thunk->data_offset;
912 func_o = pe->exp_offs + sizeof(IMAGE_EXPORT_DIRECTORY);
913 name_o = func_o + sym_count * sizeof (DWORD);
914 ord_o = name_o + sym_count * sizeof (DWORD);
915 str_o = ord_o + sym_count * sizeof(WORD);
917 hdr = section_ptr_add(pe->thunk, str_o - pe->exp_offs);
918 hdr->Characteristics = 0;
919 hdr->Base = 1;
920 hdr->NumberOfFunctions = sym_count;
921 hdr->NumberOfNames = sym_count;
922 hdr->AddressOfFunctions = func_o + rva_base;
923 hdr->AddressOfNames = name_o + rva_base;
924 hdr->AddressOfNameOrdinals = ord_o + rva_base;
925 hdr->Name = str_o + rva_base;
926 put_elf_str(pe->thunk, dllname);
928 #if 1
929 /* automatically write exports to <output-filename>.def */
930 strcpy(buf, pe->filename);
931 strcpy(tcc_fileextension(buf), ".def");
932 op = fopen(buf, "w");
933 if (NULL == op) {
934 error_noabort("could not create '%s': %s", buf, strerror(errno));
935 } else {
936 fprintf(op, "LIBRARY %s\n\nEXPORTS\n", dllname);
937 if (pe->s1->verbose)
938 printf("<- %s (%d symbols)\n", buf, sym_count);
940 #endif
942 for (ord = 0; ord < sym_count; ++ord)
944 p = sorted[ord], sym_index = p->index, name = p->name;
945 /* insert actual address later in pe_relocate_rva */
946 put_elf_reloc(symtab_section, pe->thunk,
947 func_o, R_XXX_RELATIVE, sym_index);
948 *(DWORD*)(pe->thunk->data + name_o)
949 = pe->thunk->data_offset + rva_base;
950 *(WORD*)(pe->thunk->data + ord_o)
951 = ord;
952 put_elf_str(pe->thunk, name);
953 func_o += sizeof (DWORD);
954 name_o += sizeof (DWORD);
955 ord_o += sizeof (WORD);
956 if (op)
957 fprintf(op, "%s\n", name);
959 pe->exp_size = pe->thunk->data_offset - pe->exp_offs;
960 dynarray_reset(&sorted, &sym_count);
961 if (op)
962 fclose(op);
965 /* ------------------------------------------------------------- */
966 static void pe_build_reloc (struct pe_info *pe)
968 DWORD offset, block_ptr, addr;
969 int count, i;
970 ElfW_Rel *rel, *rel_end;
971 Section *s = NULL, *sr;
973 offset = addr = block_ptr = count = i = 0;
974 rel = rel_end = NULL;
976 for(;;) {
977 if (rel < rel_end) {
978 int type = ELFW_R_(TYPE)(rel->r_info);
979 addr = rel->r_offset + s->sh_addr;
980 ++ rel;
981 if (type != REL_TYPE_DIRECT)
982 continue;
983 if (count == 0) { /* new block */
984 block_ptr = pe->reloc->data_offset;
985 section_ptr_add(pe->reloc, sizeof(struct pe_reloc_header));
986 offset = addr & 0xFFFFFFFF<<12;
988 if ((addr -= offset) < (1<<12)) { /* one block spans 4k addresses */
989 WORD *wp = section_ptr_add(pe->reloc, sizeof (WORD));
990 *wp = addr | IMAGE_REL_BASED_HIGHLOW<<12;
991 ++count;
992 continue;
994 -- rel;
996 } else if (i < pe->sec_count) {
997 sr = (s = pe->s1->sections[pe->sec_info[i++].ord])->reloc;
998 if (sr) {
999 rel = (ElfW_Rel *)sr->data;
1000 rel_end = (ElfW_Rel *)(sr->data + sr->data_offset);
1002 continue;
1005 if (count) {
1006 /* store the last block and ready for a new one */
1007 struct pe_reloc_header *hdr;
1008 if (count & 1) /* align for DWORDS */
1009 section_ptr_add(pe->reloc, sizeof(WORD)), ++count;
1010 hdr = (struct pe_reloc_header *)(pe->reloc->data + block_ptr);
1011 hdr -> offset = offset - pe->imagebase;
1012 hdr -> size = count * sizeof(WORD) + sizeof(struct pe_reloc_header);
1013 count = 0;
1016 if (rel >= rel_end)
1017 break;
1021 /* ------------------------------------------------------------- */
1022 static int pe_section_class(Section *s)
1024 int type, flags;
1025 const char *name;
1027 type = s->sh_type;
1028 flags = s->sh_flags;
1029 name = s->name;
1030 if (flags & SHF_ALLOC) {
1031 if (type == SHT_PROGBITS) {
1032 if (flags & SHF_EXECINSTR)
1033 return sec_text;
1034 if (flags & SHF_WRITE)
1035 return sec_data;
1036 if (0 == strcmp(name, ".rsrc"))
1037 return sec_rsrc;
1038 if (0 == strcmp(name, ".iedat"))
1039 return sec_idata;
1040 return sec_other;
1041 } else if (type == SHT_NOBITS) {
1042 if (flags & SHF_WRITE)
1043 return sec_bss;
1045 } else {
1046 if (0 == strcmp(name, ".reloc"))
1047 return sec_reloc;
1048 if (0 == strncmp(name, ".stab", 5)) /* .stab and .stabstr */
1049 return sec_stab;
1051 return -1;
1054 static int pe_assign_addresses (struct pe_info *pe)
1056 int i, k, o, c;
1057 DWORD addr;
1058 int *section_order;
1059 struct section_info *si;
1060 Section *s;
1062 // pe->thunk = new_section(pe->s1, ".iedat", SHT_PROGBITS, SHF_ALLOC);
1064 section_order = tcc_malloc(pe->s1->nb_sections * sizeof (int));
1065 for (o = k = 0 ; k < sec_last; ++k) {
1066 for (i = 1; i < pe->s1->nb_sections; ++i) {
1067 s = pe->s1->sections[i];
1068 if (k == pe_section_class(s)) {
1069 // printf("%s %d\n", s->name, k);
1070 s->sh_addr = pe->imagebase;
1071 section_order[o++] = i;
1076 pe->sec_info = tcc_mallocz(o * sizeof (struct section_info));
1077 addr = pe->imagebase + 1;
1079 for (i = 0; i < o; ++i)
1081 k = section_order[i];
1082 s = pe->s1->sections[k];
1083 c = pe_section_class(s);
1084 si = &pe->sec_info[pe->sec_count];
1086 #ifdef PE_MERGE_DATA
1087 if (c == sec_bss && pe->sec_count && si[-1].cls == sec_data) {
1088 /* append .bss to .data */
1089 s->sh_addr = addr = ((addr-1) | 15) + 1;
1090 addr += s->data_offset;
1091 si[-1].sh_size = addr - si[-1].sh_addr;
1092 continue;
1094 #endif
1095 strcpy(si->name, s->name);
1096 si->cls = c;
1097 si->ord = k;
1098 si->sh_addr = s->sh_addr = addr = pe_virtual_align(pe, addr);
1099 si->sh_flags = s->sh_flags;
1101 if (c == sec_data && NULL == pe->thunk)
1102 pe->thunk = s;
1104 if (s == pe->thunk) {
1105 pe_build_imports(pe);
1106 pe_build_exports(pe);
1109 if (c == sec_reloc)
1110 pe_build_reloc (pe);
1112 if (s->data_offset)
1114 if (s->sh_type != SHT_NOBITS) {
1115 si->data = s->data;
1116 si->data_size = s->data_offset;
1119 addr += s->data_offset;
1120 si->sh_size = s->data_offset;
1121 ++pe->sec_count;
1123 // printf("%08x %05x %s\n", si->sh_addr, si->sh_size, si->name);
1126 #if 0
1127 for (i = 1; i < pe->s1->nb_sections; ++i) {
1128 Section *s = pe->s1->sections[i];
1129 int type = s->sh_type;
1130 int flags = s->sh_flags;
1131 printf("section %-16s %-10s %5x %s,%s,%s\n",
1132 s->name,
1133 type == SHT_PROGBITS ? "progbits" :
1134 type == SHT_NOBITS ? "nobits" :
1135 type == SHT_SYMTAB ? "symtab" :
1136 type == SHT_STRTAB ? "strtab" :
1137 type == SHT_RELX ? "rel" : "???",
1138 s->data_offset,
1139 flags & SHF_ALLOC ? "alloc" : "",
1140 flags & SHF_WRITE ? "write" : "",
1141 flags & SHF_EXECINSTR ? "exec" : ""
1144 pe->s1->verbose = 2;
1145 #endif
1147 tcc_free(section_order);
1148 return 0;
1151 /* ------------------------------------------------------------- */
1152 static void pe_relocate_rva (struct pe_info *pe, Section *s)
1154 Section *sr = s->reloc;
1155 ElfW_Rel *rel, *rel_end;
1156 rel_end = (ElfW_Rel *)(sr->data + sr->data_offset);
1157 for(rel = (ElfW_Rel *)sr->data; rel < rel_end; rel++) {
1158 if (ELFW_R_(TYPE)(rel->r_info) == R_XXX_RELATIVE) {
1159 int sym_index = ELFW_R_(SYM)(rel->r_info);
1160 DWORD addr = s->sh_addr;
1161 if (sym_index) {
1162 ElfW(Sym) *sym = (ElfW(Sym) *)symtab_section->data + sym_index;
1163 addr = sym->st_value;
1165 // printf("reloc rva %08x %08x\n", (DWORD)rel->r_offset, addr);
1166 *(DWORD*)(s->data + rel->r_offset) += addr - pe->imagebase;
1171 /*----------------------------------------------------------------------------*/
1173 static int pe_isafunc(int sym_index)
1175 Section *sr = text_section->reloc;
1176 ElfW_Rel *rel, *rel_end;
1177 Elf32_Word info = ELF32_R_INFO(sym_index, R_386_PC32);
1178 if (!sr)
1179 return 0;
1180 rel_end = (ElfW_Rel *)(sr->data + sr->data_offset);
1181 for (rel = (ElfW_Rel *)sr->data; rel < rel_end; rel++)
1182 if (rel->r_info == info)
1183 return 1;
1184 return 0;
1187 /*----------------------------------------------------------------------------*/
1188 static int pe_check_symbols(struct pe_info *pe)
1190 ElfW(Sym) *sym;
1191 int sym_index, sym_end;
1192 int ret = 0;
1194 pe_align_section(text_section, 8);
1196 sym_end = symtab_section->data_offset / sizeof(ElfW(Sym));
1197 for (sym_index = 1; sym_index < sym_end; ++sym_index) {
1199 sym = (ElfW(Sym) *)symtab_section->data + sym_index;
1200 if (sym->st_shndx == SHN_UNDEF) {
1202 const char *name = symtab_section->link->data + sym->st_name;
1203 unsigned type = ELFW_ST_TYPE(sym->st_info);
1204 int imp_sym = pe_find_import(pe->s1, name);
1205 struct import_symbol *is;
1207 if (0 == imp_sym)
1208 goto not_found;
1209 is = pe_add_import(pe, imp_sym);
1210 if (!is)
1211 goto not_found;
1213 if (type == STT_NOTYPE) {
1214 /* symbols from assembler have no type, find out which */
1215 if (pe_isafunc(sym_index))
1216 type = STT_FUNC;
1217 else
1218 type = STT_OBJECT;
1221 if (type == STT_FUNC) {
1222 unsigned long offset = is->thk_offset;
1223 if (offset) {
1224 /* got aliased symbol, like stricmp and _stricmp */
1226 } else {
1227 char buffer[100];
1228 WORD *p;
1230 offset = text_section->data_offset;
1231 /* add the 'jmp IAT[x]' instruction */
1232 p = section_ptr_add(text_section, 8);
1233 *p = 0x25FF;
1234 #ifdef TCC_TARGET_X86_64
1235 *(DWORD*)(p+1) = (DWORD)-4;
1236 #endif
1237 /* add a helper symbol, will be patched later in
1238 pe_build_imports */
1239 sprintf(buffer, "IAT.%s", name);
1240 is->iat_index = put_elf_sym(
1241 symtab_section, 0, sizeof(DWORD),
1242 ELFW_ST_INFO(STB_GLOBAL, STT_OBJECT),
1243 0, SHN_UNDEF, buffer);
1244 put_elf_reloc(symtab_section, text_section,
1245 offset + 2, R_XXX_THUNKFIX, is->iat_index);
1246 is->thk_offset = offset;
1249 /* tcc_realloc might have altered sym's address */
1250 sym = (ElfW(Sym) *)symtab_section->data + sym_index;
1252 /* patch the original symbol */
1253 sym->st_value = offset;
1254 sym->st_shndx = text_section->sh_num;
1255 sym->st_other &= ~1; /* do not export */
1256 continue;
1259 if (type == STT_OBJECT) { /* data, ptr to that should be */
1260 if (0 == is->iat_index) {
1261 /* original symbol will be patched later in pe_build_imports */
1262 is->iat_index = sym_index;
1263 continue;
1267 not_found:
1268 error_noabort("undefined symbol '%s'", name);
1269 ret = -1;
1271 } else if (pe->s1->rdynamic
1272 && ELFW_ST_BIND(sym->st_info) != STB_LOCAL) {
1273 /* if -rdynamic option, then export all non local symbols */
1274 sym->st_other |= 1;
1277 return ret;
1280 /*----------------------------------------------------------------------------*/
1281 #ifdef PE_PRINT_SECTIONS
1282 static void pe_print_section(FILE * f, Section * s)
1284 /* just if you'r curious */
1285 BYTE *p, *e, b;
1286 int i, n, l, m;
1287 p = s->data;
1288 e = s->data + s->data_offset;
1289 l = e - p;
1291 fprintf(f, "section \"%s\"", s->name);
1292 if (s->link)
1293 fprintf(f, "\nlink \"%s\"", s->link->name);
1294 if (s->reloc)
1295 fprintf(f, "\nreloc \"%s\"", s->reloc->name);
1296 fprintf(f, "\nv_addr %08X", (unsigned)s->sh_addr);
1297 fprintf(f, "\ncontents %08X", (unsigned)l);
1298 fprintf(f, "\n\n");
1300 if (s->sh_type == SHT_NOBITS)
1301 return;
1303 if (0 == l)
1304 return;
1306 if (s->sh_type == SHT_SYMTAB)
1307 m = sizeof(ElfW(Sym));
1308 else if (s->sh_type == SHT_RELX)
1309 m = sizeof(ElfW_Rel);
1310 else
1311 m = 16;
1313 fprintf(f, "%-8s", "offset");
1314 for (i = 0; i < m; ++i)
1315 fprintf(f, " %02x", i);
1316 n = 56;
1318 if (s->sh_type == SHT_SYMTAB || s->sh_type == SHT_RELX) {
1319 const char *fields1[] = {
1320 "name",
1321 "value",
1322 "size",
1323 "bind",
1324 "type",
1325 "other",
1326 "shndx",
1327 NULL
1330 const char *fields2[] = {
1331 "offs",
1332 "type",
1333 "symb",
1334 NULL
1337 const char **p;
1339 if (s->sh_type == SHT_SYMTAB)
1340 p = fields1, n = 106;
1341 else
1342 p = fields2, n = 58;
1344 for (i = 0; p[i]; ++i)
1345 fprintf(f, "%6s", p[i]);
1346 fprintf(f, " symbol");
1349 fprintf(f, "\n");
1350 for (i = 0; i < n; ++i)
1351 fprintf(f, "-");
1352 fprintf(f, "\n");
1354 for (i = 0; i < l;)
1356 fprintf(f, "%08X", i);
1357 for (n = 0; n < m; ++n) {
1358 if (n + i < l)
1359 fprintf(f, " %02X", p[i + n]);
1360 else
1361 fprintf(f, " ");
1364 if (s->sh_type == SHT_SYMTAB) {
1365 ElfW(Sym) *sym = (ElfW(Sym) *) (p + i);
1366 const char *name = s->link->data + sym->st_name;
1367 fprintf(f, " %04X %04X %04X %02X %02X %02X %04X \"%s\"",
1368 (unsigned)sym->st_name,
1369 (unsigned)sym->st_value,
1370 (unsigned)sym->st_size,
1371 (unsigned)ELFW_ST_BIND(sym->st_info),
1372 (unsigned)ELFW_ST_TYPE(sym->st_info),
1373 (unsigned)sym->st_other,
1374 (unsigned)sym->st_shndx,
1375 name);
1377 } else if (s->sh_type == SHT_RELX) {
1378 ElfW_Rel *rel = (ElfW_Rel *) (p + i);
1379 ElfW(Sym) *sym =
1380 (ElfW(Sym) *) s->link->data + ELFW_R_(SYM)(rel->r_info);
1381 const char *name = s->link->link->data + sym->st_name;
1382 fprintf(f, " %04X %02X %04X \"%s\"",
1383 (unsigned)rel->r_offset,
1384 (unsigned)ELFW_R_(TYPE)(rel->r_info),
1385 (unsigned)ELFW_R_(SYM)(rel->r_info),
1386 name);
1387 } else {
1388 fprintf(f, " ");
1389 for (n = 0; n < m; ++n) {
1390 if (n + i < l) {
1391 b = p[i + n];
1392 if (b < 32 || b >= 127)
1393 b = '.';
1394 fprintf(f, "%c", b);
1398 i += m;
1399 fprintf(f, "\n");
1401 fprintf(f, "\n\n");
1404 static void pe_print_sections(TCCState *s1, const char *fname)
1406 Section *s;
1407 FILE *f;
1408 int i;
1409 f = fopen(fname, "w");
1410 for (i = 1; i < s1->nb_sections; ++i) {
1411 s = s1->sections[i];
1412 pe_print_section(f, s);
1414 pe_print_section(f, s1->dynsymtab_section);
1415 fclose(f);
1417 #endif
1419 /* ------------------------------------------------------------- */
1421 static int read_mem(FILE *fp, unsigned offset, void *buffer, unsigned len)
1423 fseek(fp, offset, 0);
1424 return len == fread(buffer, 1, len, fp);
1427 /* -------------------------------------------------------------
1428 * This is for compiled windows resources in 'coff' format
1429 * as generated by 'windres.exe -O coff ...'.
1432 static int pe_load_res(TCCState *s1, FILE *fp)
1434 struct pe_rsrc_header hdr;
1435 Section *rsrc_section;
1436 int i, ret = -1;
1437 BYTE *ptr;
1438 unsigned offs;
1440 if (!read_mem(fp, 0, &hdr, sizeof hdr))
1441 goto quit;
1443 if (hdr.filehdr.Machine != 0x014C
1444 || hdr.filehdr.NumberOfSections != 1
1445 || strcmp(hdr.sectionhdr.Name, ".rsrc") != 0)
1446 goto quit;
1448 rsrc_section = new_section(s1, ".rsrc", SHT_PROGBITS, SHF_ALLOC);
1449 ptr = section_ptr_add(rsrc_section, hdr.sectionhdr.SizeOfRawData);
1450 offs = hdr.sectionhdr.PointerToRawData;
1451 if (!read_mem(fp, offs, ptr, hdr.sectionhdr.SizeOfRawData))
1452 goto quit;
1453 offs = hdr.sectionhdr.PointerToRelocations;
1454 for (i = 0; i < hdr.sectionhdr.NumberOfRelocations; ++i)
1456 struct pe_rsrc_reloc rel;
1457 if (!read_mem(fp, offs, &rel, sizeof rel))
1458 goto quit;
1459 // printf("rsrc_reloc: %x %x %x\n", rel.offset, rel.size, rel.type);
1460 if (rel.type != 7) /* DIR32NB */
1461 goto quit;
1462 put_elf_reloc(symtab_section, rsrc_section,
1463 rel.offset, R_XXX_RELATIVE, 0);
1464 offs += sizeof rel;
1466 ret = 0;
1467 quit:
1468 return ret;
1471 /* ------------------------------------------------------------- */
1472 static char *trimfront(char *p)
1474 while (*p && (unsigned char)*p <= ' ')
1475 ++p;
1476 return p;
1479 static char *trimback(char *a, char *e)
1481 while (e > a && (unsigned char)e[-1] <= ' ')
1482 --e;
1483 *e = 0;;
1484 return a;
1487 static char *get_line(char *line, int size, FILE *fp)
1489 if (NULL == fgets(line, size, fp))
1490 return NULL;
1491 trimback(line, strchr(line, 0));
1492 return trimfront(line);
1495 /* ------------------------------------------------------------- */
1496 static int pe_load_def(TCCState *s1, FILE *fp)
1498 DLLReference *dllref;
1499 int state = 0, ret = -1;
1500 char line[400], dllname[80], *p;
1502 for (;;) {
1503 p = get_line(line, sizeof line, fp);
1504 if (NULL == p)
1505 break;
1506 if (0 == *p || ';' == *p)
1507 continue;
1508 switch (state) {
1509 case 0:
1510 if (0 != strnicmp(p, "LIBRARY", 7))
1511 goto quit;
1512 strcpy(dllname, trimfront(p+7));
1513 ++state;
1514 continue;
1516 case 1:
1517 if (0 != stricmp(p, "EXPORTS"))
1518 goto quit;
1519 ++state;
1520 continue;
1522 case 2:
1523 dllref = tcc_mallocz(sizeof(DLLReference) + strlen(dllname));
1524 strcpy(dllref->name, dllname);
1525 dynarray_add((void ***) &s1->loaded_dlls, &s1->nb_loaded_dlls, dllref);
1526 ++state;
1528 default:
1529 add_elf_sym(s1->dynsymtab_section,
1530 s1->nb_loaded_dlls, 0,
1531 ELFW_ST_INFO(STB_GLOBAL, STT_FUNC), 0,
1532 text_section->sh_num, p);
1533 continue;
1536 ret = 0;
1537 quit:
1538 return ret;
1541 /* ------------------------------------------------------------- */
1542 #define TINY_IMPDEF_GET_EXPORT_NAMES_ONLY
1543 #include "win32/tools/tiny_impdef.c"
1545 static int pe_load_dll(TCCState *s1, const char *dllname, FILE *fp)
1547 int i = 0;
1548 char *p, *q;
1549 p = get_export_names(fp);
1550 if (p) {
1551 DLLReference *dllref;
1552 dllref = tcc_mallocz(sizeof(DLLReference) + strlen(dllname));
1553 strcpy(dllref->name, dllname);
1554 dynarray_add((void ***) &s1->loaded_dlls, &s1->nb_loaded_dlls, dllref);
1555 for (q = p, i = 0; *q; ++i) {
1556 add_elf_sym(s1->dynsymtab_section,
1557 s1->nb_loaded_dlls, 0,
1558 ELFW_ST_INFO(STB_GLOBAL, STT_FUNC), 0,
1559 text_section->sh_num, q);
1560 q += 1 + strlen(q);
1562 tcc_free(p);
1564 return i ? 0 : -1;
1567 /* ------------------------------------------------------------- */
1568 ST_FUNC int pe_load_file(struct TCCState *s1, const char *filename, int fd)
1570 FILE *fp = fdopen(dup(fd), "rb");
1571 int ret = -1;
1572 char buf[10];
1573 if (fp) {
1574 if (0 == strcmp(tcc_fileextension(filename), ".def"))
1575 ret = pe_load_def(s1, fp);
1576 else if (pe_load_res(s1, fp) == 0)
1577 ret = 0;
1578 else if (read_mem(fp, 0, buf, sizeof buf) && 0 == strncmp(buf, "MZ", 2))
1579 ret = pe_load_dll(s1, tcc_basename(filename), fp);
1580 fclose(fp);
1582 return ret;
1585 ST_FUNC int pe_add_dll(struct TCCState *s, const char *libname)
1587 static const char *pat[] = {
1588 "%s.def", "lib%s.def", "%s.dll", "lib%s.dll", NULL
1590 const char **p = pat;
1591 do {
1592 char buf[MAX_PATH];
1593 snprintf(buf, sizeof(buf), *p, libname);
1594 if (tcc_add_dll(s, buf, 0) == 0)
1595 return 0;
1596 } while (*++p);
1597 return -1;
1600 /* ------------------------------------------------------------- */
1601 /* helper function for load/store to insert one more indirection */
1603 ST_FUNC int pe_dllimport(int r, SValue *sv, void (*fn)(int r, SValue *sv))
1605 int t;
1606 if ((sv->r & (VT_VALMASK|VT_SYM|VT_CONST)) != (VT_SYM|VT_CONST))
1607 return 0;
1608 t = sv->sym->type.t;
1609 if (0 == (t & VT_IMPORT))
1610 return 0;
1612 sv->sym->type.t = t & ~VT_IMPORT;
1613 //printf("import %x %04x %s\n", t, ind, get_tok_str(sv->sym->v, NULL));
1615 *++vtop = *sv;
1616 vtop->type.t &= ~(VT_ARRAY|VT_IMPORT);
1617 mk_pointer(&vtop->type);
1618 indir();
1619 fn(r, vtop);
1620 --vtop;
1622 sv->sym->type.t = t;
1623 return 1;
1626 /* ------------------------------------------------------------- */
1627 #ifdef TCC_TARGET_X86_64
1628 #define PE_STDSYM(n,s) n
1629 #else
1630 #define PE_STDSYM(n,s) "_" n s
1631 #endif
1633 static void pe_add_runtime_ex(TCCState *s1, struct pe_info *pe)
1635 const char *start_symbol;
1636 unsigned long addr = 0;
1637 int pe_type = 0;
1639 if (find_elf_sym(symtab_section, PE_STDSYM("WinMain","@16")))
1640 pe_type = PE_GUI;
1641 else
1642 if (TCC_OUTPUT_DLL == s1->output_type) {
1643 pe_type = PE_DLL;
1644 /* need this for 'tccelf.c:relocate_section()' */
1645 s1->output_type = TCC_OUTPUT_EXE;
1648 start_symbol =
1649 TCC_OUTPUT_MEMORY == s1->output_type
1650 ? PE_GUI == pe_type ? "_runwinmain" : NULL
1651 : PE_DLL == pe_type ? PE_STDSYM("_dllstart","@12")
1652 : PE_GUI == pe_type ? "_winstart" : "_start"
1655 /* grab the startup code from libtcc1 */
1656 if (start_symbol)
1657 add_elf_sym(symtab_section,
1658 0, 0,
1659 ELFW_ST_INFO(STB_GLOBAL, STT_NOTYPE), 0,
1660 SHN_UNDEF, start_symbol);
1662 if (0 == s1->nostdlib) {
1663 static const char *libs[] = {
1664 "tcc1", "msvcrt", "kernel32", "", "user32", "gdi32", NULL
1666 const char **pp, *p;
1667 for (pp = libs; 0 != (p = *pp); ++pp) {
1668 if (0 == *p) {
1669 if (PE_DLL != pe_type && PE_GUI != pe_type)
1670 break;
1671 } else if (tcc_add_library(s1, p) < 0)
1672 error_noabort("cannot find library: %s", p);
1676 if (start_symbol) {
1677 addr = (uplong)tcc_get_symbol_err(s1, start_symbol);
1678 if (s1->output_type == TCC_OUTPUT_MEMORY && addr)
1679 /* for -run GUI's, put '_runwinmain' instead of 'main' */
1680 add_elf_sym(symtab_section,
1681 addr, 0,
1682 ELFW_ST_INFO(STB_GLOBAL, STT_NOTYPE), 0,
1683 text_section->sh_num, "main");
1686 pe->type = pe_type;
1687 pe->start_addr = addr;
1690 ST_FUNC int pe_output_file(TCCState * s1, const char *filename)
1692 int ret;
1693 struct pe_info pe;
1694 int i;
1696 memset(&pe, 0, sizeof pe);
1697 pe.filename = filename;
1698 pe.s1 = s1;
1700 tcc_add_bcheck(s1);
1701 pe_add_runtime_ex(s1, &pe);
1702 relocate_common_syms(); /* assign bss adresses */
1703 tcc_add_linker_symbols(s1);
1705 ret = pe_check_symbols(&pe);
1706 if (ret)
1708 else if (filename) {
1709 if (PE_DLL == pe.type) {
1710 pe.reloc = new_section(pe.s1, ".reloc", SHT_PROGBITS, 0);
1711 /* XXX: check if is correct for arm-pe target */
1712 pe.imagebase = 0x10000000;
1713 } else {
1714 #if defined(TCC_TARGET_ARM)
1715 pe.imagebase = 0x00010000;
1716 #else
1717 pe.imagebase = 0x00400000;
1718 #endif
1721 /* if no subsystem specified, we use "console" subsystem by default */
1722 if (s1->pe_subsystem != 0)
1723 pe.subsystem = s1->pe_subsystem;
1724 else
1725 #if defined(TCC_TARGET_ARM)
1726 pe.subsystem = 3;
1727 #else
1728 pe.subsystem = 9;
1729 #endif
1730 /* set default file/section alignment */
1731 if (pe.subsystem == 1) {
1732 pe.section_align = 0x20;
1733 pe.file_align = 0x20;
1734 } else {
1735 pe.section_align = 0x1000;
1736 pe.file_align = 0x200;
1739 if (s1->section_align != 0)
1740 pe.section_align = s1->section_align;
1741 if (s1->pe_file_align != 0)
1742 pe.file_align = s1->pe_file_align;
1744 if ((pe.subsystem >= 10) && (pe.subsystem <= 12))
1745 pe.imagebase = 0;
1747 if (s1->has_text_addr)
1748 pe.imagebase = s1->text_addr;
1750 pe_assign_addresses(&pe);
1751 relocate_syms(s1, 0);
1752 for (i = 1; i < s1->nb_sections; ++i) {
1753 Section *s = s1->sections[i];
1754 if (s->reloc) {
1755 relocate_section(s1, s);
1756 pe_relocate_rva(&pe, s);
1759 if (s1->nb_errors)
1760 ret = -1;
1761 else
1762 ret = pe_write(&pe);
1763 tcc_free(pe.sec_info);
1764 } else {
1765 #ifndef TCC_IS_NATIVE
1766 error_noabort("-run supported only on native platform");
1767 #endif
1768 pe.type = PE_RUN;
1769 pe.thunk = data_section;
1770 pe_build_imports(&pe);
1773 #ifdef PE_PRINT_SECTIONS
1774 pe_print_sections(s1, "tcc.log");
1775 #endif
1776 return ret;
1779 /* ------------------------------------------------------------- */