From 5342b32eef56a73dfc9c932bf4c77963de2f6f8e Mon Sep 17 00:00:00 2001 From: grischka Date: Wed, 19 Dec 2007 17:36:42 +0000 Subject: [PATCH] Switch to newer tccpe.c (includes support for resources) --- Changelog | 1 + i386-gen.c | 6 +- tcc.c | 309 +++--- tccelf.c | 161 ++-- tccpe.c | 2795 ++++++++++++++++++++++++++++++------------------------ win32/readme.txt | 241 ++--- 6 files changed, 1934 insertions(+), 1579 deletions(-) rewrite tccpe.c (67%) rewrite win32/readme.txt (97%) diff --git a/Changelog b/Changelog index ff12519e..791e83f5 100644 --- a/Changelog +++ b/Changelog @@ -1,5 +1,6 @@ version 0.9.24: +- Switch to newer tccpe.c (includes support for resources) - Handle backslashes within #include, #error, #warning - Import changesets (part 4) 428,457,460,467: defines for openbsd etc. - Use _WIN32 for a windows hosted tcc and define it for the PE target, diff --git a/i386-gen.c b/i386-gen.c index 77505d70..a3d27434 100644 --- a/i386-gen.c +++ b/i386-gen.c @@ -380,7 +380,7 @@ void gfunc_call(int nb_args) } save_regs(0); /* save used temporary registers */ func_sym = vtop->type.ref; - func_call = func_sym->r; + func_call = FUNC_CALL(func_sym->r); /* fast call case */ if ((func_call >= FUNC_FASTCALL1 && func_call <= FUNC_FASTCALL3) || func_call == FUNC_FASTCALLW) { @@ -402,7 +402,7 @@ void gfunc_call(int nb_args) } } gcall_or_jmp(0); - if (args_size && func_sym->r != FUNC_STDCALL) + if (args_size && func_call != FUNC_STDCALL) gadd_sp(args_size); vtop--; } @@ -423,7 +423,7 @@ void gfunc_prolog(CType *func_type) CType *type; sym = func_type->ref; - func_call = sym->r; + func_call = FUNC_CALL(sym->r); addr = 8; loc = 0; if (func_call >= FUNC_FASTCALL1 && func_call <= FUNC_FASTCALL3) { diff --git a/tcc.c b/tcc.c index c43d919c..a8a3f361 100644 --- a/tcc.c +++ b/tcc.c @@ -40,7 +40,7 @@ #include #ifdef _WIN32 #include -// #include +#include #endif #ifndef _WIN32 #include @@ -230,10 +230,24 @@ typedef struct AttributeDef { int aligned; int packed; Section *section; - unsigned char func_call; /* FUNC_CDECL, FUNC_STDCALL, FUNC_FASTCALLx */ - unsigned char dllexport; + int func_attr; /* calling convention, exports, ... */ } AttributeDef; +/* -------------------------------------------------- */ +/* gr: wrappers for casting sym->r for other purposes */ +typedef struct { + unsigned + func_call : 8, + func_args : 8, + func_export : 1; +} func_attr_t; + +#define FUNC_CALL(r) (((func_attr_t*)&(r))->func_call) +#define FUNC_EXPORT(r) (((func_attr_t*)&(r))->func_export) +#define FUNC_ARGS(r) (((func_attr_t*)&(r))->func_args) +#define INLINE_DEF(r) (*(int **)&(r)) +/* -------------------------------------------------- */ + #define SYM_STRUCT 0x40000000 /* struct/union/enum symbol space */ #define SYM_FIELD 0x20000000 /* struct/union field symbol space */ #define SYM_FIRST_ANOM 0x10000000 /* first anonymous sym */ @@ -383,6 +397,9 @@ static CType char_pointer_type, func_old_type, int_type; /* true if isid(c) || isnum(c) */ static unsigned char isidnum_table[256]; +/* display some information during compilation */ +static int verbose = 0; + /* compile with debug symbol (and use them if error during execution) */ static int do_debug = 0; @@ -723,14 +740,6 @@ static const char tcc_keywords[] = #define TOK_UIDENT TOK_DEFINE #ifdef _WIN32 -int __stdcall GetModuleFileNameA(void *, char *, int); -void *__stdcall GetProcAddress(void *, const char *); -void *__stdcall GetModuleHandleA(const char *); -void *__stdcall LoadLibraryA(const char *); -int __stdcall FreeConsole(void); -int __stdcall VirtualProtect(void*,unsigned long,unsigned long,unsigned long*); -#define PAGE_EXECUTE_READWRITE 0x0040 - #define snprintf _snprintf #define vsnprintf _vsnprintf #ifndef __GNUC__ @@ -758,6 +767,7 @@ extern long double strtold (const char *__nptr, char **__endptr); static char *pstrcpy(char *buf, int buf_size, const char *s); static char *pstrcat(char *buf, int buf_size, const char *s); static char *tcc_basename(const char *name); +static char *tcc_fileextension (const char *p); static void next(void); static void next_nomacro(void); @@ -858,10 +868,12 @@ int tcc_output_coff(TCCState *s1, FILE *f); /* tccpe.c */ void *resolve_sym(TCCState *s1, const char *sym, int type); -int pe_load_def_file(struct TCCState *s1, FILE *fp); -void pe_setup_paths(struct TCCState *s1, int *p_output_type, const char **p_outfile, char *first_file); -unsigned long pe_add_runtime(struct TCCState *s1); -int tcc_output_pe(struct TCCState *s1, const char *filename); +int pe_load_def_file(struct TCCState *s1, int fd); +int pe_test_res_file(void *v, int size); +int pe_load_res_file(struct TCCState *s1, int fd); +void pe_add_runtime(struct TCCState *s1); +void pe_guess_outfile(char *objfilename, int output_type); +int pe_output_file(struct TCCState *s1, const char *filename); /* tccasm.c */ @@ -1036,6 +1048,27 @@ static int strstart(const char *str, const char *val, const char **ptr) return 1; } +/* extract the basename of a file */ +static char *tcc_basename(const char *name) +{ + char *p = strchr(name, 0); + while (p > name + && p[-1] != '/' +#ifdef _WIN32 + && p[-1] != '\\' +#endif + ) + --p; + return p; +} + +static char *tcc_fileextension (const char *name) +{ + char *b = tcc_basename(name); + char *e = strrchr(b, '.'); + return e ? e : strchr(b, 0); +} + #ifdef _WIN32 char *normalize_slashes(char *path) { @@ -1162,6 +1195,16 @@ static void dynarray_add(void ***ptab, int *nb_ptr, void *data) *nb_ptr = nb; } +static void dynarray_reset(void *pp, int *n) +{ + void **p; + for (p = *(void***)pp; *n; ++p, --*n) + if (*p) + tcc_free(*p); + tcc_free(*(void**)pp); + *(void**)pp = NULL; +} + /* symbol allocator */ static Sym *__sym_malloc(void) { @@ -1291,7 +1334,7 @@ static void put_extern_sym2(Sym *sym, Section *section, unsigned long value, unsigned long size, int can_add_underscore) { - int sym_type, sym_bind, sh_num, info; + int sym_type, sym_bind, sh_num, info, other, attr; Elf32_Sym *esym; const char *name; char buf1[256]; @@ -1302,16 +1345,29 @@ static void put_extern_sym2(Sym *sym, Section *section, sh_num = SHN_ABS; else sh_num = section->sh_num; + + other = attr = 0; + + if ((sym->type.t & VT_BTYPE) == VT_FUNC) { + sym_type = STT_FUNC; +#ifdef TCC_TARGET_PE + if (sym->type.ref) + attr = sym->type.ref->r; + if (FUNC_EXPORT(attr)) + other |= 1; + if (FUNC_CALL(attr) == FUNC_STDCALL) + other |= 2; +#endif + } else { + sym_type = STT_OBJECT; + } + + if (sym->type.t & VT_STATIC) + sym_bind = STB_LOCAL; + else + sym_bind = STB_GLOBAL; + if (!sym->c) { - if ((sym->type.t & VT_BTYPE) == VT_FUNC) - sym_type = STT_FUNC; - else - sym_type = STT_OBJECT; - if (sym->type.t & VT_STATIC) - sym_bind = STB_LOCAL; - else - sym_bind = STB_GLOBAL; - name = get_tok_str(sym->v, NULL); #ifdef CONFIG_TCC_BCHECK if (do_bounds_check) { @@ -1342,18 +1398,26 @@ static void put_extern_sym2(Sym *sym, Section *section, } } #endif + +#ifdef TCC_TARGET_PE + if ((other & 2) && can_add_underscore) { + sprintf(buf1, "_%s@%d", name, FUNC_ARGS(attr)); + name = buf1; + } else +#endif if (tcc_state->leading_underscore && can_add_underscore) { buf1[0] = '_'; pstrcpy(buf1 + 1, sizeof(buf1) - 1, name); name = buf1; } info = ELF32_ST_INFO(sym_bind, sym_type); - sym->c = add_elf_sym(symtab_section, value, size, info, 0, sh_num, name); + sym->c = add_elf_sym(symtab_section, value, size, info, other, sh_num, name); } else { esym = &((Elf32_Sym *)symtab_section->data)[sym->c]; esym->st_value = value; esym->st_size = size; esym->st_shndx = sh_num; + esym->st_other |= other; } } @@ -2868,7 +2932,7 @@ static void preprocess(int is_bof) { TCCState *s1 = tcc_state; int size, i, c, n, saved_parse_flags; - char buf[1024], *q, *p; + char buf[1024], *q; char buf1[1024]; BufferedFile *f; Sym *s; @@ -2962,10 +3026,7 @@ static void preprocess(int is_bof) } else { if (c == '\"') { /* first search in current dir if "header.h" */ - size = 0; - p = strrchr(file->filename, '/'); - if (p) - size = p + 1 - file->filename; + size = tcc_basename(file->filename) - file->filename; if (size > sizeof(buf1) - 1) size = sizeof(buf1) - 1; memcpy(buf1, file->filename, size); @@ -4026,7 +4087,9 @@ static int *macro_arg_subst(Sym **nested_list, int *macro_str, Sym *args) cstr_ccat(&cstr, ' '); TOK_GET(t, st, cval); cstr_cat(&cstr, get_tok_str(t, &cval)); +#ifndef PP_NOSPACES notfirst = 1; +#endif } cstr_ccat(&cstr, '\0'); #ifdef PP_DEBUG @@ -6112,7 +6175,7 @@ static int is_compatible_func(CType *type1, CType *type2) if (!is_compatible_types(&s1->type, &s2->type)) return 0; /* check func_call */ - if (s1->r != s2->r) + if (FUNC_CALL(s1->r) != FUNC_CALL(s2->r)) return 0; /* XXX: not complete */ if (s1->c == FUNC_OLD || s2->c == FUNC_OLD) @@ -6569,12 +6632,12 @@ static void parse_attribute(AttributeDef *ad) case TOK_CDECL1: case TOK_CDECL2: case TOK_CDECL3: - ad->func_call = FUNC_CDECL; + FUNC_CALL(ad->func_attr) = FUNC_CDECL; break; case TOK_STDCALL1: case TOK_STDCALL2: case TOK_STDCALL3: - ad->func_call = FUNC_STDCALL; + FUNC_CALL(ad->func_attr) = FUNC_STDCALL; break; #ifdef TCC_TARGET_I386 case TOK_REGPARM1: @@ -6586,17 +6649,17 @@ static void parse_attribute(AttributeDef *ad) else if (n < 0) n = 0; if (n > 0) - ad->func_call = FUNC_FASTCALL1 + n - 1; + FUNC_CALL(ad->func_attr) = FUNC_FASTCALL1 + n - 1; skip(')'); break; case TOK_FASTCALL1: case TOK_FASTCALL2: case TOK_FASTCALL3: - ad->func_call = FUNC_FASTCALLW; + FUNC_CALL(ad->func_attr) = FUNC_FASTCALLW; break; #endif case TOK_DLLEXPORT: - ad->dllexport = 1; + FUNC_EXPORT(ad->func_attr) = 1; break; default: if (tcc_state->warn_unsupported) @@ -6979,7 +7042,7 @@ static int parse_btype(CType *type, AttributeDef *ad) } the_end: if ((t & (VT_SIGNED|VT_UNSIGNED)) == (VT_SIGNED|VT_UNSIGNED)) - error("signed and unsigned modifier"); + error("signed and unsigned modifier"); if (tcc_state->char_is_unsigned) { if ((t & (VT_SIGNED|VT_UNSIGNED|VT_BTYPE)) == VT_BYTE) t |= VT_UNSIGNED; @@ -7009,7 +7072,7 @@ static inline void convert_parameter_type(CType *pt) static void post_type(CType *type, AttributeDef *ad) { - int n, l, t1; + int n, l, t1, arg_size, align; Sym **plast, *s, *first; AttributeDef ad1; CType pt; @@ -7020,6 +7083,7 @@ static void post_type(CType *type, AttributeDef *ad) l = 0; first = NULL; plast = &first; + arg_size = 0; if (tok != ')') { for(;;) { /* read param name and compute offset */ @@ -7038,6 +7102,7 @@ static void post_type(CType *type, AttributeDef *ad) type_decl(&pt, &ad1, &n, TYPE_DIRECT | TYPE_ABSTRACT); if ((pt.t & VT_BTYPE) == VT_VOID) error("parameter declared as void"); + arg_size += (type_size(&pt, &align) + 3) & ~3; } else { old_proto: n = tok; @@ -7070,7 +7135,8 @@ static void post_type(CType *type, AttributeDef *ad) type->t &= ~(VT_STORAGE | VT_CONSTANT); post_type(type, ad); /* we push a anonymous symbol which will contain the function prototype */ - s = sym_push(SYM_FIELD, type, ad->func_call, l); + FUNC_ARGS(ad->func_attr) = arg_size; + s = sym_push(SYM_FIELD, type, ad->func_attr, l); s->next = first; type->t = t1 | VT_FUNC; type->ref = s; @@ -7629,6 +7695,7 @@ static void unary(void) next(); sa = s->next; /* first parameter */ nb_args = 0; + ret.r2 = VT_CONST; /* compute first implicit argument if a structure is returned */ if ((s->type.t & VT_BTYPE) == VT_STRUCT) { /* get some space for the returned structure */ @@ -7643,7 +7710,6 @@ static void unary(void) nb_args++; } else { ret.type = s->type; - ret.r2 = VT_CONST; /* return in register */ if (is_float(ret.type.t)) { ret.r = REG_FRET; @@ -8660,12 +8726,11 @@ static void decl_initializer(CType *type, Section *sec, unsigned long c, them as ((w)char *) expressions */ if ((tok == TOK_LSTR && #ifdef TCC_TARGET_PE - (t1->t & VT_BTYPE) == VT_SHORT && (t1->t & VT_UNSIGNED)) || + (t1->t & VT_BTYPE) == VT_SHORT && (t1->t & VT_UNSIGNED) #else - (t1->t & VT_BTYPE) == VT_INT) || + (t1->t & VT_BTYPE) == VT_INT #endif - (tok == TOK_STR && - (t1->t & VT_BTYPE) == VT_BYTE)) { + ) || (tok == TOK_STR && (t1->t & VT_BTYPE) == VT_BYTE)) { while (tok == TOK_STR || tok == TOK_LSTR) { int cstr_len, ch; CString *cstr; @@ -9166,9 +9231,9 @@ static void gen_inline_functions(void) sym->c != 0) { /* the function was used: generate its code and convert it to a normal function */ - str = (int *)sym->r; + str = INLINE_DEF(sym->r); sym->r = VT_SYM | VT_CONST; - type->t &= ~VT_INLINE; + sym->type.t &= ~VT_INLINE; macro_ptr = str; next(); @@ -9190,7 +9255,10 @@ static void gen_inline_functions(void) if (((type->t & VT_BTYPE) == VT_FUNC) && (type->t & (VT_STATIC | VT_INLINE)) == (VT_STATIC | VT_INLINE)) { - str = (int *)sym->r; + //gr printf("sym %d %s\n", sym->r, get_tok_str(sym->v, NULL)); + if (sym->r == (VT_SYM | VT_CONST)) //gr beware! + continue; + str = INLINE_DEF(sym->r); tok_str_free(str); sym->r = 0; /* fail safe */ } @@ -9273,9 +9341,13 @@ static void decl(int l) /* specific case: if not func_call defined, we put the one of the prototype */ /* XXX: should have default value */ - if (sym->type.ref->r != FUNC_CDECL && - type.ref->r == FUNC_CDECL) - type.ref->r = sym->type.ref->r; + r = sym->type.ref->r; + if (FUNC_CALL(r) != FUNC_CDECL + && FUNC_CALL(type.ref->r) == FUNC_CDECL) + FUNC_CALL(type.ref->r) = FUNC_CALL(r); + if (FUNC_EXPORT(r)) + FUNC_EXPORT(type.ref->r) = 1; + if (!is_compatible_types(&sym->type, &type)) { func_error1: error("incompatible types for redefinition of '%s'", @@ -9317,7 +9389,7 @@ static void decl(int l) } tok_str_add(&func_str, -1); tok_str_add(&func_str, 0); - sym->r = (int)func_str.str; + INLINE_DEF(sym->r) = func_str.str; } else { /* compute text section */ cur_text_section = ad.section; @@ -9325,11 +9397,6 @@ static void decl(int l) cur_text_section = text_section; sym->r = VT_SYM | VT_CONST; gen_function(sym); -#ifdef TCC_TARGET_PE - if (ad.dllexport) { - ((Elf32_Sym *)symtab_section->data)[sym->c].st_other |= 1; - } -#endif } break; } else { @@ -9341,8 +9408,8 @@ static void decl(int l) } else if ((type.t & VT_BTYPE) == VT_FUNC) { /* external function definition */ /* specific case for func_call attribute */ - if (ad.func_call) - type.ref->r = ad.func_call; + if (ad.func_attr) + type.ref->r = ad.func_attr; external_sym(v, &type, 0); } else { /* not lvalue if array */ @@ -9891,9 +9958,9 @@ int tcc_relocate(TCCState *s1) relocate_common_syms(); tcc_add_linker_symbols(s1); - +#ifndef TCC_TARGET_PE build_got_entries(s1); - +#endif /* compute relocation address : section are relocated in place. We also alloc the bss space */ for(i = 1; i < s1->nb_sections; i++) { @@ -10118,27 +10185,15 @@ void tcc_delete(TCCState *s1) tcc_free(s1->sections); /* free loaded dlls array */ - for(i = 0; i < s1->nb_loaded_dlls; i++) - tcc_free(s1->loaded_dlls[i]); - tcc_free(s1->loaded_dlls); - - /* library paths */ - for(i = 0; i < s1->nb_library_paths; i++) - tcc_free(s1->library_paths[i]); - tcc_free(s1->library_paths); + dynarray_reset(&s1->loaded_dlls, &s1->nb_loaded_dlls); - /* cached includes */ - for(i = 0; i < s1->nb_cached_includes; i++) - tcc_free(s1->cached_includes[i]); - tcc_free(s1->cached_includes); + /* free library paths */ + dynarray_reset(&s1->library_paths, &s1->nb_library_paths); - for(i = 0; i < s1->nb_include_paths; i++) - tcc_free(s1->include_paths[i]); - tcc_free(s1->include_paths); - - for(i = 0; i < s1->nb_sysinclude_paths; i++) - tcc_free(s1->sysinclude_paths[i]); - tcc_free(s1->sysinclude_paths); + /* free include paths */ + dynarray_reset(&s1->cached_includes, &s1->nb_cached_includes); + dynarray_reset(&s1->include_paths, &s1->nb_include_paths); + dynarray_reset(&s1->sysinclude_paths, &s1->nb_sysinclude_paths); tcc_free(s1); } @@ -10163,19 +10218,14 @@ int tcc_add_sysinclude_path(TCCState *s1, const char *pathname) static int tcc_add_file_internal(TCCState *s1, const char *filename, int flags) { - const char *ext, *filename1; + const char *ext; Elf32_Ehdr ehdr; int fd, ret; BufferedFile *saved_file; /* find source file type with extension */ - filename1 = strrchr(filename, '/'); - if (filename1) - filename1++; - else - filename1 = filename; - ext = strrchr(filename1, '.'); - if (ext) + ext = tcc_fileextension(filename); + if (ext[0]) ext++; /* open the file */ @@ -10191,7 +10241,7 @@ static int tcc_add_file_internal(TCCState *s1, const char *filename, int flags) if (flags & AFF_PREPROCESS) { ret = tcc_preprocess(s1); - } else if (!ext || !strcmp(ext, "c")) { + } else if (!ext[0] || !strcmp(ext, "c")) { /* C file assumed */ ret = tcc_compile(s1); } else @@ -10206,7 +10256,7 @@ static int tcc_add_file_internal(TCCState *s1, const char *filename, int flags) #endif #ifdef TCC_TARGET_PE if (!strcmp(ext, "def")) { - ret = pe_load_def_file(s1, fdopen(file->fd, "rb")); + ret = pe_load_def_file(s1, file->fd); } else #endif { @@ -10257,6 +10307,11 @@ static int tcc_add_file_internal(TCCState *s1, const char *filename, int flags) ret = tcc_load_coff(s1, fd); } else #endif +#ifdef TCC_TARGET_PE + if (pe_test_res_file(&ehdr, ret)) { + ret = pe_load_res_file(s1, fd); + } else +#endif { /* as GNU ld, consider it is an ld script if not recognized */ try_load_script: @@ -10478,20 +10533,6 @@ int tcc_set_flag(TCCState *s, const char *flag_name, int value) flag_name, value); } -/* extract the basename of a file */ -static char *tcc_basename(const char *name) -{ - char *p = strchr(name, 0); - while (p > name - && p[-1] != '/' -#ifdef _WIN32 - && p[-1] != '\\' -#endif - ) - --p; - return p; -} - #if !defined(LIBTCC) static int64_t getclock_us(void) @@ -10535,7 +10576,7 @@ void help(void) " -shared generate a shared library\n" " -static static linking\n" " -rdynamic export all global symbols to dynamic linker\n" - " -r relocatable output\n" + " -r generate (relocatable) object file\n" "Debugger options:\n" " -g generate runtime debug info\n" #ifdef CONFIG_TCC_BCHECK @@ -10885,6 +10926,7 @@ int main(int argc, char **argv) nb_libraries = 0; reloc_output = 0; print_search_dirs = 0; + ret = 0; optind = parse_args(s, argc - 1, argv + 1) + 1; @@ -10915,30 +10957,28 @@ int main(int argc, char **argv) if (!outfile) { s->outfile = stdout; } else { - s->outfile = fopen(outfile, "wb"); + s->outfile = fopen(outfile, "w"); if (!s->outfile) error("could not open '%s", outfile); } } else if (output_type != TCC_OUTPUT_MEMORY) { if (!outfile) { /* compute default outfile name */ - pstrcpy(objfilename, sizeof(objfilename) - 1, - /* strip path */ - tcc_basename(files[0])); + char *ext; + pstrcpy(objfilename, sizeof(objfilename), tcc_basename(files[0])); + ext = tcc_fileextension(objfilename); #ifdef TCC_TARGET_PE - pe_guess_outfile(objfilename, output_type); -#else - if (output_type == TCC_OUTPUT_OBJ && !reloc_output) { - char *ext = strrchr(objfilename, '.'); - if (!ext) - goto default_outfile; - /* add .o extension */ - strcpy(ext + 1, "o"); - } else { - default_outfile: - pstrcpy(objfilename, sizeof(objfilename), "a.out"); - } + if (output_type == TCC_OUTPUT_DLL) + strcpy(ext, ".dll"); + else + if (output_type == TCC_OUTPUT_EXE) + strcpy(ext, ".exe"); + else #endif + if (output_type == TCC_OUTPUT_OBJ && !reloc_output && *ext) + strcpy(ext, ".o"); + else + pstrcpy(objfilename, sizeof(objfilename), "a.out"); outfile = objfilename; } } @@ -10950,29 +10990,29 @@ int main(int argc, char **argv) tcc_set_output_type(s, output_type); /* compile or add each files or library */ - for(i = 0;i < nb_files; i++) { + for(i = 0; i < nb_files && ret == 0; i++) { const char *filename; filename = files[i]; if (output_type == TCC_OUTPUT_PREPROCESS) { - tcc_add_file_internal(s, filename, - AFF_PRINT_ERROR | AFF_PREPROCESS); + if (tcc_add_file_internal(s, filename, + AFF_PRINT_ERROR | AFF_PREPROCESS) < 0) + ret = 1; + } else if (filename[0] == '-') { + if (tcc_add_library(s, filename + 2) < 0) + error("cannot find %s", filename); } else { - if (filename[0] == '-') { - if (tcc_add_library(s, filename + 2) < 0) - error("cannot find %s", filename); - } else { - if (tcc_add_file(s, filename) < 0) { - ret = 1; - goto the_end; - } - } + if (tcc_add_file(s, filename) < 0) + ret = 1; } } /* free all files */ tcc_free(files); + if (ret) + goto the_end; + if (do_bench) { double total_time; total_time = (double)(getclock_us() - start_time) / 1000000.0; @@ -10989,13 +11029,12 @@ int main(int argc, char **argv) if (s->output_type == TCC_OUTPUT_PREPROCESS) { if (outfile) fclose(s->outfile); - ret = 0; } else if (s->output_type == TCC_OUTPUT_MEMORY) { ret = tcc_run(s, argc - optind, argv + optind); } else #ifdef TCC_TARGET_PE if (s->output_type != TCC_OUTPUT_OBJ) { - ret = tcc_output_pe(s, outfile); + ret = pe_output_file(s, outfile); } else #endif { diff --git a/tccelf.c b/tccelf.c index a3c9aee0..273d0b91 100644 --- a/tccelf.c +++ b/tccelf.c @@ -531,11 +531,11 @@ static void relocate_section(TCCState *s1, Section *s) *(int *)ptr += s1->got_offsets[sym_index]; break; #elif defined(TCC_TARGET_ARM) - case R_ARM_PC24: - case R_ARM_CALL: - case R_ARM_JUMP24: - case R_ARM_PLT32: - { + case R_ARM_PC24: + case R_ARM_CALL: + case R_ARM_JUMP24: + case R_ARM_PLT32: + { int x; x = (*(int *)ptr)&0xffffff; (*(int *)ptr) &= 0xff000000; @@ -548,42 +548,42 @@ static void relocate_section(TCCState *s1, Section *s) x >>= 2; x &= 0xffffff; (*(int *)ptr) |= x; - } - break; - case R_ARM_PREL31: - { - int x; - x = (*(int *)ptr) & 0x7fffffff; - (*(int *)ptr) &= 0x80000000; - x = (x * 2) / 2; - x += val - addr; - if((x^(x>>1))&0x40000000) - error("can't relocate value at %x",addr); - (*(int *)ptr) |= x & 0x7fffffff; - } - case R_ARM_ABS32: - *(int *)ptr += val; - break; - case R_ARM_BASE_PREL: - *(int *)ptr += s1->got->sh_addr - addr; - break; - case R_ARM_GOTOFF32: + } + break; + case R_ARM_PREL31: + { + int x; + x = (*(int *)ptr) & 0x7fffffff; + (*(int *)ptr) &= 0x80000000; + x = (x * 2) / 2; + x += val - addr; + if((x^(x>>1))&0x40000000) + error("can't relocate value at %x",addr); + (*(int *)ptr) |= x & 0x7fffffff; + } + case R_ARM_ABS32: + *(int *)ptr += val; + break; + case R_ARM_BASE_PREL: + *(int *)ptr += s1->got->sh_addr - addr; + break; + case R_ARM_GOTOFF32: *(int *)ptr += val - s1->got->sh_addr; break; case R_ARM_GOT_BREL: /* we load the got offset */ *(int *)ptr += s1->got_offsets[sym_index]; break; - case R_ARM_COPY: + case R_ARM_COPY: break; - default: - fprintf(stderr,"FIXME: handle reloc type %x at %lx [%.8x] to %lx\n", + default: + fprintf(stderr,"FIXME: handle reloc type %x at %lx [%.8x] to %lx\n", type,addr,(unsigned int )ptr,val); break; #elif defined(TCC_TARGET_C67) - case R_C60_32: - *(int *)ptr += val; - break; + case R_C60_32: + *(int *)ptr += val; + break; case R_C60LO16: { uint32_t orig; @@ -603,7 +603,7 @@ static void relocate_section(TCCState *s1, Section *s) case R_C60HI16: break; default: - fprintf(stderr,"FIXME: handle reloc type %x at %lx [%.8x] to %lx\n", + fprintf(stderr,"FIXME: handle reloc type %x at %lx [%.8x] to %lx\n", type,addr,(unsigned int )ptr,val); break; #else @@ -784,7 +784,7 @@ static void put_got_entry(TCCState *s1, offset = plt->data_offset - 16; } #elif defined(TCC_TARGET_ARM) - if (reloc_type == R_ARM_JUMP_SLOT) { + if (reloc_type == R_ARM_JUMP_SLOT) { Section *plt; uint8_t *p; @@ -797,17 +797,17 @@ static void put_got_entry(TCCState *s1, if (plt->data_offset == 0) { /* first plt entry */ p = section_ptr_add(plt, 16); - put32(p , 0xe52de004); - put32(p + 4, 0xe59fe010); - put32(p + 8, 0xe08fe00e); - put32(p + 12, 0xe5bef008); + put32(p , 0xe52de004); + put32(p + 4, 0xe59fe010); + put32(p + 8, 0xe08fe00e); + put32(p + 12, 0xe5bef008); } p = section_ptr_add(plt, 16); - put32(p , 0xe59fc004); - put32(p+4, 0xe08fc00c); - put32(p+8, 0xe59cf000); - put32(p+12, s1->got->data_offset); + put32(p , 0xe59fc004); + put32(p+4, 0xe08fc00c); + put32(p+8, 0xe59cf000); + put32(p+12, s1->got->data_offset); /* the symbol is modified so that it will be relocated to the PLT */ @@ -872,7 +872,7 @@ static void build_got_entries(TCCState *s1) } break; #elif defined(TCC_TARGET_ARM) - case R_ARM_GOT_BREL: + case R_ARM_GOT_BREL: case R_ARM_GOTOFF32: case R_ARM_BASE_PREL: case R_ARM_PLT32: @@ -891,7 +891,7 @@ static void build_got_entries(TCCState *s1) } break; #elif defined(TCC_TARGET_C67) - case R_C60_GOT32: + case R_C60_GOT32: case R_C60_GOTOFF: case R_C60_GOTPC: case R_C60_PLT32: @@ -1547,13 +1547,13 @@ int tcc_output_file(TCCState *s1, const char *filename) p += 16; } #elif defined(TCC_TARGET_ARM) - int x; - x=s1->got->sh_addr - s1->plt->sh_addr - 12; - p +=16; - while (p < p_end) { - put32(p + 12, x + get32(p + 12) + s1->plt->data - p); - p += 16; - } + int x; + x=s1->got->sh_addr - s1->plt->sh_addr - 12; + p +=16; + while (p < p_end) { + put32(p + 12, x + get32(p + 12) + s1->plt->data - p); + p += 16; + } #elif defined(TCC_TARGET_C67) /* XXX: TODO */ #else @@ -1682,8 +1682,8 @@ int tcc_output_file(TCCState *s1, const char *filename) #endif #ifdef TCC_TARGET_ARM #ifdef TCC_ARM_EABI - ehdr.e_ident[EI_OSABI] = 0; - ehdr.e_flags = 4 << 24; + ehdr.e_ident[EI_OSABI] = 0; + ehdr.e_flags = 4 << 24; #else ehdr.e_ident[EI_OSABI] = ELFOSABI_ARM; #endif @@ -1859,7 +1859,7 @@ static int tcc_load_object_file(TCCState *s1, if (sh->sh_type != SHT_PROGBITS && sh->sh_type != SHT_REL && #ifdef TCC_ARM_EABI - sh->sh_type != SHT_ARM_EXIDX && + sh->sh_type != SHT_ARM_EXIDX && #endif sh->sh_type != SHT_NOBITS) continue; @@ -2022,16 +2022,16 @@ static int tcc_load_object_file(TCCState *s1, return ret; } -#define ARMAG "!\012" /* For COFF and a.out archives */ +#define ARMAG "!\012" /* For COFF and a.out archives */ typedef struct ArchiveHeader { - char ar_name[16]; /* name of this member */ - char ar_date[12]; /* file mtime */ - char ar_uid[6]; /* owner uid; printed as decimal */ - char ar_gid[6]; /* owner gid; printed as decimal */ - char ar_mode[8]; /* file mode, printed as octal */ - char ar_size[10]; /* file size, printed as decimal */ - char ar_fmag[2]; /* should contain ARFMAG */ + char ar_name[16]; /* name of this member */ + char ar_date[12]; /* file mtime */ + char ar_uid[6]; /* owner uid; printed as decimal */ + char ar_gid[6]; /* owner gid; printed as decimal */ + char ar_mode[8]; /* file mode, printed as octal */ + char ar_size[10]; /* file size, printed as decimal */ + char ar_fmag[2]; /* should contain ARFMAG */ } ArchiveHeader; static int get_be32(const uint8_t *b) @@ -2056,26 +2056,26 @@ static int tcc_load_alacarte(TCCState *s1, int fd, int size) ar_names = ar_index + nsyms * 4; do { - bound = 0; - for(p = ar_names, i = 0; i < nsyms; i++, p += strlen(p)+1) { - sym_index = find_elf_sym(symtab_section, p); - if(sym_index) { - sym = &((Elf32_Sym *)symtab_section->data)[sym_index]; - if(sym->st_shndx == SHN_UNDEF) { - off = get_be32(ar_index + i * 4) + sizeof(ArchiveHeader); + bound = 0; + for(p = ar_names, i = 0; i < nsyms; i++, p += strlen(p)+1) { + sym_index = find_elf_sym(symtab_section, p); + if(sym_index) { + sym = &((Elf32_Sym *)symtab_section->data)[sym_index]; + if(sym->st_shndx == SHN_UNDEF) { + off = get_be32(ar_index + i * 4) + sizeof(ArchiveHeader); #if 0 - printf("%5d\t%s\t%08x\n", i, p, sym->st_shndx); + printf("%5d\t%s\t%08x\n", i, p, sym->st_shndx); #endif - ++bound; - lseek(fd, off, SEEK_SET); - if(tcc_load_object_file(s1, fd, off) < 0) { + ++bound; + lseek(fd, off, SEEK_SET); + if(tcc_load_object_file(s1, fd, off) < 0) { fail: ret = -1; goto the_end; } - } - } - } + } + } + } } while(bound); ret = 0; the_end: @@ -2119,8 +2119,8 @@ static int tcc_load_archive(TCCState *s1, int fd) size = (size + 1) & ~1; if (!strcmp(ar_name, "/")) { /* coff symbol table : we handle it */ - if(s1->alacarte_link) - return tcc_load_alacarte(s1, fd, size); + if(s1->alacarte_link) + return tcc_load_alacarte(s1, fd, size); } else if (!strcmp(ar_name, "//") || !strcmp(ar_name, "__.SYMDEF") || !strcmp(ar_name, "__.SYMDEF/") || @@ -2146,7 +2146,7 @@ static int tcc_load_dll(TCCState *s1, int fd, const char *filename, int level) Elf32_Sym *sym, *dynsym; Elf32_Dyn *dt, *dynamic; unsigned char *dynstr; - const char *name, *soname, *p; + const char *name, *soname; DLLReference *dllref; read(fd, &ehdr, sizeof(ehdr)); @@ -2185,10 +2185,7 @@ static int tcc_load_dll(TCCState *s1, int fd, const char *filename, int level) } /* compute the real library name */ - soname = filename; - p = strrchr(soname, '/'); - if (p) - soname = p + 1; + soname = tcc_basename(filename); for(i = 0, dt = dynamic; i < nb_dts; i++, dt++) { if (dt->d_tag == DT_SONAME) { diff --git a/tccpe.c b/tccpe.c dissimilarity index 67% index 29204173..25b5413a 100644 --- a/tccpe.c +++ b/tccpe.c @@ -1,1244 +1,1551 @@ -/* - * TCCPE.C - PE file output for the TinyC Compiler - * - * Copyright (c) 2005 grischka - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - */ - -typedef unsigned char BYTE; -typedef unsigned short WORD; -typedef unsigned long DWORD; -#define ST static - -/* XXX: move that to TCC ? */ -int verbose = 0; - -/* definitions below are from winnt.h */ - -typedef struct _IMAGE_DOS_HEADER { /* DOS .EXE header */ - WORD e_magic; /* Magic number */ - WORD e_cblp; /* Bytes on last page of file */ - WORD e_cp; /* Pages in file */ - WORD e_crlc; /* Relocations */ - WORD e_cparhdr; /* Size of header in paragraphs */ - WORD e_minalloc; /* Minimum extra paragraphs needed */ - WORD e_maxalloc; /* Maximum extra paragraphs needed */ - WORD e_ss; /* Initial (relative) SS value */ - WORD e_sp; /* Initial SP value */ - WORD e_csum; /* Checksum */ - WORD e_ip; /* Initial IP value */ - WORD e_cs; /* Initial (relative) CS value */ - WORD e_lfarlc; /* File address of relocation table */ - WORD e_ovno; /* Overlay number */ - WORD e_res[4]; /* Reserved words */ - WORD e_oemid; /* OEM identifier (for e_oeminfo) */ - WORD e_oeminfo; /* OEM information; e_oemid specific */ - WORD e_res2[10]; /* Reserved words */ - DWORD e_lfanew; /* File address of new exe header */ - BYTE e_code[0x40]; - -} IMAGE_DOS_HEADER, *PIMAGE_DOS_HEADER; - -#define IMAGE_NT_SIGNATURE 0x00004550 /* PE00 */ -#define SIZE_OF_NT_SIGNATURE 4 - -typedef struct _IMAGE_FILE_HEADER { - WORD Machine; - WORD NumberOfSections; - DWORD TimeDateStamp; - DWORD PointerToSymbolTable; - DWORD NumberOfSymbols; - WORD SizeOfOptionalHeader; - WORD Characteristics; -} IMAGE_FILE_HEADER, *PIMAGE_FILE_HEADER; - - -#define IMAGE_SIZEOF_FILE_HEADER 20 - -typedef struct _IMAGE_DATA_DIRECTORY { - DWORD VirtualAddress; - DWORD Size; -} IMAGE_DATA_DIRECTORY, *PIMAGE_DATA_DIRECTORY; - - -typedef struct _IMAGE_OPTIONAL_HEADER { - /* Standard fields. */ - WORD Magic; - BYTE MajorLinkerVersion; - BYTE MinorLinkerVersion; - DWORD SizeOfCode; - DWORD SizeOfInitializedData; - DWORD SizeOfUninitializedData; - DWORD AddressOfEntryPoint; - DWORD BaseOfCode; - DWORD BaseOfData; - - /* NT additional fields. */ - DWORD ImageBase; - DWORD SectionAlignment; - DWORD FileAlignment; - WORD MajorOperatingSystemVersion; - WORD MinorOperatingSystemVersion; - WORD MajorImageVersion; - WORD MinorImageVersion; - WORD MajorSubsystemVersion; - WORD MinorSubsystemVersion; - DWORD Win32VersionValue; - DWORD SizeOfImage; - DWORD SizeOfHeaders; - DWORD CheckSum; - WORD Subsystem; - WORD DllCharacteristics; - DWORD SizeOfStackReserve; - DWORD SizeOfStackCommit; - DWORD SizeOfHeapReserve; - DWORD SizeOfHeapCommit; - DWORD LoaderFlags; - DWORD NumberOfRvaAndSizes; - IMAGE_DATA_DIRECTORY DataDirectory[16]; - -} IMAGE_OPTIONAL_HEADER32, *PIMAGE_OPTIONAL_HEADER32; - - -#define IMAGE_DIRECTORY_ENTRY_EXPORT 0 /* Export Directory */ -#define IMAGE_DIRECTORY_ENTRY_IMPORT 1 /* Import Directory */ -#define IMAGE_DIRECTORY_ENTRY_RESOURCE 2 /* Resource Directory */ -#define IMAGE_DIRECTORY_ENTRY_EXCEPTION 3 /* Exception Directory */ -#define IMAGE_DIRECTORY_ENTRY_SECURITY 4 /* Security Directory */ -#define IMAGE_DIRECTORY_ENTRY_BASERELOC 5 /* Base Relocation Table */ -#define IMAGE_DIRECTORY_ENTRY_DEBUG 6 /* Debug Directory */ -/* IMAGE_DIRECTORY_ENTRY_COPYRIGHT 7 (X86 usage) */ -#define IMAGE_DIRECTORY_ENTRY_ARCHITECTURE 7 /* Architecture Specific Data */ -#define IMAGE_DIRECTORY_ENTRY_GLOBALPTR 8 /* RVA of GP */ -#define IMAGE_DIRECTORY_ENTRY_TLS 9 /* TLS Directory */ -#define IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG 10 /* Load Configuration Directory */ -#define IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT 11 /* Bound Import Directory in headers */ -#define IMAGE_DIRECTORY_ENTRY_IAT 12 /* Import Address Table */ -#define IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT 13 /* Delay Load Import Descriptors */ -#define IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR 14 /* COM Runtime descriptor */ - -/* Section header format. */ -#define IMAGE_SIZEOF_SHORT_NAME 8 - -typedef struct _IMAGE_SECTION_HEADER { - BYTE Name[IMAGE_SIZEOF_SHORT_NAME]; - union { - DWORD PhysicalAddress; - DWORD VirtualSize; - } Misc; - DWORD VirtualAddress; - DWORD SizeOfRawData; - DWORD PointerToRawData; - DWORD PointerToRelocations; - DWORD PointerToLinenumbers; - WORD NumberOfRelocations; - WORD NumberOfLinenumbers; - DWORD Characteristics; -} IMAGE_SECTION_HEADER, *PIMAGE_SECTION_HEADER; - -#define IMAGE_SIZEOF_SECTION_HEADER 40 - -/* ----------------------------------------------------------- */ -typedef struct _IMAGE_BASE_RELOCATION { - DWORD VirtualAddress; - DWORD SizeOfBlock; -// WORD TypeOffset[1]; -} IMAGE_BASE_RELOCATION; - -#define IMAGE_SIZEOF_BASE_RELOCATION 8 - -#define IMAGE_REL_BASED_ABSOLUTE 0 -#define IMAGE_REL_BASED_HIGH 1 -#define IMAGE_REL_BASED_LOW 2 -#define IMAGE_REL_BASED_HIGHLOW 3 -#define IMAGE_REL_BASED_HIGHADJ 4 -#define IMAGE_REL_BASED_MIPS_JMPADDR 5 -#define IMAGE_REL_BASED_SECTION 6 -#define IMAGE_REL_BASED_REL32 7 - -/* ----------------------------------------------------------- */ - -/* ----------------------------------------------------------- */ -IMAGE_DOS_HEADER pe_dos_hdr = { - 0x5A4D, /*WORD e_magic; Magic number */ - 0x0090, /*WORD e_cblp; Bytes on last page of file */ - 0x0003, /*WORD e_cp; Pages in file */ - 0x0000, /*WORD e_crlc; Relocations */ - - 0x0004, /*WORD e_cparhdr; Size of header in paragraphs */ - 0x0000, /*WORD e_minalloc; Minimum extra paragraphs needed */ - 0xFFFF, /*WORD e_maxalloc; Maximum extra paragraphs needed */ - 0x0000, /*WORD e_ss; Initial (relative) SS value */ - - 0x00B8, /*WORD e_sp; Initial SP value */ - 0x0000, /*WORD e_csum; Checksum */ - 0x0000, /*WORD e_ip; Initial IP value */ - 0x0000, /*WORD e_cs; Initial (relative) CS value */ - 0x0040, /*WORD e_lfarlc; File address of relocation table */ - 0x0000, /*WORD e_ovno; Overlay number */ - {0, 0, 0, 0}, /*WORD e_res[4]; Reserved words */ - 0x0000, /*WORD e_oemid; OEM identifier (for e_oeminfo) */ - 0x0000, /*WORD e_oeminfo; OEM information; e_oemid specific */ - {0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, /*WORD e_res2[10]; Reserved words */ - 0x00000080, /*DWORD e_lfanew; File address of new exe header */ - { /* 14 code bytes + "This program cannot be run in DOS mode.\r\r\n$" + 6 * 0x00 */ - /*0040 */ 0x0e, 0x1f, 0xba, 0x0e, 0x00, 0xb4, 0x09, 0xcd, 0x21, 0xb8, - 0x01, 0x4c, 0xcd, 0x21, 0x54, 0x68, - /*0050 */ 0x69, 0x73, 0x20, 0x70, 0x72, 0x6f, 0x67, 0x72, 0x61, 0x6d, - 0x20, 0x63, 0x61, 0x6e, 0x6e, 0x6f, - /*0060 */ 0x74, 0x20, 0x62, 0x65, 0x20, 0x72, 0x75, 0x6e, 0x20, 0x69, - 0x6e, 0x20, 0x44, 0x4f, 0x53, 0x20, - /*0070 */ 0x6d, 0x6f, 0x64, 0x65, 0x2e, 0x0d, 0x0d, 0x0a, 0x24, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - /*0080 */ - } -}; - -DWORD pe_magic = IMAGE_NT_SIGNATURE; - -IMAGE_FILE_HEADER pe_file_hdr = { - 0x014C, /*WORD Machine; */ - 0x0003, /*WORD NumberOfSections; */ - 0x00000000, /*DWORD TimeDateStamp; */ - 0x00000000, /*DWORD PointerToSymbolTable; */ - 0x00000000, /*DWORD NumberOfSymbols; */ - 0x00E0, /*WORD SizeOfOptionalHeader; */ - 0x030F /*WORD Characteristics; */ -}; - -IMAGE_OPTIONAL_HEADER32 pe_opt_hdr = { - /* Standard fields. */ - 0x010B, /*WORD Magic; */ - 0x06, /*BYTE MajorLinkerVersion; */ - 0x00, /*BYTE MinorLinkerVersion; */ - 0x00000000, /*DWORD SizeOfCode; */ - 0x00000000, /*DWORD SizeOfInitializedData; */ - 0x00000000, /*DWORD SizeOfUninitializedData; */ - 0x00000000, /*DWORD AddressOfEntryPoint; */ - 0x00000000, /*DWORD BaseOfCode; */ - 0x00000000, /*DWORD BaseOfData; */ - - /* NT additional fields. */ - 0x00400000, /*DWORD ImageBase; */ - 0x00001000, /*DWORD SectionAlignment; */ - 0x00000200, /*DWORD FileAlignment; */ - 0x0004, /*WORD MajorOperatingSystemVersion; */ - 0x0000, /*WORD MinorOperatingSystemVersion; */ - 0x0000, /*WORD MajorImageVersion; */ - 0x0000, /*WORD MinorImageVersion; */ - 0x0004, /*WORD MajorSubsystemVersion; */ - 0x0000, /*WORD MinorSubsystemVersion; */ - 0x00000000, /*DWORD Win32VersionValue; */ - 0x00000000, /*DWORD SizeOfImage; */ - 0x00000200, /*DWORD SizeOfHeaders; */ - 0x00000000, /*DWORD CheckSum; */ - 0x0002, /*WORD Subsystem; */ - 0x0000, /*WORD DllCharacteristics; */ - 0x00100000, /*DWORD SizeOfStackReserve; */ - 0x00001000, /*DWORD SizeOfStackCommit; */ - 0x00100000, /*DWORD SizeOfHeapReserve; */ - 0x00001000, /*DWORD SizeOfHeapCommit; */ - 0x00000000, /*DWORD LoaderFlags; */ - 0x00000010, /*DWORD NumberOfRvaAndSizes; */ - - /* IMAGE_DATA_DIRECTORY DataDirectory[16]; */ - {{0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, - {0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}} -}; - -/*----------------------------------------------------------------------------*/ - -/*----------------------------------------------------------------------------*/ - -struct pe_import_header { - DWORD first_entry; - DWORD time_date; - DWORD forwarder; - DWORD lib_name_offset; - DWORD first_thunk; -}; - -struct pe_export_header { - DWORD Characteristics; - DWORD TimeDateStamp; - DWORD Version; - DWORD Name; - DWORD Base; - DWORD NumberOfFunctions; - DWORD NumberOfNames; - DWORD AddressOfFunctions; - DWORD AddressOfNames; - DWORD AddressOfNameOrdinals; -}; - -struct pe_reloc_header { - DWORD offset; - DWORD size; -}; - -/* ------------------------------------------------------------- */ -/* internal temporary structures */ - -ST const char *pe_sec_names[] = { - ".text", - ".data", - ".bss", - ".rsrc", - ".reloc", - ".stab", - ".stabstr" -}; - -enum { - sec_text = 0, - sec_data, - sec_bss, - sec_rsrc, - sec_reloc, - sec_stab, - sec_stabstr, - pe_sec_number -}; - -ST DWORD pe_flags[] = { - 0x60000020, /* ".text", */ - 0xC0000040, /* ".data", */ - 0xC0000080, /* ".bss", */ - 0x40000040, /* ".rsrc", */ - 0x42000040, /* ".reloc", */ - 0x42000802, /* ".stab", */ - 0x42000802 /* ".stabstr", */ -}; - -struct section_info { - struct section_info *next; - int id; - DWORD sh_addr; - DWORD sh_size; - unsigned char *data; - DWORD data_size; -}; - -struct import_symbol { - int sym_index; - int offset; -}; - -struct pe_import_info { - int dll_index; - int sym_count; - struct import_symbol **symbols; -}; - -struct pe_info { - const char *filename; - DWORD sizeofheaders; - DWORD imagebase; - DWORD start_addr; - DWORD imp_offs; - DWORD imp_size; - DWORD iat_offs; - DWORD iat_size; - DWORD exp_offs; - DWORD exp_size; - struct section_info sh_info[pe_sec_number]; - int sec_count; - struct pe_import_info **imp_info; - int imp_count; - Section *reloc; - Section *thunk; - TCCState *s1; -}; - -/* ------------------------------------------------------------- */ -#define PE_MERGE_DATA -// #define PE_PRINT_SECTIONS - -#ifndef MAX_PATH -#define MAX_PATH 260 -#endif - -void error_noabort(const char *, ...); - -ST char pe_type; - -#define PE_NUL 0 -#define PE_DLL 1 -#define PE_GUI 2 -#define PE_EXE 3 - -ST int pe_find_import(TCCState * s1, const char *symbol, char *ret) -{ - int sym_index = find_elf_sym(s1->dynsymtab_section, symbol); - if (0 == sym_index) { - /* Hm, maybe it's '_symbol' instead of 'symbol' or '__imp__symbol' */ - char buffer[100]; - if (0 == memcmp(symbol, "__imp__", 7)) - symbol += 6; - else - buffer[0] = '_', strcpy(buffer + 1, symbol), symbol = buffer; - sym_index = find_elf_sym(s1->dynsymtab_section, symbol); - } - if (ret) - strcpy(ret, symbol); - return sym_index; -} - -#ifdef _WIN32 -ST void **pe_imp; -ST int nb_pe_imp; - -void *resolve_sym(struct TCCState *s1, const char *symbol, int type) -{ - char buffer[100], *p = buffer; - void *a = NULL; - int sym_index = pe_find_import(s1, symbol, p); - int dll_index; - const char *dll_name; - void *hm; - - if (sym_index) { - dll_index = ((Elf32_Sym *) s1->dynsymtab_section->data)[sym_index]. - st_other; - dll_name = s1->loaded_dlls[dll_index]->name; - hm = GetModuleHandleA(dll_name); - if (NULL == hm) - hm = LoadLibraryA(dll_name); - if (hm) { - a = GetProcAddress(hm, buffer); - if (a && STT_OBJECT == type) { - // need to return a pointer to the address for data objects - dynarray_add(&pe_imp, &nb_pe_imp, a); - a = &pe_imp[nb_pe_imp - 1]; - } - } - } - return a; -} -#endif - -#define for_sym_in_symtab(sym) \ -for (sym = (Elf32_Sym *)symtab_section->data + 1; \ - sym < (Elf32_Sym *)(symtab_section->data + \ - symtab_section->data_offset); \ - ++sym) - -#define pe_set_datadir(dir,addr,size) \ - pe_opt_hdr.DataDirectory[dir].VirtualAddress = addr, \ - pe_opt_hdr.DataDirectory[dir].Size = size - -/*----------------------------------------------------------------------------*/ -ST void dynarray_reset(void ***pp, int *n) -{ - int i; - for (i = 0; i < *n; ++i) - tcc_free((*pp)[i]); - tcc_free(*pp); - *pp = NULL; - *n = 0; -} - -ST int dynarray_assoc(void **pp, int n, int key) -{ - int i; - for (i = 0; i < n; ++i, ++pp) - if (key == **(int **) pp) - return i; - return -1; -} - -#if 0 -ST DWORD umin(DWORD a, DWORD b) -{ - return a < b ? a : b; -} -#endif - -ST DWORD umax(DWORD a, DWORD b) -{ - return a < b ? b : a; -} - -ST void pe_fpad(FILE * fp, DWORD new_pos) -{ - DWORD pos = ftell(fp); - while (++pos <= new_pos) - fputc(0, fp); -} - -ST DWORD pe_file_align(DWORD n) -{ - return (n + (0x200 - 1)) & ~(0x200 - 1); -} - -ST DWORD pe_virtual_align(DWORD n) -{ - return (n + (0x1000 - 1)) & ~(0x1000 - 1); -} - -ST void pe_align_section(Section * s, int a) -{ - int i = s->data_offset & (a - 1); - if (i) - section_ptr_add(s, a - i); -} - - -/*----------------------------------------------------------------------------*/ -ST int pe_write_pe(struct pe_info *pe) -{ - int i; - FILE *op; - DWORD file_offset; - IMAGE_SECTION_HEADER ish[pe_sec_number], *psh; - int sec_index = 0; - - op = fopen(pe->filename, "wb"); - if (NULL == op) { - error_noabort("could not create file: %s", pe->filename); - return 1; - } - - memset(&ish, 0, sizeof ish); - - pe->sizeofheaders = pe_file_align(sizeof pe_dos_hdr - + sizeof pe_magic - + sizeof pe_file_hdr - + sizeof pe_opt_hdr - + - pe->sec_count * - sizeof(IMAGE_SECTION_HEADER) - ); - - file_offset = pe->sizeofheaders; - pe_fpad(op, file_offset); - - if (2 == verbose) - printf("-------------------------------" - "\n virt file size section" "\n"); - - for (i = 0; i < pe->sec_count; ++i) { - struct section_info *si = pe->sh_info + i; - const char *sh_name = pe_sec_names[si->id]; - unsigned long addr = si->sh_addr - pe->imagebase; - unsigned long size = si->sh_size; - - if (2 == verbose) - printf("%6lx %6lx %6lx %s\n", - addr, file_offset, size, sh_name); - - switch (si->id) { - case sec_text: - pe_opt_hdr.BaseOfCode = addr; - pe_opt_hdr.AddressOfEntryPoint = addr + pe->start_addr; - break; - - case sec_data: - pe_opt_hdr.BaseOfData = addr; - if (pe->imp_size) { - pe_set_datadir(IMAGE_DIRECTORY_ENTRY_IMPORT, - pe->imp_offs + addr, pe->imp_size); - pe_set_datadir(IMAGE_DIRECTORY_ENTRY_IAT, - pe->iat_offs + addr, pe->iat_size); - } - if (pe->exp_size) { - pe_set_datadir(IMAGE_DIRECTORY_ENTRY_EXPORT, - pe->exp_offs + addr, pe->exp_size); - } - break; - - case sec_bss: - break; - - case sec_reloc: - pe_set_datadir(IMAGE_DIRECTORY_ENTRY_BASERELOC, addr, size); - break; - - case sec_rsrc: - pe_set_datadir(IMAGE_DIRECTORY_ENTRY_RESOURCE, addr, size); - break; - - case sec_stab: - break; - - case sec_stabstr: - break; - } - - psh = &ish[sec_index++]; - strcpy((char *) psh->Name, sh_name); - - psh->Characteristics = pe_flags[si->id]; - psh->VirtualAddress = addr; - psh->Misc.VirtualSize = size; - pe_opt_hdr.SizeOfImage = - umax(psh->VirtualAddress + psh->Misc.VirtualSize, - pe_opt_hdr.SizeOfImage); - - if (si->data_size) { - psh->PointerToRawData = file_offset; - fwrite(si->data, 1, si->data_size, op); - file_offset = pe_file_align(file_offset + si->data_size); - psh->SizeOfRawData = file_offset - psh->PointerToRawData; - pe_fpad(op, file_offset); - } - } - - /*----------------------------------------------------- */ - - pe_file_hdr.NumberOfSections = sec_index; - pe_opt_hdr.SizeOfHeaders = pe->sizeofheaders; - pe_opt_hdr.ImageBase = pe->imagebase; - if (PE_DLL == pe_type) - pe_file_hdr.Characteristics = 0x230E; - else if (PE_GUI != pe_type) - pe_opt_hdr.Subsystem = 3; - - fseek(op, SEEK_SET, 0); - fwrite(&pe_dos_hdr, 1, sizeof pe_dos_hdr, op); - fwrite(&pe_magic, 1, sizeof pe_magic, op); - fwrite(&pe_file_hdr, 1, sizeof pe_file_hdr, op); - fwrite(&pe_opt_hdr, 1, sizeof pe_opt_hdr, op); - for (i = 0; i < sec_index; ++i) - fwrite(&ish[i], 1, sizeof(IMAGE_SECTION_HEADER), op); - fclose(op); - - if (2 == verbose) - printf("-------------------------------\n"); - if (verbose) - printf("<-- %s (%lu bytes)\n", pe->filename, file_offset); - - return 0; -} - -/*----------------------------------------------------------------------------*/ -ST int pe_add_import(struct pe_info *pe, int sym_index, DWORD offset) -{ - int i; - int dll_index; - struct pe_import_info *p; - struct import_symbol *s; - - dll_index = - ((Elf32_Sym *) pe->s1->dynsymtab_section->data)[sym_index]. - st_other; - i = dynarray_assoc((void **) pe->imp_info, pe->imp_count, dll_index); - if (-1 != i) { - p = pe->imp_info[i]; - goto found_dll; - } - p = tcc_mallocz(sizeof *p); - p->dll_index = dll_index; - dynarray_add((void ***) &pe->imp_info, &pe->imp_count, p); - - found_dll: - i = dynarray_assoc((void **) p->symbols, p->sym_count, sym_index); - if (-1 != i) - goto found_sym; - s = tcc_mallocz(sizeof *s); - s->sym_index = sym_index; - s->offset = offset; - dynarray_add((void ***) &p->symbols, &p->sym_count, s); - - found_sym: - return 1; -} - -/*----------------------------------------------------------------------------*/ -ST void pe_build_imports(struct pe_info *pe) -{ - int thk_ptr, ent_ptr, dll_ptr, sym_cnt, i; - DWORD voffset = pe->thunk->sh_addr - pe->imagebase; - int ndlls = pe->imp_count; - - for (sym_cnt = i = 0; i < ndlls; ++i) - sym_cnt += pe->imp_info[i]->sym_count; - - if (0 == sym_cnt) - return; - - pe_align_section(pe->thunk, 16); - - pe->imp_offs = dll_ptr = pe->thunk->data_offset; - pe->imp_size = (ndlls + 1) * sizeof(struct pe_import_header); - pe->iat_offs = dll_ptr + pe->imp_size; - pe->iat_size = (sym_cnt + ndlls) * sizeof(DWORD); - section_ptr_add(pe->thunk, pe->imp_size + 2 * pe->iat_size); - - thk_ptr = pe->iat_offs; - ent_ptr = pe->iat_offs + pe->iat_size; - for (i = 0; i < pe->imp_count; ++i) { - struct pe_import_header *hdr; - int k, n, v; - struct pe_import_info *p = pe->imp_info[i]; - const char *name = pe->s1->loaded_dlls[p->dll_index]->name; - - /* put the dll name into the import header */ - if (0 == strncmp(name, "lib", 3)) - name += 3; - v = put_elf_str(pe->thunk, name); - - hdr = (struct pe_import_header *) (pe->thunk->data + dll_ptr); - hdr->first_thunk = thk_ptr + voffset; - hdr->first_entry = ent_ptr + voffset; - hdr->lib_name_offset = v + voffset; - - for (k = 0, n = p->sym_count; k <= n; ++k) { - if (k < n) { - DWORD offset = p->symbols[k]->offset; - int sym_index = p->symbols[k]->sym_index; - Elf32_Sym *sym = - (Elf32_Sym *) pe->s1->dynsymtab_section->data + - sym_index; - const char *name = - pe->s1->dynsymtab_section->link->data + sym->st_name; - - if (offset & 0x80000000) { /* ref to data */ - Elf32_Sym *sym = - &((Elf32_Sym *) symtab_section-> - data)[offset & 0x7FFFFFFF]; - sym->st_value = thk_ptr; - sym->st_shndx = pe->thunk->sh_num; - } else { /* ref to function */ - - char buffer[100]; - sprintf(buffer, "IAT.%s", name); - sym_index = - put_elf_sym(symtab_section, thk_ptr, sizeof(DWORD), - ELF32_ST_INFO(STB_GLOBAL, STT_OBJECT), - 0, pe->thunk->sh_num, buffer); - - put_elf_reloc(symtab_section, text_section, offset, R_386_32, /*R_JMP_SLOT, */ - sym_index); - } - v = pe->thunk->data_offset + voffset; - section_ptr_add(pe->thunk, sizeof(WORD)); /* hint, not used */ - put_elf_str(pe->thunk, name); - } else { - v = 0; // last entry is zero - } - *(DWORD *) (pe->thunk->data + thk_ptr) = - *(DWORD *) (pe->thunk->data + ent_ptr) = v; - thk_ptr += sizeof(DWORD); - ent_ptr += sizeof(DWORD); - } - dll_ptr += sizeof(struct pe_import_header); - dynarray_reset((void ***) &p->symbols, &p->sym_count); - } - dynarray_reset((void ***) &pe->imp_info, &pe->imp_count); -} - -/* ------------------------------------------------------------- */ -ST int sym_cmp(const void *va, const void *vb) -{ - Elf32_Sym *sa = (Elf32_Sym *)symtab_section->data + *(int*)va; - Elf32_Sym *sb = (Elf32_Sym *)symtab_section->data + *(int*)vb; - const char *ca = symtab_section->link->data + sa->st_name; - const char *cb = symtab_section->link->data + sb->st_name; - return strcmp(ca, cb); -} - -ST void pe_build_exports(struct pe_info *pe) -{ - Elf32_Sym *sym; - DWORD func_offset, voffset; - struct pe_export_header *hdr; - int sym_count, n, ord, *sorted; - - voffset = pe->thunk->sh_addr - pe->imagebase; - sym_count = 0, n = 1, sorted = NULL; - - // for simplicity only functions are exported - for_sym_in_symtab(sym) - { - if ((sym->st_other & 1) - && sym->st_shndx == text_section->sh_num) - dynarray_add((void***)&sorted, &sym_count, (void*)n); - ++n; - } - - if (0 == sym_count) - return; - - qsort (sorted, sym_count, sizeof sorted[0], sym_cmp); - pe_align_section(pe->thunk, 16); - - pe->exp_offs = pe->thunk->data_offset; - hdr = section_ptr_add(pe->thunk, - sizeof(struct pe_export_header) + - sym_count * (2 * sizeof(DWORD) + sizeof(WORD))); - - func_offset = pe->exp_offs + sizeof(struct pe_export_header); - - hdr->Characteristics = 0; - hdr->Base = 1; - hdr->NumberOfFunctions = sym_count; - hdr->NumberOfNames = sym_count; - hdr->AddressOfFunctions = func_offset + voffset; - hdr->AddressOfNames = hdr->AddressOfFunctions + sym_count * sizeof(DWORD); - hdr->AddressOfNameOrdinals = hdr->AddressOfNames + sym_count * sizeof(DWORD); - hdr->Name = pe->thunk->data_offset + voffset; - put_elf_str(pe->thunk, tcc_basename(pe->filename)); - - for (ord = 0; ord < sym_count; ++ord) - { - char *name; DWORD *p, *pfunc, *pname; WORD *pord; - sym = (Elf32_Sym *)symtab_section->data + sorted[ord]; - name = symtab_section->link->data + sym->st_name; - p = (DWORD*)(pe->thunk->data + func_offset); - pfunc = p + ord; - pname = p + sym_count + ord; - pord = (WORD *)(p + 2*sym_count) + ord; - *pfunc = sym->st_value + pe->s1->sections[sym->st_shndx]->sh_addr - pe->imagebase; - *pname = pe->thunk->data_offset + voffset; - *pord = ord; - put_elf_str(pe->thunk, name); - /* printf("export: %s\n", name); */ - } - pe->exp_size = pe->thunk->data_offset - pe->exp_offs; - tcc_free(sorted); -} - -/* ------------------------------------------------------------- */ -ST void pe_build_reloc(struct pe_info *pe, int *section_order, - int section_count) -{ - DWORD offset, block_ptr, addr; - int count, i; - Elf32_Rel *rel, *rel_end; - Section *s = NULL, *sr; - offset = addr = block_ptr = count = i = 0; - rel = rel_end = NULL; - for (;;) { - if (rel < rel_end) { - int type = ELF32_R_TYPE(rel->r_info); - addr = rel->r_offset + s->sh_addr; - ++rel; - if (type != R_386_32) - continue; - if (count == 0) { /* new block */ - block_ptr = pe->reloc->data_offset; - section_ptr_add(pe->reloc, sizeof(struct pe_reloc_header)); - offset = addr & 0xFFFFFFFF << 12; - } - if ((addr -= offset) < (1 << 12)) { /* one block spans 4k addresses */ - WORD *wp = section_ptr_add(pe->reloc, sizeof(WORD)); - *wp = addr | IMAGE_REL_BASED_HIGHLOW << 12; - ++count; - continue; - } - --rel; - } else if (i < section_count) { - sr = (s = pe->s1->sections[section_order[i++]])->reloc; - if (sr) { - rel = (Elf32_Rel *) sr->data; - rel_end = (Elf32_Rel *) (sr->data + sr->data_offset); - } - continue; - } - - if (count) { /* store the last block and ready for a new one */ - struct pe_reloc_header *hdr; - if (count & 1) - section_ptr_add(pe->reloc, 2), ++count; - hdr = (struct pe_reloc_header *) (pe->reloc->data + block_ptr); - hdr->offset = offset - pe->imagebase; - hdr->size = - count * sizeof(WORD) + sizeof(struct pe_reloc_header); - count = 0; - } - if (rel >= rel_end) - break; - } -} - -/* ------------------------------------------------------------- */ -ST int pe_assign_addresses(struct pe_info *pe) -{ - int i, k, n; - DWORD addr; - int section_order[pe_sec_number]; - struct section_info *si_data = NULL; - - pe->imagebase = PE_DLL == pe_type ? 0x10000000 : 0x00400000; - addr = pe->imagebase + 1; - - if (PE_DLL == pe_type) - pe->reloc = new_section(pe->s1, ".reloc", SHT_DYNAMIC, SHF_ALLOC); - - for (n = k = 0; n < pe_sec_number; ++n) { - for (i = 1; i < pe->s1->nb_sections; ++i) { - Section *s = pe->s1->sections[i]; - if (0 == strcmp(s->name, pe_sec_names[n])) { - struct section_info *si = &pe->sh_info[pe->sec_count]; -#ifdef PE_MERGE_DATA - if (n == sec_bss && si_data) { - /* append .bss to .data */ - s->sh_addr = addr = ((addr - 1) | 15) + 1; - addr += s->data_offset; - si_data->sh_size = addr - si_data->sh_addr; - } else -#endif - { - si->sh_addr = s->sh_addr = addr = - pe_virtual_align(addr); - si->id = n; - - if (n == sec_data) { - pe->thunk = s; - si_data = si; - pe_build_imports(pe); - pe_build_exports(pe); - } else if (n == sec_reloc) { - pe_build_reloc(pe, section_order, k); - } - - if (s->data_offset) { - if (n != sec_bss) { - si->data = s->data; - si->data_size = s->data_offset; - } - - addr += s->data_offset; - si->sh_size = s->data_offset; - ++pe->sec_count; - } - //printf("Section %08X %04X %s\n", si->sh_addr, si->data_size, s->name); - } - section_order[k] = i, ++k; - } - } - } - return 0; -} - -/*----------------------------------------------------------------------------*/ -ST int pe_check_symbols(struct pe_info *pe) -{ - Elf32_Sym *sym; - int ret = 0; - - pe_align_section(text_section, 8); - - for_sym_in_symtab(sym) { - if (sym->st_shndx == SHN_UNDEF) { - const char *symbol = symtab_section->link->data + sym->st_name; - unsigned type = ELF32_ST_TYPE(sym->st_info); - int sym_index = pe_find_import(pe->s1, symbol, NULL); - if (sym_index) { - if (type == STT_FUNC) { - unsigned long offset = text_section->data_offset; - if (pe_add_import(pe, sym_index, offset + 2)) { - /* add the 'jmp IAT[x]' instruction */ - *(WORD *) section_ptr_add(text_section, 8) = - 0x25FF; - /* patch the symbol */ - sym->st_shndx = text_section->sh_num; - sym->st_value = offset; - continue; - } - } else if (type == STT_OBJECT) { /* data, ptr to that should be */ - if (pe_add_import(pe, sym_index, - (sym - - (Elf32_Sym *) symtab_section->data) | - 0x80000000)) - continue; - } - } - error_noabort("undefined symbol '%s'", symbol); - ret = 1; - } else - if (pe->s1->rdynamic - && ELF32_ST_BIND(sym->st_info) != STB_LOCAL) { - /* if -rdynamic option, then export all non local symbols */ - sym->st_other |= 1; - } - } - return ret; -} - -/*----------------------------------------------------------------------------*/ -#ifdef PE_PRINT_SECTIONS -ST void pe_print_section(FILE * f, Section * s) -{ /* just if you'r curious */ - BYTE *p, *e, b; - int i, n, l, m; - p = s->data; - e = s->data + s->data_offset; - l = e - p; - - fprintf(f, "section \"%s\"", s->name); - if (s->link) - fprintf(f, "\nlink \"%s\"", s->link->name); - if (s->reloc) - fprintf(f, "\nreloc \"%s\"", s->reloc->name); - fprintf(f, "\nv_addr %08X", s->sh_addr); - fprintf(f, "\ncontents %08X", l); - fprintf(f, "\n\n"); - - if (s->sh_type == SHT_NOBITS) - return; - - if (s->sh_type == SHT_SYMTAB) - m = sizeof(Elf32_Sym); - if (s->sh_type == SHT_REL) - m = sizeof(Elf32_Rel); - else - m = 16; - - for (i = 0; i < l;) { - fprintf(f, "%08X", i); - for (n = 0; n < m; ++n) { - if (n + i < l) - fprintf(f, " %02X", p[i + n]); - else - fprintf(f, " "); - } - - if (s->sh_type == SHT_SYMTAB) { - Elf32_Sym *sym = (Elf32_Sym *) (p + i); - const char *name = s->link->data + sym->st_name; - fprintf(f, - " name:%04X" - " value:%04X" - " size:%04X" - " bind:%02X" - " type:%02X" - " other:%02X" - " shndx:%04X" - " \"%s\"", - sym->st_name, - sym->st_value, - sym->st_size, - ELF32_ST_BIND(sym->st_info), - ELF32_ST_TYPE(sym->st_info), - sym->st_other, sym->st_shndx, name); - } else if (s->sh_type == SHT_REL) { - Elf32_Rel *rel = (Elf32_Rel *) (p + i); - Elf32_Sym *sym = - (Elf32_Sym *) s->link->data + ELF32_R_SYM(rel->r_info); - const char *name = s->link->link->data + sym->st_name; - fprintf(f, - " offset:%04X" - " type:%02X" - " symbol:%04X" - " \"%s\"", - rel->r_offset, - ELF32_R_TYPE(rel->r_info), - ELF32_R_SYM(rel->r_info), name); - } else { - fprintf(f, " "); - for (n = 0; n < m; ++n) { - if (n + i < l) { - b = p[i + n]; - if (b < 32 || b >= 127) - b = '.'; - fprintf(f, "%c", b); - } - } - } - i += m; - fprintf(f, "\n"); - } - fprintf(f, "\n\n"); -} -#endif - -static int pe_test_cmd(const char **pp, const char *cmd) -{ - const char *p; - char *q, buf[16]; - int ret; - - p = *pp; - q = buf; - while (*p != '\0' && !is_space(*p)) { - if ((q - buf) < sizeof(buf) - 1) - *q++ = toup(*p); - p++; - } - *q = '\0'; - ret = !strcmp(buf, cmd); - *pp = p; - return ret; -} - -/* ------------------------------------------------------------- */ -int pe_load_def_file(TCCState * s1, FILE * fp) -{ - DLLReference *dllref; - int f = 0, sym_index; - char *p, line[120], dllname[40]; - while (fgets(line, sizeof line, fp)) { - p = strchr(line, 0); - while (p > line && p[-1] <= ' ') - --p; - *p = 0; - p = line; - while (*p && *p <= ' ') - ++p; - - if (*p && ';' != *p) - switch (f) { - case 0: - if (!pe_test_cmd((const char **)&p, "LIBRARY")) - return -1; - while (is_space(*p)) - p++; - pstrcpy(dllname, sizeof(dllname), p); - ++f; - continue; - - case 1: - if (!pe_test_cmd((const char **)&p, "EXPORTS")) - return -1; - ++f; - continue; - - case 2: - dllref = - tcc_malloc(sizeof(DLLReference) + strlen(dllname)); - strcpy(dllref->name, dllname); - dllref->level = 0; - dynarray_add((void ***) &s1->loaded_dlls, - &s1->nb_loaded_dlls, dllref); - ++f; - - default: - /* tccpe needs to know from what dll it should import - the sym */ - sym_index = add_elf_sym(s1->dynsymtab_section, - 0, 0, ELF32_ST_INFO(STB_GLOBAL, - STT_FUNC), - s1->nb_loaded_dlls - 1, - text_section->sh_num, p); - continue; - } - } - return 0; -} - -/* ------------------------------------------------------------- */ -void pe_guess_outfile(char *objfilename, int output_type) -{ - char *ext = strrchr(objfilename, '.'); - if (NULL == ext) - ext = strchr(objfilename, 0); - if (output_type == TCC_OUTPUT_DLL) - strcpy(ext, ".dll"); - else - if (output_type == TCC_OUTPUT_EXE) - strcpy(ext, ".exe"); - else - if (output_type == TCC_OUTPUT_OBJ && strcmp(ext, ".o")) - strcpy(ext, ".o"); - else - error("no outputfile given"); -} - -/* ------------------------------------------------------------- */ -unsigned long pe_add_runtime(TCCState * s1) -{ - const char *start_symbol; - unsigned long addr; - - if (find_elf_sym(symtab_section, "WinMain")) - pe_type = PE_GUI; - else - if (TCC_OUTPUT_DLL == s1->output_type) - { - pe_type = PE_DLL; - // need this for 'tccelf.c:relocate_section()' - s1->output_type = TCC_OUTPUT_EXE; - } - - start_symbol = - TCC_OUTPUT_MEMORY == s1->output_type - ? PE_GUI == pe_type ? "_runwinmain" : NULL - : PE_DLL == pe_type ? "_dllstart" - : PE_GUI == pe_type ? "_winstart" : "_start"; - - /* grab the startup code from libtcc1 */ - if (start_symbol) - add_elf_sym(symtab_section, - 0, 0, - ELF32_ST_INFO(STB_GLOBAL, STT_NOTYPE), 0, - SHN_UNDEF, start_symbol); - - if (0 == s1->nostdlib) { - tcc_add_library(s1, "tcc1"); - tcc_add_library(s1, "msvcrt"); - if (PE_DLL == pe_type || PE_GUI == pe_type) { - tcc_add_library(s1, "kernel32"); - tcc_add_library(s1, "user32"); - tcc_add_library(s1, "gdi32"); - } - } - - addr = start_symbol ? - (unsigned long) tcc_get_symbol_err(s1, start_symbol) : 0; - - if (s1->output_type == TCC_OUTPUT_MEMORY && addr) { - /* for -run GUI's, put '_runwinmain' instead of 'main' */ - add_elf_sym(symtab_section, - addr, 0, - ELF32_ST_INFO(STB_GLOBAL, STT_NOTYPE), 0, - text_section->sh_num, "main"); - - /* FreeConsole(); */ - } - return addr; -} - -int tcc_output_pe(TCCState * s1, const char *filename) -{ - int ret; - struct pe_info pe; - int i; - memset(&pe, 0, sizeof pe); - pe.filename = filename; - pe.s1 = s1; - pe.start_addr = pe_add_runtime(s1); - - relocate_common_syms(); /* assign bss adresses */ - ret = pe_check_symbols(&pe); - if (0 == ret) { - pe_assign_addresses(&pe); - relocate_syms(s1, 0); - for (i = 1; i < s1->nb_sections; ++i) { - Section *s = s1->sections[i]; - if (s->reloc) - relocate_section(s1, s); - } - ret = pe_write_pe(&pe); - } -#ifdef PE_PRINT_SECTIONS - { - Section *s; - FILE *f; - f = fopen("tccpe.log", "wt"); - for (i = 1; i < s1->nb_sections; ++i) { - s = s1->sections[i]; - pe_print_section(f, s); - } - pe_print_section(f, s1->dynsymtab_section); - fclose(f); - } -#endif - return ret; -} - -/*----------------------------------------------------------------------------*/ +/* + * TCCPE.C - PE file output for the Tiny C Compiler + * + * Copyright (c) 2005-2007 grischka + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ + +#ifdef TCC_TARGET_PE + +#define ST_FN static +#define ST_DATA static +#define PUB_FN + +#ifndef _WIN32 +#define stricmp strcasecmp +#define strnicmp strncasecmp +#endif + +#ifndef MAX_PATH +#define MAX_PATH 260 +#endif + +#define PE_MERGE_DATA +// #define PE_PRINT_SECTIONS + +/* ----------------------------------------------------------- */ +#ifndef IMAGE_NT_SIGNATURE +/* ----------------------------------------------------------- */ +/* definitions below are from winnt.h */ + +typedef unsigned char BYTE; +typedef unsigned short WORD; +typedef unsigned long DWORD; +#pragma pack(push, 1) + +typedef struct _IMAGE_DOS_HEADER { /* DOS .EXE header */ + WORD e_magic; /* Magic number */ + WORD e_cblp; /* Bytes on last page of file */ + WORD e_cp; /* Pages in file */ + WORD e_crlc; /* Relocations */ + WORD e_cparhdr; /* Size of header in paragraphs */ + WORD e_minalloc; /* Minimum extra paragraphs needed */ + WORD e_maxalloc; /* Maximum extra paragraphs needed */ + WORD e_ss; /* Initial (relative) SS value */ + WORD e_sp; /* Initial SP value */ + WORD e_csum; /* Checksum */ + WORD e_ip; /* Initial IP value */ + WORD e_cs; /* Initial (relative) CS value */ + WORD e_lfarlc; /* File address of relocation table */ + WORD e_ovno; /* Overlay number */ + WORD e_res[4]; /* Reserved words */ + WORD e_oemid; /* OEM identifier (for e_oeminfo) */ + WORD e_oeminfo; /* OEM information; e_oemid specific */ + WORD e_res2[10]; /* Reserved words */ + DWORD e_lfanew; /* File address of new exe header */ +} IMAGE_DOS_HEADER, *PIMAGE_DOS_HEADER; + +#define IMAGE_NT_SIGNATURE 0x00004550 /* PE00 */ +#define SIZE_OF_NT_SIGNATURE 4 + +typedef struct _IMAGE_FILE_HEADER { + WORD Machine; + WORD NumberOfSections; + DWORD TimeDateStamp; + DWORD PointerToSymbolTable; + DWORD NumberOfSymbols; + WORD SizeOfOptionalHeader; + WORD Characteristics; +} IMAGE_FILE_HEADER, *PIMAGE_FILE_HEADER; + + +#define IMAGE_SIZEOF_FILE_HEADER 20 + +typedef struct _IMAGE_DATA_DIRECTORY { + DWORD VirtualAddress; + DWORD Size; +} IMAGE_DATA_DIRECTORY, *PIMAGE_DATA_DIRECTORY; + + +typedef struct _IMAGE_OPTIONAL_HEADER { + /* Standard fields. */ + WORD Magic; + BYTE MajorLinkerVersion; + BYTE MinorLinkerVersion; + DWORD SizeOfCode; + DWORD SizeOfInitializedData; + DWORD SizeOfUninitializedData; + DWORD AddressOfEntryPoint; + DWORD BaseOfCode; + DWORD BaseOfData; + + /* NT additional fields. */ + DWORD ImageBase; + DWORD SectionAlignment; + DWORD FileAlignment; + WORD MajorOperatingSystemVersion; + WORD MinorOperatingSystemVersion; + WORD MajorImageVersion; + WORD MinorImageVersion; + WORD MajorSubsystemVersion; + WORD MinorSubsystemVersion; + DWORD Win32VersionValue; + DWORD SizeOfImage; + DWORD SizeOfHeaders; + DWORD CheckSum; + WORD Subsystem; + WORD DllCharacteristics; + DWORD SizeOfStackReserve; + DWORD SizeOfStackCommit; + DWORD SizeOfHeapReserve; + DWORD SizeOfHeapCommit; + DWORD LoaderFlags; + DWORD NumberOfRvaAndSizes; + IMAGE_DATA_DIRECTORY DataDirectory[16]; + +} IMAGE_OPTIONAL_HEADER, *PIMAGE_OPTIONAL_HEADER; + + +#define IMAGE_DIRECTORY_ENTRY_EXPORT 0 /* Export Directory */ +#define IMAGE_DIRECTORY_ENTRY_IMPORT 1 /* Import Directory */ +#define IMAGE_DIRECTORY_ENTRY_RESOURCE 2 /* Resource Directory */ +#define IMAGE_DIRECTORY_ENTRY_EXCEPTION 3 /* Exception Directory */ +#define IMAGE_DIRECTORY_ENTRY_SECURITY 4 /* Security Directory */ +#define IMAGE_DIRECTORY_ENTRY_BASERELOC 5 /* Base Relocation Table */ +#define IMAGE_DIRECTORY_ENTRY_DEBUG 6 /* Debug Directory */ +/* IMAGE_DIRECTORY_ENTRY_COPYRIGHT 7 (X86 usage) */ +#define IMAGE_DIRECTORY_ENTRY_ARCHITECTURE 7 /* Architecture Specific Data */ +#define IMAGE_DIRECTORY_ENTRY_GLOBALPTR 8 /* RVA of GP */ +#define IMAGE_DIRECTORY_ENTRY_TLS 9 /* TLS Directory */ +#define IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG 10 /* Load Configuration Directory */ +#define IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT 11 /* Bound Import Directory in headers */ +#define IMAGE_DIRECTORY_ENTRY_IAT 12 /* Import Address Table */ +#define IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT 13 /* Delay Load Import Descriptors */ +#define IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR 14 /* COM Runtime descriptor */ + +/* Section header format. */ +#define IMAGE_SIZEOF_SHORT_NAME 8 + +typedef struct _IMAGE_SECTION_HEADER { + BYTE Name[IMAGE_SIZEOF_SHORT_NAME]; + union { + DWORD PhysicalAddress; + DWORD VirtualSize; + } Misc; + DWORD VirtualAddress; + DWORD SizeOfRawData; + DWORD PointerToRawData; + DWORD PointerToRelocations; + DWORD PointerToLinenumbers; + WORD NumberOfRelocations; + WORD NumberOfLinenumbers; + DWORD Characteristics; +} IMAGE_SECTION_HEADER, *PIMAGE_SECTION_HEADER; + +#define IMAGE_SIZEOF_SECTION_HEADER 40 + +typedef struct _IMAGE_BASE_RELOCATION { + DWORD VirtualAddress; + DWORD SizeOfBlock; +// WORD TypeOffset[1]; +} IMAGE_BASE_RELOCATION; + +#define IMAGE_SIZEOF_BASE_RELOCATION 8 + +#define IMAGE_REL_BASED_ABSOLUTE 0 +#define IMAGE_REL_BASED_HIGH 1 +#define IMAGE_REL_BASED_LOW 2 +#define IMAGE_REL_BASED_HIGHLOW 3 +#define IMAGE_REL_BASED_HIGHADJ 4 +#define IMAGE_REL_BASED_MIPS_JMPADDR 5 +#define IMAGE_REL_BASED_SECTION 6 +#define IMAGE_REL_BASED_REL32 7 + +#pragma pack(pop) + +/* ----------------------------------------------------------- */ +#endif /* ndef IMAGE_NT_SIGNATURE */ +/* ----------------------------------------------------------- */ + +#pragma pack(push, 1) + +struct pe_header +{ + IMAGE_DOS_HEADER doshdr; + BYTE dosstub[0x40]; + DWORD nt_sig; + IMAGE_FILE_HEADER filehdr; + IMAGE_OPTIONAL_HEADER opthdr; +}; + +struct pe_import_header { + DWORD first_entry; + DWORD time_date; + DWORD forwarder; + DWORD lib_name_offset; + DWORD first_thunk; +}; + +struct pe_export_header { + DWORD Characteristics; + DWORD TimeDateStamp; + DWORD Version; + DWORD Name; + DWORD Base; + DWORD NumberOfFunctions; + DWORD NumberOfNames; + DWORD AddressOfFunctions; + DWORD AddressOfNames; + DWORD AddressOfNameOrdinals; +}; + +struct pe_reloc_header { + DWORD offset; + DWORD size; +}; + +struct pe_rsrc_header { + struct _IMAGE_FILE_HEADER filehdr; + struct _IMAGE_SECTION_HEADER sectionhdr; +}; + +struct pe_rsrc_reloc { + DWORD offset; + DWORD size; + WORD type; +}; + +#pragma pack(pop) + +/* ----------------------------------------------------------- */ +ST_DATA struct pe_header pe_header = { +{ + /* IMAGE_DOS_HEADER doshdr */ + 0x5A4D, /*WORD e_magic; Magic number */ + 0x0090, /*WORD e_cblp; Bytes on last page of file */ + 0x0003, /*WORD e_cp; Pages in file */ + 0x0000, /*WORD e_crlc; Relocations */ + + 0x0004, /*WORD e_cparhdr; Size of header in paragraphs */ + 0x0000, /*WORD e_minalloc; Minimum extra paragraphs needed */ + 0xFFFF, /*WORD e_maxalloc; Maximum extra paragraphs needed */ + 0x0000, /*WORD e_ss; Initial (relative) SS value */ + + 0x00B8, /*WORD e_sp; Initial SP value */ + 0x0000, /*WORD e_csum; Checksum */ + 0x0000, /*WORD e_ip; Initial IP value */ + 0x0000, /*WORD e_cs; Initial (relative) CS value */ + 0x0040, /*WORD e_lfarlc; File address of relocation table */ + 0x0000, /*WORD e_ovno; Overlay number */ + {0,0,0,0}, /*WORD e_res[4]; Reserved words */ + 0x0000, /*WORD e_oemid; OEM identifier (for e_oeminfo) */ + 0x0000, /*WORD e_oeminfo; OEM information; e_oemid specific */ + {0,0,0,0,0,0,0,0,0,0}, /*WORD e_res2[10]; Reserved words */ + 0x00000080 /*DWORD e_lfanew; File address of new exe header */ +},{ + /* BYTE dosstub[0x40] */ + /* 14 code bytes + "This program cannot be run in DOS mode.\r\r\n$" + 6 * 0x00 */ + 0x0e,0x1f,0xba,0x0e,0x00,0xb4,0x09,0xcd,0x21,0xb8,0x01,0x4c,0xcd,0x21,0x54,0x68, + 0x69,0x73,0x20,0x70,0x72,0x6f,0x67,0x72,0x61,0x6d,0x20,0x63,0x61,0x6e,0x6e,0x6f, + 0x74,0x20,0x62,0x65,0x20,0x72,0x75,0x6e,0x20,0x69,0x6e,0x20,0x44,0x4f,0x53,0x20, + 0x6d,0x6f,0x64,0x65,0x2e,0x0d,0x0d,0x0a,0x24,0x00,0x00,0x00,0x00,0x00,0x00,0x00, +}, + 0x00004550, /* DWORD nt_sig = IMAGE_NT_SIGNATURE */ +{ + /* IMAGE_FILE_HEADER filehdr */ + 0x014C, /*WORD Machine; */ + 0x0003, /*WORD NumberOfSections; */ + 0x00000000, /*DWORD TimeDateStamp; */ + 0x00000000, /*DWORD PointerToSymbolTable; */ + 0x00000000, /*DWORD NumberOfSymbols; */ + 0x00E0, /*WORD SizeOfOptionalHeader; */ + 0x030F /*WORD Characteristics; */ +},{ + /* IMAGE_OPTIONAL_HEADER opthdr */ + /* Standard fields. */ + 0x010B, /*WORD Magic; */ + 0x06, /*BYTE MajorLinkerVersion; */ + 0x00, /*BYTE MinorLinkerVersion; */ + 0x00000000, /*DWORD SizeOfCode; */ + 0x00000000, /*DWORD SizeOfInitializedData; */ + 0x00000000, /*DWORD SizeOfUninitializedData; */ + 0x00000000, /*DWORD AddressOfEntryPoint; */ + 0x00000000, /*DWORD BaseOfCode; */ + 0x00000000, /*DWORD BaseOfData; */ + + /* NT additional fields. */ + 0x00400000, /*DWORD ImageBase; */ + 0x00001000, /*DWORD SectionAlignment; */ + 0x00000200, /*DWORD FileAlignment; */ + 0x0004, /*WORD MajorOperatingSystemVersion; */ + 0x0000, /*WORD MinorOperatingSystemVersion; */ + 0x0000, /*WORD MajorImageVersion; */ + 0x0000, /*WORD MinorImageVersion; */ + 0x0004, /*WORD MajorSubsystemVersion; */ + 0x0000, /*WORD MinorSubsystemVersion; */ + 0x00000000, /*DWORD Win32VersionValue; */ + 0x00000000, /*DWORD SizeOfImage; */ + 0x00000200, /*DWORD SizeOfHeaders; */ + 0x00000000, /*DWORD CheckSum; */ + 0x0002, /*WORD Subsystem; */ + 0x0000, /*WORD DllCharacteristics; */ + 0x00100000, /*DWORD SizeOfStackReserve; */ + 0x00001000, /*DWORD SizeOfStackCommit; */ + 0x00100000, /*DWORD SizeOfHeapReserve; */ + 0x00001000, /*DWORD SizeOfHeapCommit; */ + 0x00000000, /*DWORD LoaderFlags; */ + 0x00000010, /*DWORD NumberOfRvaAndSizes; */ + + /* IMAGE_DATA_DIRECTORY DataDirectory[16]; */ + {{0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, + {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}} +}}; + +/* ------------------------------------------------------------- */ +/* internal temporary structures */ + +/* +#define IMAGE_SCN_CNT_CODE 0x00000020 +#define IMAGE_SCN_CNT_INITIALIZED_DATA 0x00000040 +#define IMAGE_SCN_CNT_UNINITIALIZED_DATA 0x00000080 +#define IMAGE_SCN_MEM_DISCARDABLE 0x02000000 +#define IMAGE_SCN_MEM_SHARED 0x10000000 +#define IMAGE_SCN_MEM_EXECUTE 0x20000000 +#define IMAGE_SCN_MEM_READ 0x40000000 +#define IMAGE_SCN_MEM_WRITE 0x80000000 +*/ + +enum { + sec_text = 0, + sec_data , + sec_bss , + sec_idata , + sec_rsrc , + sec_stab , + sec_reloc , + + sec_last +}; + +ST_DATA DWORD pe_sec_flags[] = { + 0x60000020, /* ".text" , */ + 0xC0000040, /* ".data" , */ + 0xC0000080, /* ".bss" , */ + 0x40000040, /* ".idata" , */ + 0x40000040, /* ".rsrc" , */ + 0x42000802, /* ".stab" , */ + 0x42000040, /* ".reloc" , */ +}; + +struct section_info { + int cls, ord; + char name[32]; + DWORD sh_addr; + DWORD sh_size; + DWORD sh_flags; + unsigned char *data; + DWORD data_size; + IMAGE_SECTION_HEADER ish; +}; + +struct import_symbol { + int sym_index; + int iat_index; + int thk_offset; +}; + +struct pe_import_info { + int dll_index; + int sym_count; + struct import_symbol **symbols; +}; + +struct pe_info { + TCCState *s1; + Section *reloc; + Section *thunk; + const char *filename; + int type; + DWORD sizeofheaders; + DWORD imagebase; + DWORD start_addr; + DWORD imp_offs; + DWORD imp_size; + DWORD iat_offs; + DWORD iat_size; + DWORD exp_offs; + DWORD exp_size; + struct section_info *sec_info; + int sec_count; + struct pe_import_info **imp_info; + int imp_count; +}; + +/* ------------------------------------------------------------- */ + +#define PE_NUL 0 +#define PE_DLL 1 +#define PE_GUI 2 +#define PE_EXE 3 + +void error_noabort(const char *, ...); + +#ifdef _WIN32 +void dbg_printf (const char *fmt, ...) +{ + char buffer[4000]; + va_list arg; + int x; + va_start(arg, fmt); + x = vsprintf (buffer, fmt, arg); + strcpy(buffer+x, "\n"); + OutputDebugString(buffer); +} +#endif + +/* --------------------------------------------*/ + +ST_FN const char* get_alt_symbol(char *buffer, const char *symbol) +{ + const char *p; + p = strrchr(symbol, '@'); + if (p && isnum(p[1]) && symbol[0] == '_') { /* stdcall decor */ + strcpy(buffer, symbol+1)[p-symbol-1] = 0; + } else if (symbol[0] != '_') { /* try non-ansi function */ + buffer[0] = '_', strcpy(buffer + 1, symbol); + } else if (0 == memcmp(symbol, "__imp__", 7)) { /* mingw 2.0 */ + strcpy(buffer, symbol + 6); + } else if (0 == memcmp(symbol, "_imp___", 7)) { /* mingw 3.7 */ + strcpy(buffer, symbol + 6); + } else { + return symbol; + } + return buffer; +} + +ST_FN int pe_find_import(TCCState * s1, const char *symbol) +{ + char buffer[200]; + const char *s; + int sym_index, n = 0; + do { + s = n ? get_alt_symbol(buffer, symbol) : symbol; + sym_index = find_elf_sym(s1->dynsymtab_section, s); + // printf("find %d %s\n", sym_index, s); + } while (0 == sym_index && ++n < 2); + return sym_index; +} + +#if defined _WIN32 || defined __CYGWIN__ + +#ifdef __CYGWIN__ +# include +# define LoadLibrary(s) dlopen(s, RTLD_NOW) +# define GetProcAddress(h,s) dlsym(h, s) +#endif + +/* for the -run option: dynamically load symbol from dll */ +void *resolve_sym(struct TCCState *s1, const char *symbol, int type) +{ + char buffer[100]; + int sym_index, dll_index; + void *hModule, *addr, **m; + + sym_index = pe_find_import(s1, symbol); + if (0 == sym_index) + return NULL; + dll_index = ((Elf32_Sym *)s1->dynsymtab_section->data + sym_index)->st_value; + hModule = LoadLibrary(s1->loaded_dlls[dll_index-1]->name); + addr = GetProcAddress(hModule, symbol); + if (NULL == addr) + addr = GetProcAddress(hModule, get_alt_symbol(buffer, symbol)); + + if (addr && STT_OBJECT == type) { + /* need to return a pointer to the address for data objects */ + m = (void**)tcc_malloc(sizeof addr), *m = addr, addr = m; +#ifdef MEM_DEBUG + /* yep, we don't free it */ + mem_cur_size -= sizeof (void*); +#endif + } + return addr; +} +#endif + +/*----------------------------------------------------------------------------*/ + +ST_FN int dynarray_assoc(void **pp, int n, int key) +{ + int i; + for (i = 0; i < n; ++i, ++pp) + if (key == **(int **) pp) + return i; + return -1; +} + +#if 0 +ST_FN DWORD umin(DWORD a, DWORD b) +{ + return a < b ? a : b; +} +#endif + +ST_FN DWORD umax(DWORD a, DWORD b) +{ + return a < b ? b : a; +} + +ST_FN void pe_fpad(FILE *fp, DWORD new_pos) +{ + DWORD pos = ftell(fp); + while (++pos <= new_pos) + fputc(0, fp); +} + +ST_FN DWORD pe_file_align(DWORD n) +{ + return (n + (0x200 - 1)) & ~(0x200 - 1); +} + +ST_FN DWORD pe_virtual_align(DWORD n) +{ + return (n + (0x1000 - 1)) & ~(0x1000 - 1); +} + +ST_FN void pe_align_section(Section *s, int a) +{ + int i = s->data_offset & (a-1); + if (i) + section_ptr_add(s, a - i); +} + +ST_FN void pe_set_datadir(int dir, DWORD addr, DWORD size) +{ + pe_header.opthdr.DataDirectory[dir].VirtualAddress = addr; + pe_header.opthdr.DataDirectory[dir].Size = size; +} + +/*----------------------------------------------------------------------------*/ +ST_FN int pe_write(struct pe_info *pe) +{ + int i; + FILE *op; + DWORD file_offset, r; + + op = fopen(pe->filename, "wb"); + if (NULL == op) { + error_noabort("could not write '%s': %s", pe->filename, strerror(errno)); + return 1; + } + + pe->sizeofheaders = pe_file_align( + sizeof pe_header + + pe->sec_count * sizeof (IMAGE_SECTION_HEADER) + ); + + file_offset = pe->sizeofheaders; + pe_fpad(op, file_offset); + + if (2 == verbose) + printf("-------------------------------" + "\n virt file size section" "\n"); + + for (i = 0; i < pe->sec_count; ++i) { + struct section_info *si = pe->sec_info + i; + const char *sh_name = si->name; + unsigned long addr = si->sh_addr - pe->imagebase; + unsigned long size = si->sh_size; + IMAGE_SECTION_HEADER *psh = &si->ish; + + if (2 == verbose) + printf("%6lx %6lx %6lx %s\n", + addr, file_offset, size, sh_name); + + switch (si->cls) { + case sec_text: + pe_header.opthdr.BaseOfCode = addr; + pe_header.opthdr.AddressOfEntryPoint = addr + pe->start_addr; + break; + + case sec_data: + pe_header.opthdr.BaseOfData = addr; + break; + + case sec_bss: + break; + + case sec_reloc: + pe_set_datadir(IMAGE_DIRECTORY_ENTRY_BASERELOC, addr, size); + break; + + case sec_rsrc: + pe_set_datadir(IMAGE_DIRECTORY_ENTRY_RESOURCE, addr, size); + break; + + case sec_stab: + break; + } + + if (pe->thunk == pe->s1->sections[si->ord]) { + if (pe->imp_size) { + pe_set_datadir(IMAGE_DIRECTORY_ENTRY_IMPORT, + pe->imp_offs + addr, pe->imp_size); + pe_set_datadir(IMAGE_DIRECTORY_ENTRY_IAT, + pe->iat_offs + addr, pe->iat_size); + } + if (pe->exp_size) { + pe_set_datadir(IMAGE_DIRECTORY_ENTRY_EXPORT, + pe->exp_offs + addr, pe->exp_size); + } + } + + strcpy((char*)psh->Name, sh_name); + + psh->Characteristics = pe_sec_flags[si->cls]; + psh->VirtualAddress = addr; + psh->Misc.VirtualSize = size; + pe_header.opthdr.SizeOfImage = + umax(pe_virtual_align(size + addr), pe_header.opthdr.SizeOfImage); + + if (si->data_size) { + psh->PointerToRawData = r = file_offset; + fwrite(si->data, 1, si->data_size, op); + file_offset = pe_file_align(file_offset + si->data_size); + psh->SizeOfRawData = file_offset - r; + pe_fpad(op, file_offset); + } + } + + // pe_header.filehdr.TimeDateStamp = time(NULL); + pe_header.filehdr.NumberOfSections = pe->sec_count; + pe_header.opthdr.SizeOfHeaders = pe->sizeofheaders; + pe_header.opthdr.ImageBase = pe->imagebase; + if (PE_DLL == pe->type) + pe_header.filehdr.Characteristics = 0x230E; + else if (PE_GUI != pe->type) + pe_header.opthdr.Subsystem = 3; + + fseek(op, SEEK_SET, 0); + fwrite(&pe_header, 1, sizeof pe_header, op); + for (i = 0; i < pe->sec_count; ++i) + fwrite(&pe->sec_info[i].ish, 1, sizeof(IMAGE_SECTION_HEADER), op); + fclose (op); + + if (2 == verbose) + printf("-------------------------------\n"); + if (verbose) + printf("<- %s (%lu bytes)\n", pe->filename, file_offset); + + return 0; +} + +/*----------------------------------------------------------------------------*/ + +ST_FN struct import_symbol *pe_add_import(struct pe_info *pe, int sym_index) +{ + int i; + int dll_index; + struct pe_import_info *p; + struct import_symbol *s; + + dll_index = ((Elf32_Sym *)pe->s1->dynsymtab_section->data + sym_index)->st_value; + if (0 == dll_index) + return NULL; + + i = dynarray_assoc ((void**)pe->imp_info, pe->imp_count, dll_index); + if (-1 != i) { + p = pe->imp_info[i]; + goto found_dll; + } + p = tcc_mallocz(sizeof *p); + p->dll_index = dll_index; + dynarray_add((void***)&pe->imp_info, &pe->imp_count, p); + +found_dll: + i = dynarray_assoc ((void**)p->symbols, p->sym_count, sym_index); + if (-1 != i) + return p->symbols[i]; + + s = tcc_mallocz(sizeof *s); + dynarray_add((void***)&p->symbols, &p->sym_count, s); + s->sym_index = sym_index; + return s; +} + +/*----------------------------------------------------------------------------*/ +ST_FN void pe_build_imports(struct pe_info *pe) +{ + int thk_ptr, ent_ptr, dll_ptr, sym_cnt, i; + DWORD rva_base = pe->thunk->sh_addr - pe->imagebase; + int ndlls = pe->imp_count; + + for (sym_cnt = i = 0; i < ndlls; ++i) + sym_cnt += pe->imp_info[i]->sym_count; + + if (0 == sym_cnt) + return; + + pe_align_section(pe->thunk, 16); + + pe->imp_offs = dll_ptr = pe->thunk->data_offset; + pe->imp_size = (ndlls + 1) * sizeof(struct pe_import_header); + pe->iat_offs = dll_ptr + pe->imp_size; + pe->iat_size = (sym_cnt + ndlls) * sizeof(DWORD); + section_ptr_add(pe->thunk, pe->imp_size + 2*pe->iat_size); + + thk_ptr = pe->iat_offs; + ent_ptr = pe->iat_offs + pe->iat_size; + + for (i = 0; i < pe->imp_count; ++i) { + struct pe_import_header *hdr; + int k, n, v; + struct pe_import_info *p = pe->imp_info[i]; + const char *name = pe->s1->loaded_dlls[p->dll_index-1]->name; + + /* put the dll name into the import header */ + v = put_elf_str(pe->thunk, name); + + hdr = (struct pe_import_header*)(pe->thunk->data + dll_ptr); + hdr->first_thunk = thk_ptr + rva_base; + hdr->first_entry = ent_ptr + rva_base; + hdr->lib_name_offset = v + rva_base; + + for (k = 0, n = p->sym_count; k <= n; ++k) { + if (k < n) { + DWORD iat_index = p->symbols[k]->iat_index; + int sym_index = p->symbols[k]->sym_index; + Elf32_Sym *imp_sym = (Elf32_Sym *)pe->s1->dynsymtab_section->data + sym_index; + Elf32_Sym *org_sym = (Elf32_Sym *)symtab_section->data + iat_index; + const char *name = pe->s1->dynsymtab_section->link->data + imp_sym->st_name; + + org_sym->st_value = thk_ptr; + org_sym->st_shndx = pe->thunk->sh_num; + v = pe->thunk->data_offset + rva_base; + section_ptr_add(pe->thunk, sizeof(WORD)); /* hint, not used */ + put_elf_str(pe->thunk, name); + + } else { + v = 0; /* last entry is zero */ + } + *(DWORD*)(pe->thunk->data+thk_ptr) = + *(DWORD*)(pe->thunk->data+ent_ptr) = v; + thk_ptr += sizeof (DWORD); + ent_ptr += sizeof (DWORD); + } + dll_ptr += sizeof(struct pe_import_header); + dynarray_reset(&p->symbols, &p->sym_count); + } + dynarray_reset(&pe->imp_info, &pe->imp_count); +} + +/* ------------------------------------------------------------- */ +/* + For now only functions are exported. Export of data + would work, but import requires compiler support to + do an additional indirection. + + For instance: + __declspec(dllimport) extern int something; + + needs to be translated to: + + *(int*)something +*/ + +ST_FN int sym_cmp(const void *va, const void *vb) +{ + const char *ca = ((const char **)va)[1]; + const char *cb = ((const char **)vb)[1]; + return strcmp(ca, cb); +} + +ST_FN void pe_build_exports(struct pe_info *pe) +{ + Elf32_Sym *sym; + int sym_index, sym_end; + DWORD rva_base, func_o, name_o, ord_o, str_o; + struct pe_export_header *hdr; + int sym_count, n, ord, *sorted, *sp; + + FILE *op; + char buf[MAX_PATH]; + const char *dllname; + const char *name; + + rva_base = pe->thunk->sh_addr - pe->imagebase; + sym_count = 0, n = 1, sorted = NULL, op = NULL; + + sym_end = symtab_section->data_offset / sizeof(Elf32_Sym); + for (sym_index = 1; sym_index < sym_end; ++sym_index) { + sym = (Elf32_Sym*)symtab_section->data + sym_index; + name = symtab_section->link->data + sym->st_name; + if ((sym->st_other & 1) + /* export only symbols from actually written sections */ + && pe->s1->sections[sym->st_shndx]->sh_addr) { + dynarray_add((void***)&sorted, &sym_count, (void*)n); + dynarray_add((void***)&sorted, &sym_count, (void*)name); + } + ++n; +#if 0 + if (sym->st_other & 1) + printf("export: %s\n", name); + if (sym->st_other & 2) + printf("stdcall: %s\n", name); +#endif + } + + if (0 == sym_count) + return; + sym_count /= 2; + + qsort (sorted, sym_count, 2 * sizeof sorted[0], sym_cmp); + pe_align_section(pe->thunk, 16); + dllname = tcc_basename(pe->filename); + + pe->exp_offs = pe->thunk->data_offset; + func_o = pe->exp_offs + sizeof(struct pe_export_header); + name_o = func_o + sym_count * sizeof (DWORD); + ord_o = name_o + sym_count * sizeof (DWORD); + str_o = ord_o + sym_count * sizeof(WORD); + + hdr = section_ptr_add(pe->thunk, str_o - pe->exp_offs); + hdr->Characteristics = 0; + hdr->Base = 1; + hdr->NumberOfFunctions = sym_count; + hdr->NumberOfNames = sym_count; + hdr->AddressOfFunctions = func_o + rva_base; + hdr->AddressOfNames = name_o + rva_base; + hdr->AddressOfNameOrdinals = ord_o + rva_base; + hdr->Name = str_o + rva_base; + put_elf_str(pe->thunk, dllname); + +#if 1 + /* automatically write exports to .def */ + strcpy(buf, pe->filename); + strcpy(tcc_fileextension(buf), ".def"); + op = fopen(buf, "w"); + if (NULL == op) { + error_noabort("could not create '%s': %s", buf, strerror(errno)); + } else { + fprintf(op, "LIBRARY %s\n\nEXPORTS\n", dllname); + if (verbose) + printf("<- %s (%d symbols)\n", buf, sym_count); + } +#endif + + for (sp = sorted, ord = 0; ord < sym_count; ++ord, sp += 2) + { + sym_index = sp[0], name = (const char *)sp[1]; + /* insert actual address later in pe_relocate_rva */ + put_elf_reloc(symtab_section, pe->thunk, + func_o, R_386_RELATIVE, sym_index); + *(DWORD*)(pe->thunk->data + name_o) + = pe->thunk->data_offset + rva_base; + *(WORD*)(pe->thunk->data + ord_o) + = ord; + put_elf_str(pe->thunk, name); + func_o += sizeof (DWORD); + name_o += sizeof (DWORD); + ord_o += sizeof (WORD); + + if (op) + fprintf(op, "%s\n", name); + } + pe->exp_size = pe->thunk->data_offset - pe->exp_offs; + tcc_free(sorted); +} + +/* ------------------------------------------------------------- */ +ST_FN void pe_build_reloc (struct pe_info *pe) +{ + DWORD offset, block_ptr, addr; + int count, i; + Elf32_Rel *rel, *rel_end; + Section *s = NULL, *sr; + + offset = addr = block_ptr = count = i = 0; + rel = rel_end = NULL; + + for(;;) { + if (rel < rel_end) { + int type = ELF32_R_TYPE(rel->r_info); + addr = rel->r_offset + s->sh_addr; + ++ rel; + if (type != R_386_32) + continue; + if (count == 0) { /* new block */ + block_ptr = pe->reloc->data_offset; + section_ptr_add(pe->reloc, sizeof(struct pe_reloc_header)); + offset = addr & 0xFFFFFFFF<<12; + } + if ((addr -= offset) < (1<<12)) { /* one block spans 4k addresses */ + WORD *wp = section_ptr_add(pe->reloc, sizeof (WORD)); + *wp = addr | IMAGE_REL_BASED_HIGHLOW<<12; + ++count; + continue; + } + -- rel; + + } else if (i < pe->sec_count) { + sr = (s = pe->s1->sections[pe->sec_info[i++].ord])->reloc; + if (sr) { + rel = (Elf32_Rel *)sr->data; + rel_end = (Elf32_Rel *)(sr->data + sr->data_offset); + } + continue; + } + + if (count) { + /* store the last block and ready for a new one */ + struct pe_reloc_header *hdr; + if (count & 1) /* align for DWORDS */ + section_ptr_add(pe->reloc, sizeof(WORD)), ++count; + hdr = (struct pe_reloc_header *)(pe->reloc->data + block_ptr); + hdr -> offset = offset - pe->imagebase; + hdr -> size = count * sizeof(WORD) + sizeof(struct pe_reloc_header); + count = 0; + } + + if (rel >= rel_end) + break; + } +} + +/* ------------------------------------------------------------- */ +ST_FN int pe_section_class(Section *s) +{ + int type, flags; + const char *name; + + type = s->sh_type; + flags = s->sh_flags; + name = s->name; + if (flags & SHF_ALLOC) { + if (type == SHT_PROGBITS) { + if (flags & SHF_EXECINSTR) + return sec_text; + if (flags & SHF_WRITE) + return sec_data; + if (0 == strcmp(name, ".rsrc")) + return sec_rsrc; + if (0 == strcmp(name, ".iedat")) + return sec_idata; + } else if (type == SHT_NOBITS) { + if (flags & SHF_WRITE) + return sec_bss; + } + } else { + if (0 == strcmp(name, ".reloc")) + return sec_reloc; + if (0 == strncmp(name, ".stab", 5)) /* .stab and .stabstr */ + return sec_stab; + } + return -1; +} + +ST_FN int pe_assign_addresses (struct pe_info *pe) +{ + int i, k, o, c; + DWORD addr; + int *section_order; + struct section_info *si; + Section *s; + + // pe->thunk = new_section(pe->s1, ".iedat", SHT_PROGBITS, SHF_ALLOC); + + section_order = tcc_malloc(pe->s1->nb_sections * sizeof (int)); + for (o = k = 0 ; k < sec_last; ++k) { + for (i = 1; i < pe->s1->nb_sections; ++i) { + s = pe->s1->sections[i]; + if (k == pe_section_class(s)) { + // printf("%s %d\n", s->name, k); + s->sh_addr = pe->imagebase; + section_order[o++] = i; + } + } + } + + pe->sec_info = tcc_mallocz(o * sizeof (struct section_info)); + addr = pe->imagebase + 1; + + for (i = 0; i < o; ++i) + { + k = section_order[i]; + s = pe->s1->sections[k]; + c = pe_section_class(s); + si = &pe->sec_info[pe->sec_count]; + +#ifdef PE_MERGE_DATA + if (c == sec_bss && pe->sec_count && si[-1].cls == sec_data) { + /* append .bss to .data */ + s->sh_addr = addr = ((addr-1) | 15) + 1; + addr += s->data_offset; + si[-1].sh_size = addr - si[-1].sh_addr; + continue; + } +#endif + strcpy(si->name, s->name); + si->cls = c; + si->ord = k; + si->sh_addr = s->sh_addr = addr = pe_virtual_align(addr); + si->sh_flags = s->sh_flags; + + if (c == sec_data && NULL == pe->thunk) + pe->thunk = s; + + if (s == pe->thunk) { + pe_build_imports(pe); + pe_build_exports(pe); + } + + if (c == sec_reloc) + pe_build_reloc (pe); + + if (s->data_offset) + { + if (s->sh_type != SHT_NOBITS) { + si->data = s->data; + si->data_size = s->data_offset; + } + + addr += s->data_offset; + si->sh_size = s->data_offset; + ++pe->sec_count; + } + // printf("%08x %05x %s\n", si->sh_addr, si->sh_size, si->name); + } + +#if 0 + for (i = 1; i < pe->s1->nb_sections; ++i) { + Section *s = pe->s1->sections[i]; + int type = s->sh_type; + int flags = s->sh_flags; + printf("section %-16s %-10s %5x %s,%s,%s\n", + s->name, + type == SHT_PROGBITS ? "progbits" : + type == SHT_NOBITS ? "nobits" : + type == SHT_SYMTAB ? "symtab" : + type == SHT_STRTAB ? "strtab" : + type == SHT_REL ? "rel" : "???", + s->data_offset, + flags & SHF_ALLOC ? "alloc" : "", + flags & SHF_WRITE ? "write" : "", + flags & SHF_EXECINSTR ? "exec" : "" + ); + } + verbose = 2; +#endif + + tcc_free(section_order); + return 0; +} + +/* ------------------------------------------------------------- */ +ST_FN void pe_relocate_rva (struct pe_info *pe, Section *s) +{ + Section *sr = s->reloc; + Elf32_Rel *rel, *rel_end; + rel_end = (Elf32_Rel *)(sr->data + sr->data_offset); + for(rel = (Elf32_Rel *)sr->data; rel < rel_end; rel++) + if (ELF32_R_TYPE(rel->r_info) == R_386_RELATIVE) { + int sym_index = ELF32_R_SYM(rel->r_info); + DWORD addr = s->sh_addr; + if (sym_index) { + Elf32_Sym *sym = (Elf32_Sym *)symtab_section->data + sym_index; + addr = sym->st_value; + } + *(DWORD*)(s->data + rel->r_offset) += addr - pe->imagebase; + } +} + +/*----------------------------------------------------------------------------*/ +ST_FN int pe_check_symbols(struct pe_info *pe) +{ + Elf32_Sym *sym; + int sym_index, sym_end; + int ret = 0; + + pe_align_section(text_section, 8); + + sym_end = symtab_section->data_offset / sizeof(Elf32_Sym); + for (sym_index = 1; sym_index < sym_end; ++sym_index) { + + sym = (Elf32_Sym*)symtab_section->data + sym_index; + if (sym->st_shndx == SHN_UNDEF) { + + const char *name = symtab_section->link->data + sym->st_name; + unsigned type = ELF32_ST_TYPE(sym->st_info); + int imp_sym = pe_find_import(pe->s1, name); + struct import_symbol *is; + + if (0 == imp_sym) + goto not_found; + is = pe_add_import(pe, imp_sym); + if (!is) + goto not_found; + + if (type == STT_FUNC) { + unsigned long offset = is->thk_offset; + if (offset) { + /* got aliased symbol, like stricmp and _stricmp */ + + } else { + char buffer[100]; + + offset = text_section->data_offset; + /* add the 'jmp IAT[x]' instruction */ + *(WORD*)section_ptr_add(text_section, 8) = 0x25FF; + + /* add a helper symbol, will be patched later in + pe_build_imports */ + sprintf(buffer, "IAT.%s", name); + is->iat_index = put_elf_sym( + symtab_section, 0, sizeof(DWORD), + ELF32_ST_INFO(STB_GLOBAL, STT_OBJECT), + 0, SHN_UNDEF, buffer); + put_elf_reloc(symtab_section, text_section, + offset + 2, R_386_32, is->iat_index); + is->thk_offset = offset; + } + + /* tcc_realloc might have altered sym's address */ + sym = (Elf32_Sym*)symtab_section->data + sym_index; + + /* patch the original symbol */ + sym->st_value = offset; + sym->st_shndx = text_section->sh_num; + sym->st_other &= ~1; /* do not export */ + continue; + } + + if (type == STT_OBJECT) { /* data, ptr to that should be */ + if (0 == is->iat_index) { + /* original symbol will be patched later in pe_build_imports */ + is->iat_index = sym_index; + continue; + } + } + + not_found: + error_noabort("undefined symbol '%s'", name); + ret = 1; + + } else if (pe->s1->rdynamic + && ELF32_ST_BIND(sym->st_info) != STB_LOCAL) { + /* if -rdynamic option, then export all non local symbols */ + sym->st_other |= 1; + } + } + return ret; +} + +/*----------------------------------------------------------------------------*/ +#ifdef PE_PRINT_SECTIONS +ST_FN void pe_print_section(FILE * f, Section * s) +{ + /* just if you'r curious */ + BYTE *p, *e, b; + int i, n, l, m; + p = s->data; + e = s->data + s->data_offset; + l = e - p; + + fprintf(f, "section \"%s\"", s->name); + if (s->link) + fprintf(f, "\nlink \"%s\"", s->link->name); + if (s->reloc) + fprintf(f, "\nreloc \"%s\"", s->reloc->name); + fprintf(f, "\nv_addr %08X", s->sh_addr); + fprintf(f, "\ncontents %08X", l); + fprintf(f, "\n\n"); + + if (s->sh_type == SHT_NOBITS) + return; + + if (0 == l) + return; + + if (s->sh_type == SHT_SYMTAB) + m = sizeof(Elf32_Sym); + if (s->sh_type == SHT_REL) + m = sizeof(Elf32_Rel); + else + m = 16; + + fprintf(f, "%-8s", "offset"); + for (i = 0; i < m; ++i) + fprintf(f, " %02x", i); + n = 56; + + if (s->sh_type == SHT_SYMTAB || s->sh_type == SHT_REL) { + const char *fields1[] = { + "name", + "value", + "size", + "bind", + "type", + "other", + "shndx", + NULL + }; + + const char *fields2[] = { + "offs", + "type", + "symb", + NULL + }; + + const char **p; + + if (s->sh_type == SHT_SYMTAB) + p = fields1, n = 106; + else + p = fields2, n = 58; + + for (i = 0; p[i]; ++i) + fprintf(f, "%6s", p[i]); + fprintf(f, " symbol"); + } + + fprintf(f, "\n"); + for (i = 0; i < n; ++i) + fprintf(f, "-"); + fprintf(f, "\n"); + + for (i = 0; i < l;) + { + fprintf(f, "%08X", i); + for (n = 0; n < m; ++n) { + if (n + i < l) + fprintf(f, " %02X", p[i + n]); + else + fprintf(f, " "); + } + + if (s->sh_type == SHT_SYMTAB) { + Elf32_Sym *sym = (Elf32_Sym *) (p + i); + const char *name = s->link->data + sym->st_name; + fprintf(f, " %04X %04X %04X %02X %02X %02X %04X \"%s\"", + sym->st_name, + sym->st_value, + sym->st_size, + ELF32_ST_BIND(sym->st_info), + ELF32_ST_TYPE(sym->st_info), + sym->st_other, sym->st_shndx, name); + + } else if (s->sh_type == SHT_REL) { + Elf32_Rel *rel = (Elf32_Rel *) (p + i); + Elf32_Sym *sym = + (Elf32_Sym *) s->link->data + ELF32_R_SYM(rel->r_info); + const char *name = s->link->link->data + sym->st_name; + fprintf(f, " %04X %02X %04X \"%s\"", + rel->r_offset, + ELF32_R_TYPE(rel->r_info), + ELF32_R_SYM(rel->r_info), name); + } else { + fprintf(f, " "); + for (n = 0; n < m; ++n) { + if (n + i < l) { + b = p[i + n]; + if (b < 32 || b >= 127) + b = '.'; + fprintf(f, "%c", b); + } + } + } + i += m; + fprintf(f, "\n"); + } + fprintf(f, "\n\n"); +} + +ST_FN void pe_print_sections(TCCState *s1, const char *fname) +{ + Section *s; + FILE *f; + int i; + f = fopen(fname, "wt"); + for (i = 1; i < s1->nb_sections; ++i) { + s = s1->sections[i]; + pe_print_section(f, s); + } + pe_print_section(f, s1->dynsymtab_section); + fclose(f); +} +#endif + +/* ------------------------------------------------------------- + * This is for compiled windows resources in 'coff' format + * as generated by 'windres.exe -O coff ...'. + */ + +PUB_FN int pe_test_res_file(void *v, int size) +{ + struct pe_rsrc_header *p = (struct pe_rsrc_header *)v; + return + size >= IMAGE_SIZEOF_FILE_HEADER + IMAGE_SIZEOF_SHORT_NAME /* = 28 */ + && p->filehdr.Machine == 0x014C + && 1 == p->filehdr.NumberOfSections + && 0 == strcmp(p->sectionhdr.Name, ".rsrc") + ; +} + +ST_FN int read_n(int fd, void *ptr, unsigned size) +{ + return size == read(fd, ptr, size); +} + +PUB_FN int pe_load_res_file(TCCState *s1, int fd) +{ + struct pe_rsrc_header hdr; + Section *rsrc_section; + int i, ret = -1; + BYTE *ptr; + + lseek (fd, 0, SEEK_SET); + if (!read_n(fd, &hdr, sizeof hdr)) + goto quit; + if (!pe_test_res_file(&hdr, sizeof hdr)) + goto quit; + + rsrc_section = new_section(s1, ".rsrc", SHT_PROGBITS, SHF_ALLOC); + ptr = section_ptr_add(rsrc_section, hdr.sectionhdr.SizeOfRawData); + lseek (fd, hdr.sectionhdr.PointerToRawData, SEEK_SET); + if (!read_n(fd, ptr, hdr.sectionhdr.SizeOfRawData)) + goto quit; + + lseek (fd, hdr.sectionhdr.PointerToRelocations, SEEK_SET); + for (i = 0; i < hdr.sectionhdr.NumberOfRelocations; ++i) + { + struct pe_rsrc_reloc rel; + if (!read_n(fd, &rel, sizeof rel)) + goto quit; + // printf("rsrc_reloc: %x %x %x\n", rel.offset, rel.size, rel.type); + if (rel.type != 7) /* DIR32NB */ + goto quit; + put_elf_reloc(symtab_section, rsrc_section, + rel.offset, R_386_RELATIVE, 0); + } + ret = 0; +quit: + if (ret) + error_noabort("unrecognized resource file format"); + return ret; +} + +/* ------------------------------------------------------------- */ +ST_FN char *trimfront(char *p) +{ + while (*p && (unsigned char)*p <= ' ') + ++p; + return p; +} + +ST_FN char *trimback(char *a, char *e) +{ + while (e > a && (unsigned char)e[-1] <= ' ') + --e; + *e = 0;; + return a; +} + +ST_FN char *get_line(char *line, int size, FILE *fp) +{ + if (NULL == fgets(line, size, fp)) + return NULL; + trimback(line, strchr(line, 0)); + return trimfront(line); +} + +/* ------------------------------------------------------------- */ +PUB_FN int pe_load_def_file(TCCState *s1, int fd) +{ + DLLReference *dllref; + int state = 0, ret = -1; + char line[400], dllname[80], *p; + FILE *fp = fdopen(dup(fd), "rb"); + + if (NULL == fp) + goto quit; + + for (;;) { + p = get_line(line, sizeof line, fp); + if (NULL == p) + break; + if (0 == *p || ';' == *p) + continue; + switch (state) { + case 0: + if (0 != strnicmp(p, "LIBRARY", 7)) + goto quit; + strcpy(dllname, trimfront(p+7)); + ++state; + continue; + + case 1: + if (0 != stricmp(p, "EXPORTS")) + goto quit; + ++state; + continue; + + case 2: + dllref = tcc_malloc(sizeof(DLLReference) + strlen(dllname)); + strcpy(dllref->name, dllname); + dllref->level = 0; + dynarray_add((void ***) &s1->loaded_dlls, &s1->nb_loaded_dlls, dllref); + ++state; + + default: + add_elf_sym(s1->dynsymtab_section, + s1->nb_loaded_dlls, 0, + ELF32_ST_INFO(STB_GLOBAL, STT_FUNC), 0, + text_section->sh_num, p); + continue; + } + } + ret = 0; +quit: + if (fp) + fclose(fp); + if (ret) + error_noabort("unrecognized export definition file format"); + return ret; +} + +/* ------------------------------------------------------------- */ + +ST_FN void pe_add_runtime_ex(TCCState *s1, struct pe_info *pe) +{ + const char *start_symbol; + unsigned long addr = 0; + int pe_type = 0; + + if (find_elf_sym(symtab_section, "_WinMain@16")) + pe_type = PE_GUI; + else + if (TCC_OUTPUT_DLL == s1->output_type) { + pe_type = PE_DLL; + /* need this for 'tccelf.c:relocate_section()' */ + s1->output_type = TCC_OUTPUT_EXE; + } + + start_symbol = + TCC_OUTPUT_MEMORY == s1->output_type + ? PE_GUI == pe_type ? "_runwinmain" : NULL + : PE_DLL == pe_type ? "__dllstart@12" + : PE_GUI == pe_type ? "_winstart" : "_start" + ; + + /* grab the startup code from libtcc1 */ + if (start_symbol) + add_elf_sym(symtab_section, + 0, 0, + ELF32_ST_INFO(STB_GLOBAL, STT_NOTYPE), 0, + SHN_UNDEF, start_symbol); + + if (0 == s1->nostdlib) { + tcc_add_library(s1, "tcc1"); +#ifdef __CYGWIN__ + tcc_add_library(s1, "cygwin1"); +#else + tcc_add_library(s1, "msvcrt"); +#endif + tcc_add_library(s1, "kernel32"); + if (PE_DLL == pe_type || PE_GUI == pe_type) { + tcc_add_library(s1, "user32"); + tcc_add_library(s1, "gdi32"); + } + } + + if (start_symbol) { + addr = (unsigned long)tcc_get_symbol_err(s1, start_symbol); + if (s1->output_type == TCC_OUTPUT_MEMORY && addr) + /* for -run GUI's, put '_runwinmain' instead of 'main' */ + add_elf_sym(symtab_section, + addr, 0, + ELF32_ST_INFO(STB_GLOBAL, STT_NOTYPE), 0, + text_section->sh_num, "main"); + } + + if (pe) { + pe->type = pe_type; + pe->start_addr = addr; + } +} + +PUB_FN void pe_add_runtime(TCCState *s1) +{ + pe_add_runtime_ex(s1, NULL); +} + +PUB_FN int pe_output_file(TCCState * s1, const char *filename) +{ + int ret; + struct pe_info pe; + int i; + + memset(&pe, 0, sizeof pe); + pe.filename = filename; + pe.s1 = s1; + + pe_add_runtime_ex(s1, &pe); + relocate_common_syms(); /* assign bss adresses */ + tcc_add_linker_symbols(s1); + + ret = pe_check_symbols(&pe); + if (0 == ret) { + if (PE_DLL == pe.type) { + pe.reloc = new_section(pe.s1, ".reloc", SHT_PROGBITS, 0); + pe.imagebase = 0x10000000; + } else { + pe.imagebase = 0x00400000; + } + pe_assign_addresses(&pe); + relocate_syms(s1, 0); + for (i = 1; i < s1->nb_sections; ++i) { + Section *s = s1->sections[i]; + if (s->reloc) { + relocate_section(s1, s); + pe_relocate_rva(&pe, s); + } + } + if (s1->nb_errors) + ret = 1; + else + ret = pe_write(&pe); + tcc_free(pe.sec_info); + } + +#ifdef PE_PRINT_SECTIONS + pe_print_sections(s1, "tcc.log"); +#endif + return ret; +} + +/* ------------------------------------------------------------- */ +#endif /* def TCC_TARGET_PE */ +/* ------------------------------------------------------------- */ diff --git a/win32/readme.txt b/win32/readme.txt dissimilarity index 97% index 1ad30f3b..c453a696 100644 --- a/win32/readme.txt +++ b/win32/readme.txt @@ -1,115 +1,126 @@ - - TinyCC-PE - --------- - - TinyCC (aka TCC) is a small but hyperfast C compiler, - written by Fabrice Bellard, - - - TinyCC-PE is the TinyCC compiler with an extension to - write PE executables for MS-Windows. - - - Features: - --------- - - TinyCC-PE can produce console applications, native windows - GUI programs and DLL's. - - Most of the features pointed out by Fabrice Bellard for the - original version are still valid, i.e: - - - SMALL! The package with ~400kb includes a complete C-compiler - with header files for console and GUI applications. - - - With the -run switch you can run C-sources without any - linking directly from the command line. - - - TCC can of course compile itself. - - - Compilation: (omit that if you use the binary ZIP package) - ------------ - - You must use the MinGW and MSYS tools available at - http://www.mingw.org to compile TCC for Windows. Untar the TCC - archive and type in the MSYS shell: - - ./configure - make - make install - - TCC is installed in c:\Program Files\tcc - - Installation: (from the binary ZIP package) - ------------- - - Just unzip the package to a directory anywhere on your computer. - - - Examples: - --------- - - For the 'Fibonacci' console example type from the command line: - - tcc examples\fib.c - - - For the 'Hello Windows' GUI example: - - tcc examples\hello_win.c - - - For the 'Hello DLL' example: - - tcc -shared examples\dll.c - tcc examples\hello_dll.c examples\dll.def - - - Import Definitions: - ------------------- - - TinyCC-PE searches and reads import definition files similar - to libraries. - - The included 'tiny_impdef' program may be used to make .def files - for any DLL, e.g for an 'opengl32.def': - - tiny_impdef.exe opengl32.dll - - or to the same effect: - - tcc -lkernel32 -run tiny_impdef.c opengl32.dll - - - Header Files: - ------------- - - The system header files, except '_mingw.h', are from the - 2.0 mingw distribution. See also: http://www.mingw.org/ - - - Compile TCC: - ------------ - - With TCC itself just say: - - tcc src\tcc.c -lkernel32 -o tcc.new.exe - - Other compilers like mingw-gcc or msvc work as well. - To make libtcc1.a, you need 'ar' from the mingw binutils. - - - Documentation and License: - -------------------------- - - TCC is distributed under the GNU Lesser General Public License - (see COPYING file). - - Please read the original tcc-doc.html to have all the features - of TCC. Also visit: http://fabrice.bellard.free.fr/tcc/ - - - -------------------------------------------- - 09.Apr.2005 - grischka@users.sourceforge.net - + + TinyCC-PE + --------- + + TinyCC (aka TCC) is a small but hyperfast C compiler, + written by Fabrice Bellard, + + + TinyCC-PE is the TinyCC compiler with an extension to + write PE executables for MS-Windows. + + + Features: + --------- + + TinyCC-PE can produce console applications, native windows + GUI programs and DLL's. + + Most of the features pointed out by Fabrice Bellard for the + original version are still valid, i.e: + + - SMALL! The package with ~400kb includes a complete C-compiler + with header files for console and GUI applications. + + - With the -run switch you can run C-sources without any + linking directly from the command line. + + - TCC can of course compile itself. + + + Compilation: (omit that if you use the binary ZIP package) + ------------ + + You must use the MinGW and MSYS tools available at + http://www.mingw.org to compile TCC for Windows. Untar the TCC + archive and type in the MSYS shell: + + ./configure + make + make install + + TCC is installed in c:\Program Files\tcc + + Alternatively you can use win32\build-tcc.bat to compile TCC + with just gcc and ar from MINGW. To install, copy the entire + contents of the win32 directory to where you want. + + + Installation: (from the binary ZIP package) + ------------- + + Just unzip the package to a directory anywhere on your computer. + + + Examples: + --------- + + For the 'Fibonacci' console example type from the command line: + + tcc examples\fib.c + + For the 'Hello Windows' GUI example: + + tcc examples\hello_win.c + + For the 'Hello DLL' example: + + tcc -shared examples\dll.c + tcc examples\hello_dll.c examples\dll.def + + + Import Definitions: + ------------------- + + TinyCC-PE searches and reads import definition files similar + to libraries. + + The included 'tiny_impdef' program may be used to make .def files + for any DLL, e.g for an 'opengl32.def': + + tiny_impdef.exe opengl32.dll + + or to the same effect: + + tcc -run tiny_impdef.c opengl32.dll + + + Resource Files: + --------------- + + TinyCC-PE can now link windows resources in coff format as generated + by MINGW's windres.exe. For example: + + windres -O coff app.rc -o appres.o + tcc app.c appres.o -o app.exe + + + Header Files: + ------------- + + The system header files, except '_mingw.h', are from the + 3.7 mingw distribution. See also: http://www.mingw.org/ + + + Compile TCC: + ------------ + + With TCC itself just say: + + tcc src\tcc.c -o tcc.new.exe + + Other compilers like mingw-gcc or msvc work as well. + To make libtcc1.a, you need 'ar' from the mingw binutils. + + + Documentation and License: + -------------------------- + + TCC is distributed under the GNU Lesser General Public License + (see COPYING file). + + Please read the original tcc-doc.html to have all the features + of TCC. Also visit: http://fabrice.bellard.free.fr/tcc/ + + -- + grischka@users.sourceforge.net -- 2.11.4.GIT