From 51f15d997162927a432db09dad13ca16b014a3e2 Mon Sep 17 00:00:00 2001 From: Michael Matz Date: Mon, 18 May 2020 05:15:08 +0200 Subject: [PATCH] macos: Deal with leading underscore on Mach-O all C/C++/ObjC symbols in symbols tables have a leading underscore in Mach-O. Within TCC there's some confusion with tcc_add_symbol (not adding it) and tcc_get_elf_symbol (not expecting it), and resolve_syms (using dlsym, which doesn't expect it) and -run support. But this sort of works. --- libtcc.c | 2 +- tccelf.c | 6 ++++++ tccmacho.c | 2 +- tccrun.c | 2 +- 4 files changed, 9 insertions(+), 3 deletions(-) diff --git a/libtcc.c b/libtcc.c index 7224c521..61168deb 100644 --- a/libtcc.c +++ b/libtcc.c @@ -777,7 +777,7 @@ LIBTCCAPI TCCState *tcc_new(void) s->seg_size = 32; #endif /* enable this if you want symbols with leading underscore on windows: */ -#if 0 /* def TCC_TARGET_PE */ +#if defined TCC_TARGET_MACHO /* || defined TCC_TARGET_PE */ s->leading_underscore = 1; #endif s->ppfp = stdout; diff --git a/tccelf.c b/tccelf.c index 58f24a24..99effb6b 100644 --- a/tccelf.c +++ b/tccelf.c @@ -932,7 +932,13 @@ ST_FUNC void relocate_syms(TCCState *s1, Section *symtab, int do_resolve) /* Use ld.so to resolve symbol for us (for tcc -run) */ if (do_resolve) { #if defined TCC_IS_NATIVE && !defined TCC_TARGET_PE +#ifdef TCC_TARGET_MACHO + /* The symbols in the symtables have a prepended '_' + but dlsym() needs the undecorated name. */ + void *addr = dlsym(RTLD_DEFAULT, name + 1); +#else void *addr = dlsym(RTLD_DEFAULT, name); +#endif if (addr) { sym->st_value = (addr_t) addr; #ifdef DEBUG_RELOC diff --git a/tccmacho.c b/tccmacho.c index 77e5454e..69af3ecc 100644 --- a/tccmacho.c +++ b/tccmacho.c @@ -810,7 +810,7 @@ ST_FUNC int macho_output_file(TCCState *s1, const char *filename) Section *s; collect_sections(s1, &mo); relocate_syms(s1, s1->symtab, 0); - mo.ep.entryoff = get_elf_sym_addr(s1, "main", 1) - mo.seg[1]->vmaddr; + mo.ep.entryoff = get_elf_sym_addr(s1, "_main", 1) - mo.seg[1]->vmaddr; if (s1->nb_errors) goto do_ret; diff --git a/tccrun.c b/tccrun.c index 8b7c9e44..92b0e647 100644 --- a/tccrun.c +++ b/tccrun.c @@ -140,7 +140,7 @@ LIBTCCAPI int tcc_run(TCCState *s1, int argc, char **argv) rt_context *rc = &g_rtctxt; #endif - s1->runtime_main = s1->nostdlib ? "_start" : "main"; + s1->runtime_main = s1->nostdlib ? "_start" : s1->leading_underscore ? "_main" : "main"; if ((s1->dflag & 16) && !find_elf_sym(s1->symtab, s1->runtime_main)) return 0; #ifdef CONFIG_TCC_BACKTRACE