From 926797a8a92a009184556ed45e02f3292066a296 Mon Sep 17 00:00:00 2001 From: Dmitriy Ivanov Date: Fri, 12 Sep 2014 09:43:13 -0700 Subject: [PATCH 01/20] Reformatting No functional changes. Bug: 18186310 (cherry picked from commit 6abf624d122bec8c80cc9fe1b692265bf1b28b1b)] Change-Id: I0acf52d8ee7fe2d4f44bc832cbe9fabe1782f03f --- linker/linker.cpp | 2078 ++++++++++++++++++++++----------------------- 1 file changed, 1037 insertions(+), 1041 deletions(-) diff --git a/linker/linker.cpp b/linker/linker.cpp index 9425c9d3b..37e01893f 100644 --- a/linker/linker.cpp +++ b/linker/linker.cpp @@ -88,7 +88,7 @@ static LinkerAllocator> g_soinfo_links_allocator; static soinfo* solist; static soinfo* sonext; -static soinfo* somain; /* main process, always the one after libdl_info */ +static soinfo* somain; // main process, always the one after libdl_info static const char* const kDefaultLdPaths[] = { #if defined(__LP64__) @@ -120,22 +120,22 @@ __LIBC_HIDDEN__ int g_ld_debug_verbosity; __LIBC_HIDDEN__ abort_msg_t* g_abort_message = nullptr; // For debuggerd. enum RelocationKind { - kRelocAbsolute = 0, - kRelocRelative, - kRelocCopy, - kRelocSymbol, - kRelocMax + kRelocAbsolute = 0, + kRelocRelative, + kRelocCopy, + kRelocSymbol, + kRelocMax }; #if STATS struct linker_stats_t { - int count[kRelocMax]; + int count[kRelocMax]; }; static linker_stats_t linker_stats; static void count_relocation(RelocationKind kind) { - ++linker_stats.count[kind]; + ++linker_stats.count[kind]; } #else static void count_relocation(RelocationKind) { @@ -147,13 +147,13 @@ static unsigned bitmask[4096]; #if defined(__LP64__) #define MARK(offset) \ do { \ - if ((((offset) >> 12) >> 5) < 4096) \ - bitmask[((offset) >> 12) >> 5] |= (1 << (((offset) >> 12) & 31)); \ + if ((((offset) >> 12) >> 5) < 4096) \ + bitmask[((offset) >> 12) >> 5] |= (1 << (((offset) >> 12) & 31)); \ } while (0) #else #define MARK(offset) \ do { \ - bitmask[((offset) >> 12) >> 3] |= (1 << (((offset) >> 12) & 7)); \ + bitmask[((offset) >> 12) >> 3] |= (1 << (((offset) >> 12) & 7)); \ } while (0) #endif #else @@ -165,7 +165,7 @@ static unsigned bitmask[4096]; #define DISALLOW_ALLOCATION(return_type, name, ...) \ return_type name __VA_ARGS__ \ { \ - __libc_fatal("ERROR: " #name " called from the dynamic linker!\n"); \ + __libc_fatal("ERROR: " #name " called from the dynamic linker!\n"); \ } DISALLOW_ALLOCATION(void*, malloc, (size_t u __unused)); DISALLOW_ALLOCATION(void, free, (void* u __unused)); @@ -182,10 +182,8 @@ size_t linker_get_error_buffer_size() { return sizeof(__linker_dl_err_buf); } -/* - * This function is an empty stub where GDB locates a breakpoint to get notified - * about linker activity. - */ +// This function is an empty stub where GDB locates a breakpoint to get notified +// about linker activity. extern "C" void __attribute__((noinline)) __attribute__((visibility("default"))) rtld_db_dlactivity(); static pthread_mutex_t g__r_debug_mutex = PTHREAD_MUTEX_INITIALIZER; @@ -193,76 +191,75 @@ static r_debug _r_debug = {1, nullptr, reinterpret_cast(&rtld_db_dlac static link_map* r_debug_tail = 0; static void insert_soinfo_into_debug_map(soinfo* info) { - // Copy the necessary fields into the debug structure. - link_map* map = &(info->link_map_head); - map->l_addr = info->load_bias; - map->l_name = reinterpret_cast(info->name); - map->l_ld = info->dynamic; + // Copy the necessary fields into the debug structure. + link_map* map = &(info->link_map_head); + map->l_addr = info->load_bias; + map->l_name = reinterpret_cast(info->name); + map->l_ld = info->dynamic; - /* Stick the new library at the end of the list. - * gdb tends to care more about libc than it does - * about leaf libraries, and ordering it this way - * reduces the back-and-forth over the wire. - */ - if (r_debug_tail) { - r_debug_tail->l_next = map; - map->l_prev = r_debug_tail; - map->l_next = 0; - } else { - _r_debug.r_map = map; - map->l_prev = 0; - map->l_next = 0; - } - r_debug_tail = map; + // Stick the new library at the end of the list. + // gdb tends to care more about libc than it does + // about leaf libraries, and ordering it this way + // reduces the back-and-forth over the wire. + if (r_debug_tail) { + r_debug_tail->l_next = map; + map->l_prev = r_debug_tail; + map->l_next = 0; + } else { + _r_debug.r_map = map; + map->l_prev = 0; + map->l_next = 0; + } + r_debug_tail = map; } static void remove_soinfo_from_debug_map(soinfo* info) { - link_map* map = &(info->link_map_head); + link_map* map = &(info->link_map_head); - if (r_debug_tail == map) { - r_debug_tail = map->l_prev; - } + if (r_debug_tail == map) { + r_debug_tail = map->l_prev; + } - if (map->l_prev) { - map->l_prev->l_next = map->l_next; - } - if (map->l_next) { - map->l_next->l_prev = map->l_prev; - } + if (map->l_prev) { + map->l_prev->l_next = map->l_next; + } + if (map->l_next) { + map->l_next->l_prev = map->l_prev; + } } static void notify_gdb_of_load(soinfo* info) { - if (info->flags & FLAG_EXE) { - // GDB already knows about the main executable - return; - } + if (info->flags & FLAG_EXE) { + // GDB already knows about the main executable + return; + } - ScopedPthreadMutexLocker locker(&g__r_debug_mutex); + ScopedPthreadMutexLocker locker(&g__r_debug_mutex); - _r_debug.r_state = r_debug::RT_ADD; - rtld_db_dlactivity(); + _r_debug.r_state = r_debug::RT_ADD; + rtld_db_dlactivity(); - insert_soinfo_into_debug_map(info); + insert_soinfo_into_debug_map(info); - _r_debug.r_state = r_debug::RT_CONSISTENT; - rtld_db_dlactivity(); + _r_debug.r_state = r_debug::RT_CONSISTENT; + rtld_db_dlactivity(); } static void notify_gdb_of_unload(soinfo* info) { - if (info->flags & FLAG_EXE) { - // GDB already knows about the main executable - return; - } + if (info->flags & FLAG_EXE) { + // GDB already knows about the main executable + return; + } - ScopedPthreadMutexLocker locker(&g__r_debug_mutex); + ScopedPthreadMutexLocker locker(&g__r_debug_mutex); - _r_debug.r_state = r_debug::RT_DELETE; - rtld_db_dlactivity(); + _r_debug.r_state = r_debug::RT_DELETE; + rtld_db_dlactivity(); - remove_soinfo_from_debug_map(info); + remove_soinfo_from_debug_map(info); - _r_debug.r_state = r_debug::RT_CONSISTENT; - rtld_db_dlactivity(); + _r_debug.r_state = r_debug::RT_CONSISTENT; + rtld_db_dlactivity(); } void notify_gdb_of_libraries() { @@ -301,41 +298,41 @@ static soinfo* soinfo_alloc(const char* name, struct stat* file_stat, off64_t fi } static void soinfo_free(soinfo* si) { - if (si == nullptr) { - return; + if (si == nullptr) { + return; + } + + if (si->base != 0 && si->size != 0) { + munmap(reinterpret_cast(si->base), si->size); + } + + soinfo *prev = nullptr, *trav; + + TRACE("name %s: freeing soinfo @ %p", si->name, si); + + for (trav = solist; trav != nullptr; trav = trav->next) { + if (trav == si) { + break; } + prev = trav; + } + if (trav == nullptr) { + // si was not in solist + DL_ERR("name \"%s\" is not in solist!", si->name); + return; + } - if (si->base != 0 && si->size != 0) { - munmap(reinterpret_cast(si->base), si->size); - } + // clear links to/from si + si->remove_all_links(); - soinfo *prev = nullptr, *trav; + // prev will never be null, because the first entry in solist is + // always the static libdl_info. + prev->next = si->next; + if (si == sonext) { + sonext = prev; + } - TRACE("name %s: freeing soinfo @ %p", si->name, si); - - for (trav = solist; trav != nullptr; trav = trav->next) { - if (trav == si) - break; - prev = trav; - } - if (trav == nullptr) { - /* si was not in solist */ - DL_ERR("name \"%s\" is not in solist!", si->name); - return; - } - - // clear links to/from si - si->remove_all_links(); - - /* prev will never be null, because the first entry in solist is - always the static libdl_info. - */ - prev->next = si->next; - if (si == sonext) { - sonext = prev; - } - - g_soinfo_allocator.free(si); + g_soinfo_allocator.free(si); } @@ -377,46 +374,45 @@ static void parse_LD_PRELOAD(const char* path) { #if defined(__arm__) -/* For a given PC, find the .so that it belongs to. - * Returns the base address of the .ARM.exidx section - * for that .so, and the number of 8-byte entries - * in that section (via *pcount). - * - * Intended to be called by libc's __gnu_Unwind_Find_exidx(). - * - * This function is exposed via dlfcn.cpp and libdl.so. - */ +// For a given PC, find the .so that it belongs to. +// Returns the base address of the .ARM.exidx section +// for that .so, and the number of 8-byte entries +// in that section (via *pcount). +// +// Intended to be called by libc's __gnu_Unwind_Find_exidx(). +// +// This function is exposed via dlfcn.cpp and libdl.so. _Unwind_Ptr dl_unwind_find_exidx(_Unwind_Ptr pc, int* pcount) { - unsigned addr = (unsigned)pc; + unsigned addr = (unsigned)pc; - for (soinfo* si = solist; si != 0; si = si->next) { - if ((addr >= si->base) && (addr < (si->base + si->size))) { - *pcount = si->ARM_exidx_count; - return (_Unwind_Ptr)si->ARM_exidx; - } + for (soinfo* si = solist; si != 0; si = si->next) { + if ((addr >= si->base) && (addr < (si->base + si->size))) { + *pcount = si->ARM_exidx_count; + return (_Unwind_Ptr)si->ARM_exidx; } - *pcount = 0; - return nullptr; + } + *pcount = 0; + return nullptr; } #endif -/* Here, we only have to provide a callback to iterate across all the - * loaded libraries. gcc_eh does the rest. */ +// Here, we only have to provide a callback to iterate across all the +// loaded libraries. gcc_eh does the rest. int dl_iterate_phdr(int (*cb)(dl_phdr_info* info, size_t size, void* data), void* data) { - int rv = 0; - for (soinfo* si = solist; si != nullptr; si = si->next) { - dl_phdr_info dl_info; - dl_info.dlpi_addr = si->link_map_head.l_addr; - dl_info.dlpi_name = si->link_map_head.l_name; - dl_info.dlpi_phdr = si->phdr; - dl_info.dlpi_phnum = si->phnum; - rv = cb(&dl_info, sizeof(dl_phdr_info), data); - if (rv != 0) { - break; - } + int rv = 0; + for (soinfo* si = solist; si != nullptr; si = si->next) { + dl_phdr_info dl_info; + dl_info.dlpi_addr = si->link_map_head.l_addr; + dl_info.dlpi_name = si->link_map_head.l_name; + dl_info.dlpi_phdr = si->phdr; + dl_info.dlpi_phnum = si->phnum; + rv = cb(&dl_info, sizeof(dl_phdr_info), data); + if (rv != 0) { + break; } - return rv; + } + return rv; } static ElfW(Sym)* soinfo_elf_lookup(soinfo* si, unsigned hash, const char* name) { @@ -430,7 +426,7 @@ static ElfW(Sym)* soinfo_elf_lookup(soinfo* si, unsigned hash, const char* name) ElfW(Sym)* s = symtab + n; if (strcmp(strtab + s->st_name, name)) continue; - /* only concern ourselves with global and weak symbol definitions */ + // only concern ourselves with global and weak symbol definitions switch (ELF_ST_BIND(s->st_info)) { case STB_GLOBAL: case STB_WEAK: @@ -472,134 +468,134 @@ soinfo::soinfo(const char* name, const struct stat* file_stat, off64_t file_offs } static unsigned elfhash(const char* _name) { - const unsigned char* name = reinterpret_cast(_name); - unsigned h = 0, g; + const unsigned char* name = reinterpret_cast(_name); + unsigned h = 0, g; - while (*name) { - h = (h << 4) + *name++; - g = h & 0xf0000000; - h ^= g; - h ^= g >> 24; - } - return h; + while (*name) { + h = (h << 4) + *name++; + g = h & 0xf0000000; + h ^= g; + h ^= g >> 24; + } + return h; } static ElfW(Sym)* soinfo_do_lookup(soinfo* si, const char* name, soinfo** lsi) { - unsigned elf_hash = elfhash(name); - ElfW(Sym)* s = nullptr; + unsigned elf_hash = elfhash(name); + ElfW(Sym)* s = nullptr; - if (somain != nullptr) { - /* - * Local scope is executable scope. Just start looking into it right away - * for the shortcut. - */ + if (somain != nullptr) { + /* + * Local scope is executable scope. Just start looking into it right away + * for the shortcut. + */ - if (si == somain) { - s = soinfo_elf_lookup(si, elf_hash, name); - if (s != nullptr) { - *lsi = si; - goto done; - } + if (si == somain) { + s = soinfo_elf_lookup(si, elf_hash, name); + if (s != nullptr) { + *lsi = si; + goto done; + } - /* Next, look for it in the preloads list */ - for (int i = 0; g_ld_preloads[i] != NULL; i++) { - s = soinfo_elf_lookup(g_ld_preloads[i], elf_hash, name); - if (s != NULL) { - *lsi = g_ld_preloads[i]; - goto done; - } - } - } else { - /* Order of symbol lookup is controlled by DT_SYMBOLIC flag */ - - /* - * If this object was built with symbolic relocations disabled, the - * first place to look to resolve external references is the main - * executable. - */ - - if (!si->has_DT_SYMBOLIC) { - DEBUG("%s: looking up %s in executable %s", - si->name, name, somain->name); - s = soinfo_elf_lookup(somain, elf_hash, name); - if (s != nullptr) { - *lsi = somain; - goto done; - } - - /* Next, look for it in the preloads list */ - for (int i = 0; g_ld_preloads[i] != NULL; i++) { - s = soinfo_elf_lookup(g_ld_preloads[i], elf_hash, name); - if (s != NULL) { - *lsi = g_ld_preloads[i]; - goto done; - } - } - } - - /* Look for symbols in the local scope (the object who is - * searching). This happens with C++ templates on x86 for some - * reason. - * - * Notes on weak symbols: - * The ELF specs are ambiguous about treatment of weak definitions in - * dynamic linking. Some systems return the first definition found - * and some the first non-weak definition. This is system dependent. - * Here we return the first definition found for simplicity. */ - - s = soinfo_elf_lookup(si, elf_hash, name); - if (s != nullptr) { - *lsi = si; - goto done; - } - - /* - * If this object was built with -Bsymbolic and symbol is not found - * in the local scope, try to find the symbol in the main executable. - */ - - if (si->has_DT_SYMBOLIC) { - DEBUG("%s: looking up %s in executable %s after local scope", - si->name, name, somain->name); - s = soinfo_elf_lookup(somain, elf_hash, name); - if (s != nullptr) { - *lsi = somain; - goto done; - } - - /* Next, look for it in the preloads list */ - for (int i = 0; g_ld_preloads[i] != NULL; i++) { - s = soinfo_elf_lookup(g_ld_preloads[i], elf_hash, name); - if (s != NULL) { - *lsi = g_ld_preloads[i]; - goto done; - } - } - } + /* Next, look for it in the preloads list */ + for (int i = 0; g_ld_preloads[i] != NULL; i++) { + s = soinfo_elf_lookup(g_ld_preloads[i], elf_hash, name); + if (s != NULL) { + *lsi = g_ld_preloads[i]; + goto done; } - } + } + } else { + /* Order of symbol lookup is controlled by DT_SYMBOLIC flag */ - si->get_children().visit([&](soinfo* child) { - DEBUG("%s: looking up %s in %s", si->name, name, child->name); - s = soinfo_elf_lookup(child, elf_hash, name); + /* + * If this object was built with symbolic relocations disabled, the + * first place to look to resolve external references is the main + * executable. + */ + + if (!si->has_DT_SYMBOLIC) { + DEBUG("%s: looking up %s in executable %s", + si->name, name, somain->name); + s = soinfo_elf_lookup(somain, elf_hash, name); if (s != nullptr) { - *lsi = child; - return false; + *lsi = somain; + goto done; } - return true; - }); + + /* Next, look for it in the preloads list */ + for (int i = 0; g_ld_preloads[i] != NULL; i++) { + s = soinfo_elf_lookup(g_ld_preloads[i], elf_hash, name); + if (s != NULL) { + *lsi = g_ld_preloads[i]; + goto done; + } + } + } + + /* Look for symbols in the local scope (the object who is + * searching). This happens with C++ templates on x86 for some + * reason. + * + * Notes on weak symbols: + * The ELF specs are ambiguous about treatment of weak definitions in + * dynamic linking. Some systems return the first definition found + * and some the first non-weak definition. This is system dependent. + * Here we return the first definition found for simplicity. */ + + s = soinfo_elf_lookup(si, elf_hash, name); + if (s != nullptr) { + *lsi = si; + goto done; + } + + /* + * If this object was built with -Bsymbolic and symbol is not found + * in the local scope, try to find the symbol in the main executable. + */ + + if (si->has_DT_SYMBOLIC) { + DEBUG("%s: looking up %s in executable %s after local scope", + si->name, name, somain->name); + s = soinfo_elf_lookup(somain, elf_hash, name); + if (s != nullptr) { + *lsi = somain; + goto done; + } + + /* Next, look for it in the preloads list */ + for (int i = 0; g_ld_preloads[i] != NULL; i++) { + s = soinfo_elf_lookup(g_ld_preloads[i], elf_hash, name); + if (s != NULL) { + *lsi = g_ld_preloads[i]; + goto done; + } + } + } + } + } + + si->get_children().visit([&](soinfo* child) { + DEBUG("%s: looking up %s in %s", si->name, name, child->name); + s = soinfo_elf_lookup(child, elf_hash, name); + if (s != nullptr) { + *lsi = child; + return false; + } + return true; + }); done: - if (s != nullptr) { - TRACE_TYPE(LOOKUP, "si %s sym %s s->st_value = %p, " - "found in %s, base = %p, load bias = %p", - si->name, name, reinterpret_cast(s->st_value), - (*lsi)->name, reinterpret_cast((*lsi)->base), - reinterpret_cast((*lsi)->load_bias)); - return s; - } + if (s != nullptr) { + TRACE_TYPE(LOOKUP, "si %s sym %s s->st_value = %p, " + "found in %s, base = %p, load bias = %p", + si->name, name, reinterpret_cast(s->st_value), + (*lsi)->name, reinterpret_cast((*lsi)->base), + reinterpret_cast((*lsi)->load_bias)); + return s; + } - return nullptr; + return nullptr; } // Each size has it's own allocator. @@ -1156,35 +1152,35 @@ int soinfo::Relocate(ElfW(Rela)* rela, unsigned count) { switch (type) { #if defined(__aarch64__) - case R_AARCH64_JUMP_SLOT: - case R_AARCH64_GLOB_DAT: - case R_AARCH64_ABS64: - case R_AARCH64_ABS32: - case R_AARCH64_ABS16: - case R_AARCH64_RELATIVE: - case R_AARCH64_IRELATIVE: - /* - * The sym_addr was initialized to be zero above, or the relocation - * code below does not care about value of sym_addr. - * No need to do anything. - */ - break; + case R_AARCH64_JUMP_SLOT: + case R_AARCH64_GLOB_DAT: + case R_AARCH64_ABS64: + case R_AARCH64_ABS32: + case R_AARCH64_ABS16: + case R_AARCH64_RELATIVE: + case R_AARCH64_IRELATIVE: + /* + * The sym_addr was initialized to be zero above, or the relocation + * code below does not care about value of sym_addr. + * No need to do anything. + */ + break; #elif defined(__x86_64__) - case R_X86_64_JUMP_SLOT: - case R_X86_64_GLOB_DAT: - case R_X86_64_32: - case R_X86_64_64: - case R_X86_64_RELATIVE: - case R_X86_64_IRELATIVE: - // No need to do anything. - break; - case R_X86_64_PC32: - sym_addr = reloc; - break; + case R_X86_64_JUMP_SLOT: + case R_X86_64_GLOB_DAT: + case R_X86_64_32: + case R_X86_64_64: + case R_X86_64_RELATIVE: + case R_X86_64_IRELATIVE: + // No need to do anything. + break; + case R_X86_64_PC32: + sym_addr = reloc; + break; #endif - default: - DL_ERR("unknown weak reloc type %d @ %p (%zu)", type, rela, idx); - return -1; + default: + DL_ERR("unknown weak reloc type %d @ %p (%zu)", type, rela, idx); + return -1; } } else { // We got a definition. @@ -1195,119 +1191,119 @@ int soinfo::Relocate(ElfW(Rela)* rela, unsigned count) { switch (type) { #if defined(__aarch64__) - case R_AARCH64_JUMP_SLOT: + case R_AARCH64_JUMP_SLOT: count_relocation(kRelocAbsolute); MARK(rela->r_offset); TRACE_TYPE(RELO, "RELO JMP_SLOT %16llx <- %16llx %s\n", reloc, (sym_addr + rela->r_addend), sym_name); *reinterpret_cast(reloc) = (sym_addr + rela->r_addend); break; - case R_AARCH64_GLOB_DAT: + case R_AARCH64_GLOB_DAT: count_relocation(kRelocAbsolute); MARK(rela->r_offset); TRACE_TYPE(RELO, "RELO GLOB_DAT %16llx <- %16llx %s\n", reloc, (sym_addr + rela->r_addend), sym_name); *reinterpret_cast(reloc) = (sym_addr + rela->r_addend); break; - case R_AARCH64_ABS64: + case R_AARCH64_ABS64: count_relocation(kRelocAbsolute); MARK(rela->r_offset); TRACE_TYPE(RELO, "RELO ABS64 %16llx <- %16llx %s\n", reloc, (sym_addr + rela->r_addend), sym_name); *reinterpret_cast(reloc) += (sym_addr + rela->r_addend); break; - case R_AARCH64_ABS32: + case R_AARCH64_ABS32: count_relocation(kRelocAbsolute); MARK(rela->r_offset); TRACE_TYPE(RELO, "RELO ABS32 %16llx <- %16llx %s\n", reloc, (sym_addr + rela->r_addend), sym_name); if ((static_cast(INT32_MIN) <= (*reinterpret_cast(reloc) + (sym_addr + rela->r_addend))) && ((*reinterpret_cast(reloc) + (sym_addr + rela->r_addend)) <= static_cast(UINT32_MAX))) { - *reinterpret_cast(reloc) += (sym_addr + rela->r_addend); + *reinterpret_cast(reloc) += (sym_addr + rela->r_addend); } else { - DL_ERR("0x%016llx out of range 0x%016llx to 0x%016llx", - (*reinterpret_cast(reloc) + (sym_addr + rela->r_addend)), - static_cast(INT32_MIN), - static_cast(UINT32_MAX)); - return -1; + DL_ERR("0x%016llx out of range 0x%016llx to 0x%016llx", + (*reinterpret_cast(reloc) + (sym_addr + rela->r_addend)), + static_cast(INT32_MIN), + static_cast(UINT32_MAX)); + return -1; } break; - case R_AARCH64_ABS16: + case R_AARCH64_ABS16: count_relocation(kRelocAbsolute); MARK(rela->r_offset); TRACE_TYPE(RELO, "RELO ABS16 %16llx <- %16llx %s\n", reloc, (sym_addr + rela->r_addend), sym_name); if ((static_cast(INT16_MIN) <= (*reinterpret_cast(reloc) + (sym_addr + rela->r_addend))) && ((*reinterpret_cast(reloc) + (sym_addr + rela->r_addend)) <= static_cast(UINT16_MAX))) { - *reinterpret_cast(reloc) += (sym_addr + rela->r_addend); + *reinterpret_cast(reloc) += (sym_addr + rela->r_addend); } else { - DL_ERR("0x%016llx out of range 0x%016llx to 0x%016llx", - (*reinterpret_cast(reloc) + (sym_addr + rela->r_addend)), - static_cast(INT16_MIN), - static_cast(UINT16_MAX)); - return -1; + DL_ERR("0x%016llx out of range 0x%016llx to 0x%016llx", + (*reinterpret_cast(reloc) + (sym_addr + rela->r_addend)), + static_cast(INT16_MIN), + static_cast(UINT16_MAX)); + return -1; } break; - case R_AARCH64_PREL64: + case R_AARCH64_PREL64: count_relocation(kRelocRelative); MARK(rela->r_offset); TRACE_TYPE(RELO, "RELO REL64 %16llx <- %16llx - %16llx %s\n", reloc, (sym_addr + rela->r_addend), rela->r_offset, sym_name); *reinterpret_cast(reloc) += (sym_addr + rela->r_addend) - rela->r_offset; break; - case R_AARCH64_PREL32: + case R_AARCH64_PREL32: count_relocation(kRelocRelative); MARK(rela->r_offset); TRACE_TYPE(RELO, "RELO REL32 %16llx <- %16llx - %16llx %s\n", reloc, (sym_addr + rela->r_addend), rela->r_offset, sym_name); if ((static_cast(INT32_MIN) <= (*reinterpret_cast(reloc) + ((sym_addr + rela->r_addend) - rela->r_offset))) && ((*reinterpret_cast(reloc) + ((sym_addr + rela->r_addend) - rela->r_offset)) <= static_cast(UINT32_MAX))) { - *reinterpret_cast(reloc) += ((sym_addr + rela->r_addend) - rela->r_offset); + *reinterpret_cast(reloc) += ((sym_addr + rela->r_addend) - rela->r_offset); } else { - DL_ERR("0x%016llx out of range 0x%016llx to 0x%016llx", - (*reinterpret_cast(reloc) + ((sym_addr + rela->r_addend) - rela->r_offset)), - static_cast(INT32_MIN), - static_cast(UINT32_MAX)); - return -1; + DL_ERR("0x%016llx out of range 0x%016llx to 0x%016llx", + (*reinterpret_cast(reloc) + ((sym_addr + rela->r_addend) - rela->r_offset)), + static_cast(INT32_MIN), + static_cast(UINT32_MAX)); + return -1; } break; - case R_AARCH64_PREL16: + case R_AARCH64_PREL16: count_relocation(kRelocRelative); MARK(rela->r_offset); TRACE_TYPE(RELO, "RELO REL16 %16llx <- %16llx - %16llx %s\n", reloc, (sym_addr + rela->r_addend), rela->r_offset, sym_name); if ((static_cast(INT16_MIN) <= (*reinterpret_cast(reloc) + ((sym_addr + rela->r_addend) - rela->r_offset))) && ((*reinterpret_cast(reloc) + ((sym_addr + rela->r_addend) - rela->r_offset)) <= static_cast(UINT16_MAX))) { - *reinterpret_cast(reloc) += ((sym_addr + rela->r_addend) - rela->r_offset); + *reinterpret_cast(reloc) += ((sym_addr + rela->r_addend) - rela->r_offset); } else { - DL_ERR("0x%016llx out of range 0x%016llx to 0x%016llx", - (*reinterpret_cast(reloc) + ((sym_addr + rela->r_addend) - rela->r_offset)), - static_cast(INT16_MIN), - static_cast(UINT16_MAX)); - return -1; + DL_ERR("0x%016llx out of range 0x%016llx to 0x%016llx", + (*reinterpret_cast(reloc) + ((sym_addr + rela->r_addend) - rela->r_offset)), + static_cast(INT16_MIN), + static_cast(UINT16_MAX)); + return -1; } break; - case R_AARCH64_RELATIVE: + case R_AARCH64_RELATIVE: count_relocation(kRelocRelative); MARK(rela->r_offset); if (sym) { - DL_ERR("odd RELATIVE form..."); - return -1; + DL_ERR("odd RELATIVE form..."); + return -1; } TRACE_TYPE(RELO, "RELO RELATIVE %16llx <- %16llx\n", reloc, (base + rela->r_addend)); *reinterpret_cast(reloc) = (base + rela->r_addend); break; - case R_AARCH64_IRELATIVE: - count_relocation(kRelocRelative); - MARK(rela->r_offset); - TRACE_TYPE(RELO, "RELO IRELATIVE %16llx <- %16llx\n", reloc, (base + rela->r_addend)); - *reinterpret_cast(reloc) = call_ifunc_resolver(base + rela->r_addend); - break; + case R_AARCH64_IRELATIVE: + count_relocation(kRelocRelative); + MARK(rela->r_offset); + TRACE_TYPE(RELO, "RELO IRELATIVE %16llx <- %16llx\n", reloc, (base + rela->r_addend)); + *reinterpret_cast(reloc) = call_ifunc_resolver(base + rela->r_addend); + break; - case R_AARCH64_COPY: + case R_AARCH64_COPY: /* * ET_EXEC is not supported so this should not happen. * @@ -1319,73 +1315,73 @@ int soinfo::Relocate(ElfW(Rela)* rela, unsigned count) { */ DL_ERR("%s R_AARCH64_COPY relocations are not supported", name); return -1; - case R_AARCH64_TLS_TPREL64: + case R_AARCH64_TLS_TPREL64: TRACE_TYPE(RELO, "RELO TLS_TPREL64 *** %16llx <- %16llx - %16llx\n", reloc, (sym_addr + rela->r_addend), rela->r_offset); break; - case R_AARCH64_TLS_DTPREL32: + case R_AARCH64_TLS_DTPREL32: TRACE_TYPE(RELO, "RELO TLS_DTPREL32 *** %16llx <- %16llx - %16llx\n", reloc, (sym_addr + rela->r_addend), rela->r_offset); break; #elif defined(__x86_64__) - case R_X86_64_JUMP_SLOT: - count_relocation(kRelocAbsolute); - MARK(rela->r_offset); - TRACE_TYPE(RELO, "RELO JMP_SLOT %08zx <- %08zx %s", static_cast(reloc), - static_cast(sym_addr + rela->r_addend), sym_name); - *reinterpret_cast(reloc) = sym_addr + rela->r_addend; - break; - case R_X86_64_GLOB_DAT: - count_relocation(kRelocAbsolute); - MARK(rela->r_offset); - TRACE_TYPE(RELO, "RELO GLOB_DAT %08zx <- %08zx %s", static_cast(reloc), - static_cast(sym_addr + rela->r_addend), sym_name); - *reinterpret_cast(reloc) = sym_addr + rela->r_addend; - break; - case R_X86_64_RELATIVE: - count_relocation(kRelocRelative); - MARK(rela->r_offset); - if (sym) { - DL_ERR("odd RELATIVE form..."); - return -1; - } - TRACE_TYPE(RELO, "RELO RELATIVE %08zx <- +%08zx", static_cast(reloc), - static_cast(base)); - *reinterpret_cast(reloc) = base + rela->r_addend; - break; - case R_X86_64_IRELATIVE: - count_relocation(kRelocRelative); - MARK(rela->r_offset); - TRACE_TYPE(RELO, "RELO IRELATIVE %16llx <- %16llx\n", reloc, (base + rela->r_addend)); - *reinterpret_cast(reloc) = call_ifunc_resolver(base + rela->r_addend); - break; - case R_X86_64_32: - count_relocation(kRelocRelative); - MARK(rela->r_offset); - TRACE_TYPE(RELO, "RELO R_X86_64_32 %08zx <- +%08zx %s", static_cast(reloc), - static_cast(sym_addr), sym_name); - *reinterpret_cast(reloc) = sym_addr + rela->r_addend; - break; - case R_X86_64_64: - count_relocation(kRelocRelative); - MARK(rela->r_offset); - TRACE_TYPE(RELO, "RELO R_X86_64_64 %08zx <- +%08zx %s", static_cast(reloc), - static_cast(sym_addr), sym_name); - *reinterpret_cast(reloc) = sym_addr + rela->r_addend; - break; - case R_X86_64_PC32: - count_relocation(kRelocRelative); - MARK(rela->r_offset); - TRACE_TYPE(RELO, "RELO R_X86_64_PC32 %08zx <- +%08zx (%08zx - %08zx) %s", - static_cast(reloc), static_cast(sym_addr - reloc), - static_cast(sym_addr), static_cast(reloc), sym_name); - *reinterpret_cast(reloc) = sym_addr + rela->r_addend - reloc; - break; + case R_X86_64_JUMP_SLOT: + count_relocation(kRelocAbsolute); + MARK(rela->r_offset); + TRACE_TYPE(RELO, "RELO JMP_SLOT %08zx <- %08zx %s", static_cast(reloc), + static_cast(sym_addr + rela->r_addend), sym_name); + *reinterpret_cast(reloc) = sym_addr + rela->r_addend; + break; + case R_X86_64_GLOB_DAT: + count_relocation(kRelocAbsolute); + MARK(rela->r_offset); + TRACE_TYPE(RELO, "RELO GLOB_DAT %08zx <- %08zx %s", static_cast(reloc), + static_cast(sym_addr + rela->r_addend), sym_name); + *reinterpret_cast(reloc) = sym_addr + rela->r_addend; + break; + case R_X86_64_RELATIVE: + count_relocation(kRelocRelative); + MARK(rela->r_offset); + if (sym) { + DL_ERR("odd RELATIVE form..."); + return -1; + } + TRACE_TYPE(RELO, "RELO RELATIVE %08zx <- +%08zx", static_cast(reloc), + static_cast(base)); + *reinterpret_cast(reloc) = base + rela->r_addend; + break; + case R_X86_64_IRELATIVE: + count_relocation(kRelocRelative); + MARK(rela->r_offset); + TRACE_TYPE(RELO, "RELO IRELATIVE %16llx <- %16llx\n", reloc, (base + rela->r_addend)); + *reinterpret_cast(reloc) = call_ifunc_resolver(base + rela->r_addend); + break; + case R_X86_64_32: + count_relocation(kRelocRelative); + MARK(rela->r_offset); + TRACE_TYPE(RELO, "RELO R_X86_64_32 %08zx <- +%08zx %s", static_cast(reloc), + static_cast(sym_addr), sym_name); + *reinterpret_cast(reloc) = sym_addr + rela->r_addend; + break; + case R_X86_64_64: + count_relocation(kRelocRelative); + MARK(rela->r_offset); + TRACE_TYPE(RELO, "RELO R_X86_64_64 %08zx <- +%08zx %s", static_cast(reloc), + static_cast(sym_addr), sym_name); + *reinterpret_cast(reloc) = sym_addr + rela->r_addend; + break; + case R_X86_64_PC32: + count_relocation(kRelocRelative); + MARK(rela->r_offset); + TRACE_TYPE(RELO, "RELO R_X86_64_PC32 %08zx <- +%08zx (%08zx - %08zx) %s", + static_cast(reloc), static_cast(sym_addr - reloc), + static_cast(sym_addr), static_cast(reloc), sym_name); + *reinterpret_cast(reloc) = sym_addr + rela->r_addend - reloc; + break; #endif - default: - DL_ERR("unknown reloc type %d @ %p (%zu)", type, rela, idx); - return -1; + default: + DL_ERR("unknown reloc type %d @ %p (%zu)", type, rela, idx); + return -1; } } return 0; @@ -1393,260 +1389,260 @@ int soinfo::Relocate(ElfW(Rela)* rela, unsigned count) { #else // REL, not RELA. int soinfo::Relocate(ElfW(Rel)* rel, unsigned count) { - for (size_t idx = 0; idx < count; ++idx, ++rel) { - unsigned type = ELFW(R_TYPE)(rel->r_info); - // TODO: don't use unsigned for 'sym'. Use uint32_t or ElfW(Addr) instead. - unsigned sym = ELFW(R_SYM)(rel->r_info); - ElfW(Addr) reloc = static_cast(rel->r_offset + load_bias); - ElfW(Addr) sym_addr = 0; - const char* sym_name = nullptr; + for (size_t idx = 0; idx < count; ++idx, ++rel) { + unsigned type = ELFW(R_TYPE)(rel->r_info); + // TODO: don't use unsigned for 'sym'. Use uint32_t or ElfW(Addr) instead. + unsigned sym = ELFW(R_SYM)(rel->r_info); + ElfW(Addr) reloc = static_cast(rel->r_offset + load_bias); + ElfW(Addr) sym_addr = 0; + const char* sym_name = nullptr; - DEBUG("Processing '%s' relocation at index %zd", name, idx); - if (type == 0) { // R_*_NONE - continue; + DEBUG("Processing '%s' relocation at index %zd", name, idx); + if (type == 0) { // R_*_NONE + continue; + } + + ElfW(Sym)* s = nullptr; + soinfo* lsi = nullptr; + + if (sym != 0) { + sym_name = reinterpret_cast(strtab + symtab[sym].st_name); + s = soinfo_do_lookup(this, sym_name, &lsi); + if (s == nullptr) { + // We only allow an undefined symbol if this is a weak reference... + s = &symtab[sym]; + if (ELF_ST_BIND(s->st_info) != STB_WEAK) { + DL_ERR("cannot locate symbol \"%s\" referenced by \"%s\"...", sym_name, name); + return -1; } - ElfW(Sym)* s = nullptr; - soinfo* lsi = nullptr; + /* IHI0044C AAELF 4.5.1.1: - if (sym != 0) { - sym_name = reinterpret_cast(strtab + symtab[sym].st_name); - s = soinfo_do_lookup(this, sym_name, &lsi); - if (s == nullptr) { - // We only allow an undefined symbol if this is a weak reference... - s = &symtab[sym]; - if (ELF_ST_BIND(s->st_info) != STB_WEAK) { - DL_ERR("cannot locate symbol \"%s\" referenced by \"%s\"...", sym_name, name); - return -1; - } + Libraries are not searched to resolve weak references. + It is not an error for a weak reference to remain + unsatisfied. - /* IHI0044C AAELF 4.5.1.1: - - Libraries are not searched to resolve weak references. - It is not an error for a weak reference to remain - unsatisfied. - - During linking, the value of an undefined weak reference is: - - Zero if the relocation type is absolute - - The address of the place if the relocation is pc-relative - - The address of nominal base address if the relocation - type is base-relative. - */ - - switch (type) { -#if defined(__arm__) - case R_ARM_JUMP_SLOT: - case R_ARM_GLOB_DAT: - case R_ARM_ABS32: - case R_ARM_RELATIVE: /* Don't care. */ - // sym_addr was initialized to be zero above or relocation - // code below does not care about value of sym_addr. - // No need to do anything. - break; -#elif defined(__i386__) - case R_386_JMP_SLOT: - case R_386_GLOB_DAT: - case R_386_32: - case R_386_RELATIVE: /* Don't care. */ - case R_386_IRELATIVE: - // sym_addr was initialized to be zero above or relocation - // code below does not care about value of sym_addr. - // No need to do anything. - break; - case R_386_PC32: - sym_addr = reloc; - break; -#endif - -#if defined(__arm__) - case R_ARM_COPY: - // Fall through. Can't really copy if weak symbol is not found at run-time. -#endif - default: - DL_ERR("unknown weak reloc type %d @ %p (%zu)", type, rel, idx); - return -1; - } - } else { - // We got a definition. - sym_addr = lsi->resolve_symbol_address(s); - } - count_relocation(kRelocSymbol); - } + During linking, the value of an undefined weak reference is: + - Zero if the relocation type is absolute + - The address of the place if the relocation is pc-relative + - The address of nominal base address if the relocation + type is base-relative. + */ switch (type) { #if defined(__arm__) - case R_ARM_JUMP_SLOT: - count_relocation(kRelocAbsolute); - MARK(rel->r_offset); - TRACE_TYPE(RELO, "RELO JMP_SLOT %08x <- %08x %s", reloc, sym_addr, sym_name); - *reinterpret_cast(reloc) = sym_addr; + case R_ARM_JUMP_SLOT: + case R_ARM_GLOB_DAT: + case R_ARM_ABS32: + case R_ARM_RELATIVE: /* Don't care. */ + // sym_addr was initialized to be zero above or relocation + // code below does not care about value of sym_addr. + // No need to do anything. break; - case R_ARM_GLOB_DAT: - count_relocation(kRelocAbsolute); - MARK(rel->r_offset); - TRACE_TYPE(RELO, "RELO GLOB_DAT %08x <- %08x %s", reloc, sym_addr, sym_name); - *reinterpret_cast(reloc) = sym_addr; - break; - case R_ARM_ABS32: - count_relocation(kRelocAbsolute); - MARK(rel->r_offset); - TRACE_TYPE(RELO, "RELO ABS %08x <- %08x %s", reloc, sym_addr, sym_name); - *reinterpret_cast(reloc) += sym_addr; - break; - case R_ARM_REL32: - count_relocation(kRelocRelative); - MARK(rel->r_offset); - TRACE_TYPE(RELO, "RELO REL32 %08x <- %08x - %08x %s", - reloc, sym_addr, rel->r_offset, sym_name); - *reinterpret_cast(reloc) += sym_addr - rel->r_offset; - break; - case R_ARM_COPY: - /* - * ET_EXEC is not supported so this should not happen. - * - * http://infocenter.arm.com/help/topic/com.arm.doc.ihi0044d/IHI0044D_aaelf.pdf - * - * Section 4.7.1.10 "Dynamic relocations" - * R_ARM_COPY may only appear in executable objects where e_type is - * set to ET_EXEC. - */ - DL_ERR("%s R_ARM_COPY relocations are not supported", name); - return -1; #elif defined(__i386__) - case R_386_JMP_SLOT: - count_relocation(kRelocAbsolute); - MARK(rel->r_offset); - TRACE_TYPE(RELO, "RELO JMP_SLOT %08x <- %08x %s", reloc, sym_addr, sym_name); - *reinterpret_cast(reloc) = sym_addr; + case R_386_JMP_SLOT: + case R_386_GLOB_DAT: + case R_386_32: + case R_386_RELATIVE: /* Don't care. */ + case R_386_IRELATIVE: + // sym_addr was initialized to be zero above or relocation + // code below does not care about value of sym_addr. + // No need to do anything. break; - case R_386_GLOB_DAT: - count_relocation(kRelocAbsolute); - MARK(rel->r_offset); - TRACE_TYPE(RELO, "RELO GLOB_DAT %08x <- %08x %s", reloc, sym_addr, sym_name); - *reinterpret_cast(reloc) = sym_addr; - break; - case R_386_32: - count_relocation(kRelocRelative); - MARK(rel->r_offset); - TRACE_TYPE(RELO, "RELO R_386_32 %08x <- +%08x %s", reloc, sym_addr, sym_name); - *reinterpret_cast(reloc) += sym_addr; - break; - case R_386_PC32: - count_relocation(kRelocRelative); - MARK(rel->r_offset); - TRACE_TYPE(RELO, "RELO R_386_PC32 %08x <- +%08x (%08x - %08x) %s", - reloc, (sym_addr - reloc), sym_addr, reloc, sym_name); - *reinterpret_cast(reloc) += (sym_addr - reloc); - break; -#elif defined(__mips__) - case R_MIPS_REL32: -#if defined(__LP64__) - // MIPS Elf64_Rel entries contain compound relocations - // We only handle the R_MIPS_NONE|R_MIPS_64|R_MIPS_REL32 case - if (ELF64_R_TYPE2(rel->r_info) != R_MIPS_64 || - ELF64_R_TYPE3(rel->r_info) != R_MIPS_NONE) { - DL_ERR("Unexpected compound relocation type:%d type2:%d type3:%d @ %p (%zu)", - type, (unsigned)ELF64_R_TYPE2(rel->r_info), - (unsigned)ELF64_R_TYPE3(rel->r_info), rel, idx); - return -1; - } -#endif - count_relocation(kRelocAbsolute); - MARK(rel->r_offset); - TRACE_TYPE(RELO, "RELO REL32 %08zx <- %08zx %s", static_cast(reloc), - static_cast(sym_addr), sym_name ? sym_name : "*SECTIONHDR*"); - if (s) { - *reinterpret_cast(reloc) += sym_addr; - } else { - *reinterpret_cast(reloc) += base; - } + case R_386_PC32: + sym_addr = reloc; break; #endif #if defined(__arm__) - case R_ARM_RELATIVE: -#elif defined(__i386__) - case R_386_RELATIVE: + case R_ARM_COPY: + // Fall through. Can't really copy if weak symbol is not found at run-time. #endif - count_relocation(kRelocRelative); - MARK(rel->r_offset); - if (sym) { - DL_ERR("odd RELATIVE form..."); - return -1; - } - TRACE_TYPE(RELO, "RELO RELATIVE %p <- +%p", - reinterpret_cast(reloc), reinterpret_cast(base)); - *reinterpret_cast(reloc) += base; - break; -#if defined(__i386__) - case R_386_IRELATIVE: - count_relocation(kRelocRelative); - MARK(rel->r_offset); - TRACE_TYPE(RELO, "RELO IRELATIVE %p <- %p", reinterpret_cast(reloc), reinterpret_cast(base)); - *reinterpret_cast(reloc) = call_ifunc_resolver(base + *reinterpret_cast(reloc)); - break; -#endif - - default: - DL_ERR("unknown reloc type %d @ %p (%zu)", type, rel, idx); + default: + DL_ERR("unknown weak reloc type %d @ %p (%zu)", type, rel, idx); return -1; } + } else { + // We got a definition. + sym_addr = lsi->resolve_symbol_address(s); + } + count_relocation(kRelocSymbol); } - return 0; + + switch (type) { +#if defined(__arm__) + case R_ARM_JUMP_SLOT: + count_relocation(kRelocAbsolute); + MARK(rel->r_offset); + TRACE_TYPE(RELO, "RELO JMP_SLOT %08x <- %08x %s", reloc, sym_addr, sym_name); + *reinterpret_cast(reloc) = sym_addr; + break; + case R_ARM_GLOB_DAT: + count_relocation(kRelocAbsolute); + MARK(rel->r_offset); + TRACE_TYPE(RELO, "RELO GLOB_DAT %08x <- %08x %s", reloc, sym_addr, sym_name); + *reinterpret_cast(reloc) = sym_addr; + break; + case R_ARM_ABS32: + count_relocation(kRelocAbsolute); + MARK(rel->r_offset); + TRACE_TYPE(RELO, "RELO ABS %08x <- %08x %s", reloc, sym_addr, sym_name); + *reinterpret_cast(reloc) += sym_addr; + break; + case R_ARM_REL32: + count_relocation(kRelocRelative); + MARK(rel->r_offset); + TRACE_TYPE(RELO, "RELO REL32 %08x <- %08x - %08x %s", + reloc, sym_addr, rel->r_offset, sym_name); + *reinterpret_cast(reloc) += sym_addr - rel->r_offset; + break; + case R_ARM_COPY: + /* + * ET_EXEC is not supported so this should not happen. + * + * http://infocenter.arm.com/help/topic/com.arm.doc.ihi0044d/IHI0044D_aaelf.pdf + * + * Section 4.7.1.10 "Dynamic relocations" + * R_ARM_COPY may only appear in executable objects where e_type is + * set to ET_EXEC. + */ + DL_ERR("%s R_ARM_COPY relocations are not supported", name); + return -1; +#elif defined(__i386__) + case R_386_JMP_SLOT: + count_relocation(kRelocAbsolute); + MARK(rel->r_offset); + TRACE_TYPE(RELO, "RELO JMP_SLOT %08x <- %08x %s", reloc, sym_addr, sym_name); + *reinterpret_cast(reloc) = sym_addr; + break; + case R_386_GLOB_DAT: + count_relocation(kRelocAbsolute); + MARK(rel->r_offset); + TRACE_TYPE(RELO, "RELO GLOB_DAT %08x <- %08x %s", reloc, sym_addr, sym_name); + *reinterpret_cast(reloc) = sym_addr; + break; + case R_386_32: + count_relocation(kRelocRelative); + MARK(rel->r_offset); + TRACE_TYPE(RELO, "RELO R_386_32 %08x <- +%08x %s", reloc, sym_addr, sym_name); + *reinterpret_cast(reloc) += sym_addr; + break; + case R_386_PC32: + count_relocation(kRelocRelative); + MARK(rel->r_offset); + TRACE_TYPE(RELO, "RELO R_386_PC32 %08x <- +%08x (%08x - %08x) %s", + reloc, (sym_addr - reloc), sym_addr, reloc, sym_name); + *reinterpret_cast(reloc) += (sym_addr - reloc); + break; +#elif defined(__mips__) + case R_MIPS_REL32: +#if defined(__LP64__) + // MIPS Elf64_Rel entries contain compound relocations + // We only handle the R_MIPS_NONE|R_MIPS_64|R_MIPS_REL32 case + if (ELF64_R_TYPE2(rel->r_info) != R_MIPS_64 || + ELF64_R_TYPE3(rel->r_info) != R_MIPS_NONE) { + DL_ERR("Unexpected compound relocation type:%d type2:%d type3:%d @ %p (%zu)", + type, (unsigned)ELF64_R_TYPE2(rel->r_info), + (unsigned)ELF64_R_TYPE3(rel->r_info), rel, idx); + return -1; + } +#endif + count_relocation(kRelocAbsolute); + MARK(rel->r_offset); + TRACE_TYPE(RELO, "RELO REL32 %08zx <- %08zx %s", static_cast(reloc), + static_cast(sym_addr), sym_name ? sym_name : "*SECTIONHDR*"); + if (s) { + *reinterpret_cast(reloc) += sym_addr; + } else { + *reinterpret_cast(reloc) += base; + } + break; +#endif + +#if defined(__arm__) + case R_ARM_RELATIVE: +#elif defined(__i386__) + case R_386_RELATIVE: +#endif + count_relocation(kRelocRelative); + MARK(rel->r_offset); + if (sym) { + DL_ERR("odd RELATIVE form..."); + return -1; + } + TRACE_TYPE(RELO, "RELO RELATIVE %p <- +%p", + reinterpret_cast(reloc), reinterpret_cast(base)); + *reinterpret_cast(reloc) += base; + break; +#if defined(__i386__) + case R_386_IRELATIVE: + count_relocation(kRelocRelative); + MARK(rel->r_offset); + TRACE_TYPE(RELO, "RELO IRELATIVE %p <- %p", reinterpret_cast(reloc), reinterpret_cast(base)); + *reinterpret_cast(reloc) = call_ifunc_resolver(base + *reinterpret_cast(reloc)); + break; +#endif + + default: + DL_ERR("unknown reloc type %d @ %p (%zu)", type, rel, idx); + return -1; + } + } + return 0; } #endif #if defined(__mips__) static bool mips_relocate_got(soinfo* si) { - ElfW(Addr)** got = si->plt_got; - if (got == nullptr) { - return true; - } - unsigned local_gotno = si->mips_local_gotno; - unsigned gotsym = si->mips_gotsym; - unsigned symtabno = si->mips_symtabno; - ElfW(Sym)* symtab = si->symtab; - - // got[0] is the address of the lazy resolver function. - // got[1] may be used for a GNU extension. - // Set it to a recognizable address in case someone calls it (should be _rtld_bind_start). - // FIXME: maybe this should be in a separate routine? - if ((si->flags & FLAG_LINKER) == 0) { - size_t g = 0; - got[g++] = reinterpret_cast(0xdeadbeef); - if (reinterpret_cast(got[g]) < 0) { - got[g++] = reinterpret_cast(0xdeadfeed); - } - // Relocate the local GOT entries. - for (; g < local_gotno; g++) { - got[g] = reinterpret_cast(reinterpret_cast(got[g]) + si->load_bias); - } - } - - // Now for the global GOT entries... - ElfW(Sym)* sym = symtab + gotsym; - got = si->plt_got + local_gotno; - for (size_t g = gotsym; g < symtabno; g++, sym++, got++) { - // This is an undefined reference... try to locate it. - const char* sym_name = si->strtab + sym->st_name; - soinfo* lsi = nullptr; - ElfW(Sym)* s = soinfo_do_lookup(si, sym_name, &lsi); - if (s == nullptr) { - // We only allow an undefined symbol if this is a weak reference. - s = &symtab[g]; - if (ELF_ST_BIND(s->st_info) != STB_WEAK) { - DL_ERR("cannot locate \"%s\"...", sym_name); - return false; - } - *got = 0; - } else { - // FIXME: is this sufficient? - // For reference see NetBSD link loader - // http://cvsweb.netbsd.org/bsdweb.cgi/src/libexec/ld.elf_so/arch/mips/mips_reloc.c?rev=1.53&content-type=text/x-cvsweb-markup - *got = reinterpret_cast(lsi->resolve_symbol_address(s)); - } - } + ElfW(Addr)** got = si->plt_got; + if (got == nullptr) { return true; + } + unsigned local_gotno = si->mips_local_gotno; + unsigned gotsym = si->mips_gotsym; + unsigned symtabno = si->mips_symtabno; + ElfW(Sym)* symtab = si->symtab; + + // got[0] is the address of the lazy resolver function. + // got[1] may be used for a GNU extension. + // Set it to a recognizable address in case someone calls it (should be _rtld_bind_start). + // FIXME: maybe this should be in a separate routine? + if ((si->flags & FLAG_LINKER) == 0) { + size_t g = 0; + got[g++] = reinterpret_cast(0xdeadbeef); + if (reinterpret_cast(got[g]) < 0) { + got[g++] = reinterpret_cast(0xdeadfeed); + } + // Relocate the local GOT entries. + for (; g < local_gotno; g++) { + got[g] = reinterpret_cast(reinterpret_cast(got[g]) + si->load_bias); + } + } + + // Now for the global GOT entries... + ElfW(Sym)* sym = symtab + gotsym; + got = si->plt_got + local_gotno; + for (size_t g = gotsym; g < symtabno; g++, sym++, got++) { + // This is an undefined reference... try to locate it. + const char* sym_name = si->strtab + sym->st_name; + soinfo* lsi = nullptr; + ElfW(Sym)* s = soinfo_do_lookup(si, sym_name, &lsi); + if (s == nullptr) { + // We only allow an undefined symbol if this is a weak reference. + s = &symtab[g]; + if (ELF_ST_BIND(s->st_info) != STB_WEAK) { + DL_ERR("cannot locate \"%s\"...", sym_name); + return false; + } + *got = 0; + } else { + // FIXME: is this sufficient? + // For reference see NetBSD link loader + // http://cvsweb.netbsd.org/bsdweb.cgi/src/libexec/ld.elf_so/arch/mips/mips_reloc.c?rev=1.53&content-type=text/x-cvsweb-markup + *got = reinterpret_cast(lsi->resolve_symbol_address(s)); + } + } + return true; } #endif @@ -1825,62 +1821,62 @@ ElfW(Addr) soinfo::resolve_symbol_address(ElfW(Sym)* s) { /* Force any of the closed stdin, stdout and stderr to be associated with /dev/null. */ static int nullify_closed_stdio() { - int dev_null, i, status; - int return_value = 0; + int dev_null, i, status; + int return_value = 0; - dev_null = TEMP_FAILURE_RETRY(open("/dev/null", O_RDWR)); - if (dev_null < 0) { - DL_ERR("cannot open /dev/null: %s", strerror(errno)); - return -1; - } - TRACE("[ Opened /dev/null file-descriptor=%d]", dev_null); + dev_null = TEMP_FAILURE_RETRY(open("/dev/null", O_RDWR)); + if (dev_null < 0) { + DL_ERR("cannot open /dev/null: %s", strerror(errno)); + return -1; + } + TRACE("[ Opened /dev/null file-descriptor=%d]", dev_null); - /* If any of the stdio file descriptors is valid and not associated - with /dev/null, dup /dev/null to it. */ - for (i = 0; i < 3; i++) { - /* If it is /dev/null already, we are done. */ - if (i == dev_null) { - continue; - } - - TRACE("[ Nullifying stdio file descriptor %d]", i); - status = TEMP_FAILURE_RETRY(fcntl(i, F_GETFL)); - - /* If file is opened, we are good. */ - if (status != -1) { - continue; - } - - /* The only error we allow is that the file descriptor does not - exist, in which case we dup /dev/null to it. */ - if (errno != EBADF) { - DL_ERR("fcntl failed: %s", strerror(errno)); - return_value = -1; - continue; - } - - /* Try dupping /dev/null to this stdio file descriptor and - repeat if there is a signal. Note that any errors in closing - the stdio descriptor are lost. */ - status = TEMP_FAILURE_RETRY(dup2(dev_null, i)); - if (status < 0) { - DL_ERR("dup2 failed: %s", strerror(errno)); - return_value = -1; - continue; - } + /* If any of the stdio file descriptors is valid and not associated + with /dev/null, dup /dev/null to it. */ + for (i = 0; i < 3; i++) { + /* If it is /dev/null already, we are done. */ + if (i == dev_null) { + continue; } - /* If /dev/null is not one of the stdio file descriptors, close it. */ - if (dev_null > 2) { - TRACE("[ Closing /dev/null file-descriptor=%d]", dev_null); - status = TEMP_FAILURE_RETRY(close(dev_null)); - if (status == -1) { - DL_ERR("close failed: %s", strerror(errno)); - return_value = -1; - } + TRACE("[ Nullifying stdio file descriptor %d]", i); + status = TEMP_FAILURE_RETRY(fcntl(i, F_GETFL)); + + /* If file is opened, we are good. */ + if (status != -1) { + continue; } - return return_value; + /* The only error we allow is that the file descriptor does not + exist, in which case we dup /dev/null to it. */ + if (errno != EBADF) { + DL_ERR("fcntl failed: %s", strerror(errno)); + return_value = -1; + continue; + } + + /* Try dupping /dev/null to this stdio file descriptor and + repeat if there is a signal. Note that any errors in closing + the stdio descriptor are lost. */ + status = TEMP_FAILURE_RETRY(dup2(dev_null, i)); + if (status < 0) { + DL_ERR("dup2 failed: %s", strerror(errno)); + return_value = -1; + continue; + } + } + + /* If /dev/null is not one of the stdio file descriptors, close it. */ + if (dev_null > 2) { + TRACE("[ Closing /dev/null file-descriptor=%d]", dev_null); + status = TEMP_FAILURE_RETRY(close(dev_null)); + if (status == -1) { + DL_ERR("close failed: %s", strerror(errno)); + return_value = -1; + } + } + + return return_value; } bool soinfo::PrelinkImage() { @@ -1888,318 +1884,318 @@ bool soinfo::PrelinkImage() { ElfW(Word) dynamic_flags = 0; phdr_table_get_dynamic_section(phdr, phnum, load_bias, &dynamic, &dynamic_flags); - /* We can't log anything until the linker is relocated */ - bool relocating_linker = (flags & FLAG_LINKER) != 0; - if (!relocating_linker) { - INFO("[ linking %s ]", name); - DEBUG("si->base = %p si->flags = 0x%08x", reinterpret_cast(base), flags); - } + /* We can't log anything until the linker is relocated */ + bool relocating_linker = (flags & FLAG_LINKER) != 0; + if (!relocating_linker) { + INFO("[ linking %s ]", name); + DEBUG("si->base = %p si->flags = 0x%08x", reinterpret_cast(base), flags); + } - if (dynamic == nullptr) { - if (!relocating_linker) { - DL_ERR("missing PT_DYNAMIC in \"%s\"", name); - } - return false; - } else { - if (!relocating_linker) { - DEBUG("dynamic = %p", dynamic); - } + if (dynamic == nullptr) { + if (!relocating_linker) { + DL_ERR("missing PT_DYNAMIC in \"%s\"", name); } + return false; + } else { + if (!relocating_linker) { + DEBUG("dynamic = %p", dynamic); + } + } #if defined(__arm__) - (void) phdr_table_get_arm_exidx(phdr, phnum, load_bias, - &ARM_exidx, &ARM_exidx_count); + (void) phdr_table_get_arm_exidx(phdr, phnum, load_bias, + &ARM_exidx, &ARM_exidx_count); #endif - // Extract useful information from dynamic section. - uint32_t needed_count = 0; - for (ElfW(Dyn)* d = dynamic; d->d_tag != DT_NULL; ++d) { - DEBUG("d = %p, d[0](tag) = %p d[1](val) = %p", - d, reinterpret_cast(d->d_tag), reinterpret_cast(d->d_un.d_val)); - switch (d->d_tag) { - case DT_HASH: - nbucket = reinterpret_cast(load_bias + d->d_un.d_ptr)[0]; - nchain = reinterpret_cast(load_bias + d->d_un.d_ptr)[1]; - bucket = reinterpret_cast(load_bias + d->d_un.d_ptr + 8); - chain = reinterpret_cast(load_bias + d->d_un.d_ptr + 8 + nbucket * 4); - break; - case DT_STRTAB: - strtab = reinterpret_cast(load_bias + d->d_un.d_ptr); - break; - case DT_SYMTAB: - symtab = reinterpret_cast(load_bias + d->d_un.d_ptr); - break; + // Extract useful information from dynamic section. + uint32_t needed_count = 0; + for (ElfW(Dyn)* d = dynamic; d->d_tag != DT_NULL; ++d) { + DEBUG("d = %p, d[0](tag) = %p d[1](val) = %p", + d, reinterpret_cast(d->d_tag), reinterpret_cast(d->d_un.d_val)); + switch (d->d_tag) { + case DT_HASH: + nbucket = reinterpret_cast(load_bias + d->d_un.d_ptr)[0]; + nchain = reinterpret_cast(load_bias + d->d_un.d_ptr)[1]; + bucket = reinterpret_cast(load_bias + d->d_un.d_ptr + 8); + chain = reinterpret_cast(load_bias + d->d_un.d_ptr + 8 + nbucket * 4); + break; + case DT_STRTAB: + strtab = reinterpret_cast(load_bias + d->d_un.d_ptr); + break; + case DT_SYMTAB: + symtab = reinterpret_cast(load_bias + d->d_un.d_ptr); + break; #if !defined(__LP64__) - case DT_PLTREL: - if (d->d_un.d_val != DT_REL) { - DL_ERR("unsupported DT_RELA in \"%s\"", name); - return false; - } - break; + case DT_PLTREL: + if (d->d_un.d_val != DT_REL) { + DL_ERR("unsupported DT_RELA in \"%s\"", name); + return false; + } + break; #endif - case DT_JMPREL: + case DT_JMPREL: #if defined(USE_RELA) - plt_rela = reinterpret_cast(load_bias + d->d_un.d_ptr); + plt_rela = reinterpret_cast(load_bias + d->d_un.d_ptr); #else - plt_rel = reinterpret_cast(load_bias + d->d_un.d_ptr); + plt_rel = reinterpret_cast(load_bias + d->d_un.d_ptr); #endif - break; - case DT_PLTRELSZ: + break; + case DT_PLTRELSZ: #if defined(USE_RELA) - plt_rela_count = d->d_un.d_val / sizeof(ElfW(Rela)); + plt_rela_count = d->d_un.d_val / sizeof(ElfW(Rela)); #else - plt_rel_count = d->d_un.d_val / sizeof(ElfW(Rel)); + plt_rel_count = d->d_un.d_val / sizeof(ElfW(Rel)); #endif - break; + break; #if defined(__mips__) - case DT_PLTGOT: - // Used by mips and mips64. - plt_got = reinterpret_cast(load_bias + d->d_un.d_ptr); - break; + case DT_PLTGOT: + // Used by mips and mips64. + plt_got = reinterpret_cast(load_bias + d->d_un.d_ptr); + break; #endif - case DT_DEBUG: - // Set the DT_DEBUG entry to the address of _r_debug for GDB - // if the dynamic table is writable + case DT_DEBUG: + // Set the DT_DEBUG entry to the address of _r_debug for GDB + // if the dynamic table is writable // FIXME: not working currently for N64 // The flags for the LOAD and DYNAMIC program headers do not agree. // The LOAD section containing the dynamic table has been mapped as // read-only, but the DYNAMIC header claims it is writable. #if !(defined(__mips__) && defined(__LP64__)) - if ((dynamic_flags & PF_W) != 0) { - d->d_un.d_val = reinterpret_cast(&_r_debug); - } - break; + if ((dynamic_flags & PF_W) != 0) { + d->d_un.d_val = reinterpret_cast(&_r_debug); + } + break; #endif #if defined(USE_RELA) - case DT_RELA: - rela = reinterpret_cast(load_bias + d->d_un.d_ptr); - break; - case DT_RELASZ: - rela_count = d->d_un.d_val / sizeof(ElfW(Rela)); - break; - case DT_REL: - DL_ERR("unsupported DT_REL in \"%s\"", name); - return false; - case DT_RELSZ: - DL_ERR("unsupported DT_RELSZ in \"%s\"", name); - return false; + case DT_RELA: + rela = reinterpret_cast(load_bias + d->d_un.d_ptr); + break; + case DT_RELASZ: + rela_count = d->d_un.d_val / sizeof(ElfW(Rela)); + break; + case DT_REL: + DL_ERR("unsupported DT_REL in \"%s\"", name); + return false; + case DT_RELSZ: + DL_ERR("unsupported DT_RELSZ in \"%s\"", name); + return false; #else - case DT_REL: - rel = reinterpret_cast(load_bias + d->d_un.d_ptr); - break; - case DT_RELSZ: - rel_count = d->d_un.d_val / sizeof(ElfW(Rel)); - break; - case DT_RELA: - DL_ERR("unsupported DT_RELA in \"%s\"", name); - return false; + case DT_REL: + rel = reinterpret_cast(load_bias + d->d_un.d_ptr); + break; + case DT_RELSZ: + rel_count = d->d_un.d_val / sizeof(ElfW(Rel)); + break; + case DT_RELA: + DL_ERR("unsupported DT_RELA in \"%s\"", name); + return false; #endif - case DT_INIT: - init_func = reinterpret_cast(load_bias + d->d_un.d_ptr); - DEBUG("%s constructors (DT_INIT) found at %p", name, init_func); - break; - case DT_FINI: - fini_func = reinterpret_cast(load_bias + d->d_un.d_ptr); - DEBUG("%s destructors (DT_FINI) found at %p", name, fini_func); - break; - case DT_INIT_ARRAY: - init_array = reinterpret_cast(load_bias + d->d_un.d_ptr); - DEBUG("%s constructors (DT_INIT_ARRAY) found at %p", name, init_array); - break; - case DT_INIT_ARRAYSZ: - init_array_count = ((unsigned)d->d_un.d_val) / sizeof(ElfW(Addr)); - break; - case DT_FINI_ARRAY: - fini_array = reinterpret_cast(load_bias + d->d_un.d_ptr); - DEBUG("%s destructors (DT_FINI_ARRAY) found at %p", name, fini_array); - break; - case DT_FINI_ARRAYSZ: - fini_array_count = ((unsigned)d->d_un.d_val) / sizeof(ElfW(Addr)); - break; - case DT_PREINIT_ARRAY: - preinit_array = reinterpret_cast(load_bias + d->d_un.d_ptr); - DEBUG("%s constructors (DT_PREINIT_ARRAY) found at %p", name, preinit_array); - break; - case DT_PREINIT_ARRAYSZ: - preinit_array_count = ((unsigned)d->d_un.d_val) / sizeof(ElfW(Addr)); - break; - case DT_TEXTREL: + case DT_INIT: + init_func = reinterpret_cast(load_bias + d->d_un.d_ptr); + DEBUG("%s constructors (DT_INIT) found at %p", name, init_func); + break; + case DT_FINI: + fini_func = reinterpret_cast(load_bias + d->d_un.d_ptr); + DEBUG("%s destructors (DT_FINI) found at %p", name, fini_func); + break; + case DT_INIT_ARRAY: + init_array = reinterpret_cast(load_bias + d->d_un.d_ptr); + DEBUG("%s constructors (DT_INIT_ARRAY) found at %p", name, init_array); + break; + case DT_INIT_ARRAYSZ: + init_array_count = ((unsigned)d->d_un.d_val) / sizeof(ElfW(Addr)); + break; + case DT_FINI_ARRAY: + fini_array = reinterpret_cast(load_bias + d->d_un.d_ptr); + DEBUG("%s destructors (DT_FINI_ARRAY) found at %p", name, fini_array); + break; + case DT_FINI_ARRAYSZ: + fini_array_count = ((unsigned)d->d_un.d_val) / sizeof(ElfW(Addr)); + break; + case DT_PREINIT_ARRAY: + preinit_array = reinterpret_cast(load_bias + d->d_un.d_ptr); + DEBUG("%s constructors (DT_PREINIT_ARRAY) found at %p", name, preinit_array); + break; + case DT_PREINIT_ARRAYSZ: + preinit_array_count = ((unsigned)d->d_un.d_val) / sizeof(ElfW(Addr)); + break; + case DT_TEXTREL: #if defined(__LP64__) - DL_ERR("text relocations (DT_TEXTREL) found in 64-bit ELF file \"%s\"", name); - return false; + DL_ERR("text relocations (DT_TEXTREL) found in 64-bit ELF file \"%s\"", name); + return false; #else - has_text_relocations = true; - break; + has_text_relocations = true; + break; #endif - case DT_SYMBOLIC: - has_DT_SYMBOLIC = true; - break; - case DT_NEEDED: - ++needed_count; - break; - case DT_FLAGS: - if (d->d_un.d_val & DF_TEXTREL) { + case DT_SYMBOLIC: + has_DT_SYMBOLIC = true; + break; + case DT_NEEDED: + ++needed_count; + break; + case DT_FLAGS: + if (d->d_un.d_val & DF_TEXTREL) { #if defined(__LP64__) - DL_ERR("text relocations (DF_TEXTREL) found in 64-bit ELF file \"%s\"", name); - return false; + DL_ERR("text relocations (DF_TEXTREL) found in 64-bit ELF file \"%s\"", name); + return false; #else - has_text_relocations = true; + has_text_relocations = true; #endif - } - if (d->d_un.d_val & DF_SYMBOLIC) { - has_DT_SYMBOLIC = true; - } - break; -#if defined(__mips__) - case DT_STRSZ: - case DT_SYMENT: - case DT_RELENT: - break; - case DT_MIPS_RLD_MAP: - // Set the DT_MIPS_RLD_MAP entry to the address of _r_debug for GDB. - { - r_debug** dp = reinterpret_cast(load_bias + d->d_un.d_ptr); - *dp = &_r_debug; - } - break; - case DT_MIPS_RLD_VERSION: - case DT_MIPS_FLAGS: - case DT_MIPS_BASE_ADDRESS: - case DT_MIPS_UNREFEXTNO: - break; - - case DT_MIPS_SYMTABNO: - mips_symtabno = d->d_un.d_val; - break; - - case DT_MIPS_LOCAL_GOTNO: - mips_local_gotno = d->d_un.d_val; - break; - - case DT_MIPS_GOTSYM: - mips_gotsym = d->d_un.d_val; - break; -#endif - - default: - DEBUG("Unused DT entry: type %p arg %p", - reinterpret_cast(d->d_tag), reinterpret_cast(d->d_un.d_val)); - break; } - } + if (d->d_un.d_val & DF_SYMBOLIC) { + has_DT_SYMBOLIC = true; + } + break; +#if defined(__mips__) + case DT_STRSZ: + case DT_SYMENT: + case DT_RELENT: + break; + case DT_MIPS_RLD_MAP: + // Set the DT_MIPS_RLD_MAP entry to the address of _r_debug for GDB. + { + r_debug** dp = reinterpret_cast(load_bias + d->d_un.d_ptr); + *dp = &_r_debug; + } + break; + case DT_MIPS_RLD_VERSION: + case DT_MIPS_FLAGS: + case DT_MIPS_BASE_ADDRESS: + case DT_MIPS_UNREFEXTNO: + break; - DEBUG("si->base = %p, si->strtab = %p, si->symtab = %p", - reinterpret_cast(base), strtab, symtab); + case DT_MIPS_SYMTABNO: + mips_symtabno = d->d_un.d_val; + break; - // Sanity checks. - if (relocating_linker && needed_count != 0) { - DL_ERR("linker cannot have DT_NEEDED dependencies on other libraries"); - return false; + case DT_MIPS_LOCAL_GOTNO: + mips_local_gotno = d->d_un.d_val; + break; + + case DT_MIPS_GOTSYM: + mips_gotsym = d->d_un.d_val; + break; +#endif + + default: + DEBUG("Unused DT entry: type %p arg %p", + reinterpret_cast(d->d_tag), reinterpret_cast(d->d_un.d_val)); + break; } - if (nbucket == 0) { - DL_ERR("empty/missing DT_HASH in \"%s\" (built with --hash-style=gnu?)", name); - return false; - } - if (strtab == 0) { - DL_ERR("empty/missing DT_STRTAB in \"%s\"", name); - return false; - } - if (symtab == 0) { - DL_ERR("empty/missing DT_SYMTAB in \"%s\"", name); - return false; - } - return true; + } + + DEBUG("si->base = %p, si->strtab = %p, si->symtab = %p", + reinterpret_cast(base), strtab, symtab); + + // Sanity checks. + if (relocating_linker && needed_count != 0) { + DL_ERR("linker cannot have DT_NEEDED dependencies on other libraries"); + return false; + } + if (nbucket == 0) { + DL_ERR("empty/missing DT_HASH in \"%s\" (built with --hash-style=gnu?)", name); + return false; + } + if (strtab == 0) { + DL_ERR("empty/missing DT_STRTAB in \"%s\"", name); + return false; + } + if (symtab == 0) { + DL_ERR("empty/missing DT_SYMTAB in \"%s\"", name); + return false; + } + return true; } bool soinfo::LinkImage(const android_dlextinfo* extinfo) { #if !defined(__LP64__) - if (has_text_relocations) { - // Make segments writable to allow text relocations to work properly. We will later call - // phdr_table_protect_segments() after all of them are applied and all constructors are run. - DL_WARN("%s has text relocations. This is wasting memory and prevents " - "security hardening. Please fix.", name); - if (phdr_table_unprotect_segments(phdr, phnum, load_bias) < 0) { - DL_ERR("can't unprotect loadable segments for \"%s\": %s", - name, strerror(errno)); - return false; - } + if (has_text_relocations) { + // Make segments writable to allow text relocations to work properly. We will later call + // phdr_table_protect_segments() after all of them are applied and all constructors are run. + DL_WARN("%s has text relocations. This is wasting memory and prevents " + "security hardening. Please fix.", name); + if (phdr_table_unprotect_segments(phdr, phnum, load_bias) < 0) { + DL_ERR("can't unprotect loadable segments for \"%s\": %s", + name, strerror(errno)); + return false; } + } #endif #if defined(USE_RELA) - if (rela != nullptr) { - DEBUG("[ relocating %s ]", name); - if (Relocate(rela, rela_count)) { - return false; - } + if (rela != nullptr) { + DEBUG("[ relocating %s ]", name); + if (Relocate(rela, rela_count)) { + return false; } - if (plt_rela != nullptr) { - DEBUG("[ relocating %s plt ]", name); - if (Relocate(plt_rela, plt_rela_count)) { - return false; - } + } + if (plt_rela != nullptr) { + DEBUG("[ relocating %s plt ]", name); + if (Relocate(plt_rela, plt_rela_count)) { + return false; } + } #else - if (rel != nullptr) { - DEBUG("[ relocating %s ]", name); - if (Relocate(rel, rel_count)) { - return false; - } + if (rel != nullptr) { + DEBUG("[ relocating %s ]", name); + if (Relocate(rel, rel_count)) { + return false; } - if (plt_rel != nullptr) { - DEBUG("[ relocating %s plt ]", name); - if (Relocate(plt_rel, plt_rel_count)) { - return false; - } + } + if (plt_rel != nullptr) { + DEBUG("[ relocating %s plt ]", name); + if (Relocate(plt_rel, plt_rel_count)) { + return false; } + } #endif #if defined(__mips__) - if (!mips_relocate_got(this)) { - return false; - } + if (!mips_relocate_got(this)) { + return false; + } #endif - DEBUG("[ finished linking %s ]", name); + DEBUG("[ finished linking %s ]", name); #if !defined(__LP64__) - if (has_text_relocations) { - // All relocations are done, we can protect our segments back to read-only. - if (phdr_table_protect_segments(phdr, phnum, load_bias) < 0) { - DL_ERR("can't protect segments for \"%s\": %s", - name, strerror(errno)); - return false; - } + if (has_text_relocations) { + // All relocations are done, we can protect our segments back to read-only. + if (phdr_table_protect_segments(phdr, phnum, load_bias) < 0) { + DL_ERR("can't protect segments for \"%s\": %s", + name, strerror(errno)); + return false; } + } #endif - /* We can also turn on GNU RELRO protection */ - if (phdr_table_protect_gnu_relro(phdr, phnum, load_bias) < 0) { - DL_ERR("can't enable GNU RELRO protection for \"%s\": %s", - name, strerror(errno)); - return false; - } + /* We can also turn on GNU RELRO protection */ + if (phdr_table_protect_gnu_relro(phdr, phnum, load_bias) < 0) { + DL_ERR("can't enable GNU RELRO protection for \"%s\": %s", + name, strerror(errno)); + return false; + } - /* Handle serializing/sharing the RELRO segment */ - if (extinfo && (extinfo->flags & ANDROID_DLEXT_WRITE_RELRO)) { - if (phdr_table_serialize_gnu_relro(phdr, phnum, load_bias, - extinfo->relro_fd) < 0) { - DL_ERR("failed serializing GNU RELRO section for \"%s\": %s", - name, strerror(errno)); - return false; - } - } else if (extinfo && (extinfo->flags & ANDROID_DLEXT_USE_RELRO)) { - if (phdr_table_map_gnu_relro(phdr, phnum, load_bias, - extinfo->relro_fd) < 0) { - DL_ERR("failed mapping GNU RELRO section for \"%s\": %s", - name, strerror(errno)); - return false; - } + /* Handle serializing/sharing the RELRO segment */ + if (extinfo && (extinfo->flags & ANDROID_DLEXT_WRITE_RELRO)) { + if (phdr_table_serialize_gnu_relro(phdr, phnum, load_bias, + extinfo->relro_fd) < 0) { + DL_ERR("failed serializing GNU RELRO section for \"%s\": %s", + name, strerror(errno)); + return false; } + } else if (extinfo && (extinfo->flags & ANDROID_DLEXT_USE_RELRO)) { + if (phdr_table_map_gnu_relro(phdr, phnum, load_bias, + extinfo->relro_fd) < 0) { + DL_ERR("failed mapping GNU RELRO section for \"%s\": %s", + name, strerror(errno)); + return false; + } + } - notify_gdb_of_load(this); - return true; + notify_gdb_of_load(this); + return true; } /* @@ -2267,182 +2263,182 @@ static void init_linker_info_for_gdb(ElfW(Addr) linker_base) { */ static ElfW(Addr) __linker_init_post_relocation(KernelArgumentBlock& args, ElfW(Addr) linker_base) { #if TIMING - struct timeval t0, t1; - gettimeofday(&t0, 0); + struct timeval t0, t1; + gettimeofday(&t0, 0); #endif - // Initialize environment functions, and get to the ELF aux vectors table. - linker_env_init(args); + // Initialize environment functions, and get to the ELF aux vectors table. + linker_env_init(args); - // If this is a setuid/setgid program, close the security hole described in - // ftp://ftp.freebsd.org/pub/FreeBSD/CERT/advisories/FreeBSD-SA-02:23.stdio.asc - if (get_AT_SECURE()) { - nullify_closed_stdio(); + // If this is a setuid/setgid program, close the security hole described in + // ftp://ftp.freebsd.org/pub/FreeBSD/CERT/advisories/FreeBSD-SA-02:23.stdio.asc + if (get_AT_SECURE()) { + nullify_closed_stdio(); + } + + debuggerd_init(); + + // Get a few environment variables. + const char* LD_DEBUG = linker_env_get("LD_DEBUG"); + if (LD_DEBUG != nullptr) { + g_ld_debug_verbosity = atoi(LD_DEBUG); + } + + // Normally, these are cleaned by linker_env_init, but the test + // doesn't cost us anything. + const char* ldpath_env = nullptr; + const char* ldpreload_env = nullptr; + if (!get_AT_SECURE()) { + ldpath_env = linker_env_get("LD_LIBRARY_PATH"); + ldpreload_env = linker_env_get("LD_PRELOAD"); + } + + INFO("[ android linker & debugger ]"); + + soinfo* si = soinfo_alloc(args.argv[0], nullptr, 0); + if (si == nullptr) { + exit(EXIT_FAILURE); + } + + /* bootstrap the link map, the main exe always needs to be first */ + si->flags |= FLAG_EXE; + link_map* map = &(si->link_map_head); + + map->l_addr = 0; + map->l_name = args.argv[0]; + map->l_prev = nullptr; + map->l_next = nullptr; + + _r_debug.r_map = map; + r_debug_tail = map; + + init_linker_info_for_gdb(linker_base); + + // Extract information passed from the kernel. + si->phdr = reinterpret_cast(args.getauxval(AT_PHDR)); + si->phnum = args.getauxval(AT_PHNUM); + si->entry = args.getauxval(AT_ENTRY); + + /* Compute the value of si->base. We can't rely on the fact that + * the first entry is the PHDR because this will not be true + * for certain executables (e.g. some in the NDK unit test suite) + */ + si->base = 0; + si->size = phdr_table_get_load_size(si->phdr, si->phnum); + si->load_bias = 0; + for (size_t i = 0; i < si->phnum; ++i) { + if (si->phdr[i].p_type == PT_PHDR) { + si->load_bias = reinterpret_cast(si->phdr) - si->phdr[i].p_vaddr; + si->base = reinterpret_cast(si->phdr) - si->phdr[i].p_offset; + break; } + } + si->dynamic = nullptr; + si->ref_count = 1; - debuggerd_init(); + ElfW(Ehdr)* elf_hdr = reinterpret_cast(si->base); + if (elf_hdr->e_type != ET_DYN) { + __libc_format_fd(2, "error: only position independent executables (PIE) are supported.\n"); + exit(EXIT_FAILURE); + } - // Get a few environment variables. - const char* LD_DEBUG = linker_env_get("LD_DEBUG"); - if (LD_DEBUG != nullptr) { - g_ld_debug_verbosity = atoi(LD_DEBUG); - } + // Use LD_LIBRARY_PATH and LD_PRELOAD (but only if we aren't setuid/setgid). + parse_LD_LIBRARY_PATH(ldpath_env); + parse_LD_PRELOAD(ldpreload_env); - // Normally, these are cleaned by linker_env_init, but the test - // doesn't cost us anything. - const char* ldpath_env = nullptr; - const char* ldpreload_env = nullptr; - if (!get_AT_SECURE()) { - ldpath_env = linker_env_get("LD_LIBRARY_PATH"); - ldpreload_env = linker_env_get("LD_PRELOAD"); - } + somain = si; - INFO("[ android linker & debugger ]"); + si->PrelinkImage(); - soinfo* si = soinfo_alloc(args.argv[0], nullptr, 0); - if (si == nullptr) { - exit(EXIT_FAILURE); - } + // Load ld_preloads and dependencies. + StringLinkedList needed_library_name_list; + size_t needed_libraries_count = 0; + size_t ld_preloads_count = 0; + while (g_ld_preload_names[ld_preloads_count] != nullptr) { + needed_library_name_list.push_back(g_ld_preload_names[ld_preloads_count++]); + ++needed_libraries_count; + } - /* bootstrap the link map, the main exe always needs to be first */ - si->flags |= FLAG_EXE; - link_map* map = &(si->link_map_head); + for_each_dt_needed(si, [&](const char* name) { + needed_library_name_list.push_back(name); + ++needed_libraries_count; + }); - map->l_addr = 0; - map->l_name = args.argv[0]; - map->l_prev = nullptr; - map->l_next = nullptr; + const char* needed_library_names[needed_libraries_count]; + soinfo* needed_library_si[needed_libraries_count]; - _r_debug.r_map = map; - r_debug_tail = map; + memset(needed_library_names, 0, sizeof(needed_library_names)); + needed_library_name_list.copy_to_array(needed_library_names, needed_libraries_count); - init_linker_info_for_gdb(linker_base); + if (needed_libraries_count > 0 && !find_libraries(needed_library_names, needed_libraries_count, needed_library_si, g_ld_preloads, ld_preloads_count, 0, nullptr)) { + __libc_format_fd(2, "CANNOT LINK EXECUTABLE DEPENDENCIES: %s\n", linker_get_error_buffer()); + exit(EXIT_FAILURE); + } - // Extract information passed from the kernel. - si->phdr = reinterpret_cast(args.getauxval(AT_PHDR)); - si->phnum = args.getauxval(AT_PHNUM); - si->entry = args.getauxval(AT_ENTRY); + for (size_t i = 0; iadd_child(needed_library_si[i]); + } - /* Compute the value of si->base. We can't rely on the fact that - * the first entry is the PHDR because this will not be true - * for certain executables (e.g. some in the NDK unit test suite) - */ - si->base = 0; - si->size = phdr_table_get_load_size(si->phdr, si->phnum); - si->load_bias = 0; - for (size_t i = 0; i < si->phnum; ++i) { - if (si->phdr[i].p_type == PT_PHDR) { - si->load_bias = reinterpret_cast(si->phdr) - si->phdr[i].p_vaddr; - si->base = reinterpret_cast(si->phdr) - si->phdr[i].p_offset; - break; - } - } - si->dynamic = nullptr; - si->ref_count = 1; + if (!si->LinkImage(nullptr)) { + __libc_format_fd(2, "CANNOT LINK EXECUTABLE: %s\n", linker_get_error_buffer()); + exit(EXIT_FAILURE); + } - ElfW(Ehdr)* elf_hdr = reinterpret_cast(si->base); - if (elf_hdr->e_type != ET_DYN) { - __libc_format_fd(2, "error: only position independent executables (PIE) are supported.\n"); - exit(EXIT_FAILURE); - } + add_vdso(args); - // Use LD_LIBRARY_PATH and LD_PRELOAD (but only if we aren't setuid/setgid). - parse_LD_LIBRARY_PATH(ldpath_env); - parse_LD_PRELOAD(ldpreload_env); + si->CallPreInitConstructors(); - somain = si; - - si->PrelinkImage(); - - // Load ld_preloads and dependencies. - StringLinkedList needed_library_name_list; - size_t needed_libraries_count = 0; - size_t ld_preloads_count = 0; - while (g_ld_preload_names[ld_preloads_count] != nullptr) { - needed_library_name_list.push_back(g_ld_preload_names[ld_preloads_count++]); - ++needed_libraries_count; - } - - for_each_dt_needed(si, [&](const char* name) { - needed_library_name_list.push_back(name); - ++needed_libraries_count; - }); - - const char* needed_library_names[needed_libraries_count]; - soinfo* needed_library_si[needed_libraries_count]; - - memset(needed_library_names, 0, sizeof(needed_library_names)); - needed_library_name_list.copy_to_array(needed_library_names, needed_libraries_count); - - if (needed_libraries_count > 0 && !find_libraries(needed_library_names, needed_libraries_count, needed_library_si, g_ld_preloads, ld_preloads_count, 0, nullptr)) { - __libc_format_fd(2, "CANNOT LINK EXECUTABLE DEPENDENCIES: %s\n", linker_get_error_buffer()); - exit(EXIT_FAILURE); - } - - for (size_t i = 0; iadd_child(needed_library_si[i]); - } - - if (!si->LinkImage(nullptr)) { - __libc_format_fd(2, "CANNOT LINK EXECUTABLE: %s\n", linker_get_error_buffer()); - exit(EXIT_FAILURE); - } - - add_vdso(args); - - si->CallPreInitConstructors(); - - /* After the PrelinkImage, the si->load_bias is initialized. - * For so lib, the map->l_addr will be updated in notify_gdb_of_load. - * We need to update this value for so exe here. So Unwind_Backtrace - * for some arch like x86 could work correctly within so exe. - */ - map->l_addr = si->load_bias; - si->CallConstructors(); + /* After the PrelinkImage, the si->load_bias is initialized. + * For so lib, the map->l_addr will be updated in notify_gdb_of_load. + * We need to update this value for so exe here. So Unwind_Backtrace + * for some arch like x86 could work correctly within so exe. + */ + map->l_addr = si->load_bias; + si->CallConstructors(); #if TIMING - gettimeofday(&t1, nullptr); - PRINT("LINKER TIME: %s: %d microseconds", args.argv[0], (int) ( - (((long long)t1.tv_sec * 1000000LL) + (long long)t1.tv_usec) - - (((long long)t0.tv_sec * 1000000LL) + (long long)t0.tv_usec))); + gettimeofday(&t1, nullptr); + PRINT("LINKER TIME: %s: %d microseconds", args.argv[0], (int) ( + (((long long)t1.tv_sec * 1000000LL) + (long long)t1.tv_usec) - + (((long long)t0.tv_sec * 1000000LL) + (long long)t0.tv_usec))); #endif #if STATS - PRINT("RELO STATS: %s: %d abs, %d rel, %d copy, %d symbol", args.argv[0], - linker_stats.count[kRelocAbsolute], - linker_stats.count[kRelocRelative], - linker_stats.count[kRelocCopy], - linker_stats.count[kRelocSymbol]); + PRINT("RELO STATS: %s: %d abs, %d rel, %d copy, %d symbol", args.argv[0], + linker_stats.count[kRelocAbsolute], + linker_stats.count[kRelocRelative], + linker_stats.count[kRelocCopy], + linker_stats.count[kRelocSymbol]); #endif #if COUNT_PAGES - { - unsigned n; - unsigned i; - unsigned count = 0; - for (n = 0; n < 4096; n++) { - if (bitmask[n]) { - unsigned x = bitmask[n]; + { + unsigned n; + unsigned i; + unsigned count = 0; + for (n = 0; n < 4096; n++) { + if (bitmask[n]) { + unsigned x = bitmask[n]; #if defined(__LP64__) - for (i = 0; i < 32; i++) { + for (i = 0; i < 32; i++) { #else - for (i = 0; i < 8; i++) { + for (i = 0; i < 8; i++) { #endif - if (x & 1) { - count++; - } - x >>= 1; - } - } + if (x & 1) { + count++; + } + x >>= 1; } - PRINT("PAGES MODIFIED: %s: %d (%dKB)", args.argv[0], count, count * 4); + } } + PRINT("PAGES MODIFIED: %s: %d (%dKB)", args.argv[0], count, count * 4); + } #endif #if TIMING || STATS || COUNT_PAGES - fflush(stdout); + fflush(stdout); #endif - TRACE("[ Ready to execute '%s' @ %p ]", si->name, reinterpret_cast(si->entry)); - return si->entry; + TRACE("[ Ready to execute '%s' @ %p ]", si->name, reinterpret_cast(si->entry)); + return si->entry; } /* Compute the load-bias of an existing executable. This shall only From c85e82dde5c4b2accc50a9e17740b9005dfbae6a Mon Sep 17 00:00:00 2001 From: Dmitriy Ivanov Date: Mon, 15 Sep 2014 17:00:10 -0700 Subject: [PATCH 02/20] Fix dlsym() to take into account RTLD_GLOBAL/LOCAL Symbols from libraries opened with RTLD_LOCAL (default) should not be visible via dlsym(RLTD_DEFAULT/RTLD_NEXT, .) Bug: 17512583 Bug: 18186310 (cherry picked from commit e8ba50fe0d51fbefee1a8f5bb62bf51d841512c8) Change-Id: Idf6bbe2233fb2bfc0c88677e7d1fc518fb3f7a8b --- linker/dlfcn.cpp | 2 +- linker/linker.cpp | 48 ++++++++++++++++++---------- linker/linker.h | 5 ++- tests/dlfcn_test.cpp | 36 +++++++++++++++++++++ tests/libs/dlopen_testlib_simple.cpp | 2 +- 5 files changed, 73 insertions(+), 20 deletions(-) diff --git a/linker/dlfcn.cpp b/linker/dlfcn.cpp index 3631d2fe1..59f673ad5 100644 --- a/linker/dlfcn.cpp +++ b/linker/dlfcn.cpp @@ -232,7 +232,7 @@ static unsigned g_libdl_chains[] = { 0, 2, 3, 4, 5, 6, 7, 8, 9, 10, 0 }; static unsigned g_libdl_chains[] = { 0, 2, 3, 4, 5, 6, 7, 8, 9, 0 }; #endif -static soinfo __libdl_info("libdl.so", nullptr, 0); +static soinfo __libdl_info("libdl.so", nullptr, 0, RTLD_GLOBAL); // This is used by the dynamic linker. Every process gets these symbols for free. soinfo* get_libdl_info() { diff --git a/linker/linker.cpp b/linker/linker.cpp index 37e01893f..bd05498b0 100644 --- a/linker/linker.cpp +++ b/linker/linker.cpp @@ -282,13 +282,13 @@ static void protect_data(int protection) { g_soinfo_links_allocator.protect_all(protection); } -static soinfo* soinfo_alloc(const char* name, struct stat* file_stat, off64_t file_offset) { +static soinfo* soinfo_alloc(const char* name, struct stat* file_stat, off64_t file_offset, int rtld_flags) { if (strlen(name) >= SOINFO_NAME_LEN) { DL_ERR("library name \"%s\" too long", name); return nullptr; } - soinfo* si = new (g_soinfo_allocator.alloc()) soinfo(name, file_stat, file_offset); + soinfo* si = new (g_soinfo_allocator.alloc()) soinfo(name, file_stat, file_offset, rtld_flags); sonext->next = si; sonext = si; @@ -453,7 +453,7 @@ static ElfW(Sym)* soinfo_elf_lookup(soinfo* si, unsigned hash, const char* name) return nullptr; } -soinfo::soinfo(const char* name, const struct stat* file_stat, off64_t file_offset) { +soinfo::soinfo(const char* name, const struct stat* file_stat, off64_t file_offset, int rtld_flags) { memset(this, 0, sizeof(*this)); strlcpy(this->name, name, sizeof(this->name)); @@ -465,6 +465,8 @@ soinfo::soinfo(const char* name, const struct stat* file_stat, off64_t file_offs this->st_ino = file_stat->st_ino; this->file_offset = file_offset; } + + this->rtld_flags = rtld_flags; } static unsigned elfhash(const char* _name) { @@ -716,6 +718,10 @@ ElfW(Sym)* dlsym_linear_lookup(const char* name, soinfo** found, soinfo* start) ElfW(Sym)* s = nullptr; for (soinfo* si = start; (s == nullptr) && (si != nullptr); si = si->next) { + if ((si->get_rtld_flags() & RTLD_GLOBAL) == 0) { + continue; + } + s = soinfo_elf_lookup(si, elf_hash, name); if (s != nullptr) { *found = si; @@ -806,7 +812,7 @@ static void for_each_dt_needed(const soinfo* si, F action) { } } -static soinfo* load_library(LoadTaskList& load_tasks, const char* name, int dlflags, const android_dlextinfo* extinfo) { +static soinfo* load_library(LoadTaskList& load_tasks, const char* name, int rtld_flags, const android_dlextinfo* extinfo) { int fd = -1; off64_t file_offset = 0; ScopedFd file_guard(-1); @@ -851,7 +857,7 @@ static soinfo* load_library(LoadTaskList& load_tasks, const char* name, int dlfl } } - if ((dlflags & RTLD_NOLOAD) != 0) { + if ((rtld_flags & RTLD_NOLOAD) != 0) { DL_ERR("library \"%s\" wasn't loaded and RTLD_NOLOAD prevented it", name); return nullptr; } @@ -862,7 +868,7 @@ static soinfo* load_library(LoadTaskList& load_tasks, const char* name, int dlfl return nullptr; } - soinfo* si = soinfo_alloc(SEARCH_NAME(name), &file_stat, file_offset); + soinfo* si = soinfo_alloc(SEARCH_NAME(name), &file_stat, file_offset, rtld_flags); if (si == nullptr) { return nullptr; } @@ -894,7 +900,7 @@ static soinfo *find_loaded_library_by_name(const char* name) { return nullptr; } -static soinfo* find_library_internal(LoadTaskList& load_tasks, const char* name, int dlflags, const android_dlextinfo* extinfo) { +static soinfo* find_library_internal(LoadTaskList& load_tasks, const char* name, int rtld_flags, const android_dlextinfo* extinfo) { soinfo* si = find_loaded_library_by_name(name); @@ -902,7 +908,7 @@ static soinfo* find_library_internal(LoadTaskList& load_tasks, const char* name, // of this fact is done by load_library. if (si == nullptr) { TRACE("[ '%s' has not been found by name. Trying harder...]", name); - si = load_library(load_tasks, name, dlflags, extinfo); + si = load_library(load_tasks, name, rtld_flags, extinfo); } return si; @@ -926,7 +932,7 @@ static bool is_recursive(soinfo* si, soinfo* parent) { } static bool find_libraries(const char* const library_names[], size_t library_names_size, soinfo* soinfos[], - soinfo* ld_preloads[], size_t ld_preloads_size, int dlflags, const android_dlextinfo* extinfo) { + soinfo* ld_preloads[], size_t ld_preloads_size, int rtld_flags, const android_dlextinfo* extinfo) { // Step 0: prepare. LoadTaskList load_tasks; for (size_t i = 0; i < library_names_size; ++i) { @@ -952,7 +958,7 @@ static bool find_libraries(const char* const library_names[], size_t library_nam // Step 1: load and pre-link all DT_NEEDED libraries in breadth first order. for (LoadTask::unique_ptr task(load_tasks.pop_front()); task.get() != nullptr; task.reset(load_tasks.pop_front())) { - soinfo* si = find_library_internal(load_tasks, task->get_name(), dlflags, extinfo); + soinfo* si = find_library_internal(load_tasks, task->get_name(), rtld_flags, extinfo); if (si == nullptr) { return false; } @@ -997,7 +1003,7 @@ static bool find_libraries(const char* const library_names[], size_t library_nam return true; } -static soinfo* find_library(const char* name, int dlflags, const android_dlextinfo* extinfo) { +static soinfo* find_library(const char* name, int rtld_flags, const android_dlextinfo* extinfo) { if (name == nullptr) { somain->ref_count++; return somain; @@ -1005,7 +1011,7 @@ static soinfo* find_library(const char* name, int dlflags, const android_dlextin soinfo* si; - if (!find_libraries(&name, 1, &si, nullptr, 0, dlflags, extinfo)) { + if (!find_libraries(&name, 1, &si, nullptr, 0, rtld_flags, extinfo)) { return nullptr; } @@ -1790,6 +1796,14 @@ off64_t soinfo::get_file_offset() { return 0; } +int soinfo::get_rtld_flags() { + if (has_min_version(1)) { + return rtld_flags; + } + + return 0; +} + // This is a return on get_children()/get_parents() if // 'this->flags' does not have FLAG_NEW_SOINFO set. static soinfo::soinfo_list_t g_empty_list; @@ -2210,7 +2224,7 @@ static void add_vdso(KernelArgumentBlock& args __unused) { return; } - soinfo* si = soinfo_alloc("[vdso]", nullptr, 0); + soinfo* si = soinfo_alloc("[vdso]", nullptr, 0, 0); si->phdr = reinterpret_cast(reinterpret_cast(ehdr_vdso) + ehdr_vdso->e_phoff); si->phnum = ehdr_vdso->e_phnum; @@ -2231,7 +2245,7 @@ static void add_vdso(KernelArgumentBlock& args __unused) { #else #define LINKER_PATH "/system/bin/linker" #endif -static soinfo linker_soinfo_for_gdb(LINKER_PATH, nullptr, 0); +static soinfo linker_soinfo_for_gdb(LINKER_PATH, nullptr, 0, 0); /* gdb expects the linker to be in the debug shared object list. * Without this, gdb has trouble locating the linker's ".text" @@ -2295,7 +2309,7 @@ static ElfW(Addr) __linker_init_post_relocation(KernelArgumentBlock& args, ElfW( INFO("[ android linker & debugger ]"); - soinfo* si = soinfo_alloc(args.argv[0], nullptr, 0); + soinfo* si = soinfo_alloc(args.argv[0], nullptr, 0, RTLD_GLOBAL); if (si == nullptr) { exit(EXIT_FAILURE); } @@ -2370,7 +2384,7 @@ static ElfW(Addr) __linker_init_post_relocation(KernelArgumentBlock& args, ElfW( memset(needed_library_names, 0, sizeof(needed_library_names)); needed_library_name_list.copy_to_array(needed_library_names, needed_libraries_count); - if (needed_libraries_count > 0 && !find_libraries(needed_library_names, needed_libraries_count, needed_library_si, g_ld_preloads, ld_preloads_count, 0, nullptr)) { + if (needed_libraries_count > 0 && !find_libraries(needed_library_names, needed_libraries_count, needed_library_si, g_ld_preloads, ld_preloads_count, RTLD_GLOBAL, nullptr)) { __libc_format_fd(2, "CANNOT LINK EXECUTABLE DEPENDENCIES: %s\n", linker_get_error_buffer()); exit(EXIT_FAILURE); } @@ -2483,7 +2497,7 @@ extern "C" ElfW(Addr) __linker_init(void* raw_args) { ElfW(Ehdr)* elf_hdr = reinterpret_cast(linker_addr); ElfW(Phdr)* phdr = reinterpret_cast(linker_addr + elf_hdr->e_phoff); - soinfo linker_so("[dynamic linker]", nullptr, 0); + soinfo linker_so("[dynamic linker]", nullptr, 0, 0); // If the linker is not acting as PT_INTERP entry_point is equal to // _start. Which means that the linker is running as an executable and diff --git a/linker/linker.h b/linker/linker.h index 3b140ac24..ef2fbcd6c 100644 --- a/linker/linker.h +++ b/linker/linker.h @@ -199,7 +199,7 @@ struct soinfo { #endif bool has_DT_SYMBOLIC; - soinfo(const char* name, const struct stat* file_stat, off64_t file_offset); + soinfo(const char* name, const struct stat* file_stat, off64_t file_offset, int rtld_flags); void CallConstructors(); void CallDestructors(); @@ -214,6 +214,8 @@ struct soinfo { dev_t get_st_dev(); off64_t get_file_offset(); + int get_rtld_flags(); + soinfo_list_t& get_children(); soinfo_list_t& get_parents(); @@ -246,6 +248,7 @@ struct soinfo { // version >= 1 off64_t file_offset; + int rtld_flags; }; extern soinfo* get_libdl_info(); diff --git a/tests/dlfcn_test.cpp b/tests/dlfcn_test.cpp index 9c9fbdd12..a55b36420 100644 --- a/tests/dlfcn_test.cpp +++ b/tests/dlfcn_test.cpp @@ -202,6 +202,42 @@ TEST(dlfcn, dlopen_check_order) { dlclose(handle); } +TEST(dlfcn, dlopen_check_rtld_local) { + void* sym = dlsym(RTLD_DEFAULT, "dlopen_testlib_simple_func"); + ASSERT_TRUE(sym == nullptr); + + // implicit RTLD_LOCAL + void* handle = dlopen("libtest_simple.so", RTLD_NOW); + sym = dlsym(RTLD_DEFAULT, "dlopen_testlib_simple_func"); + ASSERT_TRUE(sym == nullptr); + ASSERT_SUBSTR("undefined symbol: dlopen_testlib_simple_func", dlerror()); + sym = dlsym(handle, "dlopen_testlib_simple_func"); + ASSERT_TRUE(sym != nullptr); + ASSERT_TRUE(reinterpret_cast(sym)()); + dlclose(handle); + + // explicit RTLD_LOCAL + handle = dlopen("libtest_simple.so", RTLD_NOW | RTLD_LOCAL); + sym = dlsym(RTLD_DEFAULT, "dlopen_testlib_simple_func"); + ASSERT_TRUE(sym == nullptr); + ASSERT_SUBSTR("undefined symbol: dlopen_testlib_simple_func", dlerror()); + sym = dlsym(handle, "dlopen_testlib_simple_func"); + ASSERT_TRUE(sym != nullptr); + ASSERT_TRUE(reinterpret_cast(sym)()); + dlclose(handle); +} + +TEST(dlfcn, dlopen_check_rtld_global) { + void* sym = dlsym(RTLD_DEFAULT, "dlopen_testlib_simple_func"); + ASSERT_TRUE(sym == nullptr); + + void* handle = dlopen("libtest_simple.so", RTLD_NOW | RTLD_GLOBAL); + sym = dlsym(RTLD_DEFAULT, "dlopen_testlib_simple_func"); + ASSERT_TRUE(sym != nullptr) << dlerror(); + ASSERT_TRUE(reinterpret_cast(sym)()); + dlclose(handle); +} + // libtest_with_dependency_loop.so -> libtest_with_dependency_loop_a.so -> // libtest_with_dependency_loop_b.so -> libtest_with_dependency_loop_c.so -> // libtest_with_dependency_loop_a.so diff --git a/tests/libs/dlopen_testlib_simple.cpp b/tests/libs/dlopen_testlib_simple.cpp index afe54b4c0..06253e1f4 100644 --- a/tests/libs/dlopen_testlib_simple.cpp +++ b/tests/libs/dlopen_testlib_simple.cpp @@ -18,6 +18,6 @@ uint32_t dlopen_testlib_taxicab_number = 1729; -bool dlopen_testlib_simple_func() { +extern "C" bool dlopen_testlib_simple_func() { return true; } From b364d9538073716a256b37a790ff7bf3ddbb4f1b Mon Sep 17 00:00:00 2001 From: Dmitriy Ivanov Date: Tue, 16 Sep 2014 14:31:06 -0700 Subject: [PATCH 03/20] Remove has_DT_SYMBOLIC flag From the elf-spec: "Symbolically bound shared objects are identified by the .dynamic entry DT_SYMBOLIC. This tag is informational only; the runtime linker processes symbol lookups from these objects in the same manner as any other object." Bug: 18186310 (cherry picked from commit 8f61d991831f0ea515fa50a5c38dbbcfbab0dd28) Change-Id: I37024799ac8d1837993c8ae78780a448bedd6539 --- linker/dlfcn.cpp | 1 - linker/linker.cpp | 131 ++++++++++++++-------------------------------- linker/linker.h | 2 +- 3 files changed, 40 insertions(+), 94 deletions(-) diff --git a/linker/dlfcn.cpp b/linker/dlfcn.cpp index 59f673ad5..c02bfb89a 100644 --- a/linker/dlfcn.cpp +++ b/linker/dlfcn.cpp @@ -244,7 +244,6 @@ soinfo* get_libdl_info() { __libdl_info.nchain = sizeof(g_libdl_chains)/sizeof(unsigned); __libdl_info.bucket = g_libdl_buckets; __libdl_info.chain = g_libdl_chains; - __libdl_info.has_DT_SYMBOLIC = true; __libdl_info.ref_count = 1; } diff --git a/linker/linker.cpp b/linker/linker.cpp index bd05498b0..246475b4e 100644 --- a/linker/linker.cpp +++ b/linker/linker.cpp @@ -487,117 +487,65 @@ static ElfW(Sym)* soinfo_do_lookup(soinfo* si, const char* name, soinfo** lsi) { ElfW(Sym)* s = nullptr; if (somain != nullptr) { - /* - * Local scope is executable scope. Just start looking into it right away - * for the shortcut. - */ + DEBUG("%s: looking up %s in executable %s", + si->name, name, somain->name); - if (si == somain) { - s = soinfo_elf_lookup(si, elf_hash, name); - if (s != nullptr) { - *lsi = si; - goto done; - } + // 1. Look for it in the main executable + s = soinfo_elf_lookup(somain, elf_hash, name); + if (s != nullptr) { + *lsi = somain; + } - /* Next, look for it in the preloads list */ + // 2. Look for it in the ld_preloads + if (s == nullptr) { for (int i = 0; g_ld_preloads[i] != NULL; i++) { s = soinfo_elf_lookup(g_ld_preloads[i], elf_hash, name); - if (s != NULL) { - *lsi = g_ld_preloads[i]; - goto done; - } - } - } else { - /* Order of symbol lookup is controlled by DT_SYMBOLIC flag */ - - /* - * If this object was built with symbolic relocations disabled, the - * first place to look to resolve external references is the main - * executable. - */ - - if (!si->has_DT_SYMBOLIC) { - DEBUG("%s: looking up %s in executable %s", - si->name, name, somain->name); - s = soinfo_elf_lookup(somain, elf_hash, name); if (s != nullptr) { - *lsi = somain; - goto done; - } - - /* Next, look for it in the preloads list */ - for (int i = 0; g_ld_preloads[i] != NULL; i++) { - s = soinfo_elf_lookup(g_ld_preloads[i], elf_hash, name); - if (s != NULL) { - *lsi = g_ld_preloads[i]; - goto done; - } + *lsi = g_ld_preloads[i]; + break; } } + } - /* Look for symbols in the local scope (the object who is - * searching). This happens with C++ templates on x86 for some - * reason. - * - * Notes on weak symbols: - * The ELF specs are ambiguous about treatment of weak definitions in - * dynamic linking. Some systems return the first definition found - * and some the first non-weak definition. This is system dependent. - * Here we return the first definition found for simplicity. */ + /* Look for symbols in the local scope (the object who is + * searching). This happens with C++ templates on x86 for some + * reason. + * + * Notes on weak symbols: + * The ELF specs are ambiguous about treatment of weak definitions in + * dynamic linking. Some systems return the first definition found + * and some the first non-weak definition. This is system dependent. + * Here we return the first definition found for simplicity. */ + if (s == nullptr) { s = soinfo_elf_lookup(si, elf_hash, name); if (s != nullptr) { *lsi = si; - goto done; - } - - /* - * If this object was built with -Bsymbolic and symbol is not found - * in the local scope, try to find the symbol in the main executable. - */ - - if (si->has_DT_SYMBOLIC) { - DEBUG("%s: looking up %s in executable %s after local scope", - si->name, name, somain->name); - s = soinfo_elf_lookup(somain, elf_hash, name); - if (s != nullptr) { - *lsi = somain; - goto done; - } - - /* Next, look for it in the preloads list */ - for (int i = 0; g_ld_preloads[i] != NULL; i++) { - s = soinfo_elf_lookup(g_ld_preloads[i], elf_hash, name); - if (s != NULL) { - *lsi = g_ld_preloads[i]; - goto done; - } - } } } } - si->get_children().visit([&](soinfo* child) { - DEBUG("%s: looking up %s in %s", si->name, name, child->name); - s = soinfo_elf_lookup(child, elf_hash, name); - if (s != nullptr) { - *lsi = child; - return false; - } - return true; - }); + if (s == nullptr) { + si->get_children().visit([&](soinfo* child) { + DEBUG("%s: looking up %s in %s", si->name, name, child->name); + s = soinfo_elf_lookup(child, elf_hash, name); + if (s != nullptr) { + *lsi = child; + return false; + } + return true; + }); + } -done: if (s != nullptr) { TRACE_TYPE(LOOKUP, "si %s sym %s s->st_value = %p, " "found in %s, base = %p, load bias = %p", si->name, name, reinterpret_cast(s->st_value), (*lsi)->name, reinterpret_cast((*lsi)->base), reinterpret_cast((*lsi)->load_bias)); - return s; } - return nullptr; + return s; } // Each size has it's own allocator. @@ -2042,7 +1990,7 @@ bool soinfo::PrelinkImage() { break; #endif case DT_SYMBOLIC: - has_DT_SYMBOLIC = true; + // ignored break; case DT_NEEDED: ++needed_count; @@ -2056,9 +2004,6 @@ bool soinfo::PrelinkImage() { has_text_relocations = true; #endif } - if (d->d_un.d_val & DF_SYMBOLIC) { - has_DT_SYMBOLIC = true; - } break; #if defined(__mips__) case DT_STRSZ: @@ -2092,8 +2037,10 @@ bool soinfo::PrelinkImage() { #endif default: - DEBUG("Unused DT entry: type %p arg %p", - reinterpret_cast(d->d_tag), reinterpret_cast(d->d_un.d_val)); + if (!relocating_linker) { + DL_WARN("%s: unused DT entry: type %p arg %p", name, + reinterpret_cast(d->d_tag), reinterpret_cast(d->d_un.d_val)); + } break; } } diff --git a/linker/linker.h b/linker/linker.h index ef2fbcd6c..e39585006 100644 --- a/linker/linker.h +++ b/linker/linker.h @@ -197,7 +197,7 @@ struct soinfo { #if !defined(__LP64__) bool has_text_relocations; #endif - bool has_DT_SYMBOLIC; + bool unused4; // DO NOT USE, maintained for compatibility soinfo(const char* name, const struct stat* file_stat, off64_t file_offset, int rtld_flags); From 634a045c5c2ca1df35f582ed24bb3af0dc1d7151 Mon Sep 17 00:00:00 2001 From: Dmitriy Ivanov Date: Tue, 16 Sep 2014 15:51:25 -0700 Subject: [PATCH 04/20] Fix some unused DT_ warnings * DT_PLTGOT - ignored for non-mips * DT_RELCOUNT/RELACOUNT - ignored * DT_RELENT/RELAENT - sanity checks * DT_SYMENT - sanity check * DT_SONAME - ignore for now. Bug: 18186310 (cherry picked from commit 4a6e9a835a84aca965f0170f604381dae7f130be) Change-Id: Ib40095f0770d65628fc7abac5a471378de35ebe7 --- linker/linker.cpp | 39 +++++++++++++++++++++++++++++++++++---- 1 file changed, 35 insertions(+), 4 deletions(-) diff --git a/linker/linker.cpp b/linker/linker.cpp index 246475b4e..875335f6c 100644 --- a/linker/linker.cpp +++ b/linker/linker.cpp @@ -1875,6 +1875,10 @@ bool soinfo::PrelinkImage() { DEBUG("d = %p, d[0](tag) = %p d[1](val) = %p", d, reinterpret_cast(d->d_tag), reinterpret_cast(d->d_un.d_val)); switch (d->d_tag) { + case DT_SONAME: + // TODO: glibc dynamic linker uses this name for + // initial library lookup; consider doing the same here. + break; case DT_HASH: nbucket = reinterpret_cast(load_bias + d->d_un.d_ptr)[0]; nchain = reinterpret_cast(load_bias + d->d_un.d_ptr)[1]; @@ -1887,6 +1891,12 @@ bool soinfo::PrelinkImage() { case DT_SYMTAB: symtab = reinterpret_cast(load_bias + d->d_un.d_ptr); break; + case DT_SYMENT: + if (d->d_un.d_val != sizeof(ElfW(Sym))) { + DL_ERR("invalid DT_SYMENT: %d", d->d_un.d_val); + return false; + } + break; #if !defined(__LP64__) case DT_PLTREL: if (d->d_un.d_val != DT_REL) { @@ -1909,12 +1919,13 @@ bool soinfo::PrelinkImage() { plt_rel_count = d->d_un.d_val / sizeof(ElfW(Rel)); #endif break; -#if defined(__mips__) case DT_PLTGOT: +#if defined(__mips__) // Used by mips and mips64. plt_got = reinterpret_cast(load_bias + d->d_un.d_ptr); - break; #endif + // Ignore for other platforms... (because RTLD_LAZY is not supported) + break; case DT_DEBUG: // Set the DT_DEBUG entry to the address of _r_debug for GDB // if the dynamic table is writable @@ -1935,6 +1946,15 @@ bool soinfo::PrelinkImage() { case DT_RELASZ: rela_count = d->d_un.d_val / sizeof(ElfW(Rela)); break; + case DT_RELAENT: + if (d->d_un.d_val != sizeof(ElfW(Rela))) { + DL_ERR("invalid DT_RELAENT: %d", d->d_un.d_val); + return false; + } + break; + case DT_RELACOUNT: + // ignored (see DT_RELCOUNT comments for details) + break; case DT_REL: DL_ERR("unsupported DT_REL in \"%s\"", name); return false; @@ -1948,6 +1968,19 @@ bool soinfo::PrelinkImage() { case DT_RELSZ: rel_count = d->d_un.d_val / sizeof(ElfW(Rel)); break; + case DT_RELENT: + if (d->d_un.d_val != sizeof(ElfW(Rel))) { + DL_ERR("invalid DT_RELENT: %d", d->d_un.d_val); + return false; + } + break; + case DT_RELCOUNT: + // "Indicates that all RELATIVE relocations have been concatenated together, + // and specifies the RELATIVE relocation count." + // + // TODO: Spec also mentions that this can be used to optimize relocation process; + // Not currently used by bionic linker - ignored. + break; case DT_RELA: DL_ERR("unsupported DT_RELA in \"%s\"", name); return false; @@ -2007,8 +2040,6 @@ bool soinfo::PrelinkImage() { break; #if defined(__mips__) case DT_STRSZ: - case DT_SYMENT: - case DT_RELENT: break; case DT_MIPS_RLD_MAP: // Set the DT_MIPS_RLD_MAP entry to the address of _r_debug for GDB. From 09608848edf42fb999d08e59c8c81a62a79a6941 Mon Sep 17 00:00:00 2001 From: Dmitriy Ivanov Date: Tue, 16 Sep 2014 23:34:20 -0700 Subject: [PATCH 05/20] Fix 64bit build Bug: 18186310 (cherry picked from commit f240aa8089ea1574a7d799720efb66528f6ceb99) Change-Id: Id46f1f9be90a17a58fb44d3540095c8c685c9726 --- linker/linker.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/linker/linker.cpp b/linker/linker.cpp index 875335f6c..f8974eb6c 100644 --- a/linker/linker.cpp +++ b/linker/linker.cpp @@ -1893,7 +1893,7 @@ bool soinfo::PrelinkImage() { break; case DT_SYMENT: if (d->d_un.d_val != sizeof(ElfW(Sym))) { - DL_ERR("invalid DT_SYMENT: %d", d->d_un.d_val); + DL_ERR("invalid DT_SYMENT: %zd", static_cast(d->d_un.d_val)); return false; } break; @@ -1948,7 +1948,7 @@ bool soinfo::PrelinkImage() { break; case DT_RELAENT: if (d->d_un.d_val != sizeof(ElfW(Rela))) { - DL_ERR("invalid DT_RELAENT: %d", d->d_un.d_val); + DL_ERR("invalid DT_RELAENT: %zd", static_cast(d->d_un.d_val)); return false; } break; @@ -1970,7 +1970,7 @@ bool soinfo::PrelinkImage() { break; case DT_RELENT: if (d->d_un.d_val != sizeof(ElfW(Rel))) { - DL_ERR("invalid DT_RELENT: %d", d->d_un.d_val); + DL_ERR("invalid DT_RELENT: %zd", static_cast(d->d_un.d_val)); return false; } break; From d5eb10875affb316c4dfc3b6ceb91df244518956 Mon Sep 17 00:00:00 2001 From: Dmitriy Ivanov Date: Wed, 17 Sep 2014 16:46:40 -0700 Subject: [PATCH 06/20] Temporary disable DL_WARNs for unused DT_* Bug: 17552334 Bug: 18186310 (cherry picked from commit 1b77423eff21e916186fcb208f138e436e9f3052) Change-Id: I8a9d05195a862bc287fff7156913606f0311b8bb --- linker/linker.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/linker/linker.cpp b/linker/linker.cpp index f8974eb6c..c3178cba4 100644 --- a/linker/linker.cpp +++ b/linker/linker.cpp @@ -2069,7 +2069,7 @@ bool soinfo::PrelinkImage() { default: if (!relocating_linker) { - DL_WARN("%s: unused DT entry: type %p arg %p", name, + DEBUG("%s: unused DT entry: type %p arg %p", name, reinterpret_cast(d->d_tag), reinterpret_cast(d->d_un.d_val)); } break; From 748fbe5c41d97433dc756a50812e1caf6a6ef727 Mon Sep 17 00:00:00 2001 From: Elliott Hughes Date: Mon, 22 Sep 2014 17:43:09 -0700 Subject: [PATCH 07/20] Fix a couple more cases of missing CLOEXEC. The debuggerd case can probably never happen, because you're crashing at this point anyway. The system property one seems possible though. Bug: 18186310 (cherry picked from commit 0dc39f9952c5e3a3121ea77357bb264ef0f8ded7) Change-Id: I3e84488fc246f6c28cbd82e96d0cd4343a12c28a --- libc/bionic/system_properties.cpp | 4 ++-- linker/debugger.cpp | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/libc/bionic/system_properties.cpp b/libc/bionic/system_properties.cpp index a564c3939..0e16bf314 100644 --- a/libc/bionic/system_properties.cpp +++ b/libc/bionic/system_properties.cpp @@ -475,8 +475,8 @@ static const prop_info *find_property(prop_bt *const trie, const char *name, static int send_prop_msg(const prop_msg *msg) { - const int fd = socket(AF_LOCAL, SOCK_STREAM, 0); - if (fd < 0) { + const int fd = socket(AF_LOCAL, SOCK_STREAM | SOCK_CLOEXEC, 0); + if (fd == -1) { return -1; } diff --git a/linker/debugger.cpp b/linker/debugger.cpp index 6565985b5..ac466a5b4 100644 --- a/linker/debugger.cpp +++ b/linker/debugger.cpp @@ -215,7 +215,7 @@ static void send_debuggerd_packet(siginfo_t* info) { return; } - int s = socket_abstract_client(DEBUGGER_SOCKET_NAME, SOCK_STREAM); + int s = socket_abstract_client(DEBUGGER_SOCKET_NAME, SOCK_STREAM | SOCK_CLOEXEC); if (s == -1) { __libc_format_log(ANDROID_LOG_FATAL, "libc", "Unable to open connection to debuggerd: %s", strerror(errno)); From f90e21004e57e46b49c3338781eb3d58cc4bb517 Mon Sep 17 00:00:00 2001 From: Dmitriy Ivanov Date: Mon, 29 Sep 2014 12:10:36 -0700 Subject: [PATCH 08/20] Return has_DT_SYMBOLIC flag. This reverts commit 8f61d991831f0ea515fa50a5c38dbbcfbab0dd28 Despite the fact that static linker does all the work while linking -Bsymbolic executables, according to the SCO doc following DT_SYMBOLIC and DF_SYMBOLIC flags is still a requirement for the dynamic linker as well. (see http://www.sco.com/developers/gabi/2012-12-31/ch5.dynamic.html) Bug: 18186310 (cherry picked from commit 96bc37f2e1093416a432135265fd7a4db6c3df17) Change-Id: Ie217be4f3305d877066e4cfe91975ae1c7768330 --- linker/linker.cpp | 68 ++++++++++++++++++++++++++++++++--------------- linker/linker.h | 2 +- 2 files changed, 47 insertions(+), 23 deletions(-) diff --git a/linker/linker.cpp b/linker/linker.cpp index c3178cba4..30731090c 100644 --- a/linker/linker.cpp +++ b/linker/linker.cpp @@ -486,14 +486,34 @@ static ElfW(Sym)* soinfo_do_lookup(soinfo* si, const char* name, soinfo** lsi) { unsigned elf_hash = elfhash(name); ElfW(Sym)* s = nullptr; - if (somain != nullptr) { - DEBUG("%s: looking up %s in executable %s", - si->name, name, somain->name); - - // 1. Look for it in the main executable - s = soinfo_elf_lookup(somain, elf_hash, name); + /* "This element's presence in a shared object library alters the dynamic linker's + * symbol resolution algorithm for references within the library. Instead of starting + * a symbol search with the executable file, the dynamic linker starts from the shared + * object itself. If the shared object fails to supply the referenced symbol, the + * dynamic linker then searches the executable file and other shared objects as usual." + * + * http://www.sco.com/developers/gabi/2012-12-31/ch5.dynamic.html + * + * Note that this is unlikely since static linker avoids generating + * relocations for -Bsymbolic linked dynamic executables. + */ + if (si->has_DT_SYMBOLIC) { + DEBUG("%s: looking up %s in local scope (DT_SYMBOLIC)", si->name, name); + s = soinfo_elf_lookup(si, elf_hash, name); if (s != nullptr) { - *lsi = somain; + *lsi = si; + } + } + + if (s == nullptr && somain != nullptr) { + // 1. Look for it in the main executable unless we already did. + if (si != somain || !si->has_DT_SYMBOLIC) { + DEBUG("%s: looking up %s in executable %s", + si->name, name, somain->name); + s = soinfo_elf_lookup(somain, elf_hash, name); + if (s != nullptr) { + *lsi = somain; + } } // 2. Look for it in the ld_preloads @@ -506,22 +526,23 @@ static ElfW(Sym)* soinfo_do_lookup(soinfo* si, const char* name, soinfo** lsi) { } } } + } - /* Look for symbols in the local scope (the object who is - * searching). This happens with C++ templates on x86 for some - * reason. - * - * Notes on weak symbols: - * The ELF specs are ambiguous about treatment of weak definitions in - * dynamic linking. Some systems return the first definition found - * and some the first non-weak definition. This is system dependent. - * Here we return the first definition found for simplicity. */ + /* Look for symbols in the local scope (the object who is + * searching). This happens with C++ templates on x86 for some + * reason. + * + * Notes on weak symbols: + * The ELF specs are ambiguous about treatment of weak definitions in + * dynamic linking. Some systems return the first definition found + * and some the first non-weak definition. This is system dependent. + * Here we return the first definition found for simplicity. */ - if (s == nullptr) { - s = soinfo_elf_lookup(si, elf_hash, name); - if (s != nullptr) { - *lsi = si; - } + if (s == nullptr && !si->has_DT_SYMBOLIC) { + DEBUG("%s: looking up %s in local scope", si->name, name); + s = soinfo_elf_lookup(si, elf_hash, name); + if (s != nullptr) { + *lsi = si; } } @@ -2023,7 +2044,7 @@ bool soinfo::PrelinkImage() { break; #endif case DT_SYMBOLIC: - // ignored + has_DT_SYMBOLIC = true; break; case DT_NEEDED: ++needed_count; @@ -2037,6 +2058,9 @@ bool soinfo::PrelinkImage() { has_text_relocations = true; #endif } + if (d->d_un.d_val & DF_SYMBOLIC) { + has_DT_SYMBOLIC = true; + } break; #if defined(__mips__) case DT_STRSZ: diff --git a/linker/linker.h b/linker/linker.h index e39585006..ef2fbcd6c 100644 --- a/linker/linker.h +++ b/linker/linker.h @@ -197,7 +197,7 @@ struct soinfo { #if !defined(__LP64__) bool has_text_relocations; #endif - bool unused4; // DO NOT USE, maintained for compatibility + bool has_DT_SYMBOLIC; soinfo(const char* name, const struct stat* file_stat, off64_t file_offset, int rtld_flags); From 0f47d9c1ce3e75709f9d6ecb6b540bb518ee323a Mon Sep 17 00:00:00 2001 From: Dmitriy Ivanov Date: Mon, 29 Sep 2014 19:14:45 -0700 Subject: [PATCH 09/20] Fix unused DT entry warnings. DT_STRSZ Implement strtab boundary checks DT_FLAGS_1 Warn if flags other than DF_1_NOW|DF_1_GLOBAL are set Bug: 17552334 Bug: 18186310 (cherry picked from commit 6cdeb5234d7f4523fe9d83974f265d80f10512a6) Change-Id: I7ffc7bc600798308a77ad949a644949b64250ae2 --- libc/include/elf.h | 29 +++++++++++++++++++++++++++++ linker/dlfcn.cpp | 3 ++- linker/linker.cpp | 34 +++++++++++++++++++++++++++------- linker/linker.h | 9 ++++++++- 4 files changed, 66 insertions(+), 9 deletions(-) diff --git a/libc/include/elf.h b/libc/include/elf.h index 7a9485aea..7de464e0f 100644 --- a/libc/include/elf.h +++ b/libc/include/elf.h @@ -54,6 +54,35 @@ typedef struct { #define DF_BIND_NOW 0x00000008 #define DF_STATIC_TLS 0x00000010 +#define DF_1_NOW 0x00000001 // Perform complete relocation processing. +#define DF_1_GLOBAL 0x00000002 // implies RTLD_GLOBAL +#define DF_1_GROUP 0x00000004 +#define DF_1_NODELETE 0x00000008 // implies RTLD_NODELETE +#define DF_1_LOADFLTR 0x00000010 +#define DF_1_INITFIRST 0x00000020 +#define DF_1_NOOPEN 0x00000040 // Object can not be used with dlopen(3) +#define DF_1_ORIGIN 0x00000080 +#define DF_1_DIRECT 0x00000100 +#define DF_1_TRANS 0x00000200 +#define DF_1_INTERPOSE 0x00000400 +#define DF_1_NODEFLIB 0x00000800 +#define DF_1_NODUMP 0x00001000 // Object cannot be dumped with dldump(3) +#define DF_1_CONFALT 0x00002000 +#define DF_1_ENDFILTEE 0x00004000 +#define DF_1_DISPRELDNE 0x00008000 +#define DF_1_DISPRELPND 0x00010000 +#define DF_1_NODIRECT 0x00020000 +#define DF_1_IGNMULDEF 0x00040000 // Internal use +#define DF_1_NOKSYMS 0x00080000 // Internal use +#define DF_1_NOHDR 0x00100000 // Internal use +#define DF_1_EDITED 0x00200000 +#define DF_1_NORELOC 0x00400000 // Internal use +#define DF_1_SYMINTPOSE 0x00800000 +#define DF_1_GLOBAUDIT 0x01000000 +#define DF_1_SINGLETON 0x02000000 +#define DF_1_STUB 0x04000000 +#define DF_1_PIE 0x08000000 + #define DT_BIND_NOW 24 #define DT_INIT_ARRAY 25 #define DT_FINI_ARRAY 26 diff --git a/linker/dlfcn.cpp b/linker/dlfcn.cpp index c02bfb89a..367179d8d 100644 --- a/linker/dlfcn.cpp +++ b/linker/dlfcn.cpp @@ -147,7 +147,7 @@ int dladdr(const void* addr, Dl_info* info) { // Determine if any symbol in the library contains the specified address. ElfW(Sym)* sym = dladdr_find_symbol(si, addr); if (sym != nullptr) { - info->dli_sname = si->strtab + sym->st_name; + info->dli_sname = si->get_string(sym->st_name); info->dli_saddr = reinterpret_cast(si->resolve_symbol_address(sym)); } @@ -245,6 +245,7 @@ soinfo* get_libdl_info() { __libdl_info.bucket = g_libdl_buckets; __libdl_info.chain = g_libdl_chains; __libdl_info.ref_count = 1; + __libdl_info.strtab_size = sizeof(ANDROID_LIBDL_STRTAB); } return &__libdl_info; diff --git a/linker/linker.cpp b/linker/linker.cpp index 30731090c..9e26cf840 100644 --- a/linker/linker.cpp +++ b/linker/linker.cpp @@ -417,14 +417,13 @@ int dl_iterate_phdr(int (*cb)(dl_phdr_info* info, size_t size, void* data), void static ElfW(Sym)* soinfo_elf_lookup(soinfo* si, unsigned hash, const char* name) { ElfW(Sym)* symtab = si->symtab; - const char* strtab = si->strtab; TRACE_TYPE(LOOKUP, "SEARCH %s in %s@%p %x %zd", name, si->name, reinterpret_cast(si->base), hash, hash % si->nbucket); for (unsigned n = si->bucket[hash % si->nbucket]; n != 0; n = si->chain[n]) { ElfW(Sym)* s = symtab + n; - if (strcmp(strtab + s->st_name, name)) continue; + if (strcmp(si->get_string(s->st_name), name)) continue; // only concern ourselves with global and weak symbol definitions switch (ELF_ST_BIND(s->st_info)) { @@ -776,7 +775,7 @@ template static void for_each_dt_needed(const soinfo* si, F action) { for (ElfW(Dyn)* d = si->dynamic; d->d_tag != DT_NULL; ++d) { if (d->d_tag == DT_NEEDED) { - action(si->strtab + d->d_un.d_val); + action(si->get_string(d->d_un.d_val)); } } } @@ -1103,7 +1102,7 @@ int soinfo::Relocate(ElfW(Rela)* rela, unsigned count) { soinfo* lsi = nullptr; if (sym != 0) { - sym_name = reinterpret_cast(strtab + symtab[sym].st_name); + sym_name = get_string(symtab[sym].st_name); s = soinfo_do_lookup(this, sym_name, &lsi); if (s == nullptr) { // We only allow an undefined symbol if this is a weak reference... @@ -1381,7 +1380,7 @@ int soinfo::Relocate(ElfW(Rel)* rel, unsigned count) { soinfo* lsi = nullptr; if (sym != 0) { - sym_name = reinterpret_cast(strtab + symtab[sym].st_name); + sym_name = get_string(symtab[sym].st_name); s = soinfo_do_lookup(this, sym_name, &lsi); if (s == nullptr) { // We only allow an undefined symbol if this is a weak reference... @@ -1599,7 +1598,7 @@ static bool mips_relocate_got(soinfo* si) { got = si->plt_got + local_gotno; for (size_t g = gotsym; g < symtabno; g++, sym++, got++) { // This is an undefined reference... try to locate it. - const char* sym_name = si->strtab + sym->st_name; + const char* sym_name = si->get_string(sym->st_name); soinfo* lsi = nullptr; ElfW(Sym)* s = soinfo_do_lookup(si, sym_name, &lsi); if (s == nullptr) { @@ -1801,6 +1800,14 @@ ElfW(Addr) soinfo::resolve_symbol_address(ElfW(Sym)* s) { return static_cast(s->st_value + load_bias); } +const char* soinfo::get_string(ElfW(Word) index) const { + if (has_min_version(1) && (index >= strtab_size)) { + __libc_fatal("%s: strtab out of bounds error; STRSZ=%zd, name=%d", name, strtab_size, index); + } + + return strtab + index; +} + /* Force any of the closed stdin, stdout and stderr to be associated with /dev/null. */ static int nullify_closed_stdio() { @@ -1909,6 +1916,9 @@ bool soinfo::PrelinkImage() { case DT_STRTAB: strtab = reinterpret_cast(load_bias + d->d_un.d_ptr); break; + case DT_STRSZ: + strtab_size = d->d_un.d_val; + break; case DT_SYMTAB: symtab = reinterpret_cast(load_bias + d->d_un.d_ptr); break; @@ -2062,6 +2072,16 @@ bool soinfo::PrelinkImage() { has_DT_SYMBOLIC = true; } break; + case DT_FLAGS_1: + if ((d->d_un.d_val & DF_1_GLOBAL) != 0) { + rtld_flags |= RTLD_GLOBAL; + } + // TODO: Implement other flags + + if ((d->d_un.d_val & ~(DF_1_NOW | DF_1_GLOBAL)) != 0) { + DL_WARN("Unsupported flags DT_FLAGS_1=%p", reinterpret_cast(d->d_un.d_val)); + } + break; #if defined(__mips__) case DT_STRSZ: break; @@ -2093,7 +2113,7 @@ bool soinfo::PrelinkImage() { default: if (!relocating_linker) { - DEBUG("%s: unused DT entry: type %p arg %p", name, + DL_WARN("%s: unused DT entry: type %p arg %p", name, reinterpret_cast(d->d_tag), reinterpret_cast(d->d_un.d_val)); } break; diff --git a/linker/linker.h b/linker/linker.h index ef2fbcd6c..6329efda6 100644 --- a/linker/linker.h +++ b/linker/linker.h @@ -136,7 +136,9 @@ struct soinfo { soinfo* next; unsigned flags; + private: const char* strtab; + public: ElfW(Sym)* symtab; size_t nbucket; @@ -221,7 +223,9 @@ struct soinfo { ElfW(Addr) resolve_symbol_address(ElfW(Sym)* s); - bool inline has_min_version(uint32_t min_version) { + const char* get_string(ElfW(Word) index) const; + + bool inline has_min_version(uint32_t min_version) const { return (flags & FLAG_NEW_SOINFO) != 0 && version >= min_version; } private: @@ -249,6 +253,9 @@ struct soinfo { // version >= 1 off64_t file_offset; int rtld_flags; + size_t strtab_size; + + friend soinfo* get_libdl_info(); }; extern soinfo* get_libdl_info(); From 210ff1b27b67bd2aa29b35a46f48430b7714a802 Mon Sep 17 00:00:00 2001 From: Dmitriy Ivanov Date: Tue, 30 Sep 2014 16:30:22 -0700 Subject: [PATCH 10/20] Fix mips build Bug: 18186310 (cherry picked from commit ecf532fa1cfe91ca946243c11ef154c602870ba6) Change-Id: Ia12f2fa28c8cd3204eb7d6b4c7d872f4e81fb8ef --- linker/linker.cpp | 2 -- 1 file changed, 2 deletions(-) diff --git a/linker/linker.cpp b/linker/linker.cpp index 9e26cf840..d918bb56e 100644 --- a/linker/linker.cpp +++ b/linker/linker.cpp @@ -2083,8 +2083,6 @@ bool soinfo::PrelinkImage() { } break; #if defined(__mips__) - case DT_STRSZ: - break; case DT_MIPS_RLD_MAP: // Set the DT_MIPS_RLD_MAP entry to the address of _r_debug for GDB. { From c87f65d2cd0690d81665f8b241c1d763f72b6f80 Mon Sep 17 00:00:00 2001 From: Dmitriy Ivanov Date: Mon, 19 May 2014 15:06:58 -0700 Subject: [PATCH 11/20] Add RTLD_NODELETE flag support Bug: 18186310 Bug: https://code.google.com/p/android/issues/detail?id=64069 (cherry picked from commit 1b20dafdbe65e43b9f4c95057e8482380833ea91) Change-Id: Ic02eec22a7c322ece65eb40730a3404f611526b1 --- libc/include/dlfcn.h | 1 + linker/linker.cpp | 16 ++++- linker/linker.h | 18 ++--- tests/dlfcn_test.cpp | 80 +++++++++++++++++++++++ tests/libs/Android.mk | 29 ++++++++ tests/libs/dlopen_nodelete_1.cpp | 31 +++++++++ tests/libs/dlopen_nodelete_2.cpp | 31 +++++++++ tests/libs/dlopen_nodelete_dt_flags_1.cpp | 30 +++++++++ 8 files changed, 226 insertions(+), 10 deletions(-) create mode 100644 tests/libs/dlopen_nodelete_1.cpp create mode 100644 tests/libs/dlopen_nodelete_2.cpp create mode 100644 tests/libs/dlopen_nodelete_dt_flags_1.cpp diff --git a/libc/include/dlfcn.h b/libc/include/dlfcn.h index 8dde08cf5..afa76878f 100644 --- a/libc/include/dlfcn.h +++ b/libc/include/dlfcn.h @@ -64,6 +64,7 @@ enum { RTLD_GLOBAL = 2, #endif RTLD_NOLOAD = 4, + RTLD_NODELETE = 0x01000, }; #if defined (__LP64__) diff --git a/linker/linker.cpp b/linker/linker.cpp index d918bb56e..7b27cd79e 100644 --- a/linker/linker.cpp +++ b/linker/linker.cpp @@ -987,6 +987,11 @@ static soinfo* find_library(const char* name, int rtld_flags, const android_dlex } static void soinfo_unload(soinfo* si) { + if (!si->can_unload()) { + TRACE("not unloading '%s' - the binary is flagged with NODELETE", si->name); + return; + } + if (si->ref_count == 1) { TRACE("unloading '%s'", si->name); si->CallDestructors(); @@ -1045,7 +1050,7 @@ void do_android_update_LD_LIBRARY_PATH(const char* ld_library_path) { } soinfo* do_dlopen(const char* name, int flags, const android_dlextinfo* extinfo) { - if ((flags & ~(RTLD_NOW|RTLD_LAZY|RTLD_LOCAL|RTLD_GLOBAL|RTLD_NOLOAD)) != 0) { + if ((flags & ~(RTLD_NOW|RTLD_LAZY|RTLD_LOCAL|RTLD_GLOBAL|RTLD_NODELETE|RTLD_NOLOAD)) != 0) { DL_ERR("invalid flags to dlopen: %x", flags); return nullptr; } @@ -1808,6 +1813,9 @@ const char* soinfo::get_string(ElfW(Word) index) const { return strtab + index; } +bool soinfo::can_unload() const { + return (rtld_flags & (RTLD_NODELETE | RTLD_GLOBAL)) == 0; +} /* Force any of the closed stdin, stdout and stderr to be associated with /dev/null. */ static int nullify_closed_stdio() { @@ -2076,9 +2084,13 @@ bool soinfo::PrelinkImage() { if ((d->d_un.d_val & DF_1_GLOBAL) != 0) { rtld_flags |= RTLD_GLOBAL; } + + if ((d->d_un.d_val & DF_1_NODELETE) != 0) { + rtld_flags |= RTLD_NODELETE; + } // TODO: Implement other flags - if ((d->d_un.d_val & ~(DF_1_NOW | DF_1_GLOBAL)) != 0) { + if ((d->d_un.d_val & ~(DF_1_NOW | DF_1_GLOBAL | DF_1_NODELETE)) != 0) { DL_WARN("Unsupported flags DT_FLAGS_1=%p", reinterpret_cast(d->d_un.d_val)); } break; diff --git a/linker/linker.h b/linker/linker.h index 6329efda6..ebb4793af 100644 --- a/linker/linker.h +++ b/linker/linker.h @@ -134,7 +134,7 @@ struct soinfo { #endif soinfo* next; - unsigned flags; + uint32_t flags; private: const char* strtab; @@ -143,8 +143,8 @@ struct soinfo { size_t nbucket; size_t nchain; - unsigned* bucket; - unsigned* chain; + uint32_t* bucket; + uint32_t* chain; #if defined(__mips__) || !defined(__LP64__) // This is only used by mips and mips64, but needs to be here for @@ -179,12 +179,12 @@ struct soinfo { #if defined(__arm__) // ARM EABI section used for stack unwinding. - unsigned* ARM_exidx; + uint32_t* ARM_exidx; size_t ARM_exidx_count; #elif defined(__mips__) - unsigned mips_symtabno; - unsigned mips_local_gotno; - unsigned mips_gotsym; + uint32_t mips_symtabno; + uint32_t mips_local_gotno; + uint32_t mips_gotsym; #endif size_t ref_count; @@ -224,10 +224,12 @@ struct soinfo { ElfW(Addr) resolve_symbol_address(ElfW(Sym)* s); const char* get_string(ElfW(Word) index) const; + bool can_unload() const; bool inline has_min_version(uint32_t min_version) const { return (flags & FLAG_NEW_SOINFO) != 0 && version >= min_version; } + private: void CallArray(const char* array_name, linker_function_t* functions, size_t count, bool reverse); void CallFunction(const char* function_name, linker_function_t function); @@ -258,7 +260,7 @@ struct soinfo { friend soinfo* get_libdl_info(); }; -extern soinfo* get_libdl_info(); +soinfo* get_libdl_info(); void do_android_get_LD_LIBRARY_PATH(char*, size_t); void do_android_update_LD_LIBRARY_PATH(const char* ld_library_path); diff --git a/tests/dlfcn_test.cpp b/tests/dlfcn_test.cpp index a55b36420..e7787b4a4 100644 --- a/tests/dlfcn_test.cpp +++ b/tests/dlfcn_test.cpp @@ -232,10 +232,15 @@ TEST(dlfcn, dlopen_check_rtld_global) { ASSERT_TRUE(sym == nullptr); void* handle = dlopen("libtest_simple.so", RTLD_NOW | RTLD_GLOBAL); + ASSERT_TRUE(handle != nullptr) << dlerror(); sym = dlsym(RTLD_DEFAULT, "dlopen_testlib_simple_func"); ASSERT_TRUE(sym != nullptr) << dlerror(); ASSERT_TRUE(reinterpret_cast(sym)()); dlclose(handle); + + // RTLD_GLOBAL implies RTLD_NODELETE, let's check that + void* sym_after_dlclose = dlsym(RTLD_DEFAULT, "dlopen_testlib_simple_func"); + ASSERT_EQ(sym, sym_after_dlclose); } // libtest_with_dependency_loop.so -> libtest_with_dependency_loop_a.so -> @@ -258,6 +263,81 @@ TEST(dlfcn, dlopen_check_loop) { ASSERT_STREQ("dlopen failed: library \"libtest_with_dependency_loop.so\" wasn't loaded and RTLD_NOLOAD prevented it", dlerror()); } +TEST(dlfcn, dlopen_nodelete) { + static bool is_unloaded = false; + + void* handle = dlopen("libtest_nodelete_1.so", RTLD_NOW | RTLD_NODELETE); + ASSERT_TRUE(handle != nullptr) << dlerror(); + void (*set_unload_flag_ptr)(bool*); + set_unload_flag_ptr = reinterpret_cast(dlsym(handle, "dlopen_nodelete_1_set_unload_flag_ptr")); + ASSERT_TRUE(set_unload_flag_ptr != nullptr) << dlerror(); + set_unload_flag_ptr(&is_unloaded); + + uint32_t* taxicab_number = reinterpret_cast(dlsym(handle, "dlopen_nodelete_1_taxicab_number")); + ASSERT_TRUE(taxicab_number != nullptr) << dlerror(); + ASSERT_EQ(1729U, *taxicab_number); + *taxicab_number = 2; + + dlclose(handle); + ASSERT_TRUE(!is_unloaded); + + uint32_t* taxicab_number_after_dlclose = reinterpret_cast(dlsym(handle, "dlopen_nodelete_1_taxicab_number")); + ASSERT_EQ(taxicab_number_after_dlclose, taxicab_number); + ASSERT_EQ(2U, *taxicab_number_after_dlclose); + + + handle = dlopen("libtest_nodelete_1.so", RTLD_NOW); + uint32_t* taxicab_number2 = reinterpret_cast(dlsym(handle, "dlopen_nodelete_1_taxicab_number")); + ASSERT_EQ(taxicab_number2, taxicab_number); + + ASSERT_EQ(2U, *taxicab_number2); + + dlclose(handle); + ASSERT_TRUE(!is_unloaded); +} + +TEST(dlfcn, dlopen_nodelete_on_second_dlopen) { + static bool is_unloaded = false; + + void* handle = dlopen("libtest_nodelete_2.so", RTLD_NOW); + ASSERT_TRUE(handle != nullptr) << dlerror(); + void (*set_unload_flag_ptr)(bool*); + set_unload_flag_ptr = reinterpret_cast(dlsym(handle, "dlopen_nodelete_2_set_unload_flag_ptr")); + ASSERT_TRUE(set_unload_flag_ptr != nullptr) << dlerror(); + set_unload_flag_ptr(&is_unloaded); + + uint32_t* taxicab_number = reinterpret_cast(dlsym(handle, "dlopen_nodelete_2_taxicab_number")); + ASSERT_TRUE(taxicab_number != nullptr) << dlerror(); + + ASSERT_EQ(1729U, *taxicab_number); + *taxicab_number = 2; + + // This RTLD_NODELETE should be ignored + void* handle1 = dlopen("libtest_nodelete_2.so", RTLD_NOW | RTLD_NODELETE); + ASSERT_TRUE(handle1 != nullptr) << dlerror(); + ASSERT_EQ(handle, handle1); + + dlclose(handle1); + dlclose(handle); + + ASSERT_TRUE(is_unloaded); +} + +TEST(dlfcn, dlopen_nodelete_dt_flags_1) { + static bool is_unloaded = false; + + void* handle = dlopen("libtest_nodelete_dt_flags_1.so", RTLD_NOW); + ASSERT_TRUE(handle != nullptr) << dlerror(); + void (*set_unload_flag_ptr)(bool*); + set_unload_flag_ptr = reinterpret_cast(dlsym(handle, "dlopen_nodelete_dt_flags_1_set_unload_flag_ptr")); + ASSERT_TRUE(set_unload_flag_ptr != nullptr) << dlerror(); + set_unload_flag_ptr(&is_unloaded); + + dlclose(handle); + ASSERT_TRUE(!is_unloaded); +} + + TEST(dlfcn, dlopen_failure) { void* self = dlopen("/does/not/exist", RTLD_NOW); ASSERT_TRUE(self == NULL); diff --git a/tests/libs/Android.mk b/tests/libs/Android.mk index ee97c618a..b7335d59e 100644 --- a/tests/libs/Android.mk +++ b/tests/libs/Android.mk @@ -112,6 +112,35 @@ build_type := target build_target := SHARED_LIBRARY include $(TEST_PATH)/Android.build.mk +# ----------------------------------------------------------------------------- +# Library used by dlfcn nodelete tests +# ----------------------------------------------------------------------------- +libtest_nodelete_1_src_files := \ + dlopen_nodelete_1.cpp + +module := libtest_nodelete_1 +include $(LOCAL_PATH)/Android.build.testlib.mk + +# ----------------------------------------------------------------------------- +# Library used by dlfcn nodelete tests +# ----------------------------------------------------------------------------- +libtest_nodelete_2_src_files := \ + dlopen_nodelete_2.cpp + +module := libtest_nodelete_2 +include $(LOCAL_PATH)/Android.build.testlib.mk + +# ----------------------------------------------------------------------------- +# Library used by dlfcn nodelete tests +# ----------------------------------------------------------------------------- +libtest_nodelete_dt_flags_1_src_files := \ + dlopen_nodelete_dt_flags_1.cpp + +libtest_nodelete_dt_flags_1_ldflags := -Wl,-z,nodelete + +module := libtest_nodelete_dt_flags_1 +include $(LOCAL_PATH)/Android.build.testlib.mk + # ----------------------------------------------------------------------------- # Libraries used by dlfcn tests to verify correct load order: # libtest_check_order_2_right.so diff --git a/tests/libs/dlopen_nodelete_1.cpp b/tests/libs/dlopen_nodelete_1.cpp new file mode 100644 index 000000000..943897815 --- /dev/null +++ b/tests/libs/dlopen_nodelete_1.cpp @@ -0,0 +1,31 @@ +/* + * Copyright (C) 2014 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include + +uint32_t dlopen_nodelete_1_taxicab_number = 1729; +static bool* unload_flag_ptr = nullptr; + +extern "C" void dlopen_nodelete_1_set_unload_flag_ptr(bool* ptr) { + unload_flag_ptr = ptr; +} + +static void __attribute__((destructor)) unload_guard() { + if (unload_flag_ptr != nullptr) { + *unload_flag_ptr = true; + } +} diff --git a/tests/libs/dlopen_nodelete_2.cpp b/tests/libs/dlopen_nodelete_2.cpp new file mode 100644 index 000000000..b5ab5c1ae --- /dev/null +++ b/tests/libs/dlopen_nodelete_2.cpp @@ -0,0 +1,31 @@ +/* + * Copyright (C) 2014 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include + +uint32_t dlopen_nodelete_2_taxicab_number = 1729; +static bool* unload_flag_ptr = nullptr; + +extern "C" void dlopen_nodelete_2_set_unload_flag_ptr(bool* ptr) { + unload_flag_ptr = ptr; +} + +static void __attribute__((destructor)) unload_guard() { + if (unload_flag_ptr != nullptr) { + *unload_flag_ptr = true; + } +} diff --git a/tests/libs/dlopen_nodelete_dt_flags_1.cpp b/tests/libs/dlopen_nodelete_dt_flags_1.cpp new file mode 100644 index 000000000..39c0a7ea6 --- /dev/null +++ b/tests/libs/dlopen_nodelete_dt_flags_1.cpp @@ -0,0 +1,30 @@ +/* + * Copyright (C) 2014 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include + +static bool* unload_flag_ptr = nullptr; + +extern "C" void dlopen_nodelete_dt_flags_1_set_unload_flag_ptr(bool* ptr) { + unload_flag_ptr = ptr; +} + +static void __attribute__((destructor)) unload_guard() { + if (unload_flag_ptr != nullptr) { + *unload_flag_ptr = true; + } +} From 1d3e81a9e7795a320406cd903ef1767072ae122e Mon Sep 17 00:00:00 2001 From: Dmitriy Ivanov Date: Mon, 6 Oct 2014 11:30:43 -0700 Subject: [PATCH 12/20] Resolve "unused DT entry" warnings for x86_64 Bug: 18186310 (cherry picked from commit 513e29e16f16a6ffa1636ba282d599fd6b437aeb) Change-Id: I1e4c5af2cdc09dc978c7a78fcdcf8796c919751e --- linker/linker.cpp | 18 ++++++++++++++---- 1 file changed, 14 insertions(+), 4 deletions(-) diff --git a/linker/linker.cpp b/linker/linker.cpp index 7b27cd79e..d2bf4e570 100644 --- a/linker/linker.cpp +++ b/linker/linker.cpp @@ -1936,14 +1936,19 @@ bool soinfo::PrelinkImage() { return false; } break; -#if !defined(__LP64__) case DT_PLTREL: - if (d->d_un.d_val != DT_REL) { - DL_ERR("unsupported DT_RELA in \"%s\"", name); +#if defined(USE_RELA) + if (d->d_un.d_val != DT_RELA) { + DL_ERR("unsupported DT_PLTREL in \"%s\"; expected DT_RELA", name); + return false; + } +#else + if (d->d_un.d_val != DT_REL) { + DL_ERR("unsupported DT_PLTREL in \"%s\"; expected DT_REL", name); return false; } - break; #endif + break; case DT_JMPREL: #if defined(USE_RELA) plt_rela = reinterpret_cast(load_bias + d->d_un.d_ptr); @@ -2120,6 +2125,11 @@ bool soinfo::PrelinkImage() { mips_gotsym = d->d_un.d_val; break; #endif + case DT_VERSYM: + case DT_VERDEF: + case DT_VERDEFNUM: + // Ignore: bionic does not support symbol versioning... + break; default: if (!relocating_linker) { From e4bc6f026a10648756da031b5d765c78c9e70864 Mon Sep 17 00:00:00 2001 From: Dmitriy Ivanov Date: Wed, 15 Oct 2014 14:59:01 -0700 Subject: [PATCH 13/20] Ignore DT_BIND_NOW (0x18) Bug: 18186310 Bug: 17552334 (cherry picked from commit ea6eae182ad64312f80b9adddac511d8938e23e7) Change-Id: I07d6f6fbb462fea329581d0da02f6d88be1c262f --- linker/linker.cpp | 49 ++++++++++++++++++++++++++++++++++++++++------- 1 file changed, 42 insertions(+), 7 deletions(-) diff --git a/linker/linker.cpp b/linker/linker.cpp index d2bf4e570..41557e231 100644 --- a/linker/linker.cpp +++ b/linker/linker.cpp @@ -1915,27 +1915,33 @@ bool soinfo::PrelinkImage() { // TODO: glibc dynamic linker uses this name for // initial library lookup; consider doing the same here. break; + case DT_HASH: nbucket = reinterpret_cast(load_bias + d->d_un.d_ptr)[0]; nchain = reinterpret_cast(load_bias + d->d_un.d_ptr)[1]; bucket = reinterpret_cast(load_bias + d->d_un.d_ptr + 8); chain = reinterpret_cast(load_bias + d->d_un.d_ptr + 8 + nbucket * 4); break; + case DT_STRTAB: strtab = reinterpret_cast(load_bias + d->d_un.d_ptr); break; + case DT_STRSZ: strtab_size = d->d_un.d_val; break; + case DT_SYMTAB: symtab = reinterpret_cast(load_bias + d->d_un.d_ptr); break; + case DT_SYMENT: if (d->d_un.d_val != sizeof(ElfW(Sym))) { DL_ERR("invalid DT_SYMENT: %zd", static_cast(d->d_un.d_val)); return false; } break; + case DT_PLTREL: #if defined(USE_RELA) if (d->d_un.d_val != DT_RELA) { @@ -1949,6 +1955,7 @@ bool soinfo::PrelinkImage() { } #endif break; + case DT_JMPREL: #if defined(USE_RELA) plt_rela = reinterpret_cast(load_bias + d->d_un.d_ptr); @@ -1956,6 +1963,7 @@ bool soinfo::PrelinkImage() { plt_rel = reinterpret_cast(load_bias + d->d_un.d_ptr); #endif break; + case DT_PLTRELSZ: #if defined(USE_RELA) plt_rela_count = d->d_un.d_val / sizeof(ElfW(Rela)); @@ -1963,6 +1971,7 @@ bool soinfo::PrelinkImage() { plt_rel_count = d->d_un.d_val / sizeof(ElfW(Rel)); #endif break; + case DT_PLTGOT: #if defined(__mips__) // Used by mips and mips64. @@ -1970,6 +1979,7 @@ bool soinfo::PrelinkImage() { #endif // Ignore for other platforms... (because RTLD_LAZY is not supported) break; + case DT_DEBUG: // Set the DT_DEBUG entry to the address of _r_debug for GDB // if the dynamic table is writable @@ -1987,21 +1997,26 @@ bool soinfo::PrelinkImage() { case DT_RELA: rela = reinterpret_cast(load_bias + d->d_un.d_ptr); break; + case DT_RELASZ: rela_count = d->d_un.d_val / sizeof(ElfW(Rela)); break; + case DT_RELAENT: if (d->d_un.d_val != sizeof(ElfW(Rela))) { DL_ERR("invalid DT_RELAENT: %zd", static_cast(d->d_un.d_val)); return false; } break; + + // ignored (see DT_RELCOUNT comments for details) case DT_RELACOUNT: - // ignored (see DT_RELCOUNT comments for details) break; + case DT_REL: DL_ERR("unsupported DT_REL in \"%s\"", name); return false; + case DT_RELSZ: DL_ERR("unsupported DT_RELSZ in \"%s\"", name); return false; @@ -2009,21 +2024,24 @@ bool soinfo::PrelinkImage() { case DT_REL: rel = reinterpret_cast(load_bias + d->d_un.d_ptr); break; + case DT_RELSZ: rel_count = d->d_un.d_val / sizeof(ElfW(Rel)); break; + case DT_RELENT: if (d->d_un.d_val != sizeof(ElfW(Rel))) { DL_ERR("invalid DT_RELENT: %zd", static_cast(d->d_un.d_val)); return false; } break; + + // "Indicates that all RELATIVE relocations have been concatenated together, + // and specifies the RELATIVE relocation count." + // + // TODO: Spec also mentions that this can be used to optimize relocation process; + // Not currently used by bionic linker - ignored. case DT_RELCOUNT: - // "Indicates that all RELATIVE relocations have been concatenated together, - // and specifies the RELATIVE relocation count." - // - // TODO: Spec also mentions that this can be used to optimize relocation process; - // Not currently used by bionic linker - ignored. break; case DT_RELA: DL_ERR("unsupported DT_RELA in \"%s\"", name); @@ -2033,31 +2051,39 @@ bool soinfo::PrelinkImage() { init_func = reinterpret_cast(load_bias + d->d_un.d_ptr); DEBUG("%s constructors (DT_INIT) found at %p", name, init_func); break; + case DT_FINI: fini_func = reinterpret_cast(load_bias + d->d_un.d_ptr); DEBUG("%s destructors (DT_FINI) found at %p", name, fini_func); break; + case DT_INIT_ARRAY: init_array = reinterpret_cast(load_bias + d->d_un.d_ptr); DEBUG("%s constructors (DT_INIT_ARRAY) found at %p", name, init_array); break; + case DT_INIT_ARRAYSZ: init_array_count = ((unsigned)d->d_un.d_val) / sizeof(ElfW(Addr)); break; + case DT_FINI_ARRAY: fini_array = reinterpret_cast(load_bias + d->d_un.d_ptr); DEBUG("%s destructors (DT_FINI_ARRAY) found at %p", name, fini_array); break; + case DT_FINI_ARRAYSZ: fini_array_count = ((unsigned)d->d_un.d_val) / sizeof(ElfW(Addr)); break; + case DT_PREINIT_ARRAY: preinit_array = reinterpret_cast(load_bias + d->d_un.d_ptr); DEBUG("%s constructors (DT_PREINIT_ARRAY) found at %p", name, preinit_array); break; + case DT_PREINIT_ARRAYSZ: preinit_array_count = ((unsigned)d->d_un.d_val) / sizeof(ElfW(Addr)); break; + case DT_TEXTREL: #if defined(__LP64__) DL_ERR("text relocations (DT_TEXTREL) found in 64-bit ELF file \"%s\"", name); @@ -2066,12 +2092,15 @@ bool soinfo::PrelinkImage() { has_text_relocations = true; break; #endif + case DT_SYMBOLIC: has_DT_SYMBOLIC = true; break; + case DT_NEEDED: ++needed_count; break; + case DT_FLAGS: if (d->d_un.d_val & DF_TEXTREL) { #if defined(__LP64__) @@ -2085,6 +2114,7 @@ bool soinfo::PrelinkImage() { has_DT_SYMBOLIC = true; } break; + case DT_FLAGS_1: if ((d->d_un.d_val & DF_1_GLOBAL) != 0) { rtld_flags |= RTLD_GLOBAL; @@ -2107,6 +2137,7 @@ bool soinfo::PrelinkImage() { *dp = &_r_debug; } break; + case DT_MIPS_RLD_VERSION: case DT_MIPS_FLAGS: case DT_MIPS_BASE_ADDRESS: @@ -2125,10 +2156,14 @@ bool soinfo::PrelinkImage() { mips_gotsym = d->d_un.d_val; break; #endif + // Ignored: "Its use has been superseded by the DF_BIND_NOW flag" + case DT_BIND_NOW: + break; + + // Ignore: bionic does not support symbol versioning... case DT_VERSYM: case DT_VERDEF: case DT_VERDEFNUM: - // Ignore: bionic does not support symbol versioning... break; default: From 382e06ce8eab506276aaad39da3fbd533ef898d2 Mon Sep 17 00:00:00 2001 From: Dmitriy Ivanov Date: Thu, 30 Oct 2014 23:42:45 -0700 Subject: [PATCH 14/20] Add dlfcn_test to glibc test suite. Bug: 18186310 (cherry picked from commit eb27bbae8f0edc6b62ca2db73256c7fb53b9e9bf) Change-Id: I1d608dfa12dbafbdcdb8bc6d818c5872404c19e0 --- tests/Android.mk | 5 ++ tests/dlfcn_test.cpp | 11 ++- tests/libs/Android.build.testlib.mk | 22 +++++ tests/libs/Android.mk | 121 ++++++++++----------------- tests/libs/dlopen_testlib_simple.cpp | 1 + 5 files changed, 81 insertions(+), 79 deletions(-) create mode 100644 tests/libs/Android.build.testlib.mk diff --git a/tests/Android.mk b/tests/Android.mk index 407f21bc5..f20eb7d82 100644 --- a/tests/Android.mk +++ b/tests/Android.mk @@ -283,6 +283,7 @@ ifeq ($(HOST_OS)-$(HOST_ARCH),$(filter $(HOST_OS)-$(HOST_ARCH),linux-x86 linux-x bionic-unit-tests-glibc_src_files := \ atexit_test.cpp \ + dlfcn_test.cpp \ bionic-unit-tests-glibc_whole_static_libraries := \ libBionicStandardTests \ @@ -290,8 +291,12 @@ bionic-unit-tests-glibc_whole_static_libraries := \ bionic-unit-tests-glibc_ldlibs := \ -lrt -ldl \ +bionic-unit-tests-glibc_c_includes := \ + bionic/libc \ + bionic-unit-tests-glibc_cflags := $(test_cflags) bionic-unit-tests-glibc_cppflags := $(test_cppflags) +bionic-unit-tests-glibc_ldflags := -Wl,--export-dynamic module := bionic-unit-tests-glibc module_tag := optional diff --git a/tests/dlfcn_test.cpp b/tests/dlfcn_test.cpp index e7787b4a4..f1ec0f131 100644 --- a/tests/dlfcn_test.cpp +++ b/tests/dlfcn_test.cpp @@ -188,14 +188,14 @@ TEST(dlfcn, dlopen_check_order) { // get_answer2() is defined in (b, d) void* sym = dlsym(RTLD_DEFAULT, "dlopen_test_get_answer"); ASSERT_TRUE(sym == nullptr); - void* handle = dlopen("libtest_check_order.so", RTLD_NOW); + void* handle = dlopen("libtest_check_order.so", RTLD_NOW | RTLD_GLOBAL); ASSERT_TRUE(handle != nullptr); typedef int (*fn_t) (void); fn_t fn, fn2; fn = reinterpret_cast(dlsym(RTLD_DEFAULT, "dlopen_test_get_answer")); - ASSERT_TRUE(fn != NULL); + ASSERT_TRUE(fn != NULL) << dlerror(); fn2 = reinterpret_cast(dlsym(RTLD_DEFAULT, "dlopen_test_get_answer2")); - ASSERT_TRUE(fn2 != NULL); + ASSERT_TRUE(fn2 != NULL) << dlerror(); ASSERT_EQ(42, fn()); ASSERT_EQ(43, fn2()); @@ -248,6 +248,7 @@ TEST(dlfcn, dlopen_check_rtld_global) { // libtest_with_dependency_loop_a.so TEST(dlfcn, dlopen_check_loop) { void* handle = dlopen("libtest_with_dependency_loop.so", RTLD_NOW); +#if defined(__BIONIC__) ASSERT_TRUE(handle == nullptr); ASSERT_STREQ("dlopen failed: recursive link to \"libtest_with_dependency_loop_a.so\"", dlerror()); // This symbol should never be exposed @@ -261,6 +262,10 @@ TEST(dlfcn, dlopen_check_loop) { handle = dlopen("libtest_with_dependency_loop.so", RTLD_NOW | RTLD_NOLOAD); ASSERT_TRUE(handle == nullptr); ASSERT_STREQ("dlopen failed: library \"libtest_with_dependency_loop.so\" wasn't loaded and RTLD_NOLOAD prevented it", dlerror()); +#else // glibc allows recursive links + ASSERT_TRUE(handle != nullptr); + dlclose(handle); +#endif } TEST(dlfcn, dlopen_nodelete) { diff --git a/tests/libs/Android.build.testlib.mk b/tests/libs/Android.build.testlib.mk new file mode 100644 index 000000000..5b688e4d9 --- /dev/null +++ b/tests/libs/Android.build.testlib.mk @@ -0,0 +1,22 @@ +# +# Copyright (C) 2014 The Android Open Source Project +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +build_target := SHARED_LIBRARY +build_type := host +include $(TEST_PATH)/Android.build.mk +build_type := target +include $(TEST_PATH)/Android.build.mk + diff --git a/tests/libs/Android.mk b/tests/libs/Android.mk index b7335d59e..8746ff298 100644 --- a/tests/libs/Android.mk +++ b/tests/libs/Android.mk @@ -29,9 +29,7 @@ no-elf-hash-table-library_ldflags := \ module := no-elf-hash-table-library module_tag := optional -build_type := target -build_target := SHARED_LIBRARY -include $(TEST_PATH)/Android.build.mk +include $(LOCAL_PATH)/Android.build.testlib.mk endif # ----------------------------------------------------------------------------- @@ -45,15 +43,13 @@ libdlext_test_ldflags := \ module := libdlext_test module_tag := optional -build_type := target -build_target := SHARED_LIBRARY -include $(TEST_PATH)/Android.build.mk +include $(LOCAL_PATH)/Android.build.testlib.mk # ----------------------------------------------------------------------------- # create symlink to libdlext_test.so for symlink test # ----------------------------------------------------------------------------- # Use = instead of := to defer the evaluation of $@ -$(LOCAL_INSTALLED_MODULE): PRIVATE_POST_INSTALL_CMD = \ +$(TARGET_OUT)/lib/libdlext_test.so: PRIVATE_POST_INSTALL_CMD = \ $(hide) cd $(dir $@) && ln -sf $(notdir $@) libdlext_test_v2.so ifneq ($(TARGET_2ND_ARCH),) @@ -62,6 +58,13 @@ $(TARGET_OUT)/lib64/libdlext_test.so: PRIVATE_POST_INSTALL_CMD = \ $(hide) cd $(dir $@) && ln -sf $(notdir $@) libdlext_test_v2.so endif +# host symlinks +$(HOST_OUT)/lib64/libdlext_test.so: PRIVATE_POST_INSTALL_CMD = \ + $(hide) cd $(dir $@) && ln -sf $(notdir $@) libdlext_test_v2.so + +$(HOST_OUT)/lib/libdlext_test.so: PRIVATE_POST_INSTALL_CMD = \ + $(hide) cd $(dir $@) && ln -sf $(notdir $@) libdlext_test_v2.so + # ----------------------------------------------------------------------------- # Library used by dlext tests - without GNU RELRO program header # ----------------------------------------------------------------------------- @@ -108,9 +111,7 @@ libtest_simple_src_files := \ dlopen_testlib_simple.cpp module := libtest_simple -build_type := target -build_target := SHARED_LIBRARY -include $(TEST_PATH)/Android.build.mk +include $(LOCAL_PATH)/Android.build.testlib.mk # ----------------------------------------------------------------------------- # Library used by dlfcn nodelete tests @@ -150,9 +151,7 @@ libtest_check_order_2_right_src_files := \ libtest_check_order_2_right_cflags := -D__ANSWER=42 module := libtest_check_order_2_right -build_type := target -build_target := SHARED_LIBRARY -include $(TEST_PATH)/Android.build.mk +include $(LOCAL_PATH)/Android.build.testlib.mk # ----------------------------------------------------------------------------- # libtest_check_order_a.so @@ -162,9 +161,7 @@ libtest_check_order_a_src_files := \ libtest_check_order_a_cflags := -D__ANSWER=1 module := libtest_check_order_a -build_type := target -build_target := SHARED_LIBRARY -include $(TEST_PATH)/Android.build.mk +include $(LOCAL_PATH)/Android.build.testlib.mk # ----------------------------------------------------------------------------- # libtest_check_order_b.so @@ -174,9 +171,7 @@ libtest_check_order_b_src_files := \ libtest_check_order_b_cflags := -D__ANSWER=2 -D__ANSWER2=43 module := libtest_check_order_b -build_type := target -build_target := SHARED_LIBRARY -include $(TEST_PATH)/Android.build.mk +include $(LOCAL_PATH)/Android.build.testlib.mk # ----------------------------------------------------------------------------- # libtest_check_order_c.so @@ -186,9 +181,7 @@ libtest_check_order_3_c_src_files := \ libtest_check_order_3_c_cflags := -D__ANSWER=3 module := libtest_check_order_3_c -build_type := target -build_target := SHARED_LIBRARY -include $(TEST_PATH)/Android.build.mk +include $(LOCAL_PATH)/Android.build.testlib.mk # ----------------------------------------------------------------------------- # libtest_check_order_d.so @@ -199,9 +192,7 @@ libtest_check_order_d_src_files := \ libtest_check_order_d_shared_libraries := libtest_check_order_b libtest_check_order_d_cflags := -D__ANSWER=4 -D__ANSWER2=4 module := libtest_check_order_d -build_type := target -build_target := SHARED_LIBRARY -include $(TEST_PATH)/Android.build.mk +include $(LOCAL_PATH)/Android.build.testlib.mk # ----------------------------------------------------------------------------- # libtest_check_order_left.so @@ -212,9 +203,7 @@ libtest_check_order_1_left_src_files := \ libtest_check_order_1_left_shared_libraries := libtest_check_order_a libtest_check_order_b module := libtest_check_order_1_left -build_type := target -build_target := SHARED_LIBRARY -include $(TEST_PATH)/Android.build.mk +include $(LOCAL_PATH)/Android.build.testlib.mk # ----------------------------------------------------------------------------- # libtest_check_order.so @@ -226,9 +215,7 @@ libtest_check_order_shared_libraries := libtest_check_order_1_left \ libtest_check_order_2_right libtest_check_order_3_c module := libtest_check_order -build_type := target -build_target := SHARED_LIBRARY -include $(TEST_PATH)/Android.build.mk +include $(LOCAL_PATH)/Android.build.testlib.mk # ----------------------------------------------------------------------------- # Library with dependency loop used by dlfcn tests @@ -241,9 +228,7 @@ libtest_with_dependency_loop_shared_libraries := \ libtest_with_dependency_loop_a module := libtest_with_dependency_loop -build_type := target -build_target := SHARED_LIBRARY -include $(TEST_PATH)/Android.build.mk +include $(LOCAL_PATH)/Android.build.testlib.mk # ----------------------------------------------------------------------------- # libtest_with_dependency_loop_a.so @@ -254,9 +239,7 @@ libtest_with_dependency_loop_a_shared_libraries := \ libtest_with_dependency_loop_b_tmp module := libtest_with_dependency_loop_a -build_type := target -build_target := SHARED_LIBRARY -include $(TEST_PATH)/Android.build.mk +include $(LOCAL_PATH)/Android.build.testlib.mk # ----------------------------------------------------------------------------- # libtest_with_dependency_loop_b.so @@ -267,9 +250,7 @@ libtest_with_dependency_loop_b_tmp_src_files := dlopen_testlib_invalid.cpp libtest_with_dependency_loop_b_tmp_ldflags := -Wl,-soname=libtest_with_dependency_loop_b.so module := libtest_with_dependency_loop_b_tmp -build_type := target -build_target := SHARED_LIBRARY -include $(TEST_PATH)/Android.build.mk +include $(LOCAL_PATH)/Android.build.testlib.mk # ----------------------------------------------------------------------------- # libtest_with_dependency_loop_b.so @@ -278,9 +259,7 @@ libtest_with_dependency_loop_b_src_files := dlopen_testlib_invalid.cpp libtest_with_dependency_loop_b_shared_libraries := libtest_with_dependency_loop_c module := libtest_with_dependency_loop_b -build_type := target -build_target := SHARED_LIBRARY -include $(TEST_PATH)/Android.build.mk +include $(LOCAL_PATH)/Android.build.testlib.mk # ----------------------------------------------------------------------------- # libtest_with_dependency_loop_c.so @@ -291,9 +270,7 @@ libtest_with_dependency_loop_c_shared_libraries := \ libtest_with_dependency_loop_a module := libtest_with_dependency_loop_c -build_type := target -build_target := SHARED_LIBRARY -include $(TEST_PATH)/Android.build.mk +include $(LOCAL_PATH)/Android.build.testlib.mk # ----------------------------------------------------------------------------- # libtest_relo_check_dt_needed_order.so @@ -308,15 +285,13 @@ libtest_relo_check_dt_needed_order_shared_libraries := \ libtest_relo_check_dt_needed_order_src_files := dlopen_testlib_relo_check_dt_needed_order.cpp libtest_relo_check_dt_needed_order_1_src_files := dlopen_testlib_relo_check_dt_needed_order_1.cpp libtest_relo_check_dt_needed_order_2_src_files := dlopen_testlib_relo_check_dt_needed_order_2.cpp -build_type := target -build_target := SHARED_LIBRARY module := libtest_relo_check_dt_needed_order -include $(TEST_PATH)/Android.build.mk +include $(LOCAL_PATH)/Android.build.testlib.mk module := libtest_relo_check_dt_needed_order_1 -include $(TEST_PATH)/Android.build.mk +include $(LOCAL_PATH)/Android.build.testlib.mk module := libtest_relo_check_dt_needed_order_2 -include $(TEST_PATH)/Android.build.mk +include $(LOCAL_PATH)/Android.build.testlib.mk # ----------------------------------------------------------------------------- # Library with dependency used by dlfcn tests @@ -327,22 +302,30 @@ libtest_with_dependency_src_files := \ libtest_with_dependency_shared_libraries := libdlext_test module := libtest_with_dependency -build_type := target -build_target := SHARED_LIBRARY -include $(TEST_PATH)/Android.build.mk +include $(LOCAL_PATH)/Android.build.testlib.mk # ----------------------------------------------------------------------------- # Library used by ifunc tests # ----------------------------------------------------------------------------- +libtest_ifunc_src_files := \ + dlopen_testlib_ifunc.c + +libtest_ifunc_clang_host := false +module := libtest_ifunc +build_target := SHARED_LIBRARY + +build_type := host +include $(TEST_PATH)/Android.build.mk + ifeq ($(TARGET_ARCH),$(filter $(TARGET_ARCH),x86 x86_64)) - libtest_ifunc_src_files := \ - dlopen_testlib_ifunc.c + ifeq ($(TARGET_ARCH),arm64) + libtest_ifunc_multilib := 64 + # TODO: This is a workaround - remove it once gcc + # removes its Android ifunc checks + libtest_ifunc_cflags := -mglibc + endif - LOCAL_SDK_VERSION := current - module := libtest_ifunc build_type := target - build_target := SHARED_LIBRARY - include $(TEST_PATH)/Android.build.mk endif @@ -354,11 +337,7 @@ libtest_atexit_src_files := \ atexit_testlib.cpp module := libtest_atexit -build_target := SHARED_LIBRARY -build_type := target -include $(TEST_PATH)/Android.build.mk -build_type := host -include $(TEST_PATH)/Android.build.mk +include $(LOCAL_PATH)/Android.build.testlib.mk # ----------------------------------------------------------------------------- # Library with weak function @@ -367,14 +346,4 @@ libtest_dlsym_weak_func_src_files := \ dlsym_weak_function.cpp module := libtest_dlsym_weak_func -build_target := SHARED_LIBRARY -build_type := target -include $(TEST_PATH)/Android.build.mk -build_type := host -include $(TEST_PATH)/Android.build.mk - -LOCAL_ADDITIONAL_DEPENDENCIES := \ - $(LOCAL_PATH)/Android.mk \ - $(LOCAL_PATH)/Android.build.dlext_testzip.mk \ - $(LOCAL_PATH)/Android.build.testlib.mk \ - $(TEST_PATH)/Android.build.mk +include $(LOCAL_PATH)/Android.build.testlib.mk diff --git a/tests/libs/dlopen_testlib_simple.cpp b/tests/libs/dlopen_testlib_simple.cpp index 06253e1f4..32269557a 100644 --- a/tests/libs/dlopen_testlib_simple.cpp +++ b/tests/libs/dlopen_testlib_simple.cpp @@ -14,6 +14,7 @@ * limitations under the License. */ +#include #include uint32_t dlopen_testlib_taxicab_number = 1729; From 4d0c1f673f8a22f5415b9a879e4544f6bcfe419c Mon Sep 17 00:00:00 2001 From: Dmitriy Ivanov Date: Fri, 17 Oct 2014 11:47:18 -0700 Subject: [PATCH 15/20] Correct way to specify additional dependencies Previous one was not covering all the targets Bug: 17548097 Bug: 18186310 (cherry picked from commit 4a9e1937c56511aef579312bf39ab345f9179230) Change-Id: I2cd9e58893555d16cbfe291b2d1279621489d5ad --- tests/Android.build.mk | 1 + tests/Android.mk | 2 ++ tests/libs/Android.mk | 7 +++++++ 3 files changed, 10 insertions(+) diff --git a/tests/Android.build.mk b/tests/Android.build.mk index d54c851b2..63729dace 100644 --- a/tests/Android.build.mk +++ b/tests/Android.build.mk @@ -15,6 +15,7 @@ # include $(CLEAR_VARS) +LOCAL_ADDITIONAL_DEPENDENCIES := $(common_additional_dependencies) LOCAL_MODULE := $(module) LOCAL_MODULE_TAGS := $(module_tag) diff --git a/tests/Android.mk b/tests/Android.mk index f20eb7d82..8b0b0a0e0 100644 --- a/tests/Android.mk +++ b/tests/Android.mk @@ -28,6 +28,8 @@ else build_host := false endif +common_additional_dependencies := $(LOCAL_PATH)/Android.mk $(LOCAL_PATH)/Android.build.mk + # ----------------------------------------------------------------------------- # All standard tests. # ----------------------------------------------------------------------------- diff --git a/tests/libs/Android.mk b/tests/libs/Android.mk index 8746ff298..175a63539 100644 --- a/tests/libs/Android.mk +++ b/tests/libs/Android.mk @@ -17,6 +17,13 @@ LOCAL_PATH := $(call my-dir) TEST_PATH := $(LOCAL_PATH)/.. +common_cppflags += -std=gnu++11 +common_additional_dependencies := \ + $(LOCAL_PATH)/Android.mk \ + $(LOCAL_PATH)/Android.build.dlext_testzip.mk \ + $(LOCAL_PATH)/Android.build.testlib.mk \ + $(TEST_PATH)/Android.build.mk + # ----------------------------------------------------------------------------- # Library used by dlfcn tests. # ----------------------------------------------------------------------------- From fd2747bb585fc51b5ad56db09c0e9b66c7091a92 Mon Sep 17 00:00:00 2001 From: Dmitriy Ivanov Date: Tue, 21 Oct 2014 09:23:18 -0700 Subject: [PATCH 16/20] Fix relocation to look for symbols in local group The local group is a sequence of libraries in default (breadth-first) order. It allows RTLD_LOCALLY loaded library to correctly relocate symbols within its group (see test-cases). Local group lookup is performed after main executable and ld_preloads. Bug: 2643900 Bug: 15432753 Bug: 18186310 (cherry picked from commit cfa97f172dc1b10d650fefbb6ccffd88ce72a5fb) Change-Id: I5fa8c673f929e4652c738912c7ae078d7ec286d2 --- linker/linked_list.h | 4 +- linker/linker.cpp | 193 +++++++++++------- linker/linker.h | 6 +- tests/dlfcn_test.cpp | 186 +++++++++++++++-- .../Android.build.dlopen_check_order_dlsym.mk | 90 ++++++++ ...lopen_check_order_reloc_main_executable.mk | 56 +++++ ...build.dlopen_check_order_reloc_siblings.mk | 133 ++++++++++++ tests/libs/Android.mk | 75 +------ ...pp => dlopen_check_order_dlsym_answer.cpp} | 4 +- .../libs/dlopen_check_order_reloc_answer.cpp | 23 +++ .../dlopen_check_order_reloc_answer_impl.cpp | 19 ++ ...dlopen_check_order_reloc_nephew_answer.cpp | 21 ++ .../dlopen_check_order_reloc_root_answer.cpp | 21 ++ ...pen_check_order_reloc_root_answer_impl.cpp | 19 ++ 14 files changed, 688 insertions(+), 162 deletions(-) create mode 100644 tests/libs/Android.build.dlopen_check_order_dlsym.mk create mode 100644 tests/libs/Android.build.dlopen_check_order_reloc_main_executable.mk create mode 100644 tests/libs/Android.build.dlopen_check_order_reloc_siblings.mk rename tests/libs/{dlopen_testlib_answer.cpp => dlopen_check_order_dlsym_answer.cpp} (87%) create mode 100644 tests/libs/dlopen_check_order_reloc_answer.cpp create mode 100644 tests/libs/dlopen_check_order_reloc_answer_impl.cpp create mode 100644 tests/libs/dlopen_check_order_reloc_nephew_answer.cpp create mode 100644 tests/libs/dlopen_check_order_reloc_root_answer.cpp create mode 100644 tests/libs/dlopen_check_order_reloc_root_answer_impl.cpp diff --git a/linker/linked_list.h b/linker/linked_list.h index 4e62e208f..72a32b4ba 100644 --- a/linker/linked_list.h +++ b/linker/linked_list.h @@ -86,7 +86,7 @@ class LinkedList { } template - void for_each(F action) { + void for_each(F action) const { visit([&] (T* si) { action(si); return true; @@ -94,7 +94,7 @@ class LinkedList { } template - bool visit(F action) { + bool visit(F action) const { for (LinkedListEntry* e = head_; e != nullptr; e = e->next) { if (!action(e->element)) { return false; diff --git a/linker/linker.cpp b/linker/linker.cpp index 41557e231..eb1a483ae 100644 --- a/linker/linker.cpp +++ b/linker/linker.cpp @@ -415,7 +415,7 @@ int dl_iterate_phdr(int (*cb)(dl_phdr_info* info, size_t size, void* data), void return rv; } -static ElfW(Sym)* soinfo_elf_lookup(soinfo* si, unsigned hash, const char* name) { +static ElfW(Sym)* soinfo_elf_lookup(const soinfo* si, unsigned hash, const char* name) { ElfW(Sym)* symtab = si->symtab; TRACE_TYPE(LOOKUP, "SEARCH %s in %s@%p %x %zd", @@ -481,7 +481,7 @@ static unsigned elfhash(const char* _name) { return h; } -static ElfW(Sym)* soinfo_do_lookup(soinfo* si, const char* name, soinfo** lsi) { +static ElfW(Sym)* soinfo_do_lookup(soinfo* si, const char* name, soinfo** lsi, const soinfo::soinfo_list_t& local_group) { unsigned elf_hash = elfhash(name); ElfW(Sym)* s = nullptr; @@ -527,16 +527,21 @@ static ElfW(Sym)* soinfo_do_lookup(soinfo* si, const char* name, soinfo** lsi) { } } - /* Look for symbols in the local scope (the object who is - * searching). This happens with C++ templates on x86 for some - * reason. - * - * Notes on weak symbols: - * The ELF specs are ambiguous about treatment of weak definitions in - * dynamic linking. Some systems return the first definition found - * and some the first non-weak definition. This is system dependent. - * Here we return the first definition found for simplicity. */ + // 3. Look for it in the local group + if (s == nullptr) { + local_group.visit([&](soinfo* local_si) { + DEBUG("%s: looking up %s in %s (from local group)", si->name, name, local_si->name); + s = soinfo_elf_lookup(local_si, elf_hash, name); + if (s != nullptr) { + *lsi = local_si; + return false; + } + return true; + }); + } + + // 4. Look for it in this library (unless we already did it because of DT_SYMBOLIC) if (s == nullptr && !si->has_DT_SYMBOLIC) { DEBUG("%s: looking up %s in local scope", si->name, name); s = soinfo_elf_lookup(si, elf_hash, name); @@ -545,6 +550,7 @@ static ElfW(Sym)* soinfo_do_lookup(soinfo* si, const char* name, soinfo** lsi) { } } + // 5. Dependencies if (s == nullptr) { si->get_children().visit([&](soinfo* child) { DEBUG("%s: looking up %s in %s", si->name, name, child->name); @@ -643,33 +649,61 @@ typedef linked_list_t StringLinkedList; typedef linked_list_t LoadTaskList; -// This is used by dlsym(3). It performs symbol lookup only within the -// specified soinfo object and its dependencies in breadth first order. -ElfW(Sym)* dlsym_handle_lookup(soinfo* si, soinfo** found, const char* name) { +// This function walks down the tree of soinfo dependencies +// in breadth-first order and +// * calls action(soinfo* si) for each node, and +// * terminates walk if action returns false. +// +// walk_dependencies_tree returns false if walk was terminated +// by the action and true otherwise. +template +static bool walk_dependencies_tree(soinfo* root_soinfos[], size_t root_soinfos_size, F action) { SoinfoLinkedList visit_list; SoinfoLinkedList visited; - visit_list.push_back(si); - soinfo* current_soinfo; - while ((current_soinfo = visit_list.pop_front()) != nullptr) { - if (visited.contains(current_soinfo)) { + for (size_t i = 0; i < root_soinfos_size; ++i) { + visit_list.push_back(root_soinfos[i]); + } + + soinfo* si; + while ((si = visit_list.pop_front()) != nullptr) { + if (visited.contains(si)) { continue; } - ElfW(Sym)* result = soinfo_elf_lookup(current_soinfo, elfhash(name), name); - - if (result != nullptr) { - *found = current_soinfo; - return result; + if (!action(si)) { + return false; } - visited.push_back(current_soinfo); - current_soinfo->get_children().for_each([&](soinfo* child) { + visited.push_back(si); + + si->get_children().for_each([&](soinfo* child) { visit_list.push_back(child); }); } - return nullptr; + return true; +} + + +// This is used by dlsym(3). It performs symbol lookup only within the +// specified soinfo object and its dependencies in breadth first order. +ElfW(Sym)* dlsym_handle_lookup(soinfo* si, soinfo** found, const char* name) { + ElfW(Sym)* result = nullptr; + uint32_t elf_hash = elfhash(name); + + + walk_dependencies_tree(&si, 1, [&](soinfo* current_soinfo) { + result = soinfo_elf_lookup(current_soinfo, elf_hash, name); + if (result != nullptr) { + *found = current_soinfo; + return false; + } + + return true; + }); + + return result; } /* This is used by dlsym(3) to performs a global symbol lookup. If the @@ -899,19 +933,30 @@ static bool is_recursive(soinfo* si, soinfo* parent) { }); } -static bool find_libraries(const char* const library_names[], size_t library_names_size, soinfo* soinfos[], - soinfo* ld_preloads[], size_t ld_preloads_size, int rtld_flags, const android_dlextinfo* extinfo) { +static bool find_libraries(soinfo* start_with, const char* const library_names[], size_t library_names_count, soinfo* soinfos[], + soinfo* ld_preloads[], size_t ld_preloads_count, int rtld_flags, const android_dlextinfo* extinfo) { // Step 0: prepare. LoadTaskList load_tasks; - for (size_t i = 0; i < library_names_size; ++i) { + for (size_t i = 0; i < library_names_count; ++i) { const char* name = library_names[i]; - load_tasks.push_back(LoadTask::create(name, nullptr)); + load_tasks.push_back(LoadTask::create(name, start_with)); } - // Libraries added to this list in reverse order so that we can - // start linking from bottom-up - see step 2. - SoinfoLinkedList found_libs; - size_t soinfos_size = 0; + // If soinfos array is null allocate one on stack. + // The array is needed in case of failure; for example + // when library_names[] = {libone.so, libtwo.so} and libone.so + // is loaded correctly but libtwo.so failed for some reason. + // In this case libone.so should be unloaded on return. + // See also implementation of failure_guard below. + + if (soinfos == nullptr) { + size_t soinfos_size = sizeof(soinfo*)*library_names_count; + soinfos = reinterpret_cast(alloca(soinfos_size)); + memset(soinfos, 0, soinfos_size); + } + + // list of libraries to link - see step 2. + size_t soinfos_count = 0; auto failure_guard = make_scope_guard([&]() { // Housekeeping @@ -919,7 +964,7 @@ static bool find_libraries(const char* const library_names[], size_t library_nam LoadTask::deleter(t); }); - for (size_t i = 0; iadd_child(si); } - found_libs.push_front(si); - // When ld_preloads is not null first - // ld_preloads_size libs are in fact ld_preloads. - if (ld_preloads != nullptr && soinfos_size < ld_preloads_size) { - ld_preloads[soinfos_size] = si; + // When ld_preloads is not null, the first + // ld_preloads_count libs are in fact ld_preloads. + if (ld_preloads != nullptr && soinfos_count < ld_preloads_count) { + ld_preloads[soinfos_count] = si; } - if (soinfos_sizeflags & FLAG_LINKED) == 0) { - if (!si->LinkImage(extinfo)) { + if (!si->LinkImage(local_group, extinfo)) { return false; } si->flags |= FLAG_LINKED; } + + return true; + }); + + if (linked) { + failure_guard.disable(); } - // All is well - found_libs and load_tasks are empty at this point - // and all libs are successfully linked. - failure_guard.disable(); - return true; + return linked; } static soinfo* find_library(const char* name, int rtld_flags, const android_dlextinfo* extinfo) { @@ -979,7 +1034,7 @@ static soinfo* find_library(const char* name, int rtld_flags, const android_dlex soinfo* si; - if (!find_libraries(&name, 1, &si, nullptr, 0, rtld_flags, extinfo)) { + if (!find_libraries(nullptr, &name, 1, &si, nullptr, 0, rtld_flags, extinfo)) { return nullptr; } @@ -1090,7 +1145,7 @@ static ElfW(Addr) call_ifunc_resolver(ElfW(Addr) resolver_addr) { } #if defined(USE_RELA) -int soinfo::Relocate(ElfW(Rela)* rela, unsigned count) { +int soinfo::Relocate(ElfW(Rela)* rela, unsigned count, const soinfo_list_t& local_group) { for (size_t idx = 0; idx < count; ++idx, ++rela) { unsigned type = ELFW(R_TYPE)(rela->r_info); unsigned sym = ELFW(R_SYM)(rela->r_info); @@ -1108,7 +1163,7 @@ int soinfo::Relocate(ElfW(Rela)* rela, unsigned count) { if (sym != 0) { sym_name = get_string(symtab[sym].st_name); - s = soinfo_do_lookup(this, sym_name, &lsi); + s = soinfo_do_lookup(this, sym_name, &lsi, local_group); if (s == nullptr) { // We only allow an undefined symbol if this is a weak reference... s = &symtab[sym]; @@ -1367,7 +1422,7 @@ int soinfo::Relocate(ElfW(Rela)* rela, unsigned count) { } #else // REL, not RELA. -int soinfo::Relocate(ElfW(Rel)* rel, unsigned count) { +int soinfo::Relocate(ElfW(Rel)* rel, unsigned count, const soinfo_list_t& local_group) { for (size_t idx = 0; idx < count; ++idx, ++rel) { unsigned type = ELFW(R_TYPE)(rel->r_info); // TODO: don't use unsigned for 'sym'. Use uint32_t or ElfW(Addr) instead. @@ -1386,7 +1441,7 @@ int soinfo::Relocate(ElfW(Rel)* rel, unsigned count) { if (sym != 0) { sym_name = get_string(symtab[sym].st_name); - s = soinfo_do_lookup(this, sym_name, &lsi); + s = soinfo_do_lookup(this, sym_name, &lsi, local_group); if (s == nullptr) { // We only allow an undefined symbol if this is a weak reference... s = &symtab[sym]; @@ -1572,7 +1627,7 @@ int soinfo::Relocate(ElfW(Rel)* rel, unsigned count) { #endif #if defined(__mips__) -static bool mips_relocate_got(soinfo* si) { +static bool mips_relocate_got(soinfo* si, const soinfo::soinfo_list_t& local_group) { ElfW(Addr)** got = si->plt_got; if (got == nullptr) { return true; @@ -1605,7 +1660,7 @@ static bool mips_relocate_got(soinfo* si) { // This is an undefined reference... try to locate it. const char* sym_name = si->get_string(sym->st_name); soinfo* lsi = nullptr; - ElfW(Sym)* s = soinfo_do_lookup(si, sym_name, &lsi); + ElfW(Sym)* s = soinfo_do_lookup(si, sym_name, &lsi, local_group); if (s == nullptr) { // We only allow an undefined symbol if this is a weak reference. s = &symtab[g]; @@ -2198,7 +2253,7 @@ bool soinfo::PrelinkImage() { return true; } -bool soinfo::LinkImage(const android_dlextinfo* extinfo) { +bool soinfo::LinkImage(const soinfo_list_t& local_group, const android_dlextinfo* extinfo) { #if !defined(__LP64__) if (has_text_relocations) { @@ -2217,26 +2272,26 @@ bool soinfo::LinkImage(const android_dlextinfo* extinfo) { #if defined(USE_RELA) if (rela != nullptr) { DEBUG("[ relocating %s ]", name); - if (Relocate(rela, rela_count)) { + if (Relocate(rela, rela_count, local_group)) { return false; } } if (plt_rela != nullptr) { DEBUG("[ relocating %s plt ]", name); - if (Relocate(plt_rela, plt_rela_count)) { + if (Relocate(plt_rela, plt_rela_count, local_group)) { return false; } } #else if (rel != nullptr) { DEBUG("[ relocating %s ]", name); - if (Relocate(rel, rel_count)) { + if (Relocate(rel, rel_count, local_group)) { return false; } } if (plt_rel != nullptr) { DEBUG("[ relocating %s plt ]", name); - if (Relocate(plt_rel, plt_rel_count)) { + if (Relocate(plt_rel, plt_rel_count, local_group)) { return false; } } @@ -2310,7 +2365,7 @@ static void add_vdso(KernelArgumentBlock& args __unused) { si->load_bias = get_elf_exec_load_bias(ehdr_vdso); si->PrelinkImage(); - si->LinkImage(nullptr); + si->LinkImage(g_empty_list, nullptr); #endif } @@ -2456,21 +2511,11 @@ static ElfW(Addr) __linker_init_post_relocation(KernelArgumentBlock& args, ElfW( }); const char* needed_library_names[needed_libraries_count]; - soinfo* needed_library_si[needed_libraries_count]; memset(needed_library_names, 0, sizeof(needed_library_names)); needed_library_name_list.copy_to_array(needed_library_names, needed_libraries_count); - if (needed_libraries_count > 0 && !find_libraries(needed_library_names, needed_libraries_count, needed_library_si, g_ld_preloads, ld_preloads_count, RTLD_GLOBAL, nullptr)) { - __libc_format_fd(2, "CANNOT LINK EXECUTABLE DEPENDENCIES: %s\n", linker_get_error_buffer()); - exit(EXIT_FAILURE); - } - - for (size_t i = 0; iadd_child(needed_library_si[i]); - } - - if (!si->LinkImage(nullptr)) { + if (needed_libraries_count > 0 && !find_libraries(si, needed_library_names, needed_libraries_count, nullptr, g_ld_preloads, ld_preloads_count, RTLD_GLOBAL, nullptr)) { __libc_format_fd(2, "CANNOT LINK EXECUTABLE: %s\n", linker_get_error_buffer()); exit(EXIT_FAILURE); } @@ -2594,7 +2639,7 @@ extern "C" ElfW(Addr) __linker_init(void* raw_args) { linker_so.phnum = elf_hdr->e_phnum; linker_so.flags |= FLAG_LINKER; - if (!(linker_so.PrelinkImage() && linker_so.LinkImage(nullptr))) { + if (!(linker_so.PrelinkImage() && linker_so.LinkImage(g_empty_list, nullptr))) { // It would be nice to print an error message, but if the linker // can't link itself, there's no guarantee that we'll be able to // call write() (because it involves a GOT reference). We may as diff --git a/linker/linker.h b/linker/linker.h index ebb4793af..222aca11e 100644 --- a/linker/linker.h +++ b/linker/linker.h @@ -207,7 +207,7 @@ struct soinfo { void CallDestructors(); void CallPreInitConstructors(); bool PrelinkImage(); - bool LinkImage(const android_dlextinfo* extinfo); + bool LinkImage(const soinfo_list_t& local_group, const android_dlextinfo* extinfo); void add_child(soinfo* child); void remove_all_links(); @@ -234,9 +234,9 @@ struct soinfo { void CallArray(const char* array_name, linker_function_t* functions, size_t count, bool reverse); void CallFunction(const char* function_name, linker_function_t function); #if defined(USE_RELA) - int Relocate(ElfW(Rela)* rela, unsigned count); + int Relocate(ElfW(Rela)* rela, unsigned count, const soinfo_list_t& local_group); #else - int Relocate(ElfW(Rel)* rel, unsigned count); + int Relocate(ElfW(Rel)* rel, unsigned count, const soinfo_list_t& local_group); #endif private: diff --git a/tests/dlfcn_test.cpp b/tests/dlfcn_test.cpp index f1ec0f131..e604f5abe 100644 --- a/tests/dlfcn_test.cpp +++ b/tests/dlfcn_test.cpp @@ -162,39 +162,39 @@ TEST(dlfcn, dlopen_check_relocation_dt_needed_order) { ASSERT_EQ(1, fn()); } -TEST(dlfcn, dlopen_check_order) { +TEST(dlfcn, dlopen_check_order_dlsym) { // Here is how the test library and its dt_needed // libraries are arranged // - // libtest_check_order.so + // libtest_check_order_children.so // | - // +-> libtest_check_order_1_left.so + // +-> ..._1_left.so // | | - // | +-> libtest_check_order_a.so + // | +-> ..._a.so // | | - // | +-> libtest_check_order_b.so + // | +-> ...r_b.so // | - // +-> libtest_check_order_2_right.so + // +-> ..._2_right.so // | | - // | +-> libtest_check_order_d.so + // | +-> ..._d.so // | | - // | +-> libtest_check_order_b.so + // | +-> ..._b.so // | - // +-> libtest_check_order_3_c.so + // +-> ..._3_c.so // // load order should be (1, 2, 3, a, b, d) // // get_answer() is defined in (2, 3, a, b, c) // get_answer2() is defined in (b, d) - void* sym = dlsym(RTLD_DEFAULT, "dlopen_test_get_answer"); + void* sym = dlsym(RTLD_DEFAULT, "check_order_dlsym_get_answer"); ASSERT_TRUE(sym == nullptr); - void* handle = dlopen("libtest_check_order.so", RTLD_NOW | RTLD_GLOBAL); - ASSERT_TRUE(handle != nullptr); + void* handle = dlopen("libtest_check_order_dlsym.so", RTLD_NOW | RTLD_GLOBAL); + ASSERT_TRUE(handle != nullptr) << dlerror(); typedef int (*fn_t) (void); fn_t fn, fn2; - fn = reinterpret_cast(dlsym(RTLD_DEFAULT, "dlopen_test_get_answer")); + fn = reinterpret_cast(dlsym(RTLD_DEFAULT, "check_order_dlsym_get_answer")); ASSERT_TRUE(fn != NULL) << dlerror(); - fn2 = reinterpret_cast(dlsym(RTLD_DEFAULT, "dlopen_test_get_answer2")); + fn2 = reinterpret_cast(dlsym(RTLD_DEFAULT, "check_order_dlsym_get_answer2")); ASSERT_TRUE(fn2 != NULL) << dlerror(); ASSERT_EQ(42, fn()); @@ -202,6 +202,163 @@ TEST(dlfcn, dlopen_check_order) { dlclose(handle); } +TEST(dlfcn, dlopen_check_order_reloc_siblings) { + // This is how this one works: + // we lookup and call get_answer which is defined in '_2.so' + // and in turn calls external get_answer_impl() defined in _1.so and in '_[a-f].so' + // the correct _impl() is implemented by '_a.so'; + // + // Note that this is test for RTLD_LOCAL (TODO: test for GLOBAL?) + // + // Here is the picture: + // + // libtest_check_order_reloc_siblings.so + // | + // +-> ..._1.so <- empty + // | | + // | +-> ..._a.so <- exports correct answer_impl() + // | | + // | +-> ..._b.so <- every other letter exporting incorrect one. + // | + // +-> ..._2.so <- empty + // | | + // | +-> ..._c.so + // | | + // | +-> ..._d.so + // | + // +-> ..._3.so <- empty + // | + // +-> ..._e.so + // | + // +-> ..._f.so <- exports get_answer() that calls get_anser_impl(); + // implements incorrect get_answer_impl() + + void* handle = dlopen("libtest_check_order_reloc_siblings.so", RTLD_NOW | RTLD_NOLOAD); + ASSERT_TRUE(handle == nullptr); +#ifdef __BIONIC__ + // TODO: glibc returns nullptr on dlerror() here. Is it bug? + ASSERT_STREQ("dlopen failed: library \"libtest_check_order_reloc_siblings.so\" wasn't loaded and RTLD_NOLOAD prevented it", dlerror()); +#endif + + handle = dlopen("libtest_check_order_reloc_siblings.so", RTLD_NOW | RTLD_LOCAL); + ASSERT_TRUE(handle != nullptr) << dlerror(); + + typedef int (*fn_t) (void); + fn_t fn = reinterpret_cast(dlsym(handle, "check_order_reloc_get_answer")); + ASSERT_TRUE(fn != nullptr) << dlerror(); + ASSERT_EQ(42, fn()); + + ASSERT_EQ(0, dlclose(handle)); +} + +TEST(dlfcn, dlopen_check_order_reloc_siblings_with_preload) { + // This test uses the same library as dlopen_check_order_reloc_siblings. + // Unlike dlopen_check_order_reloc_siblings it preloads + // libtest_check_order_reloc_siblings_1.so (first dependency) prior to + // dlopen(libtest_check_order_reloc_siblings.so) + + void* handle = dlopen("libtest_check_order_reloc_siblings.so", RTLD_NOW | RTLD_NOLOAD); + ASSERT_TRUE(handle == nullptr); + handle = dlopen("libtest_check_order_reloc_siblings_1.so", RTLD_NOW | RTLD_NOLOAD); + ASSERT_TRUE(handle == nullptr); + + void* handle_for_1 = dlopen("libtest_check_order_reloc_siblings_1.so", RTLD_NOW | RTLD_LOCAL); + ASSERT_TRUE(handle_for_1 != nullptr) << dlerror(); + + handle = dlopen("libtest_check_order_reloc_siblings.so", RTLD_NOW | RTLD_LOCAL); + ASSERT_TRUE(handle != nullptr) << dlerror(); + + ASSERT_EQ(0, dlclose(handle_for_1)); + + typedef int (*fn_t) (void); + fn_t fn = reinterpret_cast(dlsym(handle, "check_order_reloc_get_answer")); + ASSERT_TRUE(fn != nullptr) << dlerror(); + ASSERT_EQ(42, fn()); + + ASSERT_EQ(0, dlclose(handle)); +} + +TEST(dlfcn, dlopen_check_order_reloc_nephew) { + // This is how this one works: + // we lookup and call nephew_get_answer which is defined in '_2.so' + // and in turn calls external get_answer_impl() defined in '_[a-f].so' + // the correct _impl() is implemented by '_a.so'; + // + // Here is the picture: + // + // libtest_check_order_reloc_siblings.so + // | + // +-> ..._1.so <- empty + // | | + // | +-> ..._a.so <- exports correct answer_impl() + // | | + // | +-> ..._b.so <- every other letter exporting incorrect one. + // | + // +-> ..._2.so <- empty + // | | + // | +-> ..._c.so + // | | + // | +-> ..._d.so + // | + // +-> ..._3.so <- nephew_get_answer() that calls get_answer_impl(); + // | + // +-> ..._e.so + // | + // +-> ..._f.so + + void* handle = dlopen("libtest_check_order_reloc_siblings.so", RTLD_NOW | RTLD_NOLOAD); + ASSERT_TRUE(handle == nullptr); +#ifdef __BIONIC__ + // TODO: glibc returns nullptr on dlerror() here. Is it bug? + ASSERT_STREQ("dlopen failed: library \"libtest_check_order_reloc_siblings.so\" wasn't loaded and RTLD_NOLOAD prevented it", dlerror()); +#endif + + handle = dlopen("libtest_check_order_reloc_siblings.so", RTLD_NOW | RTLD_LOCAL); + ASSERT_TRUE(handle != nullptr) << dlerror(); + + typedef int (*fn_t) (void); + fn_t fn = reinterpret_cast(dlsym(handle, "check_order_reloc_nephew_get_answer")); + ASSERT_TRUE(fn != nullptr) << dlerror(); + ASSERT_EQ(42, fn()); + + ASSERT_EQ(0, dlclose(handle)); +} + +extern "C" int check_order_reloc_root_get_answer_impl() { + return 42; +} + +TEST(dlfcn, dlopen_check_order_reloc_main_executable) { + // This is how this one works: + // we lookup and call get_answer3 which is defined in 'root.so' + // and in turn calls external root_get_answer_impl() defined in _2.so and + // above the correct _impl() is one in the executable. + // + // libtest_check_order_reloc_root.so + // | + // +-> ..._1.so <- empty + // | + // +-> ..._2.so <- gives incorrect answer for answer_main_impl() + // + + void* handle = dlopen("libtest_check_order_reloc_root.so", RTLD_NOW | RTLD_NOLOAD); + ASSERT_TRUE(handle == nullptr); +#ifdef __BIONIC__ + // TODO: glibc returns nullptr on dlerror() here. Is it bug? + ASSERT_STREQ("dlopen failed: library \"libtest_check_order_reloc_root.so\" wasn't loaded and RTLD_NOLOAD prevented it", dlerror()); +#endif + + handle = dlopen("libtest_check_order_reloc_root.so", RTLD_NOW | RTLD_LOCAL); + ASSERT_TRUE(handle != nullptr) << dlerror(); + + typedef int (*fn_t) (void); + fn_t fn = reinterpret_cast(dlsym(handle, "check_order_reloc_root_get_answer")); + ASSERT_TRUE(fn != nullptr) << dlerror(); + ASSERT_EQ(42, fn()); + + ASSERT_EQ(0, dlclose(handle)); +} + TEST(dlfcn, dlopen_check_rtld_local) { void* sym = dlsym(RTLD_DEFAULT, "dlopen_testlib_simple_func"); ASSERT_TRUE(sym == nullptr); @@ -342,7 +499,6 @@ TEST(dlfcn, dlopen_nodelete_dt_flags_1) { ASSERT_TRUE(!is_unloaded); } - TEST(dlfcn, dlopen_failure) { void* self = dlopen("/does/not/exist", RTLD_NOW); ASSERT_TRUE(self == NULL); diff --git a/tests/libs/Android.build.dlopen_check_order_dlsym.mk b/tests/libs/Android.build.dlopen_check_order_dlsym.mk new file mode 100644 index 000000000..73d8c1a83 --- /dev/null +++ b/tests/libs/Android.build.dlopen_check_order_dlsym.mk @@ -0,0 +1,90 @@ +# +# Copyright (C) 2012 The Android Open Source Project +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +# ----------------------------------------------------------------------------- +# Libraries used by dlfcn tests to verify correct load order: +# libtest_check_order_2_right.so +# ----------------------------------------------------------------------------- +libtest_check_order_dlsym_2_right_src_files := \ + dlopen_check_order_dlsym_answer.cpp + +libtest_check_order_dlsym_2_right_cflags := -D__ANSWER=42 +module := libtest_check_order_dlsym_2_right +include $(LOCAL_PATH)/Android.build.testlib.mk + +# ----------------------------------------------------------------------------- +# libtest_check_order_a.so +# ----------------------------------------------------------------------------- +libtest_check_order_dlsym_a_src_files := \ + dlopen_check_order_dlsym_answer.cpp + +libtest_check_order_dlsym_a_cflags := -D__ANSWER=1 +module := libtest_check_order_dlsym_a +include $(LOCAL_PATH)/Android.build.testlib.mk + +# ----------------------------------------------------------------------------- +# libtest_check_order_b.so +# ----------------------------------------------------------------------------- +libtest_check_order_dlsym_b_src_files := \ + dlopen_check_order_dlsym_answer.cpp + +libtest_check_order_dlsym_b_cflags := -D__ANSWER=2 -D__ANSWER2=43 +module := libtest_check_order_dlsym_b +include $(LOCAL_PATH)/Android.build.testlib.mk + +# ----------------------------------------------------------------------------- +# libtest_check_order_c.so +# ----------------------------------------------------------------------------- +libtest_check_order_dlsym_3_c_src_files := \ + dlopen_check_order_dlsym_answer.cpp + +libtest_check_order_dlsym_3_c_cflags := -D__ANSWER=3 +module := libtest_check_order_dlsym_3_c +include $(LOCAL_PATH)/Android.build.testlib.mk + +# ----------------------------------------------------------------------------- +# libtest_check_order_d.so +# ----------------------------------------------------------------------------- +libtest_check_order_dlsym_d_src_files := \ + dlopen_check_order_dlsym_answer.cpp + +libtest_check_order_dlsym_d_shared_libraries := libtest_check_order_dlsym_b +libtest_check_order_dlsym_d_cflags := -D__ANSWER=4 -D__ANSWER2=4 +module := libtest_check_order_dlsym_d +include $(LOCAL_PATH)/Android.build.testlib.mk + +# ----------------------------------------------------------------------------- +# libtest_check_order_left.so +# ----------------------------------------------------------------------------- +libtest_check_order_dlsym_1_left_src_files := \ + empty.cpp + +libtest_check_order_dlsym_1_left_shared_libraries := libtest_check_order_dlsym_a libtest_check_order_dlsym_b + +module := libtest_check_order_dlsym_1_left +include $(LOCAL_PATH)/Android.build.testlib.mk + +# ----------------------------------------------------------------------------- +# libtest_check_order.so +# ----------------------------------------------------------------------------- +libtest_check_order_dlsym_src_files := \ + empty.cpp + +libtest_check_order_dlsym_shared_libraries := libtest_check_order_dlsym_1_left \ + libtest_check_order_dlsym_2_right libtest_check_order_dlsym_3_c + +module := libtest_check_order_dlsym +include $(LOCAL_PATH)/Android.build.testlib.mk diff --git a/tests/libs/Android.build.dlopen_check_order_reloc_main_executable.mk b/tests/libs/Android.build.dlopen_check_order_reloc_main_executable.mk new file mode 100644 index 000000000..639696b25 --- /dev/null +++ b/tests/libs/Android.build.dlopen_check_order_reloc_main_executable.mk @@ -0,0 +1,56 @@ +# +# Copyright (C) 2012 The Android Open Source Project +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +# ----------------------------------------------------------------------------- +# Libraries used by dlfcn tests to verify correct relocation order: +# libtest_check_order_reloc_root*.so +# ----------------------------------------------------------------------------- + + +# ----------------------------------------------------------------------------- +# ..._1.so - empty +# ----------------------------------------------------------------------------- +libtest_check_order_reloc_root_1_src_files := \ + empty.cpp + + +module := libtest_check_order_reloc_root_1 +include $(LOCAL_PATH)/Android.build.testlib.mk + + +# ----------------------------------------------------------------------------- +# ..._2.so - this one has the incorrect answer +# ----------------------------------------------------------------------------- +libtest_check_order_reloc_root_2_src_files := \ + dlopen_check_order_reloc_root_answer_impl.cpp + +libtest_check_order_reloc_root_2_cflags := -D__ANSWER=2 + +module := libtest_check_order_reloc_root_2 +include $(LOCAL_PATH)/Android.build.testlib.mk + +# ----------------------------------------------------------------------------- +# libtest_check_order_reloc_root.so <- implements get_answer3() +# ----------------------------------------------------------------------------- +libtest_check_order_reloc_root_src_files := \ + dlopen_check_order_reloc_root_answer.cpp + +libtest_check_order_reloc_root_shared_libraries := \ + libtest_check_order_reloc_root_1 \ + libtest_check_order_reloc_root_2 + +module := libtest_check_order_reloc_root +include $(LOCAL_PATH)/Android.build.testlib.mk diff --git a/tests/libs/Android.build.dlopen_check_order_reloc_siblings.mk b/tests/libs/Android.build.dlopen_check_order_reloc_siblings.mk new file mode 100644 index 000000000..0f1a2b4da --- /dev/null +++ b/tests/libs/Android.build.dlopen_check_order_reloc_siblings.mk @@ -0,0 +1,133 @@ +# +# Copyright (C) 2014 The Android Open Source Project +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +# ----------------------------------------------------------------------------- +# Libraries used by dlfcn tests to verify correct relocation order: +# libtest_check_order_reloc_siblings*.so +# ----------------------------------------------------------------------------- + +# ----------------------------------------------------------------------------- +# ..._1.so - empty +# ----------------------------------------------------------------------------- +libtest_check_order_reloc_siblings_1_src_files := \ + empty.cpp + +libtest_check_order_reloc_siblings_1_shared_libraries := \ + libtest_check_order_reloc_siblings_a \ + libtest_check_order_reloc_siblings_b + +module := libtest_check_order_reloc_siblings_1 +include $(LOCAL_PATH)/Android.build.testlib.mk + + +# ----------------------------------------------------------------------------- +# ..._2.so - empty +# ----------------------------------------------------------------------------- +libtest_check_order_reloc_siblings_2_src_files := \ + empty.cpp + +libtest_check_order_reloc_siblings_2_shared_libraries := \ + libtest_check_order_reloc_siblings_c \ + libtest_check_order_reloc_siblings_d + +module := libtest_check_order_reloc_siblings_2 +include $(LOCAL_PATH)/Android.build.testlib.mk + +# ----------------------------------------------------------------------------- +# ..._3.so - get_answer2(); +# ----------------------------------------------------------------------------- +libtest_check_order_reloc_siblings_3_src_files := \ + dlopen_check_order_reloc_nephew_answer.cpp + +libtest_check_order_reloc_siblings_3_shared_libraries := \ + libtest_check_order_reloc_siblings_e \ + libtest_check_order_reloc_siblings_f + +module := libtest_check_order_reloc_siblings_3 +include $(LOCAL_PATH)/Android.build.testlib.mk + +# ----------------------------------------------------------------------------- +# ..._a.so <- correct impl +# ----------------------------------------------------------------------------- +libtest_check_order_reloc_siblings_a_src_files := \ + dlopen_check_order_reloc_answer_impl.cpp + +libtest_check_order_reloc_siblings_a_cflags := -D__ANSWER=42 +module := libtest_check_order_reloc_siblings_a +include $(LOCAL_PATH)/Android.build.testlib.mk + +# ----------------------------------------------------------------------------- +# ..._b.so +# ----------------------------------------------------------------------------- +libtest_check_order_reloc_siblings_b_src_files := \ + dlopen_check_order_reloc_answer_impl.cpp + +libtest_check_order_reloc_siblings_b_cflags := -D__ANSWER=1 +module := libtest_check_order_reloc_siblings_b +include $(LOCAL_PATH)/Android.build.testlib.mk + +# ----------------------------------------------------------------------------- +# ..._c.so +# ----------------------------------------------------------------------------- +libtest_check_order_reloc_siblings_c_src_files := \ + dlopen_check_order_reloc_answer_impl.cpp + +libtest_check_order_reloc_siblings_c_cflags := -D__ANSWER=2 +module := libtest_check_order_reloc_siblings_c +include $(LOCAL_PATH)/Android.build.testlib.mk + +# ----------------------------------------------------------------------------- +# ..._d.so +# ----------------------------------------------------------------------------- +libtest_check_order_reloc_siblings_d_src_files := \ + dlopen_check_order_reloc_answer_impl.cpp + +libtest_check_order_reloc_siblings_d_cflags := -D__ANSWER=3 +module := libtest_check_order_reloc_siblings_d +include $(LOCAL_PATH)/Android.build.testlib.mk + +# ----------------------------------------------------------------------------- +# ..._e.so +# ----------------------------------------------------------------------------- +libtest_check_order_reloc_siblings_e_src_files := \ + dlopen_check_order_reloc_answer_impl.cpp + +libtest_check_order_reloc_siblings_e_cflags := -D__ANSWER=4 +module := libtest_check_order_reloc_siblings_e +include $(LOCAL_PATH)/Android.build.testlib.mk + +# ----------------------------------------------------------------------------- +# ..._f.so <- get_answer() +# ----------------------------------------------------------------------------- +libtest_check_order_reloc_siblings_f_src_files := \ + dlopen_check_order_reloc_answer.cpp + +module := libtest_check_order_reloc_siblings_f +include $(LOCAL_PATH)/Android.build.testlib.mk + +# ----------------------------------------------------------------------------- +# libtest_check_order_reloc_siblings.so +# ----------------------------------------------------------------------------- +libtest_check_order_reloc_siblings_src_files := \ + empty.cpp + +libtest_check_order_reloc_siblings_shared_libraries := \ + libtest_check_order_reloc_siblings_1 \ + libtest_check_order_reloc_siblings_2 \ + libtest_check_order_reloc_siblings_3 + +module := libtest_check_order_reloc_siblings +include $(LOCAL_PATH)/Android.build.testlib.mk diff --git a/tests/libs/Android.mk b/tests/libs/Android.mk index 175a63539..05e7113ba 100644 --- a/tests/libs/Android.mk +++ b/tests/libs/Android.mk @@ -21,6 +21,9 @@ common_cppflags += -std=gnu++11 common_additional_dependencies := \ $(LOCAL_PATH)/Android.mk \ $(LOCAL_PATH)/Android.build.dlext_testzip.mk \ + $(LOCAL_PATH)/Android.build.dlopen_check_order_dlsym.mk \ + $(LOCAL_PATH)/Android.build.dlopen_check_order_reloc_siblings.mk \ + $(LOCAL_PATH)/Android.build.dlopen_check_order_reloc_main_executable.mk \ $(LOCAL_PATH)/Android.build.testlib.mk \ $(TEST_PATH)/Android.build.mk @@ -150,79 +153,19 @@ module := libtest_nodelete_dt_flags_1 include $(LOCAL_PATH)/Android.build.testlib.mk # ----------------------------------------------------------------------------- -# Libraries used by dlfcn tests to verify correct load order: -# libtest_check_order_2_right.so +# Build libtest_check_order_dlsym.so with its dependencies. # ----------------------------------------------------------------------------- -libtest_check_order_2_right_src_files := \ - dlopen_testlib_answer.cpp - -libtest_check_order_2_right_cflags := -D__ANSWER=42 -module := libtest_check_order_2_right -include $(LOCAL_PATH)/Android.build.testlib.mk +include $(LOCAL_PATH)/Android.build.dlopen_check_order_dlsym.mk # ----------------------------------------------------------------------------- -# libtest_check_order_a.so +# Build libtest_check_order_siblings.so with its dependencies. # ----------------------------------------------------------------------------- -libtest_check_order_a_src_files := \ - dlopen_testlib_answer.cpp - -libtest_check_order_a_cflags := -D__ANSWER=1 -module := libtest_check_order_a -include $(LOCAL_PATH)/Android.build.testlib.mk +include $(LOCAL_PATH)/Android.build.dlopen_check_order_reloc_siblings.mk # ----------------------------------------------------------------------------- -# libtest_check_order_b.so +# Build libtest_check_order_root.so with its dependencies. # ----------------------------------------------------------------------------- -libtest_check_order_b_src_files := \ - dlopen_testlib_answer.cpp - -libtest_check_order_b_cflags := -D__ANSWER=2 -D__ANSWER2=43 -module := libtest_check_order_b -include $(LOCAL_PATH)/Android.build.testlib.mk - -# ----------------------------------------------------------------------------- -# libtest_check_order_c.so -# ----------------------------------------------------------------------------- -libtest_check_order_3_c_src_files := \ - dlopen_testlib_answer.cpp - -libtest_check_order_3_c_cflags := -D__ANSWER=3 -module := libtest_check_order_3_c -include $(LOCAL_PATH)/Android.build.testlib.mk - -# ----------------------------------------------------------------------------- -# libtest_check_order_d.so -# ----------------------------------------------------------------------------- -libtest_check_order_d_src_files := \ - dlopen_testlib_answer.cpp - -libtest_check_order_d_shared_libraries := libtest_check_order_b -libtest_check_order_d_cflags := -D__ANSWER=4 -D__ANSWER2=4 -module := libtest_check_order_d -include $(LOCAL_PATH)/Android.build.testlib.mk - -# ----------------------------------------------------------------------------- -# libtest_check_order_left.so -# ----------------------------------------------------------------------------- -libtest_check_order_1_left_src_files := \ - empty.cpp - -libtest_check_order_1_left_shared_libraries := libtest_check_order_a libtest_check_order_b - -module := libtest_check_order_1_left -include $(LOCAL_PATH)/Android.build.testlib.mk - -# ----------------------------------------------------------------------------- -# libtest_check_order.so -# ----------------------------------------------------------------------------- -libtest_check_order_src_files := \ - empty.cpp - -libtest_check_order_shared_libraries := libtest_check_order_1_left \ - libtest_check_order_2_right libtest_check_order_3_c - -module := libtest_check_order -include $(LOCAL_PATH)/Android.build.testlib.mk +include $(LOCAL_PATH)/Android.build.dlopen_check_order_reloc_main_executable.mk # ----------------------------------------------------------------------------- # Library with dependency loop used by dlfcn tests diff --git a/tests/libs/dlopen_testlib_answer.cpp b/tests/libs/dlopen_check_order_dlsym_answer.cpp similarity index 87% rename from tests/libs/dlopen_testlib_answer.cpp rename to tests/libs/dlopen_check_order_dlsym_answer.cpp index a4d75046e..2ae6cf79e 100644 --- a/tests/libs/dlopen_testlib_answer.cpp +++ b/tests/libs/dlopen_check_order_dlsym_answer.cpp @@ -14,12 +14,12 @@ * limitations under the License. */ -extern "C" int dlopen_test_get_answer() { +extern "C" int check_order_dlsym_get_answer() { return __ANSWER; } #ifdef __ANSWER2 -extern "C" int dlopen_test_get_answer2() { +extern "C" int check_order_dlsym_get_answer2() { return __ANSWER2; } #endif diff --git a/tests/libs/dlopen_check_order_reloc_answer.cpp b/tests/libs/dlopen_check_order_reloc_answer.cpp new file mode 100644 index 000000000..036670bee --- /dev/null +++ b/tests/libs/dlopen_check_order_reloc_answer.cpp @@ -0,0 +1,23 @@ +/* + * Copyright (C) 2014 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +extern "C" int __attribute__((weak)) check_order_reloc_get_answer_impl() { + return 0; +} + +extern "C" int check_order_reloc_get_answer() { + return check_order_reloc_get_answer_impl(); +} diff --git a/tests/libs/dlopen_check_order_reloc_answer_impl.cpp b/tests/libs/dlopen_check_order_reloc_answer_impl.cpp new file mode 100644 index 000000000..324b905da --- /dev/null +++ b/tests/libs/dlopen_check_order_reloc_answer_impl.cpp @@ -0,0 +1,19 @@ +/* + * Copyright (C) 2014 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +extern "C" int check_order_reloc_get_answer_impl() { + return __ANSWER; +} diff --git a/tests/libs/dlopen_check_order_reloc_nephew_answer.cpp b/tests/libs/dlopen_check_order_reloc_nephew_answer.cpp new file mode 100644 index 000000000..065d1bef7 --- /dev/null +++ b/tests/libs/dlopen_check_order_reloc_nephew_answer.cpp @@ -0,0 +1,21 @@ +/* + * Copyright (C) 2014 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +extern "C" int check_order_reloc_get_answer_impl(); + +extern "C" int check_order_reloc_nephew_get_answer() { + return check_order_reloc_get_answer_impl(); +} diff --git a/tests/libs/dlopen_check_order_reloc_root_answer.cpp b/tests/libs/dlopen_check_order_reloc_root_answer.cpp new file mode 100644 index 000000000..b21abd77a --- /dev/null +++ b/tests/libs/dlopen_check_order_reloc_root_answer.cpp @@ -0,0 +1,21 @@ +/* + * Copyright (C) 2014 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +extern "C" int check_order_reloc_root_get_answer_impl(); + +extern "C" int check_order_reloc_root_get_answer() { + return check_order_reloc_root_get_answer_impl(); +} diff --git a/tests/libs/dlopen_check_order_reloc_root_answer_impl.cpp b/tests/libs/dlopen_check_order_reloc_root_answer_impl.cpp new file mode 100644 index 000000000..25fb9aca9 --- /dev/null +++ b/tests/libs/dlopen_check_order_reloc_root_answer_impl.cpp @@ -0,0 +1,19 @@ +/* + * Copyright (C) 2014 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +extern "C" int check_order_reloc_root_get_answer_impl() { + return __ANSWER; +} From 6442dbd3bcadbd5e522465743a8d8cf56338ae1c Mon Sep 17 00:00:00 2001 From: Dmitriy Ivanov Date: Thu, 23 Oct 2014 14:19:07 -0700 Subject: [PATCH 17/20] Remove unnecessary lookups during relocations local_group includes this library and its dependencies. Bug: 18186310 (cherry picked from commit e47b3f8456fc34ac136e9fddef59a9ae37febcbe) Change-Id: I93c2d873e924df7319569307444bf603d7d27bf0 --- linker/linker.cpp | 27 +++++---------------------- 1 file changed, 5 insertions(+), 22 deletions(-) diff --git a/linker/linker.cpp b/linker/linker.cpp index eb1a483ae..c63ac35bb 100644 --- a/linker/linker.cpp +++ b/linker/linker.cpp @@ -530,6 +530,11 @@ static ElfW(Sym)* soinfo_do_lookup(soinfo* si, const char* name, soinfo** lsi, c // 3. Look for it in the local group if (s == nullptr) { local_group.visit([&](soinfo* local_si) { + if (local_si == si && si->has_DT_SYMBOLIC) { + // we already did this - skip + return true; + } + DEBUG("%s: looking up %s in %s (from local group)", si->name, name, local_si->name); s = soinfo_elf_lookup(local_si, elf_hash, name); if (s != nullptr) { @@ -541,28 +546,6 @@ static ElfW(Sym)* soinfo_do_lookup(soinfo* si, const char* name, soinfo** lsi, c }); } - // 4. Look for it in this library (unless we already did it because of DT_SYMBOLIC) - if (s == nullptr && !si->has_DT_SYMBOLIC) { - DEBUG("%s: looking up %s in local scope", si->name, name); - s = soinfo_elf_lookup(si, elf_hash, name); - if (s != nullptr) { - *lsi = si; - } - } - - // 5. Dependencies - if (s == nullptr) { - si->get_children().visit([&](soinfo* child) { - DEBUG("%s: looking up %s in %s", si->name, name, child->name); - s = soinfo_elf_lookup(child, elf_hash, name); - if (s != nullptr) { - *lsi = child; - return false; - } - return true; - }); - } - if (s != nullptr) { TRACE_TYPE(LOOKUP, "si %s sym %s s->st_value = %p, " "found in %s, base = %p, load bias = %p", From bf3d5ef5fd240d4c5fbde1b32f9084dbc720840b Mon Sep 17 00:00:00 2001 From: Dmitriy Ivanov Date: Thu, 23 Oct 2014 14:34:12 -0700 Subject: [PATCH 18/20] Fix mips build Bug: 18186310 (cherry picked from commit 90b74fb8671db6f5512821a033e12a6248e5c804) Change-Id: I8d4ed254e5c421b65b62c401abdb1ee07e5dc3b2 --- linker/linker.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/linker/linker.cpp b/linker/linker.cpp index c63ac35bb..f8963b59c 100644 --- a/linker/linker.cpp +++ b/linker/linker.cpp @@ -2281,7 +2281,7 @@ bool soinfo::LinkImage(const soinfo_list_t& local_group, const android_dlextinfo #endif #if defined(__mips__) - if (!mips_relocate_got(this)) { + if (!mips_relocate_got(this, local_group)) { return false; } #endif From 976402cca13a1f4f3aa988fd301575e134ef5f2c Mon Sep 17 00:00:00 2001 From: Dmitriy Ivanov Date: Thu, 28 Aug 2014 14:12:12 -0700 Subject: [PATCH 19/20] Fix symbol lookup order during relocation Relocate symbol against DF_1_GLOBAL shared libraries loaded before this shared library. This includes main executable, ld_preloads and other libraries that have DF_1_GLOBAL flag set. Bug: 2643900 Bug: 15432753 Bug: 18186310 (cherry picked from commit d225a5e65223b375a63548c4b780f04d8f3d7b60) Change-Id: I4e889cdf2dfbf8230b0790053d311ee6b0d0ee2d --- linker/linked_list.h | 12 +++ linker/linker.cpp | 162 +++++++++++++++++----------- linker/linker.h | 23 ++-- tests/Android.mk | 13 ++- tests/dl_test.cpp | 72 +++++++++++++ tests/dlfcn_test.cpp | 14 +++ tests/libs/Android.mk | 36 +++++++ tests/libs/dl_df_1_global.cpp | 19 ++++ tests/libs/dl_df_1_use_global.cpp | 23 ++++ tests/libs/dl_preempt_library_1.cpp | 45 ++++++++ tests/libs/dl_preempt_library_2.cpp | 37 +++++++ 11 files changed, 385 insertions(+), 71 deletions(-) create mode 100644 tests/dl_test.cpp create mode 100644 tests/libs/dl_df_1_global.cpp create mode 100644 tests/libs/dl_df_1_use_global.cpp create mode 100644 tests/libs/dl_preempt_library_1.cpp create mode 100644 tests/libs/dl_preempt_library_2.cpp diff --git a/linker/linked_list.h b/linker/linked_list.h index 72a32b4ba..b08806161 100644 --- a/linker/linked_list.h +++ b/linker/linked_list.h @@ -36,6 +36,12 @@ class LinkedList { clear(); } + LinkedList(LinkedList&& that) { + this->head_ = that.head_; + this->tail_ = that.tail_; + that.head_ = that.tail_ = nullptr; + } + void push_front(T* const element) { LinkedListEntry* new_entry = Allocator::alloc(); new_entry->next = head_; @@ -140,6 +146,12 @@ class LinkedList { return false; } + static LinkedList make_list(T* const element) { + LinkedList one_element_list; + one_element_list.push_back(element); + return one_element_list; + } + private: LinkedListEntry* head_; LinkedListEntry* tail_; diff --git a/linker/linker.cpp b/linker/linker.cpp index f8963b59c..ef6e3e127 100644 --- a/linker/linker.cpp +++ b/linker/linker.cpp @@ -282,7 +282,7 @@ static void protect_data(int protection) { g_soinfo_links_allocator.protect_all(protection); } -static soinfo* soinfo_alloc(const char* name, struct stat* file_stat, off64_t file_offset, int rtld_flags) { +static soinfo* soinfo_alloc(const char* name, struct stat* file_stat, off64_t file_offset, uint32_t rtld_flags) { if (strlen(name) >= SOINFO_NAME_LEN) { DL_ERR("library name \"%s\" too long", name); return nullptr; @@ -481,7 +481,8 @@ static unsigned elfhash(const char* _name) { return h; } -static ElfW(Sym)* soinfo_do_lookup(soinfo* si, const char* name, soinfo** lsi, const soinfo::soinfo_list_t& local_group) { +static ElfW(Sym)* soinfo_do_lookup(soinfo* si_from, const char* name, soinfo** si_found_in, + const soinfo::soinfo_list_t& global_group, const soinfo::soinfo_list_t& local_group) { unsigned elf_hash = elfhash(name); ElfW(Sym)* s = nullptr; @@ -496,49 +497,40 @@ static ElfW(Sym)* soinfo_do_lookup(soinfo* si, const char* name, soinfo** lsi, c * Note that this is unlikely since static linker avoids generating * relocations for -Bsymbolic linked dynamic executables. */ - if (si->has_DT_SYMBOLIC) { - DEBUG("%s: looking up %s in local scope (DT_SYMBOLIC)", si->name, name); - s = soinfo_elf_lookup(si, elf_hash, name); + if (si_from->has_DT_SYMBOLIC) { + DEBUG("%s: looking up %s in local scope (DT_SYMBOLIC)", si_from->name, name); + s = soinfo_elf_lookup(si_from, elf_hash, name); if (s != nullptr) { - *lsi = si; + *si_found_in = si_from; } } - if (s == nullptr && somain != nullptr) { - // 1. Look for it in the main executable unless we already did. - if (si != somain || !si->has_DT_SYMBOLIC) { - DEBUG("%s: looking up %s in executable %s", - si->name, name, somain->name); - s = soinfo_elf_lookup(somain, elf_hash, name); + // 1. Look for it in global_group + if (s == nullptr) { + global_group.visit([&](soinfo* global_si) { + DEBUG("%s: looking up %s in %s (from global group)", si_from->name, name, global_si->name); + s = soinfo_elf_lookup(global_si, elf_hash, name); if (s != nullptr) { - *lsi = somain; + *si_found_in = global_si; + return false; } - } - // 2. Look for it in the ld_preloads - if (s == nullptr) { - for (int i = 0; g_ld_preloads[i] != NULL; i++) { - s = soinfo_elf_lookup(g_ld_preloads[i], elf_hash, name); - if (s != nullptr) { - *lsi = g_ld_preloads[i]; - break; - } - } - } + return true; + }); } - // 3. Look for it in the local group + // 2. Look for it in the local group if (s == nullptr) { local_group.visit([&](soinfo* local_si) { - if (local_si == si && si->has_DT_SYMBOLIC) { + if (local_si == si_from && si_from->has_DT_SYMBOLIC) { // we already did this - skip return true; } - DEBUG("%s: looking up %s in %s (from local group)", si->name, name, local_si->name); + DEBUG("%s: looking up %s in %s (from local group)", si_from->name, name, local_si->name); s = soinfo_elf_lookup(local_si, elf_hash, name); if (s != nullptr) { - *lsi = local_si; + *si_found_in = local_si; return false; } @@ -549,9 +541,9 @@ static ElfW(Sym)* soinfo_do_lookup(soinfo* si, const char* name, soinfo** lsi, c if (s != nullptr) { TRACE_TYPE(LOOKUP, "si %s sym %s s->st_value = %p, " "found in %s, base = %p, load bias = %p", - si->name, name, reinterpret_cast(s->st_value), - (*lsi)->name, reinterpret_cast((*lsi)->base), - reinterpret_cast((*lsi)->load_bias)); + si_from->name, name, reinterpret_cast(s->st_value), + (*si_found_in)->name, reinterpret_cast((*si_found_in)->base), + reinterpret_cast((*si_found_in)->load_bias)); } return s; @@ -916,6 +908,24 @@ static bool is_recursive(soinfo* si, soinfo* parent) { }); } +// TODO: this is slightly unusual way to construct +// the global group for relocation. Not every RTLD_GLOBAL +// library is included in this group for backwards-compatibility +// reasons. +// +// This group consists of the main executable, LD_PRELOADs +// and libraries with the DF_1_GLOBAL flag set. +static soinfo::soinfo_list_t make_global_group() { + soinfo::soinfo_list_t global_group; + for (soinfo* si = somain; si != nullptr; si = si->next) { + if ((si->get_dt_flags_1() & DF_1_GLOBAL) != 0) { + global_group.push_back(si); + } + } + + return global_group; +} + static bool find_libraries(soinfo* start_with, const char* const library_names[], size_t library_names_count, soinfo* soinfos[], soinfo* ld_preloads[], size_t ld_preloads_count, int rtld_flags, const android_dlextinfo* extinfo) { // Step 0: prepare. @@ -925,6 +935,9 @@ static bool find_libraries(soinfo* start_with, const char* const library_names[] load_tasks.push_back(LoadTask::create(name, start_with)); } + // Construct global_group. + soinfo::soinfo_list_t global_group = make_global_group(); + // If soinfos array is null allocate one on stack. // The array is needed in case of failure; for example // when library_names[] = {libone.so, libtwo.so} and libone.so @@ -973,6 +986,11 @@ static bool find_libraries(soinfo* start_with, const char* const library_names[] // When ld_preloads is not null, the first // ld_preloads_count libs are in fact ld_preloads. if (ld_preloads != nullptr && soinfos_count < ld_preloads_count) { + // Add LD_PRELOADed libraries to the global group for future runs. + // There is no need to explicitly add them to the global group + // for this run because they are going to appear in the local + // group in the correct order. + si->set_dt_flags_1(si->get_dt_flags_1() | DF_1_GLOBAL); ld_preloads[soinfos_count] = si; } @@ -993,7 +1011,7 @@ static bool find_libraries(soinfo* start_with, const char* const library_names[] bool linked = local_group.visit([&](soinfo* si) { if ((si->flags & FLAG_LINKED) == 0) { - if (!si->LinkImage(local_group, extinfo)) { + if (!si->LinkImage(global_group, local_group, extinfo)) { return false; } si->flags |= FLAG_LINKED; @@ -1128,7 +1146,7 @@ static ElfW(Addr) call_ifunc_resolver(ElfW(Addr) resolver_addr) { } #if defined(USE_RELA) -int soinfo::Relocate(ElfW(Rela)* rela, unsigned count, const soinfo_list_t& local_group) { +int soinfo::Relocate(ElfW(Rela)* rela, unsigned count, const soinfo_list_t& global_group, const soinfo_list_t& local_group) { for (size_t idx = 0; idx < count; ++idx, ++rela) { unsigned type = ELFW(R_TYPE)(rela->r_info); unsigned sym = ELFW(R_SYM)(rela->r_info); @@ -1146,7 +1164,7 @@ int soinfo::Relocate(ElfW(Rela)* rela, unsigned count, const soinfo_list_t& loca if (sym != 0) { sym_name = get_string(symtab[sym].st_name); - s = soinfo_do_lookup(this, sym_name, &lsi, local_group); + s = soinfo_do_lookup(this, sym_name, &lsi, global_group,local_group); if (s == nullptr) { // We only allow an undefined symbol if this is a weak reference... s = &symtab[sym]; @@ -1405,7 +1423,7 @@ int soinfo::Relocate(ElfW(Rela)* rela, unsigned count, const soinfo_list_t& loca } #else // REL, not RELA. -int soinfo::Relocate(ElfW(Rel)* rel, unsigned count, const soinfo_list_t& local_group) { +int soinfo::Relocate(ElfW(Rel)* rel, unsigned count, const soinfo_list_t& global_group, const soinfo_list_t& local_group) { for (size_t idx = 0; idx < count; ++idx, ++rel) { unsigned type = ELFW(R_TYPE)(rel->r_info); // TODO: don't use unsigned for 'sym'. Use uint32_t or ElfW(Addr) instead. @@ -1424,7 +1442,7 @@ int soinfo::Relocate(ElfW(Rel)* rel, unsigned count, const soinfo_list_t& local_ if (sym != 0) { sym_name = get_string(symtab[sym].st_name); - s = soinfo_do_lookup(this, sym_name, &lsi, local_group); + s = soinfo_do_lookup(this, sym_name, &lsi, global_group, local_group); if (s == nullptr) { // We only allow an undefined symbol if this is a weak reference... s = &symtab[sym]; @@ -1610,7 +1628,7 @@ int soinfo::Relocate(ElfW(Rel)* rel, unsigned count, const soinfo_list_t& local_ #endif #if defined(__mips__) -static bool mips_relocate_got(soinfo* si, const soinfo::soinfo_list_t& local_group) { +static bool mips_relocate_got(soinfo* si, const soinfo::soinfo_list_t& global_group, const soinfo::soinfo_list_t& local_group) { ElfW(Addr)** got = si->plt_got; if (got == nullptr) { return true; @@ -1643,7 +1661,7 @@ static bool mips_relocate_got(soinfo* si, const soinfo::soinfo_list_t& local_gro // This is an undefined reference... try to locate it. const char* sym_name = si->get_string(sym->st_name); soinfo* lsi = nullptr; - ElfW(Sym)* s = soinfo_do_lookup(si, sym_name, &lsi, local_group); + ElfW(Sym)* s = soinfo_do_lookup(si, sym_name, &lsi, global_group, local_group); if (s == nullptr) { // We only allow an undefined symbol if this is a weak reference. s = &symtab[g]; @@ -1783,7 +1801,7 @@ void soinfo::remove_all_links() { children.clear(); } -dev_t soinfo::get_st_dev() { +dev_t soinfo::get_st_dev() const { if (has_min_version(0)) { return st_dev; } @@ -1791,7 +1809,7 @@ dev_t soinfo::get_st_dev() { return 0; }; -ino_t soinfo::get_st_ino() { +ino_t soinfo::get_st_ino() const { if (has_min_version(0)) { return st_ino; } @@ -1799,7 +1817,7 @@ ino_t soinfo::get_st_ino() { return 0; } -off64_t soinfo::get_file_offset() { +off64_t soinfo::get_file_offset() const { if (has_min_version(1)) { return file_offset; } @@ -1807,7 +1825,7 @@ off64_t soinfo::get_file_offset() { return 0; } -int soinfo::get_rtld_flags() { +uint32_t soinfo::get_rtld_flags() const { if (has_min_version(1)) { return rtld_flags; } @@ -1815,6 +1833,27 @@ int soinfo::get_rtld_flags() { return 0; } +uint32_t soinfo::get_dt_flags_1() const { + if (has_min_version(1)) { + return dt_flags_1; + } + + return 0; +} +void soinfo::set_dt_flags_1(uint32_t dt_flags_1) { + if (has_min_version(1)) { + if ((dt_flags_1 & DF_1_GLOBAL) != 0) { + rtld_flags |= RTLD_GLOBAL; + } + + if ((dt_flags_1 & DF_1_NODELETE) != 0) { + rtld_flags |= RTLD_NODELETE; + } + + this->dt_flags_1 = dt_flags_1; + } +} + // This is a return on get_children()/get_parents() if // 'this->flags' does not have FLAG_NEW_SOINFO set. static soinfo::soinfo_list_t g_empty_list; @@ -1852,8 +1891,9 @@ const char* soinfo::get_string(ElfW(Word) index) const { } bool soinfo::can_unload() const { - return (rtld_flags & (RTLD_NODELETE | RTLD_GLOBAL)) == 0; + return (get_rtld_flags() & (RTLD_NODELETE | RTLD_GLOBAL)) == 0; } + /* Force any of the closed stdin, stdout and stderr to be associated with /dev/null. */ static int nullify_closed_stdio() { @@ -2154,16 +2194,9 @@ bool soinfo::PrelinkImage() { break; case DT_FLAGS_1: - if ((d->d_un.d_val & DF_1_GLOBAL) != 0) { - rtld_flags |= RTLD_GLOBAL; - } + set_dt_flags_1(d->d_un.d_val); - if ((d->d_un.d_val & DF_1_NODELETE) != 0) { - rtld_flags |= RTLD_NODELETE; - } - // TODO: Implement other flags - - if ((d->d_un.d_val & ~(DF_1_NOW | DF_1_GLOBAL | DF_1_NODELETE)) != 0) { + if ((d->d_un.d_val & ~SUPPORTED_DT_FLAGS_1) != 0) { DL_WARN("Unsupported flags DT_FLAGS_1=%p", reinterpret_cast(d->d_un.d_val)); } break; @@ -2236,7 +2269,7 @@ bool soinfo::PrelinkImage() { return true; } -bool soinfo::LinkImage(const soinfo_list_t& local_group, const android_dlextinfo* extinfo) { +bool soinfo::LinkImage(const soinfo_list_t& global_group, const soinfo_list_t& local_group, const android_dlextinfo* extinfo) { #if !defined(__LP64__) if (has_text_relocations) { @@ -2255,33 +2288,33 @@ bool soinfo::LinkImage(const soinfo_list_t& local_group, const android_dlextinfo #if defined(USE_RELA) if (rela != nullptr) { DEBUG("[ relocating %s ]", name); - if (Relocate(rela, rela_count, local_group)) { + if (Relocate(rela, rela_count, global_group, local_group)) { return false; } } if (plt_rela != nullptr) { DEBUG("[ relocating %s plt ]", name); - if (Relocate(plt_rela, plt_rela_count, local_group)) { + if (Relocate(plt_rela, plt_rela_count, global_group, local_group)) { return false; } } #else if (rel != nullptr) { DEBUG("[ relocating %s ]", name); - if (Relocate(rel, rel_count, local_group)) { + if (Relocate(rel, rel_count, global_group, local_group)) { return false; } } if (plt_rel != nullptr) { DEBUG("[ relocating %s plt ]", name); - if (Relocate(plt_rel, plt_rel_count, local_group)) { + if (Relocate(plt_rel, plt_rel_count, global_group, local_group)) { return false; } } #endif #if defined(__mips__) - if (!mips_relocate_got(this, local_group)) { + if (!mips_relocate_got(this, global_group, local_group)) { return false; } #endif @@ -2348,7 +2381,7 @@ static void add_vdso(KernelArgumentBlock& args __unused) { si->load_bias = get_elf_exec_load_bias(ehdr_vdso); si->PrelinkImage(); - si->LinkImage(g_empty_list, nullptr); + si->LinkImage(g_empty_list, soinfo::soinfo_list_t::make_list(si), nullptr); #endif } @@ -2479,6 +2512,9 @@ static ElfW(Addr) __linker_init_post_relocation(KernelArgumentBlock& args, ElfW( si->PrelinkImage(); + // add somain to global group + si->set_dt_flags_1(si->get_dt_flags_1() | DF_1_GLOBAL); + // Load ld_preloads and dependencies. StringLinkedList needed_library_name_list; size_t needed_libraries_count = 0; @@ -2622,7 +2658,13 @@ extern "C" ElfW(Addr) __linker_init(void* raw_args) { linker_so.phnum = elf_hdr->e_phnum; linker_so.flags |= FLAG_LINKER; - if (!(linker_so.PrelinkImage() && linker_so.LinkImage(g_empty_list, nullptr))) { + // This might not be obvious... The reasons why we pass g_empty_list + // in place of local_group here are (1) we do not really need it, because + // linker is built with DT_SYMBOLIC and therefore relocates its symbols against + // itself without having to look into local_group and (2) allocators + // are not yet initialized, and therefore we cannot use linked_list.push_* + // functions at this point. + if (!(linker_so.PrelinkImage() && linker_so.LinkImage(g_empty_list, g_empty_list, nullptr))) { // It would be nice to print an error message, but if the linker // can't link itself, there's no guarantee that we'll be able to // call write() (because it involves a GOT reference). We may as diff --git a/linker/linker.h b/linker/linker.h index 222aca11e..0a98b40dc 100644 --- a/linker/linker.h +++ b/linker/linker.h @@ -89,7 +89,9 @@ #define FLAG_LINKER 0x00000010 // The linker itself #define FLAG_NEW_SOINFO 0x40000000 // new soinfo format -#define SOINFO_VERSION 0 +#define SUPPORTED_DT_FLAGS_1 (DF_1_NOW | DF_1_GLOBAL | DF_1_NODELETE) + +#define SOINFO_VERSION 1 #define SOINFO_NAME_LEN 128 @@ -207,16 +209,18 @@ struct soinfo { void CallDestructors(); void CallPreInitConstructors(); bool PrelinkImage(); - bool LinkImage(const soinfo_list_t& local_group, const android_dlextinfo* extinfo); + bool LinkImage(const soinfo_list_t& global_group, const soinfo_list_t& local_group, const android_dlextinfo* extinfo); void add_child(soinfo* child); void remove_all_links(); - ino_t get_st_ino(); - dev_t get_st_dev(); - off64_t get_file_offset(); + ino_t get_st_ino() const; + dev_t get_st_dev() const; + off64_t get_file_offset() const; - int get_rtld_flags(); + uint32_t get_rtld_flags() const; + uint32_t get_dt_flags_1() const; + void set_dt_flags_1(uint32_t dt_flags_1); soinfo_list_t& get_children(); soinfo_list_t& get_parents(); @@ -234,9 +238,9 @@ struct soinfo { void CallArray(const char* array_name, linker_function_t* functions, size_t count, bool reverse); void CallFunction(const char* function_name, linker_function_t function); #if defined(USE_RELA) - int Relocate(ElfW(Rela)* rela, unsigned count, const soinfo_list_t& local_group); + int Relocate(ElfW(Rela)* rela, unsigned count, const soinfo_list_t& global_group, const soinfo_list_t& local_group); #else - int Relocate(ElfW(Rel)* rel, unsigned count, const soinfo_list_t& local_group); + int Relocate(ElfW(Rel)* rel, unsigned count, const soinfo_list_t& global_group, const soinfo_list_t& local_group); #endif private: @@ -254,7 +258,8 @@ struct soinfo { // version >= 1 off64_t file_offset; - int rtld_flags; + uint32_t rtld_flags; + uint32_t dt_flags_1; size_t strtab_size; friend soinfo* get_libdl_info(); diff --git a/tests/Android.mk b/tests/Android.mk index 8b0b0a0e0..6423df183 100644 --- a/tests/Android.mk +++ b/tests/Android.mk @@ -225,6 +225,7 @@ bionic-unit-tests_whole_static_libraries := \ bionic-unit-tests_src_files := \ atexit_test.cpp \ + dl_test.cpp \ dlext_test.cpp \ dlfcn_test.cpp \ @@ -237,8 +238,7 @@ bionic-unit-tests_conlyflags := \ bionic-unit-tests_cppflags := $(test_cppflags) bionic-unit-tests_ldflags := \ - -Wl,--export-dynamic \ - -Wl,-u,DlSymTestFunction \ + -Wl,--export-dynamic bionic-unit-tests_c_includes := \ bionic/libc \ @@ -247,6 +247,9 @@ bionic-unit-tests_c_includes := \ bionic-unit-tests_shared_libraries_target := \ libdl \ libpagemap \ + libdl_preempt_test_1 \ + libdl_preempt_test_2 \ + libdl_test_df_1_global module := bionic-unit-tests module_tag := optional @@ -286,6 +289,12 @@ ifeq ($(HOST_OS)-$(HOST_ARCH),$(filter $(HOST_OS)-$(HOST_ARCH),linux-x86 linux-x bionic-unit-tests-glibc_src_files := \ atexit_test.cpp \ dlfcn_test.cpp \ + dl_test.cpp \ + +bionic-unit-tests-glibc_shared_libraries := \ + libdl_preempt_test_1 \ + libdl_preempt_test_2 \ + libdl_test_df_1_global bionic-unit-tests-glibc_whole_static_libraries := \ libBionicStandardTests \ diff --git a/tests/dl_test.cpp b/tests/dl_test.cpp new file mode 100644 index 000000000..74c7b510f --- /dev/null +++ b/tests/dl_test.cpp @@ -0,0 +1,72 @@ +/* + * Copyright (C) 2012 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include + +#include +#include +#include +#include +#include + +#include + +extern "C" int main_global_default_serial() { + return 3370318; +} + +extern "C" int main_global_protected_serial() { + return 2716057; +} + +// The following functions are defined in DT_NEEDED +// libdl_preempt_test.so library. + +// This one calls main_global_default_serial +extern "C" int main_global_default_get_serial(); + +// This one calls main_global_protected_serial +extern "C" int main_global_protected_get_serial(); + +// This one calls lib_global_default_serial +extern "C" int lib_global_default_get_serial(); + +// This one calls lib_global_protected_serial +extern "C" int lib_global_protected_get_serial(); + +// This test verifies that the global default function +// main_global_default_serial() is preempted by +// the function defined above. +TEST(dl, main_preempts_global_default) { + ASSERT_EQ(3370318, main_global_default_get_serial()); +} + +// This one makes sure that the global protected +// symbols do not get preempted +TEST(dl, main_does_not_preempt_global_protected) { + ASSERT_EQ(3370318, main_global_protected_get_serial()); +} + +// check same things for lib +TEST(dl, lib_preempts_global_default) { + ASSERT_EQ(3370318, lib_global_default_get_serial()); +} + +TEST(dl, lib_does_not_preempt_global_protected) { + ASSERT_EQ(3370318, lib_global_protected_get_serial()); +} + +// TODO: Add tests for LD_PRELOADs diff --git a/tests/dlfcn_test.cpp b/tests/dlfcn_test.cpp index e604f5abe..a7fe2f852 100644 --- a/tests/dlfcn_test.cpp +++ b/tests/dlfcn_test.cpp @@ -499,6 +499,20 @@ TEST(dlfcn, dlopen_nodelete_dt_flags_1) { ASSERT_TRUE(!is_unloaded); } +TEST(dlfcn, dlsym_df_1_global) { +#if !defined(__arm__) + void* handle = dlopen("libtest_dlsym_df_1_global.so", RTLD_NOW); + ASSERT_TRUE(handle != nullptr) << dlerror(); + int (*get_answer)(); + get_answer = reinterpret_cast(dlsym(handle, "dl_df_1_global_get_answer")); + ASSERT_TRUE(get_answer != nullptr) << dlerror(); + ASSERT_EQ(42, get_answer()); + ASSERT_EQ(0, dlclose(handle)); +#else + GTEST_LOG_(INFO) << "This test does nothing on arm (to be reenabled once b/18137520 or b/18130452 are fixed).\n"; +#endif +} + TEST(dlfcn, dlopen_failure) { void* self = dlopen("/does/not/exist", RTLD_NOW); ASSERT_TRUE(self == NULL); diff --git a/tests/libs/Android.mk b/tests/libs/Android.mk index 05e7113ba..f45e5a80f 100644 --- a/tests/libs/Android.mk +++ b/tests/libs/Android.mk @@ -289,6 +289,42 @@ libtest_atexit_src_files := \ module := libtest_atexit include $(LOCAL_PATH)/Android.build.testlib.mk +# ----------------------------------------------------------------------------- +# This library is used by dl_load test to check symbol preempting +# by main executable +# ----------------------------------------------------------------------------- +libdl_preempt_test_1_src_files := dl_preempt_library_1.cpp + +module := libdl_preempt_test_1 +include $(LOCAL_PATH)/Android.build.testlib.mk + +# ----------------------------------------------------------------------------- +# This library is used by dl_load test to check symbol preempting +# by libdl_preempt_test_1.so +# ----------------------------------------------------------------------------- +libdl_preempt_test_2_src_files := dl_preempt_library_2.cpp + +module := libdl_preempt_test_2 +include $(LOCAL_PATH)/Android.build.testlib.mk + +# ----------------------------------------------------------------------------- +# Library with DF_1_GLOBAL +# ----------------------------------------------------------------------------- +# TODO: re-enable arm once b/18137520 or b/18130452 are fixed +ifeq ($(filter $(TARGET_ARCH),arm),) +libdl_test_df_1_global_src_files := dl_df_1_global.cpp +libdl_test_df_1_global_ldflags := -fuse-ld=bfd -Wl,-z,global +module := libdl_test_df_1_global +include $(LOCAL_PATH)/Android.build.testlib.mk +endif + +# ----------------------------------------------------------------------------- +# Library using symbol from libdl_test_df_1_global +# ----------------------------------------------------------------------------- +libtest_dlsym_df_1_global_src_files := dl_df_1_use_global.cpp +module := libtest_dlsym_df_1_global +include $(LOCAL_PATH)/Android.build.testlib.mk + # ----------------------------------------------------------------------------- # Library with weak function # ----------------------------------------------------------------------------- diff --git a/tests/libs/dl_df_1_global.cpp b/tests/libs/dl_df_1_global.cpp new file mode 100644 index 000000000..39856fd50 --- /dev/null +++ b/tests/libs/dl_df_1_global.cpp @@ -0,0 +1,19 @@ +/* + * Copyright (C) 2014 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +extern "C" int dl_df_1_global_get_answer_impl() { + return 42; +} diff --git a/tests/libs/dl_df_1_use_global.cpp b/tests/libs/dl_df_1_use_global.cpp new file mode 100644 index 000000000..e14910d1c --- /dev/null +++ b/tests/libs/dl_df_1_use_global.cpp @@ -0,0 +1,23 @@ +/* + * Copyright (C) 2014 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +extern "C" int __attribute__((weak)) dl_df_1_global_get_answer_impl() { + return 0; +} + +extern "C" int dl_df_1_global_get_answer() { + return dl_df_1_global_get_answer_impl(); +} diff --git a/tests/libs/dl_preempt_library_1.cpp b/tests/libs/dl_preempt_library_1.cpp new file mode 100644 index 000000000..b4d81d5ac --- /dev/null +++ b/tests/libs/dl_preempt_library_1.cpp @@ -0,0 +1,45 @@ +/* + * Copyright (C) 2014 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// This one should be preempted by the function +// defined in the main executable. +extern "C" int __attribute__((weak)) main_global_default_serial() { + return 2716057; +} + +// Even though this one is defined by the main +// executable it should not be preempted +// because of protected visibility +extern "C" int __attribute__((weak, visibility("protected"))) main_global_protected_serial() { + return 3370318; +} + +extern "C" int main_global_default_get_serial() { + return main_global_default_serial(); +} + +extern "C" int main_global_protected_get_serial() { + return main_global_protected_serial(); +} + +// Trying to preempt functions from a DT_NEEDED .so +extern "C" int lib_global_default_serial() { + return 3370318; +} + +extern "C" int lib_global_protected_serial() { + return 2716057; +} diff --git a/tests/libs/dl_preempt_library_2.cpp b/tests/libs/dl_preempt_library_2.cpp new file mode 100644 index 000000000..8df9a1667 --- /dev/null +++ b/tests/libs/dl_preempt_library_2.cpp @@ -0,0 +1,37 @@ +/* + * Copyright (C) 2014 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// This one should be preempted by the function +// defined in libdl_preempt_test_1.so +extern "C" int __attribute__((weak)) lib_global_default_serial() { + return 2716057; +} + +// Even though this one is defined by +// libdl_preempt_test_1.so it should not be +// preempted because of protected visibility +extern "C" int __attribute__((weak,visibility("protected"))) lib_global_protected_serial() { + return 3370318; +} + +extern "C" int lib_global_default_get_serial() { + return lib_global_default_serial(); +} + +extern "C" int lib_global_protected_get_serial() { + return lib_global_protected_serial(); +} + From 445111a1c977e94a4233efd54f3690defa4a7582 Mon Sep 17 00:00:00 2001 From: Dmitriy Ivanov Date: Fri, 31 Oct 2014 17:27:02 -0700 Subject: [PATCH 20/20] Fix arm64 and arm builds. Bug: 18186310 (cherry picked from commit 4e446b19d8710cd2004785db4a00f18f249fe73f) Change-Id: Ibc77a9ade36dc6b9bf5a316b5ab9ae5f0a70e826 --- tests/Android.mk | 14 ++++++++++---- tests/dlfcn_test.cpp | 4 ++-- tests/libs/Android.mk | 2 +- 3 files changed, 13 insertions(+), 7 deletions(-) diff --git a/tests/Android.mk b/tests/Android.mk index 6423df183..5a1127b96 100644 --- a/tests/Android.mk +++ b/tests/Android.mk @@ -248,8 +248,11 @@ bionic-unit-tests_shared_libraries_target := \ libdl \ libpagemap \ libdl_preempt_test_1 \ - libdl_preempt_test_2 \ - libdl_test_df_1_global + libdl_preempt_test_2 + +ifneq ($(filter $(TARGET_ARCH),arm arm64),$(TARGET_ARCH)) +bionic-unit-tests_shared_libraries_target += libdl_test_df_1_global +endif module := bionic-unit-tests module_tag := optional @@ -293,8 +296,11 @@ bionic-unit-tests-glibc_src_files := \ bionic-unit-tests-glibc_shared_libraries := \ libdl_preempt_test_1 \ - libdl_preempt_test_2 \ - libdl_test_df_1_global + libdl_preempt_test_2 + +ifneq ($(filter $(TARGET_ARCH),arm arm64),$(TARGET_ARCH)) +bionic-unit-tests-glibc_shared_libraries += libdl_test_df_1_global +endif bionic-unit-tests-glibc_whole_static_libraries := \ libBionicStandardTests \ diff --git a/tests/dlfcn_test.cpp b/tests/dlfcn_test.cpp index a7fe2f852..2f0d430f6 100644 --- a/tests/dlfcn_test.cpp +++ b/tests/dlfcn_test.cpp @@ -500,7 +500,7 @@ TEST(dlfcn, dlopen_nodelete_dt_flags_1) { } TEST(dlfcn, dlsym_df_1_global) { -#if !defined(__arm__) +#if !defined(__arm__) && !defined(__aarch64__) void* handle = dlopen("libtest_dlsym_df_1_global.so", RTLD_NOW); ASSERT_TRUE(handle != nullptr) << dlerror(); int (*get_answer)(); @@ -509,7 +509,7 @@ TEST(dlfcn, dlsym_df_1_global) { ASSERT_EQ(42, get_answer()); ASSERT_EQ(0, dlclose(handle)); #else - GTEST_LOG_(INFO) << "This test does nothing on arm (to be reenabled once b/18137520 or b/18130452 are fixed).\n"; + GTEST_LOG_(INFO) << "This test does nothing on arm/arm64 (to be reenabled once b/18137520 or b/18130452 are fixed).\n"; #endif } diff --git a/tests/libs/Android.mk b/tests/libs/Android.mk index f45e5a80f..7d959d484 100644 --- a/tests/libs/Android.mk +++ b/tests/libs/Android.mk @@ -311,7 +311,7 @@ include $(LOCAL_PATH)/Android.build.testlib.mk # Library with DF_1_GLOBAL # ----------------------------------------------------------------------------- # TODO: re-enable arm once b/18137520 or b/18130452 are fixed -ifeq ($(filter $(TARGET_ARCH),arm),) +ifeq ($(filter $(TARGET_ARCH),arm arm64),) libdl_test_df_1_global_src_files := dl_df_1_global.cpp libdl_test_df_1_global_ldflags := -fuse-ld=bfd -Wl,-z,global module := libdl_test_df_1_global