History

initial PE format support

bellard committed 21 years ago

Commit 2c538d71 parent bdd09705 files · +1314 −19Browse files

Unified · Split

5 files
  1. Makefile +4 −1
  2. tcc.c +88 −12
  3. tccelf.c +1 −6
  4. tccpe.c +1220 −0
  5. tcctok.h +1 −0
Makefile+4−1
@@ -20,7 +20,7 @@ endif · 19 unmodified lines
20 20
21DISAS=objdump -d21DISAS=objdump -d
22INSTALL=install22INSTALL=install
23PROGS=tcc$(EXESUF) c67-tcc$(EXESUF) arm-tcc$(EXESUF)23PROGS=tcc$(EXESUF) c67-tcc$(EXESUF) arm-tcc$(EXESUF) i386-win32-tcc$(EXESUF)
24# run local version of tcc with local libraries and includes24# run local version of tcc with local libraries and includes
25TCC=./tcc -B. -I.25TCC=./tcc -B. -I.
26 26
@@ -125,6 +125,9 @@ c67-tcc$(EXESUF): tcc.c c67-gen.c tccelf.c tccasm.c tcctok.h libtcc.h tcccoff.c · 98 unmodified lines
125arm-tcc$(EXESUF): tcc.c arm-gen.c tccelf.c tccasm.c tcctok.h libtcc.h Makefile125arm-tcc$(EXESUF): tcc.c arm-gen.c tccelf.c tccasm.c tcctok.h libtcc.h Makefile
126 $(CC) $(CFLAGS) -DTCC_TARGET_ARM -o $@ $< $(LIBS)126 $(CC) $(CFLAGS) -DTCC_TARGET_ARM -o $@ $< $(LIBS)
127 127
128i386-win32-tcc$(EXESUF): tcc.c i386-gen.c tccelf.c tccasm.c i386-asm.c tcctok.h libtcc.h i386-asm.h tccpe.c Makefile
129 $(CC) $(CFLAGS) -DTCC_TARGET_PE -o $@ $< $(LIBS)
130
128# TinyCC runtime libraries131# TinyCC runtime libraries
129libtcc1.o: libtcc1.c132libtcc1.o: libtcc1.c
130 $(CC) -O2 -Wall -c -o $@ $<133 $(CC) -O2 -Wall -c -o $@ $<
tcc.c+88−12
@@ -35,13 +35,11 @@ · 34 unmodified lines
35#include <math.h>35#include <math.h>
36#include <unistd.h>36#include <unistd.h>
37#include <signal.h>37#include <signal.h>
38#include <unistd.h>
39#include <fcntl.h>38#include <fcntl.h>
40#include <setjmp.h>39#include <setjmp.h>
41#include <time.h>40#include <time.h>
42#ifdef WIN3241#ifdef WIN32
43#include <sys/timeb.h>42#include <sys/timeb.h>
44#define CONFIG_TCC_STATIC
45#endif43#endif
46#ifndef WIN3244#ifndef WIN32
47#include <sys/time.h>45#include <sys/time.h>
@@ -52,9 +50,7 @@ · 4 unmodified lines
52 50
53#include "elf.h"51#include "elf.h"
54#include "stab.h"52#include "stab.h"
55#ifndef CONFIG_TCC_STATIC53
56#include <dlfcn.h>
57#endif
58#ifndef O_BINARY54#ifndef O_BINARY
59#define O_BINARY 055#define O_BINARY 0
60#endif56#endif
@@ -218,6 +214,7 @@ typedef struct AttributeDef { · 157 unmodified lines
218 int packed; 214 int packed;
219 Section *section;215 Section *section;
220 unsigned char func_call; /* FUNC_CDECL, FUNC_STDCALL, FUNC_FASTCALLx */216 unsigned char func_call; /* FUNC_CDECL, FUNC_STDCALL, FUNC_FASTCALLx */
217 unsigned char dllexport;
221} AttributeDef;218} AttributeDef;
222 219
223#define SYM_STRUCT 0x40000000 /* struct/union/enum symbol space */220#define SYM_STRUCT 0x40000000 /* struct/union/enum symbol space */
@@ -719,6 +716,7 @@ extern long double strtold (const char *__nptr, char **__endptr); · 495 unmodified lines
719 716
720static char *pstrcpy(char *buf, int buf_size, const char *s);717static char *pstrcpy(char *buf, int buf_size, const char *s);
721static char *pstrcat(char *buf, int buf_size, const char *s);718static char *pstrcat(char *buf, int buf_size, const char *s);
719static const char *tcc_basename(const char *name);
722 720
723static void next(void);721static void next(void);
724static void next_nomacro(void);722static void next_nomacro(void);
@@ -809,6 +807,13 @@ static int tcc_add_file_internal(TCCState *s, const char *filename, int flags); · 84 unmodified lines
809/* tcccoff.c */807/* tcccoff.c */
810int tcc_output_coff(TCCState *s1, FILE *f);808int tcc_output_coff(TCCState *s1, FILE *f);
811 809
810/* tccpe.c */
811void *resolve_sym(TCCState *s1, const char *sym, int type);
812int pe_load_def_file(struct TCCState *s1, FILE *fp);
813void pe_setup_paths(struct TCCState *s1, int *p_output_type, const char **p_outfile, char *first_file);
814unsigned long pe_add_runtime(struct TCCState *s1);
815int tcc_output_pe(struct TCCState *s1, const char *filename);
816
812/* tccasm.c */817/* tccasm.c */
813 818
814#ifdef CONFIG_TCC_ASM819#ifdef CONFIG_TCC_ASM
@@ -902,7 +907,7 @@ static TCCSyms tcc_syms[] = { · 87 unmodified lines
902 { NULL, NULL },907 { NULL, NULL },
903};908};
904 909
905void *dlsym(void *handle, const char *symbol)910void *resolve_sym(TCCState *s1, const char *symbol, int type)
906{911{
907 TCCSyms *p;912 TCCSyms *p;
908 p = tcc_syms;913 p = tcc_syms;
@@ -914,6 +919,15 @@ void *dlsym(void *handle, const char *symbol) · 5 unmodified lines
914 return NULL;919 return NULL;
915}920}
916 921
922#elif !defined(WIN32)
923
924#include <dlfcn.h>
925
926void *resolve_sym(TCCState *s1, const char *sym, int type)
927{
928 return dlsym(RTLD_DEFAULT, sym);
929}
930
917#endif931#endif
918 932
919/********************************************************/933/********************************************************/
@@ -6290,6 +6304,9 @@ static void parse_attribute(AttributeDef *ad) · 5370 unmodified lines
6290 skip(')');6304 skip(')');
6291 break;6305 break;
6292#endif6306#endif
6307 case TOK_DLLEXPORT:
6308 ad->dllexport = 1;
6309 break;
6293 default:6310 default:
6294 if (tcc_state->warn_unsupported)6311 if (tcc_state->warn_unsupported)
6295 warning("'%s' attribute ignored", get_tok_str(t, NULL));6312 warning("'%s' attribute ignored", get_tok_str(t, NULL));
@@ -9195,6 +9212,10 @@ static void asm_global_instr(void) · 2899 unmodified lines
9195#include "tcccoff.c"9212#include "tcccoff.c"
9196#endif9213#endif
9197 9214
9215#ifdef TCC_TARGET_PE
9216#include "tccpe.c"
9217#endif
9218
9198/* print the position in the source file of PC value 'pc' by reading9219/* print the position in the source file of PC value 'pc' by reading
9199 the stabs debug information */9220 the stabs debug information */
9200static void rt_printline(unsigned long wanted_pc)9221static void rt_printline(unsigned long wanted_pc)
@@ -9442,7 +9463,11 @@ int tcc_relocate(TCCState *s1) · 241 unmodified lines
9442 9463
9443 s1->nb_errors = 0;9464 s1->nb_errors = 0;
9444 9465
9466#ifdef TCC_TARGET_PE
9467 pe_add_runtime(s1);
9468#else
9445 tcc_add_runtime(s1);9469 tcc_add_runtime(s1);
9470#endif
9446 9471
9447 relocate_common_syms();9472 relocate_common_syms();
9448 9473
@@ -9588,9 +9613,17 @@ TCCState *tcc_new(void) · 139 unmodified lines
9588 tcc_define_symbol(s, "__WCHAR_TYPE__", "int");9613 tcc_define_symbol(s, "__WCHAR_TYPE__", "int");
9589 9614
9590 /* default library paths */9615 /* default library paths */
9616#ifdef TCC_TARGET_PE
9617 {
9618 char buf[1024];
9619 snprintf(buf, sizeof(buf), "%s/lib", tcc_lib_path);
9620 tcc_add_library_path(s, buf);
9621 }
9622#else
9591 tcc_add_library_path(s, "/usr/local/lib");9623 tcc_add_library_path(s, "/usr/local/lib");
9592 tcc_add_library_path(s, "/usr/lib");9624 tcc_add_library_path(s, "/usr/lib");
9593 tcc_add_library_path(s, "/lib");9625 tcc_add_library_path(s, "/lib");
9626#endif
9594 9627
9595 /* no section zero */9628 /* no section zero */
9596 dynarray_add((void ***)&s->sections, &s->nb_sections, NULL);9629 dynarray_add((void ***)&s->sections, &s->nb_sections, NULL);
@@ -9727,6 +9760,11 @@ static int tcc_add_file_internal(TCCState *s1, const char *filename, int flags) · 130 unmodified lines
9727 /* non preprocessed assembler */9760 /* non preprocessed assembler */
9728 ret = tcc_assemble(s1, 0);9761 ret = tcc_assemble(s1, 0);
9729 } else 9762 } else
9763#endif
9764#ifdef TCC_TARGET_PE
9765 if (!strcmp(ext, "def")) {
9766 ret = pe_load_def_file(s1, fdopen(file->fd, "rb"));
9767 } else
9730#endif9768#endif
9731 {9769 {
9732 fd = file->fd;9770 fd = file->fd;
@@ -9749,12 +9787,16 @@ static int tcc_add_file_internal(TCCState *s1, const char *filename, int flags) · 16 unmodified lines
9749 ret = tcc_load_object_file(s1, fd, 0);9787 ret = tcc_load_object_file(s1, fd, 0);
9750 } else if (ehdr.e_type == ET_DYN) {9788 } else if (ehdr.e_type == ET_DYN) {
9751 if (s1->output_type == TCC_OUTPUT_MEMORY) {9789 if (s1->output_type == TCC_OUTPUT_MEMORY) {
9790#ifdef TCC_TARGET_PE
9791 ret = -1;
9792#else
9752 void *h;9793 void *h;
9753 h = dlopen(filename, RTLD_GLOBAL | RTLD_LAZY);9794 h = dlopen(filename, RTLD_GLOBAL | RTLD_LAZY);
9754 if (h)9795 if (h)
9755 ret = 0;9796 ret = 0;
9756 else9797 else
9757 ret = -1;9798 ret = -1;
9799#endif
9758 } else {9800 } else {
9759 ret = tcc_load_dll(s1, fd, filename, 9801 ret = tcc_load_dll(s1, fd, filename,
9760 (flags & AFF_REFERENCED_DLL) != 0);9802 (flags & AFF_REFERENCED_DLL) != 0);
@@ -9830,7 +9872,11 @@ int tcc_add_library(TCCState *s, const char *libraryname) · 69 unmodified lines
9830 9872
9831 /* first we look for the dynamic library if not static linking */9873 /* first we look for the dynamic library if not static linking */
9832 if (!s->static_link) {9874 if (!s->static_link) {
9875#ifdef TCC_TARGET_PE
9876 snprintf(buf, sizeof(buf), "%s.def", libraryname);
9877#else
9833 snprintf(buf, sizeof(buf), "lib%s.so", libraryname);9878 snprintf(buf, sizeof(buf), "lib%s.so", libraryname);
9879#endif
9834 if (tcc_add_dll(s, buf, 0) == 0)9880 if (tcc_add_dll(s, buf, 0) == 0)
9835 return 0;9881 return 0;
9836 }9882 }
@@ -9855,17 +9901,23 @@ int tcc_add_symbol(TCCState *s, const char *name, unsigned long val) · 18 unmodified lines
9855 9901
9856int tcc_set_output_type(TCCState *s, int output_type)9902int tcc_set_output_type(TCCState *s, int output_type)
9857{9903{
9858 char buf[1024];
9859
9860 s->output_type = output_type;9904 s->output_type = output_type;
9861 9905
9862 if (!s->nostdinc) {9906 if (!s->nostdinc) {
9907 char buf[1024];
9908
9863 /* default include paths */9909 /* default include paths */
9864 /* XXX: reverse order needed if -isystem support */9910 /* XXX: reverse order needed if -isystem support */
9911#ifndef TCC_TARGET_PE
9865 tcc_add_sysinclude_path(s, "/usr/local/include");9912 tcc_add_sysinclude_path(s, "/usr/local/include");
9866 tcc_add_sysinclude_path(s, "/usr/include");9913 tcc_add_sysinclude_path(s, "/usr/include");
9914#endif
9867 snprintf(buf, sizeof(buf), "%s/include", tcc_lib_path);9915 snprintf(buf, sizeof(buf), "%s/include", tcc_lib_path);
9868 tcc_add_sysinclude_path(s, buf);9916 tcc_add_sysinclude_path(s, buf);
9917#ifdef TCC_TARGET_PE
9918 snprintf(buf, sizeof(buf), "%s/include/winapi", tcc_lib_path);
9919 tcc_add_sysinclude_path(s, buf);
9920#endif
9869 }9921 }
9870 9922
9871 /* if bound checking, then add corresponding sections */9923 /* if bound checking, then add corresponding sections */
@@ -9898,12 +9950,14 @@ int tcc_set_output_type(TCCState *s, int output_type) · 26 unmodified lines
9898 }9950 }
9899 9951
9900 /* add libc crt1/crti objects */9952 /* add libc crt1/crti objects */
9953#ifndef TCC_TARGET_PE
9901 if ((output_type == TCC_OUTPUT_EXE || output_type == TCC_OUTPUT_DLL) &&9954 if ((output_type == TCC_OUTPUT_EXE || output_type == TCC_OUTPUT_DLL) &&
9902 !s->nostdlib) {9955 !s->nostdlib) {
9903 if (output_type != TCC_OUTPUT_DLL)9956 if (output_type != TCC_OUTPUT_DLL)
9904 tcc_add_file(s, CONFIG_TCC_CRT_PREFIX "/crt1.o");9957 tcc_add_file(s, CONFIG_TCC_CRT_PREFIX "/crt1.o");
9905 tcc_add_file(s, CONFIG_TCC_CRT_PREFIX "/crti.o");9958 tcc_add_file(s, CONFIG_TCC_CRT_PREFIX "/crti.o");
9906 }9959 }
9960#endif
9907 return 0;9961 return 0;
9908}9962}
9909 9963
@@ -10013,7 +10067,7 @@ static int64_t getclock_us(void) · 103 unmodified lines
10013 10067
10014void help(void)10068void help(void)
10015{10069{
10016 printf("tcc version " TCC_VERSION " - Tiny C Compiler - Copyright (C) 2001-2004 Fabrice Bellard\n"10070 printf("tcc version " TCC_VERSION " - Tiny C Compiler - Copyright (C) 2001-2005 Fabrice Bellard\n"
10017 "usage: tcc [-v] [-c] [-o outfile] [-Bdir] [-bench] [-Idir] [-Dsym[=val]] [-Usym]\n"10071 "usage: tcc [-v] [-c] [-o outfile] [-Bdir] [-bench] [-Idir] [-Dsym[=val]] [-Usym]\n"
10018 " [-Wwarn] [-g] [-b] [-bt N] [-Ldir] [-llib] [-shared] [-static]\n"10072 " [-Wwarn] [-g] [-b] [-bt N] [-Ldir] [-llib] [-shared] [-static]\n"
10019 " [infile1 infile2...] [-run infile args...]\n"10073 " [infile1 infile2...] [-run infile args...]\n"
@@ -10370,6 +10424,22 @@ int main(int argc, char **argv) · 350 unmodified lines
10370 char objfilename[1024];10424 char objfilename[1024];
10371 int64_t start_time = 0;10425 int64_t start_time = 0;
10372 10426
10427#ifdef WIN32
10428 /* on win32, we suppose the lib and includes are at the location
10429 of 'tcc.exe' */
10430 {
10431 static char path[1024];
10432
10433 GetModuleFileNameA(NULL, path, sizeof path);
10434 p = d = strlwr(path);
10435 while (*d)
10436 if (*d++ == '\\')
10437 (p = d)[-1] = '/';
10438 *p = '\0';
10439 tcc_lib_path = path;
10440 }
10441#endif
10442
10373 s = tcc_new();10443 s = tcc_new();
10374 output_type = TCC_OUTPUT_EXE;10444 output_type = TCC_OUTPUT_EXE;
10375 outfile = NULL;10445 outfile = NULL;
@@ -10461,11 +10531,17 @@ int main(int argc, char **argv) · 85 unmodified lines
10461 total_bytes / total_time / 1000000.0); 10531 total_bytes / total_time / 1000000.0);
10462 }10532 }
10463 10533
10464 if (s->output_type != TCC_OUTPUT_MEMORY) {10534 if (s->output_type == TCC_OUTPUT_MEMORY) {
10535 ret = tcc_run(s, argc - optind, argv + optind);
10536 } else
10537#ifdef TCC_TARGET_PE
10538 if (s->output_type != TCC_OUTPUT_OBJ) {
10539 ret = tcc_output_pe(s, outfile);
10540 } else
10541#endif
10542 {
10465 tcc_output_file(s, outfile);10543 tcc_output_file(s, outfile);
10466 ret = 0;10544 ret = 0;
10467 } else {
10468 ret = tcc_run(s, argc - optind, argv + optind);
10469 }10545 }
10470 the_end:10546 the_end:
10471 /* XXX: cannot do it with bound checking because of the malloc hooks */10547 /* XXX: cannot do it with bound checking because of the malloc hooks */
tccelf.c+1−6
@@ -385,11 +385,6 @@ static void relocate_common_syms(void) · 384 unmodified lines
385 }385 }
386}386}
387 387
388static void *resolve_sym(const char *sym)
389{
390 return dlsym(RTLD_DEFAULT, sym);
391}
392
393/* relocate symbol table, resolve undefined symbols if do_resolve is388/* relocate symbol table, resolve undefined symbols if do_resolve is
394 true and output error if undefined symbol. */389 true and output error if undefined symbol. */
395static void relocate_syms(TCCState *s1, int do_resolve)390static void relocate_syms(TCCState *s1, int do_resolve)
@@ -408,7 +403,7 @@ static void relocate_syms(TCCState *s1, int do_resolve) · 12 unmodified lines
408 name = strtab_section->data + sym->st_name;403 name = strtab_section->data + sym->st_name;
409 if (do_resolve) {404 if (do_resolve) {
410 name = symtab_section->link->data + sym->st_name;405 name = symtab_section->link->data + sym->st_name;
411 addr = (unsigned long)resolve_sym(name);406 addr = (unsigned long)resolve_sym(s1, name, ELF32_ST_TYPE(sym->st_info));
412 if (addr) {407 if (addr) {
413 sym->st_value = addr;408 sym->st_value = addr;
414 goto found;409 goto found;
tccpe.c+1220−0
@@ -0,0 +1,1220 @@
1/*
2 * TCCPE.C - PE file output for the TinyC Compiler
3 *
4 * Copyright (c) 2005 grischka
5 *
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.
10 *
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.
15 *
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
19 */
20
21typedef unsigned char BYTE;
22typedef unsigned short WORD;
23typedef unsigned long DWORD;
24#define ST static
25
26/* XXX: move that to TCC ? */
27int verbose = 0;
28
29/* definitions below are from winnt.h */
30
31typedef struct _IMAGE_DOS_HEADER { /* DOS .EXE header */
32 WORD e_magic; /* Magic number */
33 WORD e_cblp; /* Bytes on last page of file */
34 WORD e_cp; /* Pages in file */
35 WORD e_crlc; /* Relocations */
36 WORD e_cparhdr; /* Size of header in paragraphs */
37 WORD e_minalloc; /* Minimum extra paragraphs needed */
38 WORD e_maxalloc; /* Maximum extra paragraphs needed */
39 WORD e_ss; /* Initial (relative) SS value */
40 WORD e_sp; /* Initial SP value */
41 WORD e_csum; /* Checksum */
42 WORD e_ip; /* Initial IP value */
43 WORD e_cs; /* Initial (relative) CS value */
44 WORD e_lfarlc; /* File address of relocation table */
45 WORD e_ovno; /* Overlay number */
46 WORD e_res[4]; /* Reserved words */
47 WORD e_oemid; /* OEM identifier (for e_oeminfo) */
48 WORD e_oeminfo; /* OEM information; e_oemid specific */
49 WORD e_res2[10]; /* Reserved words */
50 DWORD e_lfanew; /* File address of new exe header */
51 BYTE e_code[0x40];
52
53} IMAGE_DOS_HEADER, *PIMAGE_DOS_HEADER;
54
55#define IMAGE_NT_SIGNATURE 0x00004550 /* PE00 */
56#define SIZE_OF_NT_SIGNATURE 4
57
58typedef struct _IMAGE_FILE_HEADER {
59 WORD Machine;
60 WORD NumberOfSections;
61 DWORD TimeDateStamp;
62 DWORD PointerToSymbolTable;
63 DWORD NumberOfSymbols;
64 WORD SizeOfOptionalHeader;
65 WORD Characteristics;
66} IMAGE_FILE_HEADER, *PIMAGE_FILE_HEADER;
67
68
69#define IMAGE_SIZEOF_FILE_HEADER 20
70
71typedef struct _IMAGE_DATA_DIRECTORY {
72 DWORD VirtualAddress;
73 DWORD Size;
74} IMAGE_DATA_DIRECTORY, *PIMAGE_DATA_DIRECTORY;
75
76
77typedef struct _IMAGE_OPTIONAL_HEADER {
78 /* Standard fields. */
79 WORD Magic;
80 BYTE MajorLinkerVersion;
81 BYTE MinorLinkerVersion;
82 DWORD SizeOfCode;
83 DWORD SizeOfInitializedData;
84 DWORD SizeOfUninitializedData;
85 DWORD AddressOfEntryPoint;
86 DWORD BaseOfCode;
87 DWORD BaseOfData;
88
89 /* NT additional fields. */
90 DWORD ImageBase;
91 DWORD SectionAlignment;
92 DWORD FileAlignment;
93 WORD MajorOperatingSystemVersion;
94 WORD MinorOperatingSystemVersion;
95 WORD MajorImageVersion;
96 WORD MinorImageVersion;
97 WORD MajorSubsystemVersion;
98 WORD MinorSubsystemVersion;
99 DWORD Win32VersionValue;
100 DWORD SizeOfImage;
101 DWORD SizeOfHeaders;
102 DWORD CheckSum;
103 WORD Subsystem;
104 WORD DllCharacteristics;
105 DWORD SizeOfStackReserve;
106 DWORD SizeOfStackCommit;
107 DWORD SizeOfHeapReserve;
108 DWORD SizeOfHeapCommit;
109 DWORD LoaderFlags;
110 DWORD NumberOfRvaAndSizes;
111 IMAGE_DATA_DIRECTORY DataDirectory[16];
112
113} IMAGE_OPTIONAL_HEADER32, *PIMAGE_OPTIONAL_HEADER32;
114
115
116#define IMAGE_DIRECTORY_ENTRY_EXPORT 0 /* Export Directory */
117#define IMAGE_DIRECTORY_ENTRY_IMPORT 1 /* Import Directory */
118#define IMAGE_DIRECTORY_ENTRY_RESOURCE 2 /* Resource Directory */
119#define IMAGE_DIRECTORY_ENTRY_EXCEPTION 3 /* Exception Directory */
120#define IMAGE_DIRECTORY_ENTRY_SECURITY 4 /* Security Directory */
121#define IMAGE_DIRECTORY_ENTRY_BASERELOC 5 /* Base Relocation Table */
122#define IMAGE_DIRECTORY_ENTRY_DEBUG 6 /* Debug Directory */
123/* IMAGE_DIRECTORY_ENTRY_COPYRIGHT 7 (X86 usage) */
124#define IMAGE_DIRECTORY_ENTRY_ARCHITECTURE 7 /* Architecture Specific Data */
125#define IMAGE_DIRECTORY_ENTRY_GLOBALPTR 8 /* RVA of GP */
126#define IMAGE_DIRECTORY_ENTRY_TLS 9 /* TLS Directory */
127#define IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG 10 /* Load Configuration Directory */
128#define IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT 11 /* Bound Import Directory in headers */
129#define IMAGE_DIRECTORY_ENTRY_IAT 12 /* Import Address Table */
130#define IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT 13 /* Delay Load Import Descriptors */
131#define IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR 14 /* COM Runtime descriptor */
132
133/* Section header format. */
134#define IMAGE_SIZEOF_SHORT_NAME 8
135
136typedef struct _IMAGE_SECTION_HEADER {
137 BYTE Name[IMAGE_SIZEOF_SHORT_NAME];
138 union {
139 DWORD PhysicalAddress;
140 DWORD VirtualSize;
141 } Misc;
142 DWORD VirtualAddress;
143 DWORD SizeOfRawData;
144 DWORD PointerToRawData;
145 DWORD PointerToRelocations;
146 DWORD PointerToLinenumbers;
147 WORD NumberOfRelocations;
148 WORD NumberOfLinenumbers;
149 DWORD Characteristics;
150} IMAGE_SECTION_HEADER, *PIMAGE_SECTION_HEADER;
151
152#define IMAGE_SIZEOF_SECTION_HEADER 40
153
154/* ----------------------------------------------------------- */
155typedef struct _IMAGE_BASE_RELOCATION {
156 DWORD VirtualAddress;
157 DWORD SizeOfBlock;
158// WORD TypeOffset[1];
159} IMAGE_BASE_RELOCATION;
160
161#define IMAGE_SIZEOF_BASE_RELOCATION 8
162
163#define IMAGE_REL_BASED_ABSOLUTE 0
164#define IMAGE_REL_BASED_HIGH 1
165#define IMAGE_REL_BASED_LOW 2
166#define IMAGE_REL_BASED_HIGHLOW 3
167#define IMAGE_REL_BASED_HIGHADJ 4
168#define IMAGE_REL_BASED_MIPS_JMPADDR 5
169#define IMAGE_REL_BASED_SECTION 6
170#define IMAGE_REL_BASED_REL32 7
171
172/* ----------------------------------------------------------- */
173
174/* ----------------------------------------------------------- */
175IMAGE_DOS_HEADER pe_dos_hdr = {
176 0x5A4D, /*WORD e_magic; Magic number */
177 0x0090, /*WORD e_cblp; Bytes on last page of file */
178 0x0003, /*WORD e_cp; Pages in file */
179 0x0000, /*WORD e_crlc; Relocations */
180
181 0x0004, /*WORD e_cparhdr; Size of header in paragraphs */
182 0x0000, /*WORD e_minalloc; Minimum extra paragraphs needed */
183 0xFFFF, /*WORD e_maxalloc; Maximum extra paragraphs needed */
184 0x0000, /*WORD e_ss; Initial (relative) SS value */
185
186 0x00B8, /*WORD e_sp; Initial SP value */
187 0x0000, /*WORD e_csum; Checksum */
188 0x0000, /*WORD e_ip; Initial IP value */
189 0x0000, /*WORD e_cs; Initial (relative) CS value */
190 0x0040, /*WORD e_lfarlc; File address of relocation table */
191 0x0000, /*WORD e_ovno; Overlay number */
192 {0, 0, 0, 0}, /*WORD e_res[4]; Reserved words */
193 0x0000, /*WORD e_oemid; OEM identifier (for e_oeminfo) */
194 0x0000, /*WORD e_oeminfo; OEM information; e_oemid specific */
195 {0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, /*WORD e_res2[10]; Reserved words */
196 0x00000080, /*DWORD e_lfanew; File address of new exe header */
197 { /* 14 code bytes + "This program cannot be run in DOS mode.\r\r\n$" + 6 * 0x00 */
198 /*0040 */ 0x0e, 0x1f, 0xba, 0x0e, 0x00, 0xb4, 0x09, 0xcd, 0x21, 0xb8,
199 0x01, 0x4c, 0xcd, 0x21, 0x54, 0x68,
200 /*0050 */ 0x69, 0x73, 0x20, 0x70, 0x72, 0x6f, 0x67, 0x72, 0x61, 0x6d,
201 0x20, 0x63, 0x61, 0x6e, 0x6e, 0x6f,
202 /*0060 */ 0x74, 0x20, 0x62, 0x65, 0x20, 0x72, 0x75, 0x6e, 0x20, 0x69,
203 0x6e, 0x20, 0x44, 0x4f, 0x53, 0x20,
204 /*0070 */ 0x6d, 0x6f, 0x64, 0x65, 0x2e, 0x0d, 0x0d, 0x0a, 0x24, 0x00,
205 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
206 /*0080 */
207 }
208};
209
210DWORD pe_magic = IMAGE_NT_SIGNATURE;
211
212IMAGE_FILE_HEADER pe_file_hdr = {
213 0x014C, /*WORD Machine; */
214 0x0003, /*WORD NumberOfSections; */
215 0x00000000, /*DWORD TimeDateStamp; */
216 0x00000000, /*DWORD PointerToSymbolTable; */
217 0x00000000, /*DWORD NumberOfSymbols; */
218 0x00E0, /*WORD SizeOfOptionalHeader; */
219 0x030F /*WORD Characteristics; */
220};
221
222IMAGE_OPTIONAL_HEADER32 pe_opt_hdr = {
223 /* Standard fields. */
224 0x010B, /*WORD Magic; */
225 0x06, /*BYTE MajorLinkerVersion; */
226 0x00, /*BYTE MinorLinkerVersion; */
227 0x00000000, /*DWORD SizeOfCode; */
228 0x00000000, /*DWORD SizeOfInitializedData; */
229 0x00000000, /*DWORD SizeOfUninitializedData; */
230 0x00000000, /*DWORD AddressOfEntryPoint; */
231 0x00000000, /*DWORD BaseOfCode; */
232 0x00000000, /*DWORD BaseOfData; */
233
234 /* NT additional fields. */
235 0x00400000, /*DWORD ImageBase; */
236 0x00001000, /*DWORD SectionAlignment; */
237 0x00000200, /*DWORD FileAlignment; */
238 0x0004, /*WORD MajorOperatingSystemVersion; */
239 0x0000, /*WORD MinorOperatingSystemVersion; */
240 0x0000, /*WORD MajorImageVersion; */
241 0x0000, /*WORD MinorImageVersion; */
242 0x0004, /*WORD MajorSubsystemVersion; */
243 0x0000, /*WORD MinorSubsystemVersion; */
244 0x00000000, /*DWORD Win32VersionValue; */
245 0x00000000, /*DWORD SizeOfImage; */
246 0x00000200, /*DWORD SizeOfHeaders; */
247 0x00000000, /*DWORD CheckSum; */
248 0x0002, /*WORD Subsystem; */
249 0x0000, /*WORD DllCharacteristics; */
250 0x00100000, /*DWORD SizeOfStackReserve; */
251 0x00001000, /*DWORD SizeOfStackCommit; */
252 0x00100000, /*DWORD SizeOfHeapReserve; */
253 0x00001000, /*DWORD SizeOfHeapCommit; */
254 0x00000000, /*DWORD LoaderFlags; */
255 0x00000010, /*DWORD NumberOfRvaAndSizes; */
256
257 /* IMAGE_DATA_DIRECTORY DataDirectory[16]; */
258 {{0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0},
259 {0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}}
260};
261
262/*----------------------------------------------------------------------------*/
263
264/*----------------------------------------------------------------------------*/
265
266struct pe_import_header {
267 DWORD first_entry;
268 DWORD time_date;
269 DWORD forwarder;
270 DWORD lib_name_offset;
271 DWORD first_thunk;
272};
273
274struct pe_export_header {
275 DWORD Characteristics;
276 DWORD TimeDateStamp;
277 DWORD Version;
278 DWORD Name;
279 DWORD Base;
280 DWORD NumberOfFunctions;
281 DWORD NumberOfNames;
282 DWORD AddressOfFunctions;
283 DWORD AddressOfNames;
284 DWORD AddressOfNameOrdinals;
285};
286
287struct pe_reloc_header {
288 DWORD offset;
289 DWORD size;
290};
291
292/* ------------------------------------------------------------- */
293/* internal temporary structures */
294
295ST const char *pe_sec_names[] = {
296 ".text",
297 ".data",
298 ".bss",
299 ".rsrc",
300 ".reloc",
301 ".stab",
302 ".stabstr"
303};
304
305enum {
306 sec_text = 0,
307 sec_data,
308 sec_bss,
309 sec_rsrc,
310 sec_reloc,
311 sec_stab,
312 sec_stabstr,
313 pe_sec_number
314};
315
316ST DWORD pe_flags[] = {
317 0x60000020, /* ".text", */
318 0xC0000040, /* ".data", */
319 0xC0000080, /* ".bss", */
320 0x40000040, /* ".rsrc", */
321 0x42000040, /* ".reloc", */
322 0x42000802, /* ".stab", */
323 0x42000802 /* ".stabstr", */
324};
325
326struct section_info {
327 struct section_info *next;
328 int id;
329 DWORD sh_addr;
330 DWORD sh_size;
331 unsigned char *data;
332 DWORD data_size;
333};
334
335struct import_symbol {
336 int sym_index;
337 int offset;
338};
339
340struct pe_import_info {
341 int dll_index;
342 int sym_count;
343 struct import_symbol **symbols;
344};
345
346struct pe_info {
347 const char *filename;
348 DWORD sizeofheaders;
349 DWORD imagebase;
350 DWORD start_addr;
351 DWORD imp_offs;
352 DWORD imp_size;
353 DWORD iat_offs;
354 DWORD iat_size;
355 DWORD exp_offs;
356 DWORD exp_size;
357 struct section_info sh_info[pe_sec_number];
358 int sec_count;
359 struct pe_import_info **imp_info;
360 int imp_count;
361 Section *reloc;
362 Section *thunk;
363 TCCState *s1;
364};
365
366/* ------------------------------------------------------------- */
367#define PE_MERGE_DATA
368// #define PE_PRINT_SECTIONS
369
370#ifndef MAX_PATH
371#define MAX_PATH 260
372#endif
373
374void error_noabort(const char *, ...);
375
376ST char pe_type;
377
378#define PE_NUL 0
379#define PE_DLL 1
380#define PE_GUI 2
381#define PE_EXE 3
382
383#ifdef WIN32
384int __stdcall GetModuleFileNameA(void *, char *, int);
385void *__stdcall GetProcAddress(void *, const char *);
386void *__stdcall GetModuleHandleA(const char *);
387void *__stdcall LoadLibraryA(const char *);
388int __stdcall FreeConsole(void);
389#endif
390
391ST int pe_find_import(TCCState * s1, const char *symbol, char *ret)
392{
393 int sym_index = find_elf_sym(s1->dynsymtab_section, symbol);
394 if (0 == sym_index) {
395 /* Hm, maybe it's '_symbol' instead of 'symbol' or '__imp__symbol' */
396 char buffer[100];
397 if (0 == memcmp(symbol, "__imp__", 7))
398 symbol += 6;
399 else
400 buffer[0] = '_', strcpy(buffer + 1, symbol), symbol = buffer;
401 sym_index = find_elf_sym(s1->dynsymtab_section, symbol);
402 }
403 if (ret)
404 strcpy(ret, symbol);
405 return sym_index;
406}
407
408#ifdef WIN32
409ST void **pe_imp;
410ST int nb_pe_imp;
411
412void *resolve_sym(struct TCCState *s1, const char *symbol, int type)
413{
414 char buffer[100], *p = buffer;
415 void *a = NULL;
416 int sym_index = pe_find_import(s1, symbol, p);
417 if (sym_index) {
418 int dll_index =
419 ((Elf32_Sym *) s1->dynsymtab_section->data)[sym_index].
420 st_other;
421 if (dll_index) {
422 const char *dll_name = s1->loaded_dlls[dll_index - 1]->name;
423 void *hm = GetModuleHandleA(dll_name);
424 if (NULL == hm)
425 hm = LoadLibraryA(dll_name);
426 if (hm) {
427 a = GetProcAddress(hm, buffer);
428 if (a && STT_OBJECT == type) {
429 // need to return a pointer to the address for data objects
430 dynarray_add(&pe_imp, &nb_pe_imp, a);
431 a = &pe_imp[nb_pe_imp - 1];
432 }
433 }
434 }
435 }
436 return a;
437}
438#endif
439
440#define for_sym_in_symtab(sym) \
441for (sym = (Elf32_Sym *)symtab_section->data + 1; \
442 sym < (Elf32_Sym *)(symtab_section->data + \
443 symtab_section->data_offset); \
444 ++sym)
445
446#define pe_set_datadir(dir,addr,size) \
447 pe_opt_hdr.DataDirectory[dir].VirtualAddress = addr, \
448 pe_opt_hdr.DataDirectory[dir].Size = size
449
450/*----------------------------------------------------------------------------*/
451ST void dynarray_reset(void ***pp, int *n)
452{
453 int i;
454 for (i = 0; i < *n; ++i)
455 tcc_free((*pp)[i]);
456 tcc_free(*pp);
457 *pp = NULL;
458 *n = 0;
459}
460
461ST int dynarray_assoc(void **pp, int n, int key)
462{
463 int i;
464 for (i = 0; i < n; ++i, ++pp)
465 if (key == **(int **) pp)
466 return i;
467 return -1;
468}
469
470#if 0
471ST DWORD umin(DWORD a, DWORD b)
472{
473 return a < b ? a : b;
474}
475#endif
476
477ST DWORD umax(DWORD a, DWORD b)
478{
479 return a < b ? b : a;
480}
481
482ST void pe_fpad(FILE * fp, DWORD new_pos)
483{
484 DWORD pos = ftell(fp);
485 while (++pos <= new_pos)
486 fputc(0, fp);
487}
488
489ST DWORD pe_file_align(DWORD n)
490{
491 return (n + (0x200 - 1)) & ~(0x200 - 1);
492}
493
494ST DWORD pe_virtual_align(DWORD n)
495{
496 return (n + (0x1000 - 1)) & ~(0x1000 - 1);
497}
498
499ST void pe_align_section(Section * s, int a)
500{
501 int i = s->data_offset & (a - 1);
502 if (i)
503 section_ptr_add(s, a - i);
504}
505
506
507/*----------------------------------------------------------------------------*/
508ST int pe_write_pe(struct pe_info *pe)
509{
510 int i;
511 FILE *op;
512 DWORD file_offset;
513 IMAGE_SECTION_HEADER ish[pe_sec_number], *psh;
514 int sec_index = 0;
515
516 op = fopen(pe->filename, "wb");
517 if (NULL == op) {
518 error_noabort("could not create file: %s", pe->filename);
519 return 1;
520 }
521
522 memset(&ish, 0, sizeof ish);
523
524 pe->sizeofheaders = pe_file_align(sizeof pe_dos_hdr
525 + sizeof pe_magic
526 + sizeof pe_file_hdr
527 + sizeof pe_opt_hdr
528 +
529 pe->sec_count *
530 sizeof(IMAGE_SECTION_HEADER)
531 );
532
533 file_offset = pe->sizeofheaders;
534 pe_fpad(op, file_offset);
535
536 if (2 == verbose)
537 printf("-------------------------------"
538 "\n virt file size section" "\n");
539
540 for (i = 0; i < pe->sec_count; ++i) {
541 struct section_info *si = pe->sh_info + i;
542 const char *sh_name = pe_sec_names[si->id];
543 unsigned long addr = si->sh_addr - pe->imagebase;
544 unsigned long size = si->sh_size;
545
546 if (2 == verbose)
547 printf("%6lx %6lx %6lx %s\n",
548 addr, file_offset, size, sh_name);
549
550 switch (si->id) {
551 case sec_text:
552 pe_opt_hdr.BaseOfCode = addr;
553 pe_opt_hdr.AddressOfEntryPoint = addr + pe->start_addr;
554 break;
555
556 case sec_data:
557 pe_opt_hdr.BaseOfData = addr;
558 if (pe->imp_size) {
559 pe_set_datadir(IMAGE_DIRECTORY_ENTRY_IMPORT,
560 pe->imp_offs + addr, pe->imp_size);
561 pe_set_datadir(IMAGE_DIRECTORY_ENTRY_IAT,
562 pe->iat_offs + addr, pe->iat_size);
563 }
564 if (pe->exp_size) {
565 pe_set_datadir(IMAGE_DIRECTORY_ENTRY_EXPORT,
566 pe->exp_offs + addr, pe->exp_size);
567 }
568 break;
569
570 case sec_bss:
571 break;
572
573 case sec_reloc:
574 pe_set_datadir(IMAGE_DIRECTORY_ENTRY_BASERELOC, addr, size);
575 break;
576
577 case sec_rsrc:
578 pe_set_datadir(IMAGE_DIRECTORY_ENTRY_RESOURCE, addr, size);
579 break;
580
581 case sec_stab:
582 break;
583
584 case sec_stabstr:
585 break;
586 }
587
588 psh = &ish[sec_index++];
589 strcpy((char *) psh->Name, sh_name);
590
591 psh->Characteristics = pe_flags[si->id];
592 psh->VirtualAddress = addr;
593 psh->Misc.VirtualSize = size;
594 pe_opt_hdr.SizeOfImage =
595 umax(psh->VirtualAddress + psh->Misc.VirtualSize,
596 pe_opt_hdr.SizeOfImage);
597
598 if (si->data_size) {
599 psh->PointerToRawData = file_offset;
600 fwrite(si->data, 1, si->data_size, op);
601 file_offset = pe_file_align(file_offset + si->data_size);
602 psh->SizeOfRawData = file_offset - psh->PointerToRawData;
603 pe_fpad(op, file_offset);
604 }
605 }
606
607 /*----------------------------------------------------- */
608
609 pe_file_hdr.NumberOfSections = sec_index;
610 pe_opt_hdr.SizeOfHeaders = pe->sizeofheaders;
611 pe_opt_hdr.ImageBase = pe->imagebase;
612 if (PE_DLL == pe_type)
613 pe_file_hdr.Characteristics = 0x230E;
614 else if (PE_GUI != pe_type)
615 pe_opt_hdr.Subsystem = 3;
616
617 fseek(op, SEEK_SET, 0);
618 fwrite(&pe_dos_hdr, 1, sizeof pe_dos_hdr, op);
619 fwrite(&pe_magic, 1, sizeof pe_magic, op);
620 fwrite(&pe_file_hdr, 1, sizeof pe_file_hdr, op);
621 fwrite(&pe_opt_hdr, 1, sizeof pe_opt_hdr, op);
622 for (i = 0; i < sec_index; ++i)
623 fwrite(&ish[i], 1, sizeof(IMAGE_SECTION_HEADER), op);
624 fclose(op);
625
626 if (2 == verbose)
627 printf("-------------------------------\n");
628 if (verbose)
629 printf("<-- %s (%lu bytes)\n", pe->filename, file_offset);
630
631 return 0;
632}
633
634/*----------------------------------------------------------------------------*/
635ST int pe_add_import(struct pe_info *pe, int sym_index, DWORD offset)
636{
637 int i;
638 int dll_index;
639 struct pe_import_info *p;
640 struct import_symbol *s;
641
642 dll_index =
643 ((Elf32_Sym *) pe->s1->dynsymtab_section->data)[sym_index].
644 st_other;
645 if (0 == dll_index)
646 return 0;
647
648 i = dynarray_assoc((void **) pe->imp_info, pe->imp_count, dll_index);
649 if (-1 != i) {
650 p = pe->imp_info[i];
651 goto found_dll;
652 }
653 p = tcc_mallocz(sizeof *p);
654 p->dll_index = dll_index;
655 dynarray_add((void ***) &pe->imp_info, &pe->imp_count, p);
656
657 found_dll:
658 i = dynarray_assoc((void **) p->symbols, p->sym_count, sym_index);
659 if (-1 != i)
660 goto found_sym;
661 s = tcc_mallocz(sizeof *s);
662 s->sym_index = sym_index;
663 s->offset = offset;
664 dynarray_add((void ***) &p->symbols, &p->sym_count, s);
665
666 found_sym:
667 return 1;
668}
669
670/*----------------------------------------------------------------------------*/
671ST void pe_build_imports(struct pe_info *pe)
672{
673 int thk_ptr, ent_ptr, dll_ptr, sym_cnt, i;
674 DWORD voffset = pe->thunk->sh_addr - pe->imagebase;
675 int ndlls = pe->imp_count;
676
677 for (sym_cnt = i = 0; i < ndlls; ++i)
678 sym_cnt += pe->imp_info[i]->sym_count;
679
680 if (0 == sym_cnt)
681 return;
682
683 pe_align_section(pe->thunk, 16);
684
685 pe->imp_offs = dll_ptr = pe->thunk->data_offset;
686 pe->imp_size = (ndlls + 1) * sizeof(struct pe_import_header);
687 pe->iat_offs = dll_ptr + pe->imp_size;
688 pe->iat_size = (sym_cnt + ndlls) * sizeof(DWORD);
689 section_ptr_add(pe->thunk, pe->imp_size + 2 * pe->iat_size);
690
691 thk_ptr = pe->iat_offs;
692 ent_ptr = pe->iat_offs + pe->iat_size;
693 for (i = 0; i < pe->imp_count; ++i) {
694 struct pe_import_header *hdr;
695 int k, n, v;
696 struct pe_import_info *p = pe->imp_info[i];
697 const char *name = pe->s1->loaded_dlls[p->dll_index - 1]->name;
698
699 /* put the dll name into the import header */
700 if (0 == strncmp(name, "lib", 3))
701 name += 3;
702 v = put_elf_str(pe->thunk, name);
703
704 hdr = (struct pe_import_header *) (pe->thunk->data + dll_ptr);
705 hdr->first_thunk = thk_ptr + voffset;
706 hdr->first_entry = ent_ptr + voffset;
707 hdr->lib_name_offset = v + voffset;
708
709 for (k = 0, n = p->sym_count; k <= n; ++k) {
710 if (k < n) {
711 DWORD offset = p->symbols[k]->offset;
712 int sym_index = p->symbols[k]->sym_index;
713 Elf32_Sym *sym =
714 (Elf32_Sym *) pe->s1->dynsymtab_section->data +
715 sym_index;
716 const char *name =
717 pe->s1->dynsymtab_section->link->data + sym->st_name;
718
719 if (offset & 0x80000000) { /* ref to data */
720 Elf32_Sym *sym =
721 &((Elf32_Sym *) symtab_section->
722 data)[offset & 0x7FFFFFFF];
723 sym->st_value = thk_ptr;
724 sym->st_shndx = pe->thunk->sh_num;
725 } else { /* ref to function */
726
727 char buffer[100];
728 sprintf(buffer, "IAT.%s", name);
729 sym_index =
730 put_elf_sym(symtab_section, thk_ptr, sizeof(DWORD),
731 ELF32_ST_INFO(STB_GLOBAL, STT_OBJECT),
732 0, pe->thunk->sh_num, buffer);
733
734 put_elf_reloc(symtab_section, text_section, offset, R_386_32, /*R_JMP_SLOT, */
735 sym_index);
736 }
737 v = pe->thunk->data_offset + voffset;
738 section_ptr_add(pe->thunk, sizeof(WORD)); /* hint, not used */
739 put_elf_str(pe->thunk, name);
740 } else {
741 v = 0; // last entry is zero
742 }
743 *(DWORD *) (pe->thunk->data + thk_ptr) =
744 *(DWORD *) (pe->thunk->data + ent_ptr) = v;
745 thk_ptr += sizeof(DWORD);
746 ent_ptr += sizeof(DWORD);
747 }
748 dll_ptr += sizeof(struct pe_import_header);
749 dynarray_reset((void ***) &p->symbols, &p->sym_count);
750 }
751 dynarray_reset((void ***) &pe->imp_info, &pe->imp_count);
752}
753
754/* ------------------------------------------------------------- */
755ST void pe_build_exports(struct pe_info *pe)
756{
757 Elf32_Sym *sym;
758 DWORD func_offset;
759 DWORD voffset = pe->thunk->sh_addr - pe->imagebase;
760 struct pe_export_header *hdr;
761 int sym_count = 0, ordinal = 0;
762
763 // for simplicity only functions are exported
764 for_sym_in_symtab(sym)
765 if (sym->st_shndx != text_section->sh_num)
766 sym->st_other &= ~1;
767 else if (sym->st_other & 1)
768 ++sym_count;
769
770 if (0 == sym_count)
771 return;
772
773 pe_align_section(pe->thunk, 16);
774
775 pe->exp_offs = pe->thunk->data_offset;
776 hdr = section_ptr_add(pe->thunk,
777 sizeof(struct pe_export_header) +
778 sym_count * (2 * sizeof(DWORD) + sizeof(WORD)));
779
780 func_offset = pe->exp_offs + sizeof(struct pe_export_header);
781
782 hdr->Characteristics = 0;
783 hdr->Base = 1;
784 hdr->NumberOfFunctions = sym_count;
785 hdr->NumberOfNames = sym_count;
786 hdr->AddressOfFunctions = func_offset + voffset;
787 hdr->AddressOfNames =
788 hdr->AddressOfFunctions + sym_count * sizeof(DWORD);
789 hdr->AddressOfNameOrdinals =
790 hdr->AddressOfNames + sym_count * sizeof(DWORD);
791 hdr->Name = pe->thunk->data_offset + voffset;
792 put_elf_str(pe->thunk, tcc_basename(pe->filename));
793
794 for_sym_in_symtab(sym)
795 if (sym->st_other & 1) {
796 char *name = symtab_section->link->data + sym->st_name;
797 DWORD *p = (DWORD *) (pe->thunk->data + func_offset);
798 DWORD *pfunc = p + ordinal;
799 DWORD *pname = p + sym_count + ordinal;
800 WORD *pord = (WORD *) (p + 2 * sym_count) + ordinal;
801 *pfunc =
802 sym->st_value + pe->s1->sections[sym->st_shndx]->sh_addr -
803 pe->imagebase;
804 *pname = pe->thunk->data_offset + voffset;
805 *pord = ordinal;
806 put_elf_str(pe->thunk, name);
807 /* printf("export: %s\n", name); */
808 ++ordinal;
809 }
810 pe->exp_size = pe->thunk->data_offset - pe->exp_offs;
811}
812
813/* ------------------------------------------------------------- */
814ST void pe_build_reloc(struct pe_info *pe, int *section_order,
815 int section_count)
816{
817 DWORD offset, block_ptr, addr;
818 int count, i;
819 Elf32_Rel *rel, *rel_end;
820 Section *s = NULL, *sr;
821 offset = addr = block_ptr = count = i = 0;
822 rel = rel_end = NULL;
823 for (;;) {
824 if (rel < rel_end) {
825 int type = ELF32_R_TYPE(rel->r_info);
826 addr = rel->r_offset + s->sh_addr;
827 ++rel;
828 if (type != R_386_32)
829 continue;
830 if (count == 0) { /* new block */
831 block_ptr = pe->reloc->data_offset;
832 section_ptr_add(pe->reloc, sizeof(struct pe_reloc_header));
833 offset = addr & 0xFFFFFFFF << 12;
834 }
835 if ((addr -= offset) < (1 << 12)) { /* one block spans 4k addresses */
836 WORD *wp = section_ptr_add(pe->reloc, sizeof(WORD));
837 *wp = addr | IMAGE_REL_BASED_HIGHLOW << 12;
838 ++count;
839 continue;
840 }
841 --rel;
842 } else if (i < section_count) {
843 sr = (s = pe->s1->sections[section_order[i++]])->reloc;
844 if (sr) {
845 rel = (Elf32_Rel *) sr->data;
846 rel_end = (Elf32_Rel *) (sr->data + sr->data_offset);
847 }
848 continue;
849 }
850
851 if (count) { /* store the last block and ready for a new one */
852 struct pe_reloc_header *hdr;
853 if (count & 1)
854 section_ptr_add(pe->reloc, 2), ++count;
855 hdr = (struct pe_reloc_header *) (pe->reloc->data + block_ptr);
856 hdr->offset = offset - pe->imagebase;
857 hdr->size =
858 count * sizeof(WORD) + sizeof(struct pe_reloc_header);
859 count = 0;
860 }
861 if (rel >= rel_end)
862 break;
863 }
864}
865
866/* ------------------------------------------------------------- */
867ST int pe_assign_addresses(struct pe_info *pe)
868{
869 int i, k, n;
870 DWORD addr;
871 int section_order[pe_sec_number];
872 struct section_info *si_data = NULL;
873
874 pe->imagebase = PE_DLL == pe_type ? 0x10000000 : 0x00400000;
875 addr = pe->imagebase + 1;
876
877 if (PE_DLL == pe_type)
878 pe->reloc = new_section(pe->s1, ".reloc", SHT_DYNAMIC, SHF_ALLOC);
879
880 for (n = k = 0; n < pe_sec_number; ++n) {
881 for (i = 1; i < pe->s1->nb_sections; ++i) {
882 Section *s = pe->s1->sections[i];
883 if (0 == strcmp(s->name, pe_sec_names[n])) {
884 struct section_info *si = &pe->sh_info[pe->sec_count];
885#ifdef PE_MERGE_DATA
886 if (n == sec_bss && si_data) {
887 /* append .bss to .data */
888 s->sh_addr = addr = ((addr - 1) | 15) + 1;
889 addr += s->data_offset;
890 si_data->sh_size = addr - si_data->sh_addr;
891 } else
892#endif
893 {
894 si->sh_addr = s->sh_addr = addr =
895 pe_virtual_align(addr);
896 si->id = n;
897
898 if (n == sec_data) {
899 pe->thunk = s;
900 si_data = si;
901 pe_build_imports(pe);
902 pe_build_exports(pe);
903 } else if (n == sec_reloc) {
904 pe_build_reloc(pe, section_order, k);
905 }
906
907 if (s->data_offset) {
908 if (n != sec_bss) {
909 si->data = s->data;
910 si->data_size = s->data_offset;
911 }
912
913 addr += s->data_offset;
914 si->sh_size = s->data_offset;
915 ++pe->sec_count;
916 }
917 //printf("Section %08X %04X %s\n", si->sh_addr, si->data_size, s->name);
918 }
919 section_order[k] = i, ++k;
920 }
921 }
922 }
923 return 0;
924}
925
926/*----------------------------------------------------------------------------*/
927ST int pe_check_symbols(struct pe_info *pe)
928{
929 Elf32_Sym *sym;
930 int ret = 0;
931
932 pe_align_section(text_section, 8);
933
934 for_sym_in_symtab(sym) {
935 if (sym->st_shndx == SHN_UNDEF) {
936 const char *symbol = symtab_section->link->data + sym->st_name;
937 unsigned type = ELF32_ST_TYPE(sym->st_info);
938 int sym_index = pe_find_import(pe->s1, symbol, NULL);
939 if (sym_index) {
940 if (type == STT_FUNC) {
941 unsigned long offset = text_section->data_offset;
942 if (pe_add_import(pe, sym_index, offset + 2)) {
943 /* add the 'jmp IAT[x]' instruction */
944 *(WORD *) section_ptr_add(text_section, 8) =
945 0x25FF;
946 /* patch the symbol */
947 sym->st_shndx = text_section->sh_num;
948 sym->st_value = offset;
949 continue;
950 }
951 } else if (type == STT_OBJECT) { /* data, ptr to that should be */
952 if (pe_add_import(pe, sym_index,
953 (sym -
954 (Elf32_Sym *) symtab_section->data) |
955 0x80000000))
956 continue;
957 }
958 }
959 error_noabort("undefined symbol '%s'", symbol);
960 ret = 1;
961 } else
962 if (pe->s1->rdynamic
963 && ELF32_ST_BIND(sym->st_info) != STB_LOCAL) {
964 /* if -rdynamic option, then export all non local symbols */
965 sym->st_other |= 1;
966 }
967 }
968 return ret;
969}
970
971/*----------------------------------------------------------------------------*/
972#ifdef PE_PRINT_SECTIONS
973ST void pe_print_section(FILE * f, Section * s)
974{ /* just if you'r curious */
975 BYTE *p, *e, b;
976 int i, n, l, m;
977 p = s->data;
978 e = s->data + s->data_offset;
979 l = e - p;
980
981 fprintf(f, "section \"%s\"", s->name);
982 if (s->link)
983 fprintf(f, "\nlink \"%s\"", s->link->name);
984 if (s->reloc)
985 fprintf(f, "\nreloc \"%s\"", s->reloc->name);
986 fprintf(f, "\nv_addr %08X", s->sh_addr);
987 fprintf(f, "\ncontents %08X", l);
988 fprintf(f, "\n\n");
989
990 if (s->sh_type == SHT_NOBITS)
991 return;
992
993 if (s->sh_type == SHT_SYMTAB)
994 m = sizeof(Elf32_Sym);
995 if (s->sh_type == SHT_REL)
996 m = sizeof(Elf32_Rel);
997 else
998 m = 16;
999
1000 for (i = 0; i < l;) {
1001 fprintf(f, "%08X", i);
1002 for (n = 0; n < m; ++n) {
1003 if (n + i < l)
1004 fprintf(f, " %02X", p[i + n]);
1005 else
1006 fprintf(f, " ");
1007 }
1008
1009 if (s->sh_type == SHT_SYMTAB) {
1010 Elf32_Sym *sym = (Elf32_Sym *) (p + i);
1011 const char *name = s->link->data + sym->st_name;
1012 fprintf(f,
1013 " name:%04X"
1014 " value:%04X"
1015 " size:%04X"
1016 " bind:%02X"
1017 " type:%02X"
1018 " other:%02X"
1019 " shndx:%04X"
1020 " \"%s\"",
1021 sym->st_name,
1022 sym->st_value,
1023 sym->st_size,
1024 ELF32_ST_BIND(sym->st_info),
1025 ELF32_ST_TYPE(sym->st_info),
1026 sym->st_other, sym->st_shndx, name);
1027 } else if (s->sh_type == SHT_REL) {
1028 Elf32_Rel *rel = (Elf32_Rel *) (p + i);
1029 Elf32_Sym *sym =
1030 (Elf32_Sym *) s->link->data + ELF32_R_SYM(rel->r_info);
1031 const char *name = s->link->link->data + sym->st_name;
1032 fprintf(f,
1033 " offset:%04X"
1034 " type:%02X"
1035 " symbol:%04X"
1036 " \"%s\"",
1037 rel->r_offset,
1038 ELF32_R_TYPE(rel->r_info),
1039 ELF32_R_SYM(rel->r_info), name);
1040 } else {
1041 fprintf(f, " ");
1042 for (n = 0; n < m; ++n) {
1043 if (n + i < l) {
1044 b = p[i + n];
1045 if (b < 32 || b >= 127)
1046 b = '.';
1047 fprintf(f, "%c", b);
1048 }
1049 }
1050 }
1051 i += m;
1052 fprintf(f, "\n");
1053 }
1054 fprintf(f, "\n\n");
1055}
1056#endif
1057
1058static int pe_test_cmd(const char **pp, const char *cmd)
1059{
1060 const char *p;
1061 char *q, buf[16];
1062 int ret;
1063
1064 p = *pp;
1065 q = buf;
1066 while (*p != '\0' && !is_space(*p)) {
1067 if ((q - buf) < sizeof(buf) - 1)
1068 *q++ = toup(*p);
1069 p++;
1070 }
1071 *q = '\0';
1072 ret = !strcmp(buf, cmd);
1073 *pp = p;
1074 return ret;
1075}
1076
1077/* ------------------------------------------------------------- */
1078int pe_load_def_file(TCCState * s1, FILE * fp)
1079{
1080 DLLReference *dllref;
1081 int f = 0, sym_index;
1082 char *p, *p_other, line[120], dllname[40];
1083 while (fgets(line, sizeof line, fp)) {
1084 p = strchr(line, 0);
1085 while (p > line && p[-1] <= ' ')
1086 --p;
1087 *p = 0;
1088 p = line;
1089 while (*p && *p <= ' ')
1090 ++p;
1091
1092 if (*p && ';' != *p)
1093 switch (f) {
1094 case 0:
1095 if (!pe_test_cmd((const char **)&p, "LIBRARY"))
1096 return -1;
1097 while (is_space(*p))
1098 p++;
1099 pstrcpy(dllname, sizeof(dllname), p);
1100 ++f;
1101 continue;
1102
1103 case 1:
1104 if (!pe_test_cmd((const char **)&p, "EXPORTS"))
1105 return -1;
1106 ++f;
1107 continue;
1108
1109 case 2:
1110 dllref =
1111 tcc_malloc(sizeof(DLLReference) + strlen(dllname));
1112 strcpy(dllref->name, dllname);
1113 dllref->level = 0;
1114 dynarray_add((void ***) &s1->loaded_dlls,
1115 &s1->nb_loaded_dlls, dllref);
1116 ++f;
1117
1118 default:
1119 sym_index = add_elf_sym(s1->dynsymtab_section,
1120 0, 0, ELF32_ST_INFO(STB_GLOBAL,
1121 STT_FUNC),
1122 text_section->sh_num, p);
1123 /*gr: tccpe needs to know from what dll it should import the sym */
1124 p_other =
1125 &((Elf32_Sym *) s1->dynsymtab_section->
1126 data)[sym_index].st_other;
1127 if (0 == *p_other)
1128 *p_other = s1->nb_loaded_dlls;
1129 continue;
1130 }
1131 }
1132 return 0;
1133}
1134
1135/* ------------------------------------------------------------- */
1136unsigned long pe_add_runtime(TCCState * s1)
1137{
1138 const char *start_symbol;
1139 unsigned long addr;
1140
1141 if (find_elf_sym(symtab_section, "WinMain"))
1142 pe_type = PE_GUI;
1143
1144 start_symbol =
1145 TCC_OUTPUT_MEMORY == s1->output_type
1146 ? PE_GUI == pe_type ? "_runwinmain" : NULL
1147 : PE_DLL == pe_type ? "_dllstart"
1148 : PE_GUI == pe_type ? "_winstart" : "_start";
1149
1150 /* grab the startup code from libtcc1 */
1151 if (start_symbol)
1152 add_elf_sym(symtab_section,
1153 0, 0,
1154 ELF32_ST_INFO(STB_GLOBAL, STT_NOTYPE),
1155 SHN_UNDEF, start_symbol);
1156
1157 if (0 == s1->nostdlib) {
1158 tcc_add_library(s1, "tcc1");
1159 tcc_add_library(s1, "msvcrt");
1160 if (PE_DLL == pe_type || PE_GUI == pe_type) {
1161 tcc_add_library(s1, "kernel32");
1162 tcc_add_library(s1, "user32");
1163 tcc_add_library(s1, "gdi32");
1164 }
1165 }
1166
1167 addr = start_symbol ?
1168 (unsigned long) tcc_get_symbol_err(s1, start_symbol) : 0;
1169
1170 if (s1->output_type == TCC_OUTPUT_MEMORY && addr) {
1171 /* for -run GUI's, put '_runwinmain' instead of 'main' */
1172 add_elf_sym(symtab_section,
1173 addr, 0,
1174 ELF32_ST_INFO(STB_GLOBAL, STT_NOTYPE),
1175 text_section->sh_num, "main");
1176
1177 /* FreeConsole(); */
1178 }
1179 return addr;
1180}
1181
1182int tcc_output_pe(TCCState * s1, const char *filename)
1183{
1184 int ret;
1185 struct pe_info pe;
1186 int i;
1187 memset(&pe, 0, sizeof pe);
1188 pe.filename = filename;
1189 pe.s1 = s1;
1190 pe.start_addr = pe_add_runtime(s1);
1191
1192 relocate_common_syms(); /* assign bss adresses */
1193 ret = pe_check_symbols(&pe);
1194 if (0 == ret) {
1195 pe_assign_addresses(&pe);
1196 relocate_syms(s1, 0);
1197 for (i = 1; i < s1->nb_sections; ++i) {
1198 Section *s = s1->sections[i];
1199 if (s->reloc)
1200 relocate_section(s1, s);
1201 }
1202 ret = pe_write_pe(&pe);
1203 }
1204#ifdef PE_PRINT_SECTIONS
1205 {
1206 Section *s;
1207 FILE *f;
1208 f = fopen("tccpe.log", "wb");
1209 for (i = 1; i < s1->nb_sections; ++i) {
1210 s = s1->sections[i];
1211 pe_print_section(f, s);
1212 }
1213 pe_print_section(f, s1->dynsymtab_section);
1214 fclose(f);
1215 }
1216#endif
1217 return ret;
1218}
1219
1220/*----------------------------------------------------------------------------*/
tcctok.h+1−0
@@ -100,6 +100,7 @@ · 99 unmodified lines
100 DEF(TOK_STDCALL1, "stdcall")100 DEF(TOK_STDCALL1, "stdcall")
101 DEF(TOK_STDCALL2, "__stdcall")101 DEF(TOK_STDCALL2, "__stdcall")
102 DEF(TOK_STDCALL3, "__stdcall__")102 DEF(TOK_STDCALL3, "__stdcall__")
103 DEF(TOK_DLLEXPORT, "dllexport")
103 DEF(TOK_NORETURN1, "noreturn")104 DEF(TOK_NORETURN1, "noreturn")
104 DEF(TOK_NORETURN2, "__noreturn__")105 DEF(TOK_NORETURN2, "__noreturn__")
105 DEF(TOK_builtin_types_compatible_p, "__builtin_types_compatible_p")106 DEF(TOK_builtin_types_compatible_p, "__builtin_types_compatible_p")

Keyboard shortcuts

General

Show keyboard shortcuts
?
Focus the current search
/

Issues and pull requests

Open filters
f

Issues, pull requests and Inbox

Select next item
j↓
Select previous item
k↑
Open selected item
Enter
Dismiss filters or clear selection
Esc

Repository code

Go to file
t