tccpe: build IAT vector with with -run too
[tinycc.git] / tccpe.c
bloba25bad38cdb4aabcb862e4da8c3bee87f83abee2
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 #if defined _WIN32 && (defined _WIN64) == (defined TCC_TARGET_X86_64)
40 #define TCC_IS_NATIVE
41 #endif
43 /* ----------------------------------------------------------- */
44 #ifndef IMAGE_NT_SIGNATURE
45 /* ----------------------------------------------------------- */
46 /* definitions below are from winnt.h */
48 typedef unsigned char BYTE;
49 typedef unsigned short WORD;
50 typedef unsigned long DWORD;
51 #pragma pack(push, 1)
53 typedef struct _IMAGE_DOS_HEADER { /* DOS .EXE header */
54 WORD e_magic; /* Magic number */
55 WORD e_cblp; /* Bytes on last page of file */
56 WORD e_cp; /* Pages in file */
57 WORD e_crlc; /* Relocations */
58 WORD e_cparhdr; /* Size of header in paragraphs */
59 WORD e_minalloc; /* Minimum extra paragraphs needed */
60 WORD e_maxalloc; /* Maximum extra paragraphs needed */
61 WORD e_ss; /* Initial (relative) SS value */
62 WORD e_sp; /* Initial SP value */
63 WORD e_csum; /* Checksum */
64 WORD e_ip; /* Initial IP value */
65 WORD e_cs; /* Initial (relative) CS value */
66 WORD e_lfarlc; /* File address of relocation table */
67 WORD e_ovno; /* Overlay number */
68 WORD e_res[4]; /* Reserved words */
69 WORD e_oemid; /* OEM identifier (for e_oeminfo) */
70 WORD e_oeminfo; /* OEM information; e_oemid specific */
71 WORD e_res2[10]; /* Reserved words */
72 DWORD e_lfanew; /* File address of new exe header */
73 } IMAGE_DOS_HEADER, *PIMAGE_DOS_HEADER;
75 #define IMAGE_NT_SIGNATURE 0x00004550 /* PE00 */
76 #define SIZE_OF_NT_SIGNATURE 4
78 typedef struct _IMAGE_FILE_HEADER {
79 WORD Machine;
80 WORD NumberOfSections;
81 DWORD TimeDateStamp;
82 DWORD PointerToSymbolTable;
83 DWORD NumberOfSymbols;
84 WORD SizeOfOptionalHeader;
85 WORD Characteristics;
86 } IMAGE_FILE_HEADER, *PIMAGE_FILE_HEADER;
89 #define IMAGE_SIZEOF_FILE_HEADER 20
91 typedef struct _IMAGE_DATA_DIRECTORY {
92 DWORD VirtualAddress;
93 DWORD Size;
94 } IMAGE_DATA_DIRECTORY, *PIMAGE_DATA_DIRECTORY;
97 typedef struct _IMAGE_OPTIONAL_HEADER {
98 /* Standard fields. */
99 WORD Magic;
100 BYTE MajorLinkerVersion;
101 BYTE MinorLinkerVersion;
102 DWORD SizeOfCode;
103 DWORD SizeOfInitializedData;
104 DWORD SizeOfUninitializedData;
105 DWORD AddressOfEntryPoint;
106 DWORD BaseOfCode;
107 DWORD BaseOfData;
109 /* NT additional fields. */
110 DWORD ImageBase;
111 DWORD SectionAlignment;
112 DWORD FileAlignment;
113 WORD MajorOperatingSystemVersion;
114 WORD MinorOperatingSystemVersion;
115 WORD MajorImageVersion;
116 WORD MinorImageVersion;
117 WORD MajorSubsystemVersion;
118 WORD MinorSubsystemVersion;
119 DWORD Win32VersionValue;
120 DWORD SizeOfImage;
121 DWORD SizeOfHeaders;
122 DWORD CheckSum;
123 WORD Subsystem;
124 WORD DllCharacteristics;
125 DWORD SizeOfStackReserve;
126 DWORD SizeOfStackCommit;
127 DWORD SizeOfHeapReserve;
128 DWORD SizeOfHeapCommit;
129 DWORD LoaderFlags;
130 DWORD NumberOfRvaAndSizes;
131 IMAGE_DATA_DIRECTORY DataDirectory[16];
133 } IMAGE_OPTIONAL_HEADER, *PIMAGE_OPTIONAL_HEADER;
136 #define IMAGE_DIRECTORY_ENTRY_EXPORT 0 /* Export Directory */
137 #define IMAGE_DIRECTORY_ENTRY_IMPORT 1 /* Import Directory */
138 #define IMAGE_DIRECTORY_ENTRY_RESOURCE 2 /* Resource Directory */
139 #define IMAGE_DIRECTORY_ENTRY_EXCEPTION 3 /* Exception Directory */
140 #define IMAGE_DIRECTORY_ENTRY_SECURITY 4 /* Security Directory */
141 #define IMAGE_DIRECTORY_ENTRY_BASERELOC 5 /* Base Relocation Table */
142 #define IMAGE_DIRECTORY_ENTRY_DEBUG 6 /* Debug Directory */
143 /* IMAGE_DIRECTORY_ENTRY_COPYRIGHT 7 (X86 usage) */
144 #define IMAGE_DIRECTORY_ENTRY_ARCHITECTURE 7 /* Architecture Specific Data */
145 #define IMAGE_DIRECTORY_ENTRY_GLOBALPTR 8 /* RVA of GP */
146 #define IMAGE_DIRECTORY_ENTRY_TLS 9 /* TLS Directory */
147 #define IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG 10 /* Load Configuration Directory */
148 #define IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT 11 /* Bound Import Directory in headers */
149 #define IMAGE_DIRECTORY_ENTRY_IAT 12 /* Import Address Table */
150 #define IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT 13 /* Delay Load Import Descriptors */
151 #define IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR 14 /* COM Runtime descriptor */
153 /* Section header format. */
154 #define IMAGE_SIZEOF_SHORT_NAME 8
156 typedef struct _IMAGE_SECTION_HEADER {
157 BYTE Name[IMAGE_SIZEOF_SHORT_NAME];
158 union {
159 DWORD PhysicalAddress;
160 DWORD VirtualSize;
161 } Misc;
162 DWORD VirtualAddress;
163 DWORD SizeOfRawData;
164 DWORD PointerToRawData;
165 DWORD PointerToRelocations;
166 DWORD PointerToLinenumbers;
167 WORD NumberOfRelocations;
168 WORD NumberOfLinenumbers;
169 DWORD Characteristics;
170 } IMAGE_SECTION_HEADER, *PIMAGE_SECTION_HEADER;
172 #define IMAGE_SIZEOF_SECTION_HEADER 40
174 typedef struct _IMAGE_BASE_RELOCATION {
175 DWORD VirtualAddress;
176 DWORD SizeOfBlock;
177 // WORD TypeOffset[1];
178 } IMAGE_BASE_RELOCATION;
180 #define IMAGE_SIZEOF_BASE_RELOCATION 8
182 #define IMAGE_REL_BASED_ABSOLUTE 0
183 #define IMAGE_REL_BASED_HIGH 1
184 #define IMAGE_REL_BASED_LOW 2
185 #define IMAGE_REL_BASED_HIGHLOW 3
186 #define IMAGE_REL_BASED_HIGHADJ 4
187 #define IMAGE_REL_BASED_MIPS_JMPADDR 5
188 #define IMAGE_REL_BASED_SECTION 6
189 #define IMAGE_REL_BASED_REL32 7
191 #pragma pack(pop)
193 /* ----------------------------------------------------------- */
194 #endif /* ndef IMAGE_NT_SIGNATURE */
195 /* ----------------------------------------------------------- */
197 #pragma pack(push, 1)
199 struct pe_header
201 IMAGE_DOS_HEADER doshdr;
202 BYTE dosstub[0x40];
203 DWORD nt_sig;
204 IMAGE_FILE_HEADER filehdr;
205 IMAGE_OPTIONAL_HEADER opthdr;
208 struct pe_import_header {
209 DWORD first_entry;
210 DWORD time_date;
211 DWORD forwarder;
212 DWORD lib_name_offset;
213 DWORD first_thunk;
216 struct pe_export_header {
217 DWORD Characteristics;
218 DWORD TimeDateStamp;
219 DWORD Version;
220 DWORD Name;
221 DWORD Base;
222 DWORD NumberOfFunctions;
223 DWORD NumberOfNames;
224 DWORD AddressOfFunctions;
225 DWORD AddressOfNames;
226 DWORD AddressOfNameOrdinals;
229 struct pe_reloc_header {
230 DWORD offset;
231 DWORD size;
234 struct pe_rsrc_header {
235 struct _IMAGE_FILE_HEADER filehdr;
236 struct _IMAGE_SECTION_HEADER sectionhdr;
239 struct pe_rsrc_reloc {
240 DWORD offset;
241 DWORD size;
242 WORD type;
245 #pragma pack(pop)
247 /* ----------------------------------------------------------- */
248 ST_DATA struct pe_header pe_header = {
250 /* IMAGE_DOS_HEADER doshdr */
251 0x5A4D, /*WORD e_magic; Magic number */
252 0x0090, /*WORD e_cblp; Bytes on last page of file */
253 0x0003, /*WORD e_cp; Pages in file */
254 0x0000, /*WORD e_crlc; Relocations */
256 0x0004, /*WORD e_cparhdr; Size of header in paragraphs */
257 0x0000, /*WORD e_minalloc; Minimum extra paragraphs needed */
258 0xFFFF, /*WORD e_maxalloc; Maximum extra paragraphs needed */
259 0x0000, /*WORD e_ss; Initial (relative) SS value */
261 0x00B8, /*WORD e_sp; Initial SP value */
262 0x0000, /*WORD e_csum; Checksum */
263 0x0000, /*WORD e_ip; Initial IP value */
264 0x0000, /*WORD e_cs; Initial (relative) CS value */
265 0x0040, /*WORD e_lfarlc; File address of relocation table */
266 0x0000, /*WORD e_ovno; Overlay number */
267 {0,0,0,0}, /*WORD e_res[4]; Reserved words */
268 0x0000, /*WORD e_oemid; OEM identifier (for e_oeminfo) */
269 0x0000, /*WORD e_oeminfo; OEM information; e_oemid specific */
270 {0,0,0,0,0,0,0,0,0,0}, /*WORD e_res2[10]; Reserved words */
271 0x00000080 /*DWORD e_lfanew; File address of new exe header */
273 /* BYTE dosstub[0x40] */
274 /* 14 code bytes + "This program cannot be run in DOS mode.\r\r\n$" + 6 * 0x00 */
275 0x0e,0x1f,0xba,0x0e,0x00,0xb4,0x09,0xcd,0x21,0xb8,0x01,0x4c,0xcd,0x21,0x54,0x68,
276 0x69,0x73,0x20,0x70,0x72,0x6f,0x67,0x72,0x61,0x6d,0x20,0x63,0x61,0x6e,0x6e,0x6f,
277 0x74,0x20,0x62,0x65,0x20,0x72,0x75,0x6e,0x20,0x69,0x6e,0x20,0x44,0x4f,0x53,0x20,
278 0x6d,0x6f,0x64,0x65,0x2e,0x0d,0x0d,0x0a,0x24,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
280 0x00004550, /* DWORD nt_sig = IMAGE_NT_SIGNATURE */
282 /* IMAGE_FILE_HEADER filehdr */
283 0x014C, /*WORD Machine; */
284 0x0003, /*WORD NumberOfSections; */
285 0x00000000, /*DWORD TimeDateStamp; */
286 0x00000000, /*DWORD PointerToSymbolTable; */
287 0x00000000, /*DWORD NumberOfSymbols; */
288 0x00E0, /*WORD SizeOfOptionalHeader; */
289 0x030F /*WORD Characteristics; */
291 /* IMAGE_OPTIONAL_HEADER opthdr */
292 /* Standard fields. */
293 0x010B, /*WORD Magic; */
294 0x06, /*BYTE MajorLinkerVersion; */
295 0x00, /*BYTE MinorLinkerVersion; */
296 0x00000000, /*DWORD SizeOfCode; */
297 0x00000000, /*DWORD SizeOfInitializedData; */
298 0x00000000, /*DWORD SizeOfUninitializedData; */
299 0x00000000, /*DWORD AddressOfEntryPoint; */
300 0x00000000, /*DWORD BaseOfCode; */
301 0x00000000, /*DWORD BaseOfData; */
303 /* NT additional fields. */
304 0x00400000, /*DWORD ImageBase; */
305 0x00001000, /*DWORD SectionAlignment; */
306 0x00000200, /*DWORD FileAlignment; */
307 0x0004, /*WORD MajorOperatingSystemVersion; */
308 0x0000, /*WORD MinorOperatingSystemVersion; */
309 0x0000, /*WORD MajorImageVersion; */
310 0x0000, /*WORD MinorImageVersion; */
311 0x0004, /*WORD MajorSubsystemVersion; */
312 0x0000, /*WORD MinorSubsystemVersion; */
313 0x00000000, /*DWORD Win32VersionValue; */
314 0x00000000, /*DWORD SizeOfImage; */
315 0x00000200, /*DWORD SizeOfHeaders; */
316 0x00000000, /*DWORD CheckSum; */
317 0x0002, /*WORD Subsystem; */
318 0x0000, /*WORD DllCharacteristics; */
319 0x00100000, /*DWORD SizeOfStackReserve; */
320 0x00001000, /*DWORD SizeOfStackCommit; */
321 0x00100000, /*DWORD SizeOfHeapReserve; */
322 0x00001000, /*DWORD SizeOfHeapCommit; */
323 0x00000000, /*DWORD LoaderFlags; */
324 0x00000010, /*DWORD NumberOfRvaAndSizes; */
326 /* IMAGE_DATA_DIRECTORY DataDirectory[16]; */
327 {{0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0},
328 {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}}
331 /* ------------------------------------------------------------- */
332 /* internal temporary structures */
335 #define IMAGE_SCN_CNT_CODE 0x00000020
336 #define IMAGE_SCN_CNT_INITIALIZED_DATA 0x00000040
337 #define IMAGE_SCN_CNT_UNINITIALIZED_DATA 0x00000080
338 #define IMAGE_SCN_MEM_DISCARDABLE 0x02000000
339 #define IMAGE_SCN_MEM_SHARED 0x10000000
340 #define IMAGE_SCN_MEM_EXECUTE 0x20000000
341 #define IMAGE_SCN_MEM_READ 0x40000000
342 #define IMAGE_SCN_MEM_WRITE 0x80000000
345 enum {
346 sec_text = 0,
347 sec_data ,
348 sec_bss ,
349 sec_idata ,
350 sec_other ,
351 sec_rsrc ,
352 sec_stab ,
353 sec_reloc ,
354 sec_last
357 ST_DATA DWORD pe_sec_flags[] = {
358 0x60000020, /* ".text" , */
359 0xC0000040, /* ".data" , */
360 0xC0000080, /* ".bss" , */
361 0x40000040, /* ".idata" , */
362 0xE0000060, /* < other > , */
363 0x40000040, /* ".rsrc" , */
364 0x42000802, /* ".stab" , */
365 0x42000040, /* ".reloc" , */
368 struct section_info {
369 int cls, ord;
370 char name[32];
371 DWORD sh_addr;
372 DWORD sh_size;
373 DWORD sh_flags;
374 unsigned char *data;
375 DWORD data_size;
376 IMAGE_SECTION_HEADER ish;
379 struct import_symbol {
380 int sym_index;
381 int iat_index;
382 int thk_offset;
385 struct pe_import_info {
386 int dll_index;
387 int sym_count;
388 struct import_symbol **symbols;
391 struct pe_info {
392 TCCState *s1;
393 Section *reloc;
394 Section *thunk;
395 const char *filename;
396 int type;
397 DWORD sizeofheaders;
398 DWORD imagebase;
399 DWORD start_addr;
400 DWORD imp_offs;
401 DWORD imp_size;
402 DWORD iat_offs;
403 DWORD iat_size;
404 DWORD exp_offs;
405 DWORD exp_size;
406 struct section_info *sec_info;
407 int sec_count;
408 struct pe_import_info **imp_info;
409 int imp_count;
412 /* ------------------------------------------------------------- */
414 #define PE_NUL 0
415 #define PE_DLL 1
416 #define PE_GUI 2
417 #define PE_EXE 3
418 #define PE_RUN 4
420 void error_noabort(const char *, ...);
422 #ifdef _WIN32
423 void dbg_printf (const char *fmt, ...)
425 char buffer[4000];
426 va_list arg;
427 int x;
428 va_start(arg, fmt);
429 x = vsprintf (buffer, fmt, arg);
430 strcpy(buffer+x, "\n");
431 OutputDebugString(buffer);
433 #endif
435 /* --------------------------------------------*/
437 ST_FN const char* get_alt_symbol(char *buffer, const char *symbol)
439 const char *p;
440 p = strrchr(symbol, '@');
441 if (p && isnum(p[1]) && symbol[0] == '_') { /* stdcall decor */
442 strcpy(buffer, symbol+1)[p-symbol-1] = 0;
443 } else if (symbol[0] != '_') { /* try non-ansi function */
444 buffer[0] = '_', strcpy(buffer + 1, symbol);
445 } else if (0 == memcmp(symbol, "__imp__", 7)) { /* mingw 2.0 */
446 strcpy(buffer, symbol + 6);
447 } else if (0 == memcmp(symbol, "_imp___", 7)) { /* mingw 3.7 */
448 strcpy(buffer, symbol + 6);
449 } else {
450 return symbol;
452 return buffer;
455 ST_FN int pe_find_import(TCCState * s1, const char *symbol)
457 char buffer[200];
458 const char *s;
459 int sym_index, n = 0;
460 do {
461 s = n ? get_alt_symbol(buffer, symbol) : symbol;
462 sym_index = find_elf_sym(s1->dynsymtab_section, s);
463 // printf("find (%d) %d %s\n", n, sym_index, s);
464 } while (0 == sym_index && ++n < 2);
465 return sym_index;
468 /*----------------------------------------------------------------------------*/
470 ST_FN int dynarray_assoc(void **pp, int n, int key)
472 int i;
473 for (i = 0; i < n; ++i, ++pp)
474 if (key == **(int **) pp)
475 return i;
476 return -1;
479 #if 0
480 ST_FN DWORD umin(DWORD a, DWORD b)
482 return a < b ? a : b;
484 #endif
486 ST_FN DWORD umax(DWORD a, DWORD b)
488 return a < b ? b : a;
491 ST_FN void pe_fpad(FILE *fp, DWORD new_pos)
493 DWORD pos = ftell(fp);
494 while (++pos <= new_pos)
495 fputc(0, fp);
498 ST_FN DWORD pe_file_align(DWORD n)
500 return (n + (0x200 - 1)) & ~(0x200 - 1);
503 ST_FN DWORD pe_virtual_align(DWORD n)
505 return (n + (0x1000 - 1)) & ~(0x1000 - 1);
508 ST_FN void pe_align_section(Section *s, int a)
510 int i = s->data_offset & (a-1);
511 if (i)
512 section_ptr_add(s, a - i);
515 ST_FN void pe_set_datadir(int dir, DWORD addr, DWORD size)
517 pe_header.opthdr.DataDirectory[dir].VirtualAddress = addr;
518 pe_header.opthdr.DataDirectory[dir].Size = size;
521 /*----------------------------------------------------------------------------*/
522 ST_FN int pe_write(struct pe_info *pe)
524 int i;
525 FILE *op;
526 DWORD file_offset, r;
528 op = fopen(pe->filename, "wb");
529 if (NULL == op) {
530 error_noabort("could not write '%s': %s", pe->filename, strerror(errno));
531 return 1;
534 pe->sizeofheaders = pe_file_align(
535 sizeof pe_header
536 + pe->sec_count * sizeof (IMAGE_SECTION_HEADER)
539 file_offset = pe->sizeofheaders;
540 pe_fpad(op, file_offset);
542 if (2 == pe->s1->verbose)
543 printf("-------------------------------"
544 "\n virt file size section" "\n");
546 for (i = 0; i < pe->sec_count; ++i) {
547 struct section_info *si = pe->sec_info + i;
548 const char *sh_name = si->name;
549 unsigned long addr = si->sh_addr - pe->imagebase;
550 unsigned long size = si->sh_size;
551 IMAGE_SECTION_HEADER *psh = &si->ish;
553 if (2 == pe->s1->verbose)
554 printf("%6lx %6lx %6lx %s\n",
555 addr, file_offset, size, sh_name);
557 switch (si->cls) {
558 case sec_text:
559 pe_header.opthdr.BaseOfCode = addr;
560 pe_header.opthdr.AddressOfEntryPoint = addr + pe->start_addr;
561 break;
563 case sec_data:
564 pe_header.opthdr.BaseOfData = addr;
565 break;
567 case sec_bss:
568 break;
570 case sec_reloc:
571 pe_set_datadir(IMAGE_DIRECTORY_ENTRY_BASERELOC, addr, size);
572 break;
574 case sec_rsrc:
575 pe_set_datadir(IMAGE_DIRECTORY_ENTRY_RESOURCE, addr, size);
576 break;
578 case sec_stab:
579 break;
582 if (pe->thunk == pe->s1->sections[si->ord]) {
583 if (pe->imp_size) {
584 pe_set_datadir(IMAGE_DIRECTORY_ENTRY_IMPORT,
585 pe->imp_offs + addr, pe->imp_size);
586 pe_set_datadir(IMAGE_DIRECTORY_ENTRY_IAT,
587 pe->iat_offs + addr, pe->iat_size);
589 if (pe->exp_size) {
590 pe_set_datadir(IMAGE_DIRECTORY_ENTRY_EXPORT,
591 pe->exp_offs + addr, pe->exp_size);
595 strcpy((char*)psh->Name, sh_name);
597 psh->Characteristics = pe_sec_flags[si->cls];
598 psh->VirtualAddress = addr;
599 psh->Misc.VirtualSize = size;
600 pe_header.opthdr.SizeOfImage =
601 umax(pe_virtual_align(size + addr), pe_header.opthdr.SizeOfImage);
603 if (si->data_size) {
604 psh->PointerToRawData = r = file_offset;
605 fwrite(si->data, 1, si->data_size, op);
606 file_offset = pe_file_align(file_offset + si->data_size);
607 psh->SizeOfRawData = file_offset - r;
608 pe_fpad(op, file_offset);
612 // pe_header.filehdr.TimeDateStamp = time(NULL);
613 pe_header.filehdr.NumberOfSections = pe->sec_count;
614 pe_header.opthdr.SizeOfHeaders = pe->sizeofheaders;
615 pe_header.opthdr.ImageBase = pe->imagebase;
616 if (PE_DLL == pe->type)
617 pe_header.filehdr.Characteristics = 0x230E;
618 else if (PE_GUI != pe->type)
619 pe_header.opthdr.Subsystem = 3;
621 fseek(op, SEEK_SET, 0);
622 fwrite(&pe_header, 1, sizeof pe_header, op);
623 for (i = 0; i < pe->sec_count; ++i)
624 fwrite(&pe->sec_info[i].ish, 1, sizeof(IMAGE_SECTION_HEADER), op);
625 fclose (op);
627 if (2 == pe->s1->verbose)
628 printf("-------------------------------\n");
629 if (pe->s1->verbose)
630 printf("<- %s (%lu bytes)\n", pe->filename, file_offset);
632 return 0;
635 /*----------------------------------------------------------------------------*/
637 ST_FN struct import_symbol *pe_add_import(struct pe_info *pe, int sym_index)
639 int i;
640 int dll_index;
641 struct pe_import_info *p;
642 struct import_symbol *s;
644 dll_index = ((Elf32_Sym *)pe->s1->dynsymtab_section->data + sym_index)->st_value;
645 if (0 == dll_index)
646 return NULL;
648 i = dynarray_assoc ((void**)pe->imp_info, pe->imp_count, dll_index);
649 if (-1 != i) {
650 p = pe->imp_info[i];
651 goto found_dll;
653 p = tcc_mallocz(sizeof *p);
654 p->dll_index = dll_index;
655 dynarray_add((void***)&pe->imp_info, &pe->imp_count, p);
657 found_dll:
658 i = dynarray_assoc ((void**)p->symbols, p->sym_count, sym_index);
659 if (-1 != i)
660 return p->symbols[i];
662 s = tcc_mallocz(sizeof *s);
663 dynarray_add((void***)&p->symbols, &p->sym_count, s);
664 s->sym_index = sym_index;
665 return s;
668 /*----------------------------------------------------------------------------*/
669 ST_FN void pe_build_imports(struct pe_info *pe)
671 int thk_ptr, ent_ptr, dll_ptr, sym_cnt, i;
672 DWORD rva_base = pe->thunk->sh_addr - pe->imagebase;
673 int ndlls = pe->imp_count;
675 for (sym_cnt = i = 0; i < ndlls; ++i)
676 sym_cnt += pe->imp_info[i]->sym_count;
678 if (0 == sym_cnt)
679 return;
681 pe_align_section(pe->thunk, 16);
683 pe->imp_offs = dll_ptr = pe->thunk->data_offset;
684 pe->imp_size = (ndlls + 1) * sizeof(struct pe_import_header);
685 pe->iat_offs = dll_ptr + pe->imp_size;
686 pe->iat_size = (sym_cnt + ndlls) * sizeof(DWORD);
687 section_ptr_add(pe->thunk, pe->imp_size + 2*pe->iat_size);
689 thk_ptr = pe->iat_offs;
690 ent_ptr = pe->iat_offs + pe->iat_size;
692 for (i = 0; i < pe->imp_count; ++i) {
693 struct pe_import_header *hdr;
694 int k, n;
695 DWORD v;
696 struct pe_import_info *p = pe->imp_info[i];
697 const char *name = pe->s1->loaded_dlls[p->dll_index-1]->name;
699 /* put the dll name into the import header */
700 v = put_elf_str(pe->thunk, name);
702 hdr = (struct pe_import_header*)(pe->thunk->data + dll_ptr);
703 hdr->first_thunk = thk_ptr + rva_base;
704 hdr->first_entry = ent_ptr + rva_base;
705 hdr->lib_name_offset = v + rva_base;
707 for (k = 0, n = p->sym_count; k <= n; ++k) {
708 if (k < n) {
709 int iat_index = p->symbols[k]->iat_index;
710 int sym_index = p->symbols[k]->sym_index;
711 Elf32_Sym *imp_sym = (Elf32_Sym *)pe->s1->dynsymtab_section->data + sym_index;
712 Elf32_Sym *org_sym = (Elf32_Sym *)symtab_section->data + iat_index;
713 const char *name = pe->s1->dynsymtab_section->link->data + imp_sym->st_name;
715 org_sym->st_value = thk_ptr;
716 org_sym->st_shndx = pe->thunk->sh_num;
717 v = pe->thunk->data_offset + rva_base;
718 section_ptr_add(pe->thunk, sizeof(WORD)); /* hint, not used */
719 put_elf_str(pe->thunk, name);
720 #ifdef TCC_IS_NATIVE
721 if (pe->type == PE_RUN) {
722 DLLReference *dllref = pe->s1->loaded_dlls[imp_sym->st_value-1];
723 if ( !dllref->handle )
724 dllref->handle = LoadLibrary(dllref->name);
725 v = (DWORD)GetProcAddress(dllref->handle, name);
726 if (!v)
727 error_noabort("undefined symbol '%s'", name);
729 #endif
730 } else {
731 v = 0; /* last entry is zero */
733 *(DWORD*)(pe->thunk->data+thk_ptr) =
734 *(DWORD*)(pe->thunk->data+ent_ptr) = v;
735 thk_ptr += sizeof (DWORD);
736 ent_ptr += sizeof (DWORD);
738 dll_ptr += sizeof(struct pe_import_header);
739 dynarray_reset(&p->symbols, &p->sym_count);
741 dynarray_reset(&pe->imp_info, &pe->imp_count);
744 /* ------------------------------------------------------------- */
746 For now only functions are exported. Export of data
747 would work, but import requires compiler support to
748 do an additional indirection.
750 For instance:
751 __declspec(dllimport) extern int something;
753 needs to be translated to:
755 *(int*)something
758 ST_FN int sym_cmp(const void *va, const void *vb)
760 const char *ca = ((const char **)va)[1];
761 const char *cb = ((const char **)vb)[1];
762 return strcmp(ca, cb);
765 ST_FN void pe_build_exports(struct pe_info *pe)
767 Elf32_Sym *sym;
768 int sym_index, sym_end;
769 DWORD rva_base, func_o, name_o, ord_o, str_o;
770 struct pe_export_header *hdr;
771 int sym_count, n, ord, *sorted, *sp;
773 FILE *op;
774 char buf[MAX_PATH];
775 const char *dllname;
776 const char *name;
778 rva_base = pe->thunk->sh_addr - pe->imagebase;
779 sym_count = 0, n = 1, sorted = NULL, op = NULL;
781 sym_end = symtab_section->data_offset / sizeof(Elf32_Sym);
782 for (sym_index = 1; sym_index < sym_end; ++sym_index) {
783 sym = (Elf32_Sym*)symtab_section->data + sym_index;
784 name = symtab_section->link->data + sym->st_name;
785 if ((sym->st_other & 1)
786 /* export only symbols from actually written sections */
787 && pe->s1->sections[sym->st_shndx]->sh_addr) {
788 dynarray_add((void***)&sorted, &sym_count, (void*)n);
789 dynarray_add((void***)&sorted, &sym_count, (void*)name);
791 ++n;
792 #if 0
793 if (sym->st_other & 1)
794 printf("export: %s\n", name);
795 if (sym->st_other & 2)
796 printf("stdcall: %s\n", name);
797 #endif
800 if (0 == sym_count)
801 return;
802 sym_count /= 2;
804 qsort (sorted, sym_count, 2 * sizeof sorted[0], sym_cmp);
805 pe_align_section(pe->thunk, 16);
806 dllname = tcc_basename(pe->filename);
808 pe->exp_offs = pe->thunk->data_offset;
809 func_o = pe->exp_offs + sizeof(struct pe_export_header);
810 name_o = func_o + sym_count * sizeof (DWORD);
811 ord_o = name_o + sym_count * sizeof (DWORD);
812 str_o = ord_o + sym_count * sizeof(WORD);
814 hdr = section_ptr_add(pe->thunk, str_o - pe->exp_offs);
815 hdr->Characteristics = 0;
816 hdr->Base = 1;
817 hdr->NumberOfFunctions = sym_count;
818 hdr->NumberOfNames = sym_count;
819 hdr->AddressOfFunctions = func_o + rva_base;
820 hdr->AddressOfNames = name_o + rva_base;
821 hdr->AddressOfNameOrdinals = ord_o + rva_base;
822 hdr->Name = str_o + rva_base;
823 put_elf_str(pe->thunk, dllname);
825 #if 1
826 /* automatically write exports to <output-filename>.def */
827 strcpy(buf, pe->filename);
828 strcpy(tcc_fileextension(buf), ".def");
829 op = fopen(buf, "w");
830 if (NULL == op) {
831 error_noabort("could not create '%s': %s", buf, strerror(errno));
832 } else {
833 fprintf(op, "LIBRARY %s\n\nEXPORTS\n", dllname);
834 if (pe->s1->verbose)
835 printf("<- %s (%d symbols)\n", buf, sym_count);
837 #endif
839 for (sp = sorted, ord = 0; ord < sym_count; ++ord, sp += 2)
841 sym_index = sp[0], name = (const char *)sp[1];
842 /* insert actual address later in pe_relocate_rva */
843 put_elf_reloc(symtab_section, pe->thunk,
844 func_o, R_386_RELATIVE, sym_index);
845 *(DWORD*)(pe->thunk->data + name_o)
846 = pe->thunk->data_offset + rva_base;
847 *(WORD*)(pe->thunk->data + ord_o)
848 = ord;
849 put_elf_str(pe->thunk, name);
850 func_o += sizeof (DWORD);
851 name_o += sizeof (DWORD);
852 ord_o += sizeof (WORD);
854 if (op)
855 fprintf(op, "%s\n", name);
857 pe->exp_size = pe->thunk->data_offset - pe->exp_offs;
858 tcc_free(sorted);
861 /* ------------------------------------------------------------- */
862 ST_FN void pe_build_reloc (struct pe_info *pe)
864 DWORD offset, block_ptr, addr;
865 int count, i;
866 Elf32_Rel *rel, *rel_end;
867 Section *s = NULL, *sr;
869 offset = addr = block_ptr = count = i = 0;
870 rel = rel_end = NULL;
872 for(;;) {
873 if (rel < rel_end) {
874 int type = ELF32_R_TYPE(rel->r_info);
875 addr = rel->r_offset + s->sh_addr;
876 ++ rel;
877 if (type != R_386_32)
878 continue;
879 if (count == 0) { /* new block */
880 block_ptr = pe->reloc->data_offset;
881 section_ptr_add(pe->reloc, sizeof(struct pe_reloc_header));
882 offset = addr & 0xFFFFFFFF<<12;
884 if ((addr -= offset) < (1<<12)) { /* one block spans 4k addresses */
885 WORD *wp = section_ptr_add(pe->reloc, sizeof (WORD));
886 *wp = addr | IMAGE_REL_BASED_HIGHLOW<<12;
887 ++count;
888 continue;
890 -- rel;
892 } else if (i < pe->sec_count) {
893 sr = (s = pe->s1->sections[pe->sec_info[i++].ord])->reloc;
894 if (sr) {
895 rel = (Elf32_Rel *)sr->data;
896 rel_end = (Elf32_Rel *)(sr->data + sr->data_offset);
898 continue;
901 if (count) {
902 /* store the last block and ready for a new one */
903 struct pe_reloc_header *hdr;
904 if (count & 1) /* align for DWORDS */
905 section_ptr_add(pe->reloc, sizeof(WORD)), ++count;
906 hdr = (struct pe_reloc_header *)(pe->reloc->data + block_ptr);
907 hdr -> offset = offset - pe->imagebase;
908 hdr -> size = count * sizeof(WORD) + sizeof(struct pe_reloc_header);
909 count = 0;
912 if (rel >= rel_end)
913 break;
917 /* ------------------------------------------------------------- */
918 ST_FN int pe_section_class(Section *s)
920 int type, flags;
921 const char *name;
923 type = s->sh_type;
924 flags = s->sh_flags;
925 name = s->name;
926 if (flags & SHF_ALLOC) {
927 if (type == SHT_PROGBITS) {
928 if (flags & SHF_EXECINSTR)
929 return sec_text;
930 if (flags & SHF_WRITE)
931 return sec_data;
932 if (0 == strcmp(name, ".rsrc"))
933 return sec_rsrc;
934 if (0 == strcmp(name, ".iedat"))
935 return sec_idata;
936 return sec_other;
937 } else if (type == SHT_NOBITS) {
938 if (flags & SHF_WRITE)
939 return sec_bss;
941 } else {
942 if (0 == strcmp(name, ".reloc"))
943 return sec_reloc;
944 if (0 == strncmp(name, ".stab", 5)) /* .stab and .stabstr */
945 return sec_stab;
947 return -1;
950 ST_FN int pe_assign_addresses (struct pe_info *pe)
952 int i, k, o, c;
953 DWORD addr;
954 int *section_order;
955 struct section_info *si;
956 Section *s;
958 // pe->thunk = new_section(pe->s1, ".iedat", SHT_PROGBITS, SHF_ALLOC);
960 section_order = tcc_malloc(pe->s1->nb_sections * sizeof (int));
961 for (o = k = 0 ; k < sec_last; ++k) {
962 for (i = 1; i < pe->s1->nb_sections; ++i) {
963 s = pe->s1->sections[i];
964 if (k == pe_section_class(s)) {
965 // printf("%s %d\n", s->name, k);
966 s->sh_addr = pe->imagebase;
967 section_order[o++] = i;
972 pe->sec_info = tcc_mallocz(o * sizeof (struct section_info));
973 addr = pe->imagebase + 1;
975 for (i = 0; i < o; ++i)
977 k = section_order[i];
978 s = pe->s1->sections[k];
979 c = pe_section_class(s);
980 si = &pe->sec_info[pe->sec_count];
982 #ifdef PE_MERGE_DATA
983 if (c == sec_bss && pe->sec_count && si[-1].cls == sec_data) {
984 /* append .bss to .data */
985 s->sh_addr = addr = ((addr-1) | 15) + 1;
986 addr += s->data_offset;
987 si[-1].sh_size = addr - si[-1].sh_addr;
988 continue;
990 #endif
991 strcpy(si->name, s->name);
992 si->cls = c;
993 si->ord = k;
994 si->sh_addr = s->sh_addr = addr = pe_virtual_align(addr);
995 si->sh_flags = s->sh_flags;
997 if (c == sec_data && NULL == pe->thunk)
998 pe->thunk = s;
1000 if (s == pe->thunk) {
1001 pe_build_imports(pe);
1002 pe_build_exports(pe);
1005 if (c == sec_reloc)
1006 pe_build_reloc (pe);
1008 if (s->data_offset)
1010 if (s->sh_type != SHT_NOBITS) {
1011 si->data = s->data;
1012 si->data_size = s->data_offset;
1015 addr += s->data_offset;
1016 si->sh_size = s->data_offset;
1017 ++pe->sec_count;
1019 // printf("%08x %05x %s\n", si->sh_addr, si->sh_size, si->name);
1022 #if 0
1023 for (i = 1; i < pe->s1->nb_sections; ++i) {
1024 Section *s = pe->s1->sections[i];
1025 int type = s->sh_type;
1026 int flags = s->sh_flags;
1027 printf("section %-16s %-10s %5x %s,%s,%s\n",
1028 s->name,
1029 type == SHT_PROGBITS ? "progbits" :
1030 type == SHT_NOBITS ? "nobits" :
1031 type == SHT_SYMTAB ? "symtab" :
1032 type == SHT_STRTAB ? "strtab" :
1033 type == SHT_REL ? "rel" : "???",
1034 s->data_offset,
1035 flags & SHF_ALLOC ? "alloc" : "",
1036 flags & SHF_WRITE ? "write" : "",
1037 flags & SHF_EXECINSTR ? "exec" : ""
1040 pe->s1->verbose = 2;
1041 #endif
1043 tcc_free(section_order);
1044 return 0;
1047 /* ------------------------------------------------------------- */
1048 ST_FN void pe_relocate_rva (struct pe_info *pe, Section *s)
1050 Section *sr = s->reloc;
1051 Elf32_Rel *rel, *rel_end;
1052 rel_end = (Elf32_Rel *)(sr->data + sr->data_offset);
1053 for(rel = (Elf32_Rel *)sr->data; rel < rel_end; rel++)
1054 if (ELF32_R_TYPE(rel->r_info) == R_386_RELATIVE) {
1055 int sym_index = ELF32_R_SYM(rel->r_info);
1056 DWORD addr = s->sh_addr;
1057 if (sym_index) {
1058 Elf32_Sym *sym = (Elf32_Sym *)symtab_section->data + sym_index;
1059 addr = sym->st_value;
1061 *(DWORD*)(s->data + rel->r_offset) += addr - pe->imagebase;
1065 /*----------------------------------------------------------------------------*/
1066 ST_FN int pe_check_symbols(struct pe_info *pe)
1068 Elf32_Sym *sym;
1069 int sym_index, sym_end;
1070 int ret = 0;
1072 pe_align_section(text_section, 8);
1074 sym_end = symtab_section->data_offset / sizeof(Elf32_Sym);
1075 for (sym_index = 1; sym_index < sym_end; ++sym_index) {
1077 sym = (Elf32_Sym*)symtab_section->data + sym_index;
1078 if (sym->st_shndx == SHN_UNDEF) {
1080 const char *name = symtab_section->link->data + sym->st_name;
1081 unsigned type = ELF32_ST_TYPE(sym->st_info);
1082 int imp_sym = pe_find_import(pe->s1, name);
1083 struct import_symbol *is;
1085 if (0 == imp_sym)
1086 goto not_found;
1087 is = pe_add_import(pe, imp_sym);
1088 if (!is)
1089 goto not_found;
1091 if (type == STT_FUNC) {
1092 unsigned long offset = is->thk_offset;
1093 if (offset) {
1094 /* got aliased symbol, like stricmp and _stricmp */
1096 } else {
1097 char buffer[100];
1099 offset = text_section->data_offset;
1100 /* add the 'jmp IAT[x]' instruction */
1101 *(WORD*)section_ptr_add(text_section, 8) = 0x25FF;
1103 /* add a helper symbol, will be patched later in
1104 pe_build_imports */
1105 sprintf(buffer, "IAT.%s", name);
1106 is->iat_index = put_elf_sym(
1107 symtab_section, 0, sizeof(DWORD),
1108 ELF32_ST_INFO(STB_GLOBAL, STT_OBJECT),
1109 0, SHN_UNDEF, buffer);
1110 put_elf_reloc(symtab_section, text_section,
1111 offset + 2, R_386_32, is->iat_index);
1112 is->thk_offset = offset;
1115 /* tcc_realloc might have altered sym's address */
1116 sym = (Elf32_Sym*)symtab_section->data + sym_index;
1118 /* patch the original symbol */
1119 sym->st_value = offset;
1120 sym->st_shndx = text_section->sh_num;
1121 sym->st_other &= ~1; /* do not export */
1122 continue;
1125 if (type == STT_OBJECT) { /* data, ptr to that should be */
1126 if (0 == is->iat_index) {
1127 /* original symbol will be patched later in pe_build_imports */
1128 is->iat_index = sym_index;
1129 continue;
1133 not_found:
1134 error_noabort("undefined symbol '%s'", name);
1135 ret = 1;
1137 } else if (pe->s1->rdynamic
1138 && ELF32_ST_BIND(sym->st_info) != STB_LOCAL) {
1139 /* if -rdynamic option, then export all non local symbols */
1140 sym->st_other |= 1;
1143 return ret;
1146 /*----------------------------------------------------------------------------*/
1147 #ifdef PE_PRINT_SECTIONS
1148 ST_FN void pe_print_section(FILE * f, Section * s)
1150 /* just if you'r curious */
1151 BYTE *p, *e, b;
1152 int i, n, l, m;
1153 p = s->data;
1154 e = s->data + s->data_offset;
1155 l = e - p;
1157 fprintf(f, "section \"%s\"", s->name);
1158 if (s->link)
1159 fprintf(f, "\nlink \"%s\"", s->link->name);
1160 if (s->reloc)
1161 fprintf(f, "\nreloc \"%s\"", s->reloc->name);
1162 fprintf(f, "\nv_addr %08X", s->sh_addr);
1163 fprintf(f, "\ncontents %08X", l);
1164 fprintf(f, "\n\n");
1166 if (s->sh_type == SHT_NOBITS)
1167 return;
1169 if (0 == l)
1170 return;
1172 if (s->sh_type == SHT_SYMTAB)
1173 m = sizeof(Elf32_Sym);
1174 if (s->sh_type == SHT_REL)
1175 m = sizeof(Elf32_Rel);
1176 else
1177 m = 16;
1179 fprintf(f, "%-8s", "offset");
1180 for (i = 0; i < m; ++i)
1181 fprintf(f, " %02x", i);
1182 n = 56;
1184 if (s->sh_type == SHT_SYMTAB || s->sh_type == SHT_REL) {
1185 const char *fields1[] = {
1186 "name",
1187 "value",
1188 "size",
1189 "bind",
1190 "type",
1191 "other",
1192 "shndx",
1193 NULL
1196 const char *fields2[] = {
1197 "offs",
1198 "type",
1199 "symb",
1200 NULL
1203 const char **p;
1205 if (s->sh_type == SHT_SYMTAB)
1206 p = fields1, n = 106;
1207 else
1208 p = fields2, n = 58;
1210 for (i = 0; p[i]; ++i)
1211 fprintf(f, "%6s", p[i]);
1212 fprintf(f, " symbol");
1215 fprintf(f, "\n");
1216 for (i = 0; i < n; ++i)
1217 fprintf(f, "-");
1218 fprintf(f, "\n");
1220 for (i = 0; i < l;)
1222 fprintf(f, "%08X", i);
1223 for (n = 0; n < m; ++n) {
1224 if (n + i < l)
1225 fprintf(f, " %02X", p[i + n]);
1226 else
1227 fprintf(f, " ");
1230 if (s->sh_type == SHT_SYMTAB) {
1231 Elf32_Sym *sym = (Elf32_Sym *) (p + i);
1232 const char *name = s->link->data + sym->st_name;
1233 fprintf(f, " %04X %04X %04X %02X %02X %02X %04X \"%s\"",
1234 sym->st_name,
1235 sym->st_value,
1236 sym->st_size,
1237 ELF32_ST_BIND(sym->st_info),
1238 ELF32_ST_TYPE(sym->st_info),
1239 sym->st_other, sym->st_shndx, name);
1241 } else if (s->sh_type == SHT_REL) {
1242 Elf32_Rel *rel = (Elf32_Rel *) (p + i);
1243 Elf32_Sym *sym =
1244 (Elf32_Sym *) s->link->data + ELF32_R_SYM(rel->r_info);
1245 const char *name = s->link->link->data + sym->st_name;
1246 fprintf(f, " %04X %02X %04X \"%s\"",
1247 rel->r_offset,
1248 ELF32_R_TYPE(rel->r_info),
1249 ELF32_R_SYM(rel->r_info), name);
1250 } else {
1251 fprintf(f, " ");
1252 for (n = 0; n < m; ++n) {
1253 if (n + i < l) {
1254 b = p[i + n];
1255 if (b < 32 || b >= 127)
1256 b = '.';
1257 fprintf(f, "%c", b);
1261 i += m;
1262 fprintf(f, "\n");
1264 fprintf(f, "\n\n");
1267 ST_FN void pe_print_sections(TCCState *s1, const char *fname)
1269 Section *s;
1270 FILE *f;
1271 int i;
1272 f = fopen(fname, "wt");
1273 for (i = 1; i < s1->nb_sections; ++i) {
1274 s = s1->sections[i];
1275 pe_print_section(f, s);
1277 pe_print_section(f, s1->dynsymtab_section);
1278 fclose(f);
1280 #endif
1282 /* -------------------------------------------------------------
1283 * This is for compiled windows resources in 'coff' format
1284 * as generated by 'windres.exe -O coff ...'.
1287 PUB_FN int pe_test_res_file(void *v, int size)
1289 struct pe_rsrc_header *p = (struct pe_rsrc_header *)v;
1290 return
1291 size >= IMAGE_SIZEOF_FILE_HEADER + IMAGE_SIZEOF_SHORT_NAME /* = 28 */
1292 && p->filehdr.Machine == 0x014C
1293 && 1 == p->filehdr.NumberOfSections
1294 && 0 == strcmp(p->sectionhdr.Name, ".rsrc")
1298 ST_FN int read_n(int fd, void *ptr, unsigned size)
1300 return size == read(fd, ptr, size);
1303 PUB_FN int pe_load_res_file(TCCState *s1, int fd)
1305 struct pe_rsrc_header hdr;
1306 Section *rsrc_section;
1307 int i, ret = -1;
1308 BYTE *ptr;
1310 lseek (fd, 0, SEEK_SET);
1311 if (!read_n(fd, &hdr, sizeof hdr))
1312 goto quit;
1313 if (!pe_test_res_file(&hdr, sizeof hdr))
1314 goto quit;
1316 rsrc_section = new_section(s1, ".rsrc", SHT_PROGBITS, SHF_ALLOC);
1317 ptr = section_ptr_add(rsrc_section, hdr.sectionhdr.SizeOfRawData);
1318 lseek (fd, hdr.sectionhdr.PointerToRawData, SEEK_SET);
1319 if (!read_n(fd, ptr, hdr.sectionhdr.SizeOfRawData))
1320 goto quit;
1322 lseek (fd, hdr.sectionhdr.PointerToRelocations, SEEK_SET);
1323 for (i = 0; i < hdr.sectionhdr.NumberOfRelocations; ++i)
1325 struct pe_rsrc_reloc rel;
1326 if (!read_n(fd, &rel, sizeof rel))
1327 goto quit;
1328 // printf("rsrc_reloc: %x %x %x\n", rel.offset, rel.size, rel.type);
1329 if (rel.type != 7) /* DIR32NB */
1330 goto quit;
1331 put_elf_reloc(symtab_section, rsrc_section,
1332 rel.offset, R_386_RELATIVE, 0);
1334 ret = 0;
1335 quit:
1336 if (ret)
1337 error_noabort("unrecognized resource file format");
1338 return ret;
1341 /* ------------------------------------------------------------- */
1342 ST_FN char *trimfront(char *p)
1344 while (*p && (unsigned char)*p <= ' ')
1345 ++p;
1346 return p;
1349 ST_FN char *trimback(char *a, char *e)
1351 while (e > a && (unsigned char)e[-1] <= ' ')
1352 --e;
1353 *e = 0;;
1354 return a;
1357 ST_FN char *get_line(char *line, int size, FILE *fp)
1359 if (NULL == fgets(line, size, fp))
1360 return NULL;
1361 trimback(line, strchr(line, 0));
1362 return trimfront(line);
1365 /* ------------------------------------------------------------- */
1366 PUB_FN int pe_load_def_file(TCCState *s1, int fd)
1368 DLLReference *dllref;
1369 int state = 0, ret = -1;
1370 char line[400], dllname[80], *p;
1371 FILE *fp = fdopen(dup(fd), "rb");
1373 if (NULL == fp)
1374 goto quit;
1376 for (;;) {
1377 p = get_line(line, sizeof line, fp);
1378 if (NULL == p)
1379 break;
1380 if (0 == *p || ';' == *p)
1381 continue;
1382 switch (state) {
1383 case 0:
1384 if (0 != strnicmp(p, "LIBRARY", 7))
1385 goto quit;
1386 strcpy(dllname, trimfront(p+7));
1387 ++state;
1388 continue;
1390 case 1:
1391 if (0 != stricmp(p, "EXPORTS"))
1392 goto quit;
1393 ++state;
1394 continue;
1396 case 2:
1397 dllref = tcc_mallocz(sizeof(DLLReference) + strlen(dllname));
1398 strcpy(dllref->name, dllname);
1399 dynarray_add((void ***) &s1->loaded_dlls, &s1->nb_loaded_dlls, dllref);
1400 ++state;
1402 default:
1403 add_elf_sym(s1->dynsymtab_section,
1404 s1->nb_loaded_dlls, 0,
1405 ELF32_ST_INFO(STB_GLOBAL, STT_FUNC), 0,
1406 text_section->sh_num, p);
1407 continue;
1410 ret = 0;
1411 quit:
1412 if (fp)
1413 fclose(fp);
1414 if (ret)
1415 error_noabort("unrecognized export definition file format");
1416 return ret;
1419 /* ------------------------------------------------------------- */
1421 ST_FN void pe_add_runtime_ex(TCCState *s1, struct pe_info *pe)
1423 const char *start_symbol;
1424 unsigned long addr = 0;
1425 int pe_type = 0;
1427 if (find_elf_sym(symtab_section, "_WinMain@16"))
1428 pe_type = PE_GUI;
1429 else
1430 if (TCC_OUTPUT_DLL == s1->output_type) {
1431 pe_type = PE_DLL;
1432 /* need this for 'tccelf.c:relocate_section()' */
1433 s1->output_type = TCC_OUTPUT_EXE;
1436 start_symbol =
1437 TCC_OUTPUT_MEMORY == s1->output_type
1438 ? PE_GUI == pe_type ? "_runwinmain" : NULL
1439 : PE_DLL == pe_type ? "__dllstart@12"
1440 : PE_GUI == pe_type ? "_winstart" : "_start"
1443 /* grab the startup code from libtcc1 */
1444 if (start_symbol)
1445 add_elf_sym(symtab_section,
1446 0, 0,
1447 ELF32_ST_INFO(STB_GLOBAL, STT_NOTYPE), 0,
1448 SHN_UNDEF, start_symbol);
1450 if (0 == s1->nostdlib) {
1451 tcc_add_library(s1, "tcc1");
1452 #ifdef __CYGWIN__
1453 tcc_add_library(s1, "cygwin1");
1454 #else
1455 tcc_add_library(s1, "msvcrt");
1456 #endif
1457 tcc_add_library(s1, "kernel32");
1458 if (PE_DLL == pe_type || PE_GUI == pe_type) {
1459 tcc_add_library(s1, "user32");
1460 tcc_add_library(s1, "gdi32");
1463 pe->type = pe_type;
1465 if (start_symbol) {
1466 addr = (unsigned long)tcc_get_symbol_err(s1, start_symbol);
1467 if (s1->output_type == TCC_OUTPUT_MEMORY && addr)
1468 /* for -run GUI's, put '_runwinmain' instead of 'main' */
1469 add_elf_sym(symtab_section,
1470 addr, 0,
1471 ELF32_ST_INFO(STB_GLOBAL, STT_NOTYPE), 0,
1472 text_section->sh_num, "main");
1474 pe->start_addr = addr;
1477 PUB_FN int pe_output_file(TCCState * s1, const char *filename)
1479 int ret;
1480 struct pe_info pe;
1481 int i;
1483 memset(&pe, 0, sizeof pe);
1484 pe.filename = filename;
1485 pe.s1 = s1;
1487 pe_add_runtime_ex(s1, &pe);
1488 relocate_common_syms(); /* assign bss adresses */
1489 tcc_add_linker_symbols(s1);
1491 ret = pe_check_symbols(&pe);
1492 if (ret)
1493 return ret;
1495 if (filename) {
1496 if (PE_DLL == pe.type) {
1497 pe.reloc = new_section(pe.s1, ".reloc", SHT_PROGBITS, 0);
1498 pe.imagebase = 0x10000000;
1499 } else {
1500 pe.imagebase = 0x00400000;
1502 pe_assign_addresses(&pe);
1503 relocate_syms(s1, 0);
1504 for (i = 1; i < s1->nb_sections; ++i) {
1505 Section *s = s1->sections[i];
1506 if (s->reloc) {
1507 relocate_section(s1, s);
1508 pe_relocate_rva(&pe, s);
1511 if (s1->nb_errors)
1512 ret = 1;
1513 else
1514 ret = pe_write(&pe);
1515 tcc_free(pe.sec_info);
1516 } else {
1517 #ifndef TCC_IS_NATIVE
1518 error_noabort("-run supported only on native platform");
1519 #endif
1520 pe.type = PE_RUN;
1521 pe.thunk = data_section;
1522 pe_build_imports(&pe);
1525 #ifdef PE_PRINT_SECTIONS
1526 pe_print_sections(s1, "tcc.log");
1527 #endif
1528 return ret;
1531 /* ------------------------------------------------------------- */
1532 #endif /* def TCC_TARGET_PE */
1533 /* ------------------------------------------------------------- */