riscv: asm: implement `j offset`
[tinycc.git] / tccpe.c
blob60a8efcfd50a7ebcde5d75d24cbd9c88baf9eda5
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 1
24 #define PE_PRINT_SECTIONS 0
26 #ifndef _WIN32
27 #define stricmp strcasecmp
28 #define strnicmp strncasecmp
29 #include <sys/stat.h> /* chmod() */
30 #endif
32 #ifdef TCC_TARGET_X86_64
33 # define ADDR3264 ULONGLONG
34 # define PE_IMAGE_REL IMAGE_REL_BASED_DIR64
35 # define REL_TYPE_DIRECT R_X86_64_64
36 # define R_XXX_THUNKFIX R_X86_64_PC32
37 # define R_XXX_RELATIVE R_X86_64_RELATIVE
38 # define R_XXX_FUNCCALL R_X86_64_PLT32
39 # define IMAGE_FILE_MACHINE 0x8664
40 # define RSRC_RELTYPE 3
42 #elif defined TCC_TARGET_ARM
43 # define ADDR3264 DWORD
44 # define PE_IMAGE_REL IMAGE_REL_BASED_HIGHLOW
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 R_XXX_FUNCCALL R_ARM_PC24
49 # define R_XXX_FUNCCALL2 R_ARM_ABS32
50 # define IMAGE_FILE_MACHINE 0x01C0
51 # define RSRC_RELTYPE 7 /* ??? (not tested) */
53 #elif defined TCC_TARGET_I386
54 # define ADDR3264 DWORD
55 # define PE_IMAGE_REL IMAGE_REL_BASED_HIGHLOW
56 # define REL_TYPE_DIRECT R_386_32
57 # define R_XXX_THUNKFIX R_386_32
58 # define R_XXX_RELATIVE R_386_RELATIVE
59 # define R_XXX_FUNCCALL R_386_PC32
60 # define IMAGE_FILE_MACHINE 0x014C
61 # define RSRC_RELTYPE 7 /* DIR32NB */
63 #endif
65 #ifndef IMAGE_NT_SIGNATURE
66 /* ----------------------------------------------------------- */
67 /* definitions below are from winnt.h */
69 typedef unsigned char BYTE;
70 typedef unsigned short WORD;
71 typedef unsigned int DWORD;
72 typedef unsigned long long ULONGLONG;
73 #pragma pack(push, 1)
75 typedef struct _IMAGE_DOS_HEADER { /* DOS .EXE header */
76 WORD e_magic; /* Magic number */
77 WORD e_cblp; /* Bytes on last page of file */
78 WORD e_cp; /* Pages in file */
79 WORD e_crlc; /* Relocations */
80 WORD e_cparhdr; /* Size of header in paragraphs */
81 WORD e_minalloc; /* Minimum extra paragraphs needed */
82 WORD e_maxalloc; /* Maximum extra paragraphs needed */
83 WORD e_ss; /* Initial (relative) SS value */
84 WORD e_sp; /* Initial SP value */
85 WORD e_csum; /* Checksum */
86 WORD e_ip; /* Initial IP value */
87 WORD e_cs; /* Initial (relative) CS value */
88 WORD e_lfarlc; /* File address of relocation table */
89 WORD e_ovno; /* Overlay number */
90 WORD e_res[4]; /* Reserved words */
91 WORD e_oemid; /* OEM identifier (for e_oeminfo) */
92 WORD e_oeminfo; /* OEM information; e_oemid specific */
93 WORD e_res2[10]; /* Reserved words */
94 DWORD e_lfanew; /* File address of new exe header */
95 } IMAGE_DOS_HEADER, *PIMAGE_DOS_HEADER;
97 #define IMAGE_NT_SIGNATURE 0x00004550 /* PE00 */
98 #define SIZE_OF_NT_SIGNATURE 4
100 typedef struct _IMAGE_FILE_HEADER {
101 WORD Machine;
102 WORD NumberOfSections;
103 DWORD TimeDateStamp;
104 DWORD PointerToSymbolTable;
105 DWORD NumberOfSymbols;
106 WORD SizeOfOptionalHeader;
107 WORD Characteristics;
108 } IMAGE_FILE_HEADER, *PIMAGE_FILE_HEADER;
111 #define IMAGE_SIZEOF_FILE_HEADER 20
113 typedef struct _IMAGE_DATA_DIRECTORY {
114 DWORD VirtualAddress;
115 DWORD Size;
116 } IMAGE_DATA_DIRECTORY, *PIMAGE_DATA_DIRECTORY;
119 typedef struct _IMAGE_OPTIONAL_HEADER {
120 /* Standard fields. */
121 WORD Magic;
122 BYTE MajorLinkerVersion;
123 BYTE MinorLinkerVersion;
124 DWORD SizeOfCode;
125 DWORD SizeOfInitializedData;
126 DWORD SizeOfUninitializedData;
127 DWORD AddressOfEntryPoint;
128 DWORD BaseOfCode;
129 #ifndef TCC_TARGET_X86_64
130 DWORD BaseOfData;
131 #endif
132 /* NT additional fields. */
133 ADDR3264 ImageBase;
134 DWORD SectionAlignment;
135 DWORD FileAlignment;
136 WORD MajorOperatingSystemVersion;
137 WORD MinorOperatingSystemVersion;
138 WORD MajorImageVersion;
139 WORD MinorImageVersion;
140 WORD MajorSubsystemVersion;
141 WORD MinorSubsystemVersion;
142 DWORD Win32VersionValue;
143 DWORD SizeOfImage;
144 DWORD SizeOfHeaders;
145 DWORD CheckSum;
146 WORD Subsystem;
147 WORD DllCharacteristics;
148 ADDR3264 SizeOfStackReserve;
149 ADDR3264 SizeOfStackCommit;
150 ADDR3264 SizeOfHeapReserve;
151 ADDR3264 SizeOfHeapCommit;
152 DWORD LoaderFlags;
153 DWORD NumberOfRvaAndSizes;
154 IMAGE_DATA_DIRECTORY DataDirectory[16];
155 } IMAGE_OPTIONAL_HEADER32, IMAGE_OPTIONAL_HEADER64, IMAGE_OPTIONAL_HEADER;
157 #define IMAGE_DIRECTORY_ENTRY_EXPORT 0 /* Export Directory */
158 #define IMAGE_DIRECTORY_ENTRY_IMPORT 1 /* Import Directory */
159 #define IMAGE_DIRECTORY_ENTRY_RESOURCE 2 /* Resource Directory */
160 #define IMAGE_DIRECTORY_ENTRY_EXCEPTION 3 /* Exception Directory */
161 #define IMAGE_DIRECTORY_ENTRY_SECURITY 4 /* Security Directory */
162 #define IMAGE_DIRECTORY_ENTRY_BASERELOC 5 /* Base Relocation Table */
163 #define IMAGE_DIRECTORY_ENTRY_DEBUG 6 /* Debug Directory */
164 /* IMAGE_DIRECTORY_ENTRY_COPYRIGHT 7 (X86 usage) */
165 #define IMAGE_DIRECTORY_ENTRY_ARCHITECTURE 7 /* Architecture Specific Data */
166 #define IMAGE_DIRECTORY_ENTRY_GLOBALPTR 8 /* RVA of GP */
167 #define IMAGE_DIRECTORY_ENTRY_TLS 9 /* TLS Directory */
168 #define IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG 10 /* Load Configuration Directory */
169 #define IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT 11 /* Bound Import Directory in headers */
170 #define IMAGE_DIRECTORY_ENTRY_IAT 12 /* Import Address Table */
171 #define IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT 13 /* Delay Load Import Descriptors */
172 #define IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR 14 /* COM Runtime descriptor */
174 /* Section header format. */
175 #define IMAGE_SIZEOF_SHORT_NAME 8
177 typedef struct _IMAGE_SECTION_HEADER {
178 BYTE Name[IMAGE_SIZEOF_SHORT_NAME];
179 union {
180 DWORD PhysicalAddress;
181 DWORD VirtualSize;
182 } Misc;
183 DWORD VirtualAddress;
184 DWORD SizeOfRawData;
185 DWORD PointerToRawData;
186 DWORD PointerToRelocations;
187 DWORD PointerToLinenumbers;
188 WORD NumberOfRelocations;
189 WORD NumberOfLinenumbers;
190 DWORD Characteristics;
191 } IMAGE_SECTION_HEADER, *PIMAGE_SECTION_HEADER;
193 #define IMAGE_SIZEOF_SECTION_HEADER 40
195 typedef struct _IMAGE_EXPORT_DIRECTORY {
196 DWORD Characteristics;
197 DWORD TimeDateStamp;
198 WORD MajorVersion;
199 WORD MinorVersion;
200 DWORD Name;
201 DWORD Base;
202 DWORD NumberOfFunctions;
203 DWORD NumberOfNames;
204 DWORD AddressOfFunctions;
205 DWORD AddressOfNames;
206 DWORD AddressOfNameOrdinals;
207 } IMAGE_EXPORT_DIRECTORY,*PIMAGE_EXPORT_DIRECTORY;
209 typedef struct _IMAGE_IMPORT_DESCRIPTOR {
210 union {
211 DWORD Characteristics;
212 DWORD OriginalFirstThunk;
214 DWORD TimeDateStamp;
215 DWORD ForwarderChain;
216 DWORD Name;
217 DWORD FirstThunk;
218 } IMAGE_IMPORT_DESCRIPTOR;
220 typedef struct _IMAGE_BASE_RELOCATION {
221 DWORD VirtualAddress;
222 DWORD SizeOfBlock;
223 // WORD TypeOffset[1];
224 } IMAGE_BASE_RELOCATION;
226 #define IMAGE_SIZEOF_BASE_RELOCATION 8
228 #define IMAGE_REL_BASED_ABSOLUTE 0
229 #define IMAGE_REL_BASED_HIGH 1
230 #define IMAGE_REL_BASED_LOW 2
231 #define IMAGE_REL_BASED_HIGHLOW 3
232 #define IMAGE_REL_BASED_HIGHADJ 4
233 #define IMAGE_REL_BASED_MIPS_JMPADDR 5
234 #define IMAGE_REL_BASED_SECTION 6
235 #define IMAGE_REL_BASED_REL32 7
236 #define IMAGE_REL_BASED_DIR64 10
238 #define IMAGE_SCN_CNT_CODE 0x00000020
239 #define IMAGE_SCN_CNT_INITIALIZED_DATA 0x00000040
240 #define IMAGE_SCN_CNT_UNINITIALIZED_DATA 0x00000080
241 #define IMAGE_SCN_MEM_DISCARDABLE 0x02000000
242 #define IMAGE_SCN_MEM_SHARED 0x10000000
243 #define IMAGE_SCN_MEM_EXECUTE 0x20000000
244 #define IMAGE_SCN_MEM_READ 0x40000000
245 #define IMAGE_SCN_MEM_WRITE 0x80000000
247 #pragma pack(pop)
249 /* ----------------------------------------------------------- */
250 #endif /* ndef IMAGE_NT_SIGNATURE */
251 /* ----------------------------------------------------------- */
253 #ifndef IMAGE_REL_BASED_DIR64
254 # define IMAGE_REL_BASED_DIR64 10
255 #endif
257 #pragma pack(push, 1)
258 struct pe_header
260 IMAGE_DOS_HEADER doshdr;
261 BYTE dosstub[0x40];
262 DWORD nt_sig;
263 IMAGE_FILE_HEADER filehdr;
264 #ifdef TCC_TARGET_X86_64
265 IMAGE_OPTIONAL_HEADER64 opthdr;
266 #else
267 #ifdef _WIN64
268 IMAGE_OPTIONAL_HEADER32 opthdr;
269 #else
270 IMAGE_OPTIONAL_HEADER opthdr;
271 #endif
272 #endif
275 struct pe_reloc_header {
276 DWORD offset;
277 DWORD size;
280 struct pe_rsrc_header {
281 struct _IMAGE_FILE_HEADER filehdr;
282 struct _IMAGE_SECTION_HEADER sectionhdr;
285 struct pe_rsrc_reloc {
286 DWORD offset;
287 DWORD size;
288 WORD type;
290 #pragma pack(pop)
292 /* ------------------------------------------------------------- */
293 /* internal temporary structures */
295 enum {
296 sec_text = 0,
297 sec_rdata ,
298 sec_data ,
299 sec_bss ,
300 sec_idata ,
301 sec_pdata ,
302 sec_other ,
303 sec_rsrc ,
304 sec_debug ,
305 sec_reloc ,
306 sec_last
309 #if 0
310 static const DWORD pe_sec_flags[] = {
311 0x60000020, /* ".text" , */
312 0xC0000040, /* ".data" , */
313 0xC0000080, /* ".bss" , */
314 0x40000040, /* ".idata" , */
315 0x40000040, /* ".pdata" , */
316 0xE0000060, /* < other > , */
317 0x40000040, /* ".rsrc" , */
318 0x42000802, /* ".stab" , */
319 0x42000040, /* ".reloc" , */
321 #endif
323 struct section_info {
324 int cls;
325 char name[32];
326 ADDR3264 sh_addr;
327 DWORD sh_size;
328 DWORD pe_flags;
329 Section *sec;
330 DWORD data_size;
331 IMAGE_SECTION_HEADER ish;
334 struct import_symbol {
335 int sym_index;
336 int iat_index;
337 int thk_offset;
340 struct pe_import_info {
341 int dll_index;
342 int sym_count;
343 struct import_symbol **symbols;
346 struct pe_info {
347 TCCState *s1;
348 Section *reloc;
349 Section *thunk;
350 const char *filename;
351 int type;
352 DWORD sizeofheaders;
353 ADDR3264 imagebase;
354 const char *start_symbol;
355 DWORD start_addr;
356 DWORD imp_offs;
357 DWORD imp_size;
358 DWORD iat_offs;
359 DWORD iat_size;
360 DWORD exp_offs;
361 DWORD exp_size;
362 int subsystem;
363 DWORD section_align;
364 DWORD file_align;
365 struct section_info **sec_info;
366 int sec_count;
367 struct pe_import_info **imp_info;
368 int imp_count;
371 #define PE_NUL 0
372 #define PE_DLL 1
373 #define PE_GUI 2
374 #define PE_EXE 3
375 #define PE_RUN 4
377 /* --------------------------------------------*/
379 static const char *pe_export_name(TCCState *s1, ElfW(Sym) *sym)
381 const char *name = (char*)symtab_section->link->data + sym->st_name;
382 if (s1->leading_underscore && name[0] == '_' && !(sym->st_other & ST_PE_STDCALL))
383 return name + 1;
384 return name;
387 static int pe_find_import(TCCState * s1, ElfW(Sym) *sym)
389 char buffer[200];
390 const char *s, *p;
391 int sym_index = 0, n = 0;
392 int a, err = 0;
394 do {
395 s = pe_export_name(s1, sym);
396 a = 0;
397 if (n) {
398 /* second try: */
399 if (sym->st_other & ST_PE_STDCALL) {
400 /* try w/0 stdcall deco (windows API convention) */
401 p = strrchr(s, '@');
402 if (!p || s[0] != '_')
403 break;
404 strcpy(buffer, s+1)[p-s-1] = 0;
405 } else if (s[0] != '_') { /* try non-ansi function */
406 buffer[0] = '_', strcpy(buffer + 1, s);
407 } else if (0 == memcmp(s, "__imp_", 6)) { /* mingw 2.0 */
408 strcpy(buffer, s + 6), a = 1;
409 } else if (0 == memcmp(s, "_imp__", 6)) { /* mingw 3.7 */
410 strcpy(buffer, s + 6), a = 1;
411 } else {
412 continue;
414 s = buffer;
416 sym_index = find_elf_sym(s1->dynsymtab_section, s);
417 // printf("find (%d) %d %s\n", n, sym_index, s);
418 if (sym_index
419 && ELFW(ST_TYPE)(sym->st_info) == STT_OBJECT
420 && 0 == (sym->st_other & ST_PE_IMPORT)
421 && 0 == a
422 ) err = -1, sym_index = 0;
423 } while (0 == sym_index && ++n < 2);
424 return n == 2 ? err : 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 static DWORD umin(DWORD a, DWORD b)
440 return a < b ? a : b;
443 static DWORD umax(DWORD a, DWORD b)
445 return a < b ? b : a;
448 static DWORD pe_file_align(struct pe_info *pe, DWORD n)
450 return (n + (pe->file_align - 1)) & ~(pe->file_align - 1);
453 static ADDR3264 pe_virtual_align(struct pe_info *pe, ADDR3264 n)
455 return (n + (pe->section_align - 1)) & ~(ADDR3264)(pe->section_align - 1);
458 static void pe_align_section(Section *s, int a)
460 int i = s->data_offset & (a-1);
461 if (i)
462 section_ptr_add(s, a - i);
465 static void pe_set_datadir(struct pe_header *hdr, int dir, DWORD addr, DWORD size)
467 hdr->opthdr.DataDirectory[dir].VirtualAddress = addr;
468 hdr->opthdr.DataDirectory[dir].Size = size;
471 struct pe_file {
472 FILE *op;
473 DWORD sum;
474 unsigned pos;
477 static int pe_fwrite(const void *data, int len, struct pe_file *pf)
479 const WORD *p = data;
480 DWORD sum;
481 int ret, i;
482 pf->pos += (ret = fwrite(data, 1, len, pf->op));
483 sum = pf->sum;
484 for (i = len; i > 0; i -= 2) {
485 sum += (i >= 2) ? *p++ : *(BYTE*)p;
486 sum = (sum + (sum >> 16)) & 0xFFFF;
488 pf->sum = sum;
489 return len == ret ? 0 : -1;
492 static void pe_fpad(struct pe_file *pf, DWORD new_pos)
494 char buf[256];
495 int n, diff = new_pos - pf->pos;
496 memset(buf, 0, sizeof buf);
497 while (diff > 0) {
498 diff -= n = umin(diff, sizeof buf);
499 fwrite(buf, n, 1, pf->op);
501 pf->pos = new_pos;
504 /*----------------------------------------------------------------------------*/
505 /* PE-DWARF/COFF support
506 does not work with a mingw-gdb really but works with cv2pdb
507 (https://github.com/rainers/cv2pdb) */
509 #define N_COFF_SYMS 0
511 static const char dwarf_secs[] =
513 ".debug_info\0"
514 ".debug_abbrev\0"
515 ".debug_line\0"
516 ".debug_aranges\0"
517 ".debug_str\0"
518 ".debug_line_str\0"
521 static const unsigned coff_strtab_size = 4 + sizeof dwarf_secs - 1;
523 static int pe_put_long_secname(char *secname, const char *name)
525 const char *d = dwarf_secs;
526 do {
527 if (0 == strcmp(d, name)) {
528 sprintf(secname, "/%d", (int)(d - dwarf_secs + 4));
529 return 1;
531 d = strchr(d, 0) + 1;
532 } while (*d);
533 return 0;
536 static void pe_create_pdb(TCCState *s1, const char *exename)
538 char buf[300]; int r;
539 snprintf(buf, sizeof buf, "cv2pdb.exe %s", exename);
540 r = system(buf);
541 strcpy(tcc_fileextension(strcpy(buf, exename)), ".pdb");
542 if (r) {
543 tcc_error_noabort("could not create '%s'\n(need working cv2pdb from https://github.com/rainers/cv2pdb)", buf);
544 } else if (s1->verbose) {
545 printf("<- %s\n", buf);
549 /*----------------------------------------------------------------------------*/
550 static int pe_write(struct pe_info *pe)
552 static const struct pe_header pe_template = {
554 /* IMAGE_DOS_HEADER doshdr */
555 0x5A4D, /*WORD e_magic; Magic number */
556 0x0090, /*WORD e_cblp; Bytes on last page of file */
557 0x0003, /*WORD e_cp; Pages in file */
558 0x0000, /*WORD e_crlc; Relocations */
560 0x0004, /*WORD e_cparhdr; Size of header in paragraphs */
561 0x0000, /*WORD e_minalloc; Minimum extra paragraphs needed */
562 0xFFFF, /*WORD e_maxalloc; Maximum extra paragraphs needed */
563 0x0000, /*WORD e_ss; Initial (relative) SS value */
565 0x00B8, /*WORD e_sp; Initial SP value */
566 0x0000, /*WORD e_csum; Checksum */
567 0x0000, /*WORD e_ip; Initial IP value */
568 0x0000, /*WORD e_cs; Initial (relative) CS value */
569 0x0040, /*WORD e_lfarlc; File address of relocation table */
570 0x0000, /*WORD e_ovno; Overlay number */
571 {0,0,0,0}, /*WORD e_res[4]; Reserved words */
572 0x0000, /*WORD e_oemid; OEM identifier (for e_oeminfo) */
573 0x0000, /*WORD e_oeminfo; OEM information; e_oemid specific */
574 {0,0,0,0,0,0,0,0,0,0}, /*WORD e_res2[10]; Reserved words */
575 0x00000080 /*DWORD e_lfanew; File address of new exe header */
577 /* BYTE dosstub[0x40] */
578 /* 14 code bytes + "This program cannot be run in DOS mode.\r\r\n$" + 6 * 0x00 */
579 0x0e,0x1f,0xba,0x0e,0x00,0xb4,0x09,0xcd,0x21,0xb8,0x01,0x4c,0xcd,0x21,0x54,0x68,
580 0x69,0x73,0x20,0x70,0x72,0x6f,0x67,0x72,0x61,0x6d,0x20,0x63,0x61,0x6e,0x6e,0x6f,
581 0x74,0x20,0x62,0x65,0x20,0x72,0x75,0x6e,0x20,0x69,0x6e,0x20,0x44,0x4f,0x53,0x20,
582 0x6d,0x6f,0x64,0x65,0x2e,0x0d,0x0d,0x0a,0x24,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
584 0x00004550, /* DWORD nt_sig = IMAGE_NT_SIGNATURE */
586 /* IMAGE_FILE_HEADER filehdr */
587 IMAGE_FILE_MACHINE, /*WORD Machine; */
588 0x0003, /*WORD NumberOfSections; */
589 0x00000000, /*DWORD TimeDateStamp; */
590 0x00000000, /*DWORD PointerToSymbolTable; */
591 0x00000000, /*DWORD NumberOfSymbols; */
592 #if defined(TCC_TARGET_X86_64)
593 0x00F0, /*WORD SizeOfOptionalHeader; */
594 0x022F /*WORD Characteristics; */
595 #define CHARACTERISTICS_DLL 0x222E
596 #elif defined(TCC_TARGET_I386)
597 0x00E0, /*WORD SizeOfOptionalHeader; */
598 0x030F /*WORD Characteristics; */
599 #define CHARACTERISTICS_DLL 0x230E
600 #elif defined(TCC_TARGET_ARM)
601 0x00E0, /*WORD SizeOfOptionalHeader; */
602 0x010F, /*WORD Characteristics; */
603 #define CHARACTERISTICS_DLL 0x230F
604 #endif
606 /* IMAGE_OPTIONAL_HEADER opthdr */
607 /* Standard fields. */
608 #ifdef TCC_TARGET_X86_64
609 0x020B, /*WORD Magic; */
610 #else
611 0x010B, /*WORD Magic; */
612 #endif
613 0x06, /*BYTE MajorLinkerVersion; */
614 0x00, /*BYTE MinorLinkerVersion; */
615 0x00000000, /*DWORD SizeOfCode; */
616 0x00000000, /*DWORD SizeOfInitializedData; */
617 0x00000000, /*DWORD SizeOfUninitializedData; */
618 0x00000000, /*DWORD AddressOfEntryPoint; */
619 0x00000000, /*DWORD BaseOfCode; */
620 #ifndef TCC_TARGET_X86_64
621 0x00000000, /*DWORD BaseOfData; */
622 #endif
623 /* NT additional fields. */
624 #if defined(TCC_TARGET_ARM)
625 0x00100000, /*DWORD ImageBase; */
626 #else
627 0x00400000, /*DWORD ImageBase; */
628 #endif
629 0x00001000, /*DWORD SectionAlignment; */
630 0x00000200, /*DWORD FileAlignment; */
631 0x0004, /*WORD MajorOperatingSystemVersion; */
632 0x0000, /*WORD MinorOperatingSystemVersion; */
633 0x0000, /*WORD MajorImageVersion; */
634 0x0000, /*WORD MinorImageVersion; */
635 0x0004, /*WORD MajorSubsystemVersion; */
636 0x0000, /*WORD MinorSubsystemVersion; */
637 0x00000000, /*DWORD Win32VersionValue; */
638 0x00000000, /*DWORD SizeOfImage; */
639 0x00000200, /*DWORD SizeOfHeaders; */
640 0x00000000, /*DWORD CheckSum; */
641 0x0002, /*WORD Subsystem; */
642 0x0000, /*WORD DllCharacteristics; */
643 0x00100000, /*DWORD SizeOfStackReserve; */
644 0x00001000, /*DWORD SizeOfStackCommit; */
645 0x00100000, /*DWORD SizeOfHeapReserve; */
646 0x00001000, /*DWORD SizeOfHeapCommit; */
647 0x00000000, /*DWORD LoaderFlags; */
648 0x00000010, /*DWORD NumberOfRvaAndSizes; */
650 /* IMAGE_DATA_DIRECTORY DataDirectory[16]; */
651 {{0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0},
652 {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}}
655 struct pe_header pe_header = pe_template;
657 int i;
658 struct pe_file pf = {0};
659 DWORD file_offset;
660 struct section_info *si;
661 IMAGE_SECTION_HEADER *psh;
662 TCCState *s1 = pe->s1;
663 int need_strtab = 0;
665 pf.op = fopen(pe->filename, "wb");
666 if (NULL == pf.op)
667 return tcc_error_noabort("could not write '%s': %s", pe->filename, strerror(errno));
669 pe->sizeofheaders = pe_file_align(pe,
670 sizeof (struct pe_header)
671 + pe->sec_count * sizeof (IMAGE_SECTION_HEADER)
674 file_offset = pe->sizeofheaders;
676 if (2 == pe->s1->verbose)
677 printf("-------------------------------"
678 "\n virt file size section" "\n");
679 for (i = 0; i < pe->sec_count; ++i) {
680 DWORD addr, size;
681 const char *sh_name;
683 si = pe->sec_info[i];
684 sh_name = si->name;
685 addr = si->sh_addr - pe->imagebase;
686 size = si->sh_size;
687 psh = &si->ish;
689 if (2 == pe->s1->verbose)
690 printf("%6x %6x %6x %s\n",
691 (unsigned)addr, (unsigned)file_offset, (unsigned)size, sh_name);
693 switch (si->cls) {
694 case sec_text:
695 if (!pe_header.opthdr.BaseOfCode)
696 pe_header.opthdr.BaseOfCode = addr;
697 break;
699 case sec_data:
700 #ifndef TCC_TARGET_X86_64
701 if (!pe_header.opthdr.BaseOfData)
702 pe_header.opthdr.BaseOfData = addr;
703 #endif
704 break;
706 case sec_bss:
707 break;
709 case sec_reloc:
710 pe_set_datadir(&pe_header, IMAGE_DIRECTORY_ENTRY_BASERELOC, addr, size);
711 break;
713 case sec_rsrc:
714 pe_set_datadir(&pe_header, IMAGE_DIRECTORY_ENTRY_RESOURCE, addr, size);
715 break;
717 case sec_pdata:
718 pe_set_datadir(&pe_header, IMAGE_DIRECTORY_ENTRY_EXCEPTION, addr, size);
719 break;
722 if (pe->imp_size) {
723 pe_set_datadir(&pe_header, IMAGE_DIRECTORY_ENTRY_IMPORT,
724 pe->imp_offs, pe->imp_size);
725 pe_set_datadir(&pe_header, IMAGE_DIRECTORY_ENTRY_IAT,
726 pe->iat_offs, pe->iat_size);
728 if (pe->exp_size) {
729 pe_set_datadir(&pe_header, IMAGE_DIRECTORY_ENTRY_EXPORT,
730 pe->exp_offs, pe->exp_size);
733 memcpy(psh->Name, sh_name, umin(strlen(sh_name), sizeof psh->Name));
734 if (si->cls == sec_debug)
735 need_strtab += pe_put_long_secname((char*)psh->Name, sh_name);
737 psh->Characteristics = si->pe_flags;
738 psh->VirtualAddress = addr;
739 psh->Misc.VirtualSize = size;
740 pe_header.opthdr.SizeOfImage =
741 umax(pe_virtual_align(pe, size + addr), pe_header.opthdr.SizeOfImage);
743 if (si->data_size) {
744 psh->PointerToRawData = file_offset;
745 file_offset = pe_file_align(pe, file_offset + si->data_size);
746 psh->SizeOfRawData = file_offset - psh->PointerToRawData;
747 if (si->cls == sec_text)
748 pe_header.opthdr.SizeOfCode += psh->SizeOfRawData;
749 else
750 pe_header.opthdr.SizeOfInitializedData += psh->SizeOfRawData;
754 //pe_header.filehdr.TimeDateStamp = time(NULL);
755 pe_header.filehdr.NumberOfSections = pe->sec_count;
756 pe_header.opthdr.AddressOfEntryPoint = pe->start_addr;
757 pe_header.opthdr.SizeOfHeaders = pe->sizeofheaders;
758 pe_header.opthdr.ImageBase = pe->imagebase;
759 pe_header.opthdr.Subsystem = pe->subsystem;
760 if (pe->s1->pe_stack_size)
761 pe_header.opthdr.SizeOfStackReserve = pe->s1->pe_stack_size;
762 if (PE_DLL == pe->type)
763 pe_header.filehdr.Characteristics = CHARACTERISTICS_DLL;
764 pe_header.filehdr.Characteristics |= pe->s1->pe_characteristics;
765 if (need_strtab) {
766 pe_header.filehdr.PointerToSymbolTable = file_offset;
767 pe_header.filehdr.NumberOfSymbols = N_COFF_SYMS;
769 pe_fwrite(&pe_header, sizeof pe_header, &pf);
770 for (i = 0; i < pe->sec_count; ++i)
771 pe_fwrite(&pe->sec_info[i]->ish, sizeof(IMAGE_SECTION_HEADER), &pf);
773 file_offset = pe->sizeofheaders;
774 for (i = 0; i < pe->sec_count; ++i) {
775 Section *s;
776 si = pe->sec_info[i];
777 if (!si->data_size)
778 continue;
779 for (s = si->sec; s; s = s->prev) {
780 pe_fpad(&pf, file_offset);
781 pe_fwrite(s->data, s->data_offset, &pf);
782 if (s->prev)
783 file_offset += s->prev->sh_addr - s->sh_addr;
785 file_offset = si->ish.PointerToRawData + si->ish.SizeOfRawData;
786 pe_fpad(&pf, file_offset);
789 if (need_strtab) {
790 /* create a tiny COFF string table with the long section names */
791 pe_fwrite(&coff_strtab_size, sizeof coff_strtab_size, &pf);
792 pe_fwrite(dwarf_secs, sizeof dwarf_secs - 1, &pf);
793 file_offset = pf.pos;
796 pf.sum += file_offset;
797 fseek(pf.op, offsetof(struct pe_header, opthdr.CheckSum), SEEK_SET);
798 pe_fwrite(&pf.sum, sizeof (DWORD), &pf);
800 fclose (pf.op);
801 #ifndef _WIN32
802 chmod(pe->filename, 0777);
803 #endif
805 if (2 == pe->s1->verbose)
806 printf("-------------------------------\n");
807 if (pe->s1->verbose)
808 printf("<- %s (%u bytes)\n", pe->filename, (unsigned)file_offset);
810 if (s1->do_debug & 16)
811 pe_create_pdb(s1, pe->filename);
812 return 0;
815 /*----------------------------------------------------------------------------*/
817 static struct import_symbol *pe_add_import(struct pe_info *pe, int sym_index)
819 int i;
820 int dll_index;
821 struct pe_import_info *p;
822 struct import_symbol *s;
823 ElfW(Sym) *isym;
825 isym = (ElfW(Sym) *)pe->s1->dynsymtab_section->data + sym_index;
826 dll_index = isym->st_size;
828 i = dynarray_assoc ((void**)pe->imp_info, pe->imp_count, dll_index);
829 if (-1 != i) {
830 p = pe->imp_info[i];
831 goto found_dll;
833 p = tcc_mallocz(sizeof *p);
834 p->dll_index = dll_index;
835 dynarray_add(&pe->imp_info, &pe->imp_count, p);
837 found_dll:
838 i = dynarray_assoc ((void**)p->symbols, p->sym_count, sym_index);
839 if (-1 != i)
840 return p->symbols[i];
842 s = tcc_mallocz(sizeof *s);
843 dynarray_add(&p->symbols, &p->sym_count, s);
844 s->sym_index = sym_index;
845 return s;
848 void pe_free_imports(struct pe_info *pe)
850 int i;
851 for (i = 0; i < pe->imp_count; ++i) {
852 struct pe_import_info *p = pe->imp_info[i];
853 dynarray_reset(&p->symbols, &p->sym_count);
855 dynarray_reset(&pe->imp_info, &pe->imp_count);
858 /*----------------------------------------------------------------------------*/
859 static void pe_build_imports(struct pe_info *pe)
861 int thk_ptr, ent_ptr, dll_ptr, sym_cnt, i;
862 DWORD rva_base = pe->thunk->sh_addr - pe->imagebase;
863 int ndlls = pe->imp_count;
864 TCCState *s1 = pe->s1;
866 for (sym_cnt = i = 0; i < ndlls; ++i)
867 sym_cnt += pe->imp_info[i]->sym_count;
869 if (0 == sym_cnt)
870 return;
872 pe_align_section(pe->thunk, 16);
873 pe->imp_size = (ndlls + 1) * sizeof(IMAGE_IMPORT_DESCRIPTOR);
874 pe->iat_size = (sym_cnt + ndlls) * sizeof(ADDR3264);
875 dll_ptr = pe->thunk->data_offset;
876 thk_ptr = dll_ptr + pe->imp_size;
877 ent_ptr = thk_ptr + pe->iat_size;
878 pe->imp_offs = dll_ptr + rva_base;
879 pe->iat_offs = thk_ptr + rva_base;
880 section_ptr_add(pe->thunk, pe->imp_size + 2*pe->iat_size);
882 for (i = 0; i < pe->imp_count; ++i) {
883 IMAGE_IMPORT_DESCRIPTOR *hdr;
884 int k, n, dllindex;
885 ADDR3264 v;
886 struct pe_import_info *p = pe->imp_info[i];
887 const char *name;
888 DLLReference *dllref;
890 dllindex = p->dll_index;
891 if (dllindex)
892 name = tcc_basename((dllref = pe->s1->loaded_dlls[dllindex-1])->name);
893 else
894 name = "", dllref = NULL;
896 /* put the dll name into the import header */
897 v = put_elf_str(pe->thunk, name);
898 hdr = (IMAGE_IMPORT_DESCRIPTOR*)(pe->thunk->data + dll_ptr);
899 hdr->FirstThunk = thk_ptr + rva_base;
900 hdr->OriginalFirstThunk = ent_ptr + rva_base;
901 hdr->Name = v + rva_base;
903 for (k = 0, n = p->sym_count; k <= n; ++k) {
904 if (k < n) {
905 int iat_index = p->symbols[k]->iat_index;
906 int sym_index = p->symbols[k]->sym_index;
907 ElfW(Sym) *imp_sym = (ElfW(Sym) *)pe->s1->dynsymtab_section->data + sym_index;
908 ElfW(Sym) *org_sym = (ElfW(Sym) *)symtab_section->data + iat_index;
909 const char *name = (char*)pe->s1->dynsymtab_section->link->data + imp_sym->st_name;
910 int ordinal;
912 org_sym->st_value = thk_ptr;
913 org_sym->st_shndx = pe->thunk->sh_num;
915 if (dllref)
916 v = 0, ordinal = imp_sym->st_value; /* ordinal from pe_load_def */
917 else
918 ordinal = 0, v = imp_sym->st_value; /* address from tcc_add_symbol() */
920 #ifdef TCC_IS_NATIVE
921 if (pe->type == PE_RUN) {
922 if (dllref) {
923 if ( !dllref->handle )
924 dllref->handle = LoadLibraryA(dllref->name);
925 v = (ADDR3264)GetProcAddress(dllref->handle, ordinal?(char*)0+ordinal:name);
927 if (!v)
928 tcc_error_noabort("could not resolve symbol '%s'", name);
929 } else
930 #endif
931 if (ordinal) {
932 v = ordinal | (ADDR3264)1 << (sizeof(ADDR3264)*8 - 1);
933 } else {
934 v = pe->thunk->data_offset + rva_base;
935 section_ptr_add(pe->thunk, sizeof(WORD)); /* hint, not used */
936 put_elf_str(pe->thunk, name);
939 } else {
940 v = 0; /* last entry is zero */
943 *(ADDR3264*)(pe->thunk->data+thk_ptr) =
944 *(ADDR3264*)(pe->thunk->data+ent_ptr) = v;
945 thk_ptr += sizeof (ADDR3264);
946 ent_ptr += sizeof (ADDR3264);
948 dll_ptr += sizeof(IMAGE_IMPORT_DESCRIPTOR);
952 /* ------------------------------------------------------------- */
954 struct pe_sort_sym
956 int index;
957 const char *name;
960 static int sym_cmp(const void *va, const void *vb)
962 const char *ca = (*(struct pe_sort_sym**)va)->name;
963 const char *cb = (*(struct pe_sort_sym**)vb)->name;
964 return strcmp(ca, cb);
967 static void pe_build_exports(struct pe_info *pe)
969 ElfW(Sym) *sym;
970 int sym_index, sym_end;
971 DWORD rva_base, base_o, func_o, name_o, ord_o, str_o;
972 IMAGE_EXPORT_DIRECTORY *hdr;
973 int sym_count, ord;
974 struct pe_sort_sym **sorted, *p;
975 TCCState *s1 = pe->s1;
977 FILE *op;
978 char buf[260];
979 const char *dllname;
980 const char *name;
982 rva_base = pe->thunk->sh_addr - pe->imagebase;
983 sym_count = 0, sorted = NULL, op = NULL;
985 sym_end = symtab_section->data_offset / sizeof(ElfW(Sym));
986 for (sym_index = 1; sym_index < sym_end; ++sym_index) {
987 sym = (ElfW(Sym)*)symtab_section->data + sym_index;
988 name = pe_export_name(pe->s1, sym);
989 if (sym->st_other & ST_PE_EXPORT) {
990 p = tcc_malloc(sizeof *p);
991 p->index = sym_index;
992 p->name = name;
993 dynarray_add(&sorted, &sym_count, p);
995 #if 0
996 if (sym->st_other & ST_PE_EXPORT)
997 printf("export: %s\n", name);
998 if (sym->st_other & ST_PE_STDCALL)
999 printf("stdcall: %s\n", name);
1000 #endif
1003 if (0 == sym_count)
1004 return;
1006 qsort (sorted, sym_count, sizeof *sorted, sym_cmp);
1008 pe_align_section(pe->thunk, 16);
1009 dllname = tcc_basename(pe->filename);
1011 base_o = pe->thunk->data_offset;
1012 func_o = base_o + sizeof(IMAGE_EXPORT_DIRECTORY);
1013 name_o = func_o + sym_count * sizeof (DWORD);
1014 ord_o = name_o + sym_count * sizeof (DWORD);
1015 str_o = ord_o + sym_count * sizeof(WORD);
1017 hdr = section_ptr_add(pe->thunk, str_o - base_o);
1018 hdr->Characteristics = 0;
1019 hdr->Base = 1;
1020 hdr->NumberOfFunctions = sym_count;
1021 hdr->NumberOfNames = sym_count;
1022 hdr->AddressOfFunctions = func_o + rva_base;
1023 hdr->AddressOfNames = name_o + rva_base;
1024 hdr->AddressOfNameOrdinals = ord_o + rva_base;
1025 hdr->Name = str_o + rva_base;
1026 put_elf_str(pe->thunk, dllname);
1028 #if 1
1029 /* automatically write exports to <output-filename>.def */
1030 pstrcpy(buf, sizeof buf, pe->filename);
1031 strcpy(tcc_fileextension(buf), ".def");
1032 op = fopen(buf, "wb");
1033 if (NULL == op) {
1034 tcc_error_noabort("could not create '%s': %s", buf, strerror(errno));
1035 } else {
1036 fprintf(op, "LIBRARY %s\n\nEXPORTS\n", dllname);
1037 if (pe->s1->verbose)
1038 printf("<- %s (%d symbol%s)\n", buf, sym_count, &"s"[sym_count < 2]);
1040 #endif
1042 for (ord = 0; ord < sym_count; ++ord)
1044 p = sorted[ord], sym_index = p->index, name = p->name;
1045 /* insert actual address later in relocate_sections() */
1046 put_elf_reloc(symtab_section, pe->thunk,
1047 func_o, R_XXX_RELATIVE, sym_index);
1048 *(DWORD*)(pe->thunk->data + name_o)
1049 = pe->thunk->data_offset + rva_base;
1050 *(WORD*)(pe->thunk->data + ord_o)
1051 = ord;
1052 put_elf_str(pe->thunk, name);
1053 func_o += sizeof (DWORD);
1054 name_o += sizeof (DWORD);
1055 ord_o += sizeof (WORD);
1056 if (op)
1057 fprintf(op, "%s\n", name);
1060 pe->exp_offs = base_o + rva_base;
1061 pe->exp_size = pe->thunk->data_offset - base_o;
1062 dynarray_reset(&sorted, &sym_count);
1063 if (op)
1064 fclose(op);
1067 /* ------------------------------------------------------------- */
1068 static void pe_build_reloc (struct pe_info *pe)
1070 DWORD offset, block_ptr, sh_addr, addr;
1071 int count, i;
1072 ElfW_Rel *rel, *rel_end;
1073 Section *s = NULL, *sr;
1074 struct pe_reloc_header *hdr;
1076 sh_addr = offset = block_ptr = count = i = 0;
1077 rel = rel_end = NULL;
1079 for(;;) {
1080 if (rel < rel_end) {
1081 int type = ELFW(R_TYPE)(rel->r_info);
1082 addr = rel->r_offset + sh_addr;
1083 ++ rel;
1084 if (type != REL_TYPE_DIRECT)
1085 continue;
1086 if (count == 0) { /* new block */
1087 block_ptr = pe->reloc->data_offset;
1088 section_ptr_add(pe->reloc, sizeof(struct pe_reloc_header));
1089 offset = addr & 0xFFFFFFFF<<12;
1091 if ((addr -= offset) < (1<<12)) { /* one block spans 4k addresses */
1092 WORD *wp = section_ptr_add(pe->reloc, sizeof (WORD));
1093 *wp = addr | PE_IMAGE_REL<<12;
1094 ++count;
1095 continue;
1097 -- rel;
1099 } else if (s) {
1100 sr = s->reloc;
1101 if (sr) {
1102 rel = (ElfW_Rel *)sr->data;
1103 rel_end = (ElfW_Rel *)(sr->data + sr->data_offset);
1104 sh_addr = s->sh_addr;
1106 s = s->prev;
1107 continue;
1109 } else if (i < pe->sec_count) {
1110 s = pe->sec_info[i]->sec, ++i;
1111 continue;
1113 } else if (!count)
1114 break;
1116 /* fill the last block and ready for a new one */
1117 if (count & 1) /* align for DWORDS */
1118 section_ptr_add(pe->reloc, sizeof(WORD)), ++count;
1119 hdr = (struct pe_reloc_header *)(pe->reloc->data + block_ptr);
1120 hdr -> offset = offset - pe->imagebase;
1121 hdr -> size = count * sizeof(WORD) + sizeof(struct pe_reloc_header);
1122 count = 0;
1126 /* ------------------------------------------------------------- */
1127 static int pe_section_class(Section *s)
1129 int type, flags;
1130 const char *name;
1131 type = s->sh_type;
1132 flags = s->sh_flags;
1133 name = s->name;
1135 if (0 == memcmp(name, ".stab", 5) || 0 == memcmp(name, ".debug_", 7)) {
1136 if (s->s1->do_debug)
1137 return sec_debug;
1139 } else if (flags & SHF_ALLOC) {
1140 if (type == SHT_PROGBITS
1141 || type == SHT_INIT_ARRAY
1142 || type == SHT_FINI_ARRAY) {
1143 if (flags & SHF_EXECINSTR)
1144 return sec_text;
1145 if (flags & SHF_WRITE)
1146 return sec_data;
1147 if (0 == strcmp(name, ".rsrc"))
1148 return sec_rsrc;
1149 if (0 == strcmp(name, ".iedat"))
1150 return sec_idata;
1151 if (0 == strcmp(name, ".pdata"))
1152 return sec_pdata;
1153 return sec_rdata;
1154 } else if (type == SHT_NOBITS) {
1155 return sec_bss;
1157 return sec_other;
1158 } else {
1159 if (0 == strcmp(name, ".reloc"))
1160 return sec_reloc;
1162 return sec_last;
1165 static int pe_assign_addresses (struct pe_info *pe)
1167 int i, k, n, c, nbs;
1168 ADDR3264 addr;
1169 int *sec_order, *sec_cls;
1170 struct section_info *si;
1171 Section *s;
1172 TCCState *s1 = pe->s1;
1174 if (PE_DLL == pe->type)
1175 pe->reloc = new_section(pe->s1, ".reloc", SHT_PROGBITS, 0);
1176 //pe->thunk = new_section(pe->s1, ".iedat", SHT_PROGBITS, SHF_ALLOC);
1178 nbs = s1->nb_sections;
1179 sec_order = tcc_mallocz(2 * sizeof (int) * nbs);
1180 sec_cls = sec_order + nbs;
1181 for (i = 1; i < nbs; ++i) {
1182 s = s1->sections[i];
1183 k = pe_section_class(s);
1184 for (n = i; n > 1 && k < (c = sec_cls[n - 1]); --n)
1185 sec_cls[n] = c, sec_order[n] = sec_order[n - 1];
1186 sec_cls[n] = k, sec_order[n] = i;
1188 si = NULL;
1189 addr = pe->imagebase + 1;
1191 for (i = 1; (c = sec_cls[i]) < sec_last; ++i) {
1192 s = s1->sections[sec_order[i]];
1194 if (PE_MERGE_DATA && c == sec_bss)
1195 c = sec_data;
1197 if (si && c == si->cls && c != sec_debug) {
1198 /* merge with previous section */
1199 s->sh_addr = addr = ((addr - 1) | (16 - 1)) + 1;
1200 } else {
1201 si = NULL;
1202 s->sh_addr = addr = pe_virtual_align(pe, addr);
1205 if (NULL == pe->thunk
1206 && c == (data_section == rodata_section ? sec_data : sec_rdata))
1207 pe->thunk = s;
1209 if (s == pe->thunk) {
1210 pe_build_imports(pe);
1211 pe_build_exports(pe);
1213 if (s == pe->reloc)
1214 pe_build_reloc (pe);
1216 if (0 == s->data_offset)
1217 continue;
1219 if (si)
1220 goto add_section;
1222 si = tcc_mallocz(sizeof *si);
1223 dynarray_add(&pe->sec_info, &pe->sec_count, si);
1225 strcpy(si->name, s->name);
1226 si->cls = c;
1227 si->sh_addr = addr;
1229 si->pe_flags = IMAGE_SCN_MEM_READ;
1230 if (s->sh_flags & SHF_EXECINSTR)
1231 si->pe_flags |= IMAGE_SCN_MEM_EXECUTE | IMAGE_SCN_CNT_CODE;
1232 else if (s->sh_type == SHT_NOBITS)
1233 si->pe_flags |= IMAGE_SCN_CNT_UNINITIALIZED_DATA;
1234 else
1235 si->pe_flags |= IMAGE_SCN_CNT_INITIALIZED_DATA;
1236 if (s->sh_flags & SHF_WRITE)
1237 si->pe_flags |= IMAGE_SCN_MEM_WRITE;
1238 if (0 == (s->sh_flags & SHF_ALLOC))
1239 si->pe_flags |= IMAGE_SCN_MEM_DISCARDABLE;
1241 add_section:
1242 addr += s->data_offset;
1243 si->sh_size = addr - si->sh_addr;
1244 if (s->sh_type != SHT_NOBITS) {
1245 Section **ps = &si->sec;
1246 while (*ps)
1247 ps = &(*ps)->prev;
1248 *ps = s, s->prev = NULL;
1249 si->data_size = si->sh_size;
1251 //printf("%08x %05x %08x %s\n", si->sh_addr, si->sh_size, si->pe_flags, s->name);
1253 #if 0
1254 for (i = 1; i < nbs; ++i) {
1255 Section *s = s1->sections[sec_order[i]];
1256 int type = s->sh_type;
1257 int flags = s->sh_flags;
1258 printf("section %-16s %-10s %p %04x %s,%s,%s\n",
1259 s->name,
1260 type == SHT_PROGBITS ? "progbits" :
1261 type == SHT_INIT_ARRAY ? "initarr" :
1262 type == SHT_FINI_ARRAY ? "finiarr" :
1263 type == SHT_NOBITS ? "nobits" :
1264 type == SHT_SYMTAB ? "symtab" :
1265 type == SHT_STRTAB ? "strtab" :
1266 type == SHT_RELX ? "rel" : "???",
1267 s->sh_addr,
1268 (unsigned)s->data_offset,
1269 flags & SHF_ALLOC ? "alloc" : "",
1270 flags & SHF_WRITE ? "write" : "",
1271 flags & SHF_EXECINSTR ? "exec" : ""
1273 fflush(stdout);
1275 s1->verbose = 2;
1276 #endif
1277 tcc_free(sec_order);
1278 return 0;
1281 /*----------------------------------------------------------------------------*/
1283 static int pe_isafunc(TCCState *s1, int sym_index)
1285 Section *sr = text_section->reloc;
1286 ElfW_Rel *rel, *rel_end;
1287 ElfW(Addr)info = ELFW(R_INFO)(sym_index, R_XXX_FUNCCALL);
1288 #ifdef R_XXX_FUNCCALL2
1289 ElfW(Addr)info2 = ELFW(R_INFO)(sym_index, R_XXX_FUNCCALL2);
1290 #endif
1291 if (!sr)
1292 return 0;
1293 rel_end = (ElfW_Rel *)(sr->data + sr->data_offset);
1294 for (rel = (ElfW_Rel *)sr->data; rel < rel_end; rel++) {
1295 if (rel->r_info == info)
1296 return 1;
1297 #ifdef R_XXX_FUNCCALL2
1298 if (rel->r_info == info2)
1299 return 1;
1300 #endif
1302 return 0;
1305 /*----------------------------------------------------------------------------*/
1306 static int pe_check_symbols(struct pe_info *pe)
1308 ElfW(Sym) *sym;
1309 int sym_index, sym_end;
1310 int ret = 0;
1311 TCCState *s1 = pe->s1;
1313 pe_align_section(text_section, 8);
1315 sym_end = symtab_section->data_offset / sizeof(ElfW(Sym));
1316 for (sym_index = 1; sym_index < sym_end; ++sym_index) {
1318 sym = (ElfW(Sym) *)symtab_section->data + sym_index;
1319 if (sym->st_shndx == SHN_UNDEF) {
1321 const char *name = (char*)symtab_section->link->data + sym->st_name;
1322 unsigned type = ELFW(ST_TYPE)(sym->st_info);
1323 int imp_sym = pe_find_import(pe->s1, sym);
1324 struct import_symbol *is;
1326 if (imp_sym <= 0)
1327 goto not_found;
1329 if (type == STT_NOTYPE) {
1330 /* symbols from assembler have no type, find out which */
1331 if (pe_isafunc(s1, sym_index))
1332 type = STT_FUNC;
1333 else
1334 type = STT_OBJECT;
1337 is = pe_add_import(pe, imp_sym);
1339 if (type == STT_FUNC) {
1340 unsigned offset = is->thk_offset;
1341 if (offset) {
1342 /* got aliased symbol, like stricmp and _stricmp */
1343 } else {
1344 char buffer[100];
1345 unsigned char *p;
1347 /* add a helper symbol, will be patched later in
1348 pe_build_imports */
1349 sprintf(buffer, "IAT.%s", name);
1350 is->iat_index = put_elf_sym(
1351 symtab_section, 0, sizeof(DWORD),
1352 ELFW(ST_INFO)(STB_LOCAL, STT_OBJECT),
1353 0, SHN_UNDEF, buffer);
1355 offset = text_section->data_offset;
1356 is->thk_offset = offset;
1358 /* add the 'jmp IAT[x]' instruction */
1359 #ifdef TCC_TARGET_ARM
1360 p = section_ptr_add(text_section, 8+4); // room for code and address
1361 write32le(p + 0, 0xE59FC000); // arm code ldr ip, [pc] ; PC+8+0 = 0001xxxx
1362 write32le(p + 4, 0xE59CF000); // arm code ldr pc, [ip]
1363 put_elf_reloc(symtab_section, text_section,
1364 offset + 8, R_XXX_THUNKFIX, is->iat_index); // offset to IAT position
1365 #else
1366 p = section_ptr_add(text_section, 8);
1367 write16le(p, 0x25FF);
1368 #ifdef TCC_TARGET_X86_64
1369 write32le(p + 2, (DWORD)-4);
1370 #endif
1371 put_elf_reloc(symtab_section, text_section,
1372 offset + 2, R_XXX_THUNKFIX, is->iat_index);
1373 #endif
1375 /* tcc_realloc might have altered sym's address */
1376 sym = (ElfW(Sym) *)symtab_section->data + sym_index;
1378 /* patch the original symbol */
1379 sym->st_value = offset;
1380 sym->st_shndx = text_section->sh_num;
1381 sym->st_other &= ~ST_PE_EXPORT; /* do not export */
1382 continue;
1385 if (type == STT_OBJECT) { /* data, ptr to that should be */
1386 if (0 == is->iat_index) {
1387 /* original symbol will be patched later in pe_build_imports */
1388 is->iat_index = sym_index;
1389 continue;
1393 not_found:
1394 if (ELFW(ST_BIND)(sym->st_info) == STB_WEAK)
1395 /* STB_WEAK undefined symbols are accepted */
1396 continue;
1397 ret = tcc_error_noabort("undefined symbol '%s'%s", name,
1398 imp_sym < 0 ? ", missing __declspec(dllimport)?":"");
1400 } else if (pe->s1->rdynamic
1401 && ELFW(ST_BIND)(sym->st_info) != STB_LOCAL) {
1402 /* if -rdynamic option, then export all non local symbols */
1403 sym->st_other |= ST_PE_EXPORT;
1406 return ret;
1409 /*----------------------------------------------------------------------------*/
1410 #if PE_PRINT_SECTIONS
1411 static void pe_print_section(FILE * f, Section * s)
1413 /* just if you're curious */
1414 BYTE *p, *e, b;
1415 int i, n, l, m;
1416 p = s->data;
1417 e = s->data + s->data_offset;
1418 l = e - p;
1420 fprintf(f, "section \"%s\"", s->name);
1421 if (s->link)
1422 fprintf(f, "\nlink \"%s\"", s->link->name);
1423 if (s->reloc)
1424 fprintf(f, "\nreloc \"%s\"", s->reloc->name);
1425 fprintf(f, "\nv_addr %08X", (unsigned)s->sh_addr);
1426 fprintf(f, "\ncontents %08X", (unsigned)l);
1427 fprintf(f, "\n\n");
1429 if (s->sh_type == SHT_NOBITS)
1430 return;
1432 if (0 == l)
1433 return;
1435 if (s->sh_type == SHT_SYMTAB)
1436 m = sizeof(ElfW(Sym));
1437 else if (s->sh_type == SHT_RELX)
1438 m = sizeof(ElfW_Rel);
1439 else
1440 m = 16;
1442 fprintf(f, "%-8s", "offset");
1443 for (i = 0; i < m; ++i)
1444 fprintf(f, " %02x", i);
1445 n = 56;
1447 if (s->sh_type == SHT_SYMTAB || s->sh_type == SHT_RELX) {
1448 const char *fields1[] = {
1449 "name",
1450 "value",
1451 "size",
1452 "bind",
1453 "type",
1454 "other",
1455 "shndx",
1456 NULL
1459 const char *fields2[] = {
1460 "offs",
1461 "type",
1462 "symb",
1463 NULL
1466 const char **p;
1468 if (s->sh_type == SHT_SYMTAB)
1469 p = fields1, n = 106;
1470 else
1471 p = fields2, n = 58;
1473 for (i = 0; p[i]; ++i)
1474 fprintf(f, "%6s", p[i]);
1475 fprintf(f, " symbol");
1478 fprintf(f, "\n");
1479 for (i = 0; i < n; ++i)
1480 fprintf(f, "-");
1481 fprintf(f, "\n");
1483 for (i = 0; i < l;)
1485 fprintf(f, "%08X", i);
1486 for (n = 0; n < m; ++n) {
1487 if (n + i < l)
1488 fprintf(f, " %02X", p[i + n]);
1489 else
1490 fprintf(f, " ");
1493 if (s->sh_type == SHT_SYMTAB) {
1494 ElfW(Sym) *sym = (ElfW(Sym) *) (p + i);
1495 const char *name = s->link->data + sym->st_name;
1496 fprintf(f, " %04X %04X %04X %02X %02X %02X %04X \"%s\"",
1497 (unsigned)sym->st_name,
1498 (unsigned)sym->st_value,
1499 (unsigned)sym->st_size,
1500 (unsigned)ELFW(ST_BIND)(sym->st_info),
1501 (unsigned)ELFW(ST_TYPE)(sym->st_info),
1502 (unsigned)sym->st_other,
1503 (unsigned)sym->st_shndx,
1504 name);
1506 } else if (s->sh_type == SHT_RELX) {
1507 ElfW_Rel *rel = (ElfW_Rel *) (p + i);
1508 ElfW(Sym) *sym =
1509 (ElfW(Sym) *) s->link->data + ELFW(R_SYM)(rel->r_info);
1510 const char *name = s->link->link->data + sym->st_name;
1511 fprintf(f, " %04X %02X %04X \"%s\"",
1512 (unsigned)rel->r_offset,
1513 (unsigned)ELFW(R_TYPE)(rel->r_info),
1514 (unsigned)ELFW(R_SYM)(rel->r_info),
1515 name);
1516 } else {
1517 fprintf(f, " ");
1518 for (n = 0; n < m; ++n) {
1519 if (n + i < l) {
1520 b = p[i + n];
1521 if (b < 32 || b >= 127)
1522 b = '.';
1523 fprintf(f, "%c", b);
1527 i += m;
1528 fprintf(f, "\n");
1530 fprintf(f, "\n\n");
1533 static void pe_print_sections(TCCState *s1, const char *fname)
1535 Section *s;
1536 FILE *f;
1537 int i;
1538 f = fopen(fname, "w");
1539 for (i = 1; i < s1->nb_sections; ++i) {
1540 s = s1->sections[i];
1541 pe_print_section(f, s);
1543 pe_print_section(f, s1->dynsymtab_section);
1544 fclose(f);
1546 #endif
1548 /* ------------------------------------------------------------- */
1549 /* helper function for load/store to insert one more indirection */
1551 #if defined TCC_TARGET_I386 || defined TCC_TARGET_X86_64
1552 ST_FUNC SValue *pe_getimport(SValue *sv, SValue *v2)
1554 int r2;
1555 if ((sv->r & (VT_VALMASK|VT_SYM)) != (VT_CONST|VT_SYM) || (sv->r2 != VT_CONST))
1556 return sv;
1557 if (!sv->sym->a.dllimport)
1558 return sv;
1559 // printf("import %04x %04x %04x %s\n", sv->type.t, sv->sym->type.t, sv->r, get_tok_str(sv->sym->v, NULL));
1560 memset(v2, 0, sizeof *v2);
1561 v2->type.t = VT_PTR;
1562 v2->r = VT_CONST | VT_SYM | VT_LVAL;
1563 v2->sym = sv->sym;
1565 r2 = get_reg(RC_INT);
1566 load(r2, v2);
1567 v2->r = r2;
1568 if ((uint32_t)sv->c.i) {
1569 vpushv(v2);
1570 vpushi(sv->c.i);
1571 gen_opi('+');
1572 *v2 = *vtop--;
1574 v2->type.t = sv->type.t;
1575 v2->r |= sv->r & VT_LVAL;
1576 return v2;
1578 #endif
1580 ST_FUNC int pe_putimport(TCCState *s1, int dllindex, const char *name, addr_t value)
1582 return set_elf_sym(
1583 s1->dynsymtab_section,
1584 value,
1585 dllindex, /* st_size */
1586 ELFW(ST_INFO)(STB_GLOBAL, STT_NOTYPE),
1588 value ? SHN_ABS : SHN_UNDEF,
1589 name
1593 static int read_mem(int fd, unsigned offset, void *buffer, unsigned len)
1595 lseek(fd, offset, SEEK_SET);
1596 return len == read(fd, buffer, len);
1599 /* ------------------------------------------------------------- */
1601 static int get_dllexports(int fd, char **pp)
1603 int i, k, l, n, n0, ret;
1604 char *p;
1606 IMAGE_SECTION_HEADER ish;
1607 IMAGE_EXPORT_DIRECTORY ied;
1608 IMAGE_DOS_HEADER dh;
1609 IMAGE_FILE_HEADER ih;
1610 DWORD sig, ref, addr;
1611 DWORD *namep = NULL, p0 = 0, p1;
1613 int pef_hdroffset, opt_hdroffset, sec_hdroffset;
1615 n = n0 = 0;
1616 p = NULL;
1617 ret = 1;
1618 if (!read_mem(fd, 0, &dh, sizeof dh))
1619 goto the_end;
1620 if (!read_mem(fd, dh.e_lfanew, &sig, sizeof sig))
1621 goto the_end;
1622 if (sig != 0x00004550)
1623 goto the_end;
1624 pef_hdroffset = dh.e_lfanew + sizeof sig;
1625 if (!read_mem(fd, pef_hdroffset, &ih, sizeof ih))
1626 goto the_end;
1627 opt_hdroffset = pef_hdroffset + sizeof ih;
1628 if (ih.Machine == 0x014C) {
1629 IMAGE_OPTIONAL_HEADER32 oh;
1630 sec_hdroffset = opt_hdroffset + sizeof oh;
1631 if (!read_mem(fd, opt_hdroffset, &oh, sizeof oh))
1632 goto the_end;
1633 if (IMAGE_DIRECTORY_ENTRY_EXPORT >= oh.NumberOfRvaAndSizes)
1634 goto the_end_0;
1635 addr = oh.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress;
1636 } else if (ih.Machine == 0x8664) {
1637 IMAGE_OPTIONAL_HEADER64 oh;
1638 sec_hdroffset = opt_hdroffset + sizeof oh;
1639 if (!read_mem(fd, opt_hdroffset, &oh, sizeof oh))
1640 goto the_end;
1641 if (IMAGE_DIRECTORY_ENTRY_EXPORT >= oh.NumberOfRvaAndSizes)
1642 goto the_end_0;
1643 addr = oh.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress;
1644 } else
1645 goto the_end;
1647 //printf("addr: %08x\n", addr);
1648 for (i = 0; i < ih.NumberOfSections; ++i) {
1649 if (!read_mem(fd, sec_hdroffset + i * sizeof ish, &ish, sizeof ish))
1650 goto the_end;
1651 //printf("vaddr: %08x\n", ish.VirtualAddress);
1652 if (addr >= ish.VirtualAddress && addr < ish.VirtualAddress + ish.SizeOfRawData)
1653 goto found;
1655 goto the_end_0;
1656 found:
1657 ref = ish.VirtualAddress - ish.PointerToRawData;
1658 if (!read_mem(fd, addr - ref, &ied, sizeof ied))
1659 goto the_end;
1660 k = ied.NumberOfNames;
1661 if (k) {
1662 namep = tcc_malloc(l = k * sizeof *namep);
1663 if (!read_mem(fd, ied.AddressOfNames - ref, namep, l))
1664 goto the_end;
1665 for (i = l = 0; i < k; ++i) {
1666 p1 = namep[i] - ref;
1667 if (p1 != p0)
1668 lseek(fd, p0 = p1, SEEK_SET), l = 0;
1669 do {
1670 if (0 == l) {
1671 if (n + 1000 >= n0)
1672 p = tcc_realloc(p, n0 += 1000);
1673 if ((l = read(fd, p + n, 1000 - 1)) <= 0)
1674 goto the_end;
1676 --l, ++p0;
1677 } while (p[n++]);
1679 p[n] = 0;
1681 the_end_0:
1682 ret = 0;
1683 the_end:
1684 tcc_free(namep);
1685 if (ret && p)
1686 tcc_free(p), p = NULL;
1687 *pp = p;
1688 return ret;
1691 /* -------------------------------------------------------------
1692 * This is for compiled windows resources in 'coff' format
1693 * as generated by 'windres.exe -O coff ...'.
1696 static int pe_load_res(TCCState *s1, int fd)
1698 struct pe_rsrc_header hdr;
1699 Section *rsrc_section;
1700 int i, ret = -1, sym_index;
1701 BYTE *ptr;
1702 unsigned offs;
1704 if (!read_mem(fd, 0, &hdr, sizeof hdr))
1705 goto quit;
1707 if (hdr.filehdr.Machine != IMAGE_FILE_MACHINE
1708 || hdr.filehdr.NumberOfSections != 1
1709 || strcmp((char*)hdr.sectionhdr.Name, ".rsrc") != 0)
1710 goto quit;
1712 rsrc_section = new_section(s1, ".rsrc", SHT_PROGBITS, SHF_ALLOC);
1713 ptr = section_ptr_add(rsrc_section, hdr.sectionhdr.SizeOfRawData);
1714 offs = hdr.sectionhdr.PointerToRawData;
1715 if (!read_mem(fd, offs, ptr, hdr.sectionhdr.SizeOfRawData))
1716 goto quit;
1717 offs = hdr.sectionhdr.PointerToRelocations;
1718 sym_index = put_elf_sym(symtab_section, 0, 0, 0, 0, rsrc_section->sh_num, ".rsrc");
1719 for (i = 0; i < hdr.sectionhdr.NumberOfRelocations; ++i) {
1720 struct pe_rsrc_reloc rel;
1721 if (!read_mem(fd, offs, &rel, sizeof rel))
1722 goto quit;
1723 // printf("rsrc_reloc: %x %x %x\n", rel.offset, rel.size, rel.type);
1724 if (rel.type != RSRC_RELTYPE)
1725 goto quit;
1726 put_elf_reloc(symtab_section, rsrc_section,
1727 rel.offset, R_XXX_RELATIVE, sym_index);
1728 offs += sizeof rel;
1730 ret = 0;
1731 quit:
1732 return ret;
1735 /* ------------------------------------------------------------- */
1737 static char *trimfront(char *p)
1739 while ((unsigned char)*p <= ' ' && *p && *p != '\n')
1740 ++p;
1741 return p;
1745 static char *trimback(char *a, char *e)
1747 while (e > a && (unsigned char)e[-1] <= ' ')
1748 --e;
1749 *e = 0;;
1750 return a;
1753 static char *get_token(char **s, char *f)
1755 char *p = *s, *e;
1756 p = e = trimfront(p);
1757 while ((unsigned char)*e > ' ')
1758 ++e;
1759 *s = trimfront(e);
1760 *f = **s; *e = 0;
1761 return p;
1764 static int pe_load_def(TCCState *s1, int fd)
1766 int state = 0, ret = -1, dllindex = 0, ord;
1767 char dllname[80], *buf, *line, *p, *x, next;
1769 buf = tcc_load_text(fd);
1770 for (line = buf;; ++line) {
1771 p = get_token(&line, &next);
1772 if (!(*p && *p != ';'))
1773 goto skip;
1774 switch (state) {
1775 case 0:
1776 if (0 != stricmp(p, "LIBRARY") || next == '\n')
1777 goto quit;
1778 pstrcpy(dllname, sizeof dllname, get_token(&line, &next));
1779 ++state;
1780 break;
1781 case 1:
1782 if (0 != stricmp(p, "EXPORTS"))
1783 goto quit;
1784 ++state;
1785 break;
1786 case 2:
1787 dllindex = tcc_add_dllref(s1, dllname, 0)->index;
1788 ++state;
1789 /* fall through */
1790 default:
1791 /* get ordinal and will store in sym->st_value */
1792 ord = 0;
1793 if (next == '@') {
1794 x = get_token(&line, &next);
1795 ord = (int)strtol(x + 1, &x, 10);
1797 //printf("token %s ; %s : %d\n", dllname, p, ord);
1798 pe_putimport(s1, dllindex, p, ord);
1799 break;
1801 skip:
1802 while ((unsigned char)next > ' ')
1803 get_token(&line, &next);
1804 if (next != '\n')
1805 break;
1807 ret = 0;
1808 quit:
1809 tcc_free(buf);
1810 return ret;
1813 /* ------------------------------------------------------------- */
1815 static int pe_load_dll(TCCState *s1, int fd, const char *filename)
1817 char *p, *q;
1818 DLLReference *ref = tcc_add_dllref(s1, filename, 0);
1819 if (ref->found)
1820 return 0;
1821 if (get_dllexports(fd, &p))
1822 return -1;
1823 if (p) {
1824 for (q = p; *q; q += 1 + strlen(q))
1825 pe_putimport(s1, ref->index, q, 0);
1826 tcc_free(p);
1828 return 0;
1831 ST_FUNC int pe_load_file(struct TCCState *s1, int fd, const char *filename)
1833 int ret = -1;
1834 char buf[10];
1835 if (0 == strcmp(tcc_fileextension(filename), ".def"))
1836 ret = pe_load_def(s1, fd);
1837 else if (pe_load_res(s1, fd) == 0)
1838 ret = 0;
1839 else if (read_mem(fd, 0, buf, 4) && 0 == memcmp(buf, "MZ", 2))
1840 ret = pe_load_dll(s1, fd, filename);
1841 return ret;
1844 PUB_FUNC int tcc_get_dllexports(const char *filename, char **pp)
1846 int ret, fd = open(filename, O_RDONLY | O_BINARY);
1847 if (fd < 0)
1848 return -1;
1849 ret = get_dllexports(fd, pp);
1850 close(fd);
1851 return ret;
1854 /* ------------------------------------------------------------- */
1855 #ifdef TCC_TARGET_X86_64
1856 static unsigned pe_add_uwwind_info(TCCState *s1)
1858 if (NULL == s1->uw_pdata) {
1859 s1->uw_pdata = find_section(s1, ".pdata");
1860 s1->uw_pdata->sh_addralign = 4;
1862 if (0 == s1->uw_sym)
1863 s1->uw_sym = put_elf_sym(symtab_section, 0, 0, 0, 0, text_section->sh_num, ".uw_base");
1864 if (0 == s1->uw_offs) {
1865 /* As our functions all have the same stackframe, we use one entry for all */
1866 static const unsigned char uw_info[] = {
1867 0x01, // UBYTE: 3 Version , UBYTE: 5 Flags
1868 0x04, // UBYTE Size of prolog
1869 0x02, // UBYTE Count of unwind codes
1870 0x05, // UBYTE: 4 Frame Register (rbp), UBYTE: 4 Frame Register offset (scaled)
1871 // USHORT * n Unwind codes array
1872 // 0x0b, 0x01, 0xff, 0xff, // stack size
1873 0x04, 0x03, // set frame ptr (mov rsp -> rbp)
1874 0x01, 0x50 // push reg (rbp)
1877 Section *s = text_section;
1878 unsigned char *p;
1880 section_ptr_add(s, -s->data_offset & 3); /* align */
1881 s1->uw_offs = s->data_offset;
1882 p = section_ptr_add(s, sizeof uw_info);
1883 memcpy(p, uw_info, sizeof uw_info);
1886 return s1->uw_offs;
1889 ST_FUNC void pe_add_unwind_data(unsigned start, unsigned end, unsigned stack)
1891 TCCState *s1 = tcc_state;
1892 Section *pd;
1893 unsigned o, n, d;
1894 struct /* _RUNTIME_FUNCTION */ {
1895 DWORD BeginAddress;
1896 DWORD EndAddress;
1897 DWORD UnwindData;
1898 } *p;
1900 d = pe_add_uwwind_info(s1);
1901 pd = s1->uw_pdata;
1902 o = pd->data_offset;
1903 p = section_ptr_add(pd, sizeof *p);
1905 /* record this function */
1906 p->BeginAddress = start;
1907 p->EndAddress = end;
1908 p->UnwindData = d;
1910 /* put relocations on it */
1911 for (n = o + sizeof *p; o < n; o += sizeof p->BeginAddress)
1912 put_elf_reloc(symtab_section, pd, o, R_XXX_RELATIVE, s1->uw_sym);
1914 #endif
1915 /* ------------------------------------------------------------- */
1916 #ifdef TCC_TARGET_X86_64
1917 #define PE_STDSYM(n,s) n
1918 #else
1919 #define PE_STDSYM(n,s) "_" n s
1920 #endif
1922 static void pe_add_runtime(TCCState *s1, struct pe_info *pe)
1924 const char *start_symbol;
1925 int pe_type;
1927 if (TCC_OUTPUT_DLL == s1->output_type) {
1928 pe_type = PE_DLL;
1929 start_symbol = PE_STDSYM("__dllstart","@12");
1930 } else {
1931 const char *run_symbol;
1932 if (find_elf_sym(symtab_section, PE_STDSYM("WinMain","@16"))) {
1933 start_symbol = "__winstart";
1934 run_symbol = "__runwinmain";
1935 pe_type = PE_GUI;
1936 } else if (find_elf_sym(symtab_section, PE_STDSYM("wWinMain","@16"))) {
1937 start_symbol = "__wwinstart";
1938 run_symbol = "__runwwinmain";
1939 pe_type = PE_GUI;
1940 } else if (find_elf_sym(symtab_section, "wmain")) {
1941 start_symbol = "__wstart";
1942 run_symbol = "__runwmain";
1943 pe_type = PE_EXE;
1944 } else {
1945 start_symbol = "__start";
1946 run_symbol = "__runmain";
1947 pe_type = PE_EXE;
1948 if (s1->pe_subsystem == 2)
1949 pe_type = PE_GUI;
1952 if (TCC_OUTPUT_MEMORY == s1->output_type && !s1->nostdlib)
1953 start_symbol = run_symbol;
1955 if (s1->elf_entryname) {
1956 pe->start_symbol = start_symbol = s1->elf_entryname;
1957 } else {
1958 pe->start_symbol = start_symbol + 1;
1959 if (!s1->leading_underscore || strchr(start_symbol, '@'))
1960 ++start_symbol;
1963 #ifdef CONFIG_TCC_BACKTRACE
1964 if (s1->do_backtrace) {
1965 #ifdef CONFIG_TCC_BCHECK
1966 if (s1->do_bounds_check && s1->output_type != TCC_OUTPUT_DLL)
1967 tcc_add_support(s1, "bcheck.o");
1968 #endif
1969 if (s1->output_type == TCC_OUTPUT_EXE)
1970 tcc_add_support(s1, "bt-exe.o");
1971 if (s1->output_type == TCC_OUTPUT_DLL)
1972 tcc_add_support(s1, "bt-dll.o");
1973 if (s1->output_type != TCC_OUTPUT_DLL)
1974 tcc_add_support(s1, "bt-log.o");
1975 tcc_add_btstub(s1);
1977 #endif
1979 /* grab the startup code from libtcc1.a */
1980 #ifdef TCC_IS_NATIVE
1981 if (TCC_OUTPUT_MEMORY != s1->output_type || s1->run_main)
1982 #endif
1983 set_global_sym(s1, start_symbol, NULL, 0);
1985 if (0 == s1->nostdlib) {
1986 static const char * const libs[] = {
1987 "msvcrt", "kernel32", "", "user32", "gdi32", NULL
1989 const char * const *pp, *p;
1990 if (TCC_LIBTCC1[0])
1991 tcc_add_support(s1, TCC_LIBTCC1);
1992 for (pp = libs; 0 != (p = *pp); ++pp) {
1993 if (*p)
1994 tcc_add_library_err(s1, p);
1995 else if (PE_DLL != pe_type && PE_GUI != pe_type)
1996 break;
2000 /* need this for 'tccelf.c:relocate_sections()' */
2001 if (TCC_OUTPUT_DLL == s1->output_type)
2002 s1->output_type = TCC_OUTPUT_EXE;
2003 if (TCC_OUTPUT_MEMORY == s1->output_type)
2004 pe_type = PE_RUN;
2005 pe->type = pe_type;
2008 static void pe_set_options(TCCState * s1, struct pe_info *pe)
2010 if (PE_DLL == pe->type) {
2011 /* XXX: check if is correct for arm-pe target */
2012 pe->imagebase = 0x10000000;
2013 } else {
2014 #if defined(TCC_TARGET_ARM)
2015 pe->imagebase = 0x00010000;
2016 #else
2017 pe->imagebase = 0x00400000;
2018 #endif
2021 #if defined(TCC_TARGET_ARM)
2022 /* we use "console" subsystem by default */
2023 pe->subsystem = 9;
2024 #else
2025 if (PE_DLL == pe->type || PE_GUI == pe->type)
2026 pe->subsystem = 2;
2027 else
2028 pe->subsystem = 3;
2029 #endif
2030 /* Allow override via -Wl,-subsystem=... option */
2031 if (s1->pe_subsystem != 0)
2032 pe->subsystem = s1->pe_subsystem;
2034 /* set default file/section alignment */
2035 if (pe->subsystem == 1) {
2036 pe->section_align = 0x20;
2037 pe->file_align = 0x20;
2038 } else {
2039 pe->section_align = 0x1000;
2040 pe->file_align = 0x200;
2043 if (s1->section_align != 0)
2044 pe->section_align = s1->section_align;
2045 if (s1->pe_file_align != 0)
2046 pe->file_align = s1->pe_file_align;
2048 if ((pe->subsystem >= 10) && (pe->subsystem <= 12))
2049 pe->imagebase = 0;
2051 if (s1->has_text_addr)
2052 pe->imagebase = s1->text_addr;
2055 ST_FUNC int pe_output_file(TCCState *s1, const char *filename)
2057 struct pe_info pe;
2059 memset(&pe, 0, sizeof pe);
2060 pe.filename = filename;
2061 pe.s1 = s1;
2062 s1->filetype = 0;
2064 #ifdef CONFIG_TCC_BCHECK
2065 tcc_add_bcheck(s1);
2066 #endif
2067 pe_add_runtime(s1, &pe);
2068 tcc_add_pragma_libs(s1);
2069 resolve_common_syms(s1);
2070 pe_set_options(s1, &pe);
2071 pe_check_symbols(&pe);
2073 if (s1->nb_errors)
2075 else if (filename) {
2076 pe_assign_addresses(&pe);
2077 relocate_syms(s1, s1->symtab, 0);
2078 s1->pe_imagebase = pe.imagebase;
2079 relocate_sections(s1);
2080 pe.start_addr = (DWORD)
2081 (get_sym_addr(s1, pe.start_symbol, 1, 1) - pe.imagebase);
2082 if (0 == s1->nb_errors)
2083 pe_write(&pe);
2084 dynarray_reset(&pe.sec_info, &pe.sec_count);
2085 } else {
2086 #ifdef TCC_IS_NATIVE
2087 pe.thunk = data_section;
2088 pe_build_imports(&pe);
2089 s1->run_main = pe.start_symbol;
2090 #ifdef TCC_TARGET_X86_64
2091 s1->uw_pdata = find_section(s1, ".pdata");
2092 #endif
2093 #endif
2095 pe_free_imports(&pe);
2096 #if PE_PRINT_SECTIONS
2097 if (s1->g_debug & 8)
2098 pe_print_sections(s1, "tcc.log");
2099 #endif
2100 return s1->nb_errors ? -1 : 0;
2103 /* ------------------------------------------------------------- */