win64: align jmp_buf
[tinycc/kirr.git] / tccpe.c
blobac3688f4e63231f0bdd0e1b804ad494f43982dd8
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 #ifdef TCC_TARGET_X86_64
354 // need to have a __chkstk eventually
355 0x00008000, /*DWORD SizeOfStackCommit; */
356 #else
357 0x00001000, /*DWORD SizeOfStackCommit; */
358 #endif
359 0x00100000, /*DWORD SizeOfHeapReserve; */
360 0x00001000, /*DWORD SizeOfHeapCommit; */
361 0x00000000, /*DWORD LoaderFlags; */
362 0x00000010, /*DWORD NumberOfRvaAndSizes; */
364 /* IMAGE_DATA_DIRECTORY DataDirectory[16]; */
365 {{0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0},
366 {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}}
369 /* ------------------------------------------------------------- */
370 /* internal temporary structures */
373 #define IMAGE_SCN_CNT_CODE 0x00000020
374 #define IMAGE_SCN_CNT_INITIALIZED_DATA 0x00000040
375 #define IMAGE_SCN_CNT_UNINITIALIZED_DATA 0x00000080
376 #define IMAGE_SCN_MEM_DISCARDABLE 0x02000000
377 #define IMAGE_SCN_MEM_SHARED 0x10000000
378 #define IMAGE_SCN_MEM_EXECUTE 0x20000000
379 #define IMAGE_SCN_MEM_READ 0x40000000
380 #define IMAGE_SCN_MEM_WRITE 0x80000000
383 enum {
384 sec_text = 0,
385 sec_data ,
386 sec_bss ,
387 sec_idata ,
388 sec_other ,
389 sec_rsrc ,
390 sec_stab ,
391 sec_reloc ,
392 sec_last
395 ST_DATA DWORD pe_sec_flags[] = {
396 0x60000020, /* ".text" , */
397 0xC0000040, /* ".data" , */
398 0xC0000080, /* ".bss" , */
399 0x40000040, /* ".idata" , */
400 0xE0000060, /* < other > , */
401 0x40000040, /* ".rsrc" , */
402 0x42000802, /* ".stab" , */
403 0x42000040, /* ".reloc" , */
406 struct section_info {
407 int cls, ord;
408 char name[32];
409 DWORD sh_addr;
410 DWORD sh_size;
411 DWORD sh_flags;
412 unsigned char *data;
413 DWORD data_size;
414 IMAGE_SECTION_HEADER ish;
417 struct import_symbol {
418 int sym_index;
419 int iat_index;
420 int thk_offset;
423 struct pe_import_info {
424 int dll_index;
425 int sym_count;
426 struct import_symbol **symbols;
429 struct pe_info {
430 TCCState *s1;
431 Section *reloc;
432 Section *thunk;
433 const char *filename;
434 int type;
435 DWORD sizeofheaders;
436 DWORD imagebase;
437 DWORD start_addr;
438 DWORD imp_offs;
439 DWORD imp_size;
440 DWORD iat_offs;
441 DWORD iat_size;
442 DWORD exp_offs;
443 DWORD exp_size;
444 struct section_info *sec_info;
445 int sec_count;
446 struct pe_import_info **imp_info;
447 int imp_count;
450 /* ------------------------------------------------------------- */
452 #define PE_NUL 0
453 #define PE_DLL 1
454 #define PE_GUI 2
455 #define PE_EXE 3
456 #define PE_RUN 4
458 void error_noabort(const char *, ...);
460 #ifdef _WIN32
461 void dbg_printf (const char *fmt, ...)
463 char buffer[4000];
464 va_list arg;
465 int x;
466 va_start(arg, fmt);
467 x = vsprintf (buffer, fmt, arg);
468 strcpy(buffer+x, "\n");
469 OutputDebugString(buffer);
471 #endif
473 /* --------------------------------------------*/
475 ST_FN const char* get_alt_symbol(char *buffer, const char *symbol)
477 const char *p;
478 p = strrchr(symbol, '@');
479 if (p && isnum(p[1]) && symbol[0] == '_') { /* stdcall decor */
480 strcpy(buffer, symbol+1)[p-symbol-1] = 0;
481 } else if (symbol[0] != '_') { /* try non-ansi function */
482 buffer[0] = '_', strcpy(buffer + 1, symbol);
483 } else if (0 == memcmp(symbol, "__imp__", 7)) { /* mingw 2.0 */
484 strcpy(buffer, symbol + 6);
485 } else if (0 == memcmp(symbol, "_imp___", 7)) { /* mingw 3.7 */
486 strcpy(buffer, symbol + 6);
487 } else {
488 return symbol;
490 return buffer;
493 ST_FN int pe_find_import(TCCState * s1, const char *symbol)
495 char buffer[200];
496 const char *s;
497 int sym_index, n = 0;
498 do {
499 s = n ? get_alt_symbol(buffer, symbol) : symbol;
500 sym_index = find_elf_sym(s1->dynsymtab_section, s);
501 // printf("find (%d) %d %s\n", n, sym_index, s);
502 } while (0 == sym_index && ++n < 2);
503 return sym_index;
506 /*----------------------------------------------------------------------------*/
508 ST_FN int dynarray_assoc(void **pp, int n, int key)
510 int i;
511 for (i = 0; i < n; ++i, ++pp)
512 if (key == **(int **) pp)
513 return i;
514 return -1;
517 #if 0
518 ST_FN DWORD umin(DWORD a, DWORD b)
520 return a < b ? a : b;
522 #endif
524 ST_FN DWORD umax(DWORD a, DWORD b)
526 return a < b ? b : a;
529 ST_FN void pe_fpad(FILE *fp, DWORD new_pos)
531 DWORD pos = ftell(fp);
532 while (++pos <= new_pos)
533 fputc(0, fp);
536 ST_FN DWORD pe_file_align(DWORD n)
538 return (n + (0x200 - 1)) & ~(0x200 - 1);
541 ST_FN DWORD pe_virtual_align(DWORD n)
543 return (n + (0x1000 - 1)) & ~(0x1000 - 1);
546 ST_FN void pe_align_section(Section *s, int a)
548 int i = s->data_offset & (a-1);
549 if (i)
550 section_ptr_add(s, a - i);
553 ST_FN void pe_set_datadir(int dir, DWORD addr, DWORD size)
555 pe_header.opthdr.DataDirectory[dir].VirtualAddress = addr;
556 pe_header.opthdr.DataDirectory[dir].Size = size;
559 /*----------------------------------------------------------------------------*/
560 ST_FN int pe_write(struct pe_info *pe)
562 int i;
563 FILE *op;
564 DWORD file_offset, r;
566 op = fopen(pe->filename, "wb");
567 if (NULL == op) {
568 error_noabort("could not write '%s': %s", pe->filename, strerror(errno));
569 return 1;
572 pe->sizeofheaders = pe_file_align(
573 sizeof pe_header
574 + pe->sec_count * sizeof (IMAGE_SECTION_HEADER)
577 file_offset = pe->sizeofheaders;
578 pe_fpad(op, file_offset);
580 if (2 == pe->s1->verbose)
581 printf("-------------------------------"
582 "\n virt file size section" "\n");
584 for (i = 0; i < pe->sec_count; ++i) {
585 struct section_info *si = pe->sec_info + i;
586 const char *sh_name = si->name;
587 unsigned long addr = si->sh_addr - pe->imagebase;
588 unsigned long size = si->sh_size;
589 IMAGE_SECTION_HEADER *psh = &si->ish;
591 if (2 == pe->s1->verbose)
592 printf("%6lx %6lx %6lx %s\n",
593 addr, file_offset, size, sh_name);
595 switch (si->cls) {
596 case sec_text:
597 pe_header.opthdr.BaseOfCode = addr;
598 pe_header.opthdr.AddressOfEntryPoint = addr + pe->start_addr;
599 break;
601 case sec_data:
602 #ifndef TCC_TARGET_X86_64
603 pe_header.opthdr.BaseOfData = addr;
604 #endif
605 break;
607 case sec_bss:
608 break;
610 case sec_reloc:
611 pe_set_datadir(IMAGE_DIRECTORY_ENTRY_BASERELOC, addr, size);
612 break;
614 case sec_rsrc:
615 pe_set_datadir(IMAGE_DIRECTORY_ENTRY_RESOURCE, addr, size);
616 break;
618 case sec_stab:
619 break;
622 if (pe->thunk == pe->s1->sections[si->ord]) {
623 if (pe->imp_size) {
624 pe_set_datadir(IMAGE_DIRECTORY_ENTRY_IMPORT,
625 pe->imp_offs + addr, pe->imp_size);
626 pe_set_datadir(IMAGE_DIRECTORY_ENTRY_IAT,
627 pe->iat_offs + addr, pe->iat_size);
629 if (pe->exp_size) {
630 pe_set_datadir(IMAGE_DIRECTORY_ENTRY_EXPORT,
631 pe->exp_offs + addr, pe->exp_size);
635 strcpy((char*)psh->Name, sh_name);
637 psh->Characteristics = pe_sec_flags[si->cls];
638 psh->VirtualAddress = addr;
639 psh->Misc.VirtualSize = size;
640 pe_header.opthdr.SizeOfImage =
641 umax(pe_virtual_align(size + addr), pe_header.opthdr.SizeOfImage);
643 if (si->data_size) {
644 psh->PointerToRawData = r = file_offset;
645 fwrite(si->data, 1, si->data_size, op);
646 file_offset = pe_file_align(file_offset + si->data_size);
647 psh->SizeOfRawData = file_offset - r;
648 pe_fpad(op, file_offset);
652 // pe_header.filehdr.TimeDateStamp = time(NULL);
653 pe_header.filehdr.NumberOfSections = pe->sec_count;
654 pe_header.opthdr.SizeOfHeaders = pe->sizeofheaders;
655 pe_header.opthdr.ImageBase = pe->imagebase;
656 if (PE_DLL == pe->type)
657 pe_header.filehdr.Characteristics = CHARACTERISTICS_DLL;
658 else if (PE_GUI != pe->type)
659 pe_header.opthdr.Subsystem = 3;
661 fseek(op, SEEK_SET, 0);
662 fwrite(&pe_header, 1, sizeof pe_header, op);
663 for (i = 0; i < pe->sec_count; ++i)
664 fwrite(&pe->sec_info[i].ish, 1, sizeof(IMAGE_SECTION_HEADER), op);
665 fclose (op);
667 if (2 == pe->s1->verbose)
668 printf("-------------------------------\n");
669 if (pe->s1->verbose)
670 printf("<- %s (%lu bytes)\n", pe->filename, file_offset);
672 return 0;
675 /*----------------------------------------------------------------------------*/
677 #ifdef TCC_TARGET_X86_64
678 #define ELFW_R_(type) ELF64_R_##type
679 #define ElfW_Rel ElfW(Rela)
681 #define REL_TYPE_DIRECT R_X86_64_64
682 #define R_XXX_THUNKFIX R_X86_64_PC32
683 #define R_XXX_RELATIVE R_X86_64_RELATIVE
685 #define ELFW_ST_BIND ELF64_ST_BIND
686 #define ELFW_ST_TYPE ELF64_ST_TYPE
687 #define ELFW_ST_INFO ELF64_ST_INFO
688 #else
689 #define ELFW_R_(type) ELF32_R_##type
690 #define ElfW_Rel ElfW(Rel)
692 #define REL_TYPE_DIRECT R_386_32
693 #define R_XXX_THUNKFIX R_386_32
694 #define R_XXX_RELATIVE R_386_RELATIVE
696 #define ELFW_ST_BIND ELF32_ST_BIND
697 #define ELFW_ST_TYPE ELF32_ST_TYPE
698 #define ELFW_ST_INFO ELF32_ST_INFO
699 #endif
700 /*----------------------------------------------------------------------------*/
702 ST_FN struct import_symbol *pe_add_import(struct pe_info *pe, int sym_index)
704 int i;
705 int dll_index;
706 struct pe_import_info *p;
707 struct import_symbol *s;
709 dll_index = ((ElfW(Sym) *)pe->s1->dynsymtab_section->data + sym_index)->st_value;
710 if (0 == dll_index)
711 return NULL;
713 i = dynarray_assoc ((void**)pe->imp_info, pe->imp_count, dll_index);
714 if (-1 != i) {
715 p = pe->imp_info[i];
716 goto found_dll;
718 p = tcc_mallocz(sizeof *p);
719 p->dll_index = dll_index;
720 dynarray_add((void***)&pe->imp_info, &pe->imp_count, p);
722 found_dll:
723 i = dynarray_assoc ((void**)p->symbols, p->sym_count, sym_index);
724 if (-1 != i)
725 return p->symbols[i];
727 s = tcc_mallocz(sizeof *s);
728 dynarray_add((void***)&p->symbols, &p->sym_count, s);
729 s->sym_index = sym_index;
730 return s;
733 /*----------------------------------------------------------------------------*/
734 ST_FN void pe_build_imports(struct pe_info *pe)
736 int thk_ptr, ent_ptr, dll_ptr, sym_cnt, i;
737 DWORD rva_base = pe->thunk->sh_addr - pe->imagebase;
738 int ndlls = pe->imp_count;
740 for (sym_cnt = i = 0; i < ndlls; ++i)
741 sym_cnt += pe->imp_info[i]->sym_count;
743 if (0 == sym_cnt)
744 return;
746 pe_align_section(pe->thunk, 16);
748 pe->imp_offs = dll_ptr = pe->thunk->data_offset;
749 pe->imp_size = (ndlls + 1) * sizeof(IMAGE_IMPORT_DESCRIPTOR);
750 pe->iat_offs = dll_ptr + pe->imp_size;
751 pe->iat_size = (sym_cnt + ndlls) * sizeof(ADDR3264);
752 section_ptr_add(pe->thunk, pe->imp_size + 2*pe->iat_size);
754 thk_ptr = pe->iat_offs;
755 ent_ptr = pe->iat_offs + pe->iat_size;
757 for (i = 0; i < pe->imp_count; ++i) {
758 IMAGE_IMPORT_DESCRIPTOR *hdr;
759 int k, n;
760 ADDR3264 v;
761 struct pe_import_info *p = pe->imp_info[i];
762 const char *name = pe->s1->loaded_dlls[p->dll_index-1]->name;
764 /* put the dll name into the import header */
765 v = put_elf_str(pe->thunk, name);
767 hdr = (IMAGE_IMPORT_DESCRIPTOR*)(pe->thunk->data + dll_ptr);
768 hdr->FirstThunk = thk_ptr + rva_base;
769 hdr->OriginalFirstThunk = ent_ptr + rva_base;
770 hdr->Name = v + rva_base;
772 for (k = 0, n = p->sym_count; k <= n; ++k) {
773 if (k < n) {
774 int iat_index = p->symbols[k]->iat_index;
775 int sym_index = p->symbols[k]->sym_index;
776 ElfW(Sym) *imp_sym = (ElfW(Sym) *)pe->s1->dynsymtab_section->data + sym_index;
777 ElfW(Sym) *org_sym = (ElfW(Sym) *)symtab_section->data + iat_index;
778 const char *name = pe->s1->dynsymtab_section->link->data + imp_sym->st_name;
780 org_sym->st_value = thk_ptr;
781 org_sym->st_shndx = pe->thunk->sh_num;
782 v = pe->thunk->data_offset + rva_base;
783 section_ptr_add(pe->thunk, sizeof(WORD)); /* hint, not used */
784 put_elf_str(pe->thunk, name);
785 #ifdef TCC_IS_NATIVE
786 if (pe->type == PE_RUN) {
787 DLLReference *dllref = pe->s1->loaded_dlls[imp_sym->st_value-1];
788 if ( !dllref->handle )
789 dllref->handle = LoadLibrary(dllref->name);
790 v = (ADDR3264)GetProcAddress(dllref->handle, name);
791 if (!v)
792 error_noabort("undefined symbol '%s'", name);
794 #endif
795 } else {
796 v = 0; /* last entry is zero */
798 *(ADDR3264*)(pe->thunk->data+thk_ptr) =
799 *(ADDR3264*)(pe->thunk->data+ent_ptr) = v;
800 thk_ptr += sizeof (ADDR3264);
801 ent_ptr += sizeof (ADDR3264);
803 dll_ptr += sizeof(IMAGE_IMPORT_DESCRIPTOR);
804 dynarray_reset(&p->symbols, &p->sym_count);
806 dynarray_reset(&pe->imp_info, &pe->imp_count);
809 /* ------------------------------------------------------------- */
811 For now only functions are exported. Export of data
812 would work, but import requires compiler support to
813 do an additional indirection.
815 For instance:
816 __declspec(dllimport) extern int something;
818 needs to be translated to:
820 *(int*)something
823 struct pe_sort_sym
825 int index;
826 const char *name;
829 ST_FN int sym_cmp(const void *va, const void *vb)
831 const char *ca = (*(struct pe_sort_sym**)va)->name;
832 const char *cb = (*(struct pe_sort_sym**)vb)->name;
833 return strcmp(ca, cb);
836 ST_FN void pe_build_exports(struct pe_info *pe)
838 ElfW(Sym) *sym;
839 int sym_index, sym_end;
840 DWORD rva_base, func_o, name_o, ord_o, str_o;
841 IMAGE_EXPORT_DIRECTORY *hdr;
842 int sym_count, ord;
843 struct pe_sort_sym **sorted, *p;
845 FILE *op;
846 char buf[MAX_PATH];
847 const char *dllname;
848 const char *name;
850 rva_base = pe->thunk->sh_addr - pe->imagebase;
851 sym_count = 0, sorted = NULL, op = NULL;
853 sym_end = symtab_section->data_offset / sizeof(ElfW(Sym));
854 for (sym_index = 1; sym_index < sym_end; ++sym_index) {
855 sym = (ElfW(Sym)*)symtab_section->data + sym_index;
856 name = symtab_section->link->data + sym->st_name;
857 if ((sym->st_other & 1)
858 /* export only symbols from actually written sections */
859 && pe->s1->sections[sym->st_shndx]->sh_addr) {
860 p = tcc_malloc(sizeof *p);
861 p->index = sym_index;
862 p->name = name;
863 dynarray_add((void***)&sorted, &sym_count, p);
865 #if 0
866 if (sym->st_other & 1)
867 printf("export: %s\n", name);
868 if (sym->st_other & 2)
869 printf("stdcall: %s\n", name);
870 #endif
873 if (0 == sym_count)
874 return;
876 qsort (sorted, sym_count, sizeof *sorted, sym_cmp);
878 pe_align_section(pe->thunk, 16);
879 dllname = tcc_basename(pe->filename);
881 pe->exp_offs = pe->thunk->data_offset;
882 func_o = pe->exp_offs + sizeof(IMAGE_EXPORT_DIRECTORY);
883 name_o = func_o + sym_count * sizeof (DWORD);
884 ord_o = name_o + sym_count * sizeof (DWORD);
885 str_o = ord_o + sym_count * sizeof(WORD);
887 hdr = section_ptr_add(pe->thunk, str_o - pe->exp_offs);
888 hdr->Characteristics = 0;
889 hdr->Base = 1;
890 hdr->NumberOfFunctions = sym_count;
891 hdr->NumberOfNames = sym_count;
892 hdr->AddressOfFunctions = func_o + rva_base;
893 hdr->AddressOfNames = name_o + rva_base;
894 hdr->AddressOfNameOrdinals = ord_o + rva_base;
895 hdr->Name = str_o + rva_base;
896 put_elf_str(pe->thunk, dllname);
898 #if 1
899 /* automatically write exports to <output-filename>.def */
900 strcpy(buf, pe->filename);
901 strcpy(tcc_fileextension(buf), ".def");
902 op = fopen(buf, "w");
903 if (NULL == op) {
904 error_noabort("could not create '%s': %s", buf, strerror(errno));
905 } else {
906 fprintf(op, "LIBRARY %s\n\nEXPORTS\n", dllname);
907 if (pe->s1->verbose)
908 printf("<- %s (%d symbols)\n", buf, sym_count);
910 #endif
912 for (ord = 0; ord < sym_count; ++ord)
914 p = sorted[ord], sym_index = p->index, name = p->name;
915 /* insert actual address later in pe_relocate_rva */
916 put_elf_reloc(symtab_section, pe->thunk,
917 func_o, R_XXX_RELATIVE, sym_index);
918 *(DWORD*)(pe->thunk->data + name_o)
919 = pe->thunk->data_offset + rva_base;
920 *(WORD*)(pe->thunk->data + ord_o)
921 = ord;
922 put_elf_str(pe->thunk, name);
923 func_o += sizeof (DWORD);
924 name_o += sizeof (DWORD);
925 ord_o += sizeof (WORD);
926 if (op)
927 fprintf(op, "%s\n", name);
929 pe->exp_size = pe->thunk->data_offset - pe->exp_offs;
930 dynarray_reset(&sorted, &sym_count);
933 /* ------------------------------------------------------------- */
934 ST_FN void pe_build_reloc (struct pe_info *pe)
936 DWORD offset, block_ptr, addr;
937 int count, i;
938 ElfW_Rel *rel, *rel_end;
939 Section *s = NULL, *sr;
941 offset = addr = block_ptr = count = i = 0;
942 rel = rel_end = NULL;
944 for(;;) {
945 if (rel < rel_end) {
946 int type = ELFW_R_(TYPE)(rel->r_info);
947 addr = rel->r_offset + s->sh_addr;
948 ++ rel;
949 if (type != REL_TYPE_DIRECT)
950 continue;
951 if (count == 0) { /* new block */
952 block_ptr = pe->reloc->data_offset;
953 section_ptr_add(pe->reloc, sizeof(struct pe_reloc_header));
954 offset = addr & 0xFFFFFFFF<<12;
956 if ((addr -= offset) < (1<<12)) { /* one block spans 4k addresses */
957 WORD *wp = section_ptr_add(pe->reloc, sizeof (WORD));
958 *wp = addr | IMAGE_REL_BASED_HIGHLOW<<12;
959 ++count;
960 continue;
962 -- rel;
964 } else if (i < pe->sec_count) {
965 sr = (s = pe->s1->sections[pe->sec_info[i++].ord])->reloc;
966 if (sr) {
967 rel = (ElfW_Rel *)sr->data;
968 rel_end = (ElfW_Rel *)(sr->data + sr->data_offset);
970 continue;
973 if (count) {
974 /* store the last block and ready for a new one */
975 struct pe_reloc_header *hdr;
976 if (count & 1) /* align for DWORDS */
977 section_ptr_add(pe->reloc, sizeof(WORD)), ++count;
978 hdr = (struct pe_reloc_header *)(pe->reloc->data + block_ptr);
979 hdr -> offset = offset - pe->imagebase;
980 hdr -> size = count * sizeof(WORD) + sizeof(struct pe_reloc_header);
981 count = 0;
984 if (rel >= rel_end)
985 break;
989 /* ------------------------------------------------------------- */
990 ST_FN int pe_section_class(Section *s)
992 int type, flags;
993 const char *name;
995 type = s->sh_type;
996 flags = s->sh_flags;
997 name = s->name;
998 if (flags & SHF_ALLOC) {
999 if (type == SHT_PROGBITS) {
1000 if (flags & SHF_EXECINSTR)
1001 return sec_text;
1002 if (flags & SHF_WRITE)
1003 return sec_data;
1004 if (0 == strcmp(name, ".rsrc"))
1005 return sec_rsrc;
1006 if (0 == strcmp(name, ".iedat"))
1007 return sec_idata;
1008 return sec_other;
1009 } else if (type == SHT_NOBITS) {
1010 if (flags & SHF_WRITE)
1011 return sec_bss;
1013 } else {
1014 if (0 == strcmp(name, ".reloc"))
1015 return sec_reloc;
1016 if (0 == strncmp(name, ".stab", 5)) /* .stab and .stabstr */
1017 return sec_stab;
1019 return -1;
1022 ST_FN int pe_assign_addresses (struct pe_info *pe)
1024 int i, k, o, c;
1025 DWORD addr;
1026 int *section_order;
1027 struct section_info *si;
1028 Section *s;
1030 // pe->thunk = new_section(pe->s1, ".iedat", SHT_PROGBITS, SHF_ALLOC);
1032 section_order = tcc_malloc(pe->s1->nb_sections * sizeof (int));
1033 for (o = k = 0 ; k < sec_last; ++k) {
1034 for (i = 1; i < pe->s1->nb_sections; ++i) {
1035 s = pe->s1->sections[i];
1036 if (k == pe_section_class(s)) {
1037 // printf("%s %d\n", s->name, k);
1038 s->sh_addr = pe->imagebase;
1039 section_order[o++] = i;
1044 pe->sec_info = tcc_mallocz(o * sizeof (struct section_info));
1045 addr = pe->imagebase + 1;
1047 for (i = 0; i < o; ++i)
1049 k = section_order[i];
1050 s = pe->s1->sections[k];
1051 c = pe_section_class(s);
1052 si = &pe->sec_info[pe->sec_count];
1054 #ifdef PE_MERGE_DATA
1055 if (c == sec_bss && pe->sec_count && si[-1].cls == sec_data) {
1056 /* append .bss to .data */
1057 s->sh_addr = addr = ((addr-1) | 15) + 1;
1058 addr += s->data_offset;
1059 si[-1].sh_size = addr - si[-1].sh_addr;
1060 continue;
1062 #endif
1063 strcpy(si->name, s->name);
1064 si->cls = c;
1065 si->ord = k;
1066 si->sh_addr = s->sh_addr = addr = pe_virtual_align(addr);
1067 si->sh_flags = s->sh_flags;
1069 if (c == sec_data && NULL == pe->thunk)
1070 pe->thunk = s;
1072 if (s == pe->thunk) {
1073 pe_build_imports(pe);
1074 pe_build_exports(pe);
1077 if (c == sec_reloc)
1078 pe_build_reloc (pe);
1080 if (s->data_offset)
1082 if (s->sh_type != SHT_NOBITS) {
1083 si->data = s->data;
1084 si->data_size = s->data_offset;
1087 addr += s->data_offset;
1088 si->sh_size = s->data_offset;
1089 ++pe->sec_count;
1091 // printf("%08x %05x %s\n", si->sh_addr, si->sh_size, si->name);
1094 #if 0
1095 for (i = 1; i < pe->s1->nb_sections; ++i) {
1096 Section *s = pe->s1->sections[i];
1097 int type = s->sh_type;
1098 int flags = s->sh_flags;
1099 printf("section %-16s %-10s %5x %s,%s,%s\n",
1100 s->name,
1101 type == SHT_PROGBITS ? "progbits" :
1102 type == SHT_NOBITS ? "nobits" :
1103 type == SHT_SYMTAB ? "symtab" :
1104 type == SHT_STRTAB ? "strtab" :
1105 type == SHT_RELX ? "rel" : "???",
1106 s->data_offset,
1107 flags & SHF_ALLOC ? "alloc" : "",
1108 flags & SHF_WRITE ? "write" : "",
1109 flags & SHF_EXECINSTR ? "exec" : ""
1112 pe->s1->verbose = 2;
1113 #endif
1115 tcc_free(section_order);
1116 return 0;
1119 /* ------------------------------------------------------------- */
1120 ST_FN void pe_relocate_rva (struct pe_info *pe, Section *s)
1122 Section *sr = s->reloc;
1123 ElfW_Rel *rel, *rel_end;
1124 rel_end = (ElfW_Rel *)(sr->data + sr->data_offset);
1125 for(rel = (ElfW_Rel *)sr->data; rel < rel_end; rel++) {
1126 if (ELFW_R_(TYPE)(rel->r_info) == R_XXX_RELATIVE) {
1127 int sym_index = ELFW_R_(SYM)(rel->r_info);
1128 DWORD addr = s->sh_addr;
1129 if (sym_index) {
1130 ElfW(Sym) *sym = (ElfW(Sym) *)symtab_section->data + sym_index;
1131 addr = sym->st_value;
1133 // printf("reloc rva %08x %08x\n", (DWORD)rel->r_offset, addr);
1134 *(DWORD*)(s->data + rel->r_offset) += addr - pe->imagebase;
1139 /*----------------------------------------------------------------------------*/
1140 ST_FN int pe_check_symbols(struct pe_info *pe)
1142 ElfW(Sym) *sym;
1143 int sym_index, sym_end;
1144 int ret = 0;
1146 pe_align_section(text_section, 8);
1148 sym_end = symtab_section->data_offset / sizeof(ElfW(Sym));
1149 for (sym_index = 1; sym_index < sym_end; ++sym_index) {
1151 sym = (ElfW(Sym) *)symtab_section->data + sym_index;
1152 if (sym->st_shndx == SHN_UNDEF) {
1154 const char *name = symtab_section->link->data + sym->st_name;
1155 unsigned type = ELFW_ST_TYPE(sym->st_info);
1156 int imp_sym = pe_find_import(pe->s1, name);
1157 struct import_symbol *is;
1159 if (0 == imp_sym)
1160 goto not_found;
1161 is = pe_add_import(pe, imp_sym);
1162 if (!is)
1163 goto not_found;
1165 if (type == STT_FUNC) {
1166 unsigned long offset = is->thk_offset;
1167 if (offset) {
1168 /* got aliased symbol, like stricmp and _stricmp */
1170 } else {
1171 char buffer[100];
1172 WORD *p;
1174 offset = text_section->data_offset;
1175 /* add the 'jmp IAT[x]' instruction */
1176 p = section_ptr_add(text_section, 8);
1177 *p = 0x25FF;
1178 #ifdef TCC_TARGET_X86_64
1179 *(DWORD*)(p+1) = (DWORD)-4;
1180 #endif
1181 /* add a helper symbol, will be patched later in
1182 pe_build_imports */
1183 sprintf(buffer, "IAT.%s", name);
1184 is->iat_index = put_elf_sym(
1185 symtab_section, 0, sizeof(DWORD),
1186 ELFW_ST_INFO(STB_GLOBAL, STT_OBJECT),
1187 0, SHN_UNDEF, buffer);
1188 put_elf_reloc(symtab_section, text_section,
1189 offset + 2, R_XXX_THUNKFIX, is->iat_index);
1190 is->thk_offset = offset;
1193 /* tcc_realloc might have altered sym's address */
1194 sym = (ElfW(Sym) *)symtab_section->data + sym_index;
1196 /* patch the original symbol */
1197 sym->st_value = offset;
1198 sym->st_shndx = text_section->sh_num;
1199 sym->st_other &= ~1; /* do not export */
1200 continue;
1203 if (type == STT_OBJECT) { /* data, ptr to that should be */
1204 if (0 == is->iat_index) {
1205 /* original symbol will be patched later in pe_build_imports */
1206 is->iat_index = sym_index;
1207 continue;
1211 not_found:
1212 error_noabort("undefined symbol '%s'", name);
1213 ret = 1;
1215 } else if (pe->s1->rdynamic
1216 && ELFW_ST_BIND(sym->st_info) != STB_LOCAL) {
1217 /* if -rdynamic option, then export all non local symbols */
1218 sym->st_other |= 1;
1221 return ret;
1224 /*----------------------------------------------------------------------------*/
1225 #ifdef PE_PRINT_SECTIONS
1226 ST_FN void pe_print_section(FILE * f, Section * s)
1228 /* just if you'r curious */
1229 BYTE *p, *e, b;
1230 int i, n, l, m;
1231 p = s->data;
1232 e = s->data + s->data_offset;
1233 l = e - p;
1235 fprintf(f, "section \"%s\"", s->name);
1236 if (s->link)
1237 fprintf(f, "\nlink \"%s\"", s->link->name);
1238 if (s->reloc)
1239 fprintf(f, "\nreloc \"%s\"", s->reloc->name);
1240 fprintf(f, "\nv_addr %08X", (unsigned)s->sh_addr);
1241 fprintf(f, "\ncontents %08X", (unsigned)l);
1242 fprintf(f, "\n\n");
1244 if (s->sh_type == SHT_NOBITS)
1245 return;
1247 if (0 == l)
1248 return;
1250 if (s->sh_type == SHT_SYMTAB)
1251 m = sizeof(ElfW(Sym));
1252 else if (s->sh_type == SHT_RELX)
1253 m = sizeof(ElfW_Rel);
1254 else
1255 m = 16;
1257 fprintf(f, "%-8s", "offset");
1258 for (i = 0; i < m; ++i)
1259 fprintf(f, " %02x", i);
1260 n = 56;
1262 if (s->sh_type == SHT_SYMTAB || s->sh_type == SHT_RELX) {
1263 const char *fields1[] = {
1264 "name",
1265 "value",
1266 "size",
1267 "bind",
1268 "type",
1269 "other",
1270 "shndx",
1271 NULL
1274 const char *fields2[] = {
1275 "offs",
1276 "type",
1277 "symb",
1278 NULL
1281 const char **p;
1283 if (s->sh_type == SHT_SYMTAB)
1284 p = fields1, n = 106;
1285 else
1286 p = fields2, n = 58;
1288 for (i = 0; p[i]; ++i)
1289 fprintf(f, "%6s", p[i]);
1290 fprintf(f, " symbol");
1293 fprintf(f, "\n");
1294 for (i = 0; i < n; ++i)
1295 fprintf(f, "-");
1296 fprintf(f, "\n");
1298 for (i = 0; i < l;)
1300 fprintf(f, "%08X", i);
1301 for (n = 0; n < m; ++n) {
1302 if (n + i < l)
1303 fprintf(f, " %02X", p[i + n]);
1304 else
1305 fprintf(f, " ");
1308 if (s->sh_type == SHT_SYMTAB) {
1309 ElfW(Sym) *sym = (ElfW(Sym) *) (p + i);
1310 const char *name = s->link->data + sym->st_name;
1311 fprintf(f, " %04X %04X %04X %02X %02X %02X %04X \"%s\"",
1312 (unsigned)sym->st_name,
1313 (unsigned)sym->st_value,
1314 (unsigned)sym->st_size,
1315 (unsigned)ELFW_ST_BIND(sym->st_info),
1316 (unsigned)ELFW_ST_TYPE(sym->st_info),
1317 (unsigned)sym->st_other,
1318 (unsigned)sym->st_shndx,
1319 name);
1321 } else if (s->sh_type == SHT_RELX) {
1322 ElfW_Rel *rel = (ElfW_Rel *) (p + i);
1323 ElfW(Sym) *sym =
1324 (ElfW(Sym) *) s->link->data + ELFW_R_(SYM)(rel->r_info);
1325 const char *name = s->link->link->data + sym->st_name;
1326 fprintf(f, " %04X %02X %04X \"%s\"",
1327 (unsigned)rel->r_offset,
1328 (unsigned)ELFW_R_(TYPE)(rel->r_info),
1329 (unsigned)ELFW_R_(SYM)(rel->r_info),
1330 name);
1331 } else {
1332 fprintf(f, " ");
1333 for (n = 0; n < m; ++n) {
1334 if (n + i < l) {
1335 b = p[i + n];
1336 if (b < 32 || b >= 127)
1337 b = '.';
1338 fprintf(f, "%c", b);
1342 i += m;
1343 fprintf(f, "\n");
1345 fprintf(f, "\n\n");
1348 ST_FN void pe_print_sections(TCCState *s1, const char *fname)
1350 Section *s;
1351 FILE *f;
1352 int i;
1353 f = fopen(fname, "w");
1354 for (i = 1; i < s1->nb_sections; ++i) {
1355 s = s1->sections[i];
1356 pe_print_section(f, s);
1358 pe_print_section(f, s1->dynsymtab_section);
1359 fclose(f);
1361 #endif
1363 /* -------------------------------------------------------------
1364 * This is for compiled windows resources in 'coff' format
1365 * as generated by 'windres.exe -O coff ...'.
1368 PUB_FN int pe_test_res_file(void *v, int size)
1370 struct pe_rsrc_header *p = (struct pe_rsrc_header *)v;
1371 return
1372 size >= IMAGE_SIZEOF_FILE_HEADER + IMAGE_SIZEOF_SHORT_NAME /* = 28 */
1373 && p->filehdr.Machine == 0x014C
1374 && 1 == p->filehdr.NumberOfSections
1375 && 0 == strcmp(p->sectionhdr.Name, ".rsrc")
1379 ST_FN int read_n(int fd, void *ptr, unsigned size)
1381 return size == read(fd, ptr, size);
1384 PUB_FN int pe_load_res_file(TCCState *s1, int fd)
1386 struct pe_rsrc_header hdr;
1387 Section *rsrc_section;
1388 int i, ret = -1;
1389 BYTE *ptr;
1391 lseek (fd, 0, SEEK_SET);
1392 if (!read_n(fd, &hdr, sizeof hdr))
1393 goto quit;
1394 if (!pe_test_res_file(&hdr, sizeof hdr))
1395 goto quit;
1397 rsrc_section = new_section(s1, ".rsrc", SHT_PROGBITS, SHF_ALLOC);
1398 ptr = section_ptr_add(rsrc_section, hdr.sectionhdr.SizeOfRawData);
1399 lseek (fd, hdr.sectionhdr.PointerToRawData, SEEK_SET);
1400 if (!read_n(fd, ptr, hdr.sectionhdr.SizeOfRawData))
1401 goto quit;
1403 lseek (fd, hdr.sectionhdr.PointerToRelocations, SEEK_SET);
1404 for (i = 0; i < hdr.sectionhdr.NumberOfRelocations; ++i)
1406 struct pe_rsrc_reloc rel;
1407 if (!read_n(fd, &rel, sizeof rel))
1408 goto quit;
1409 // printf("rsrc_reloc: %x %x %x\n", rel.offset, rel.size, rel.type);
1410 if (rel.type != 7) /* DIR32NB */
1411 goto quit;
1412 put_elf_reloc(symtab_section, rsrc_section,
1413 rel.offset, R_XXX_RELATIVE, 0);
1415 ret = 0;
1416 quit:
1417 if (ret)
1418 error_noabort("unrecognized resource file format");
1419 return ret;
1422 /* ------------------------------------------------------------- */
1423 ST_FN char *trimfront(char *p)
1425 while (*p && (unsigned char)*p <= ' ')
1426 ++p;
1427 return p;
1430 ST_FN char *trimback(char *a, char *e)
1432 while (e > a && (unsigned char)e[-1] <= ' ')
1433 --e;
1434 *e = 0;;
1435 return a;
1438 ST_FN char *get_line(char *line, int size, FILE *fp)
1440 if (NULL == fgets(line, size, fp))
1441 return NULL;
1442 trimback(line, strchr(line, 0));
1443 return trimfront(line);
1446 /* ------------------------------------------------------------- */
1447 PUB_FN int pe_load_def_file(TCCState *s1, int fd)
1449 DLLReference *dllref;
1450 int state = 0, ret = -1;
1451 char line[400], dllname[80], *p;
1452 FILE *fp = fdopen(dup(fd), "rb");
1454 if (NULL == fp)
1455 goto quit;
1457 for (;;) {
1458 p = get_line(line, sizeof line, fp);
1459 if (NULL == p)
1460 break;
1461 if (0 == *p || ';' == *p)
1462 continue;
1463 switch (state) {
1464 case 0:
1465 if (0 != strnicmp(p, "LIBRARY", 7))
1466 goto quit;
1467 strcpy(dllname, trimfront(p+7));
1468 ++state;
1469 continue;
1471 case 1:
1472 if (0 != stricmp(p, "EXPORTS"))
1473 goto quit;
1474 ++state;
1475 continue;
1477 case 2:
1478 dllref = tcc_mallocz(sizeof(DLLReference) + strlen(dllname));
1479 strcpy(dllref->name, dllname);
1480 dynarray_add((void ***) &s1->loaded_dlls, &s1->nb_loaded_dlls, dllref);
1481 ++state;
1483 default:
1484 add_elf_sym(s1->dynsymtab_section,
1485 s1->nb_loaded_dlls, 0,
1486 ELFW_ST_INFO(STB_GLOBAL, STT_FUNC), 0,
1487 text_section->sh_num, p);
1488 continue;
1491 ret = 0;
1492 quit:
1493 if (fp)
1494 fclose(fp);
1495 if (ret)
1496 error_noabort("unrecognized export definition file format");
1497 return ret;
1500 /* ------------------------------------------------------------- */
1501 #ifdef TCC_TARGET_X86_64
1502 #define PE_STDSYM(n,s) n
1503 #else
1504 #define PE_STDSYM(n,s) "_" n s
1505 #endif
1507 ST_FN void pe_add_runtime_ex(TCCState *s1, struct pe_info *pe)
1509 const char *start_symbol;
1510 unsigned long addr = 0;
1511 int pe_type = 0;
1513 if (find_elf_sym(symtab_section, PE_STDSYM("WinMain","@16")))
1514 pe_type = PE_GUI;
1515 else
1516 if (TCC_OUTPUT_DLL == s1->output_type) {
1517 pe_type = PE_DLL;
1518 /* need this for 'tccelf.c:relocate_section()' */
1519 s1->output_type = TCC_OUTPUT_EXE;
1522 start_symbol =
1523 TCC_OUTPUT_MEMORY == s1->output_type
1524 ? PE_GUI == pe_type ? "_runwinmain" : NULL
1525 : PE_DLL == pe_type ? PE_STDSYM("_dllstart","@12")
1526 : PE_GUI == pe_type ? "_winstart" : "_start"
1529 /* grab the startup code from libtcc1 */
1530 if (start_symbol)
1531 add_elf_sym(symtab_section,
1532 0, 0,
1533 ELFW_ST_INFO(STB_GLOBAL, STT_NOTYPE), 0,
1534 SHN_UNDEF, start_symbol);
1536 if (0 == s1->nostdlib) {
1537 static const char *libs[] = {
1538 "tcc1", "msvcrt", "kernel32", "", "user32", "gdi32", NULL
1540 const char **pp, *p;
1541 for (pp = libs; 0 != (p = *pp); ++pp) {
1542 if (0 == *p) {
1543 if (PE_DLL != pe_type && PE_GUI != pe_type)
1544 break;
1545 } else if (tcc_add_library(s1, p) < 0)
1546 error_noabort("cannot find library: %s", p);
1550 if (start_symbol) {
1551 addr = (uplong)tcc_get_symbol_err(s1, start_symbol);
1552 if (s1->output_type == TCC_OUTPUT_MEMORY && addr)
1553 /* for -run GUI's, put '_runwinmain' instead of 'main' */
1554 add_elf_sym(symtab_section,
1555 addr, 0,
1556 ELFW_ST_INFO(STB_GLOBAL, STT_NOTYPE), 0,
1557 text_section->sh_num, "main");
1560 pe->type = pe_type;
1561 pe->start_addr = addr;
1564 PUB_FN int pe_output_file(TCCState * s1, const char *filename)
1566 int ret;
1567 struct pe_info pe;
1568 int i;
1570 memset(&pe, 0, sizeof pe);
1571 pe.filename = filename;
1572 pe.s1 = s1;
1574 pe_add_runtime_ex(s1, &pe);
1575 relocate_common_syms(); /* assign bss adresses */
1576 tcc_add_linker_symbols(s1);
1578 ret = pe_check_symbols(&pe);
1579 if (ret)
1580 return ret;
1582 if (filename) {
1583 if (PE_DLL == pe.type) {
1584 pe.reloc = new_section(pe.s1, ".reloc", SHT_PROGBITS, 0);
1585 pe.imagebase = 0x10000000;
1586 } else {
1587 pe.imagebase = 0x00400000;
1589 pe_assign_addresses(&pe);
1590 relocate_syms(s1, 0);
1591 for (i = 1; i < s1->nb_sections; ++i) {
1592 Section *s = s1->sections[i];
1593 if (s->reloc) {
1594 relocate_section(s1, s);
1595 pe_relocate_rva(&pe, s);
1598 if (s1->nb_errors)
1599 ret = 1;
1600 else
1601 ret = pe_write(&pe);
1602 tcc_free(pe.sec_info);
1603 } else {
1604 #ifndef TCC_IS_NATIVE
1605 error_noabort("-run supported only on native platform");
1606 #endif
1607 pe.type = PE_RUN;
1608 pe.thunk = data_section;
1609 pe_build_imports(&pe);
1612 #ifdef PE_PRINT_SECTIONS
1613 pe_print_sections(s1, "tcc.log");
1614 #endif
1615 return ret;
1618 /* ------------------------------------------------------------- */
1619 #endif /* def TCC_TARGET_PE */
1620 /* ------------------------------------------------------------- */