win32: structure return GCC compatible (ret 4 with cdecl)
[tinycc/k1w1.git] / tccpe.c
blob1e3fdb36900ee6267af23f75f77a9032f365ba5d
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 /* ----------------------------------------------------------- */
40 #ifndef IMAGE_NT_SIGNATURE
41 /* ----------------------------------------------------------- */
42 /* definitions below are from winnt.h */
44 typedef unsigned char BYTE;
45 typedef unsigned short WORD;
46 typedef unsigned long DWORD;
47 #pragma pack(push, 1)
49 typedef struct _IMAGE_DOS_HEADER { /* DOS .EXE header */
50 WORD e_magic; /* Magic number */
51 WORD e_cblp; /* Bytes on last page of file */
52 WORD e_cp; /* Pages in file */
53 WORD e_crlc; /* Relocations */
54 WORD e_cparhdr; /* Size of header in paragraphs */
55 WORD e_minalloc; /* Minimum extra paragraphs needed */
56 WORD e_maxalloc; /* Maximum extra paragraphs needed */
57 WORD e_ss; /* Initial (relative) SS value */
58 WORD e_sp; /* Initial SP value */
59 WORD e_csum; /* Checksum */
60 WORD e_ip; /* Initial IP value */
61 WORD e_cs; /* Initial (relative) CS value */
62 WORD e_lfarlc; /* File address of relocation table */
63 WORD e_ovno; /* Overlay number */
64 WORD e_res[4]; /* Reserved words */
65 WORD e_oemid; /* OEM identifier (for e_oeminfo) */
66 WORD e_oeminfo; /* OEM information; e_oemid specific */
67 WORD e_res2[10]; /* Reserved words */
68 DWORD e_lfanew; /* File address of new exe header */
69 } IMAGE_DOS_HEADER, *PIMAGE_DOS_HEADER;
71 #define IMAGE_NT_SIGNATURE 0x00004550 /* PE00 */
72 #define SIZE_OF_NT_SIGNATURE 4
74 typedef struct _IMAGE_FILE_HEADER {
75 WORD Machine;
76 WORD NumberOfSections;
77 DWORD TimeDateStamp;
78 DWORD PointerToSymbolTable;
79 DWORD NumberOfSymbols;
80 WORD SizeOfOptionalHeader;
81 WORD Characteristics;
82 } IMAGE_FILE_HEADER, *PIMAGE_FILE_HEADER;
85 #define IMAGE_SIZEOF_FILE_HEADER 20
87 typedef struct _IMAGE_DATA_DIRECTORY {
88 DWORD VirtualAddress;
89 DWORD Size;
90 } IMAGE_DATA_DIRECTORY, *PIMAGE_DATA_DIRECTORY;
93 typedef struct _IMAGE_OPTIONAL_HEADER {
94 /* Standard fields. */
95 WORD Magic;
96 BYTE MajorLinkerVersion;
97 BYTE MinorLinkerVersion;
98 DWORD SizeOfCode;
99 DWORD SizeOfInitializedData;
100 DWORD SizeOfUninitializedData;
101 DWORD AddressOfEntryPoint;
102 DWORD BaseOfCode;
103 DWORD BaseOfData;
105 /* NT additional fields. */
106 DWORD ImageBase;
107 DWORD SectionAlignment;
108 DWORD FileAlignment;
109 WORD MajorOperatingSystemVersion;
110 WORD MinorOperatingSystemVersion;
111 WORD MajorImageVersion;
112 WORD MinorImageVersion;
113 WORD MajorSubsystemVersion;
114 WORD MinorSubsystemVersion;
115 DWORD Win32VersionValue;
116 DWORD SizeOfImage;
117 DWORD SizeOfHeaders;
118 DWORD CheckSum;
119 WORD Subsystem;
120 WORD DllCharacteristics;
121 DWORD SizeOfStackReserve;
122 DWORD SizeOfStackCommit;
123 DWORD SizeOfHeapReserve;
124 DWORD SizeOfHeapCommit;
125 DWORD LoaderFlags;
126 DWORD NumberOfRvaAndSizes;
127 IMAGE_DATA_DIRECTORY DataDirectory[16];
129 } IMAGE_OPTIONAL_HEADER, *PIMAGE_OPTIONAL_HEADER;
132 #define IMAGE_DIRECTORY_ENTRY_EXPORT 0 /* Export Directory */
133 #define IMAGE_DIRECTORY_ENTRY_IMPORT 1 /* Import Directory */
134 #define IMAGE_DIRECTORY_ENTRY_RESOURCE 2 /* Resource Directory */
135 #define IMAGE_DIRECTORY_ENTRY_EXCEPTION 3 /* Exception Directory */
136 #define IMAGE_DIRECTORY_ENTRY_SECURITY 4 /* Security Directory */
137 #define IMAGE_DIRECTORY_ENTRY_BASERELOC 5 /* Base Relocation Table */
138 #define IMAGE_DIRECTORY_ENTRY_DEBUG 6 /* Debug Directory */
139 /* IMAGE_DIRECTORY_ENTRY_COPYRIGHT 7 (X86 usage) */
140 #define IMAGE_DIRECTORY_ENTRY_ARCHITECTURE 7 /* Architecture Specific Data */
141 #define IMAGE_DIRECTORY_ENTRY_GLOBALPTR 8 /* RVA of GP */
142 #define IMAGE_DIRECTORY_ENTRY_TLS 9 /* TLS Directory */
143 #define IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG 10 /* Load Configuration Directory */
144 #define IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT 11 /* Bound Import Directory in headers */
145 #define IMAGE_DIRECTORY_ENTRY_IAT 12 /* Import Address Table */
146 #define IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT 13 /* Delay Load Import Descriptors */
147 #define IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR 14 /* COM Runtime descriptor */
149 /* Section header format. */
150 #define IMAGE_SIZEOF_SHORT_NAME 8
152 typedef struct _IMAGE_SECTION_HEADER {
153 BYTE Name[IMAGE_SIZEOF_SHORT_NAME];
154 union {
155 DWORD PhysicalAddress;
156 DWORD VirtualSize;
157 } Misc;
158 DWORD VirtualAddress;
159 DWORD SizeOfRawData;
160 DWORD PointerToRawData;
161 DWORD PointerToRelocations;
162 DWORD PointerToLinenumbers;
163 WORD NumberOfRelocations;
164 WORD NumberOfLinenumbers;
165 DWORD Characteristics;
166 } IMAGE_SECTION_HEADER, *PIMAGE_SECTION_HEADER;
168 #define IMAGE_SIZEOF_SECTION_HEADER 40
170 typedef struct _IMAGE_BASE_RELOCATION {
171 DWORD VirtualAddress;
172 DWORD SizeOfBlock;
173 // WORD TypeOffset[1];
174 } IMAGE_BASE_RELOCATION;
176 #define IMAGE_SIZEOF_BASE_RELOCATION 8
178 #define IMAGE_REL_BASED_ABSOLUTE 0
179 #define IMAGE_REL_BASED_HIGH 1
180 #define IMAGE_REL_BASED_LOW 2
181 #define IMAGE_REL_BASED_HIGHLOW 3
182 #define IMAGE_REL_BASED_HIGHADJ 4
183 #define IMAGE_REL_BASED_MIPS_JMPADDR 5
184 #define IMAGE_REL_BASED_SECTION 6
185 #define IMAGE_REL_BASED_REL32 7
187 #pragma pack(pop)
189 /* ----------------------------------------------------------- */
190 #endif /* ndef IMAGE_NT_SIGNATURE */
191 /* ----------------------------------------------------------- */
193 #pragma pack(push, 1)
195 struct pe_header
197 IMAGE_DOS_HEADER doshdr;
198 BYTE dosstub[0x40];
199 DWORD nt_sig;
200 IMAGE_FILE_HEADER filehdr;
201 IMAGE_OPTIONAL_HEADER opthdr;
204 struct pe_import_header {
205 DWORD first_entry;
206 DWORD time_date;
207 DWORD forwarder;
208 DWORD lib_name_offset;
209 DWORD first_thunk;
212 struct pe_export_header {
213 DWORD Characteristics;
214 DWORD TimeDateStamp;
215 DWORD Version;
216 DWORD Name;
217 DWORD Base;
218 DWORD NumberOfFunctions;
219 DWORD NumberOfNames;
220 DWORD AddressOfFunctions;
221 DWORD AddressOfNames;
222 DWORD AddressOfNameOrdinals;
225 struct pe_reloc_header {
226 DWORD offset;
227 DWORD size;
230 struct pe_rsrc_header {
231 struct _IMAGE_FILE_HEADER filehdr;
232 struct _IMAGE_SECTION_HEADER sectionhdr;
235 struct pe_rsrc_reloc {
236 DWORD offset;
237 DWORD size;
238 WORD type;
241 #pragma pack(pop)
243 /* ----------------------------------------------------------- */
244 ST_DATA struct pe_header pe_header = {
246 /* IMAGE_DOS_HEADER doshdr */
247 0x5A4D, /*WORD e_magic; Magic number */
248 0x0090, /*WORD e_cblp; Bytes on last page of file */
249 0x0003, /*WORD e_cp; Pages in file */
250 0x0000, /*WORD e_crlc; Relocations */
252 0x0004, /*WORD e_cparhdr; Size of header in paragraphs */
253 0x0000, /*WORD e_minalloc; Minimum extra paragraphs needed */
254 0xFFFF, /*WORD e_maxalloc; Maximum extra paragraphs needed */
255 0x0000, /*WORD e_ss; Initial (relative) SS value */
257 0x00B8, /*WORD e_sp; Initial SP value */
258 0x0000, /*WORD e_csum; Checksum */
259 0x0000, /*WORD e_ip; Initial IP value */
260 0x0000, /*WORD e_cs; Initial (relative) CS value */
261 0x0040, /*WORD e_lfarlc; File address of relocation table */
262 0x0000, /*WORD e_ovno; Overlay number */
263 {0,0,0,0}, /*WORD e_res[4]; Reserved words */
264 0x0000, /*WORD e_oemid; OEM identifier (for e_oeminfo) */
265 0x0000, /*WORD e_oeminfo; OEM information; e_oemid specific */
266 {0,0,0,0,0,0,0,0,0,0}, /*WORD e_res2[10]; Reserved words */
267 0x00000080 /*DWORD e_lfanew; File address of new exe header */
269 /* BYTE dosstub[0x40] */
270 /* 14 code bytes + "This program cannot be run in DOS mode.\r\r\n$" + 6 * 0x00 */
271 0x0e,0x1f,0xba,0x0e,0x00,0xb4,0x09,0xcd,0x21,0xb8,0x01,0x4c,0xcd,0x21,0x54,0x68,
272 0x69,0x73,0x20,0x70,0x72,0x6f,0x67,0x72,0x61,0x6d,0x20,0x63,0x61,0x6e,0x6e,0x6f,
273 0x74,0x20,0x62,0x65,0x20,0x72,0x75,0x6e,0x20,0x69,0x6e,0x20,0x44,0x4f,0x53,0x20,
274 0x6d,0x6f,0x64,0x65,0x2e,0x0d,0x0d,0x0a,0x24,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
276 0x00004550, /* DWORD nt_sig = IMAGE_NT_SIGNATURE */
278 /* IMAGE_FILE_HEADER filehdr */
279 0x014C, /*WORD Machine; */
280 0x0003, /*WORD NumberOfSections; */
281 0x00000000, /*DWORD TimeDateStamp; */
282 0x00000000, /*DWORD PointerToSymbolTable; */
283 0x00000000, /*DWORD NumberOfSymbols; */
284 0x00E0, /*WORD SizeOfOptionalHeader; */
285 0x030F /*WORD Characteristics; */
287 /* IMAGE_OPTIONAL_HEADER opthdr */
288 /* Standard fields. */
289 0x010B, /*WORD Magic; */
290 0x06, /*BYTE MajorLinkerVersion; */
291 0x00, /*BYTE MinorLinkerVersion; */
292 0x00000000, /*DWORD SizeOfCode; */
293 0x00000000, /*DWORD SizeOfInitializedData; */
294 0x00000000, /*DWORD SizeOfUninitializedData; */
295 0x00000000, /*DWORD AddressOfEntryPoint; */
296 0x00000000, /*DWORD BaseOfCode; */
297 0x00000000, /*DWORD BaseOfData; */
299 /* NT additional fields. */
300 0x00400000, /*DWORD ImageBase; */
301 0x00001000, /*DWORD SectionAlignment; */
302 0x00000200, /*DWORD FileAlignment; */
303 0x0004, /*WORD MajorOperatingSystemVersion; */
304 0x0000, /*WORD MinorOperatingSystemVersion; */
305 0x0000, /*WORD MajorImageVersion; */
306 0x0000, /*WORD MinorImageVersion; */
307 0x0004, /*WORD MajorSubsystemVersion; */
308 0x0000, /*WORD MinorSubsystemVersion; */
309 0x00000000, /*DWORD Win32VersionValue; */
310 0x00000000, /*DWORD SizeOfImage; */
311 0x00000200, /*DWORD SizeOfHeaders; */
312 0x00000000, /*DWORD CheckSum; */
313 0x0002, /*WORD Subsystem; */
314 0x0000, /*WORD DllCharacteristics; */
315 0x00100000, /*DWORD SizeOfStackReserve; */
316 0x00001000, /*DWORD SizeOfStackCommit; */
317 0x00100000, /*DWORD SizeOfHeapReserve; */
318 0x00001000, /*DWORD SizeOfHeapCommit; */
319 0x00000000, /*DWORD LoaderFlags; */
320 0x00000010, /*DWORD NumberOfRvaAndSizes; */
322 /* IMAGE_DATA_DIRECTORY DataDirectory[16]; */
323 {{0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0},
324 {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}}
327 /* ------------------------------------------------------------- */
328 /* internal temporary structures */
331 #define IMAGE_SCN_CNT_CODE 0x00000020
332 #define IMAGE_SCN_CNT_INITIALIZED_DATA 0x00000040
333 #define IMAGE_SCN_CNT_UNINITIALIZED_DATA 0x00000080
334 #define IMAGE_SCN_MEM_DISCARDABLE 0x02000000
335 #define IMAGE_SCN_MEM_SHARED 0x10000000
336 #define IMAGE_SCN_MEM_EXECUTE 0x20000000
337 #define IMAGE_SCN_MEM_READ 0x40000000
338 #define IMAGE_SCN_MEM_WRITE 0x80000000
341 enum {
342 sec_text = 0,
343 sec_data ,
344 sec_bss ,
345 sec_idata ,
346 sec_other ,
347 sec_rsrc ,
348 sec_stab ,
349 sec_reloc ,
350 sec_last
353 ST_DATA DWORD pe_sec_flags[] = {
354 0x60000020, /* ".text" , */
355 0xC0000040, /* ".data" , */
356 0xC0000080, /* ".bss" , */
357 0x40000040, /* ".idata" , */
358 0xE0000060, /* < other > , */
359 0x40000040, /* ".rsrc" , */
360 0x42000802, /* ".stab" , */
361 0x42000040, /* ".reloc" , */
364 struct section_info {
365 int cls, ord;
366 char name[32];
367 DWORD sh_addr;
368 DWORD sh_size;
369 DWORD sh_flags;
370 unsigned char *data;
371 DWORD data_size;
372 IMAGE_SECTION_HEADER ish;
375 struct import_symbol {
376 int sym_index;
377 int iat_index;
378 int thk_offset;
381 struct pe_import_info {
382 int dll_index;
383 int sym_count;
384 struct import_symbol **symbols;
387 struct pe_info {
388 TCCState *s1;
389 Section *reloc;
390 Section *thunk;
391 const char *filename;
392 int type;
393 DWORD sizeofheaders;
394 DWORD imagebase;
395 DWORD start_addr;
396 DWORD imp_offs;
397 DWORD imp_size;
398 DWORD iat_offs;
399 DWORD iat_size;
400 DWORD exp_offs;
401 DWORD exp_size;
402 struct section_info *sec_info;
403 int sec_count;
404 struct pe_import_info **imp_info;
405 int imp_count;
408 /* ------------------------------------------------------------- */
410 #define PE_NUL 0
411 #define PE_DLL 1
412 #define PE_GUI 2
413 #define PE_EXE 3
415 void error_noabort(const char *, ...);
417 #ifdef _WIN32
418 void dbg_printf (const char *fmt, ...)
420 char buffer[4000];
421 va_list arg;
422 int x;
423 va_start(arg, fmt);
424 x = vsprintf (buffer, fmt, arg);
425 strcpy(buffer+x, "\n");
426 OutputDebugString(buffer);
428 #endif
430 /* --------------------------------------------*/
432 ST_FN const char* get_alt_symbol(char *buffer, const char *symbol)
434 const char *p;
435 p = strrchr(symbol, '@');
436 if (p && isnum(p[1]) && symbol[0] == '_') { /* stdcall decor */
437 strcpy(buffer, symbol+1)[p-symbol-1] = 0;
438 } else if (symbol[0] != '_') { /* try non-ansi function */
439 buffer[0] = '_', strcpy(buffer + 1, symbol);
440 } else if (0 == memcmp(symbol, "__imp__", 7)) { /* mingw 2.0 */
441 strcpy(buffer, symbol + 6);
442 } else if (0 == memcmp(symbol, "_imp___", 7)) { /* mingw 3.7 */
443 strcpy(buffer, symbol + 6);
444 } else {
445 return symbol;
447 return buffer;
450 ST_FN int pe_find_import(TCCState * s1, const char *symbol)
452 char buffer[200];
453 const char *s;
454 int sym_index, n = 0;
455 do {
456 s = n ? get_alt_symbol(buffer, symbol) : symbol;
457 sym_index = find_elf_sym(s1->dynsymtab_section, s);
458 // printf("find %d %s\n", sym_index, s);
459 } while (0 == sym_index && ++n < 2);
460 return sym_index;
463 #if defined _WIN32 || defined __CYGWIN__
465 #ifdef __CYGWIN__
466 # include <dlfcn.h>
467 # define LoadLibrary(s) dlopen(s, RTLD_NOW)
468 # define GetProcAddress(h,s) dlsym(h, s)
469 #else
470 # define dlclose(h) FreeLibrary(h)
471 #endif
473 /* for the -run option: dynamically load symbol from dll */
474 void *resolve_sym(struct TCCState *s1, const char *symbol, int type)
476 char buffer[100];
477 int sym_index, dll_index;
478 void *addr, **m;
479 DLLReference *dllref;
481 sym_index = pe_find_import(s1, symbol);
482 if (0 == sym_index)
483 return NULL;
484 dll_index = ((Elf32_Sym *)s1->dynsymtab_section->data + sym_index)->st_value;
485 dllref = s1->loaded_dlls[dll_index-1];
486 if ( !dllref->handle )
488 dllref->handle = LoadLibrary(dllref->name);
490 addr = GetProcAddress(dllref->handle, symbol);
491 if (NULL == addr)
492 addr = GetProcAddress(dllref->handle, get_alt_symbol(buffer, symbol));
494 if (addr && STT_OBJECT == type) {
495 /* need to return a pointer to the address for data objects */
496 m = (void**)tcc_malloc(sizeof addr), *m = addr, addr = m;
497 #ifdef MEM_DEBUG
498 /* yep, we don't free it */
499 mem_cur_size -= sizeof (void*);
500 #endif
502 return addr;
504 #endif
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 pe_header.opthdr.BaseOfData = addr;
603 break;
605 case sec_bss:
606 break;
608 case sec_reloc:
609 pe_set_datadir(IMAGE_DIRECTORY_ENTRY_BASERELOC, addr, size);
610 break;
612 case sec_rsrc:
613 pe_set_datadir(IMAGE_DIRECTORY_ENTRY_RESOURCE, addr, size);
614 break;
616 case sec_stab:
617 break;
620 if (pe->thunk == pe->s1->sections[si->ord]) {
621 if (pe->imp_size) {
622 pe_set_datadir(IMAGE_DIRECTORY_ENTRY_IMPORT,
623 pe->imp_offs + addr, pe->imp_size);
624 pe_set_datadir(IMAGE_DIRECTORY_ENTRY_IAT,
625 pe->iat_offs + addr, pe->iat_size);
627 if (pe->exp_size) {
628 pe_set_datadir(IMAGE_DIRECTORY_ENTRY_EXPORT,
629 pe->exp_offs + addr, pe->exp_size);
633 strcpy((char*)psh->Name, sh_name);
635 psh->Characteristics = pe_sec_flags[si->cls];
636 psh->VirtualAddress = addr;
637 psh->Misc.VirtualSize = size;
638 pe_header.opthdr.SizeOfImage =
639 umax(pe_virtual_align(size + addr), pe_header.opthdr.SizeOfImage);
641 if (si->data_size) {
642 psh->PointerToRawData = r = file_offset;
643 fwrite(si->data, 1, si->data_size, op);
644 file_offset = pe_file_align(file_offset + si->data_size);
645 psh->SizeOfRawData = file_offset - r;
646 pe_fpad(op, file_offset);
650 // pe_header.filehdr.TimeDateStamp = time(NULL);
651 pe_header.filehdr.NumberOfSections = pe->sec_count;
652 pe_header.opthdr.SizeOfHeaders = pe->sizeofheaders;
653 pe_header.opthdr.ImageBase = pe->imagebase;
654 if (PE_DLL == pe->type)
655 pe_header.filehdr.Characteristics = 0x230E;
656 else if (PE_GUI != pe->type)
657 pe_header.opthdr.Subsystem = 3;
659 fseek(op, SEEK_SET, 0);
660 fwrite(&pe_header, 1, sizeof pe_header, op);
661 for (i = 0; i < pe->sec_count; ++i)
662 fwrite(&pe->sec_info[i].ish, 1, sizeof(IMAGE_SECTION_HEADER), op);
663 fclose (op);
665 if (2 == pe->s1->verbose)
666 printf("-------------------------------\n");
667 if (pe->s1->verbose)
668 printf("<- %s (%lu bytes)\n", pe->filename, file_offset);
670 return 0;
673 /*----------------------------------------------------------------------------*/
675 ST_FN struct import_symbol *pe_add_import(struct pe_info *pe, int sym_index)
677 int i;
678 int dll_index;
679 struct pe_import_info *p;
680 struct import_symbol *s;
682 dll_index = ((Elf32_Sym *)pe->s1->dynsymtab_section->data + sym_index)->st_value;
683 if (0 == dll_index)
684 return NULL;
686 i = dynarray_assoc ((void**)pe->imp_info, pe->imp_count, dll_index);
687 if (-1 != i) {
688 p = pe->imp_info[i];
689 goto found_dll;
691 p = tcc_mallocz(sizeof *p);
692 p->dll_index = dll_index;
693 dynarray_add((void***)&pe->imp_info, &pe->imp_count, p);
695 found_dll:
696 i = dynarray_assoc ((void**)p->symbols, p->sym_count, sym_index);
697 if (-1 != i)
698 return p->symbols[i];
700 s = tcc_mallocz(sizeof *s);
701 dynarray_add((void***)&p->symbols, &p->sym_count, s);
702 s->sym_index = sym_index;
703 return s;
706 /*----------------------------------------------------------------------------*/
707 ST_FN void pe_build_imports(struct pe_info *pe)
709 int thk_ptr, ent_ptr, dll_ptr, sym_cnt, i;
710 DWORD rva_base = pe->thunk->sh_addr - pe->imagebase;
711 int ndlls = pe->imp_count;
713 for (sym_cnt = i = 0; i < ndlls; ++i)
714 sym_cnt += pe->imp_info[i]->sym_count;
716 if (0 == sym_cnt)
717 return;
719 pe_align_section(pe->thunk, 16);
721 pe->imp_offs = dll_ptr = pe->thunk->data_offset;
722 pe->imp_size = (ndlls + 1) * sizeof(struct pe_import_header);
723 pe->iat_offs = dll_ptr + pe->imp_size;
724 pe->iat_size = (sym_cnt + ndlls) * sizeof(DWORD);
725 section_ptr_add(pe->thunk, pe->imp_size + 2*pe->iat_size);
727 thk_ptr = pe->iat_offs;
728 ent_ptr = pe->iat_offs + pe->iat_size;
730 for (i = 0; i < pe->imp_count; ++i) {
731 struct pe_import_header *hdr;
732 int k, n, v;
733 struct pe_import_info *p = pe->imp_info[i];
734 const char *name = pe->s1->loaded_dlls[p->dll_index-1]->name;
736 /* put the dll name into the import header */
737 v = put_elf_str(pe->thunk, name);
739 hdr = (struct pe_import_header*)(pe->thunk->data + dll_ptr);
740 hdr->first_thunk = thk_ptr + rva_base;
741 hdr->first_entry = ent_ptr + rva_base;
742 hdr->lib_name_offset = v + rva_base;
744 for (k = 0, n = p->sym_count; k <= n; ++k) {
745 if (k < n) {
746 DWORD iat_index = p->symbols[k]->iat_index;
747 int sym_index = p->symbols[k]->sym_index;
748 Elf32_Sym *imp_sym = (Elf32_Sym *)pe->s1->dynsymtab_section->data + sym_index;
749 Elf32_Sym *org_sym = (Elf32_Sym *)symtab_section->data + iat_index;
750 const char *name = pe->s1->dynsymtab_section->link->data + imp_sym->st_name;
752 org_sym->st_value = thk_ptr;
753 org_sym->st_shndx = pe->thunk->sh_num;
754 v = pe->thunk->data_offset + rva_base;
755 section_ptr_add(pe->thunk, sizeof(WORD)); /* hint, not used */
756 put_elf_str(pe->thunk, name);
758 } else {
759 v = 0; /* last entry is zero */
761 *(DWORD*)(pe->thunk->data+thk_ptr) =
762 *(DWORD*)(pe->thunk->data+ent_ptr) = v;
763 thk_ptr += sizeof (DWORD);
764 ent_ptr += sizeof (DWORD);
766 dll_ptr += sizeof(struct pe_import_header);
767 dynarray_reset(&p->symbols, &p->sym_count);
769 dynarray_reset(&pe->imp_info, &pe->imp_count);
772 /* ------------------------------------------------------------- */
774 For now only functions are exported. Export of data
775 would work, but import requires compiler support to
776 do an additional indirection.
778 For instance:
779 __declspec(dllimport) extern int something;
781 needs to be translated to:
783 *(int*)something
786 ST_FN int sym_cmp(const void *va, const void *vb)
788 const char *ca = ((const char **)va)[1];
789 const char *cb = ((const char **)vb)[1];
790 return strcmp(ca, cb);
793 ST_FN void pe_build_exports(struct pe_info *pe)
795 Elf32_Sym *sym;
796 int sym_index, sym_end;
797 DWORD rva_base, func_o, name_o, ord_o, str_o;
798 struct pe_export_header *hdr;
799 int sym_count, n, ord, *sorted, *sp;
801 FILE *op;
802 char buf[MAX_PATH];
803 const char *dllname;
804 const char *name;
806 rva_base = pe->thunk->sh_addr - pe->imagebase;
807 sym_count = 0, n = 1, sorted = NULL, op = NULL;
809 sym_end = symtab_section->data_offset / sizeof(Elf32_Sym);
810 for (sym_index = 1; sym_index < sym_end; ++sym_index) {
811 sym = (Elf32_Sym*)symtab_section->data + sym_index;
812 name = symtab_section->link->data + sym->st_name;
813 if ((sym->st_other & 1)
814 /* export only symbols from actually written sections */
815 && pe->s1->sections[sym->st_shndx]->sh_addr) {
816 dynarray_add((void***)&sorted, &sym_count, (void*)n);
817 dynarray_add((void***)&sorted, &sym_count, (void*)name);
819 ++n;
820 #if 0
821 if (sym->st_other & 1)
822 printf("export: %s\n", name);
823 if (sym->st_other & 2)
824 printf("stdcall: %s\n", name);
825 #endif
828 if (0 == sym_count)
829 return;
830 sym_count /= 2;
832 qsort (sorted, sym_count, 2 * sizeof sorted[0], sym_cmp);
833 pe_align_section(pe->thunk, 16);
834 dllname = tcc_basename(pe->filename);
836 pe->exp_offs = pe->thunk->data_offset;
837 func_o = pe->exp_offs + sizeof(struct pe_export_header);
838 name_o = func_o + sym_count * sizeof (DWORD);
839 ord_o = name_o + sym_count * sizeof (DWORD);
840 str_o = ord_o + sym_count * sizeof(WORD);
842 hdr = section_ptr_add(pe->thunk, str_o - pe->exp_offs);
843 hdr->Characteristics = 0;
844 hdr->Base = 1;
845 hdr->NumberOfFunctions = sym_count;
846 hdr->NumberOfNames = sym_count;
847 hdr->AddressOfFunctions = func_o + rva_base;
848 hdr->AddressOfNames = name_o + rva_base;
849 hdr->AddressOfNameOrdinals = ord_o + rva_base;
850 hdr->Name = str_o + rva_base;
851 put_elf_str(pe->thunk, dllname);
853 #if 1
854 /* automatically write exports to <output-filename>.def */
855 strcpy(buf, pe->filename);
856 strcpy(tcc_fileextension(buf), ".def");
857 op = fopen(buf, "w");
858 if (NULL == op) {
859 error_noabort("could not create '%s': %s", buf, strerror(errno));
860 } else {
861 fprintf(op, "LIBRARY %s\n\nEXPORTS\n", dllname);
862 if (pe->s1->verbose)
863 printf("<- %s (%d symbols)\n", buf, sym_count);
865 #endif
867 for (sp = sorted, ord = 0; ord < sym_count; ++ord, sp += 2)
869 sym_index = sp[0], name = (const char *)sp[1];
870 /* insert actual address later in pe_relocate_rva */
871 put_elf_reloc(symtab_section, pe->thunk,
872 func_o, R_386_RELATIVE, sym_index);
873 *(DWORD*)(pe->thunk->data + name_o)
874 = pe->thunk->data_offset + rva_base;
875 *(WORD*)(pe->thunk->data + ord_o)
876 = ord;
877 put_elf_str(pe->thunk, name);
878 func_o += sizeof (DWORD);
879 name_o += sizeof (DWORD);
880 ord_o += sizeof (WORD);
882 if (op)
883 fprintf(op, "%s\n", name);
885 pe->exp_size = pe->thunk->data_offset - pe->exp_offs;
886 tcc_free(sorted);
889 /* ------------------------------------------------------------- */
890 ST_FN void pe_build_reloc (struct pe_info *pe)
892 DWORD offset, block_ptr, addr;
893 int count, i;
894 Elf32_Rel *rel, *rel_end;
895 Section *s = NULL, *sr;
897 offset = addr = block_ptr = count = i = 0;
898 rel = rel_end = NULL;
900 for(;;) {
901 if (rel < rel_end) {
902 int type = ELF32_R_TYPE(rel->r_info);
903 addr = rel->r_offset + s->sh_addr;
904 ++ rel;
905 if (type != R_386_32)
906 continue;
907 if (count == 0) { /* new block */
908 block_ptr = pe->reloc->data_offset;
909 section_ptr_add(pe->reloc, sizeof(struct pe_reloc_header));
910 offset = addr & 0xFFFFFFFF<<12;
912 if ((addr -= offset) < (1<<12)) { /* one block spans 4k addresses */
913 WORD *wp = section_ptr_add(pe->reloc, sizeof (WORD));
914 *wp = addr | IMAGE_REL_BASED_HIGHLOW<<12;
915 ++count;
916 continue;
918 -- rel;
920 } else if (i < pe->sec_count) {
921 sr = (s = pe->s1->sections[pe->sec_info[i++].ord])->reloc;
922 if (sr) {
923 rel = (Elf32_Rel *)sr->data;
924 rel_end = (Elf32_Rel *)(sr->data + sr->data_offset);
926 continue;
929 if (count) {
930 /* store the last block and ready for a new one */
931 struct pe_reloc_header *hdr;
932 if (count & 1) /* align for DWORDS */
933 section_ptr_add(pe->reloc, sizeof(WORD)), ++count;
934 hdr = (struct pe_reloc_header *)(pe->reloc->data + block_ptr);
935 hdr -> offset = offset - pe->imagebase;
936 hdr -> size = count * sizeof(WORD) + sizeof(struct pe_reloc_header);
937 count = 0;
940 if (rel >= rel_end)
941 break;
945 /* ------------------------------------------------------------- */
946 ST_FN int pe_section_class(Section *s)
948 int type, flags;
949 const char *name;
951 type = s->sh_type;
952 flags = s->sh_flags;
953 name = s->name;
954 if (flags & SHF_ALLOC) {
955 if (type == SHT_PROGBITS) {
956 if (flags & SHF_EXECINSTR)
957 return sec_text;
958 if (flags & SHF_WRITE)
959 return sec_data;
960 if (0 == strcmp(name, ".rsrc"))
961 return sec_rsrc;
962 if (0 == strcmp(name, ".iedat"))
963 return sec_idata;
964 return sec_other;
965 } else if (type == SHT_NOBITS) {
966 if (flags & SHF_WRITE)
967 return sec_bss;
969 } else {
970 if (0 == strcmp(name, ".reloc"))
971 return sec_reloc;
972 if (0 == strncmp(name, ".stab", 5)) /* .stab and .stabstr */
973 return sec_stab;
975 return -1;
978 ST_FN int pe_assign_addresses (struct pe_info *pe)
980 int i, k, o, c;
981 DWORD addr;
982 int *section_order;
983 struct section_info *si;
984 Section *s;
986 // pe->thunk = new_section(pe->s1, ".iedat", SHT_PROGBITS, SHF_ALLOC);
988 section_order = tcc_malloc(pe->s1->nb_sections * sizeof (int));
989 for (o = k = 0 ; k < sec_last; ++k) {
990 for (i = 1; i < pe->s1->nb_sections; ++i) {
991 s = pe->s1->sections[i];
992 if (k == pe_section_class(s)) {
993 // printf("%s %d\n", s->name, k);
994 s->sh_addr = pe->imagebase;
995 section_order[o++] = i;
1000 pe->sec_info = tcc_mallocz(o * sizeof (struct section_info));
1001 addr = pe->imagebase + 1;
1003 for (i = 0; i < o; ++i)
1005 k = section_order[i];
1006 s = pe->s1->sections[k];
1007 c = pe_section_class(s);
1008 si = &pe->sec_info[pe->sec_count];
1010 #ifdef PE_MERGE_DATA
1011 if (c == sec_bss && pe->sec_count && si[-1].cls == sec_data) {
1012 /* append .bss to .data */
1013 s->sh_addr = addr = ((addr-1) | 15) + 1;
1014 addr += s->data_offset;
1015 si[-1].sh_size = addr - si[-1].sh_addr;
1016 continue;
1018 #endif
1019 strcpy(si->name, s->name);
1020 si->cls = c;
1021 si->ord = k;
1022 si->sh_addr = s->sh_addr = addr = pe_virtual_align(addr);
1023 si->sh_flags = s->sh_flags;
1025 if (c == sec_data && NULL == pe->thunk)
1026 pe->thunk = s;
1028 if (s == pe->thunk) {
1029 pe_build_imports(pe);
1030 pe_build_exports(pe);
1033 if (c == sec_reloc)
1034 pe_build_reloc (pe);
1036 if (s->data_offset)
1038 if (s->sh_type != SHT_NOBITS) {
1039 si->data = s->data;
1040 si->data_size = s->data_offset;
1043 addr += s->data_offset;
1044 si->sh_size = s->data_offset;
1045 ++pe->sec_count;
1047 // printf("%08x %05x %s\n", si->sh_addr, si->sh_size, si->name);
1050 #if 0
1051 for (i = 1; i < pe->s1->nb_sections; ++i) {
1052 Section *s = pe->s1->sections[i];
1053 int type = s->sh_type;
1054 int flags = s->sh_flags;
1055 printf("section %-16s %-10s %5x %s,%s,%s\n",
1056 s->name,
1057 type == SHT_PROGBITS ? "progbits" :
1058 type == SHT_NOBITS ? "nobits" :
1059 type == SHT_SYMTAB ? "symtab" :
1060 type == SHT_STRTAB ? "strtab" :
1061 type == SHT_REL ? "rel" : "???",
1062 s->data_offset,
1063 flags & SHF_ALLOC ? "alloc" : "",
1064 flags & SHF_WRITE ? "write" : "",
1065 flags & SHF_EXECINSTR ? "exec" : ""
1068 pe->s1->verbose = 2;
1069 #endif
1071 tcc_free(section_order);
1072 return 0;
1075 /* ------------------------------------------------------------- */
1076 ST_FN void pe_relocate_rva (struct pe_info *pe, Section *s)
1078 Section *sr = s->reloc;
1079 Elf32_Rel *rel, *rel_end;
1080 rel_end = (Elf32_Rel *)(sr->data + sr->data_offset);
1081 for(rel = (Elf32_Rel *)sr->data; rel < rel_end; rel++)
1082 if (ELF32_R_TYPE(rel->r_info) == R_386_RELATIVE) {
1083 int sym_index = ELF32_R_SYM(rel->r_info);
1084 DWORD addr = s->sh_addr;
1085 if (sym_index) {
1086 Elf32_Sym *sym = (Elf32_Sym *)symtab_section->data + sym_index;
1087 addr = sym->st_value;
1089 *(DWORD*)(s->data + rel->r_offset) += addr - pe->imagebase;
1093 /*----------------------------------------------------------------------------*/
1094 ST_FN int pe_check_symbols(struct pe_info *pe)
1096 Elf32_Sym *sym;
1097 int sym_index, sym_end;
1098 int ret = 0;
1100 pe_align_section(text_section, 8);
1102 sym_end = symtab_section->data_offset / sizeof(Elf32_Sym);
1103 for (sym_index = 1; sym_index < sym_end; ++sym_index) {
1105 sym = (Elf32_Sym*)symtab_section->data + sym_index;
1106 if (sym->st_shndx == SHN_UNDEF) {
1108 const char *name = symtab_section->link->data + sym->st_name;
1109 unsigned type = ELF32_ST_TYPE(sym->st_info);
1110 int imp_sym = pe_find_import(pe->s1, name);
1111 struct import_symbol *is;
1113 if (0 == imp_sym)
1114 goto not_found;
1115 is = pe_add_import(pe, imp_sym);
1116 if (!is)
1117 goto not_found;
1119 if (type == STT_FUNC) {
1120 unsigned long offset = is->thk_offset;
1121 if (offset) {
1122 /* got aliased symbol, like stricmp and _stricmp */
1124 } else {
1125 char buffer[100];
1127 offset = text_section->data_offset;
1128 /* add the 'jmp IAT[x]' instruction */
1129 *(WORD*)section_ptr_add(text_section, 8) = 0x25FF;
1131 /* add a helper symbol, will be patched later in
1132 pe_build_imports */
1133 sprintf(buffer, "IAT.%s", name);
1134 is->iat_index = put_elf_sym(
1135 symtab_section, 0, sizeof(DWORD),
1136 ELF32_ST_INFO(STB_GLOBAL, STT_OBJECT),
1137 0, SHN_UNDEF, buffer);
1138 put_elf_reloc(symtab_section, text_section,
1139 offset + 2, R_386_32, is->iat_index);
1140 is->thk_offset = offset;
1143 /* tcc_realloc might have altered sym's address */
1144 sym = (Elf32_Sym*)symtab_section->data + sym_index;
1146 /* patch the original symbol */
1147 sym->st_value = offset;
1148 sym->st_shndx = text_section->sh_num;
1149 sym->st_other &= ~1; /* do not export */
1150 continue;
1153 if (type == STT_OBJECT) { /* data, ptr to that should be */
1154 if (0 == is->iat_index) {
1155 /* original symbol will be patched later in pe_build_imports */
1156 is->iat_index = sym_index;
1157 continue;
1161 not_found:
1162 error_noabort("undefined symbol '%s'", name);
1163 ret = 1;
1165 } else if (pe->s1->rdynamic
1166 && ELF32_ST_BIND(sym->st_info) != STB_LOCAL) {
1167 /* if -rdynamic option, then export all non local symbols */
1168 sym->st_other |= 1;
1171 return ret;
1174 /*----------------------------------------------------------------------------*/
1175 #ifdef PE_PRINT_SECTIONS
1176 ST_FN void pe_print_section(FILE * f, Section * s)
1178 /* just if you'r curious */
1179 BYTE *p, *e, b;
1180 int i, n, l, m;
1181 p = s->data;
1182 e = s->data + s->data_offset;
1183 l = e - p;
1185 fprintf(f, "section \"%s\"", s->name);
1186 if (s->link)
1187 fprintf(f, "\nlink \"%s\"", s->link->name);
1188 if (s->reloc)
1189 fprintf(f, "\nreloc \"%s\"", s->reloc->name);
1190 fprintf(f, "\nv_addr %08X", s->sh_addr);
1191 fprintf(f, "\ncontents %08X", l);
1192 fprintf(f, "\n\n");
1194 if (s->sh_type == SHT_NOBITS)
1195 return;
1197 if (0 == l)
1198 return;
1200 if (s->sh_type == SHT_SYMTAB)
1201 m = sizeof(Elf32_Sym);
1202 if (s->sh_type == SHT_REL)
1203 m = sizeof(Elf32_Rel);
1204 else
1205 m = 16;
1207 fprintf(f, "%-8s", "offset");
1208 for (i = 0; i < m; ++i)
1209 fprintf(f, " %02x", i);
1210 n = 56;
1212 if (s->sh_type == SHT_SYMTAB || s->sh_type == SHT_REL) {
1213 const char *fields1[] = {
1214 "name",
1215 "value",
1216 "size",
1217 "bind",
1218 "type",
1219 "other",
1220 "shndx",
1221 NULL
1224 const char *fields2[] = {
1225 "offs",
1226 "type",
1227 "symb",
1228 NULL
1231 const char **p;
1233 if (s->sh_type == SHT_SYMTAB)
1234 p = fields1, n = 106;
1235 else
1236 p = fields2, n = 58;
1238 for (i = 0; p[i]; ++i)
1239 fprintf(f, "%6s", p[i]);
1240 fprintf(f, " symbol");
1243 fprintf(f, "\n");
1244 for (i = 0; i < n; ++i)
1245 fprintf(f, "-");
1246 fprintf(f, "\n");
1248 for (i = 0; i < l;)
1250 fprintf(f, "%08X", i);
1251 for (n = 0; n < m; ++n) {
1252 if (n + i < l)
1253 fprintf(f, " %02X", p[i + n]);
1254 else
1255 fprintf(f, " ");
1258 if (s->sh_type == SHT_SYMTAB) {
1259 Elf32_Sym *sym = (Elf32_Sym *) (p + i);
1260 const char *name = s->link->data + sym->st_name;
1261 fprintf(f, " %04X %04X %04X %02X %02X %02X %04X \"%s\"",
1262 sym->st_name,
1263 sym->st_value,
1264 sym->st_size,
1265 ELF32_ST_BIND(sym->st_info),
1266 ELF32_ST_TYPE(sym->st_info),
1267 sym->st_other, sym->st_shndx, name);
1269 } else if (s->sh_type == SHT_REL) {
1270 Elf32_Rel *rel = (Elf32_Rel *) (p + i);
1271 Elf32_Sym *sym =
1272 (Elf32_Sym *) s->link->data + ELF32_R_SYM(rel->r_info);
1273 const char *name = s->link->link->data + sym->st_name;
1274 fprintf(f, " %04X %02X %04X \"%s\"",
1275 rel->r_offset,
1276 ELF32_R_TYPE(rel->r_info),
1277 ELF32_R_SYM(rel->r_info), name);
1278 } else {
1279 fprintf(f, " ");
1280 for (n = 0; n < m; ++n) {
1281 if (n + i < l) {
1282 b = p[i + n];
1283 if (b < 32 || b >= 127)
1284 b = '.';
1285 fprintf(f, "%c", b);
1289 i += m;
1290 fprintf(f, "\n");
1292 fprintf(f, "\n\n");
1295 ST_FN void pe_print_sections(TCCState *s1, const char *fname)
1297 Section *s;
1298 FILE *f;
1299 int i;
1300 f = fopen(fname, "wt");
1301 for (i = 1; i < s1->nb_sections; ++i) {
1302 s = s1->sections[i];
1303 pe_print_section(f, s);
1305 pe_print_section(f, s1->dynsymtab_section);
1306 fclose(f);
1308 #endif
1310 /* -------------------------------------------------------------
1311 * This is for compiled windows resources in 'coff' format
1312 * as generated by 'windres.exe -O coff ...'.
1315 PUB_FN int pe_test_res_file(void *v, int size)
1317 struct pe_rsrc_header *p = (struct pe_rsrc_header *)v;
1318 return
1319 size >= IMAGE_SIZEOF_FILE_HEADER + IMAGE_SIZEOF_SHORT_NAME /* = 28 */
1320 && p->filehdr.Machine == 0x014C
1321 && 1 == p->filehdr.NumberOfSections
1322 && 0 == strcmp(p->sectionhdr.Name, ".rsrc")
1326 ST_FN int read_n(int fd, void *ptr, unsigned size)
1328 return size == read(fd, ptr, size);
1331 PUB_FN int pe_load_res_file(TCCState *s1, int fd)
1333 struct pe_rsrc_header hdr;
1334 Section *rsrc_section;
1335 int i, ret = -1;
1336 BYTE *ptr;
1338 lseek (fd, 0, SEEK_SET);
1339 if (!read_n(fd, &hdr, sizeof hdr))
1340 goto quit;
1341 if (!pe_test_res_file(&hdr, sizeof hdr))
1342 goto quit;
1344 rsrc_section = new_section(s1, ".rsrc", SHT_PROGBITS, SHF_ALLOC);
1345 ptr = section_ptr_add(rsrc_section, hdr.sectionhdr.SizeOfRawData);
1346 lseek (fd, hdr.sectionhdr.PointerToRawData, SEEK_SET);
1347 if (!read_n(fd, ptr, hdr.sectionhdr.SizeOfRawData))
1348 goto quit;
1350 lseek (fd, hdr.sectionhdr.PointerToRelocations, SEEK_SET);
1351 for (i = 0; i < hdr.sectionhdr.NumberOfRelocations; ++i)
1353 struct pe_rsrc_reloc rel;
1354 if (!read_n(fd, &rel, sizeof rel))
1355 goto quit;
1356 // printf("rsrc_reloc: %x %x %x\n", rel.offset, rel.size, rel.type);
1357 if (rel.type != 7) /* DIR32NB */
1358 goto quit;
1359 put_elf_reloc(symtab_section, rsrc_section,
1360 rel.offset, R_386_RELATIVE, 0);
1362 ret = 0;
1363 quit:
1364 if (ret)
1365 error_noabort("unrecognized resource file format");
1366 return ret;
1369 /* ------------------------------------------------------------- */
1370 ST_FN char *trimfront(char *p)
1372 while (*p && (unsigned char)*p <= ' ')
1373 ++p;
1374 return p;
1377 ST_FN char *trimback(char *a, char *e)
1379 while (e > a && (unsigned char)e[-1] <= ' ')
1380 --e;
1381 *e = 0;;
1382 return a;
1385 ST_FN char *get_line(char *line, int size, FILE *fp)
1387 if (NULL == fgets(line, size, fp))
1388 return NULL;
1389 trimback(line, strchr(line, 0));
1390 return trimfront(line);
1393 /* ------------------------------------------------------------- */
1394 PUB_FN int pe_load_def_file(TCCState *s1, int fd)
1396 DLLReference *dllref;
1397 int state = 0, ret = -1;
1398 char line[400], dllname[80], *p;
1399 FILE *fp = fdopen(dup(fd), "rb");
1401 if (NULL == fp)
1402 goto quit;
1404 for (;;) {
1405 p = get_line(line, sizeof line, fp);
1406 if (NULL == p)
1407 break;
1408 if (0 == *p || ';' == *p)
1409 continue;
1410 switch (state) {
1411 case 0:
1412 if (0 != strnicmp(p, "LIBRARY", 7))
1413 goto quit;
1414 strcpy(dllname, trimfront(p+7));
1415 ++state;
1416 continue;
1418 case 1:
1419 if (0 != stricmp(p, "EXPORTS"))
1420 goto quit;
1421 ++state;
1422 continue;
1424 case 2:
1425 dllref = tcc_mallocz(sizeof(DLLReference) + strlen(dllname));
1426 strcpy(dllref->name, dllname);
1427 dynarray_add((void ***) &s1->loaded_dlls, &s1->nb_loaded_dlls, dllref);
1428 ++state;
1430 default:
1431 add_elf_sym(s1->dynsymtab_section,
1432 s1->nb_loaded_dlls, 0,
1433 ELF32_ST_INFO(STB_GLOBAL, STT_FUNC), 0,
1434 text_section->sh_num, p);
1435 continue;
1438 ret = 0;
1439 quit:
1440 if (fp)
1441 fclose(fp);
1442 if (ret)
1443 error_noabort("unrecognized export definition file format");
1444 return ret;
1447 /* ------------------------------------------------------------- */
1449 ST_FN void pe_add_runtime_ex(TCCState *s1, struct pe_info *pe)
1451 const char *start_symbol;
1452 unsigned long addr = 0;
1453 int pe_type = 0;
1455 if (find_elf_sym(symtab_section, "_WinMain@16"))
1456 pe_type = PE_GUI;
1457 else
1458 if (TCC_OUTPUT_DLL == s1->output_type) {
1459 pe_type = PE_DLL;
1460 /* need this for 'tccelf.c:relocate_section()' */
1461 s1->output_type = TCC_OUTPUT_EXE;
1464 start_symbol =
1465 TCC_OUTPUT_MEMORY == s1->output_type
1466 ? PE_GUI == pe_type ? "_runwinmain" : NULL
1467 : PE_DLL == pe_type ? "__dllstart@12"
1468 : PE_GUI == pe_type ? "_winstart" : "_start"
1471 /* grab the startup code from libtcc1 */
1472 if (start_symbol)
1473 add_elf_sym(symtab_section,
1474 0, 0,
1475 ELF32_ST_INFO(STB_GLOBAL, STT_NOTYPE), 0,
1476 SHN_UNDEF, start_symbol);
1478 if (0 == s1->nostdlib) {
1479 tcc_add_library(s1, "tcc1");
1480 #ifdef __CYGWIN__
1481 tcc_add_library(s1, "cygwin1");
1482 #else
1483 tcc_add_library(s1, "msvcrt");
1484 #endif
1485 tcc_add_library(s1, "kernel32");
1486 if (PE_DLL == pe_type || PE_GUI == pe_type) {
1487 tcc_add_library(s1, "user32");
1488 tcc_add_library(s1, "gdi32");
1492 if (start_symbol) {
1493 addr = (unsigned long)tcc_get_symbol_err(s1, start_symbol);
1494 if (s1->output_type == TCC_OUTPUT_MEMORY && addr)
1495 /* for -run GUI's, put '_runwinmain' instead of 'main' */
1496 add_elf_sym(symtab_section,
1497 addr, 0,
1498 ELF32_ST_INFO(STB_GLOBAL, STT_NOTYPE), 0,
1499 text_section->sh_num, "main");
1502 if (pe) {
1503 pe->type = pe_type;
1504 pe->start_addr = addr;
1508 PUB_FN void pe_add_runtime(TCCState *s1)
1510 pe_add_runtime_ex(s1, NULL);
1513 PUB_FN int pe_output_file(TCCState * s1, const char *filename)
1515 int ret;
1516 struct pe_info pe;
1517 int i;
1519 memset(&pe, 0, sizeof pe);
1520 pe.filename = filename;
1521 pe.s1 = s1;
1523 pe_add_runtime_ex(s1, &pe);
1524 relocate_common_syms(); /* assign bss adresses */
1525 tcc_add_linker_symbols(s1);
1527 ret = pe_check_symbols(&pe);
1528 if (0 == ret) {
1529 if (PE_DLL == pe.type) {
1530 pe.reloc = new_section(pe.s1, ".reloc", SHT_PROGBITS, 0);
1531 pe.imagebase = 0x10000000;
1532 } else {
1533 pe.imagebase = 0x00400000;
1535 pe_assign_addresses(&pe);
1536 relocate_syms(s1, 0);
1537 for (i = 1; i < s1->nb_sections; ++i) {
1538 Section *s = s1->sections[i];
1539 if (s->reloc) {
1540 relocate_section(s1, s);
1541 pe_relocate_rva(&pe, s);
1544 if (s1->nb_errors)
1545 ret = 1;
1546 else
1547 ret = pe_write(&pe);
1548 tcc_free(pe.sec_info);
1551 #ifdef PE_PRINT_SECTIONS
1552 pe_print_sections(s1, "tcc.log");
1553 #endif
1554 return ret;
1557 /* ------------------------------------------------------------- */
1558 #endif /* def TCC_TARGET_PE */
1559 /* ------------------------------------------------------------- */