tccpe: set tcc_lib_path from DLL
[tinycc.git] / tccpe.c
blob652ab0691fc2b384773389df0460c6559082819f
1 /*
2 * TCCPE.C - PE file output for the Tiny C Compiler
4 * Copyright (c) 2005-2007 grischka
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
21 #ifdef TCC_TARGET_PE
23 #define ST_FN static
24 #define ST_DATA static
25 #define PUB_FN
27 #ifndef _WIN32
28 #define stricmp strcasecmp
29 #define strnicmp strncasecmp
30 #endif
32 #ifndef MAX_PATH
33 #define MAX_PATH 260
34 #endif
36 #define PE_MERGE_DATA
37 // #define PE_PRINT_SECTIONS
39 #ifdef TCC_TARGET_X86_64
40 # define ADDR3264 ULONGLONG
41 #else
42 # define ADDR3264 DWORD
43 #endif
45 #if defined _WIN32 && (defined _WIN64) == (defined TCC_TARGET_X86_64)
46 #define TCC_IS_NATIVE
47 #endif
49 #ifdef _WIN32
50 void dbg_printf (const char *fmt, ...)
52 char buffer[4000];
53 va_list arg;
54 int x;
55 va_start(arg, fmt);
56 x = vsprintf (buffer, fmt, arg);
57 strcpy(buffer+x, "\n");
58 OutputDebugString(buffer);
60 #endif
62 /* ----------------------------------------------------------- */
63 #ifndef IMAGE_NT_SIGNATURE
64 /* ----------------------------------------------------------- */
65 /* definitions below are from winnt.h */
67 typedef unsigned char BYTE;
68 typedef unsigned short WORD;
69 typedef unsigned long DWORD;
70 typedef unsigned long long ULONGLONG;
71 #pragma pack(push, 1)
73 typedef struct _IMAGE_DOS_HEADER { /* DOS .EXE header */
74 WORD e_magic; /* Magic number */
75 WORD e_cblp; /* Bytes on last page of file */
76 WORD e_cp; /* Pages in file */
77 WORD e_crlc; /* Relocations */
78 WORD e_cparhdr; /* Size of header in paragraphs */
79 WORD e_minalloc; /* Minimum extra paragraphs needed */
80 WORD e_maxalloc; /* Maximum extra paragraphs needed */
81 WORD e_ss; /* Initial (relative) SS value */
82 WORD e_sp; /* Initial SP value */
83 WORD e_csum; /* Checksum */
84 WORD e_ip; /* Initial IP value */
85 WORD e_cs; /* Initial (relative) CS value */
86 WORD e_lfarlc; /* File address of relocation table */
87 WORD e_ovno; /* Overlay number */
88 WORD e_res[4]; /* Reserved words */
89 WORD e_oemid; /* OEM identifier (for e_oeminfo) */
90 WORD e_oeminfo; /* OEM information; e_oemid specific */
91 WORD e_res2[10]; /* Reserved words */
92 DWORD e_lfanew; /* File address of new exe header */
93 } IMAGE_DOS_HEADER, *PIMAGE_DOS_HEADER;
95 #define IMAGE_NT_SIGNATURE 0x00004550 /* PE00 */
96 #define SIZE_OF_NT_SIGNATURE 4
98 typedef struct _IMAGE_FILE_HEADER {
99 WORD Machine;
100 WORD NumberOfSections;
101 DWORD TimeDateStamp;
102 DWORD PointerToSymbolTable;
103 DWORD NumberOfSymbols;
104 WORD SizeOfOptionalHeader;
105 WORD Characteristics;
106 } IMAGE_FILE_HEADER, *PIMAGE_FILE_HEADER;
109 #define IMAGE_SIZEOF_FILE_HEADER 20
111 typedef struct _IMAGE_DATA_DIRECTORY {
112 DWORD VirtualAddress;
113 DWORD Size;
114 } IMAGE_DATA_DIRECTORY, *PIMAGE_DATA_DIRECTORY;
117 typedef struct _IMAGE_OPTIONAL_HEADER {
118 /* Standard fields. */
119 WORD Magic;
120 BYTE MajorLinkerVersion;
121 BYTE MinorLinkerVersion;
122 DWORD SizeOfCode;
123 DWORD SizeOfInitializedData;
124 DWORD SizeOfUninitializedData;
125 DWORD AddressOfEntryPoint;
126 DWORD BaseOfCode;
127 #ifndef TCC_TARGET_X86_64
128 DWORD BaseOfData;
129 #endif
130 /* NT additional fields. */
131 ADDR3264 ImageBase;
132 DWORD SectionAlignment;
133 DWORD FileAlignment;
134 WORD MajorOperatingSystemVersion;
135 WORD MinorOperatingSystemVersion;
136 WORD MajorImageVersion;
137 WORD MinorImageVersion;
138 WORD MajorSubsystemVersion;
139 WORD MinorSubsystemVersion;
140 DWORD Win32VersionValue;
141 DWORD SizeOfImage;
142 DWORD SizeOfHeaders;
143 DWORD CheckSum;
144 WORD Subsystem;
145 WORD DllCharacteristics;
146 ADDR3264 SizeOfStackReserve;
147 ADDR3264 SizeOfStackCommit;
148 ADDR3264 SizeOfHeapReserve;
149 ADDR3264 SizeOfHeapCommit;
150 DWORD LoaderFlags;
151 DWORD NumberOfRvaAndSizes;
152 IMAGE_DATA_DIRECTORY DataDirectory[16];
153 } IMAGE_OPTIONAL_HEADER32, IMAGE_OPTIONAL_HEADER64, IMAGE_OPTIONAL_HEADER;
155 #define IMAGE_DIRECTORY_ENTRY_EXPORT 0 /* Export Directory */
156 #define IMAGE_DIRECTORY_ENTRY_IMPORT 1 /* Import Directory */
157 #define IMAGE_DIRECTORY_ENTRY_RESOURCE 2 /* Resource Directory */
158 #define IMAGE_DIRECTORY_ENTRY_EXCEPTION 3 /* Exception Directory */
159 #define IMAGE_DIRECTORY_ENTRY_SECURITY 4 /* Security Directory */
160 #define IMAGE_DIRECTORY_ENTRY_BASERELOC 5 /* Base Relocation Table */
161 #define IMAGE_DIRECTORY_ENTRY_DEBUG 6 /* Debug Directory */
162 /* IMAGE_DIRECTORY_ENTRY_COPYRIGHT 7 (X86 usage) */
163 #define IMAGE_DIRECTORY_ENTRY_ARCHITECTURE 7 /* Architecture Specific Data */
164 #define IMAGE_DIRECTORY_ENTRY_GLOBALPTR 8 /* RVA of GP */
165 #define IMAGE_DIRECTORY_ENTRY_TLS 9 /* TLS Directory */
166 #define IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG 10 /* Load Configuration Directory */
167 #define IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT 11 /* Bound Import Directory in headers */
168 #define IMAGE_DIRECTORY_ENTRY_IAT 12 /* Import Address Table */
169 #define IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT 13 /* Delay Load Import Descriptors */
170 #define IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR 14 /* COM Runtime descriptor */
172 /* Section header format. */
173 #define IMAGE_SIZEOF_SHORT_NAME 8
175 typedef struct _IMAGE_SECTION_HEADER {
176 BYTE Name[IMAGE_SIZEOF_SHORT_NAME];
177 union {
178 DWORD PhysicalAddress;
179 DWORD VirtualSize;
180 } Misc;
181 DWORD VirtualAddress;
182 DWORD SizeOfRawData;
183 DWORD PointerToRawData;
184 DWORD PointerToRelocations;
185 DWORD PointerToLinenumbers;
186 WORD NumberOfRelocations;
187 WORD NumberOfLinenumbers;
188 DWORD Characteristics;
189 } IMAGE_SECTION_HEADER, *PIMAGE_SECTION_HEADER;
191 #define IMAGE_SIZEOF_SECTION_HEADER 40
193 typedef struct _IMAGE_EXPORT_DIRECTORY {
194 DWORD Characteristics;
195 DWORD TimeDateStamp;
196 WORD MajorVersion;
197 WORD MinorVersion;
198 DWORD Name;
199 DWORD Base;
200 DWORD NumberOfFunctions;
201 DWORD NumberOfNames;
202 DWORD AddressOfFunctions;
203 DWORD AddressOfNames;
204 DWORD AddressOfNameOrdinals;
205 } IMAGE_EXPORT_DIRECTORY,*PIMAGE_EXPORT_DIRECTORY;
207 typedef struct _IMAGE_IMPORT_DESCRIPTOR {
208 union {
209 DWORD Characteristics;
210 DWORD OriginalFirstThunk;
212 DWORD TimeDateStamp;
213 DWORD ForwarderChain;
214 DWORD Name;
215 DWORD FirstThunk;
216 } IMAGE_IMPORT_DESCRIPTOR;
218 typedef struct _IMAGE_BASE_RELOCATION {
219 DWORD VirtualAddress;
220 DWORD SizeOfBlock;
221 // WORD TypeOffset[1];
222 } IMAGE_BASE_RELOCATION;
224 #define IMAGE_SIZEOF_BASE_RELOCATION 8
226 #define IMAGE_REL_BASED_ABSOLUTE 0
227 #define IMAGE_REL_BASED_HIGH 1
228 #define IMAGE_REL_BASED_LOW 2
229 #define IMAGE_REL_BASED_HIGHLOW 3
230 #define IMAGE_REL_BASED_HIGHADJ 4
231 #define IMAGE_REL_BASED_MIPS_JMPADDR 5
232 #define IMAGE_REL_BASED_SECTION 6
233 #define IMAGE_REL_BASED_REL32 7
235 #pragma pack(pop)
237 /* ----------------------------------------------------------- */
238 #endif /* ndef IMAGE_NT_SIGNATURE */
239 /* ----------------------------------------------------------- */
240 #pragma pack(push, 1)
242 struct pe_header
244 IMAGE_DOS_HEADER doshdr;
245 BYTE dosstub[0x40];
246 DWORD nt_sig;
247 IMAGE_FILE_HEADER filehdr;
248 #ifdef TCC_TARGET_X86_64
249 IMAGE_OPTIONAL_HEADER64 opthdr;
250 #else
251 #ifdef _WIN64
252 IMAGE_OPTIONAL_HEADER32 opthdr;
253 #else
254 IMAGE_OPTIONAL_HEADER opthdr;
255 #endif
256 #endif
259 struct pe_reloc_header {
260 DWORD offset;
261 DWORD size;
264 struct pe_rsrc_header {
265 struct _IMAGE_FILE_HEADER filehdr;
266 struct _IMAGE_SECTION_HEADER sectionhdr;
269 struct pe_rsrc_reloc {
270 DWORD offset;
271 DWORD size;
272 WORD type;
275 #pragma pack(pop)
277 /* ----------------------------------------------------------- */
278 ST_DATA struct pe_header pe_header = {
280 /* IMAGE_DOS_HEADER doshdr */
281 0x5A4D, /*WORD e_magic; Magic number */
282 0x0090, /*WORD e_cblp; Bytes on last page of file */
283 0x0003, /*WORD e_cp; Pages in file */
284 0x0000, /*WORD e_crlc; Relocations */
286 0x0004, /*WORD e_cparhdr; Size of header in paragraphs */
287 0x0000, /*WORD e_minalloc; Minimum extra paragraphs needed */
288 0xFFFF, /*WORD e_maxalloc; Maximum extra paragraphs needed */
289 0x0000, /*WORD e_ss; Initial (relative) SS value */
291 0x00B8, /*WORD e_sp; Initial SP value */
292 0x0000, /*WORD e_csum; Checksum */
293 0x0000, /*WORD e_ip; Initial IP value */
294 0x0000, /*WORD e_cs; Initial (relative) CS value */
295 0x0040, /*WORD e_lfarlc; File address of relocation table */
296 0x0000, /*WORD e_ovno; Overlay number */
297 {0,0,0,0}, /*WORD e_res[4]; Reserved words */
298 0x0000, /*WORD e_oemid; OEM identifier (for e_oeminfo) */
299 0x0000, /*WORD e_oeminfo; OEM information; e_oemid specific */
300 {0,0,0,0,0,0,0,0,0,0}, /*WORD e_res2[10]; Reserved words */
301 0x00000080 /*DWORD e_lfanew; File address of new exe header */
303 /* BYTE dosstub[0x40] */
304 /* 14 code bytes + "This program cannot be run in DOS mode.\r\r\n$" + 6 * 0x00 */
305 0x0e,0x1f,0xba,0x0e,0x00,0xb4,0x09,0xcd,0x21,0xb8,0x01,0x4c,0xcd,0x21,0x54,0x68,
306 0x69,0x73,0x20,0x70,0x72,0x6f,0x67,0x72,0x61,0x6d,0x20,0x63,0x61,0x6e,0x6e,0x6f,
307 0x74,0x20,0x62,0x65,0x20,0x72,0x75,0x6e,0x20,0x69,0x6e,0x20,0x44,0x4f,0x53,0x20,
308 0x6d,0x6f,0x64,0x65,0x2e,0x0d,0x0d,0x0a,0x24,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
310 0x00004550, /* DWORD nt_sig = IMAGE_NT_SIGNATURE */
312 /* IMAGE_FILE_HEADER filehdr */
313 #ifdef TCC_TARGET_X86_64
314 0x8664, /*WORD Machine; */
315 #else
316 0x014C, /*WORD Machine; */
317 #endif
318 0x0003, /*WORD NumberOfSections; */
319 0x00000000, /*DWORD TimeDateStamp; */
320 0x00000000, /*DWORD PointerToSymbolTable; */
321 0x00000000, /*DWORD NumberOfSymbols; */
322 #ifdef TCC_TARGET_X86_64
323 0x00F0, /*WORD SizeOfOptionalHeader; */
324 0x022F /*WORD Characteristics; */
325 #define CHARACTERISTICS_DLL 0x222E
326 #else
327 0x00E0, /*WORD SizeOfOptionalHeader; */
328 0x030F /*WORD Characteristics; */
329 #define CHARACTERISTICS_DLL 0x230E
330 #endif
332 /* IMAGE_OPTIONAL_HEADER opthdr */
333 /* Standard fields. */
334 #ifdef TCC_TARGET_X86_64
335 0x020B, /*WORD Magic; */
336 #else
337 0x010B, /*WORD Magic; */
338 #endif
339 0x06, /*BYTE MajorLinkerVersion; */
340 0x00, /*BYTE MinorLinkerVersion; */
341 0x00000000, /*DWORD SizeOfCode; */
342 0x00000000, /*DWORD SizeOfInitializedData; */
343 0x00000000, /*DWORD SizeOfUninitializedData; */
344 0x00000000, /*DWORD AddressOfEntryPoint; */
345 0x00000000, /*DWORD BaseOfCode; */
346 #ifndef TCC_TARGET_X86_64
347 0x00000000, /*DWORD BaseOfData; */
348 #endif
349 /* NT additional fields. */
350 0x00400000, /*DWORD ImageBase; */
351 0x00001000, /*DWORD SectionAlignment; */
352 0x00000200, /*DWORD FileAlignment; */
353 0x0004, /*WORD MajorOperatingSystemVersion; */
354 0x0000, /*WORD MinorOperatingSystemVersion; */
355 0x0000, /*WORD MajorImageVersion; */
356 0x0000, /*WORD MinorImageVersion; */
357 0x0004, /*WORD MajorSubsystemVersion; */
358 0x0000, /*WORD MinorSubsystemVersion; */
359 0x00000000, /*DWORD Win32VersionValue; */
360 0x00000000, /*DWORD SizeOfImage; */
361 0x00000200, /*DWORD SizeOfHeaders; */
362 0x00000000, /*DWORD CheckSum; */
363 0x0002, /*WORD Subsystem; */
364 0x0000, /*WORD DllCharacteristics; */
365 0x00100000, /*DWORD SizeOfStackReserve; */
366 0x00001000, /*DWORD SizeOfStackCommit; */
367 0x00100000, /*DWORD SizeOfHeapReserve; */
368 0x00001000, /*DWORD SizeOfHeapCommit; */
369 0x00000000, /*DWORD LoaderFlags; */
370 0x00000010, /*DWORD NumberOfRvaAndSizes; */
372 /* IMAGE_DATA_DIRECTORY DataDirectory[16]; */
373 {{0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0},
374 {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}}
377 /* ------------------------------------------------------------- */
378 /* internal temporary structures */
381 #define IMAGE_SCN_CNT_CODE 0x00000020
382 #define IMAGE_SCN_CNT_INITIALIZED_DATA 0x00000040
383 #define IMAGE_SCN_CNT_UNINITIALIZED_DATA 0x00000080
384 #define IMAGE_SCN_MEM_DISCARDABLE 0x02000000
385 #define IMAGE_SCN_MEM_SHARED 0x10000000
386 #define IMAGE_SCN_MEM_EXECUTE 0x20000000
387 #define IMAGE_SCN_MEM_READ 0x40000000
388 #define IMAGE_SCN_MEM_WRITE 0x80000000
391 enum {
392 sec_text = 0,
393 sec_data ,
394 sec_bss ,
395 sec_idata ,
396 sec_other ,
397 sec_rsrc ,
398 sec_stab ,
399 sec_reloc ,
400 sec_last
403 ST_DATA DWORD pe_sec_flags[] = {
404 0x60000020, /* ".text" , */
405 0xC0000040, /* ".data" , */
406 0xC0000080, /* ".bss" , */
407 0x40000040, /* ".idata" , */
408 0xE0000060, /* < other > , */
409 0x40000040, /* ".rsrc" , */
410 0x42000802, /* ".stab" , */
411 0x42000040, /* ".reloc" , */
414 struct section_info {
415 int cls, ord;
416 char name[32];
417 DWORD sh_addr;
418 DWORD sh_size;
419 DWORD sh_flags;
420 unsigned char *data;
421 DWORD data_size;
422 IMAGE_SECTION_HEADER ish;
425 struct import_symbol {
426 int sym_index;
427 int iat_index;
428 int thk_offset;
431 struct pe_import_info {
432 int dll_index;
433 int sym_count;
434 struct import_symbol **symbols;
437 struct pe_info {
438 TCCState *s1;
439 Section *reloc;
440 Section *thunk;
441 const char *filename;
442 int type;
443 DWORD sizeofheaders;
444 DWORD imagebase;
445 DWORD start_addr;
446 DWORD imp_offs;
447 DWORD imp_size;
448 DWORD iat_offs;
449 DWORD iat_size;
450 DWORD exp_offs;
451 DWORD exp_size;
452 struct section_info *sec_info;
453 int sec_count;
454 struct pe_import_info **imp_info;
455 int imp_count;
458 #define PE_NUL 0
459 #define PE_DLL 1
460 #define PE_GUI 2
461 #define PE_EXE 3
462 #define PE_RUN 4
464 /* --------------------------------------------*/
466 ST_FN const char* get_alt_symbol(char *buffer, const char *symbol)
468 const char *p;
469 p = strrchr(symbol, '@');
470 if (p && isnum(p[1]) && symbol[0] == '_') { /* stdcall decor */
471 strcpy(buffer, symbol+1)[p-symbol-1] = 0;
472 } else if (symbol[0] != '_') { /* try non-ansi function */
473 buffer[0] = '_', strcpy(buffer + 1, symbol);
474 } else if (0 == memcmp(symbol, "__imp__", 7)) { /* mingw 2.0 */
475 strcpy(buffer, symbol + 6);
476 } else if (0 == memcmp(symbol, "_imp___", 7)) { /* mingw 3.7 */
477 strcpy(buffer, symbol + 6);
478 } else {
479 return symbol;
481 return buffer;
484 ST_FN int pe_find_import(TCCState * s1, const char *symbol)
486 char buffer[200];
487 const char *s;
488 int sym_index, n = 0;
489 do {
490 s = n ? get_alt_symbol(buffer, symbol) : symbol;
491 sym_index = find_elf_sym(s1->dynsymtab_section, s);
492 // printf("find (%d) %d %s\n", n, sym_index, s);
493 } while (0 == sym_index && ++n < 2);
494 return sym_index;
497 /*----------------------------------------------------------------------------*/
499 ST_FN int dynarray_assoc(void **pp, int n, int key)
501 int i;
502 for (i = 0; i < n; ++i, ++pp)
503 if (key == **(int **) pp)
504 return i;
505 return -1;
508 #if 0
509 ST_FN DWORD umin(DWORD a, DWORD b)
511 return a < b ? a : b;
513 #endif
515 ST_FN DWORD umax(DWORD a, DWORD b)
517 return a < b ? b : a;
520 ST_FN void pe_fpad(FILE *fp, DWORD new_pos)
522 DWORD pos = ftell(fp);
523 while (++pos <= new_pos)
524 fputc(0, fp);
527 ST_FN DWORD pe_file_align(DWORD n)
529 return (n + (0x200 - 1)) & ~(0x200 - 1);
532 ST_FN DWORD pe_virtual_align(DWORD n)
534 return (n + (0x1000 - 1)) & ~(0x1000 - 1);
537 ST_FN void pe_align_section(Section *s, int a)
539 int i = s->data_offset & (a-1);
540 if (i)
541 section_ptr_add(s, a - i);
544 ST_FN void pe_set_datadir(int dir, DWORD addr, DWORD size)
546 pe_header.opthdr.DataDirectory[dir].VirtualAddress = addr;
547 pe_header.opthdr.DataDirectory[dir].Size = size;
550 /*----------------------------------------------------------------------------*/
551 ST_FN int pe_write(struct pe_info *pe)
553 int i;
554 FILE *op;
555 DWORD file_offset, r;
557 op = fopen(pe->filename, "wb");
558 if (NULL == op) {
559 error_noabort("could not write '%s': %s", pe->filename, strerror(errno));
560 return 1;
563 pe->sizeofheaders = pe_file_align(
564 sizeof pe_header
565 + pe->sec_count * sizeof (IMAGE_SECTION_HEADER)
568 file_offset = pe->sizeofheaders;
569 pe_fpad(op, file_offset);
571 if (2 == pe->s1->verbose)
572 printf("-------------------------------"
573 "\n virt file size section" "\n");
575 for (i = 0; i < pe->sec_count; ++i) {
576 struct section_info *si = pe->sec_info + i;
577 const char *sh_name = si->name;
578 unsigned long addr = si->sh_addr - pe->imagebase;
579 unsigned long size = si->sh_size;
580 IMAGE_SECTION_HEADER *psh = &si->ish;
582 if (2 == pe->s1->verbose)
583 printf("%6lx %6lx %6lx %s\n",
584 addr, file_offset, size, sh_name);
586 switch (si->cls) {
587 case sec_text:
588 pe_header.opthdr.BaseOfCode = addr;
589 pe_header.opthdr.AddressOfEntryPoint = addr + pe->start_addr;
590 break;
592 case sec_data:
593 #ifndef TCC_TARGET_X86_64
594 pe_header.opthdr.BaseOfData = addr;
595 #endif
596 break;
598 case sec_bss:
599 break;
601 case sec_reloc:
602 pe_set_datadir(IMAGE_DIRECTORY_ENTRY_BASERELOC, addr, size);
603 break;
605 case sec_rsrc:
606 pe_set_datadir(IMAGE_DIRECTORY_ENTRY_RESOURCE, addr, size);
607 break;
609 case sec_stab:
610 break;
613 if (pe->thunk == pe->s1->sections[si->ord]) {
614 if (pe->imp_size) {
615 pe_set_datadir(IMAGE_DIRECTORY_ENTRY_IMPORT,
616 pe->imp_offs + addr, pe->imp_size);
617 pe_set_datadir(IMAGE_DIRECTORY_ENTRY_IAT,
618 pe->iat_offs + addr, pe->iat_size);
620 if (pe->exp_size) {
621 pe_set_datadir(IMAGE_DIRECTORY_ENTRY_EXPORT,
622 pe->exp_offs + addr, pe->exp_size);
626 strcpy((char*)psh->Name, sh_name);
628 psh->Characteristics = pe_sec_flags[si->cls];
629 psh->VirtualAddress = addr;
630 psh->Misc.VirtualSize = size;
631 pe_header.opthdr.SizeOfImage =
632 umax(pe_virtual_align(size + addr), pe_header.opthdr.SizeOfImage);
634 if (si->data_size) {
635 psh->PointerToRawData = r = file_offset;
636 fwrite(si->data, 1, si->data_size, op);
637 file_offset = pe_file_align(file_offset + si->data_size);
638 psh->SizeOfRawData = file_offset - r;
639 pe_fpad(op, file_offset);
643 // pe_header.filehdr.TimeDateStamp = time(NULL);
644 pe_header.filehdr.NumberOfSections = pe->sec_count;
645 pe_header.opthdr.SizeOfHeaders = pe->sizeofheaders;
646 pe_header.opthdr.ImageBase = pe->imagebase;
647 if (PE_DLL == pe->type)
648 pe_header.filehdr.Characteristics = CHARACTERISTICS_DLL;
649 else if (PE_GUI != pe->type)
650 pe_header.opthdr.Subsystem = 3;
652 fseek(op, SEEK_SET, 0);
653 fwrite(&pe_header, 1, sizeof pe_header, op);
654 for (i = 0; i < pe->sec_count; ++i)
655 fwrite(&pe->sec_info[i].ish, 1, sizeof(IMAGE_SECTION_HEADER), op);
656 fclose (op);
658 if (2 == pe->s1->verbose)
659 printf("-------------------------------\n");
660 if (pe->s1->verbose)
661 printf("<- %s (%lu bytes)\n", pe->filename, file_offset);
663 return 0;
666 /*----------------------------------------------------------------------------*/
668 #ifdef TCC_TARGET_X86_64
669 #define ELFW_R_(type) ELF64_R_##type
670 #define ElfW_Rel ElfW(Rela)
672 #define REL_TYPE_DIRECT R_X86_64_64
673 #define R_XXX_THUNKFIX R_X86_64_PC32
674 #define R_XXX_RELATIVE R_X86_64_RELATIVE
676 #define ELFW_ST_BIND ELF64_ST_BIND
677 #define ELFW_ST_TYPE ELF64_ST_TYPE
678 #define ELFW_ST_INFO ELF64_ST_INFO
679 #else
680 #define ELFW_R_(type) ELF32_R_##type
681 #define ElfW_Rel ElfW(Rel)
683 #define REL_TYPE_DIRECT R_386_32
684 #define R_XXX_THUNKFIX R_386_32
685 #define R_XXX_RELATIVE R_386_RELATIVE
687 #define ELFW_ST_BIND ELF32_ST_BIND
688 #define ELFW_ST_TYPE ELF32_ST_TYPE
689 #define ELFW_ST_INFO ELF32_ST_INFO
690 #endif
691 /*----------------------------------------------------------------------------*/
693 ST_FN struct import_symbol *pe_add_import(struct pe_info *pe, int sym_index)
695 int i;
696 int dll_index;
697 struct pe_import_info *p;
698 struct import_symbol *s;
700 dll_index = ((ElfW(Sym) *)pe->s1->dynsymtab_section->data + sym_index)->st_value;
701 if (0 == dll_index)
702 return NULL;
704 i = dynarray_assoc ((void**)pe->imp_info, pe->imp_count, dll_index);
705 if (-1 != i) {
706 p = pe->imp_info[i];
707 goto found_dll;
709 p = tcc_mallocz(sizeof *p);
710 p->dll_index = dll_index;
711 dynarray_add((void***)&pe->imp_info, &pe->imp_count, p);
713 found_dll:
714 i = dynarray_assoc ((void**)p->symbols, p->sym_count, sym_index);
715 if (-1 != i)
716 return p->symbols[i];
718 s = tcc_mallocz(sizeof *s);
719 dynarray_add((void***)&p->symbols, &p->sym_count, s);
720 s->sym_index = sym_index;
721 return s;
724 /*----------------------------------------------------------------------------*/
725 ST_FN void pe_build_imports(struct pe_info *pe)
727 int thk_ptr, ent_ptr, dll_ptr, sym_cnt, i;
728 DWORD rva_base = pe->thunk->sh_addr - pe->imagebase;
729 int ndlls = pe->imp_count;
731 for (sym_cnt = i = 0; i < ndlls; ++i)
732 sym_cnt += pe->imp_info[i]->sym_count;
734 if (0 == sym_cnt)
735 return;
737 pe_align_section(pe->thunk, 16);
739 pe->imp_offs = dll_ptr = pe->thunk->data_offset;
740 pe->imp_size = (ndlls + 1) * sizeof(IMAGE_IMPORT_DESCRIPTOR);
741 pe->iat_offs = dll_ptr + pe->imp_size;
742 pe->iat_size = (sym_cnt + ndlls) * sizeof(ADDR3264);
743 section_ptr_add(pe->thunk, pe->imp_size + 2*pe->iat_size);
745 thk_ptr = pe->iat_offs;
746 ent_ptr = pe->iat_offs + pe->iat_size;
748 for (i = 0; i < pe->imp_count; ++i) {
749 IMAGE_IMPORT_DESCRIPTOR *hdr;
750 int k, n;
751 ADDR3264 v;
752 struct pe_import_info *p = pe->imp_info[i];
753 const char *name = pe->s1->loaded_dlls[p->dll_index-1]->name;
755 /* put the dll name into the import header */
756 v = put_elf_str(pe->thunk, name);
758 hdr = (IMAGE_IMPORT_DESCRIPTOR*)(pe->thunk->data + dll_ptr);
759 hdr->FirstThunk = thk_ptr + rva_base;
760 hdr->OriginalFirstThunk = ent_ptr + rva_base;
761 hdr->Name = v + rva_base;
763 for (k = 0, n = p->sym_count; k <= n; ++k) {
764 if (k < n) {
765 int iat_index = p->symbols[k]->iat_index;
766 int sym_index = p->symbols[k]->sym_index;
767 ElfW(Sym) *imp_sym = (ElfW(Sym) *)pe->s1->dynsymtab_section->data + sym_index;
768 ElfW(Sym) *org_sym = (ElfW(Sym) *)symtab_section->data + iat_index;
769 const char *name = pe->s1->dynsymtab_section->link->data + imp_sym->st_name;
771 org_sym->st_value = thk_ptr;
772 org_sym->st_shndx = pe->thunk->sh_num;
773 v = pe->thunk->data_offset + rva_base;
774 section_ptr_add(pe->thunk, sizeof(WORD)); /* hint, not used */
775 put_elf_str(pe->thunk, name);
776 #ifdef TCC_IS_NATIVE
777 if (pe->type == PE_RUN) {
778 DLLReference *dllref = pe->s1->loaded_dlls[imp_sym->st_value-1];
779 if ( !dllref->handle )
780 dllref->handle = LoadLibrary(dllref->name);
781 v = (ADDR3264)GetProcAddress(dllref->handle, name);
782 if (!v)
783 error_noabort("undefined symbol '%s'", name);
785 #endif
786 } else {
787 v = 0; /* last entry is zero */
789 *(ADDR3264*)(pe->thunk->data+thk_ptr) =
790 *(ADDR3264*)(pe->thunk->data+ent_ptr) = v;
791 thk_ptr += sizeof (ADDR3264);
792 ent_ptr += sizeof (ADDR3264);
794 dll_ptr += sizeof(IMAGE_IMPORT_DESCRIPTOR);
795 dynarray_reset(&p->symbols, &p->sym_count);
797 dynarray_reset(&pe->imp_info, &pe->imp_count);
800 /* ------------------------------------------------------------- */
802 For now only functions are exported. Export of data
803 would work, but import requires compiler support to
804 do an additional indirection.
806 For instance:
807 __declspec(dllimport) extern int something;
809 needs to be translated to:
811 *(int*)something
814 struct pe_sort_sym
816 int index;
817 const char *name;
820 ST_FN int sym_cmp(const void *va, const void *vb)
822 const char *ca = (*(struct pe_sort_sym**)va)->name;
823 const char *cb = (*(struct pe_sort_sym**)vb)->name;
824 return strcmp(ca, cb);
827 ST_FN void pe_build_exports(struct pe_info *pe)
829 ElfW(Sym) *sym;
830 int sym_index, sym_end;
831 DWORD rva_base, func_o, name_o, ord_o, str_o;
832 IMAGE_EXPORT_DIRECTORY *hdr;
833 int sym_count, ord;
834 struct pe_sort_sym **sorted, *p;
836 FILE *op;
837 char buf[MAX_PATH];
838 const char *dllname;
839 const char *name;
841 rva_base = pe->thunk->sh_addr - pe->imagebase;
842 sym_count = 0, sorted = NULL, op = NULL;
844 sym_end = symtab_section->data_offset / sizeof(ElfW(Sym));
845 for (sym_index = 1; sym_index < sym_end; ++sym_index) {
846 sym = (ElfW(Sym)*)symtab_section->data + sym_index;
847 name = symtab_section->link->data + sym->st_name;
848 if ((sym->st_other & 1)
849 /* export only symbols from actually written sections */
850 && pe->s1->sections[sym->st_shndx]->sh_addr) {
851 p = tcc_malloc(sizeof *p);
852 p->index = sym_index;
853 p->name = name;
854 dynarray_add((void***)&sorted, &sym_count, p);
856 #if 0
857 if (sym->st_other & 1)
858 printf("export: %s\n", name);
859 if (sym->st_other & 2)
860 printf("stdcall: %s\n", name);
861 #endif
864 if (0 == sym_count)
865 return;
867 qsort (sorted, sym_count, sizeof *sorted, sym_cmp);
869 pe_align_section(pe->thunk, 16);
870 dllname = tcc_basename(pe->filename);
872 pe->exp_offs = pe->thunk->data_offset;
873 func_o = pe->exp_offs + sizeof(IMAGE_EXPORT_DIRECTORY);
874 name_o = func_o + sym_count * sizeof (DWORD);
875 ord_o = name_o + sym_count * sizeof (DWORD);
876 str_o = ord_o + sym_count * sizeof(WORD);
878 hdr = section_ptr_add(pe->thunk, str_o - pe->exp_offs);
879 hdr->Characteristics = 0;
880 hdr->Base = 1;
881 hdr->NumberOfFunctions = sym_count;
882 hdr->NumberOfNames = sym_count;
883 hdr->AddressOfFunctions = func_o + rva_base;
884 hdr->AddressOfNames = name_o + rva_base;
885 hdr->AddressOfNameOrdinals = ord_o + rva_base;
886 hdr->Name = str_o + rva_base;
887 put_elf_str(pe->thunk, dllname);
889 #if 1
890 /* automatically write exports to <output-filename>.def */
891 strcpy(buf, pe->filename);
892 strcpy(tcc_fileextension(buf), ".def");
893 op = fopen(buf, "w");
894 if (NULL == op) {
895 error_noabort("could not create '%s': %s", buf, strerror(errno));
896 } else {
897 fprintf(op, "LIBRARY %s\n\nEXPORTS\n", dllname);
898 if (pe->s1->verbose)
899 printf("<- %s (%d symbols)\n", buf, sym_count);
901 #endif
903 for (ord = 0; ord < sym_count; ++ord)
905 p = sorted[ord], sym_index = p->index, name = p->name;
906 /* insert actual address later in pe_relocate_rva */
907 put_elf_reloc(symtab_section, pe->thunk,
908 func_o, R_XXX_RELATIVE, sym_index);
909 *(DWORD*)(pe->thunk->data + name_o)
910 = pe->thunk->data_offset + rva_base;
911 *(WORD*)(pe->thunk->data + ord_o)
912 = ord;
913 put_elf_str(pe->thunk, name);
914 func_o += sizeof (DWORD);
915 name_o += sizeof (DWORD);
916 ord_o += sizeof (WORD);
917 if (op)
918 fprintf(op, "%s\n", name);
920 pe->exp_size = pe->thunk->data_offset - pe->exp_offs;
921 dynarray_reset(&sorted, &sym_count);
924 /* ------------------------------------------------------------- */
925 ST_FN void pe_build_reloc (struct pe_info *pe)
927 DWORD offset, block_ptr, addr;
928 int count, i;
929 ElfW_Rel *rel, *rel_end;
930 Section *s = NULL, *sr;
932 offset = addr = block_ptr = count = i = 0;
933 rel = rel_end = NULL;
935 for(;;) {
936 if (rel < rel_end) {
937 int type = ELFW_R_(TYPE)(rel->r_info);
938 addr = rel->r_offset + s->sh_addr;
939 ++ rel;
940 if (type != REL_TYPE_DIRECT)
941 continue;
942 if (count == 0) { /* new block */
943 block_ptr = pe->reloc->data_offset;
944 section_ptr_add(pe->reloc, sizeof(struct pe_reloc_header));
945 offset = addr & 0xFFFFFFFF<<12;
947 if ((addr -= offset) < (1<<12)) { /* one block spans 4k addresses */
948 WORD *wp = section_ptr_add(pe->reloc, sizeof (WORD));
949 *wp = addr | IMAGE_REL_BASED_HIGHLOW<<12;
950 ++count;
951 continue;
953 -- rel;
955 } else if (i < pe->sec_count) {
956 sr = (s = pe->s1->sections[pe->sec_info[i++].ord])->reloc;
957 if (sr) {
958 rel = (ElfW_Rel *)sr->data;
959 rel_end = (ElfW_Rel *)(sr->data + sr->data_offset);
961 continue;
964 if (count) {
965 /* store the last block and ready for a new one */
966 struct pe_reloc_header *hdr;
967 if (count & 1) /* align for DWORDS */
968 section_ptr_add(pe->reloc, sizeof(WORD)), ++count;
969 hdr = (struct pe_reloc_header *)(pe->reloc->data + block_ptr);
970 hdr -> offset = offset - pe->imagebase;
971 hdr -> size = count * sizeof(WORD) + sizeof(struct pe_reloc_header);
972 count = 0;
975 if (rel >= rel_end)
976 break;
980 /* ------------------------------------------------------------- */
981 ST_FN int pe_section_class(Section *s)
983 int type, flags;
984 const char *name;
986 type = s->sh_type;
987 flags = s->sh_flags;
988 name = s->name;
989 if (flags & SHF_ALLOC) {
990 if (type == SHT_PROGBITS) {
991 if (flags & SHF_EXECINSTR)
992 return sec_text;
993 if (flags & SHF_WRITE)
994 return sec_data;
995 if (0 == strcmp(name, ".rsrc"))
996 return sec_rsrc;
997 if (0 == strcmp(name, ".iedat"))
998 return sec_idata;
999 return sec_other;
1000 } else if (type == SHT_NOBITS) {
1001 if (flags & SHF_WRITE)
1002 return sec_bss;
1004 } else {
1005 if (0 == strcmp(name, ".reloc"))
1006 return sec_reloc;
1007 if (0 == strncmp(name, ".stab", 5)) /* .stab and .stabstr */
1008 return sec_stab;
1010 return -1;
1013 ST_FN int pe_assign_addresses (struct pe_info *pe)
1015 int i, k, o, c;
1016 DWORD addr;
1017 int *section_order;
1018 struct section_info *si;
1019 Section *s;
1021 // pe->thunk = new_section(pe->s1, ".iedat", SHT_PROGBITS, SHF_ALLOC);
1023 section_order = tcc_malloc(pe->s1->nb_sections * sizeof (int));
1024 for (o = k = 0 ; k < sec_last; ++k) {
1025 for (i = 1; i < pe->s1->nb_sections; ++i) {
1026 s = pe->s1->sections[i];
1027 if (k == pe_section_class(s)) {
1028 // printf("%s %d\n", s->name, k);
1029 s->sh_addr = pe->imagebase;
1030 section_order[o++] = i;
1035 pe->sec_info = tcc_mallocz(o * sizeof (struct section_info));
1036 addr = pe->imagebase + 1;
1038 for (i = 0; i < o; ++i)
1040 k = section_order[i];
1041 s = pe->s1->sections[k];
1042 c = pe_section_class(s);
1043 si = &pe->sec_info[pe->sec_count];
1045 #ifdef PE_MERGE_DATA
1046 if (c == sec_bss && pe->sec_count && si[-1].cls == sec_data) {
1047 /* append .bss to .data */
1048 s->sh_addr = addr = ((addr-1) | 15) + 1;
1049 addr += s->data_offset;
1050 si[-1].sh_size = addr - si[-1].sh_addr;
1051 continue;
1053 #endif
1054 strcpy(si->name, s->name);
1055 si->cls = c;
1056 si->ord = k;
1057 si->sh_addr = s->sh_addr = addr = pe_virtual_align(addr);
1058 si->sh_flags = s->sh_flags;
1060 if (c == sec_data && NULL == pe->thunk)
1061 pe->thunk = s;
1063 if (s == pe->thunk) {
1064 pe_build_imports(pe);
1065 pe_build_exports(pe);
1068 if (c == sec_reloc)
1069 pe_build_reloc (pe);
1071 if (s->data_offset)
1073 if (s->sh_type != SHT_NOBITS) {
1074 si->data = s->data;
1075 si->data_size = s->data_offset;
1078 addr += s->data_offset;
1079 si->sh_size = s->data_offset;
1080 ++pe->sec_count;
1082 // printf("%08x %05x %s\n", si->sh_addr, si->sh_size, si->name);
1085 #if 0
1086 for (i = 1; i < pe->s1->nb_sections; ++i) {
1087 Section *s = pe->s1->sections[i];
1088 int type = s->sh_type;
1089 int flags = s->sh_flags;
1090 printf("section %-16s %-10s %5x %s,%s,%s\n",
1091 s->name,
1092 type == SHT_PROGBITS ? "progbits" :
1093 type == SHT_NOBITS ? "nobits" :
1094 type == SHT_SYMTAB ? "symtab" :
1095 type == SHT_STRTAB ? "strtab" :
1096 type == SHT_RELX ? "rel" : "???",
1097 s->data_offset,
1098 flags & SHF_ALLOC ? "alloc" : "",
1099 flags & SHF_WRITE ? "write" : "",
1100 flags & SHF_EXECINSTR ? "exec" : ""
1103 pe->s1->verbose = 2;
1104 #endif
1106 tcc_free(section_order);
1107 return 0;
1110 /* ------------------------------------------------------------- */
1111 ST_FN void pe_relocate_rva (struct pe_info *pe, Section *s)
1113 Section *sr = s->reloc;
1114 ElfW_Rel *rel, *rel_end;
1115 rel_end = (ElfW_Rel *)(sr->data + sr->data_offset);
1116 for(rel = (ElfW_Rel *)sr->data; rel < rel_end; rel++) {
1117 if (ELFW_R_(TYPE)(rel->r_info) == R_XXX_RELATIVE) {
1118 int sym_index = ELFW_R_(SYM)(rel->r_info);
1119 DWORD addr = s->sh_addr;
1120 if (sym_index) {
1121 ElfW(Sym) *sym = (ElfW(Sym) *)symtab_section->data + sym_index;
1122 addr = sym->st_value;
1124 // printf("reloc rva %08x %08x\n", (DWORD)rel->r_offset, addr);
1125 *(DWORD*)(s->data + rel->r_offset) += addr - pe->imagebase;
1130 /*----------------------------------------------------------------------------*/
1131 ST_FN int pe_check_symbols(struct pe_info *pe)
1133 ElfW(Sym) *sym;
1134 int sym_index, sym_end;
1135 int ret = 0;
1137 pe_align_section(text_section, 8);
1139 sym_end = symtab_section->data_offset / sizeof(ElfW(Sym));
1140 for (sym_index = 1; sym_index < sym_end; ++sym_index) {
1142 sym = (ElfW(Sym) *)symtab_section->data + sym_index;
1143 if (sym->st_shndx == SHN_UNDEF) {
1145 const char *name = symtab_section->link->data + sym->st_name;
1146 unsigned type = ELFW_ST_TYPE(sym->st_info);
1147 int imp_sym = pe_find_import(pe->s1, name);
1148 struct import_symbol *is;
1150 if (0 == imp_sym)
1151 goto not_found;
1152 is = pe_add_import(pe, imp_sym);
1153 if (!is)
1154 goto not_found;
1156 if (type == STT_FUNC) {
1157 unsigned long offset = is->thk_offset;
1158 if (offset) {
1159 /* got aliased symbol, like stricmp and _stricmp */
1161 } else {
1162 char buffer[100];
1163 WORD *p;
1165 offset = text_section->data_offset;
1166 /* add the 'jmp IAT[x]' instruction */
1167 p = section_ptr_add(text_section, 8);
1168 *p = 0x25FF;
1169 #ifdef TCC_TARGET_X86_64
1170 *(DWORD*)(p+1) = (DWORD)-4;
1171 #endif
1172 /* add a helper symbol, will be patched later in
1173 pe_build_imports */
1174 sprintf(buffer, "IAT.%s", name);
1175 is->iat_index = put_elf_sym(
1176 symtab_section, 0, sizeof(DWORD),
1177 ELFW_ST_INFO(STB_GLOBAL, STT_OBJECT),
1178 0, SHN_UNDEF, buffer);
1179 put_elf_reloc(symtab_section, text_section,
1180 offset + 2, R_XXX_THUNKFIX, is->iat_index);
1181 is->thk_offset = offset;
1184 /* tcc_realloc might have altered sym's address */
1185 sym = (ElfW(Sym) *)symtab_section->data + sym_index;
1187 /* patch the original symbol */
1188 sym->st_value = offset;
1189 sym->st_shndx = text_section->sh_num;
1190 sym->st_other &= ~1; /* do not export */
1191 continue;
1194 if (type == STT_OBJECT) { /* data, ptr to that should be */
1195 if (0 == is->iat_index) {
1196 /* original symbol will be patched later in pe_build_imports */
1197 is->iat_index = sym_index;
1198 continue;
1202 not_found:
1203 error_noabort("undefined symbol '%s'", name);
1204 ret = 1;
1206 } else if (pe->s1->rdynamic
1207 && ELFW_ST_BIND(sym->st_info) != STB_LOCAL) {
1208 /* if -rdynamic option, then export all non local symbols */
1209 sym->st_other |= 1;
1212 return ret;
1215 /*----------------------------------------------------------------------------*/
1216 #ifdef PE_PRINT_SECTIONS
1217 ST_FN void pe_print_section(FILE * f, Section * s)
1219 /* just if you'r curious */
1220 BYTE *p, *e, b;
1221 int i, n, l, m;
1222 p = s->data;
1223 e = s->data + s->data_offset;
1224 l = e - p;
1226 fprintf(f, "section \"%s\"", s->name);
1227 if (s->link)
1228 fprintf(f, "\nlink \"%s\"", s->link->name);
1229 if (s->reloc)
1230 fprintf(f, "\nreloc \"%s\"", s->reloc->name);
1231 fprintf(f, "\nv_addr %08X", (unsigned)s->sh_addr);
1232 fprintf(f, "\ncontents %08X", (unsigned)l);
1233 fprintf(f, "\n\n");
1235 if (s->sh_type == SHT_NOBITS)
1236 return;
1238 if (0 == l)
1239 return;
1241 if (s->sh_type == SHT_SYMTAB)
1242 m = sizeof(ElfW(Sym));
1243 else if (s->sh_type == SHT_RELX)
1244 m = sizeof(ElfW_Rel);
1245 else
1246 m = 16;
1248 fprintf(f, "%-8s", "offset");
1249 for (i = 0; i < m; ++i)
1250 fprintf(f, " %02x", i);
1251 n = 56;
1253 if (s->sh_type == SHT_SYMTAB || s->sh_type == SHT_RELX) {
1254 const char *fields1[] = {
1255 "name",
1256 "value",
1257 "size",
1258 "bind",
1259 "type",
1260 "other",
1261 "shndx",
1262 NULL
1265 const char *fields2[] = {
1266 "offs",
1267 "type",
1268 "symb",
1269 NULL
1272 const char **p;
1274 if (s->sh_type == SHT_SYMTAB)
1275 p = fields1, n = 106;
1276 else
1277 p = fields2, n = 58;
1279 for (i = 0; p[i]; ++i)
1280 fprintf(f, "%6s", p[i]);
1281 fprintf(f, " symbol");
1284 fprintf(f, "\n");
1285 for (i = 0; i < n; ++i)
1286 fprintf(f, "-");
1287 fprintf(f, "\n");
1289 for (i = 0; i < l;)
1291 fprintf(f, "%08X", i);
1292 for (n = 0; n < m; ++n) {
1293 if (n + i < l)
1294 fprintf(f, " %02X", p[i + n]);
1295 else
1296 fprintf(f, " ");
1299 if (s->sh_type == SHT_SYMTAB) {
1300 ElfW(Sym) *sym = (ElfW(Sym) *) (p + i);
1301 const char *name = s->link->data + sym->st_name;
1302 fprintf(f, " %04X %04X %04X %02X %02X %02X %04X \"%s\"",
1303 (unsigned)sym->st_name,
1304 (unsigned)sym->st_value,
1305 (unsigned)sym->st_size,
1306 (unsigned)ELFW_ST_BIND(sym->st_info),
1307 (unsigned)ELFW_ST_TYPE(sym->st_info),
1308 (unsigned)sym->st_other,
1309 (unsigned)sym->st_shndx,
1310 name);
1312 } else if (s->sh_type == SHT_RELX) {
1313 ElfW_Rel *rel = (ElfW_Rel *) (p + i);
1314 ElfW(Sym) *sym =
1315 (ElfW(Sym) *) s->link->data + ELFW_R_(SYM)(rel->r_info);
1316 const char *name = s->link->link->data + sym->st_name;
1317 fprintf(f, " %04X %02X %04X \"%s\"",
1318 (unsigned)rel->r_offset,
1319 (unsigned)ELFW_R_(TYPE)(rel->r_info),
1320 (unsigned)ELFW_R_(SYM)(rel->r_info),
1321 name);
1322 } else {
1323 fprintf(f, " ");
1324 for (n = 0; n < m; ++n) {
1325 if (n + i < l) {
1326 b = p[i + n];
1327 if (b < 32 || b >= 127)
1328 b = '.';
1329 fprintf(f, "%c", b);
1333 i += m;
1334 fprintf(f, "\n");
1336 fprintf(f, "\n\n");
1339 ST_FN void pe_print_sections(TCCState *s1, const char *fname)
1341 Section *s;
1342 FILE *f;
1343 int i;
1344 f = fopen(fname, "w");
1345 for (i = 1; i < s1->nb_sections; ++i) {
1346 s = s1->sections[i];
1347 pe_print_section(f, s);
1349 pe_print_section(f, s1->dynsymtab_section);
1350 fclose(f);
1352 #endif
1354 /* ------------------------------------------------------------- */
1356 ST_FN int read_mem(FILE *fp, unsigned offset, void *buffer, unsigned len)
1358 fseek(fp, offset, 0);
1359 return len == fread(buffer, 1, len, fp);
1362 /* -------------------------------------------------------------
1363 * This is for compiled windows resources in 'coff' format
1364 * as generated by 'windres.exe -O coff ...'.
1367 ST_FN int pe_load_res(TCCState *s1, FILE *fp)
1369 struct pe_rsrc_header hdr;
1370 Section *rsrc_section;
1371 int i, ret = -1;
1372 BYTE *ptr;
1373 unsigned offs;
1375 if (!read_mem(fp, 0, &hdr, sizeof hdr))
1376 goto quit;
1378 if (hdr.filehdr.Machine != 0x014C
1379 || hdr.filehdr.NumberOfSections != 1
1380 || strcmp(hdr.sectionhdr.Name, ".rsrc") != 0)
1381 goto quit;
1383 rsrc_section = new_section(s1, ".rsrc", SHT_PROGBITS, SHF_ALLOC);
1384 ptr = section_ptr_add(rsrc_section, hdr.sectionhdr.SizeOfRawData);
1385 offs = hdr.sectionhdr.PointerToRawData;
1386 if (!read_mem(fp, offs, ptr, hdr.sectionhdr.SizeOfRawData))
1387 goto quit;
1388 offs = hdr.sectionhdr.PointerToRelocations;
1389 for (i = 0; i < hdr.sectionhdr.NumberOfRelocations; ++i)
1391 struct pe_rsrc_reloc rel;
1392 if (!read_mem(fp, offs, &rel, sizeof rel))
1393 goto quit;
1394 // printf("rsrc_reloc: %x %x %x\n", rel.offset, rel.size, rel.type);
1395 if (rel.type != 7) /* DIR32NB */
1396 goto quit;
1397 put_elf_reloc(symtab_section, rsrc_section,
1398 rel.offset, R_XXX_RELATIVE, 0);
1399 offs += sizeof rel;
1401 ret = 0;
1402 quit:
1403 return ret;
1406 /* ------------------------------------------------------------- */
1407 ST_FN char *trimfront(char *p)
1409 while (*p && (unsigned char)*p <= ' ')
1410 ++p;
1411 return p;
1414 ST_FN char *trimback(char *a, char *e)
1416 while (e > a && (unsigned char)e[-1] <= ' ')
1417 --e;
1418 *e = 0;;
1419 return a;
1422 ST_FN char *get_line(char *line, int size, FILE *fp)
1424 if (NULL == fgets(line, size, fp))
1425 return NULL;
1426 trimback(line, strchr(line, 0));
1427 return trimfront(line);
1430 /* ------------------------------------------------------------- */
1431 ST_FN int pe_load_def(TCCState *s1, FILE *fp)
1433 DLLReference *dllref;
1434 int state = 0, ret = -1;
1435 char line[400], dllname[80], *p;
1437 for (;;) {
1438 p = get_line(line, sizeof line, fp);
1439 if (NULL == p)
1440 break;
1441 if (0 == *p || ';' == *p)
1442 continue;
1443 switch (state) {
1444 case 0:
1445 if (0 != strnicmp(p, "LIBRARY", 7))
1446 goto quit;
1447 strcpy(dllname, trimfront(p+7));
1448 ++state;
1449 continue;
1451 case 1:
1452 if (0 != stricmp(p, "EXPORTS"))
1453 goto quit;
1454 ++state;
1455 continue;
1457 case 2:
1458 dllref = tcc_mallocz(sizeof(DLLReference) + strlen(dllname));
1459 strcpy(dllref->name, dllname);
1460 dynarray_add((void ***) &s1->loaded_dlls, &s1->nb_loaded_dlls, dllref);
1461 ++state;
1463 default:
1464 add_elf_sym(s1->dynsymtab_section,
1465 s1->nb_loaded_dlls, 0,
1466 ELFW_ST_INFO(STB_GLOBAL, STT_FUNC), 0,
1467 text_section->sh_num, p);
1468 continue;
1471 ret = 0;
1472 quit:
1473 return ret;
1476 /* ------------------------------------------------------------- */
1477 #define TINY_IMPDEF_GET_EXPORT_NAMES_ONLY
1478 #include "win32/tools/tiny_impdef.c"
1480 ST_FN int pe_load_dll(TCCState *s1, const char *dllname, FILE *fp)
1482 int i = 0;
1483 char *p, *q;
1484 p = get_export_names(fp);
1485 if (p) {
1486 DLLReference *dllref;
1487 dllref = tcc_mallocz(sizeof(DLLReference) + strlen(dllname));
1488 strcpy(dllref->name, dllname);
1489 dynarray_add((void ***) &s1->loaded_dlls, &s1->nb_loaded_dlls, dllref);
1490 for (q = p, i = 0; *q; ++i) {
1491 add_elf_sym(s1->dynsymtab_section,
1492 s1->nb_loaded_dlls, 0,
1493 ELFW_ST_INFO(STB_GLOBAL, STT_FUNC), 0,
1494 text_section->sh_num, q);
1495 q += 1 + strlen(q);
1497 tcc_free(p);
1499 return i ? 0 : -1;
1502 /* ------------------------------------------------------------- */
1503 PUB_FN int pe_load_file(struct TCCState *s1, const char *filename, int fd)
1505 FILE *fp = fdopen(dup(fd), "rb");
1506 int ret = -1;
1507 char buf[10];
1508 if (fp) {
1509 if (0 == strcmp(tcc_fileextension(filename), ".def"))
1510 ret = pe_load_def(s1, fp);
1511 else if (pe_load_res(s1, fp) == 0)
1512 ret = 0;
1513 else if (read_mem(fp, 0, buf, sizeof buf) && 0 == strncmp(buf, "MZ", 2))
1514 ret = pe_load_dll(s1, tcc_basename(filename), fp);
1515 fclose(fp);
1517 return ret;
1520 int pe_add_dll(struct TCCState *s, const char *libraryname)
1522 char buf[MAX_PATH];
1523 snprintf(buf, sizeof(buf), "%s.def", libraryname);
1524 if (tcc_add_dll(s, buf, 0) == 0)
1525 return 0;
1526 snprintf(buf, sizeof(buf), "%s.dll", libraryname);
1527 if (tcc_add_dll(s, buf, 0) == 0)
1528 return 0;
1529 return -1;
1532 /* ------------------------------------------------------------- */
1533 #ifdef TCC_TARGET_X86_64
1534 #define PE_STDSYM(n,s) n
1535 #else
1536 #define PE_STDSYM(n,s) "_" n s
1537 #endif
1539 ST_FN void pe_add_runtime_ex(TCCState *s1, struct pe_info *pe)
1541 const char *start_symbol;
1542 unsigned long addr = 0;
1543 int pe_type = 0;
1545 if (find_elf_sym(symtab_section, PE_STDSYM("WinMain","@16")))
1546 pe_type = PE_GUI;
1547 else
1548 if (TCC_OUTPUT_DLL == s1->output_type) {
1549 pe_type = PE_DLL;
1550 /* need this for 'tccelf.c:relocate_section()' */
1551 s1->output_type = TCC_OUTPUT_EXE;
1554 start_symbol =
1555 TCC_OUTPUT_MEMORY == s1->output_type
1556 ? PE_GUI == pe_type ? "_runwinmain" : NULL
1557 : PE_DLL == pe_type ? PE_STDSYM("_dllstart","@12")
1558 : PE_GUI == pe_type ? "_winstart" : "_start"
1561 /* grab the startup code from libtcc1 */
1562 if (start_symbol)
1563 add_elf_sym(symtab_section,
1564 0, 0,
1565 ELFW_ST_INFO(STB_GLOBAL, STT_NOTYPE), 0,
1566 SHN_UNDEF, start_symbol);
1568 if (0 == s1->nostdlib) {
1569 static const char *libs[] = {
1570 "tcc1", "msvcrt", "kernel32", "", "user32", "gdi32", NULL
1572 const char **pp, *p;
1573 for (pp = libs; 0 != (p = *pp); ++pp) {
1574 if (0 == *p) {
1575 if (PE_DLL != pe_type && PE_GUI != pe_type)
1576 break;
1577 } else if (tcc_add_library(s1, p) < 0)
1578 error_noabort("cannot find library: %s", p);
1582 if (start_symbol) {
1583 addr = (uplong)tcc_get_symbol_err(s1, start_symbol);
1584 if (s1->output_type == TCC_OUTPUT_MEMORY && addr)
1585 /* for -run GUI's, put '_runwinmain' instead of 'main' */
1586 add_elf_sym(symtab_section,
1587 addr, 0,
1588 ELFW_ST_INFO(STB_GLOBAL, STT_NOTYPE), 0,
1589 text_section->sh_num, "main");
1592 pe->type = pe_type;
1593 pe->start_addr = addr;
1596 PUB_FN int pe_output_file(TCCState * s1, const char *filename)
1598 int ret;
1599 struct pe_info pe;
1600 int i;
1602 memset(&pe, 0, sizeof pe);
1603 pe.filename = filename;
1604 pe.s1 = s1;
1606 pe_add_runtime_ex(s1, &pe);
1607 relocate_common_syms(); /* assign bss adresses */
1608 tcc_add_linker_symbols(s1);
1610 ret = pe_check_symbols(&pe);
1611 if (ret)
1612 return ret;
1614 if (filename) {
1615 if (PE_DLL == pe.type) {
1616 pe.reloc = new_section(pe.s1, ".reloc", SHT_PROGBITS, 0);
1617 pe.imagebase = 0x10000000;
1618 } else {
1619 pe.imagebase = 0x00400000;
1621 pe_assign_addresses(&pe);
1622 relocate_syms(s1, 0);
1623 for (i = 1; i < s1->nb_sections; ++i) {
1624 Section *s = s1->sections[i];
1625 if (s->reloc) {
1626 relocate_section(s1, s);
1627 pe_relocate_rva(&pe, s);
1630 if (s1->nb_errors)
1631 ret = 1;
1632 else
1633 ret = pe_write(&pe);
1634 tcc_free(pe.sec_info);
1635 } else {
1636 #ifndef TCC_IS_NATIVE
1637 error_noabort("-run supported only on native platform");
1638 #endif
1639 pe.type = PE_RUN;
1640 pe.thunk = data_section;
1641 pe_build_imports(&pe);
1644 #ifdef PE_PRINT_SECTIONS
1645 pe_print_sections(s1, "tcc.log");
1646 #endif
1647 return ret;
1650 /* ------------------------------------------------------------- */
1651 #endif /* def TCC_TARGET_PE */
1652 /* ------------------------------------------------------------- */