win32: reformat examples, crt etc
[tinycc.git] / tccpe.c
blob89ff3bdbbaa1f782846dd13cb6f484d1c9a40285
1 /*
2 * TCCPE.C - PE file output for the Tiny C Compiler
4 * Copyright (c) 2005-2007 grischka
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
21 #ifdef TCC_TARGET_PE
23 #define ST_FN static
24 #define ST_DATA static
25 #define PUB_FN
27 #ifndef _WIN32
28 #define stricmp strcasecmp
29 #define strnicmp strncasecmp
30 #endif
32 #ifndef MAX_PATH
33 #define MAX_PATH 260
34 #endif
36 #define PE_MERGE_DATA
37 // #define PE_PRINT_SECTIONS
39 #ifdef TCC_TARGET_X86_64
40 # define ADDR3264 ULONGLONG
41 #else
42 # define ADDR3264 DWORD
43 #endif
45 #if defined _WIN32 && (defined _WIN64) == (defined TCC_TARGET_X86_64)
46 #define TCC_IS_NATIVE
47 #endif
49 /* ----------------------------------------------------------- */
50 #ifndef IMAGE_NT_SIGNATURE
51 /* ----------------------------------------------------------- */
52 /* definitions below are from winnt.h */
54 typedef unsigned char BYTE;
55 typedef unsigned short WORD;
56 typedef unsigned long DWORD;
57 typedef unsigned long long ULONGLONG;
58 #pragma pack(push, 1)
60 typedef struct _IMAGE_DOS_HEADER { /* DOS .EXE header */
61 WORD e_magic; /* Magic number */
62 WORD e_cblp; /* Bytes on last page of file */
63 WORD e_cp; /* Pages in file */
64 WORD e_crlc; /* Relocations */
65 WORD e_cparhdr; /* Size of header in paragraphs */
66 WORD e_minalloc; /* Minimum extra paragraphs needed */
67 WORD e_maxalloc; /* Maximum extra paragraphs needed */
68 WORD e_ss; /* Initial (relative) SS value */
69 WORD e_sp; /* Initial SP value */
70 WORD e_csum; /* Checksum */
71 WORD e_ip; /* Initial IP value */
72 WORD e_cs; /* Initial (relative) CS value */
73 WORD e_lfarlc; /* File address of relocation table */
74 WORD e_ovno; /* Overlay number */
75 WORD e_res[4]; /* Reserved words */
76 WORD e_oemid; /* OEM identifier (for e_oeminfo) */
77 WORD e_oeminfo; /* OEM information; e_oemid specific */
78 WORD e_res2[10]; /* Reserved words */
79 DWORD e_lfanew; /* File address of new exe header */
80 } IMAGE_DOS_HEADER, *PIMAGE_DOS_HEADER;
82 #define IMAGE_NT_SIGNATURE 0x00004550 /* PE00 */
83 #define SIZE_OF_NT_SIGNATURE 4
85 typedef struct _IMAGE_FILE_HEADER {
86 WORD Machine;
87 WORD NumberOfSections;
88 DWORD TimeDateStamp;
89 DWORD PointerToSymbolTable;
90 DWORD NumberOfSymbols;
91 WORD SizeOfOptionalHeader;
92 WORD Characteristics;
93 } IMAGE_FILE_HEADER, *PIMAGE_FILE_HEADER;
96 #define IMAGE_SIZEOF_FILE_HEADER 20
98 typedef struct _IMAGE_DATA_DIRECTORY {
99 DWORD VirtualAddress;
100 DWORD Size;
101 } IMAGE_DATA_DIRECTORY, *PIMAGE_DATA_DIRECTORY;
104 typedef struct _IMAGE_OPTIONAL_HEADER {
105 /* Standard fields. */
106 WORD Magic;
107 BYTE MajorLinkerVersion;
108 BYTE MinorLinkerVersion;
109 DWORD SizeOfCode;
110 DWORD SizeOfInitializedData;
111 DWORD SizeOfUninitializedData;
112 DWORD AddressOfEntryPoint;
113 DWORD BaseOfCode;
114 #ifndef TCC_TARGET_X86_64
115 DWORD BaseOfData;
116 #endif
117 /* NT additional fields. */
118 ADDR3264 ImageBase;
119 DWORD SectionAlignment;
120 DWORD FileAlignment;
121 WORD MajorOperatingSystemVersion;
122 WORD MinorOperatingSystemVersion;
123 WORD MajorImageVersion;
124 WORD MinorImageVersion;
125 WORD MajorSubsystemVersion;
126 WORD MinorSubsystemVersion;
127 DWORD Win32VersionValue;
128 DWORD SizeOfImage;
129 DWORD SizeOfHeaders;
130 DWORD CheckSum;
131 WORD Subsystem;
132 WORD DllCharacteristics;
133 ADDR3264 SizeOfStackReserve;
134 ADDR3264 SizeOfStackCommit;
135 ADDR3264 SizeOfHeapReserve;
136 ADDR3264 SizeOfHeapCommit;
137 DWORD LoaderFlags;
138 DWORD NumberOfRvaAndSizes;
139 IMAGE_DATA_DIRECTORY DataDirectory[16];
140 } IMAGE_OPTIONAL_HEADER32, IMAGE_OPTIONAL_HEADER64, IMAGE_OPTIONAL_HEADER;
142 #define IMAGE_DIRECTORY_ENTRY_EXPORT 0 /* Export Directory */
143 #define IMAGE_DIRECTORY_ENTRY_IMPORT 1 /* Import Directory */
144 #define IMAGE_DIRECTORY_ENTRY_RESOURCE 2 /* Resource Directory */
145 #define IMAGE_DIRECTORY_ENTRY_EXCEPTION 3 /* Exception Directory */
146 #define IMAGE_DIRECTORY_ENTRY_SECURITY 4 /* Security Directory */
147 #define IMAGE_DIRECTORY_ENTRY_BASERELOC 5 /* Base Relocation Table */
148 #define IMAGE_DIRECTORY_ENTRY_DEBUG 6 /* Debug Directory */
149 /* IMAGE_DIRECTORY_ENTRY_COPYRIGHT 7 (X86 usage) */
150 #define IMAGE_DIRECTORY_ENTRY_ARCHITECTURE 7 /* Architecture Specific Data */
151 #define IMAGE_DIRECTORY_ENTRY_GLOBALPTR 8 /* RVA of GP */
152 #define IMAGE_DIRECTORY_ENTRY_TLS 9 /* TLS Directory */
153 #define IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG 10 /* Load Configuration Directory */
154 #define IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT 11 /* Bound Import Directory in headers */
155 #define IMAGE_DIRECTORY_ENTRY_IAT 12 /* Import Address Table */
156 #define IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT 13 /* Delay Load Import Descriptors */
157 #define IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR 14 /* COM Runtime descriptor */
159 /* Section header format. */
160 #define IMAGE_SIZEOF_SHORT_NAME 8
162 typedef struct _IMAGE_SECTION_HEADER {
163 BYTE Name[IMAGE_SIZEOF_SHORT_NAME];
164 union {
165 DWORD PhysicalAddress;
166 DWORD VirtualSize;
167 } Misc;
168 DWORD VirtualAddress;
169 DWORD SizeOfRawData;
170 DWORD PointerToRawData;
171 DWORD PointerToRelocations;
172 DWORD PointerToLinenumbers;
173 WORD NumberOfRelocations;
174 WORD NumberOfLinenumbers;
175 DWORD Characteristics;
176 } IMAGE_SECTION_HEADER, *PIMAGE_SECTION_HEADER;
178 #define IMAGE_SIZEOF_SECTION_HEADER 40
180 typedef struct _IMAGE_EXPORT_DIRECTORY {
181 DWORD Characteristics;
182 DWORD TimeDateStamp;
183 WORD MajorVersion;
184 WORD MinorVersion;
185 DWORD Name;
186 DWORD Base;
187 DWORD NumberOfFunctions;
188 DWORD NumberOfNames;
189 DWORD AddressOfFunctions;
190 DWORD AddressOfNames;
191 DWORD AddressOfNameOrdinals;
192 } IMAGE_EXPORT_DIRECTORY,*PIMAGE_EXPORT_DIRECTORY;
194 typedef struct _IMAGE_IMPORT_DESCRIPTOR {
195 union {
196 DWORD Characteristics;
197 DWORD OriginalFirstThunk;
199 DWORD TimeDateStamp;
200 DWORD ForwarderChain;
201 DWORD Name;
202 DWORD FirstThunk;
203 } IMAGE_IMPORT_DESCRIPTOR;
205 typedef struct _IMAGE_BASE_RELOCATION {
206 DWORD VirtualAddress;
207 DWORD SizeOfBlock;
208 // WORD TypeOffset[1];
209 } IMAGE_BASE_RELOCATION;
211 #define IMAGE_SIZEOF_BASE_RELOCATION 8
213 #define IMAGE_REL_BASED_ABSOLUTE 0
214 #define IMAGE_REL_BASED_HIGH 1
215 #define IMAGE_REL_BASED_LOW 2
216 #define IMAGE_REL_BASED_HIGHLOW 3
217 #define IMAGE_REL_BASED_HIGHADJ 4
218 #define IMAGE_REL_BASED_MIPS_JMPADDR 5
219 #define IMAGE_REL_BASED_SECTION 6
220 #define IMAGE_REL_BASED_REL32 7
222 #pragma pack(pop)
224 /* ----------------------------------------------------------- */
225 #endif /* ndef IMAGE_NT_SIGNATURE */
226 /* ----------------------------------------------------------- */
227 #pragma pack(push, 1)
229 struct pe_header
231 IMAGE_DOS_HEADER doshdr;
232 BYTE dosstub[0x40];
233 DWORD nt_sig;
234 IMAGE_FILE_HEADER filehdr;
235 #ifdef TCC_TARGET_X86_64
236 IMAGE_OPTIONAL_HEADER64 opthdr;
237 #else
238 #ifdef _WIN64
239 IMAGE_OPTIONAL_HEADER32 opthdr;
240 #else
241 IMAGE_OPTIONAL_HEADER opthdr;
242 #endif
243 #endif
246 struct pe_reloc_header {
247 DWORD offset;
248 DWORD size;
251 struct pe_rsrc_header {
252 struct _IMAGE_FILE_HEADER filehdr;
253 struct _IMAGE_SECTION_HEADER sectionhdr;
256 struct pe_rsrc_reloc {
257 DWORD offset;
258 DWORD size;
259 WORD type;
262 #pragma pack(pop)
264 /* ----------------------------------------------------------- */
265 ST_DATA struct pe_header pe_header = {
267 /* IMAGE_DOS_HEADER doshdr */
268 0x5A4D, /*WORD e_magic; Magic number */
269 0x0090, /*WORD e_cblp; Bytes on last page of file */
270 0x0003, /*WORD e_cp; Pages in file */
271 0x0000, /*WORD e_crlc; Relocations */
273 0x0004, /*WORD e_cparhdr; Size of header in paragraphs */
274 0x0000, /*WORD e_minalloc; Minimum extra paragraphs needed */
275 0xFFFF, /*WORD e_maxalloc; Maximum extra paragraphs needed */
276 0x0000, /*WORD e_ss; Initial (relative) SS value */
278 0x00B8, /*WORD e_sp; Initial SP value */
279 0x0000, /*WORD e_csum; Checksum */
280 0x0000, /*WORD e_ip; Initial IP value */
281 0x0000, /*WORD e_cs; Initial (relative) CS value */
282 0x0040, /*WORD e_lfarlc; File address of relocation table */
283 0x0000, /*WORD e_ovno; Overlay number */
284 {0,0,0,0}, /*WORD e_res[4]; Reserved words */
285 0x0000, /*WORD e_oemid; OEM identifier (for e_oeminfo) */
286 0x0000, /*WORD e_oeminfo; OEM information; e_oemid specific */
287 {0,0,0,0,0,0,0,0,0,0}, /*WORD e_res2[10]; Reserved words */
288 0x00000080 /*DWORD e_lfanew; File address of new exe header */
290 /* BYTE dosstub[0x40] */
291 /* 14 code bytes + "This program cannot be run in DOS mode.\r\r\n$" + 6 * 0x00 */
292 0x0e,0x1f,0xba,0x0e,0x00,0xb4,0x09,0xcd,0x21,0xb8,0x01,0x4c,0xcd,0x21,0x54,0x68,
293 0x69,0x73,0x20,0x70,0x72,0x6f,0x67,0x72,0x61,0x6d,0x20,0x63,0x61,0x6e,0x6e,0x6f,
294 0x74,0x20,0x62,0x65,0x20,0x72,0x75,0x6e,0x20,0x69,0x6e,0x20,0x44,0x4f,0x53,0x20,
295 0x6d,0x6f,0x64,0x65,0x2e,0x0d,0x0d,0x0a,0x24,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
297 0x00004550, /* DWORD nt_sig = IMAGE_NT_SIGNATURE */
299 /* IMAGE_FILE_HEADER filehdr */
300 #ifdef TCC_TARGET_X86_64
301 0x8664, /*WORD Machine; */
302 #else
303 0x014C, /*WORD Machine; */
304 #endif
305 0x0003, /*WORD NumberOfSections; */
306 0x00000000, /*DWORD TimeDateStamp; */
307 0x00000000, /*DWORD PointerToSymbolTable; */
308 0x00000000, /*DWORD NumberOfSymbols; */
309 #ifdef TCC_TARGET_X86_64
310 0x00F0, /*WORD SizeOfOptionalHeader; */
311 0x022F /*WORD Characteristics; */
312 #define CHARACTERISTICS_DLL 0x222E
313 #else
314 0x00E0, /*WORD SizeOfOptionalHeader; */
315 0x030F /*WORD Characteristics; */
316 #define CHARACTERISTICS_DLL 0x230E
317 #endif
319 /* IMAGE_OPTIONAL_HEADER opthdr */
320 /* Standard fields. */
321 #ifdef TCC_TARGET_X86_64
322 0x020B, /*WORD Magic; */
323 #else
324 0x010B, /*WORD Magic; */
325 #endif
326 0x06, /*BYTE MajorLinkerVersion; */
327 0x00, /*BYTE MinorLinkerVersion; */
328 0x00000000, /*DWORD SizeOfCode; */
329 0x00000000, /*DWORD SizeOfInitializedData; */
330 0x00000000, /*DWORD SizeOfUninitializedData; */
331 0x00000000, /*DWORD AddressOfEntryPoint; */
332 0x00000000, /*DWORD BaseOfCode; */
333 #ifndef TCC_TARGET_X86_64
334 0x00000000, /*DWORD BaseOfData; */
335 #endif
336 /* NT additional fields. */
337 0x00400000, /*DWORD ImageBase; */
338 0x00001000, /*DWORD SectionAlignment; */
339 0x00000200, /*DWORD FileAlignment; */
340 0x0004, /*WORD MajorOperatingSystemVersion; */
341 0x0000, /*WORD MinorOperatingSystemVersion; */
342 0x0000, /*WORD MajorImageVersion; */
343 0x0000, /*WORD MinorImageVersion; */
344 0x0004, /*WORD MajorSubsystemVersion; */
345 0x0000, /*WORD MinorSubsystemVersion; */
346 0x00000000, /*DWORD Win32VersionValue; */
347 0x00000000, /*DWORD SizeOfImage; */
348 0x00000200, /*DWORD SizeOfHeaders; */
349 0x00000000, /*DWORD CheckSum; */
350 0x0002, /*WORD Subsystem; */
351 0x0000, /*WORD DllCharacteristics; */
352 0x00100000, /*DWORD SizeOfStackReserve; */
353 0x00001000, /*DWORD SizeOfStackCommit; */
354 0x00100000, /*DWORD SizeOfHeapReserve; */
355 0x00001000, /*DWORD SizeOfHeapCommit; */
356 0x00000000, /*DWORD LoaderFlags; */
357 0x00000010, /*DWORD NumberOfRvaAndSizes; */
359 /* IMAGE_DATA_DIRECTORY DataDirectory[16]; */
360 {{0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0},
361 {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}}
364 /* ------------------------------------------------------------- */
365 /* internal temporary structures */
368 #define IMAGE_SCN_CNT_CODE 0x00000020
369 #define IMAGE_SCN_CNT_INITIALIZED_DATA 0x00000040
370 #define IMAGE_SCN_CNT_UNINITIALIZED_DATA 0x00000080
371 #define IMAGE_SCN_MEM_DISCARDABLE 0x02000000
372 #define IMAGE_SCN_MEM_SHARED 0x10000000
373 #define IMAGE_SCN_MEM_EXECUTE 0x20000000
374 #define IMAGE_SCN_MEM_READ 0x40000000
375 #define IMAGE_SCN_MEM_WRITE 0x80000000
378 enum {
379 sec_text = 0,
380 sec_data ,
381 sec_bss ,
382 sec_idata ,
383 sec_other ,
384 sec_rsrc ,
385 sec_stab ,
386 sec_reloc ,
387 sec_last
390 ST_DATA DWORD pe_sec_flags[] = {
391 0x60000020, /* ".text" , */
392 0xC0000040, /* ".data" , */
393 0xC0000080, /* ".bss" , */
394 0x40000040, /* ".idata" , */
395 0xE0000060, /* < other > , */
396 0x40000040, /* ".rsrc" , */
397 0x42000802, /* ".stab" , */
398 0x42000040, /* ".reloc" , */
401 struct section_info {
402 int cls, ord;
403 char name[32];
404 DWORD sh_addr;
405 DWORD sh_size;
406 DWORD sh_flags;
407 unsigned char *data;
408 DWORD data_size;
409 IMAGE_SECTION_HEADER ish;
412 struct import_symbol {
413 int sym_index;
414 int iat_index;
415 int thk_offset;
418 struct pe_import_info {
419 int dll_index;
420 int sym_count;
421 struct import_symbol **symbols;
424 struct pe_info {
425 TCCState *s1;
426 Section *reloc;
427 Section *thunk;
428 const char *filename;
429 int type;
430 DWORD sizeofheaders;
431 DWORD imagebase;
432 DWORD start_addr;
433 DWORD imp_offs;
434 DWORD imp_size;
435 DWORD iat_offs;
436 DWORD iat_size;
437 DWORD exp_offs;
438 DWORD exp_size;
439 struct section_info *sec_info;
440 int sec_count;
441 struct pe_import_info **imp_info;
442 int imp_count;
445 /* ------------------------------------------------------------- */
447 #define PE_NUL 0
448 #define PE_DLL 1
449 #define PE_GUI 2
450 #define PE_EXE 3
451 #define PE_RUN 4
453 void error_noabort(const char *, ...);
455 #ifdef _WIN32
456 void dbg_printf (const char *fmt, ...)
458 char buffer[4000];
459 va_list arg;
460 int x;
461 va_start(arg, fmt);
462 x = vsprintf (buffer, fmt, arg);
463 strcpy(buffer+x, "\n");
464 OutputDebugString(buffer);
466 #endif
468 /* --------------------------------------------*/
470 ST_FN const char* get_alt_symbol(char *buffer, const char *symbol)
472 const char *p;
473 p = strrchr(symbol, '@');
474 if (p && isnum(p[1]) && symbol[0] == '_') { /* stdcall decor */
475 strcpy(buffer, symbol+1)[p-symbol-1] = 0;
476 } else if (symbol[0] != '_') { /* try non-ansi function */
477 buffer[0] = '_', strcpy(buffer + 1, symbol);
478 } else if (0 == memcmp(symbol, "__imp__", 7)) { /* mingw 2.0 */
479 strcpy(buffer, symbol + 6);
480 } else if (0 == memcmp(symbol, "_imp___", 7)) { /* mingw 3.7 */
481 strcpy(buffer, symbol + 6);
482 } else {
483 return symbol;
485 return buffer;
488 ST_FN int pe_find_import(TCCState * s1, const char *symbol)
490 char buffer[200];
491 const char *s;
492 int sym_index, n = 0;
493 do {
494 s = n ? get_alt_symbol(buffer, symbol) : symbol;
495 sym_index = find_elf_sym(s1->dynsymtab_section, s);
496 // printf("find (%d) %d %s\n", n, sym_index, s);
497 } while (0 == sym_index && ++n < 2);
498 return sym_index;
501 /*----------------------------------------------------------------------------*/
503 ST_FN int dynarray_assoc(void **pp, int n, int key)
505 int i;
506 for (i = 0; i < n; ++i, ++pp)
507 if (key == **(int **) pp)
508 return i;
509 return -1;
512 #if 0
513 ST_FN DWORD umin(DWORD a, DWORD b)
515 return a < b ? a : b;
517 #endif
519 ST_FN DWORD umax(DWORD a, DWORD b)
521 return a < b ? b : a;
524 ST_FN void pe_fpad(FILE *fp, DWORD new_pos)
526 DWORD pos = ftell(fp);
527 while (++pos <= new_pos)
528 fputc(0, fp);
531 ST_FN DWORD pe_file_align(DWORD n)
533 return (n + (0x200 - 1)) & ~(0x200 - 1);
536 ST_FN DWORD pe_virtual_align(DWORD n)
538 return (n + (0x1000 - 1)) & ~(0x1000 - 1);
541 ST_FN void pe_align_section(Section *s, int a)
543 int i = s->data_offset & (a-1);
544 if (i)
545 section_ptr_add(s, a - i);
548 ST_FN void pe_set_datadir(int dir, DWORD addr, DWORD size)
550 pe_header.opthdr.DataDirectory[dir].VirtualAddress = addr;
551 pe_header.opthdr.DataDirectory[dir].Size = size;
554 /*----------------------------------------------------------------------------*/
555 ST_FN int pe_write(struct pe_info *pe)
557 int i;
558 FILE *op;
559 DWORD file_offset, r;
561 op = fopen(pe->filename, "wb");
562 if (NULL == op) {
563 error_noabort("could not write '%s': %s", pe->filename, strerror(errno));
564 return 1;
567 pe->sizeofheaders = pe_file_align(
568 sizeof pe_header
569 + pe->sec_count * sizeof (IMAGE_SECTION_HEADER)
572 file_offset = pe->sizeofheaders;
573 pe_fpad(op, file_offset);
575 if (2 == pe->s1->verbose)
576 printf("-------------------------------"
577 "\n virt file size section" "\n");
579 for (i = 0; i < pe->sec_count; ++i) {
580 struct section_info *si = pe->sec_info + i;
581 const char *sh_name = si->name;
582 unsigned long addr = si->sh_addr - pe->imagebase;
583 unsigned long size = si->sh_size;
584 IMAGE_SECTION_HEADER *psh = &si->ish;
586 if (2 == pe->s1->verbose)
587 printf("%6lx %6lx %6lx %s\n",
588 addr, file_offset, size, sh_name);
590 switch (si->cls) {
591 case sec_text:
592 pe_header.opthdr.BaseOfCode = addr;
593 pe_header.opthdr.AddressOfEntryPoint = addr + pe->start_addr;
594 break;
596 case sec_data:
597 #ifndef TCC_TARGET_X86_64
598 pe_header.opthdr.BaseOfData = addr;
599 #endif
600 break;
602 case sec_bss:
603 break;
605 case sec_reloc:
606 pe_set_datadir(IMAGE_DIRECTORY_ENTRY_BASERELOC, addr, size);
607 break;
609 case sec_rsrc:
610 pe_set_datadir(IMAGE_DIRECTORY_ENTRY_RESOURCE, addr, size);
611 break;
613 case sec_stab:
614 break;
617 if (pe->thunk == pe->s1->sections[si->ord]) {
618 if (pe->imp_size) {
619 pe_set_datadir(IMAGE_DIRECTORY_ENTRY_IMPORT,
620 pe->imp_offs + addr, pe->imp_size);
621 pe_set_datadir(IMAGE_DIRECTORY_ENTRY_IAT,
622 pe->iat_offs + addr, pe->iat_size);
624 if (pe->exp_size) {
625 pe_set_datadir(IMAGE_DIRECTORY_ENTRY_EXPORT,
626 pe->exp_offs + addr, pe->exp_size);
630 strcpy((char*)psh->Name, sh_name);
632 psh->Characteristics = pe_sec_flags[si->cls];
633 psh->VirtualAddress = addr;
634 psh->Misc.VirtualSize = size;
635 pe_header.opthdr.SizeOfImage =
636 umax(pe_virtual_align(size + addr), pe_header.opthdr.SizeOfImage);
638 if (si->data_size) {
639 psh->PointerToRawData = r = file_offset;
640 fwrite(si->data, 1, si->data_size, op);
641 file_offset = pe_file_align(file_offset + si->data_size);
642 psh->SizeOfRawData = file_offset - r;
643 pe_fpad(op, file_offset);
647 // pe_header.filehdr.TimeDateStamp = time(NULL);
648 pe_header.filehdr.NumberOfSections = pe->sec_count;
649 pe_header.opthdr.SizeOfHeaders = pe->sizeofheaders;
650 pe_header.opthdr.ImageBase = pe->imagebase;
651 if (PE_DLL == pe->type)
652 pe_header.filehdr.Characteristics = CHARACTERISTICS_DLL;
653 else if (PE_GUI != pe->type)
654 pe_header.opthdr.Subsystem = 3;
656 fseek(op, SEEK_SET, 0);
657 fwrite(&pe_header, 1, sizeof pe_header, op);
658 for (i = 0; i < pe->sec_count; ++i)
659 fwrite(&pe->sec_info[i].ish, 1, sizeof(IMAGE_SECTION_HEADER), op);
660 fclose (op);
662 if (2 == pe->s1->verbose)
663 printf("-------------------------------\n");
664 if (pe->s1->verbose)
665 printf("<- %s (%lu bytes)\n", pe->filename, file_offset);
667 return 0;
670 /*----------------------------------------------------------------------------*/
672 #ifdef TCC_TARGET_X86_64
673 #define ELFW_R_(type) ELF64_R_##type
674 #define ElfW_Rel ElfW(Rela)
676 #define REL_TYPE_DIRECT R_X86_64_64
677 #define R_XXX_THUNKFIX R_X86_64_PC32
678 #define R_XXX_RELATIVE R_X86_64_RELATIVE
680 #define ELFW_ST_BIND ELF64_ST_BIND
681 #define ELFW_ST_TYPE ELF64_ST_TYPE
682 #define ELFW_ST_INFO ELF64_ST_INFO
683 #else
684 #define ELFW_R_(type) ELF32_R_##type
685 #define ElfW_Rel ElfW(Rel)
687 #define REL_TYPE_DIRECT R_386_32
688 #define R_XXX_THUNKFIX R_386_32
689 #define R_XXX_RELATIVE R_386_RELATIVE
691 #define ELFW_ST_BIND ELF32_ST_BIND
692 #define ELFW_ST_TYPE ELF32_ST_TYPE
693 #define ELFW_ST_INFO ELF32_ST_INFO
694 #endif
695 /*----------------------------------------------------------------------------*/
697 ST_FN struct import_symbol *pe_add_import(struct pe_info *pe, int sym_index)
699 int i;
700 int dll_index;
701 struct pe_import_info *p;
702 struct import_symbol *s;
704 dll_index = ((ElfW(Sym) *)pe->s1->dynsymtab_section->data + sym_index)->st_value;
705 if (0 == dll_index)
706 return NULL;
708 i = dynarray_assoc ((void**)pe->imp_info, pe->imp_count, dll_index);
709 if (-1 != i) {
710 p = pe->imp_info[i];
711 goto found_dll;
713 p = tcc_mallocz(sizeof *p);
714 p->dll_index = dll_index;
715 dynarray_add((void***)&pe->imp_info, &pe->imp_count, p);
717 found_dll:
718 i = dynarray_assoc ((void**)p->symbols, p->sym_count, sym_index);
719 if (-1 != i)
720 return p->symbols[i];
722 s = tcc_mallocz(sizeof *s);
723 dynarray_add((void***)&p->symbols, &p->sym_count, s);
724 s->sym_index = sym_index;
725 return s;
728 /*----------------------------------------------------------------------------*/
729 ST_FN void pe_build_imports(struct pe_info *pe)
731 int thk_ptr, ent_ptr, dll_ptr, sym_cnt, i;
732 DWORD rva_base = pe->thunk->sh_addr - pe->imagebase;
733 int ndlls = pe->imp_count;
735 for (sym_cnt = i = 0; i < ndlls; ++i)
736 sym_cnt += pe->imp_info[i]->sym_count;
738 if (0 == sym_cnt)
739 return;
741 pe_align_section(pe->thunk, 16);
743 pe->imp_offs = dll_ptr = pe->thunk->data_offset;
744 pe->imp_size = (ndlls + 1) * sizeof(IMAGE_IMPORT_DESCRIPTOR);
745 pe->iat_offs = dll_ptr + pe->imp_size;
746 pe->iat_size = (sym_cnt + ndlls) * sizeof(ADDR3264);
747 section_ptr_add(pe->thunk, pe->imp_size + 2*pe->iat_size);
749 thk_ptr = pe->iat_offs;
750 ent_ptr = pe->iat_offs + pe->iat_size;
752 for (i = 0; i < pe->imp_count; ++i) {
753 IMAGE_IMPORT_DESCRIPTOR *hdr;
754 int k, n;
755 ADDR3264 v;
756 struct pe_import_info *p = pe->imp_info[i];
757 const char *name = pe->s1->loaded_dlls[p->dll_index-1]->name;
759 /* put the dll name into the import header */
760 v = put_elf_str(pe->thunk, name);
762 hdr = (IMAGE_IMPORT_DESCRIPTOR*)(pe->thunk->data + dll_ptr);
763 hdr->FirstThunk = thk_ptr + rva_base;
764 hdr->OriginalFirstThunk = ent_ptr + rva_base;
765 hdr->Name = v + rva_base;
767 for (k = 0, n = p->sym_count; k <= n; ++k) {
768 if (k < n) {
769 int iat_index = p->symbols[k]->iat_index;
770 int sym_index = p->symbols[k]->sym_index;
771 ElfW(Sym) *imp_sym = (ElfW(Sym) *)pe->s1->dynsymtab_section->data + sym_index;
772 ElfW(Sym) *org_sym = (ElfW(Sym) *)symtab_section->data + iat_index;
773 const char *name = pe->s1->dynsymtab_section->link->data + imp_sym->st_name;
775 org_sym->st_value = thk_ptr;
776 org_sym->st_shndx = pe->thunk->sh_num;
777 v = pe->thunk->data_offset + rva_base;
778 section_ptr_add(pe->thunk, sizeof(WORD)); /* hint, not used */
779 put_elf_str(pe->thunk, name);
780 #ifdef TCC_IS_NATIVE
781 if (pe->type == PE_RUN) {
782 DLLReference *dllref = pe->s1->loaded_dlls[imp_sym->st_value-1];
783 if ( !dllref->handle )
784 dllref->handle = LoadLibrary(dllref->name);
785 v = (ADDR3264)GetProcAddress(dllref->handle, name);
786 if (!v)
787 error_noabort("undefined symbol '%s'", name);
789 #endif
790 } else {
791 v = 0; /* last entry is zero */
793 *(ADDR3264*)(pe->thunk->data+thk_ptr) =
794 *(ADDR3264*)(pe->thunk->data+ent_ptr) = v;
795 thk_ptr += sizeof (ADDR3264);
796 ent_ptr += sizeof (ADDR3264);
798 dll_ptr += sizeof(IMAGE_IMPORT_DESCRIPTOR);
799 dynarray_reset(&p->symbols, &p->sym_count);
801 dynarray_reset(&pe->imp_info, &pe->imp_count);
804 /* ------------------------------------------------------------- */
806 For now only functions are exported. Export of data
807 would work, but import requires compiler support to
808 do an additional indirection.
810 For instance:
811 __declspec(dllimport) extern int something;
813 needs to be translated to:
815 *(int*)something
818 struct pe_sort_sym
820 int index;
821 const char *name;
824 ST_FN int sym_cmp(const void *va, const void *vb)
826 const char *ca = (*(struct pe_sort_sym**)va)->name;
827 const char *cb = (*(struct pe_sort_sym**)vb)->name;
828 return strcmp(ca, cb);
831 ST_FN void pe_build_exports(struct pe_info *pe)
833 ElfW(Sym) *sym;
834 int sym_index, sym_end;
835 DWORD rva_base, func_o, name_o, ord_o, str_o;
836 IMAGE_EXPORT_DIRECTORY *hdr;
837 int sym_count, ord;
838 struct pe_sort_sym **sorted, *p;
840 FILE *op;
841 char buf[MAX_PATH];
842 const char *dllname;
843 const char *name;
845 rva_base = pe->thunk->sh_addr - pe->imagebase;
846 sym_count = 0, sorted = NULL, op = NULL;
848 sym_end = symtab_section->data_offset / sizeof(ElfW(Sym));
849 for (sym_index = 1; sym_index < sym_end; ++sym_index) {
850 sym = (ElfW(Sym)*)symtab_section->data + sym_index;
851 name = symtab_section->link->data + sym->st_name;
852 if ((sym->st_other & 1)
853 /* export only symbols from actually written sections */
854 && pe->s1->sections[sym->st_shndx]->sh_addr) {
855 p = tcc_malloc(sizeof *p);
856 p->index = sym_index;
857 p->name = name;
858 dynarray_add((void***)&sorted, &sym_count, p);
860 #if 0
861 if (sym->st_other & 1)
862 printf("export: %s\n", name);
863 if (sym->st_other & 2)
864 printf("stdcall: %s\n", name);
865 #endif
868 if (0 == sym_count)
869 return;
871 qsort (sorted, sym_count, sizeof *sorted, sym_cmp);
873 pe_align_section(pe->thunk, 16);
874 dllname = tcc_basename(pe->filename);
876 pe->exp_offs = pe->thunk->data_offset;
877 func_o = pe->exp_offs + sizeof(IMAGE_EXPORT_DIRECTORY);
878 name_o = func_o + sym_count * sizeof (DWORD);
879 ord_o = name_o + sym_count * sizeof (DWORD);
880 str_o = ord_o + sym_count * sizeof(WORD);
882 hdr = section_ptr_add(pe->thunk, str_o - pe->exp_offs);
883 hdr->Characteristics = 0;
884 hdr->Base = 1;
885 hdr->NumberOfFunctions = sym_count;
886 hdr->NumberOfNames = sym_count;
887 hdr->AddressOfFunctions = func_o + rva_base;
888 hdr->AddressOfNames = name_o + rva_base;
889 hdr->AddressOfNameOrdinals = ord_o + rva_base;
890 hdr->Name = str_o + rva_base;
891 put_elf_str(pe->thunk, dllname);
893 #if 1
894 /* automatically write exports to <output-filename>.def */
895 strcpy(buf, pe->filename);
896 strcpy(tcc_fileextension(buf), ".def");
897 op = fopen(buf, "w");
898 if (NULL == op) {
899 error_noabort("could not create '%s': %s", buf, strerror(errno));
900 } else {
901 fprintf(op, "LIBRARY %s\n\nEXPORTS\n", dllname);
902 if (pe->s1->verbose)
903 printf("<- %s (%d symbols)\n", buf, sym_count);
905 #endif
907 for (ord = 0; ord < sym_count; ++ord)
909 p = sorted[ord], sym_index = p->index, name = p->name;
910 /* insert actual address later in pe_relocate_rva */
911 put_elf_reloc(symtab_section, pe->thunk,
912 func_o, R_XXX_RELATIVE, sym_index);
913 *(DWORD*)(pe->thunk->data + name_o)
914 = pe->thunk->data_offset + rva_base;
915 *(WORD*)(pe->thunk->data + ord_o)
916 = ord;
917 put_elf_str(pe->thunk, name);
918 func_o += sizeof (DWORD);
919 name_o += sizeof (DWORD);
920 ord_o += sizeof (WORD);
921 if (op)
922 fprintf(op, "%s\n", name);
924 pe->exp_size = pe->thunk->data_offset - pe->exp_offs;
925 dynarray_reset(&sorted, &sym_count);
928 /* ------------------------------------------------------------- */
929 ST_FN void pe_build_reloc (struct pe_info *pe)
931 DWORD offset, block_ptr, addr;
932 int count, i;
933 ElfW_Rel *rel, *rel_end;
934 Section *s = NULL, *sr;
936 offset = addr = block_ptr = count = i = 0;
937 rel = rel_end = NULL;
939 for(;;) {
940 if (rel < rel_end) {
941 int type = ELFW_R_(TYPE)(rel->r_info);
942 addr = rel->r_offset + s->sh_addr;
943 ++ rel;
944 if (type != REL_TYPE_DIRECT)
945 continue;
946 if (count == 0) { /* new block */
947 block_ptr = pe->reloc->data_offset;
948 section_ptr_add(pe->reloc, sizeof(struct pe_reloc_header));
949 offset = addr & 0xFFFFFFFF<<12;
951 if ((addr -= offset) < (1<<12)) { /* one block spans 4k addresses */
952 WORD *wp = section_ptr_add(pe->reloc, sizeof (WORD));
953 *wp = addr | IMAGE_REL_BASED_HIGHLOW<<12;
954 ++count;
955 continue;
957 -- rel;
959 } else if (i < pe->sec_count) {
960 sr = (s = pe->s1->sections[pe->sec_info[i++].ord])->reloc;
961 if (sr) {
962 rel = (ElfW_Rel *)sr->data;
963 rel_end = (ElfW_Rel *)(sr->data + sr->data_offset);
965 continue;
968 if (count) {
969 /* store the last block and ready for a new one */
970 struct pe_reloc_header *hdr;
971 if (count & 1) /* align for DWORDS */
972 section_ptr_add(pe->reloc, sizeof(WORD)), ++count;
973 hdr = (struct pe_reloc_header *)(pe->reloc->data + block_ptr);
974 hdr -> offset = offset - pe->imagebase;
975 hdr -> size = count * sizeof(WORD) + sizeof(struct pe_reloc_header);
976 count = 0;
979 if (rel >= rel_end)
980 break;
984 /* ------------------------------------------------------------- */
985 ST_FN int pe_section_class(Section *s)
987 int type, flags;
988 const char *name;
990 type = s->sh_type;
991 flags = s->sh_flags;
992 name = s->name;
993 if (flags & SHF_ALLOC) {
994 if (type == SHT_PROGBITS) {
995 if (flags & SHF_EXECINSTR)
996 return sec_text;
997 if (flags & SHF_WRITE)
998 return sec_data;
999 if (0 == strcmp(name, ".rsrc"))
1000 return sec_rsrc;
1001 if (0 == strcmp(name, ".iedat"))
1002 return sec_idata;
1003 return sec_other;
1004 } else if (type == SHT_NOBITS) {
1005 if (flags & SHF_WRITE)
1006 return sec_bss;
1008 } else {
1009 if (0 == strcmp(name, ".reloc"))
1010 return sec_reloc;
1011 if (0 == strncmp(name, ".stab", 5)) /* .stab and .stabstr */
1012 return sec_stab;
1014 return -1;
1017 ST_FN int pe_assign_addresses (struct pe_info *pe)
1019 int i, k, o, c;
1020 DWORD addr;
1021 int *section_order;
1022 struct section_info *si;
1023 Section *s;
1025 // pe->thunk = new_section(pe->s1, ".iedat", SHT_PROGBITS, SHF_ALLOC);
1027 section_order = tcc_malloc(pe->s1->nb_sections * sizeof (int));
1028 for (o = k = 0 ; k < sec_last; ++k) {
1029 for (i = 1; i < pe->s1->nb_sections; ++i) {
1030 s = pe->s1->sections[i];
1031 if (k == pe_section_class(s)) {
1032 // printf("%s %d\n", s->name, k);
1033 s->sh_addr = pe->imagebase;
1034 section_order[o++] = i;
1039 pe->sec_info = tcc_mallocz(o * sizeof (struct section_info));
1040 addr = pe->imagebase + 1;
1042 for (i = 0; i < o; ++i)
1044 k = section_order[i];
1045 s = pe->s1->sections[k];
1046 c = pe_section_class(s);
1047 si = &pe->sec_info[pe->sec_count];
1049 #ifdef PE_MERGE_DATA
1050 if (c == sec_bss && pe->sec_count && si[-1].cls == sec_data) {
1051 /* append .bss to .data */
1052 s->sh_addr = addr = ((addr-1) | 15) + 1;
1053 addr += s->data_offset;
1054 si[-1].sh_size = addr - si[-1].sh_addr;
1055 continue;
1057 #endif
1058 strcpy(si->name, s->name);
1059 si->cls = c;
1060 si->ord = k;
1061 si->sh_addr = s->sh_addr = addr = pe_virtual_align(addr);
1062 si->sh_flags = s->sh_flags;
1064 if (c == sec_data && NULL == pe->thunk)
1065 pe->thunk = s;
1067 if (s == pe->thunk) {
1068 pe_build_imports(pe);
1069 pe_build_exports(pe);
1072 if (c == sec_reloc)
1073 pe_build_reloc (pe);
1075 if (s->data_offset)
1077 if (s->sh_type != SHT_NOBITS) {
1078 si->data = s->data;
1079 si->data_size = s->data_offset;
1082 addr += s->data_offset;
1083 si->sh_size = s->data_offset;
1084 ++pe->sec_count;
1086 // printf("%08x %05x %s\n", si->sh_addr, si->sh_size, si->name);
1089 #if 0
1090 for (i = 1; i < pe->s1->nb_sections; ++i) {
1091 Section *s = pe->s1->sections[i];
1092 int type = s->sh_type;
1093 int flags = s->sh_flags;
1094 printf("section %-16s %-10s %5x %s,%s,%s\n",
1095 s->name,
1096 type == SHT_PROGBITS ? "progbits" :
1097 type == SHT_NOBITS ? "nobits" :
1098 type == SHT_SYMTAB ? "symtab" :
1099 type == SHT_STRTAB ? "strtab" :
1100 type == SHT_RELX ? "rel" : "???",
1101 s->data_offset,
1102 flags & SHF_ALLOC ? "alloc" : "",
1103 flags & SHF_WRITE ? "write" : "",
1104 flags & SHF_EXECINSTR ? "exec" : ""
1107 pe->s1->verbose = 2;
1108 #endif
1110 tcc_free(section_order);
1111 return 0;
1114 /* ------------------------------------------------------------- */
1115 ST_FN void pe_relocate_rva (struct pe_info *pe, Section *s)
1117 Section *sr = s->reloc;
1118 ElfW_Rel *rel, *rel_end;
1119 rel_end = (ElfW_Rel *)(sr->data + sr->data_offset);
1120 for(rel = (ElfW_Rel *)sr->data; rel < rel_end; rel++) {
1121 if (ELFW_R_(TYPE)(rel->r_info) == R_XXX_RELATIVE) {
1122 int sym_index = ELFW_R_(SYM)(rel->r_info);
1123 DWORD addr = s->sh_addr;
1124 if (sym_index) {
1125 ElfW(Sym) *sym = (ElfW(Sym) *)symtab_section->data + sym_index;
1126 addr = sym->st_value;
1128 // printf("reloc rva %08x %08x\n", (DWORD)rel->r_offset, addr);
1129 *(DWORD*)(s->data + rel->r_offset) += addr - pe->imagebase;
1134 /*----------------------------------------------------------------------------*/
1135 ST_FN int pe_check_symbols(struct pe_info *pe)
1137 ElfW(Sym) *sym;
1138 int sym_index, sym_end;
1139 int ret = 0;
1141 pe_align_section(text_section, 8);
1143 sym_end = symtab_section->data_offset / sizeof(ElfW(Sym));
1144 for (sym_index = 1; sym_index < sym_end; ++sym_index) {
1146 sym = (ElfW(Sym) *)symtab_section->data + sym_index;
1147 if (sym->st_shndx == SHN_UNDEF) {
1149 const char *name = symtab_section->link->data + sym->st_name;
1150 unsigned type = ELFW_ST_TYPE(sym->st_info);
1151 int imp_sym = pe_find_import(pe->s1, name);
1152 struct import_symbol *is;
1154 if (0 == imp_sym)
1155 goto not_found;
1156 is = pe_add_import(pe, imp_sym);
1157 if (!is)
1158 goto not_found;
1160 if (type == STT_FUNC) {
1161 unsigned long offset = is->thk_offset;
1162 if (offset) {
1163 /* got aliased symbol, like stricmp and _stricmp */
1165 } else {
1166 char buffer[100];
1167 WORD *p;
1169 offset = text_section->data_offset;
1170 /* add the 'jmp IAT[x]' instruction */
1171 p = section_ptr_add(text_section, 8);
1172 *p = 0x25FF;
1173 #ifdef TCC_TARGET_X86_64
1174 *(DWORD*)(p+1) = (DWORD)-4;
1175 #endif
1176 /* add a helper symbol, will be patched later in
1177 pe_build_imports */
1178 sprintf(buffer, "IAT.%s", name);
1179 is->iat_index = put_elf_sym(
1180 symtab_section, 0, sizeof(DWORD),
1181 ELFW_ST_INFO(STB_GLOBAL, STT_OBJECT),
1182 0, SHN_UNDEF, buffer);
1183 put_elf_reloc(symtab_section, text_section,
1184 offset + 2, R_XXX_THUNKFIX, is->iat_index);
1185 is->thk_offset = offset;
1188 /* tcc_realloc might have altered sym's address */
1189 sym = (ElfW(Sym) *)symtab_section->data + sym_index;
1191 /* patch the original symbol */
1192 sym->st_value = offset;
1193 sym->st_shndx = text_section->sh_num;
1194 sym->st_other &= ~1; /* do not export */
1195 continue;
1198 if (type == STT_OBJECT) { /* data, ptr to that should be */
1199 if (0 == is->iat_index) {
1200 /* original symbol will be patched later in pe_build_imports */
1201 is->iat_index = sym_index;
1202 continue;
1206 not_found:
1207 error_noabort("undefined symbol '%s'", name);
1208 ret = 1;
1210 } else if (pe->s1->rdynamic
1211 && ELFW_ST_BIND(sym->st_info) != STB_LOCAL) {
1212 /* if -rdynamic option, then export all non local symbols */
1213 sym->st_other |= 1;
1216 return ret;
1219 /*----------------------------------------------------------------------------*/
1220 #ifdef PE_PRINT_SECTIONS
1221 ST_FN void pe_print_section(FILE * f, Section * s)
1223 /* just if you'r curious */
1224 BYTE *p, *e, b;
1225 int i, n, l, m;
1226 p = s->data;
1227 e = s->data + s->data_offset;
1228 l = e - p;
1230 fprintf(f, "section \"%s\"", s->name);
1231 if (s->link)
1232 fprintf(f, "\nlink \"%s\"", s->link->name);
1233 if (s->reloc)
1234 fprintf(f, "\nreloc \"%s\"", s->reloc->name);
1235 fprintf(f, "\nv_addr %08X", (unsigned)s->sh_addr);
1236 fprintf(f, "\ncontents %08X", (unsigned)l);
1237 fprintf(f, "\n\n");
1239 if (s->sh_type == SHT_NOBITS)
1240 return;
1242 if (0 == l)
1243 return;
1245 if (s->sh_type == SHT_SYMTAB)
1246 m = sizeof(ElfW(Sym));
1247 else if (s->sh_type == SHT_RELX)
1248 m = sizeof(ElfW_Rel);
1249 else
1250 m = 16;
1252 fprintf(f, "%-8s", "offset");
1253 for (i = 0; i < m; ++i)
1254 fprintf(f, " %02x", i);
1255 n = 56;
1257 if (s->sh_type == SHT_SYMTAB || s->sh_type == SHT_RELX) {
1258 const char *fields1[] = {
1259 "name",
1260 "value",
1261 "size",
1262 "bind",
1263 "type",
1264 "other",
1265 "shndx",
1266 NULL
1269 const char *fields2[] = {
1270 "offs",
1271 "type",
1272 "symb",
1273 NULL
1276 const char **p;
1278 if (s->sh_type == SHT_SYMTAB)
1279 p = fields1, n = 106;
1280 else
1281 p = fields2, n = 58;
1283 for (i = 0; p[i]; ++i)
1284 fprintf(f, "%6s", p[i]);
1285 fprintf(f, " symbol");
1288 fprintf(f, "\n");
1289 for (i = 0; i < n; ++i)
1290 fprintf(f, "-");
1291 fprintf(f, "\n");
1293 for (i = 0; i < l;)
1295 fprintf(f, "%08X", i);
1296 for (n = 0; n < m; ++n) {
1297 if (n + i < l)
1298 fprintf(f, " %02X", p[i + n]);
1299 else
1300 fprintf(f, " ");
1303 if (s->sh_type == SHT_SYMTAB) {
1304 ElfW(Sym) *sym = (ElfW(Sym) *) (p + i);
1305 const char *name = s->link->data + sym->st_name;
1306 fprintf(f, " %04X %04X %04X %02X %02X %02X %04X \"%s\"",
1307 (unsigned)sym->st_name,
1308 (unsigned)sym->st_value,
1309 (unsigned)sym->st_size,
1310 (unsigned)ELFW_ST_BIND(sym->st_info),
1311 (unsigned)ELFW_ST_TYPE(sym->st_info),
1312 (unsigned)sym->st_other,
1313 (unsigned)sym->st_shndx,
1314 name);
1316 } else if (s->sh_type == SHT_RELX) {
1317 ElfW_Rel *rel = (ElfW_Rel *) (p + i);
1318 ElfW(Sym) *sym =
1319 (ElfW(Sym) *) s->link->data + ELFW_R_(SYM)(rel->r_info);
1320 const char *name = s->link->link->data + sym->st_name;
1321 fprintf(f, " %04X %02X %04X \"%s\"",
1322 (unsigned)rel->r_offset,
1323 (unsigned)ELFW_R_(TYPE)(rel->r_info),
1324 (unsigned)ELFW_R_(SYM)(rel->r_info),
1325 name);
1326 } else {
1327 fprintf(f, " ");
1328 for (n = 0; n < m; ++n) {
1329 if (n + i < l) {
1330 b = p[i + n];
1331 if (b < 32 || b >= 127)
1332 b = '.';
1333 fprintf(f, "%c", b);
1337 i += m;
1338 fprintf(f, "\n");
1340 fprintf(f, "\n\n");
1343 ST_FN void pe_print_sections(TCCState *s1, const char *fname)
1345 Section *s;
1346 FILE *f;
1347 int i;
1348 f = fopen(fname, "w");
1349 for (i = 1; i < s1->nb_sections; ++i) {
1350 s = s1->sections[i];
1351 pe_print_section(f, s);
1353 pe_print_section(f, s1->dynsymtab_section);
1354 fclose(f);
1356 #endif
1358 /* -------------------------------------------------------------
1359 * This is for compiled windows resources in 'coff' format
1360 * as generated by 'windres.exe -O coff ...'.
1363 PUB_FN int pe_test_res_file(void *v, int size)
1365 struct pe_rsrc_header *p = (struct pe_rsrc_header *)v;
1366 return
1367 size >= IMAGE_SIZEOF_FILE_HEADER + IMAGE_SIZEOF_SHORT_NAME /* = 28 */
1368 && p->filehdr.Machine == 0x014C
1369 && 1 == p->filehdr.NumberOfSections
1370 && 0 == strcmp(p->sectionhdr.Name, ".rsrc")
1374 ST_FN int read_n(int fd, void *ptr, unsigned size)
1376 return size == read(fd, ptr, size);
1379 PUB_FN int pe_load_res_file(TCCState *s1, int fd)
1381 struct pe_rsrc_header hdr;
1382 Section *rsrc_section;
1383 int i, ret = -1;
1384 BYTE *ptr;
1386 lseek (fd, 0, SEEK_SET);
1387 if (!read_n(fd, &hdr, sizeof hdr))
1388 goto quit;
1389 if (!pe_test_res_file(&hdr, sizeof hdr))
1390 goto quit;
1392 rsrc_section = new_section(s1, ".rsrc", SHT_PROGBITS, SHF_ALLOC);
1393 ptr = section_ptr_add(rsrc_section, hdr.sectionhdr.SizeOfRawData);
1394 lseek (fd, hdr.sectionhdr.PointerToRawData, SEEK_SET);
1395 if (!read_n(fd, ptr, hdr.sectionhdr.SizeOfRawData))
1396 goto quit;
1398 lseek (fd, hdr.sectionhdr.PointerToRelocations, SEEK_SET);
1399 for (i = 0; i < hdr.sectionhdr.NumberOfRelocations; ++i)
1401 struct pe_rsrc_reloc rel;
1402 if (!read_n(fd, &rel, sizeof rel))
1403 goto quit;
1404 // printf("rsrc_reloc: %x %x %x\n", rel.offset, rel.size, rel.type);
1405 if (rel.type != 7) /* DIR32NB */
1406 goto quit;
1407 put_elf_reloc(symtab_section, rsrc_section,
1408 rel.offset, R_XXX_RELATIVE, 0);
1410 ret = 0;
1411 quit:
1412 if (ret)
1413 error_noabort("unrecognized resource file format");
1414 return ret;
1417 /* ------------------------------------------------------------- */
1418 ST_FN char *trimfront(char *p)
1420 while (*p && (unsigned char)*p <= ' ')
1421 ++p;
1422 return p;
1425 ST_FN char *trimback(char *a, char *e)
1427 while (e > a && (unsigned char)e[-1] <= ' ')
1428 --e;
1429 *e = 0;;
1430 return a;
1433 ST_FN char *get_line(char *line, int size, FILE *fp)
1435 if (NULL == fgets(line, size, fp))
1436 return NULL;
1437 trimback(line, strchr(line, 0));
1438 return trimfront(line);
1441 /* ------------------------------------------------------------- */
1442 PUB_FN int pe_load_def_file(TCCState *s1, int fd)
1444 DLLReference *dllref;
1445 int state = 0, ret = -1;
1446 char line[400], dllname[80], *p;
1447 FILE *fp = fdopen(dup(fd), "rb");
1449 if (NULL == fp)
1450 goto quit;
1452 for (;;) {
1453 p = get_line(line, sizeof line, fp);
1454 if (NULL == p)
1455 break;
1456 if (0 == *p || ';' == *p)
1457 continue;
1458 switch (state) {
1459 case 0:
1460 if (0 != strnicmp(p, "LIBRARY", 7))
1461 goto quit;
1462 strcpy(dllname, trimfront(p+7));
1463 ++state;
1464 continue;
1466 case 1:
1467 if (0 != stricmp(p, "EXPORTS"))
1468 goto quit;
1469 ++state;
1470 continue;
1472 case 2:
1473 dllref = tcc_mallocz(sizeof(DLLReference) + strlen(dllname));
1474 strcpy(dllref->name, dllname);
1475 dynarray_add((void ***) &s1->loaded_dlls, &s1->nb_loaded_dlls, dllref);
1476 ++state;
1478 default:
1479 add_elf_sym(s1->dynsymtab_section,
1480 s1->nb_loaded_dlls, 0,
1481 ELFW_ST_INFO(STB_GLOBAL, STT_FUNC), 0,
1482 text_section->sh_num, p);
1483 continue;
1486 ret = 0;
1487 quit:
1488 if (fp)
1489 fclose(fp);
1490 if (ret)
1491 error_noabort("unrecognized export definition file format");
1492 return ret;
1495 /* ------------------------------------------------------------- */
1496 #ifdef TCC_TARGET_X86_64
1497 #define PE_STDSYM(n,s) n
1498 #else
1499 #define PE_STDSYM(n,s) "_" n s
1500 #endif
1502 ST_FN void pe_add_runtime_ex(TCCState *s1, struct pe_info *pe)
1504 const char *start_symbol;
1505 unsigned long addr = 0;
1506 int pe_type = 0;
1508 if (find_elf_sym(symtab_section, PE_STDSYM("WinMain","@16")))
1509 pe_type = PE_GUI;
1510 else
1511 if (TCC_OUTPUT_DLL == s1->output_type) {
1512 pe_type = PE_DLL;
1513 /* need this for 'tccelf.c:relocate_section()' */
1514 s1->output_type = TCC_OUTPUT_EXE;
1517 start_symbol =
1518 TCC_OUTPUT_MEMORY == s1->output_type
1519 ? PE_GUI == pe_type ? "_runwinmain" : NULL
1520 : PE_DLL == pe_type ? PE_STDSYM("_dllstart","@12")
1521 : PE_GUI == pe_type ? "_winstart" : "_start"
1524 /* grab the startup code from libtcc1 */
1525 if (start_symbol)
1526 add_elf_sym(symtab_section,
1527 0, 0,
1528 ELFW_ST_INFO(STB_GLOBAL, STT_NOTYPE), 0,
1529 SHN_UNDEF, start_symbol);
1531 if (0 == s1->nostdlib) {
1532 static const char *libs[] = {
1533 "tcc1", "msvcrt", "kernel32", "", "user32", "gdi32", NULL
1535 const char **pp, *p;
1536 for (pp = libs; 0 != (p = *pp); ++pp) {
1537 if (0 == *p) {
1538 if (PE_DLL != pe_type && PE_GUI != pe_type)
1539 break;
1540 } else if (tcc_add_library(s1, p) < 0)
1541 error_noabort("cannot find library: %s", p);
1545 if (start_symbol) {
1546 addr = (uplong)tcc_get_symbol_err(s1, start_symbol);
1547 if (s1->output_type == TCC_OUTPUT_MEMORY && addr)
1548 /* for -run GUI's, put '_runwinmain' instead of 'main' */
1549 add_elf_sym(symtab_section,
1550 addr, 0,
1551 ELFW_ST_INFO(STB_GLOBAL, STT_NOTYPE), 0,
1552 text_section->sh_num, "main");
1555 pe->type = pe_type;
1556 pe->start_addr = addr;
1559 PUB_FN int pe_output_file(TCCState * s1, const char *filename)
1561 int ret;
1562 struct pe_info pe;
1563 int i;
1565 memset(&pe, 0, sizeof pe);
1566 pe.filename = filename;
1567 pe.s1 = s1;
1569 pe_add_runtime_ex(s1, &pe);
1570 relocate_common_syms(); /* assign bss adresses */
1571 tcc_add_linker_symbols(s1);
1573 ret = pe_check_symbols(&pe);
1574 if (ret)
1575 return ret;
1577 if (filename) {
1578 if (PE_DLL == pe.type) {
1579 pe.reloc = new_section(pe.s1, ".reloc", SHT_PROGBITS, 0);
1580 pe.imagebase = 0x10000000;
1581 } else {
1582 pe.imagebase = 0x00400000;
1584 pe_assign_addresses(&pe);
1585 relocate_syms(s1, 0);
1586 for (i = 1; i < s1->nb_sections; ++i) {
1587 Section *s = s1->sections[i];
1588 if (s->reloc) {
1589 relocate_section(s1, s);
1590 pe_relocate_rva(&pe, s);
1593 if (s1->nb_errors)
1594 ret = 1;
1595 else
1596 ret = pe_write(&pe);
1597 tcc_free(pe.sec_info);
1598 } else {
1599 #ifndef TCC_IS_NATIVE
1600 error_noabort("-run supported only on native platform");
1601 #endif
1602 pe.type = PE_RUN;
1603 pe.thunk = data_section;
1604 pe_build_imports(&pe);
1607 #ifdef PE_PRINT_SECTIONS
1608 pe_print_sections(s1, "tcc.log");
1609 #endif
1610 return ret;
1613 /* ------------------------------------------------------------- */
1614 #endif /* def TCC_TARGET_PE */
1615 /* ------------------------------------------------------------- */