Cygwin Makefile was to aggresive to remove entire lib/
[tinycc.git] / tccpe.c
blob287eb99ad4bd658faf113cf32a7d46ba936dba56
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 #include "tcc.h"
23 #define PE_MERGE_DATA
24 /* #define PE_PRINT_SECTIONS */
26 #ifndef _WIN32
27 #define stricmp strcasecmp
28 #define strnicmp strncasecmp
29 #endif
31 #ifndef MAX_PATH
32 #define MAX_PATH 260
33 #endif
35 #ifdef TCC_TARGET_X86_64
36 # define ADDR3264 ULONGLONG
37 # define REL_TYPE_DIRECT R_X86_64_64
38 # define R_XXX_THUNKFIX R_X86_64_PC32
39 # define R_XXX_RELATIVE R_X86_64_RELATIVE
40 # define IMAGE_FILE_MACHINE 0x8664
41 # define RSRC_RELTYPE 3
43 #elif defined TCC_TARGET_ARM
44 # define ADDR3264 DWORD
45 # define REL_TYPE_DIRECT R_ARM_ABS32
46 # define R_XXX_THUNKFIX R_ARM_ABS32
47 # define R_XXX_RELATIVE R_ARM_RELATIVE
48 # define IMAGE_FILE_MACHINE 0x01C0
49 # define RSRC_RELTYPE 7 /* ??? (not tested) */
51 #elif defined TCC_TARGET_I386
52 # define ADDR3264 DWORD
53 # define REL_TYPE_DIRECT R_386_32
54 # define R_XXX_THUNKFIX R_386_32
55 # define R_XXX_RELATIVE R_386_RELATIVE
56 # define IMAGE_FILE_MACHINE 0x014C
57 # define RSRC_RELTYPE 7 /* DIR32NB */
59 #endif
61 #if 0
62 #ifdef _WIN32
63 void dbg_printf (const char *fmt, ...)
65 char buffer[4000];
66 va_list arg;
67 int x;
68 va_start(arg, fmt);
69 x = vsprintf (buffer, fmt, arg);
70 strcpy(buffer+x, "\n");
71 OutputDebugString(buffer);
73 #endif
74 #endif
76 /* ----------------------------------------------------------- */
77 #ifndef IMAGE_NT_SIGNATURE
78 /* ----------------------------------------------------------- */
79 /* definitions below are from winnt.h */
81 typedef unsigned char BYTE;
82 typedef unsigned short WORD;
83 typedef unsigned int DWORD;
84 typedef unsigned long long ULONGLONG;
85 #pragma pack(push, 1)
87 typedef struct _IMAGE_DOS_HEADER { /* DOS .EXE header */
88 WORD e_magic; /* Magic number */
89 WORD e_cblp; /* Bytes on last page of file */
90 WORD e_cp; /* Pages in file */
91 WORD e_crlc; /* Relocations */
92 WORD e_cparhdr; /* Size of header in paragraphs */
93 WORD e_minalloc; /* Minimum extra paragraphs needed */
94 WORD e_maxalloc; /* Maximum extra paragraphs needed */
95 WORD e_ss; /* Initial (relative) SS value */
96 WORD e_sp; /* Initial SP value */
97 WORD e_csum; /* Checksum */
98 WORD e_ip; /* Initial IP value */
99 WORD e_cs; /* Initial (relative) CS value */
100 WORD e_lfarlc; /* File address of relocation table */
101 WORD e_ovno; /* Overlay number */
102 WORD e_res[4]; /* Reserved words */
103 WORD e_oemid; /* OEM identifier (for e_oeminfo) */
104 WORD e_oeminfo; /* OEM information; e_oemid specific */
105 WORD e_res2[10]; /* Reserved words */
106 DWORD e_lfanew; /* File address of new exe header */
107 } IMAGE_DOS_HEADER, *PIMAGE_DOS_HEADER;
109 #define IMAGE_NT_SIGNATURE 0x00004550 /* PE00 */
110 #define SIZE_OF_NT_SIGNATURE 4
112 typedef struct _IMAGE_FILE_HEADER {
113 WORD Machine;
114 WORD NumberOfSections;
115 DWORD TimeDateStamp;
116 DWORD PointerToSymbolTable;
117 DWORD NumberOfSymbols;
118 WORD SizeOfOptionalHeader;
119 WORD Characteristics;
120 } IMAGE_FILE_HEADER, *PIMAGE_FILE_HEADER;
123 #define IMAGE_SIZEOF_FILE_HEADER 20
125 typedef struct _IMAGE_DATA_DIRECTORY {
126 DWORD VirtualAddress;
127 DWORD Size;
128 } IMAGE_DATA_DIRECTORY, *PIMAGE_DATA_DIRECTORY;
131 typedef struct _IMAGE_OPTIONAL_HEADER {
132 /* Standard fields. */
133 WORD Magic;
134 BYTE MajorLinkerVersion;
135 BYTE MinorLinkerVersion;
136 DWORD SizeOfCode;
137 DWORD SizeOfInitializedData;
138 DWORD SizeOfUninitializedData;
139 DWORD AddressOfEntryPoint;
140 DWORD BaseOfCode;
141 #ifndef TCC_TARGET_X86_64
142 DWORD BaseOfData;
143 #endif
144 /* NT additional fields. */
145 ADDR3264 ImageBase;
146 DWORD SectionAlignment;
147 DWORD FileAlignment;
148 WORD MajorOperatingSystemVersion;
149 WORD MinorOperatingSystemVersion;
150 WORD MajorImageVersion;
151 WORD MinorImageVersion;
152 WORD MajorSubsystemVersion;
153 WORD MinorSubsystemVersion;
154 DWORD Win32VersionValue;
155 DWORD SizeOfImage;
156 DWORD SizeOfHeaders;
157 DWORD CheckSum;
158 WORD Subsystem;
159 WORD DllCharacteristics;
160 ADDR3264 SizeOfStackReserve;
161 ADDR3264 SizeOfStackCommit;
162 ADDR3264 SizeOfHeapReserve;
163 ADDR3264 SizeOfHeapCommit;
164 DWORD LoaderFlags;
165 DWORD NumberOfRvaAndSizes;
166 IMAGE_DATA_DIRECTORY DataDirectory[16];
167 } IMAGE_OPTIONAL_HEADER32, IMAGE_OPTIONAL_HEADER64, IMAGE_OPTIONAL_HEADER;
169 #define IMAGE_DIRECTORY_ENTRY_EXPORT 0 /* Export Directory */
170 #define IMAGE_DIRECTORY_ENTRY_IMPORT 1 /* Import Directory */
171 #define IMAGE_DIRECTORY_ENTRY_RESOURCE 2 /* Resource Directory */
172 #define IMAGE_DIRECTORY_ENTRY_EXCEPTION 3 /* Exception Directory */
173 #define IMAGE_DIRECTORY_ENTRY_SECURITY 4 /* Security Directory */
174 #define IMAGE_DIRECTORY_ENTRY_BASERELOC 5 /* Base Relocation Table */
175 #define IMAGE_DIRECTORY_ENTRY_DEBUG 6 /* Debug Directory */
176 /* IMAGE_DIRECTORY_ENTRY_COPYRIGHT 7 (X86 usage) */
177 #define IMAGE_DIRECTORY_ENTRY_ARCHITECTURE 7 /* Architecture Specific Data */
178 #define IMAGE_DIRECTORY_ENTRY_GLOBALPTR 8 /* RVA of GP */
179 #define IMAGE_DIRECTORY_ENTRY_TLS 9 /* TLS Directory */
180 #define IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG 10 /* Load Configuration Directory */
181 #define IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT 11 /* Bound Import Directory in headers */
182 #define IMAGE_DIRECTORY_ENTRY_IAT 12 /* Import Address Table */
183 #define IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT 13 /* Delay Load Import Descriptors */
184 #define IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR 14 /* COM Runtime descriptor */
186 /* Section header format. */
187 #define IMAGE_SIZEOF_SHORT_NAME 8
189 typedef struct _IMAGE_SECTION_HEADER {
190 BYTE Name[IMAGE_SIZEOF_SHORT_NAME];
191 union {
192 DWORD PhysicalAddress;
193 DWORD VirtualSize;
194 } Misc;
195 DWORD VirtualAddress;
196 DWORD SizeOfRawData;
197 DWORD PointerToRawData;
198 DWORD PointerToRelocations;
199 DWORD PointerToLinenumbers;
200 WORD NumberOfRelocations;
201 WORD NumberOfLinenumbers;
202 DWORD Characteristics;
203 } IMAGE_SECTION_HEADER, *PIMAGE_SECTION_HEADER;
205 #define IMAGE_SIZEOF_SECTION_HEADER 40
207 typedef struct _IMAGE_EXPORT_DIRECTORY {
208 DWORD Characteristics;
209 DWORD TimeDateStamp;
210 WORD MajorVersion;
211 WORD MinorVersion;
212 DWORD Name;
213 DWORD Base;
214 DWORD NumberOfFunctions;
215 DWORD NumberOfNames;
216 DWORD AddressOfFunctions;
217 DWORD AddressOfNames;
218 DWORD AddressOfNameOrdinals;
219 } IMAGE_EXPORT_DIRECTORY,*PIMAGE_EXPORT_DIRECTORY;
221 typedef struct _IMAGE_IMPORT_DESCRIPTOR {
222 union {
223 DWORD Characteristics;
224 DWORD OriginalFirstThunk;
226 DWORD TimeDateStamp;
227 DWORD ForwarderChain;
228 DWORD Name;
229 DWORD FirstThunk;
230 } IMAGE_IMPORT_DESCRIPTOR;
232 typedef struct _IMAGE_BASE_RELOCATION {
233 DWORD VirtualAddress;
234 DWORD SizeOfBlock;
235 // WORD TypeOffset[1];
236 } IMAGE_BASE_RELOCATION;
238 #define IMAGE_SIZEOF_BASE_RELOCATION 8
240 #define IMAGE_REL_BASED_ABSOLUTE 0
241 #define IMAGE_REL_BASED_HIGH 1
242 #define IMAGE_REL_BASED_LOW 2
243 #define IMAGE_REL_BASED_HIGHLOW 3
244 #define IMAGE_REL_BASED_HIGHADJ 4
245 #define IMAGE_REL_BASED_MIPS_JMPADDR 5
246 #define IMAGE_REL_BASED_SECTION 6
247 #define IMAGE_REL_BASED_REL32 7
249 #pragma pack(pop)
251 /* ----------------------------------------------------------- */
252 #endif /* ndef IMAGE_NT_SIGNATURE */
253 /* ----------------------------------------------------------- */
254 #pragma pack(push, 1)
256 struct pe_header
258 IMAGE_DOS_HEADER doshdr;
259 BYTE dosstub[0x40];
260 DWORD nt_sig;
261 IMAGE_FILE_HEADER filehdr;
262 #ifdef TCC_TARGET_X86_64
263 IMAGE_OPTIONAL_HEADER64 opthdr;
264 #else
265 #ifdef _WIN64
266 IMAGE_OPTIONAL_HEADER32 opthdr;
267 #else
268 IMAGE_OPTIONAL_HEADER opthdr;
269 #endif
270 #endif
273 struct pe_reloc_header {
274 DWORD offset;
275 DWORD size;
278 struct pe_rsrc_header {
279 struct _IMAGE_FILE_HEADER filehdr;
280 struct _IMAGE_SECTION_HEADER sectionhdr;
283 struct pe_rsrc_reloc {
284 DWORD offset;
285 DWORD size;
286 WORD type;
289 #pragma pack(pop)
291 /* ------------------------------------------------------------- */
292 /* internal temporary structures */
295 #define IMAGE_SCN_CNT_CODE 0x00000020
296 #define IMAGE_SCN_CNT_INITIALIZED_DATA 0x00000040
297 #define IMAGE_SCN_CNT_UNINITIALIZED_DATA 0x00000080
298 #define IMAGE_SCN_MEM_DISCARDABLE 0x02000000
299 #define IMAGE_SCN_MEM_SHARED 0x10000000
300 #define IMAGE_SCN_MEM_EXECUTE 0x20000000
301 #define IMAGE_SCN_MEM_READ 0x40000000
302 #define IMAGE_SCN_MEM_WRITE 0x80000000
305 enum {
306 sec_text = 0,
307 sec_data ,
308 sec_bss ,
309 sec_idata ,
310 sec_pdata ,
311 sec_other ,
312 sec_rsrc ,
313 sec_stab ,
314 sec_reloc ,
315 sec_last
318 static const DWORD pe_sec_flags[] = {
319 0x60000020, /* ".text" , */
320 0xC0000040, /* ".data" , */
321 0xC0000080, /* ".bss" , */
322 0x40000040, /* ".idata" , */
323 0x40000040, /* ".pdata" , */
324 0xE0000060, /* < other > , */
325 0x40000040, /* ".rsrc" , */
326 0x42000802, /* ".stab" , */
327 0x42000040, /* ".reloc" , */
330 struct section_info {
331 int cls, ord;
332 char name[32];
333 DWORD sh_addr;
334 DWORD sh_size;
335 DWORD sh_flags;
336 unsigned char *data;
337 DWORD data_size;
338 IMAGE_SECTION_HEADER ish;
341 struct import_symbol {
342 int sym_index;
343 int iat_index;
344 int thk_offset;
347 struct pe_import_info {
348 int dll_index;
349 int sym_count;
350 struct import_symbol **symbols;
353 struct pe_info {
354 TCCState *s1;
355 Section *reloc;
356 Section *thunk;
357 const char *filename;
358 int type;
359 DWORD sizeofheaders;
360 ADDR3264 imagebase;
361 const char *start_symbol;
362 DWORD start_addr;
363 DWORD imp_offs;
364 DWORD imp_size;
365 DWORD iat_offs;
366 DWORD iat_size;
367 DWORD exp_offs;
368 DWORD exp_size;
369 int subsystem;
370 DWORD section_align;
371 DWORD file_align;
372 struct section_info *sec_info;
373 int sec_count;
374 struct pe_import_info **imp_info;
375 int imp_count;
378 #define PE_NUL 0
379 #define PE_DLL 1
380 #define PE_GUI 2
381 #define PE_EXE 3
382 #define PE_RUN 4
384 /* --------------------------------------------*/
386 static const char *pe_export_name(TCCState *s1, ElfW(Sym) *sym)
388 const char *name = symtab_section->link->data + sym->st_name;
389 if (s1->leading_underscore && name[0] == '_' && !(sym->st_other & ST_PE_STDCALL))
390 return name + 1;
391 return name;
394 static int pe_find_import(TCCState * s1, ElfW(Sym) *sym)
396 char buffer[200];
397 const char *s, *p;
398 int sym_index = 0, n = 0;
400 do {
401 s = pe_export_name(s1, sym);
402 if (n) {
403 /* second try: */
404 if (sym->st_other & ST_PE_STDCALL) {
405 /* try w/0 stdcall deco (windows API convention) */
406 p = strrchr(s, '@');
407 if (!p || s[0] != '_')
408 break;
409 strcpy(buffer, s+1)[p-s-1] = 0;
410 } else if (s[0] != '_') { /* try non-ansi function */
411 buffer[0] = '_', strcpy(buffer + 1, s);
412 } else if (0 == memcmp(s, "__imp__", 7)) { /* mingw 2.0 */
413 strcpy(buffer, s + 6);
414 } else if (0 == memcmp(s, "_imp___", 7)) { /* mingw 3.7 */
415 strcpy(buffer, s + 6);
416 } else {
417 break;
419 s = buffer;
421 sym_index = find_elf_sym(s1->dynsymtab_section, s);
422 // printf("find (%d) %d %s\n", n, sym_index, s);
423 } while (0 == sym_index && ++n < 2);
424 return sym_index;
427 /*----------------------------------------------------------------------------*/
429 static int dynarray_assoc(void **pp, int n, int key)
431 int i;
432 for (i = 0; i < n; ++i, ++pp)
433 if (key == **(int **) pp)
434 return i;
435 return -1;
438 #if 0
439 ST_FN DWORD umin(DWORD a, DWORD b)
441 return a < b ? a : b;
443 #endif
445 static DWORD umax(DWORD a, DWORD b)
447 return a < b ? b : a;
450 static DWORD pe_file_align(struct pe_info *pe, DWORD n)
452 return (n + (pe->file_align - 1)) & ~(pe->file_align - 1);
455 static DWORD pe_virtual_align(struct pe_info *pe, DWORD n)
457 return (n + (pe->section_align - 1)) & ~(pe->section_align - 1);
460 static void pe_align_section(Section *s, int a)
462 int i = s->data_offset & (a-1);
463 if (i)
464 section_ptr_add(s, a - i);
467 static void pe_set_datadir(struct pe_header *hdr, int dir, DWORD addr, DWORD size)
469 hdr->opthdr.DataDirectory[dir].VirtualAddress = addr;
470 hdr->opthdr.DataDirectory[dir].Size = size;
473 static int pe_fwrite(void *data, unsigned len, FILE *fp, DWORD *psum)
475 if (psum) {
476 DWORD sum = *psum;
477 WORD *p = data;
478 int i;
479 for (i = len; i > 0; i -= 2) {
480 sum += (i >= 2) ? *p++ : *(BYTE*)p;
481 sum = (sum + (sum >> 16)) & 0xFFFF;
483 *psum = sum;
485 return len == fwrite(data, 1, len, fp) ? 0 : -1;
488 static void pe_fpad(FILE *fp, DWORD new_pos)
490 DWORD pos = ftell(fp);
491 while (++pos <= new_pos)
492 fputc(0, fp);
495 /*----------------------------------------------------------------------------*/
496 static int pe_write(struct pe_info *pe)
498 static const struct pe_header pe_template = {
500 /* IMAGE_DOS_HEADER doshdr */
501 0x5A4D, /*WORD e_magic; Magic number */
502 0x0090, /*WORD e_cblp; Bytes on last page of file */
503 0x0003, /*WORD e_cp; Pages in file */
504 0x0000, /*WORD e_crlc; Relocations */
506 0x0004, /*WORD e_cparhdr; Size of header in paragraphs */
507 0x0000, /*WORD e_minalloc; Minimum extra paragraphs needed */
508 0xFFFF, /*WORD e_maxalloc; Maximum extra paragraphs needed */
509 0x0000, /*WORD e_ss; Initial (relative) SS value */
511 0x00B8, /*WORD e_sp; Initial SP value */
512 0x0000, /*WORD e_csum; Checksum */
513 0x0000, /*WORD e_ip; Initial IP value */
514 0x0000, /*WORD e_cs; Initial (relative) CS value */
515 0x0040, /*WORD e_lfarlc; File address of relocation table */
516 0x0000, /*WORD e_ovno; Overlay number */
517 {0,0,0,0}, /*WORD e_res[4]; Reserved words */
518 0x0000, /*WORD e_oemid; OEM identifier (for e_oeminfo) */
519 0x0000, /*WORD e_oeminfo; OEM information; e_oemid specific */
520 {0,0,0,0,0,0,0,0,0,0}, /*WORD e_res2[10]; Reserved words */
521 0x00000080 /*DWORD e_lfanew; File address of new exe header */
523 /* BYTE dosstub[0x40] */
524 /* 14 code bytes + "This program cannot be run in DOS mode.\r\r\n$" + 6 * 0x00 */
525 0x0e,0x1f,0xba,0x0e,0x00,0xb4,0x09,0xcd,0x21,0xb8,0x01,0x4c,0xcd,0x21,0x54,0x68,
526 0x69,0x73,0x20,0x70,0x72,0x6f,0x67,0x72,0x61,0x6d,0x20,0x63,0x61,0x6e,0x6e,0x6f,
527 0x74,0x20,0x62,0x65,0x20,0x72,0x75,0x6e,0x20,0x69,0x6e,0x20,0x44,0x4f,0x53,0x20,
528 0x6d,0x6f,0x64,0x65,0x2e,0x0d,0x0d,0x0a,0x24,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
530 0x00004550, /* DWORD nt_sig = IMAGE_NT_SIGNATURE */
532 /* IMAGE_FILE_HEADER filehdr */
533 IMAGE_FILE_MACHINE, /*WORD Machine; */
534 0x0003, /*WORD NumberOfSections; */
535 0x00000000, /*DWORD TimeDateStamp; */
536 0x00000000, /*DWORD PointerToSymbolTable; */
537 0x00000000, /*DWORD NumberOfSymbols; */
538 #if defined(TCC_TARGET_X86_64)
539 0x00F0, /*WORD SizeOfOptionalHeader; */
540 0x022F /*WORD Characteristics; */
541 #define CHARACTERISTICS_DLL 0x222E
542 #elif defined(TCC_TARGET_I386)
543 0x00E0, /*WORD SizeOfOptionalHeader; */
544 0x030F /*WORD Characteristics; */
545 #define CHARACTERISTICS_DLL 0x230E
546 #elif defined(TCC_TARGET_ARM)
547 0x00E0, /*WORD SizeOfOptionalHeader; */
548 0x010F, /*WORD Characteristics; */
549 #define CHARACTERISTICS_DLL 0x230F
550 #endif
552 /* IMAGE_OPTIONAL_HEADER opthdr */
553 /* Standard fields. */
554 #ifdef TCC_TARGET_X86_64
555 0x020B, /*WORD Magic; */
556 #else
557 0x010B, /*WORD Magic; */
558 #endif
559 0x06, /*BYTE MajorLinkerVersion; */
560 0x00, /*BYTE MinorLinkerVersion; */
561 0x00000000, /*DWORD SizeOfCode; */
562 0x00000000, /*DWORD SizeOfInitializedData; */
563 0x00000000, /*DWORD SizeOfUninitializedData; */
564 0x00000000, /*DWORD AddressOfEntryPoint; */
565 0x00000000, /*DWORD BaseOfCode; */
566 #ifndef TCC_TARGET_X86_64
567 0x00000000, /*DWORD BaseOfData; */
568 #endif
569 /* NT additional fields. */
570 #if defined(TCC_TARGET_ARM)
571 0x00100000, /*DWORD ImageBase; */
572 #else
573 0x00400000, /*DWORD ImageBase; */
574 #endif
575 0x00001000, /*DWORD SectionAlignment; */
576 0x00000200, /*DWORD FileAlignment; */
577 0x0004, /*WORD MajorOperatingSystemVersion; */
578 0x0000, /*WORD MinorOperatingSystemVersion; */
579 0x0000, /*WORD MajorImageVersion; */
580 0x0000, /*WORD MinorImageVersion; */
581 0x0004, /*WORD MajorSubsystemVersion; */
582 0x0000, /*WORD MinorSubsystemVersion; */
583 0x00000000, /*DWORD Win32VersionValue; */
584 0x00000000, /*DWORD SizeOfImage; */
585 0x00000200, /*DWORD SizeOfHeaders; */
586 0x00000000, /*DWORD CheckSum; */
587 0x0002, /*WORD Subsystem; */
588 0x0000, /*WORD DllCharacteristics; */
589 0x00100000, /*DWORD SizeOfStackReserve; */
590 0x00001000, /*DWORD SizeOfStackCommit; */
591 0x00100000, /*DWORD SizeOfHeapReserve; */
592 0x00001000, /*DWORD SizeOfHeapCommit; */
593 0x00000000, /*DWORD LoaderFlags; */
594 0x00000010, /*DWORD NumberOfRvaAndSizes; */
596 /* IMAGE_DATA_DIRECTORY DataDirectory[16]; */
597 {{0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0},
598 {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}}
601 struct pe_header pe_header = pe_template;
603 int i;
604 FILE *op;
605 DWORD file_offset, sum;
606 struct section_info *si;
607 IMAGE_SECTION_HEADER *psh;
609 op = fopen(pe->filename, "wb");
610 if (NULL == op) {
611 tcc_error_noabort("could not write '%s': %s", pe->filename, strerror(errno));
612 return -1;
615 pe->sizeofheaders = pe_file_align(pe,
616 sizeof (struct pe_header)
617 + pe->sec_count * sizeof (IMAGE_SECTION_HEADER)
620 file_offset = pe->sizeofheaders;
622 if (2 == pe->s1->verbose)
623 printf("-------------------------------"
624 "\n virt file size section" "\n");
625 for (i = 0; i < pe->sec_count; ++i) {
626 DWORD addr, size;
627 const char *sh_name;
629 si = pe->sec_info + i;
630 sh_name = si->name;
631 addr = si->sh_addr - pe->imagebase;
632 size = si->sh_size;
633 psh = &si->ish;
635 if (2 == pe->s1->verbose)
636 printf("%6x %6x %6x %s\n",
637 (unsigned)addr, (unsigned)file_offset, (unsigned)size, sh_name);
639 switch (si->cls) {
640 case sec_text:
641 pe_header.opthdr.BaseOfCode = addr;
642 break;
644 case sec_data:
645 #ifndef TCC_TARGET_X86_64
646 pe_header.opthdr.BaseOfData = addr;
647 #endif
648 break;
650 case sec_bss:
651 break;
653 case sec_reloc:
654 pe_set_datadir(&pe_header, IMAGE_DIRECTORY_ENTRY_BASERELOC, addr, size);
655 break;
657 case sec_rsrc:
658 pe_set_datadir(&pe_header, IMAGE_DIRECTORY_ENTRY_RESOURCE, addr, size);
659 break;
661 case sec_pdata:
662 pe_set_datadir(&pe_header, IMAGE_DIRECTORY_ENTRY_EXCEPTION, addr, size);
663 break;
665 case sec_stab:
666 break;
669 if (pe->thunk == pe->s1->sections[si->ord]) {
670 if (pe->imp_size) {
671 pe_set_datadir(&pe_header, IMAGE_DIRECTORY_ENTRY_IMPORT,
672 pe->imp_offs + addr, pe->imp_size);
673 pe_set_datadir(&pe_header, IMAGE_DIRECTORY_ENTRY_IAT,
674 pe->iat_offs + addr, pe->iat_size);
676 if (pe->exp_size) {
677 pe_set_datadir(&pe_header, IMAGE_DIRECTORY_ENTRY_EXPORT,
678 pe->exp_offs + addr, pe->exp_size);
682 strncpy((char*)psh->Name, sh_name, sizeof psh->Name);
684 psh->Characteristics = pe_sec_flags[si->cls];
685 psh->VirtualAddress = addr;
686 psh->Misc.VirtualSize = size;
687 pe_header.opthdr.SizeOfImage =
688 umax(pe_virtual_align(pe, size + addr), pe_header.opthdr.SizeOfImage);
690 if (si->data_size) {
691 psh->PointerToRawData = file_offset;
692 file_offset = pe_file_align(pe, file_offset + si->data_size);
693 psh->SizeOfRawData = file_offset - psh->PointerToRawData;
694 if (si->cls == sec_text)
695 pe_header.opthdr.SizeOfCode += psh->SizeOfRawData;
696 else
697 pe_header.opthdr.SizeOfInitializedData += psh->SizeOfRawData;
701 //pe_header.filehdr.TimeDateStamp = time(NULL);
702 pe_header.filehdr.NumberOfSections = pe->sec_count;
703 pe_header.opthdr.AddressOfEntryPoint = pe->start_addr;
704 pe_header.opthdr.SizeOfHeaders = pe->sizeofheaders;
705 pe_header.opthdr.ImageBase = pe->imagebase;
706 pe_header.opthdr.Subsystem = pe->subsystem;
707 if (pe->s1->pe_stack_size)
708 pe_header.opthdr.SizeOfStackReserve = pe->s1->pe_stack_size;
709 if (PE_DLL == pe->type)
710 pe_header.filehdr.Characteristics = CHARACTERISTICS_DLL;
711 pe_header.filehdr.Characteristics |= pe->s1->pe_characteristics;
713 sum = 0;
714 pe_fwrite(&pe_header, sizeof pe_header, op, &sum);
715 for (i = 0; i < pe->sec_count; ++i)
716 pe_fwrite(&pe->sec_info[i].ish, sizeof(IMAGE_SECTION_HEADER), op, &sum);
717 pe_fpad(op, pe->sizeofheaders);
718 for (i = 0; i < pe->sec_count; ++i) {
719 si = pe->sec_info + i;
720 psh = &si->ish;
721 if (si->data_size) {
722 pe_fwrite(si->data, si->data_size, op, &sum);
723 file_offset = psh->PointerToRawData + psh->SizeOfRawData;
724 pe_fpad(op, file_offset);
728 pe_header.opthdr.CheckSum = sum + file_offset;
729 fseek(op, offsetof(struct pe_header, opthdr.CheckSum), SEEK_SET);
730 pe_fwrite(&pe_header.opthdr.CheckSum, sizeof pe_header.opthdr.CheckSum, op, NULL);
731 fclose (op);
733 if (2 == pe->s1->verbose)
734 printf("-------------------------------\n");
735 if (pe->s1->verbose)
736 printf("<- %s (%u bytes)\n", pe->filename, (unsigned)file_offset);
738 return 0;
741 /*----------------------------------------------------------------------------*/
743 static struct import_symbol *pe_add_import(struct pe_info *pe, int sym_index)
745 int i;
746 int dll_index;
747 struct pe_import_info *p;
748 struct import_symbol *s;
749 ElfW(Sym) *isym;
751 isym = (ElfW(Sym) *)pe->s1->dynsymtab_section->data + sym_index;
752 dll_index = isym->st_size;
754 i = dynarray_assoc ((void**)pe->imp_info, pe->imp_count, dll_index);
755 if (-1 != i) {
756 p = pe->imp_info[i];
757 goto found_dll;
759 p = tcc_mallocz(sizeof *p);
760 p->dll_index = dll_index;
761 dynarray_add(&pe->imp_info, &pe->imp_count, p);
763 found_dll:
764 i = dynarray_assoc ((void**)p->symbols, p->sym_count, sym_index);
765 if (-1 != i)
766 return p->symbols[i];
768 s = tcc_mallocz(sizeof *s);
769 dynarray_add(&p->symbols, &p->sym_count, s);
770 s->sym_index = sym_index;
771 return s;
774 void pe_free_imports(struct pe_info *pe)
776 int i;
777 for (i = 0; i < pe->imp_count; ++i) {
778 struct pe_import_info *p = pe->imp_info[i];
779 dynarray_reset(&p->symbols, &p->sym_count);
781 dynarray_reset(&pe->imp_info, &pe->imp_count);
784 /*----------------------------------------------------------------------------*/
785 static void pe_build_imports(struct pe_info *pe)
787 int thk_ptr, ent_ptr, dll_ptr, sym_cnt, i;
788 DWORD rva_base = pe->thunk->sh_addr - pe->imagebase;
789 int ndlls = pe->imp_count;
791 for (sym_cnt = i = 0; i < ndlls; ++i)
792 sym_cnt += pe->imp_info[i]->sym_count;
794 if (0 == sym_cnt)
795 return;
797 pe_align_section(pe->thunk, 16);
799 pe->imp_offs = dll_ptr = pe->thunk->data_offset;
800 pe->imp_size = (ndlls + 1) * sizeof(IMAGE_IMPORT_DESCRIPTOR);
801 pe->iat_offs = dll_ptr + pe->imp_size;
802 pe->iat_size = (sym_cnt + ndlls) * sizeof(ADDR3264);
803 section_ptr_add(pe->thunk, pe->imp_size + 2*pe->iat_size);
805 thk_ptr = pe->iat_offs;
806 ent_ptr = pe->iat_offs + pe->iat_size;
808 for (i = 0; i < pe->imp_count; ++i) {
809 IMAGE_IMPORT_DESCRIPTOR *hdr;
810 int k, n, dllindex;
811 ADDR3264 v;
812 struct pe_import_info *p = pe->imp_info[i];
813 const char *name;
814 DLLReference *dllref;
816 dllindex = p->dll_index;
817 if (dllindex)
818 name = (dllref = pe->s1->loaded_dlls[dllindex-1])->name;
819 else
820 name = "", dllref = NULL;
822 /* put the dll name into the import header */
823 v = put_elf_str(pe->thunk, name);
824 hdr = (IMAGE_IMPORT_DESCRIPTOR*)(pe->thunk->data + dll_ptr);
825 hdr->FirstThunk = thk_ptr + rva_base;
826 hdr->OriginalFirstThunk = ent_ptr + rva_base;
827 hdr->Name = v + rva_base;
829 for (k = 0, n = p->sym_count; k <= n; ++k) {
830 if (k < n) {
831 int iat_index = p->symbols[k]->iat_index;
832 int sym_index = p->symbols[k]->sym_index;
833 ElfW(Sym) *imp_sym = (ElfW(Sym) *)pe->s1->dynsymtab_section->data + sym_index;
834 ElfW(Sym) *org_sym = (ElfW(Sym) *)symtab_section->data + iat_index;
835 const char *name = pe->s1->dynsymtab_section->link->data + imp_sym->st_name;
836 int ordinal;
838 org_sym->st_value = thk_ptr;
839 org_sym->st_shndx = pe->thunk->sh_num;
841 if (dllref)
842 v = 0, ordinal = imp_sym->st_value; /* ordinal from pe_load_def */
843 else
844 ordinal = 0, v = imp_sym->st_value; /* address from tcc_add_symbol() */
846 #ifdef TCC_IS_NATIVE
847 if (pe->type == PE_RUN) {
848 if (dllref) {
849 if ( !dllref->handle )
850 dllref->handle = LoadLibrary(dllref->name);
851 v = (ADDR3264)GetProcAddress(dllref->handle, ordinal?(char*)0+ordinal:name);
853 if (!v)
854 tcc_error_noabort("can't build symbol '%s'", name);
855 } else
856 #endif
857 if (ordinal) {
858 v = ordinal | (ADDR3264)1 << (sizeof(ADDR3264)*8 - 1);
859 } else {
860 v = pe->thunk->data_offset + rva_base;
861 section_ptr_add(pe->thunk, sizeof(WORD)); /* hint, not used */
862 put_elf_str(pe->thunk, name);
865 } else {
866 v = 0; /* last entry is zero */
869 *(ADDR3264*)(pe->thunk->data+thk_ptr) =
870 *(ADDR3264*)(pe->thunk->data+ent_ptr) = v;
871 thk_ptr += sizeof (ADDR3264);
872 ent_ptr += sizeof (ADDR3264);
874 dll_ptr += sizeof(IMAGE_IMPORT_DESCRIPTOR);
878 /* ------------------------------------------------------------- */
880 struct pe_sort_sym
882 int index;
883 const char *name;
886 static int sym_cmp(const void *va, const void *vb)
888 const char *ca = (*(struct pe_sort_sym**)va)->name;
889 const char *cb = (*(struct pe_sort_sym**)vb)->name;
890 return strcmp(ca, cb);
893 static void pe_build_exports(struct pe_info *pe)
895 ElfW(Sym) *sym;
896 int sym_index, sym_end;
897 DWORD rva_base, func_o, name_o, ord_o, str_o;
898 IMAGE_EXPORT_DIRECTORY *hdr;
899 int sym_count, ord;
900 struct pe_sort_sym **sorted, *p;
902 FILE *op;
903 char buf[MAX_PATH];
904 const char *dllname;
905 const char *name;
907 rva_base = pe->thunk->sh_addr - pe->imagebase;
908 sym_count = 0, sorted = NULL, op = NULL;
910 sym_end = symtab_section->data_offset / sizeof(ElfW(Sym));
911 for (sym_index = 1; sym_index < sym_end; ++sym_index) {
912 sym = (ElfW(Sym)*)symtab_section->data + sym_index;
913 name = pe_export_name(pe->s1, sym);
914 if ((sym->st_other & ST_PE_EXPORT)
915 /* export only symbols from actually written sections */
916 && pe->s1->sections[sym->st_shndx]->sh_addr) {
917 p = tcc_malloc(sizeof *p);
918 p->index = sym_index;
919 p->name = name;
920 dynarray_add(&sorted, &sym_count, p);
922 #if 0
923 if (sym->st_other & ST_PE_EXPORT)
924 printf("export: %s\n", name);
925 if (sym->st_other & ST_PE_STDCALL)
926 printf("stdcall: %s\n", name);
927 #endif
930 if (0 == sym_count)
931 return;
933 qsort (sorted, sym_count, sizeof *sorted, sym_cmp);
935 pe_align_section(pe->thunk, 16);
936 dllname = tcc_basename(pe->filename);
938 pe->exp_offs = pe->thunk->data_offset;
939 func_o = pe->exp_offs + sizeof(IMAGE_EXPORT_DIRECTORY);
940 name_o = func_o + sym_count * sizeof (DWORD);
941 ord_o = name_o + sym_count * sizeof (DWORD);
942 str_o = ord_o + sym_count * sizeof(WORD);
944 hdr = section_ptr_add(pe->thunk, str_o - pe->exp_offs);
945 hdr->Characteristics = 0;
946 hdr->Base = 1;
947 hdr->NumberOfFunctions = sym_count;
948 hdr->NumberOfNames = sym_count;
949 hdr->AddressOfFunctions = func_o + rva_base;
950 hdr->AddressOfNames = name_o + rva_base;
951 hdr->AddressOfNameOrdinals = ord_o + rva_base;
952 hdr->Name = str_o + rva_base;
953 put_elf_str(pe->thunk, dllname);
955 #if 1
956 /* automatically write exports to <output-filename>.def */
957 pstrcpy(buf, sizeof buf, pe->filename);
958 strcpy(tcc_fileextension(buf), ".def");
959 op = fopen(buf, "w");
960 if (NULL == op) {
961 tcc_error_noabort("could not create '%s': %s", buf, strerror(errno));
962 } else {
963 fprintf(op, "LIBRARY %s\n\nEXPORTS\n", dllname);
964 if (pe->s1->verbose)
965 printf("<- %s (%d symbol%s)\n", buf, sym_count, "s" + (sym_count < 2));
967 #endif
969 for (ord = 0; ord < sym_count; ++ord)
971 p = sorted[ord], sym_index = p->index, name = p->name;
972 /* insert actual address later in pe_relocate_rva */
973 put_elf_reloc(symtab_section, pe->thunk,
974 func_o, R_XXX_RELATIVE, sym_index);
975 *(DWORD*)(pe->thunk->data + name_o)
976 = pe->thunk->data_offset + rva_base;
977 *(WORD*)(pe->thunk->data + ord_o)
978 = ord;
979 put_elf_str(pe->thunk, name);
980 func_o += sizeof (DWORD);
981 name_o += sizeof (DWORD);
982 ord_o += sizeof (WORD);
983 if (op)
984 fprintf(op, "%s\n", name);
986 pe->exp_size = pe->thunk->data_offset - pe->exp_offs;
987 dynarray_reset(&sorted, &sym_count);
988 if (op)
989 fclose(op);
992 /* ------------------------------------------------------------- */
993 static void pe_build_reloc (struct pe_info *pe)
995 DWORD offset, block_ptr, addr;
996 int count, i;
997 ElfW_Rel *rel, *rel_end;
998 Section *s = NULL, *sr;
1000 offset = addr = block_ptr = count = i = 0;
1001 rel = rel_end = NULL;
1003 for(;;) {
1004 if (rel < rel_end) {
1005 int type = ELFW(R_TYPE)(rel->r_info);
1006 addr = rel->r_offset + s->sh_addr;
1007 ++ rel;
1008 if (type != REL_TYPE_DIRECT)
1009 continue;
1010 if (count == 0) { /* new block */
1011 block_ptr = pe->reloc->data_offset;
1012 section_ptr_add(pe->reloc, sizeof(struct pe_reloc_header));
1013 offset = addr & 0xFFFFFFFF<<12;
1015 if ((addr -= offset) < (1<<12)) { /* one block spans 4k addresses */
1016 WORD *wp = section_ptr_add(pe->reloc, sizeof (WORD));
1017 *wp = addr | IMAGE_REL_BASED_HIGHLOW<<12;
1018 ++count;
1019 continue;
1021 -- rel;
1023 } else if (i < pe->sec_count) {
1024 sr = (s = pe->s1->sections[pe->sec_info[i++].ord])->reloc;
1025 if (sr) {
1026 rel = (ElfW_Rel *)sr->data;
1027 rel_end = (ElfW_Rel *)(sr->data + sr->data_offset);
1029 continue;
1032 if (count) {
1033 /* store the last block and ready for a new one */
1034 struct pe_reloc_header *hdr;
1035 if (count & 1) /* align for DWORDS */
1036 section_ptr_add(pe->reloc, sizeof(WORD)), ++count;
1037 hdr = (struct pe_reloc_header *)(pe->reloc->data + block_ptr);
1038 hdr -> offset = offset - pe->imagebase;
1039 hdr -> size = count * sizeof(WORD) + sizeof(struct pe_reloc_header);
1040 count = 0;
1043 if (rel >= rel_end)
1044 break;
1048 /* ------------------------------------------------------------- */
1049 static int pe_section_class(Section *s)
1051 int type, flags;
1052 const char *name;
1054 type = s->sh_type;
1055 flags = s->sh_flags;
1056 name = s->name;
1057 if (flags & SHF_ALLOC) {
1058 if (type == SHT_PROGBITS) {
1059 if (flags & SHF_EXECINSTR)
1060 return sec_text;
1061 if (flags & SHF_WRITE)
1062 return sec_data;
1063 if (0 == strcmp(name, ".rsrc"))
1064 return sec_rsrc;
1065 if (0 == strcmp(name, ".iedat"))
1066 return sec_idata;
1067 if (0 == strcmp(name, ".pdata"))
1068 return sec_pdata;
1069 return sec_other;
1070 } else if (type == SHT_NOBITS) {
1071 if (flags & SHF_WRITE)
1072 return sec_bss;
1074 } else {
1075 if (0 == strcmp(name, ".reloc"))
1076 return sec_reloc;
1077 if (0 == strncmp(name, ".stab", 5)) /* .stab and .stabstr */
1078 return sec_stab;
1080 return -1;
1083 static int pe_assign_addresses (struct pe_info *pe)
1085 int i, k, o, c;
1086 DWORD addr;
1087 int *section_order;
1088 struct section_info *si;
1089 Section *s;
1091 if (PE_DLL == pe->type)
1092 pe->reloc = new_section(pe->s1, ".reloc", SHT_PROGBITS, 0);
1094 // pe->thunk = new_section(pe->s1, ".iedat", SHT_PROGBITS, SHF_ALLOC);
1096 section_order = tcc_malloc(pe->s1->nb_sections * sizeof (int));
1097 for (o = k = 0 ; k < sec_last; ++k) {
1098 for (i = 1; i < pe->s1->nb_sections; ++i) {
1099 s = pe->s1->sections[i];
1100 if (k == pe_section_class(s)) {
1101 // printf("%s %d\n", s->name, k);
1102 s->sh_addr = pe->imagebase;
1103 section_order[o++] = i;
1108 pe->sec_info = tcc_mallocz(o * sizeof (struct section_info));
1109 addr = pe->imagebase + 1;
1111 for (i = 0; i < o; ++i)
1113 k = section_order[i];
1114 s = pe->s1->sections[k];
1115 c = pe_section_class(s);
1116 si = &pe->sec_info[pe->sec_count];
1118 #ifdef PE_MERGE_DATA
1119 if (c == sec_bss && pe->sec_count && si[-1].cls == sec_data) {
1120 /* append .bss to .data */
1121 s->sh_addr = addr = ((addr-1) | (s->sh_addralign-1)) + 1;
1122 addr += s->data_offset;
1123 si[-1].sh_size = addr - si[-1].sh_addr;
1124 continue;
1126 #endif
1127 if (c == sec_stab && 0 == pe->s1->do_debug)
1128 continue;
1130 strcpy(si->name, s->name);
1131 si->cls = c;
1132 si->ord = k;
1133 si->sh_addr = s->sh_addr = addr = pe_virtual_align(pe, addr);
1134 si->sh_flags = s->sh_flags;
1136 if (c == sec_data && NULL == pe->thunk)
1137 pe->thunk = s;
1139 if (s == pe->thunk) {
1140 pe_build_imports(pe);
1141 pe_build_exports(pe);
1144 if (c == sec_reloc)
1145 pe_build_reloc (pe);
1147 if (s->data_offset)
1149 if (s->sh_type != SHT_NOBITS) {
1150 si->data = s->data;
1151 si->data_size = s->data_offset;
1154 addr += s->data_offset;
1155 si->sh_size = s->data_offset;
1156 ++pe->sec_count;
1158 // printf("%08x %05x %s\n", si->sh_addr, si->sh_size, si->name);
1161 #if 0
1162 for (i = 1; i < pe->s1->nb_sections; ++i) {
1163 Section *s = pe->s1->sections[i];
1164 int type = s->sh_type;
1165 int flags = s->sh_flags;
1166 printf("section %-16s %-10s %5x %s,%s,%s\n",
1167 s->name,
1168 type == SHT_PROGBITS ? "progbits" :
1169 type == SHT_NOBITS ? "nobits" :
1170 type == SHT_SYMTAB ? "symtab" :
1171 type == SHT_STRTAB ? "strtab" :
1172 type == SHT_RELX ? "rel" : "???",
1173 s->data_offset,
1174 flags & SHF_ALLOC ? "alloc" : "",
1175 flags & SHF_WRITE ? "write" : "",
1176 flags & SHF_EXECINSTR ? "exec" : ""
1179 pe->s1->verbose = 2;
1180 #endif
1182 tcc_free(section_order);
1183 return 0;
1186 /* ------------------------------------------------------------- */
1187 static void pe_relocate_rva (struct pe_info *pe, Section *s)
1189 Section *sr = s->reloc;
1190 ElfW_Rel *rel, *rel_end;
1191 rel_end = (ElfW_Rel *)(sr->data + sr->data_offset);
1192 for(rel = (ElfW_Rel *)sr->data; rel < rel_end; rel++) {
1193 if (ELFW(R_TYPE)(rel->r_info) == R_XXX_RELATIVE) {
1194 int sym_index = ELFW(R_SYM)(rel->r_info);
1195 DWORD addr = s->sh_addr;
1196 if (sym_index) {
1197 ElfW(Sym) *sym = (ElfW(Sym) *)symtab_section->data + sym_index;
1198 addr = sym->st_value;
1200 // printf("reloc rva %08x %08x %s\n", (DWORD)rel->r_offset, addr, s->name);
1201 *(DWORD*)(s->data + rel->r_offset) += addr - pe->imagebase;
1206 /*----------------------------------------------------------------------------*/
1208 static int pe_isafunc(int sym_index)
1210 Section *sr = text_section->reloc;
1211 ElfW_Rel *rel, *rel_end;
1212 Elf32_Word info = ELF32_R_INFO(sym_index, R_386_PC32);
1213 if (!sr)
1214 return 0;
1215 rel_end = (ElfW_Rel *)(sr->data + sr->data_offset);
1216 for (rel = (ElfW_Rel *)sr->data; rel < rel_end; rel++)
1217 if (rel->r_info == info)
1218 return 1;
1219 return 0;
1222 /*----------------------------------------------------------------------------*/
1223 static int pe_check_symbols(struct pe_info *pe)
1225 ElfW(Sym) *sym;
1226 int sym_index, sym_end;
1227 int ret = 0;
1229 pe_align_section(text_section, 8);
1231 sym_end = symtab_section->data_offset / sizeof(ElfW(Sym));
1232 for (sym_index = 1; sym_index < sym_end; ++sym_index) {
1234 sym = (ElfW(Sym) *)symtab_section->data + sym_index;
1235 if (sym->st_shndx == SHN_UNDEF) {
1237 const char *name = symtab_section->link->data + sym->st_name;
1238 unsigned type = ELFW(ST_TYPE)(sym->st_info);
1239 int imp_sym = pe_find_import(pe->s1, sym);
1240 struct import_symbol *is;
1242 if (0 == imp_sym)
1243 goto not_found;
1245 if (type == STT_NOTYPE) {
1246 /* symbols from assembler have no type, find out which */
1247 if (pe_isafunc(sym_index))
1248 type = STT_FUNC;
1249 else
1250 type = STT_OBJECT;
1253 is = pe_add_import(pe, imp_sym);
1255 if (type == STT_FUNC) {
1256 unsigned long offset = is->thk_offset;
1257 if (offset) {
1258 /* got aliased symbol, like stricmp and _stricmp */
1260 } else {
1261 char buffer[100];
1262 WORD *p;
1264 offset = text_section->data_offset;
1265 /* add the 'jmp IAT[x]' instruction */
1266 #ifdef TCC_TARGET_ARM
1267 p = section_ptr_add(text_section, 8+4); // room for code and address
1268 (*(DWORD*)(p)) = 0xE59FC000; // arm code ldr ip, [pc] ; PC+8+0 = 0001xxxx
1269 (*(DWORD*)(p+2)) = 0xE59CF000; // arm code ldr pc, [ip]
1270 #else
1271 p = section_ptr_add(text_section, 8);
1272 *p = 0x25FF;
1273 #ifdef TCC_TARGET_X86_64
1274 *(DWORD*)(p+1) = (DWORD)-4;
1275 #endif
1276 #endif
1277 /* add a helper symbol, will be patched later in
1278 pe_build_imports */
1279 sprintf(buffer, "IAT.%s", name);
1280 is->iat_index = put_elf_sym(
1281 symtab_section, 0, sizeof(DWORD),
1282 ELFW(ST_INFO)(STB_GLOBAL, STT_OBJECT),
1283 0, SHN_UNDEF, buffer);
1284 #ifdef TCC_TARGET_ARM
1285 put_elf_reloc(symtab_section, text_section,
1286 offset + 8, R_XXX_THUNKFIX, is->iat_index); // offset to IAT position
1287 #else
1288 put_elf_reloc(symtab_section, text_section,
1289 offset + 2, R_XXX_THUNKFIX, is->iat_index);
1290 #endif
1291 is->thk_offset = offset;
1294 /* tcc_realloc might have altered sym's address */
1295 sym = (ElfW(Sym) *)symtab_section->data + sym_index;
1297 /* patch the original symbol */
1298 sym->st_value = offset;
1299 sym->st_shndx = text_section->sh_num;
1300 sym->st_other &= ~ST_PE_EXPORT; /* do not export */
1301 continue;
1304 if (type == STT_OBJECT) { /* data, ptr to that should be */
1305 if (0 == is->iat_index) {
1306 /* original symbol will be patched later in pe_build_imports */
1307 is->iat_index = sym_index;
1308 continue;
1312 not_found:
1313 if (ELFW(ST_BIND)(sym->st_info) == STB_WEAK)
1314 /* STB_WEAK undefined symbols are accepted */
1315 continue;
1316 tcc_error_noabort("undefined symbol '%s'", name);
1317 ret = -1;
1319 } else if (pe->s1->rdynamic
1320 && ELFW(ST_BIND)(sym->st_info) != STB_LOCAL) {
1321 /* if -rdynamic option, then export all non local symbols */
1322 sym->st_other |= ST_PE_EXPORT;
1325 return ret;
1328 /*----------------------------------------------------------------------------*/
1329 #ifdef PE_PRINT_SECTIONS
1330 static void pe_print_section(FILE * f, Section * s)
1332 /* just if you'r curious */
1333 BYTE *p, *e, b;
1334 int i, n, l, m;
1335 p = s->data;
1336 e = s->data + s->data_offset;
1337 l = e - p;
1339 fprintf(f, "section \"%s\"", s->name);
1340 if (s->link)
1341 fprintf(f, "\nlink \"%s\"", s->link->name);
1342 if (s->reloc)
1343 fprintf(f, "\nreloc \"%s\"", s->reloc->name);
1344 fprintf(f, "\nv_addr %08X", (unsigned)s->sh_addr);
1345 fprintf(f, "\ncontents %08X", (unsigned)l);
1346 fprintf(f, "\n\n");
1348 if (s->sh_type == SHT_NOBITS)
1349 return;
1351 if (0 == l)
1352 return;
1354 if (s->sh_type == SHT_SYMTAB)
1355 m = sizeof(ElfW(Sym));
1356 else if (s->sh_type == SHT_RELX)
1357 m = sizeof(ElfW_Rel);
1358 else
1359 m = 16;
1361 fprintf(f, "%-8s", "offset");
1362 for (i = 0; i < m; ++i)
1363 fprintf(f, " %02x", i);
1364 n = 56;
1366 if (s->sh_type == SHT_SYMTAB || s->sh_type == SHT_RELX) {
1367 const char *fields1[] = {
1368 "name",
1369 "value",
1370 "size",
1371 "bind",
1372 "type",
1373 "other",
1374 "shndx",
1375 NULL
1378 const char *fields2[] = {
1379 "offs",
1380 "type",
1381 "symb",
1382 NULL
1385 const char **p;
1387 if (s->sh_type == SHT_SYMTAB)
1388 p = fields1, n = 106;
1389 else
1390 p = fields2, n = 58;
1392 for (i = 0; p[i]; ++i)
1393 fprintf(f, "%6s", p[i]);
1394 fprintf(f, " symbol");
1397 fprintf(f, "\n");
1398 for (i = 0; i < n; ++i)
1399 fprintf(f, "-");
1400 fprintf(f, "\n");
1402 for (i = 0; i < l;)
1404 fprintf(f, "%08X", i);
1405 for (n = 0; n < m; ++n) {
1406 if (n + i < l)
1407 fprintf(f, " %02X", p[i + n]);
1408 else
1409 fprintf(f, " ");
1412 if (s->sh_type == SHT_SYMTAB) {
1413 ElfW(Sym) *sym = (ElfW(Sym) *) (p + i);
1414 const char *name = s->link->data + sym->st_name;
1415 fprintf(f, " %04X %04X %04X %02X %02X %02X %04X \"%s\"",
1416 (unsigned)sym->st_name,
1417 (unsigned)sym->st_value,
1418 (unsigned)sym->st_size,
1419 (unsigned)ELFW(ST_BIND)(sym->st_info),
1420 (unsigned)ELFW(ST_TYPE)(sym->st_info),
1421 (unsigned)sym->st_other,
1422 (unsigned)sym->st_shndx,
1423 name);
1425 } else if (s->sh_type == SHT_RELX) {
1426 ElfW_Rel *rel = (ElfW_Rel *) (p + i);
1427 ElfW(Sym) *sym =
1428 (ElfW(Sym) *) s->link->data + ELFW(R_SYM)(rel->r_info);
1429 const char *name = s->link->link->data + sym->st_name;
1430 fprintf(f, " %04X %02X %04X \"%s\"",
1431 (unsigned)rel->r_offset,
1432 (unsigned)ELFW(R_TYPE)(rel->r_info),
1433 (unsigned)ELFW(R_SYM)(rel->r_info),
1434 name);
1435 } else {
1436 fprintf(f, " ");
1437 for (n = 0; n < m; ++n) {
1438 if (n + i < l) {
1439 b = p[i + n];
1440 if (b < 32 || b >= 127)
1441 b = '.';
1442 fprintf(f, "%c", b);
1446 i += m;
1447 fprintf(f, "\n");
1449 fprintf(f, "\n\n");
1452 static void pe_print_sections(TCCState *s1, const char *fname)
1454 Section *s;
1455 FILE *f;
1456 int i;
1457 f = fopen(fname, "w");
1458 for (i = 1; i < s1->nb_sections; ++i) {
1459 s = s1->sections[i];
1460 pe_print_section(f, s);
1462 pe_print_section(f, s1->dynsymtab_section);
1463 fclose(f);
1465 #endif
1467 /* ------------------------------------------------------------- */
1468 /* helper function for load/store to insert one more indirection */
1470 #ifndef TCC_TARGET_ARM
1471 ST_FUNC SValue *pe_getimport(SValue *sv, SValue *v2)
1473 Sym *sym;
1474 ElfW(Sym) *esym;
1475 int r2;
1477 if ((sv->r & (VT_VALMASK|VT_SYM)) != (VT_CONST|VT_SYM) || (sv->r2 != VT_CONST))
1478 return sv;
1479 sym = sv->sym;
1480 if ((sym->type.t & (VT_EXTERN|VT_STATIC)) != VT_EXTERN)
1481 return sv;
1482 if (!sym->c)
1483 put_extern_sym(sym, NULL, 0, 0);
1484 esym = &((ElfW(Sym) *)symtab_section->data)[sym->c];
1485 if (!(esym->st_other & ST_PE_IMPORT))
1486 return sv;
1488 // printf("import %04x %04x %04x %s\n", sv->type.t, sym->type.t, sv->r, get_tok_str(sv->sym->v, NULL));
1490 memset(v2, 0, sizeof *v2);
1491 v2->type.t = VT_PTR;
1492 v2->r = VT_CONST | VT_SYM | VT_LVAL;
1493 v2->sym = sv->sym;
1495 r2 = get_reg(RC_INT);
1496 load(r2, v2);
1497 v2->r = r2;
1499 if ((uint32_t)sv->c.i) {
1500 vpushv(v2);
1501 vpushi(sv->c.i);
1502 gen_opi('+');
1503 *v2 = *vtop--;
1506 v2->type.t = sv->type.t;
1507 v2->r |= sv->r & VT_LVAL;
1508 return v2;
1510 #endif
1512 ST_FUNC int pe_putimport(TCCState *s1, int dllindex, const char *name, addr_t value)
1514 return set_elf_sym(
1515 s1->dynsymtab_section,
1516 value,
1517 dllindex, /* st_size */
1518 ELFW(ST_INFO)(STB_GLOBAL, STT_NOTYPE),
1520 value ? SHN_ABS : SHN_UNDEF,
1521 name
1525 static int add_dllref(TCCState *s1, const char *dllname)
1527 DLLReference *dllref;
1528 int i;
1529 for (i = 0; i < s1->nb_loaded_dlls; ++i)
1530 if (0 == strcmp(s1->loaded_dlls[i]->name, dllname))
1531 return i + 1;
1532 dllref = tcc_mallocz(sizeof(DLLReference) + strlen(dllname));
1533 strcpy(dllref->name, dllname);
1534 dynarray_add(&s1->loaded_dlls, &s1->nb_loaded_dlls, dllref);
1535 return s1->nb_loaded_dlls;
1538 /* ------------------------------------------------------------- */
1540 static int read_mem(int fd, unsigned offset, void *buffer, unsigned len)
1542 lseek(fd, offset, SEEK_SET);
1543 return len == read(fd, buffer, len);
1546 /* ------------------------------------------------------------- */
1548 PUB_FUNC int tcc_get_dllexports(const char *filename, char **pp)
1550 int l, i, n, n0, ret;
1551 char *p;
1552 int fd;
1554 IMAGE_SECTION_HEADER ish;
1555 IMAGE_EXPORT_DIRECTORY ied;
1556 IMAGE_DOS_HEADER dh;
1557 IMAGE_FILE_HEADER ih;
1558 DWORD sig, ref, addr, ptr, namep;
1559 #ifdef TCC_TARGET_X86_64
1560 IMAGE_OPTIONAL_HEADER64 oh;
1561 #else
1562 IMAGE_OPTIONAL_HEADER32 oh;
1563 #endif
1564 int pef_hdroffset, opt_hdroffset, sec_hdroffset;
1566 n = n0 = 0;
1567 p = NULL;
1568 ret = -1;
1570 fd = open(filename, O_RDONLY | O_BINARY);
1571 if (fd < 0)
1572 goto the_end_1;
1573 ret = 1;
1575 if (!read_mem(fd, 0, &dh, sizeof dh))
1576 goto the_end;
1577 if (!read_mem(fd, dh.e_lfanew, &sig, sizeof sig))
1578 goto the_end;
1579 if (sig != 0x00004550)
1580 goto the_end;
1581 pef_hdroffset = dh.e_lfanew + sizeof sig;
1582 if (!read_mem(fd, pef_hdroffset, &ih, sizeof ih))
1583 goto the_end;
1584 if (IMAGE_FILE_MACHINE != ih.Machine) {
1585 if (ih.Machine == 0x014C)
1586 ret = 32;
1587 else if (ih.Machine == 0x8664)
1588 ret = 64;
1589 goto the_end;
1591 opt_hdroffset = pef_hdroffset + sizeof ih;
1592 sec_hdroffset = opt_hdroffset + sizeof oh;
1593 if (!read_mem(fd, opt_hdroffset, &oh, sizeof oh))
1594 goto the_end;
1596 if (IMAGE_DIRECTORY_ENTRY_EXPORT >= oh.NumberOfRvaAndSizes)
1597 goto the_end_0;
1599 addr = oh.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress;
1600 //printf("addr: %08x\n", addr);
1601 for (i = 0; i < ih.NumberOfSections; ++i) {
1602 if (!read_mem(fd, sec_hdroffset + i * sizeof ish, &ish, sizeof ish))
1603 goto the_end;
1604 //printf("vaddr: %08x\n", ish.VirtualAddress);
1605 if (addr >= ish.VirtualAddress && addr < ish.VirtualAddress + ish.SizeOfRawData)
1606 goto found;
1608 goto the_end_0;
1610 found:
1611 ref = ish.VirtualAddress - ish.PointerToRawData;
1612 if (!read_mem(fd, addr - ref, &ied, sizeof ied))
1613 goto the_end;
1615 namep = ied.AddressOfNames - ref;
1616 for (i = 0; i < ied.NumberOfNames; ++i) {
1617 if (!read_mem(fd, namep, &ptr, sizeof ptr))
1618 goto the_end;
1619 namep += sizeof ptr;
1620 for (l = 0;;) {
1621 if (n+1 >= n0)
1622 p = tcc_realloc(p, n0 = n0 ? n0 * 2 : 256);
1623 if (!read_mem(fd, ptr - ref + l++, p + n, 1)) {
1624 tcc_free(p), p = NULL;
1625 goto the_end;
1627 if (p[n++] == 0)
1628 break;
1631 if (p)
1632 p[n] = 0;
1633 the_end_0:
1634 ret = 0;
1635 the_end:
1636 close(fd);
1637 the_end_1:
1638 *pp = p;
1639 return ret;
1642 /* -------------------------------------------------------------
1643 * This is for compiled windows resources in 'coff' format
1644 * as generated by 'windres.exe -O coff ...'.
1647 static int pe_load_res(TCCState *s1, int fd)
1649 struct pe_rsrc_header hdr;
1650 Section *rsrc_section;
1651 int i, ret = -1;
1652 BYTE *ptr;
1653 unsigned offs;
1655 if (!read_mem(fd, 0, &hdr, sizeof hdr))
1656 goto quit;
1658 if (hdr.filehdr.Machine != IMAGE_FILE_MACHINE
1659 || hdr.filehdr.NumberOfSections != 1
1660 || strcmp(hdr.sectionhdr.Name, ".rsrc") != 0)
1661 goto quit;
1663 rsrc_section = new_section(s1, ".rsrc", SHT_PROGBITS, SHF_ALLOC);
1664 ptr = section_ptr_add(rsrc_section, hdr.sectionhdr.SizeOfRawData);
1665 offs = hdr.sectionhdr.PointerToRawData;
1666 if (!read_mem(fd, offs, ptr, hdr.sectionhdr.SizeOfRawData))
1667 goto quit;
1668 offs = hdr.sectionhdr.PointerToRelocations;
1669 for (i = 0; i < hdr.sectionhdr.NumberOfRelocations; ++i)
1671 struct pe_rsrc_reloc rel;
1672 if (!read_mem(fd, offs, &rel, sizeof rel))
1673 goto quit;
1674 // printf("rsrc_reloc: %x %x %x\n", rel.offset, rel.size, rel.type);
1675 if (rel.type != RSRC_RELTYPE)
1676 goto quit;
1677 put_elf_reloc(symtab_section, rsrc_section,
1678 rel.offset, R_XXX_RELATIVE, 0);
1679 offs += sizeof rel;
1681 ret = 0;
1682 quit:
1683 return ret;
1686 /* ------------------------------------------------------------- */
1688 static char *trimfront(char *p)
1690 while (*p && (unsigned char)*p <= ' ')
1691 ++p;
1692 return p;
1695 static char *trimback(char *a, char *e)
1697 while (e > a && (unsigned char)e[-1] <= ' ')
1698 --e;
1699 *e = 0;;
1700 return a;
1703 /* ------------------------------------------------------------- */
1704 static int pe_load_def(TCCState *s1, int fd)
1706 int state = 0, ret = -1, dllindex = 0, ord;
1707 char line[400], dllname[80], *p, *x;
1708 FILE *fp;
1710 fp = fdopen(dup(fd), "rb");
1711 while (fgets(line, sizeof line, fp))
1713 p = trimfront(trimback(line, strchr(line, 0)));
1714 if (0 == *p || ';' == *p)
1715 continue;
1717 switch (state) {
1718 case 0:
1719 if (0 != strnicmp(p, "LIBRARY", 7))
1720 goto quit;
1721 pstrcpy(dllname, sizeof dllname, trimfront(p+7));
1722 ++state;
1723 continue;
1725 case 1:
1726 if (0 != stricmp(p, "EXPORTS"))
1727 goto quit;
1728 ++state;
1729 continue;
1731 case 2:
1732 dllindex = add_dllref(s1, dllname);
1733 ++state;
1734 /* fall through */
1735 default:
1736 /* get ordinal and will store in sym->st_value */
1737 ord = 0;
1738 x = strchr(p, ' ');
1739 if (x) {
1740 *x = 0, x = strrchr(x + 1, '@');
1741 if (x) {
1742 char *d;
1743 ord = (int)strtol(x + 1, &d, 10);
1744 if (*d)
1745 ord = 0;
1748 pe_putimport(s1, dllindex, p, ord);
1749 continue;
1752 ret = 0;
1753 quit:
1754 fclose(fp);
1755 return ret;
1758 /* ------------------------------------------------------------- */
1759 static int pe_load_dll(TCCState *s1, const char *filename)
1761 char *p, *q;
1762 int index, ret;
1764 ret = tcc_get_dllexports(filename, &p);
1765 if (ret) {
1766 return -1;
1767 } else if (p) {
1768 index = add_dllref(s1, tcc_basename(filename));
1769 for (q = p; *q; q += 1 + strlen(q))
1770 pe_putimport(s1, index, q, 0);
1771 tcc_free(p);
1773 return 0;
1776 /* ------------------------------------------------------------- */
1777 ST_FUNC int pe_load_file(struct TCCState *s1, const char *filename, int fd)
1779 int ret = -1;
1780 char buf[10];
1781 if (0 == strcmp(tcc_fileextension(filename), ".def"))
1782 ret = pe_load_def(s1, fd);
1783 else if (pe_load_res(s1, fd) == 0)
1784 ret = 0;
1785 else if (read_mem(fd, 0, buf, 4) && 0 == memcmp(buf, "MZ\220", 4))
1786 ret = pe_load_dll(s1, filename);
1787 return ret;
1790 /* ------------------------------------------------------------- */
1791 #ifdef TCC_TARGET_X86_64
1792 static unsigned pe_add_uwwind_info(TCCState *s1)
1794 if (NULL == s1->uw_pdata) {
1795 s1->uw_pdata = find_section(tcc_state, ".pdata");
1796 s1->uw_pdata->sh_addralign = 4;
1797 s1->uw_sym = put_elf_sym(symtab_section, 0, 0, 0, 0, text_section->sh_num, NULL);
1800 if (0 == s1->uw_offs) {
1801 /* As our functions all have the same stackframe, we use one entry for all */
1802 static const unsigned char uw_info[] = {
1803 0x01, // UBYTE: 3 Version , UBYTE: 5 Flags
1804 0x04, // UBYTE Size of prolog
1805 0x02, // UBYTE Count of unwind codes
1806 0x05, // UBYTE: 4 Frame Register (rbp), UBYTE: 4 Frame Register offset (scaled)
1807 // USHORT * n Unwind codes array
1808 // 0x0b, 0x01, 0xff, 0xff, // stack size
1809 0x04, 0x03, // set frame ptr (mov rsp -> rbp)
1810 0x01, 0x50 // push reg (rbp)
1813 Section *s = text_section;
1814 unsigned char *p;
1816 section_ptr_add(s, -s->data_offset & 3); /* align */
1817 s1->uw_offs = s->data_offset;
1818 p = section_ptr_add(s, sizeof uw_info);
1819 memcpy(p, uw_info, sizeof uw_info);
1822 return s1->uw_offs;
1825 ST_FUNC void pe_add_unwind_data(unsigned start, unsigned end, unsigned stack)
1827 TCCState *s1 = tcc_state;
1828 Section *pd;
1829 unsigned o, n, d;
1830 struct /* _RUNTIME_FUNCTION */ {
1831 DWORD BeginAddress;
1832 DWORD EndAddress;
1833 DWORD UnwindData;
1834 } *p;
1836 d = pe_add_uwwind_info(s1);
1837 pd = s1->uw_pdata;
1838 o = pd->data_offset;
1839 p = section_ptr_add(pd, sizeof *p);
1841 /* record this function */
1842 p->BeginAddress = start;
1843 p->EndAddress = end;
1844 p->UnwindData = d;
1846 /* put relocations on it */
1847 for (n = o + sizeof *p; o < n; o += sizeof p->BeginAddress)
1848 put_elf_reloc(symtab_section, pd, o, R_X86_64_RELATIVE, s1->uw_sym);
1850 #endif
1851 /* ------------------------------------------------------------- */
1852 #ifdef TCC_TARGET_X86_64
1853 #define PE_STDSYM(n,s) n
1854 #else
1855 #define PE_STDSYM(n,s) "_" n s
1856 #endif
1858 static void pe_add_runtime(TCCState *s1, struct pe_info *pe)
1860 const char *start_symbol;
1861 int pe_type = 0;
1862 int unicode_entry = 0;
1864 if (find_elf_sym(symtab_section, PE_STDSYM("WinMain","@16")))
1865 pe_type = PE_GUI;
1866 else
1867 if (find_elf_sym(symtab_section, PE_STDSYM("wWinMain","@16"))) {
1868 pe_type = PE_GUI;
1869 unicode_entry = PE_GUI;
1871 else
1872 if (TCC_OUTPUT_DLL == s1->output_type) {
1873 pe_type = PE_DLL;
1874 /* need this for 'tccelf.c:relocate_section()' */
1875 s1->output_type = TCC_OUTPUT_EXE;
1877 else {
1878 pe_type = PE_EXE;
1879 if (find_elf_sym(symtab_section, "wmain"))
1880 unicode_entry = PE_EXE;
1883 start_symbol =
1884 TCC_OUTPUT_MEMORY == s1->output_type
1885 ? PE_GUI == pe_type ? (unicode_entry ? "__runwwinmain" : "__runwinmain")
1886 : (unicode_entry ? "__runwmain" : "__runmain")
1887 : PE_DLL == pe_type ? PE_STDSYM("__dllstart","@12")
1888 : PE_GUI == pe_type ? (unicode_entry ? "__wwinstart": "__winstart")
1889 : (unicode_entry ? "__wstart" : "__start")
1892 if (!s1->leading_underscore || strchr(start_symbol, '@'))
1893 ++start_symbol;
1895 /* grab the startup code from libtcc1 */
1896 #ifdef TCC_IS_NATIVE
1897 if (TCC_OUTPUT_MEMORY != s1->output_type || s1->runtime_main)
1898 #endif
1899 set_elf_sym(symtab_section,
1900 0, 0,
1901 ELFW(ST_INFO)(STB_GLOBAL, STT_NOTYPE), 0,
1902 SHN_UNDEF, start_symbol);
1904 tcc_add_pragma_libs(s1);
1906 if (0 == s1->nostdlib) {
1907 static const char *libs[] = {
1908 TCC_LIBTCC1, "msvcrt", "kernel32", "", "user32", "gdi32", NULL
1910 const char **pp, *p;
1911 for (pp = libs; 0 != (p = *pp); ++pp) {
1912 if (0 == *p) {
1913 if (PE_DLL != pe_type && PE_GUI != pe_type)
1914 break;
1915 } else if (pp == libs && tcc_add_dll(s1, p, 0) >= 0) {
1916 continue;
1917 } else {
1918 tcc_add_library_err(s1, p);
1923 if (TCC_OUTPUT_MEMORY == s1->output_type)
1924 pe_type = PE_RUN;
1925 pe->type = pe_type;
1926 pe->start_symbol = start_symbol;
1929 static void pe_set_options(TCCState * s1, struct pe_info *pe)
1931 if (PE_DLL == pe->type) {
1932 /* XXX: check if is correct for arm-pe target */
1933 pe->imagebase = 0x10000000;
1934 } else {
1935 #if defined(TCC_TARGET_ARM)
1936 pe->imagebase = 0x00010000;
1937 #else
1938 pe->imagebase = 0x00400000;
1939 #endif
1942 #if defined(TCC_TARGET_ARM)
1943 /* we use "console" subsystem by default */
1944 pe->subsystem = 9;
1945 #else
1946 if (PE_DLL == pe->type || PE_GUI == pe->type)
1947 pe->subsystem = 2;
1948 else
1949 pe->subsystem = 3;
1950 #endif
1951 /* Allow override via -Wl,-subsystem=... option */
1952 if (s1->pe_subsystem != 0)
1953 pe->subsystem = s1->pe_subsystem;
1955 /* set default file/section alignment */
1956 if (pe->subsystem == 1) {
1957 pe->section_align = 0x20;
1958 pe->file_align = 0x20;
1959 } else {
1960 pe->section_align = 0x1000;
1961 pe->file_align = 0x200;
1964 if (s1->section_align != 0)
1965 pe->section_align = s1->section_align;
1966 if (s1->pe_file_align != 0)
1967 pe->file_align = s1->pe_file_align;
1969 if ((pe->subsystem >= 10) && (pe->subsystem <= 12))
1970 pe->imagebase = 0;
1972 if (s1->has_text_addr)
1973 pe->imagebase = s1->text_addr;
1976 ST_FUNC int pe_output_file(TCCState *s1, const char *filename)
1978 int ret;
1979 struct pe_info pe;
1980 int i;
1982 memset(&pe, 0, sizeof pe);
1983 pe.filename = filename;
1984 pe.s1 = s1;
1986 tcc_add_bcheck(s1);
1987 pe_add_runtime(s1, &pe);
1988 relocate_common_syms(); /* assign bss adresses */
1989 tcc_add_linker_symbols(s1);
1990 pe_set_options(s1, &pe);
1992 ret = pe_check_symbols(&pe);
1993 if (ret)
1995 else if (filename) {
1996 pe_assign_addresses(&pe);
1997 relocate_syms(s1, s1->symtab, 0);
1998 for (i = 1; i < s1->nb_sections; ++i) {
1999 Section *s = s1->sections[i];
2000 if (s->reloc) {
2001 relocate_section(s1, s);
2002 pe_relocate_rva(&pe, s);
2005 pe.start_addr = (DWORD)
2006 ((uintptr_t)tcc_get_symbol_err(s1, pe.start_symbol)
2007 - pe.imagebase);
2008 if (s1->nb_errors)
2009 ret = -1;
2010 else
2011 ret = pe_write(&pe);
2012 tcc_free(pe.sec_info);
2013 } else {
2014 #ifdef TCC_IS_NATIVE
2015 pe.thunk = data_section;
2016 pe_build_imports(&pe);
2017 s1->runtime_main = pe.start_symbol;
2018 #endif
2021 pe_free_imports(&pe);
2023 #ifdef PE_PRINT_SECTIONS
2024 pe_print_sections(s1, "tcc.log");
2025 #endif
2026 return ret;
2029 /* ------------------------------------------------------------- */