summaryrefslogtreecommitdiffstats
path: root/linker
diff options
context:
space:
mode:
Diffstat (limited to 'linker')
-rw-r--r--linker/Android.mk1
-rw-r--r--linker/debugger.cpp28
-rw-r--r--linker/dlfcn.cpp66
-rw-r--r--linker/linked_list.h49
-rw-r--r--linker/linker.cpp2748
-rw-r--r--linker/linker.h35
-rw-r--r--linker/linker_debug.h1
-rw-r--r--linker/linker_environ.cpp30
-rw-r--r--linker/linker_environ.h2
-rw-r--r--linker/linker_executable.mk2
-rw-r--r--linker/linker_libc_support.c17
-rw-r--r--linker/linker_phdr.cpp73
-rw-r--r--linker/linker_phdr.h9
-rw-r--r--linker/tests/linked_list_test.cpp109
14 files changed, 1796 insertions, 1374 deletions
diff --git a/linker/Android.mk b/linker/Android.mk
index 5853c90..4298032 100644
--- a/linker/Android.mk
+++ b/linker/Android.mk
@@ -8,6 +8,7 @@ LOCAL_SRC_FILES:= \
linker.cpp \
linker_allocator.cpp \
linker_environ.cpp \
+ linker_libc_support.c \
linker_phdr.cpp \
rt.cpp \
diff --git a/linker/debugger.cpp b/linker/debugger.cpp
index c316151..ac466a5 100644
--- a/linker/debugger.cpp
+++ b/linker/debugger.cpp
@@ -162,12 +162,12 @@ static void log_signal_summary(int signum, const siginfo_t* info) {
thread_name[MAX_TASK_NAME_LEN] = 0;
}
- // "info" will be NULL if the siginfo_t information was not available.
+ // "info" will be null if the siginfo_t information was not available.
// Many signals don't have an address or a code.
char code_desc[32]; // ", code -6"
char addr_desc[32]; // ", fault addr 0x1234"
addr_desc[0] = code_desc[0] = 0;
- if (info != NULL) {
+ if (info != nullptr) {
// For a rethrown signal, this si_code will be right and the one debuggerd shows will
// always be SI_TKILL.
__libc_format_buffer(code_desc, sizeof(code_desc), ", code %d", info->si_code);
@@ -198,7 +198,7 @@ static bool have_siginfo(int signum) {
}
bool result = (old_action.sa_flags & SA_SIGINFO) != 0;
- if (sigaction(signum, &old_action, NULL) == -1) {
+ if (sigaction(signum, &old_action, nullptr) == -1) {
__libc_format_log(ANDROID_LOG_WARN, "libc", "Restore failed in test for SA_SIGINFO: %s",
strerror(errno));
}
@@ -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));
@@ -230,7 +230,7 @@ static void send_debuggerd_packet(siginfo_t* info) {
msg.action = DEBUGGER_ACTION_CRASH;
msg.tid = gettid();
msg.abort_msg_address = reinterpret_cast<uintptr_t>(g_abort_message);
- msg.original_si_code = (info != NULL) ? info->si_code : 0;
+ msg.original_si_code = (info != nullptr) ? info->si_code : 0;
int ret = TEMP_FAILURE_RETRY(write(s, &msg, sizeof(msg)));
if (ret == sizeof(msg)) {
char debuggerd_ack;
@@ -255,7 +255,7 @@ static void debuggerd_signal_handler(int signal_number, siginfo_t* info, void*)
// It's possible somebody cleared the SA_SIGINFO flag, which would mean
// our "info" arg holds an undefined value.
if (!have_siginfo(signal_number)) {
- info = NULL;
+ info = nullptr;
}
log_signal_summary(signal_number, info);
@@ -296,14 +296,14 @@ __LIBC_HIDDEN__ void debuggerd_init() {
// Use the alternate signal stack if available so we can catch stack overflows.
action.sa_flags |= SA_ONSTACK;
- sigaction(SIGABRT, &action, NULL);
- sigaction(SIGBUS, &action, NULL);
- sigaction(SIGFPE, &action, NULL);
- sigaction(SIGILL, &action, NULL);
- sigaction(SIGPIPE, &action, NULL);
- sigaction(SIGSEGV, &action, NULL);
+ sigaction(SIGABRT, &action, nullptr);
+ sigaction(SIGBUS, &action, nullptr);
+ sigaction(SIGFPE, &action, nullptr);
+ sigaction(SIGILL, &action, nullptr);
+ sigaction(SIGPIPE, &action, nullptr);
+ sigaction(SIGSEGV, &action, nullptr);
#if defined(SIGSTKFLT)
- sigaction(SIGSTKFLT, &action, NULL);
+ sigaction(SIGSTKFLT, &action, nullptr);
#endif
- sigaction(SIGTRAP, &action, NULL);
+ sigaction(SIGTRAP, &action, nullptr);
}
diff --git a/linker/dlfcn.cpp b/linker/dlfcn.cpp
index 5d6db8e..3eb5bea 100644
--- a/linker/dlfcn.cpp
+++ b/linker/dlfcn.cpp
@@ -42,7 +42,7 @@ static const char* __bionic_set_dlerror(char* new_value) {
static void __bionic_format_dlerror(const char* msg, const char* detail) {
char* buffer = __get_thread()->dlerror_buffer;
strlcpy(buffer, msg, __BIONIC_DLERROR_BUFFER_SIZE);
- if (detail != NULL) {
+ if (detail != nullptr) {
strlcat(buffer, ": ", __BIONIC_DLERROR_BUFFER_SIZE);
strlcat(buffer, detail, __BIONIC_DLERROR_BUFFER_SIZE);
}
@@ -51,7 +51,7 @@ static void __bionic_format_dlerror(const char* msg, const char* detail) {
}
const char* dlerror() {
- const char* old_value = __bionic_set_dlerror(NULL);
+ const char* old_value = __bionic_set_dlerror(nullptr);
return old_value;
}
@@ -68,9 +68,9 @@ void android_update_LD_LIBRARY_PATH(const char* ld_library_path) {
static void* dlopen_ext(const char* filename, int flags, const android_dlextinfo* extinfo) {
ScopedPthreadMutexLocker locker(&g_dl_mutex);
soinfo* result = do_dlopen(filename, flags, extinfo);
- if (result == NULL) {
+ if (result == nullptr) {
__bionic_format_dlerror("dlopen failed", linker_get_error_buffer());
- return NULL;
+ return nullptr;
}
return result;
}
@@ -80,33 +80,33 @@ void* android_dlopen_ext(const char* filename, int flags, const android_dlextinf
}
void* dlopen(const char* filename, int flags) {
- return dlopen_ext(filename, flags, NULL);
+ return dlopen_ext(filename, flags, nullptr);
}
void* dlsym(void* handle, const char* symbol) {
ScopedPthreadMutexLocker locker(&g_dl_mutex);
#if !defined(__LP64__)
- if (handle == NULL) {
- __bionic_format_dlerror("dlsym library handle is null", NULL);
- return NULL;
+ if (handle == nullptr) {
+ __bionic_format_dlerror("dlsym library handle is null", nullptr);
+ return nullptr;
}
#endif
- if (symbol == NULL) {
- __bionic_format_dlerror("dlsym symbol name is null", NULL);
- return NULL;
+ if (symbol == nullptr) {
+ __bionic_format_dlerror("dlsym symbol name is null", nullptr);
+ return nullptr;
}
- soinfo* found = NULL;
- ElfW(Sym)* sym = NULL;
+ soinfo* found = nullptr;
+ ElfW(Sym)* sym = nullptr;
if (handle == RTLD_DEFAULT) {
- sym = dlsym_linear_lookup(symbol, &found, NULL);
+ sym = dlsym_linear_lookup(symbol, &found, nullptr);
} else if (handle == RTLD_NEXT) {
void* caller_addr = __builtin_return_address(0);
soinfo* si = find_containing_library(caller_addr);
- sym = NULL;
+ sym = nullptr;
if (si && si->next) {
sym = dlsym_linear_lookup(symbol, &found, si->next);
}
@@ -114,18 +114,18 @@ void* dlsym(void* handle, const char* symbol) {
sym = dlsym_handle_lookup(reinterpret_cast<soinfo*>(handle), &found, symbol);
}
- if (sym != NULL) {
+ if (sym != nullptr) {
unsigned bind = ELF_ST_BIND(sym->st_info);
if ((bind == STB_GLOBAL || bind == STB_WEAK) && sym->st_shndx != 0) {
- return reinterpret_cast<void*>(sym->st_value + found->load_bias);
+ return reinterpret_cast<void*>(found->resolve_symbol_address(sym));
}
__bionic_format_dlerror("symbol found but not global", symbol);
- return NULL;
+ return nullptr;
} else {
__bionic_format_dlerror("undefined symbol", symbol);
- return NULL;
+ return nullptr;
}
}
@@ -134,7 +134,7 @@ int dladdr(const void* addr, Dl_info* info) {
// Determine if this address can be found in any library currently mapped.
soinfo* si = find_containing_library(addr);
- if (si == NULL) {
+ if (si == nullptr) {
return 0;
}
@@ -146,9 +146,9 @@ 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 != NULL) {
- info->dli_sname = si->strtab + sym->st_name;
- info->dli_saddr = reinterpret_cast<void*>(si->load_bias + sym->st_value);
+ if (sym != nullptr) {
+ info->dli_sname = si->get_string(sym->st_name);
+ info->dli_saddr = reinterpret_cast<void*>(si->resolve_symbol_address(sym));
}
return 1;
@@ -164,7 +164,7 @@ int dlclose(void* handle) {
// name_offset: starting index of the name in libdl_info.strtab
#define ELF32_SYM_INITIALIZER(name_offset, value, shndx) \
{ name_offset, \
- reinterpret_cast<Elf32_Addr>(reinterpret_cast<void*>(value)), \
+ reinterpret_cast<Elf32_Addr>(value), \
/* st_size */ 0, \
(shndx == 0) ? 0 : (STB_GLOBAL << 4), \
/* st_other */ 0, \
@@ -176,7 +176,7 @@ int dlclose(void* handle) {
(shndx == 0) ? 0 : (STB_GLOBAL << 4), \
/* st_other */ 0, \
shndx, \
- reinterpret_cast<Elf64_Addr>(reinterpret_cast<void*>(value)), \
+ reinterpret_cast<Elf64_Addr>(value), \
/* st_size */ 0, \
}
@@ -199,7 +199,7 @@ static ElfW(Sym) g_libdl_symtab[] = {
// This is actually the STH_UNDEF entry. Technically, it's
// supposed to have st_name == 0, but instead, it points to an index
// in the strtab with a \0 to make iterating through the symtab easier.
- ELFW(SYM_INITIALIZER)(sizeof(ANDROID_LIBDL_STRTAB) - 1, NULL, 0),
+ ELFW(SYM_INITIALIZER)(sizeof(ANDROID_LIBDL_STRTAB) - 1, nullptr, 0),
ELFW(SYM_INITIALIZER)( 0, &dlopen, 1),
ELFW(SYM_INITIALIZER)( 7, &dlclose, 1),
ELFW(SYM_INITIALIZER)( 15, &dlsym, 1),
@@ -232,24 +232,20 @@ 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
-// Defined as global because we do not yet have access
-// to synchronization functions __cxa_guard_* needed
-// to define statics inside functions.
-static soinfo __libdl_info;
+static soinfo __libdl_info("libdl.so", nullptr, 0);
// This is used by the dynamic linker. Every process gets these symbols for free.
soinfo* get_libdl_info() {
- if (__libdl_info.name[0] == '\0') {
- // initialize
- strncpy(__libdl_info.name, "libdl.so", sizeof(__libdl_info.name));
- __libdl_info.flags = FLAG_LINKED | FLAG_NEW_SOINFO;
+ if ((__libdl_info.flags & FLAG_LINKED) == 0) {
+ __libdl_info.flags |= FLAG_LINKED;
__libdl_info.strtab = ANDROID_LIBDL_STRTAB;
__libdl_info.symtab = g_libdl_symtab;
__libdl_info.nbucket = sizeof(g_libdl_buckets)/sizeof(unsigned);
__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;
+ __libdl_info.strtab_size = sizeof(ANDROID_LIBDL_STRTAB);
}
return &__libdl_info;
diff --git a/linker/linked_list.h b/linker/linked_list.h
index 8096e62..4e62e20 100644
--- a/linker/linked_list.h
+++ b/linker/linked_list.h
@@ -32,6 +32,9 @@ template<typename T, typename Allocator>
class LinkedList {
public:
LinkedList() : head_(nullptr), tail_(nullptr) {}
+ ~LinkedList() {
+ clear();
+ }
void push_front(T* const element) {
LinkedListEntry<T>* new_entry = Allocator::alloc();
@@ -83,26 +86,54 @@ class LinkedList {
}
template<typename F>
- void for_each(F&& action) {
+ void for_each(F action) {
+ visit([&] (T* si) {
+ action(si);
+ return true;
+ });
+ }
+
+ template<typename F>
+ bool visit(F action) {
for (LinkedListEntry<T>* e = head_; e != nullptr; e = e->next) {
- if (e->element != nullptr) {
- action(e->element);
+ if (!action(e->element)) {
+ return false;
}
}
+ return true;
}
template<typename F>
- void remove_if(F&& predicate) {
- for (LinkedListEntry<T>* e = head_; e != nullptr; e = e->next) {
- if (e->element != nullptr && predicate(e->element)) {
- e->element = nullptr;
+ void remove_if(F predicate) {
+ for (LinkedListEntry<T>* e = head_, *p = nullptr; e != nullptr;) {
+ if (predicate(e->element)) {
+ LinkedListEntry<T>* next = e->next;
+ if (p == nullptr) {
+ head_ = next;
+ } else {
+ p->next = next;
+ }
+ Allocator::free(e);
+ e = next;
+ } else {
+ p = e;
+ e = e->next;
}
}
}
- bool contains(const T* el) {
+ size_t copy_to_array(T* array[], size_t array_length) const {
+ size_t sz = 0;
+ for (LinkedListEntry<T>* e = head_; sz < array_length && e != nullptr; e = e->next) {
+ array[sz++] = e->element;
+ }
+
+ return sz;
+ }
+
+ bool contains(const T* el) const {
for (LinkedListEntry<T>* e = head_; e != nullptr; e = e->next) {
- if (e->element != nullptr && e->element == el) {
+ if (e->element == el) {
return true;
}
}
diff --git a/linker/linker.cpp b/linker/linker.cpp
index cf65705..54867dc 100644
--- a/linker/linker.cpp
+++ b/linker/linker.cpp
@@ -35,14 +35,17 @@
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>
-#include <sys/stat.h>
#include <unistd.h>
+#include <new>
+
// Private C library headers.
#include "private/bionic_tls.h"
#include "private/KernelArgumentBlock.h"
#include "private/ScopedPthreadMutexLocker.h"
#include "private/ScopedFd.h"
+#include "private/ScopeGuard.h"
+#include "private/UniquePtr.h"
#include "linker.h"
#include "linker_debug.h"
@@ -78,7 +81,6 @@ static const char* get_base_name(const char* name) {
#define SEARCH_NAME(x) get_base_name(x)
#endif
-static bool soinfo_link_image(soinfo* si, const android_dlextinfo* extinfo);
static ElfW(Addr) get_elf_exec_load_bias(const ElfW(Ehdr)* elf);
static LinkerAllocator<soinfo> g_soinfo_allocator;
@@ -86,7 +88,7 @@ static LinkerAllocator<LinkedListEntry<soinfo>> 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__)
@@ -96,7 +98,7 @@ static const char* const kDefaultLdPaths[] = {
"/vendor/lib",
"/system/lib",
#endif
- NULL
+ nullptr
};
#define LDPATH_BUFSIZE (LDPATH_MAX*64)
@@ -115,25 +117,25 @@ static soinfo* g_ld_preloads[LDPRELOAD_MAX + 1];
__LIBC_HIDDEN__ int g_ld_debug_verbosity;
-__LIBC_HIDDEN__ abort_msg_t* g_abort_message = NULL; // For debuggerd.
+__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) {
@@ -145,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
@@ -163,14 +165,13 @@ 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));
DISALLOW_ALLOCATION(void*, realloc, (void* u1 __unused, size_t u2 __unused));
DISALLOW_ALLOCATION(void*, calloc, (size_t u1 __unused, size_t u2 __unused));
-static char tmp_err_buf[768];
static char __linker_dl_err_buf[768];
char* linker_get_error_buffer() {
@@ -181,87 +182,84 @@ 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;
-static r_debug _r_debug = {1, NULL, reinterpret_cast<uintptr_t>(&rtld_db_dlactivity), r_debug::RT_CONSISTENT, 0};
+static r_debug _r_debug = {1, nullptr, reinterpret_cast<uintptr_t>(&rtld_db_dlactivity), r_debug::RT_CONSISTENT, 0};
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<char*>(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;
+ // 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<char*>(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;
}
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() {
@@ -284,23 +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) {
+static soinfo* soinfo_alloc(const char* name, struct stat* file_stat, off64_t file_offset) {
if (strlen(name) >= SOINFO_NAME_LEN) {
DL_ERR("library name \"%s\" too long", name);
- return NULL;
+ return nullptr;
}
- soinfo* si = g_soinfo_allocator.alloc();
-
- // Initialize the new element.
- memset(si, 0, sizeof(soinfo));
- strlcpy(si->name, name, sizeof(si->name));
- si->flags = FLAG_NEW_SOINFO;
-
- if (file_stat != NULL) {
- si->set_st_dev(file_stat->st_dev);
- si->set_st_ino(file_stat->st_ino);
- }
+ soinfo* si = new (g_soinfo_allocator.alloc()) soinfo(name, file_stat, file_offset);
sonext->next = si;
sonext = si;
@@ -310,47 +298,47 @@ static soinfo* soinfo_alloc(const char* name, struct stat* file_stat) {
}
static void soinfo_free(soinfo* si) {
- if (si == NULL) {
- return;
- }
+ if (si == nullptr) {
+ return;
+ }
- if (si->base != 0 && si->size != 0) {
- munmap(reinterpret_cast<void*>(si->base), si->size);
- }
+ if (si->base != 0 && si->size != 0) {
+ munmap(reinterpret_cast<void*>(si->base), si->size);
+ }
- soinfo *prev = NULL, *trav;
+ soinfo *prev = nullptr, *trav;
- TRACE("name %s: freeing soinfo @ %p", si->name, si);
+ TRACE("name %s: freeing soinfo @ %p", si->name, si);
- for (trav = solist; trav != NULL; trav = trav->next) {
- if (trav == si)
- break;
- prev = trav;
- }
- if (trav == NULL) {
- /* si was not in solist */
- DL_ERR("name \"%s\" is not in solist!", si->name);
- return;
+ 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();
+ // 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;
- }
+ // 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);
}
static void parse_path(const char* path, const char* delimiters,
const char** array, char* buf, size_t buf_size, size_t max_count) {
- if (path == NULL) {
+ if (path == nullptr) {
return;
}
@@ -367,9 +355,9 @@ static void parse_path(const char* path, const char* delimiters,
// Forget the last path if we had to truncate; this occurs if the 2nd to
// last char isn't '\0' (i.e. wasn't originally a delimiter).
if (i > 0 && len >= buf_size && buf[buf_size - 2] != '\0') {
- array[i - 1] = NULL;
+ array[i - 1] = nullptr;
} else {
- array[i] = NULL;
+ array[i] = nullptr;
}
}
@@ -386,60 +374,58 @@ 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 NULL;
+ }
+ *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 != NULL; 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) {
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<void*>(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 */
+ // only concern ourselves with global and weak symbol definitions
switch (ELF_ST_BIND(s->st_info)) {
case STB_GLOBAL:
case STB_WEAK:
@@ -463,159 +449,204 @@ static ElfW(Sym)* soinfo_elf_lookup(soinfo* si, unsigned hash, const char* name)
name, si->name, reinterpret_cast<void*>(si->base), hash, hash % si->nbucket);
- return NULL;
-}
-
-static unsigned elfhash(const char* _name) {
- const unsigned char* name = reinterpret_cast<const unsigned char*>(_name);
- unsigned h = 0, g;
-
- while (*name) {
- h = (h << 4) + *name++;
- g = h & 0xf0000000;
- h ^= g;
- h ^= g >> 24;
- }
- return h;
+ return nullptr;
}
-static ElfW(Sym)* soinfo_do_lookup(soinfo* si, const char* name, soinfo** lsi, soinfo* needed[]) {
- unsigned elf_hash = elfhash(name);
- ElfW(Sym)* s = NULL;
+soinfo::soinfo(const char* name, const struct stat* file_stat, off64_t file_offset) {
+ memset(this, 0, sizeof(*this));
- if (si != NULL && somain != NULL) {
- /*
- * Local scope is executable scope. Just start looking into it right away
- * for the shortcut.
- */
+ strlcpy(this->name, name, sizeof(this->name));
+ flags = FLAG_NEW_SOINFO;
+ version = SOINFO_VERSION;
- if (si == somain) {
- s = soinfo_elf_lookup(si, elf_hash, name);
- if (s != NULL) {
- *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 (file_stat != nullptr) {
+ this->st_dev = file_stat->st_dev;
+ this->st_ino = file_stat->st_ino;
+ this->file_offset = file_offset;
+ }
+}
- 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 != NULL) {
- *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 != NULL) {
- *lsi = si;
- goto done;
- }
+static unsigned elfhash(const char* _name) {
+ const unsigned char* name = reinterpret_cast<const unsigned char*>(_name);
+ unsigned h = 0, g;
+
+ while (*name) {
+ h = (h << 4) + *name++;
+ g = h & 0xf0000000;
+ h ^= g;
+ h ^= g >> 24;
+ }
+ return h;
+}
- /*
- * 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.
- */
+static ElfW(Sym)* soinfo_do_lookup(soinfo* si, const char* name, soinfo** lsi) {
+ unsigned elf_hash = elfhash(name);
+ ElfW(Sym)* s = nullptr;
+
+ /* "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 = si;
+ }
+ }
- 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 != NULL) {
- *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;
- }
- }
- }
- }
+ 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;
+ }
}
- for (int i = 0; needed[i] != NULL; i++) {
- DEBUG("%s: looking up %s in %s",
- si->name, name, needed[i]->name);
- s = soinfo_elf_lookup(needed[i], elf_hash, name);
- if (s != NULL) {
- *lsi = needed[i];
- goto done;
+ // 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;
}
+ }
}
+ }
-done:
- if (s != NULL) {
- TRACE_TYPE(LOOKUP, "si %s sym %s s->st_value = %p, "
- "found in %s, base = %p, load bias = %p",
- si->name, name, reinterpret_cast<void*>(s->st_value),
- (*lsi)->name, reinterpret_cast<void*>((*lsi)->base),
- reinterpret_cast<void*>((*lsi)->load_bias));
- return s;
+ /* 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 && !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;
}
+ }
+
+ 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;
+ });
+ }
- return NULL;
+ 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<void*>(s->st_value),
+ (*lsi)->name, reinterpret_cast<void*>((*lsi)->base),
+ reinterpret_cast<void*>((*lsi)->load_bias));
+ }
+
+ return s;
}
-// Another soinfo list allocator to use in dlsym. We don't reuse
-// SoinfoListAllocator because it is write-protected most of the time.
-static LinkerAllocator<LinkedListEntry<soinfo>> g_soinfo_list_allocator_rw;
-class SoinfoListAllocatorRW {
+// Each size has it's own allocator.
+template<size_t size>
+class SizeBasedAllocator {
+ public:
+ static void* alloc() {
+ return allocator_.alloc();
+ }
+
+ static void free(void* ptr) {
+ allocator_.free(ptr);
+ }
+
+ private:
+ static LinkerBlockAllocator allocator_;
+};
+
+template<size_t size>
+LinkerBlockAllocator SizeBasedAllocator<size>::allocator_(size);
+
+template<typename T>
+class TypeBasedAllocator {
+ public:
+ static T* alloc() {
+ return reinterpret_cast<T*>(SizeBasedAllocator<sizeof(T)>::alloc());
+ }
+
+ static void free(T* ptr) {
+ SizeBasedAllocator<sizeof(T)>::free(ptr);
+ }
+};
+
+class LoadTask {
public:
- static LinkedListEntry<soinfo>* alloc() {
- return g_soinfo_list_allocator_rw.alloc();
+ struct deleter_t {
+ void operator()(LoadTask* t) {
+ TypeBasedAllocator<LoadTask>::free(t);
+ }
+ };
+
+ typedef UniquePtr<LoadTask, deleter_t> unique_ptr;
+
+ static deleter_t deleter;
+
+ static LoadTask* create(const char* name, soinfo* needed_by) {
+ LoadTask* ptr = TypeBasedAllocator<LoadTask>::alloc();
+ return new (ptr) LoadTask(name, needed_by);
}
- static void free(LinkedListEntry<soinfo>* ptr) {
- g_soinfo_list_allocator_rw.free(ptr);
+ const char* get_name() const {
+ return name_;
}
+
+ soinfo* get_needed_by() const {
+ return needed_by_;
+ }
+ private:
+ LoadTask(const char* name, soinfo* needed_by)
+ : name_(name), needed_by_(needed_by) {}
+
+ const char* name_;
+ soinfo* needed_by_;
+
+ DISALLOW_IMPLICIT_CONSTRUCTORS(LoadTask);
};
+LoadTask::deleter_t LoadTask::deleter;
+
+template <typename T>
+using linked_list_t = LinkedList<T, TypeBasedAllocator<LinkedListEntry<T>>>;
+
+typedef linked_list_t<soinfo> SoinfoLinkedList;
+typedef linked_list_t<const char> StringLinkedList;
+typedef linked_list_t<LoadTask> 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) {
- LinkedList<soinfo, SoinfoListAllocatorRW> visit_list;
- LinkedList<soinfo, SoinfoListAllocatorRW> visited;
+ SoinfoLinkedList visit_list;
+ SoinfoLinkedList visited;
+
visit_list.push_back(si);
soinfo* current_soinfo;
while ((current_soinfo = visit_list.pop_front()) != nullptr) {
@@ -627,8 +658,6 @@ ElfW(Sym)* dlsym_handle_lookup(soinfo* si, soinfo** found, const char* name) {
if (result != nullptr) {
*found = current_soinfo;
- visit_list.clear();
- visited.clear();
return result;
}
visited.push_back(current_soinfo);
@@ -638,8 +667,6 @@ ElfW(Sym)* dlsym_handle_lookup(soinfo* si, soinfo** found, const char* name) {
});
}
- visit_list.clear();
- visited.clear();
return nullptr;
}
@@ -651,20 +678,20 @@ ElfW(Sym)* dlsym_handle_lookup(soinfo* si, soinfo** found, const char* name) {
ElfW(Sym)* dlsym_linear_lookup(const char* name, soinfo** found, soinfo* start) {
unsigned elf_hash = elfhash(name);
- if (start == NULL) {
+ if (start == nullptr) {
start = solist;
}
- ElfW(Sym)* s = NULL;
- for (soinfo* si = start; (s == NULL) && (si != NULL); si = si->next) {
+ ElfW(Sym)* s = nullptr;
+ for (soinfo* si = start; (s == nullptr) && (si != nullptr); si = si->next) {
s = soinfo_elf_lookup(si, elf_hash, name);
- if (s != NULL) {
+ if (s != nullptr) {
*found = si;
break;
}
}
- if (s != NULL) {
+ if (s != nullptr) {
TRACE_TYPE(LOOKUP, "%s s->st_value = %p, found->base = %p",
name, reinterpret_cast<void*>(s->st_value), reinterpret_cast<void*>((*found)->base));
}
@@ -674,12 +701,12 @@ ElfW(Sym)* dlsym_linear_lookup(const char* name, soinfo** found, soinfo* start)
soinfo* find_containing_library(const void* p) {
ElfW(Addr) address = reinterpret_cast<ElfW(Addr)>(p);
- for (soinfo* si = solist; si != NULL; si = si->next) {
+ for (soinfo* si = solist; si != nullptr; si = si->next) {
if (address >= si->base && address - si->base < si->size) {
return si;
}
}
- return NULL;
+ return nullptr;
}
ElfW(Sym)* dladdr_find_symbol(soinfo* si, const void* addr) {
@@ -696,12 +723,12 @@ ElfW(Sym)* dladdr_find_symbol(soinfo* si, const void* addr) {
}
}
- return NULL;
+ return nullptr;
}
static int open_library_on_path(const char* name, const char* const paths[]) {
char buf[512];
- for (size_t i = 0; paths[i] != NULL; ++i) {
+ for (size_t i = 0; paths[i] != nullptr; ++i) {
int n = __libc_format_buffer(buf, sizeof(buf), "%s/%s", paths[i], name);
if (n < 0 || n >= static_cast<int>(sizeof(buf))) {
PRINT("Warning: ignoring very long library path: %s/%s", paths[i], name);
@@ -719,7 +746,7 @@ static int open_library(const char* name) {
TRACE("[ opening %s ]", name);
// If the name contains a slash, we should attempt to open it directly and not search the paths.
- if (strchr(name, '/') != NULL) {
+ if (strchr(name, '/') != nullptr) {
int fd = TEMP_FAILURE_RETRY(open(name, O_RDONLY | O_CLOEXEC));
if (fd != -1) {
return fd;
@@ -738,112 +765,218 @@ static int open_library(const char* name) {
return fd;
}
-static soinfo* load_library(const char* name, int dlflags, const android_dlextinfo* extinfo) {
- int fd = -1;
- ScopedFd file_guard(-1);
+template<typename F>
+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->get_string(d->d_un.d_val));
+ }
+ }
+}
- if (extinfo != NULL && (extinfo->flags & ANDROID_DLEXT_USE_LIBRARY_FD) != 0) {
- fd = extinfo->library_fd;
- } else {
- // Open the file.
- fd = open_library(name);
- if (fd == -1) {
- DL_ERR("library \"%s\" not found", name);
- return NULL;
- }
+static soinfo* load_library(LoadTaskList& load_tasks, const char* name, int dlflags, const android_dlextinfo* extinfo) {
+ int fd = -1;
+ off64_t file_offset = 0;
+ ScopedFd file_guard(-1);
- file_guard.reset(fd);
+ if (extinfo != nullptr && (extinfo->flags & ANDROID_DLEXT_USE_LIBRARY_FD) != 0) {
+ fd = extinfo->library_fd;
+ if ((extinfo->flags & ANDROID_DLEXT_USE_LIBRARY_FD_OFFSET) != 0) {
+ file_offset = extinfo->library_fd_offset;
+ }
+ } else {
+ // Open the file.
+ fd = open_library(name);
+ if (fd == -1) {
+ DL_ERR("library \"%s\" not found", name);
+ return nullptr;
}
- ElfReader elf_reader(name, fd);
+ file_guard.reset(fd);
+ }
- struct stat file_stat;
- if (TEMP_FAILURE_RETRY(fstat(fd, &file_stat)) != 0) {
- DL_ERR("unable to stat file for the library %s: %s", name, strerror(errno));
- return NULL;
- }
+ if ((file_offset % PAGE_SIZE) != 0) {
+ DL_ERR("file offset for the library \"%s\" is not page-aligned: %" PRId64, name, file_offset);
+ return nullptr;
+ }
- // Check for symlink and other situations where
- // file can have different names.
- for (soinfo* si = solist; si != NULL; si = si->next) {
- if (si->get_st_dev() != 0 &&
- si->get_st_ino() != 0 &&
- si->get_st_dev() == file_stat.st_dev &&
- si->get_st_ino() == file_stat.st_ino) {
- TRACE("library \"%s\" is already loaded under different name/path \"%s\" - will return existing soinfo", name, si->name);
- return si;
- }
- }
+ struct stat file_stat;
+ if (TEMP_FAILURE_RETRY(fstat(fd, &file_stat)) != 0) {
+ DL_ERR("unable to stat file for the library \"%s\": %s", name, strerror(errno));
+ return nullptr;
+ }
- if ((dlflags & RTLD_NOLOAD) != 0) {
- return NULL;
+ // Check for symlink and other situations where
+ // file can have different names.
+ for (soinfo* si = solist; si != nullptr; si = si->next) {
+ if (si->get_st_dev() != 0 &&
+ si->get_st_ino() != 0 &&
+ si->get_st_dev() == file_stat.st_dev &&
+ si->get_st_ino() == file_stat.st_ino &&
+ si->get_file_offset() == file_offset) {
+ TRACE("library \"%s\" is already loaded under different name/path \"%s\" - will return existing soinfo", name, si->name);
+ return si;
}
+ }
- // Read the ELF header and load the segments.
- if (!elf_reader.Load(extinfo)) {
- return NULL;
- }
+ if ((dlflags & RTLD_NOLOAD) != 0) {
+ DL_ERR("library \"%s\" wasn't loaded and RTLD_NOLOAD prevented it", name);
+ return nullptr;
+ }
- soinfo* si = soinfo_alloc(SEARCH_NAME(name), &file_stat);
- if (si == NULL) {
- return NULL;
- }
- si->base = elf_reader.load_start();
- si->size = elf_reader.load_size();
- si->load_bias = elf_reader.load_bias();
- si->phnum = elf_reader.phdr_count();
- si->phdr = elf_reader.loaded_phdr();
-
- // At this point we know that whatever is loaded @ base is a valid ELF
- // shared library whose segments are properly mapped in.
- TRACE("[ load_library base=%p size=%zu name='%s' ]",
- reinterpret_cast<void*>(si->base), si->size, si->name);
-
- if (!soinfo_link_image(si, extinfo)) {
- soinfo_free(si);
- return NULL;
- }
+ // Read the ELF header and load the segments.
+ ElfReader elf_reader(name, fd, file_offset);
+ if (!elf_reader.Load(extinfo)) {
+ return nullptr;
+ }
+
+ soinfo* si = soinfo_alloc(SEARCH_NAME(name), &file_stat, file_offset);
+ if (si == nullptr) {
+ return nullptr;
+ }
+ si->base = elf_reader.load_start();
+ si->size = elf_reader.load_size();
+ si->load_bias = elf_reader.load_bias();
+ si->phnum = elf_reader.phdr_count();
+ si->phdr = elf_reader.loaded_phdr();
+
+ if (!si->PrelinkImage()) {
+ soinfo_free(si);
+ return nullptr;
+ }
- return si;
+ for_each_dt_needed(si, [&] (const char* name) {
+ load_tasks.push_back(LoadTask::create(name, si));
+ });
+
+ return si;
}
static soinfo *find_loaded_library_by_name(const char* name) {
const char* search_name = SEARCH_NAME(name);
- for (soinfo* si = solist; si != NULL; si = si->next) {
+ for (soinfo* si = solist; si != nullptr; si = si->next) {
if (!strcmp(search_name, si->name)) {
return si;
}
}
- return NULL;
+ return nullptr;
}
-static soinfo* find_library_internal(const char* name, int dlflags, const android_dlextinfo* extinfo) {
- if (name == NULL) {
- return somain;
- }
+static soinfo* find_library_internal(LoadTaskList& load_tasks, const char* name, int dlflags, const android_dlextinfo* extinfo) {
soinfo* si = find_loaded_library_by_name(name);
// Library might still be loaded, the accurate detection
- // of this fact is done by load_library
- if (si == NULL) {
+ // 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(name, dlflags, extinfo);
+ si = load_library(load_tasks, name, dlflags, extinfo);
+ }
+
+ return si;
+}
+
+static void soinfo_unload(soinfo* si);
+
+static bool is_recursive(soinfo* si, soinfo* parent) {
+ if (parent == nullptr) {
+ return false;
}
- if (si != NULL && (si->flags & FLAG_LINKED) == 0) {
+ if (si == parent) {
DL_ERR("recursive link to \"%s\"", si->name);
- return NULL;
+ return true;
}
- return si;
+ return !parent->get_parents().visit([&](soinfo* grandparent) {
+ return !is_recursive(si, grandparent);
+ });
}
-static soinfo* find_library(const char* name, int dlflags, const android_dlextinfo* extinfo) {
- soinfo* si = find_library_internal(name, dlflags, extinfo);
- if (si != NULL) {
+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) {
+ // Step 0: prepare.
+ LoadTaskList load_tasks;
+ for (size_t i = 0; i < library_names_size; ++i) {
+ const char* name = library_names[i];
+ load_tasks.push_back(LoadTask::create(name, nullptr));
+ }
+
+ // 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;
+
+ auto failure_guard = make_scope_guard([&]() {
+ // Housekeeping
+ load_tasks.for_each([] (LoadTask* t) {
+ LoadTask::deleter(t);
+ });
+
+ for (size_t i = 0; i<soinfos_size; ++i) {
+ soinfo_unload(soinfos[i]);
+ }
+ });
+
+ // 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);
+ if (si == nullptr) {
+ return false;
+ }
+
+ soinfo* needed_by = task->get_needed_by();
+
+ if (is_recursive(si, needed_by)) {
+ return false;
+ }
+
si->ref_count++;
+ if (needed_by != nullptr) {
+ needed_by->add_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;
+ }
+
+ if (soinfos_size<library_names_size) {
+ soinfos[soinfos_size++] = si;
+ }
+ }
+
+ // Step 2: link libraries.
+ soinfo* si;
+ while ((si = found_libs.pop_front()) != nullptr) {
+ if ((si->flags & FLAG_LINKED) == 0) {
+ if (!si->LinkImage(extinfo)) {
+ return false;
+ }
+ si->flags |= FLAG_LINKED;
+ }
+ }
+
+ // All is well - found_libs and load_tasks are empty at this point
+ // and all libs are successfully linked.
+ failure_guard.disable();
+ return true;
+}
+
+static soinfo* find_library(const char* name, int dlflags, const android_dlextinfo* extinfo) {
+ if (name == nullptr) {
+ somain->ref_count++;
+ return somain;
}
+
+ soinfo* si;
+
+ if (!find_libraries(&name, 1, &si, nullptr, 0, dlflags, extinfo)) {
+ return nullptr;
+ }
+
return si;
}
@@ -852,26 +985,24 @@ static void soinfo_unload(soinfo* si) {
TRACE("unloading '%s'", si->name);
si->CallDestructors();
- if ((si->flags | FLAG_NEW_SOINFO) != 0) {
- si->get_children().for_each([&] (soinfo* child) {
+ if (si->has_min_version(0)) {
+ soinfo* child = nullptr;
+ while ((child = si->get_children().pop_front()) != nullptr) {
TRACE("%s needs to unload %s", si->name, child->name);
soinfo_unload(child);
- });
+ }
} else {
- for (ElfW(Dyn)* d = si->dynamic; d->d_tag != DT_NULL; ++d) {
- if (d->d_tag == DT_NEEDED) {
- const char* library_name = si->strtab + d->d_un.d_val;
- TRACE("%s needs to unload %s", si->name, library_name);
- soinfo* needed = find_library(library_name, RTLD_NOLOAD, NULL);
- if (needed != NULL) {
- soinfo_unload(needed);
- } else {
- // Not found: for example if symlink was deleted between dlopen and dlclose
- // Since we cannot really handle errors at this point - print and continue.
- PRINT("warning: couldn't find %s needed by %s on unload.", library_name, si->name);
- }
+ for_each_dt_needed(si, [&] (const char* library_name) {
+ TRACE("deprecated (old format of soinfo): %s needs to unload %s", si->name, library_name);
+ soinfo* needed = find_library(library_name, RTLD_NOLOAD, nullptr);
+ if (needed != nullptr) {
+ soinfo_unload(needed);
+ } else {
+ // Not found: for example if symlink was deleted between dlopen and dlclose
+ // Since we cannot really handle errors at this point - print and continue.
+ PRINT("warning: couldn't find %s needed by %s on unload.", library_name, si->name);
}
- }
+ });
}
notify_gdb_of_unload(si);
@@ -910,15 +1041,22 @@ 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) {
DL_ERR("invalid flags to dlopen: %x", flags);
- return NULL;
+ return nullptr;
}
- if (extinfo != NULL && ((extinfo->flags & ~(ANDROID_DLEXT_VALID_FLAG_BITS)) != 0)) {
- DL_ERR("invalid extended flags to android_dlopen_ext: %" PRIx64, extinfo->flags);
- return NULL;
+ if (extinfo != nullptr) {
+ if ((extinfo->flags & ~(ANDROID_DLEXT_VALID_FLAG_BITS)) != 0) {
+ DL_ERR("invalid extended flags to android_dlopen_ext: 0x%" PRIx64, extinfo->flags);
+ return nullptr;
+ }
+ if ((extinfo->flags & ANDROID_DLEXT_USE_LIBRARY_FD) == 0 &&
+ (extinfo->flags & ANDROID_DLEXT_USE_LIBRARY_FD_OFFSET) != 0) {
+ DL_ERR("invalid extended flag combination (ANDROID_DLEXT_USE_LIBRARY_FD_OFFSET without ANDROID_DLEXT_USE_LIBRARY_FD): 0x%" PRIx64, extinfo->flags);
+ return nullptr;
+ }
}
protect_data(PROT_READ | PROT_WRITE);
soinfo* si = find_library(name, flags, extinfo);
- if (si != NULL) {
+ if (si != nullptr) {
si->CallConstructors();
}
protect_data(PROT_READ);
@@ -931,30 +1069,40 @@ void do_dlclose(soinfo* si) {
protect_data(PROT_READ);
}
-#if defined(USE_RELA)
-static int soinfo_relocate(soinfo* si, ElfW(Rela)* rela, unsigned count, soinfo* needed[]) {
- ElfW(Sym)* s;
- soinfo* lsi;
+static ElfW(Addr) call_ifunc_resolver(ElfW(Addr) resolver_addr) {
+ typedef ElfW(Addr) (*ifunc_resolver_t)(void);
+ ifunc_resolver_t ifunc_resolver = reinterpret_cast<ifunc_resolver_t>(resolver_addr);
+ ElfW(Addr) ifunc_addr = ifunc_resolver();
+ TRACE_TYPE(RELO, "Called ifunc_resolver@%p. The result is %p", ifunc_resolver, reinterpret_cast<void*>(ifunc_addr));
+
+ return ifunc_addr;
+}
+#if defined(USE_RELA)
+int soinfo::Relocate(ElfW(Rela)* rela, unsigned count) {
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);
- ElfW(Addr) reloc = static_cast<ElfW(Addr)>(rela->r_offset + si->load_bias);
+ ElfW(Addr) reloc = static_cast<ElfW(Addr)>(rela->r_offset + load_bias);
ElfW(Addr) sym_addr = 0;
- const char* sym_name = NULL;
+ const char* sym_name = nullptr;
- DEBUG("Processing '%s' relocation at index %zd", si->name, idx);
+ 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<const char*>(si->strtab + si->symtab[sym].st_name);
- s = soinfo_do_lookup(si, sym_name, &lsi, needed);
- if (s == NULL) {
+ 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...
- s = &si->symtab[sym];
+ s = &symtab[sym];
if (ELF_ST_BIND(s->st_info) != STB_WEAK) {
- DL_ERR("cannot locate symbol \"%s\" referenced by \"%s\"...", sym_name, si->name);
+ DL_ERR("cannot locate symbol \"%s\" referenced by \"%s\"...", sym_name, name);
return -1;
}
@@ -972,151 +1120,158 @@ static int soinfo_relocate(soinfo* si, ElfW(Rela)* rela, unsigned count, soinfo*
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:
- /*
- * 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:
- // 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.
- sym_addr = static_cast<ElfW(Addr)>(s->st_value + lsi->load_bias);
+ sym_addr = lsi->resolve_symbol_address(s);
}
count_relocation(kRelocSymbol);
- } else {
- s = NULL;
}
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<ElfW(Addr)*>(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<ElfW(Addr)*>(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<ElfW(Addr)*>(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<ElfW(Addr)>(INT32_MIN) <= (*reinterpret_cast<ElfW(Addr)*>(reloc) + (sym_addr + rela->r_addend))) &&
((*reinterpret_cast<ElfW(Addr)*>(reloc) + (sym_addr + rela->r_addend)) <= static_cast<ElfW(Addr)>(UINT32_MAX))) {
- *reinterpret_cast<ElfW(Addr)*>(reloc) += (sym_addr + rela->r_addend);
+ *reinterpret_cast<ElfW(Addr)*>(reloc) += (sym_addr + rela->r_addend);
} else {
- DL_ERR("0x%016llx out of range 0x%016llx to 0x%016llx",
- (*reinterpret_cast<ElfW(Addr)*>(reloc) + (sym_addr + rela->r_addend)),
- static_cast<ElfW(Addr)>(INT32_MIN),
- static_cast<ElfW(Addr)>(UINT32_MAX));
- return -1;
+ DL_ERR("0x%016llx out of range 0x%016llx to 0x%016llx",
+ (*reinterpret_cast<ElfW(Addr)*>(reloc) + (sym_addr + rela->r_addend)),
+ static_cast<ElfW(Addr)>(INT32_MIN),
+ static_cast<ElfW(Addr)>(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<ElfW(Addr)>(INT16_MIN) <= (*reinterpret_cast<ElfW(Addr)*>(reloc) + (sym_addr + rela->r_addend))) &&
((*reinterpret_cast<ElfW(Addr)*>(reloc) + (sym_addr + rela->r_addend)) <= static_cast<ElfW(Addr)>(UINT16_MAX))) {
- *reinterpret_cast<ElfW(Addr)*>(reloc) += (sym_addr + rela->r_addend);
+ *reinterpret_cast<ElfW(Addr)*>(reloc) += (sym_addr + rela->r_addend);
} else {
- DL_ERR("0x%016llx out of range 0x%016llx to 0x%016llx",
- (*reinterpret_cast<ElfW(Addr)*>(reloc) + (sym_addr + rela->r_addend)),
- static_cast<ElfW(Addr)>(INT16_MIN),
- static_cast<ElfW(Addr)>(UINT16_MAX));
- return -1;
+ DL_ERR("0x%016llx out of range 0x%016llx to 0x%016llx",
+ (*reinterpret_cast<ElfW(Addr)*>(reloc) + (sym_addr + rela->r_addend)),
+ static_cast<ElfW(Addr)>(INT16_MIN),
+ static_cast<ElfW(Addr)>(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<ElfW(Addr)*>(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<ElfW(Addr)>(INT32_MIN) <= (*reinterpret_cast<ElfW(Addr)*>(reloc) + ((sym_addr + rela->r_addend) - rela->r_offset))) &&
((*reinterpret_cast<ElfW(Addr)*>(reloc) + ((sym_addr + rela->r_addend) - rela->r_offset)) <= static_cast<ElfW(Addr)>(UINT32_MAX))) {
- *reinterpret_cast<ElfW(Addr)*>(reloc) += ((sym_addr + rela->r_addend) - rela->r_offset);
+ *reinterpret_cast<ElfW(Addr)*>(reloc) += ((sym_addr + rela->r_addend) - rela->r_offset);
} else {
- DL_ERR("0x%016llx out of range 0x%016llx to 0x%016llx",
- (*reinterpret_cast<ElfW(Addr)*>(reloc) + ((sym_addr + rela->r_addend) - rela->r_offset)),
- static_cast<ElfW(Addr)>(INT32_MIN),
- static_cast<ElfW(Addr)>(UINT32_MAX));
- return -1;
+ DL_ERR("0x%016llx out of range 0x%016llx to 0x%016llx",
+ (*reinterpret_cast<ElfW(Addr)*>(reloc) + ((sym_addr + rela->r_addend) - rela->r_offset)),
+ static_cast<ElfW(Addr)>(INT32_MIN),
+ static_cast<ElfW(Addr)>(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<ElfW(Addr)>(INT16_MIN) <= (*reinterpret_cast<ElfW(Addr)*>(reloc) + ((sym_addr + rela->r_addend) - rela->r_offset))) &&
((*reinterpret_cast<ElfW(Addr)*>(reloc) + ((sym_addr + rela->r_addend) - rela->r_offset)) <= static_cast<ElfW(Addr)>(UINT16_MAX))) {
- *reinterpret_cast<ElfW(Addr)*>(reloc) += ((sym_addr + rela->r_addend) - rela->r_offset);
+ *reinterpret_cast<ElfW(Addr)*>(reloc) += ((sym_addr + rela->r_addend) - rela->r_offset);
} else {
- DL_ERR("0x%016llx out of range 0x%016llx to 0x%016llx",
- (*reinterpret_cast<ElfW(Addr)*>(reloc) + ((sym_addr + rela->r_addend) - rela->r_offset)),
- static_cast<ElfW(Addr)>(INT16_MIN),
- static_cast<ElfW(Addr)>(UINT16_MAX));
- return -1;
+ DL_ERR("0x%016llx out of range 0x%016llx to 0x%016llx",
+ (*reinterpret_cast<ElfW(Addr)*>(reloc) + ((sym_addr + rela->r_addend) - rela->r_offset)),
+ static_cast<ElfW(Addr)>(INT16_MIN),
+ static_cast<ElfW(Addr)>(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, (si->base + rela->r_addend));
- *reinterpret_cast<ElfW(Addr)*>(reloc) = (si->base + rela->r_addend);
+ reloc, (base + rela->r_addend));
+ *reinterpret_cast<ElfW(Addr)*>(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<ElfW(Addr)*>(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.
*
@@ -1126,328 +1281,341 @@ static int soinfo_relocate(soinfo* si, ElfW(Rela)* rela, unsigned count, soinfo*
* R_AARCH64_COPY may only appear in executable objects where e_type is
* set to ET_EXEC.
*/
- DL_ERR("%s R_AARCH64_COPY relocations are not supported", si->name);
+ 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<size_t>(reloc),
- static_cast<size_t>(sym_addr + rela->r_addend), sym_name);
- *reinterpret_cast<ElfW(Addr)*>(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<size_t>(reloc),
- static_cast<size_t>(sym_addr + rela->r_addend), sym_name);
- *reinterpret_cast<ElfW(Addr)*>(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<size_t>(reloc),
- static_cast<size_t>(si->base));
- *reinterpret_cast<ElfW(Addr)*>(reloc) = si->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<size_t>(reloc),
- static_cast<size_t>(sym_addr), sym_name);
- *reinterpret_cast<ElfW(Addr)*>(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<size_t>(reloc),
- static_cast<size_t>(sym_addr), sym_name);
- *reinterpret_cast<ElfW(Addr)*>(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<size_t>(reloc), static_cast<size_t>(sym_addr - reloc),
- static_cast<size_t>(sym_addr), static_cast<size_t>(reloc), sym_name);
- *reinterpret_cast<ElfW(Addr)*>(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<size_t>(reloc),
+ static_cast<size_t>(sym_addr + rela->r_addend), sym_name);
+ *reinterpret_cast<ElfW(Addr)*>(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<size_t>(reloc),
+ static_cast<size_t>(sym_addr + rela->r_addend), sym_name);
+ *reinterpret_cast<ElfW(Addr)*>(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<size_t>(reloc),
+ static_cast<size_t>(base));
+ *reinterpret_cast<ElfW(Addr)*>(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<ElfW(Addr)*>(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<size_t>(reloc),
+ static_cast<size_t>(sym_addr), sym_name);
+ *reinterpret_cast<ElfW(Addr)*>(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<size_t>(reloc),
+ static_cast<size_t>(sym_addr), sym_name);
+ *reinterpret_cast<ElfW(Addr)*>(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<size_t>(reloc), static_cast<size_t>(sym_addr - reloc),
+ static_cast<size_t>(sym_addr), static_cast<size_t>(reloc), sym_name);
+ *reinterpret_cast<ElfW(Addr)*>(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;
}
#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<ElfW(Addr)>(rel->r_offset + load_bias);
+ ElfW(Addr) sym_addr = 0;
+ const char* sym_name = nullptr;
-static int soinfo_relocate(soinfo* si, ElfW(Rel)* rel, unsigned count, soinfo* needed[]) {
- ElfW(Sym)* s;
- soinfo* lsi;
-
- 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<ElfW(Addr)>(rel->r_offset + si->load_bias);
- ElfW(Addr) sym_addr = 0;
- const char* sym_name = NULL;
-
- DEBUG("Processing '%s' relocation at index %zd", si->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 = 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...
+ 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;
}
- if (sym != 0) {
- sym_name = reinterpret_cast<const char*>(si->strtab + si->symtab[sym].st_name);
- s = soinfo_do_lookup(si, sym_name, &lsi, needed);
- if (s == NULL) {
- // We only allow an undefined symbol if this is a weak reference...
- s = &si->symtab[sym];
- if (ELF_ST_BIND(s->st_info) != STB_WEAK) {
- DL_ERR("cannot locate symbol \"%s\" referenced by \"%s\"...", sym_name, si->name);
- return -1;
- }
-
- /* 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) {
+
+ /* 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;
+ 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. */
- // 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;
+ 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.
+ 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 = static_cast<ElfW(Addr)>(s->st_value + lsi->load_bias);
- }
- count_relocation(kRelocSymbol);
- } else {
- s = NULL;
+ 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);
+ }
- switch (type) {
+ 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<ElfW(Addr)*>(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<ElfW(Addr)*>(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<ElfW(Addr)*>(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<ElfW(Addr)*>(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", si->name);
- return -1;
+ 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<ElfW(Addr)*>(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<ElfW(Addr)*>(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<ElfW(Addr)*>(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<ElfW(Addr)*>(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<ElfW(Addr)*>(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<ElfW(Addr)*>(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<ElfW(Addr)*>(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<ElfW(Addr)*>(reloc) += (sym_addr - reloc);
- break;
+ 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<ElfW(Addr)*>(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<ElfW(Addr)*>(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<ElfW(Addr)*>(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<ElfW(Addr)*>(reloc) += (sym_addr - reloc);
+ break;
#elif defined(__mips__)
- case R_MIPS_REL32:
+ 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;
- }
+ // 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<size_t>(reloc),
- static_cast<size_t>(sym_addr), sym_name ? sym_name : "*SECTIONHDR*");
- if (s) {
- *reinterpret_cast<ElfW(Addr)*>(reloc) += sym_addr;
- } else {
- *reinterpret_cast<ElfW(Addr)*>(reloc) += si->base;
- }
- break;
+ count_relocation(kRelocAbsolute);
+ MARK(rel->r_offset);
+ TRACE_TYPE(RELO, "RELO REL32 %08zx <- %08zx %s", static_cast<size_t>(reloc),
+ static_cast<size_t>(sym_addr), sym_name ? sym_name : "*SECTIONHDR*");
+ if (s) {
+ *reinterpret_cast<ElfW(Addr)*>(reloc) += sym_addr;
+ } else {
+ *reinterpret_cast<ElfW(Addr)*>(reloc) += base;
+ }
+ break;
#endif
#if defined(__arm__)
- case R_ARM_RELATIVE:
+ case R_ARM_RELATIVE:
#elif defined(__i386__)
- case R_386_RELATIVE:
+ 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<void*>(reloc), reinterpret_cast<void*>(si->base));
- *reinterpret_cast<ElfW(Addr)*>(reloc) += si->base;
- break;
-
- default:
- DL_ERR("unknown reloc type %d @ %p (%zu)", type, rel, idx);
- return -1;
+ 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<void*>(reloc), reinterpret_cast<void*>(base));
+ *reinterpret_cast<ElfW(Addr)*>(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<void*>(reloc), reinterpret_cast<void*>(base));
+ *reinterpret_cast<ElfW(Addr)*>(reloc) = call_ifunc_resolver(base + *reinterpret_cast<ElfW(Addr)*>(reloc));
+ break;
+#endif
+
+ default:
+ DL_ERR("unknown reloc type %d @ %p (%zu)", type, rel, idx);
+ return -1;
}
- return 0;
+ }
+ return 0;
}
#endif
#if defined(__mips__)
-static bool mips_relocate_got(soinfo* si, soinfo* needed[]) {
- ElfW(Addr)** got = si->plt_got;
- if (got == NULL) {
- return true;
+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<ElfW(Addr)*>(0xdeadbeef);
+ if (reinterpret_cast<intptr_t>(got[g]) < 0) {
+ got[g++] = reinterpret_cast<ElfW(Addr)*>(0xdeadfeed);
}
- 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<ElfW(Addr)*>(0xdeadbeef);
- if (reinterpret_cast<intptr_t>(got[g]) < 0) {
- got[g++] = reinterpret_cast<ElfW(Addr)*>(0xdeadfeed);
- }
- // Relocate the local GOT entries.
- for (; g < local_gotno; g++) {
- got[g] = reinterpret_cast<ElfW(Addr)*>(reinterpret_cast<uintptr_t>(got[g]) + si->load_bias);
- }
+ // Relocate the local GOT entries.
+ for (; g < local_gotno; g++) {
+ got[g] = reinterpret_cast<ElfW(Addr)*>(reinterpret_cast<uintptr_t>(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;
- ElfW(Sym)* s = soinfo_do_lookup(si, sym_name, &lsi, needed);
- if (s == NULL) {
- // 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<ElfW(Addr)*>(lsi->load_bias + s->st_value);
- }
+ // 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->get_string(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<ElfW(Addr)*>(lsi->resolve_symbol_address(s));
}
- return true;
+ }
+ return true;
}
#endif
void soinfo::CallArray(const char* array_name __unused, linker_function_t* functions, size_t count, bool reverse) {
- if (functions == NULL) {
+ if (functions == nullptr) {
return;
}
@@ -1466,7 +1634,7 @@ void soinfo::CallArray(const char* array_name __unused, linker_function_t* funct
}
void soinfo::CallFunction(const char* function_name __unused, linker_function_t function) {
- if (function == NULL || reinterpret_cast<uintptr_t>(function) == static_cast<uintptr_t>(-1)) {
+ if (function == nullptr || reinterpret_cast<uintptr_t>(function) == static_cast<uintptr_t>(-1)) {
return;
}
@@ -1502,7 +1670,7 @@ void soinfo::CallConstructors() {
// out above, the libc constructor will be called again (recursively!).
constructors_called = true;
- if ((flags & FLAG_EXE) == 0 && preinit_array != NULL) {
+ if ((flags & FLAG_EXE) == 0 && preinit_array != nullptr) {
// The GNU dynamic linker silently ignores these, but we warn the developer.
PRINT("\"%s\": ignoring %zd-entry DT_PREINIT_ARRAY in shared library!",
name, preinit_array_count);
@@ -1520,6 +1688,9 @@ void soinfo::CallConstructors() {
}
void soinfo::CallDestructors() {
+ if (!constructors_called) {
+ return;
+ }
TRACE("\"%s\": calling destructors", name);
// DT_FINI_ARRAY must be parsed in reverse order.
@@ -1534,16 +1705,14 @@ void soinfo::CallDestructors() {
}
void soinfo::add_child(soinfo* child) {
- if ((this->flags & FLAG_NEW_SOINFO) == 0) {
- return;
+ if (has_min_version(0)) {
+ child->parents.push_back(this);
+ this->children.push_back(child);
}
-
- this->children.push_front(child);
- child->parents.push_front(this);
}
void soinfo::remove_all_links() {
- if ((this->flags & FLAG_NEW_SOINFO) == 0) {
+ if (!has_min_version(0)) {
return;
}
@@ -1555,7 +1724,7 @@ void soinfo::remove_all_links() {
});
parents.for_each([&] (soinfo* parent) {
- parent->children.for_each([&] (const soinfo* child) {
+ parent->children.remove_if([&] (const soinfo* child) {
return child == this;
});
});
@@ -1565,468 +1734,533 @@ void soinfo::remove_all_links() {
children.clear();
}
-void soinfo::set_st_dev(dev_t dev) {
- if ((this->flags & FLAG_NEW_SOINFO) == 0) {
- return;
+dev_t soinfo::get_st_dev() {
+ if (has_min_version(0)) {
+ return st_dev;
}
- st_dev = dev;
-}
+ return 0;
+};
-void soinfo::set_st_ino(ino_t ino) {
- if ((this->flags & FLAG_NEW_SOINFO) == 0) {
- return;
+ino_t soinfo::get_st_ino() {
+ if (has_min_version(0)) {
+ return st_ino;
}
- st_ino = ino;
+ return 0;
}
-dev_t soinfo::get_st_dev() {
- if ((this->flags & FLAG_NEW_SOINFO) == 0) {
- return 0;
+off64_t soinfo::get_file_offset() {
+ if (has_min_version(1)) {
+ return file_offset;
}
- return st_dev;
-};
-
-ino_t soinfo::get_st_ino() {
- if ((this->flags & FLAG_NEW_SOINFO) == 0) {
- return 0;
- }
-
- return st_ino;
+ return 0;
}
-// This is a return on get_children() in case
+// 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;
soinfo::soinfo_list_t& soinfo::get_children() {
+ if (has_min_version(0)) {
+ return this->children;
+ }
+
+ return g_empty_list;
+}
+
+soinfo::soinfo_list_t& soinfo::get_parents() {
if ((this->flags & FLAG_NEW_SOINFO) == 0) {
return g_empty_list;
}
- return this->children;
+ return this->parents;
+}
+
+ElfW(Addr) soinfo::resolve_symbol_address(ElfW(Sym)* s) {
+ if (ELF_ST_TYPE(s->st_info) == STT_GNU_IFUNC) {
+ return call_ifunc_resolver(s->st_value + load_bias);
+ }
+
+ return static_cast<ElfW(Addr)>(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() {
- 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;
+ 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("[ 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));
+ 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;
- }
+ /* 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;
- }
+ /* 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;
- }
+ /* 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;
- }
+ /* 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;
+ return return_value;
}
-static bool soinfo_link_image(soinfo* si, const android_dlextinfo* extinfo) {
- /* "base" might wrap around UINT32_MAX. */
- ElfW(Addr) base = si->load_bias;
- const ElfW(Phdr)* phdr = si->phdr;
- int phnum = si->phnum;
- bool relocating_linker = (si->flags & FLAG_LINKER) != 0;
+bool soinfo::PrelinkImage() {
+ /* Extract dynamic section */
+ 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<void*>(base), flags);
+ }
- /* We can't debug anything until the linker is relocated */
+ if (dynamic == nullptr) {
if (!relocating_linker) {
- INFO("[ linking %s ]", si->name);
- DEBUG("si->base = %p si->flags = 0x%08x", reinterpret_cast<void*>(si->base), si->flags);
+ DL_ERR("missing PT_DYNAMIC in \"%s\"", name);
}
-
- /* Extract dynamic section */
- size_t dynamic_count;
- ElfW(Word) dynamic_flags;
- phdr_table_get_dynamic_section(phdr, phnum, base, &si->dynamic,
- &dynamic_count, &dynamic_flags);
- if (si->dynamic == NULL) {
- if (!relocating_linker) {
- DL_ERR("missing PT_DYNAMIC in \"%s\"", si->name);
- }
- return false;
- } else {
- if (!relocating_linker) {
- DEBUG("dynamic = %p", si->dynamic);
- }
+ return false;
+ } else {
+ if (!relocating_linker) {
+ DEBUG("dynamic = %p", dynamic);
}
+ }
#if defined(__arm__)
- (void) phdr_table_get_arm_exidx(phdr, phnum, base,
- &si->ARM_exidx, &si->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 = si->dynamic; d->d_tag != DT_NULL; ++d) {
- DEBUG("d = %p, d[0](tag) = %p d[1](val) = %p",
- d, reinterpret_cast<void*>(d->d_tag), reinterpret_cast<void*>(d->d_un.d_val));
- switch (d->d_tag) {
- case DT_HASH:
- si->nbucket = reinterpret_cast<uint32_t*>(base + d->d_un.d_ptr)[0];
- si->nchain = reinterpret_cast<uint32_t*>(base + d->d_un.d_ptr)[1];
- si->bucket = reinterpret_cast<uint32_t*>(base + d->d_un.d_ptr + 8);
- si->chain = reinterpret_cast<uint32_t*>(base + d->d_un.d_ptr + 8 + si->nbucket * 4);
- break;
- case DT_STRTAB:
- si->strtab = reinterpret_cast<const char*>(base + d->d_un.d_ptr);
- break;
- case DT_SYMTAB:
- si->symtab = reinterpret_cast<ElfW(Sym)*>(base + 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\"", si->name);
- return false;
- }
- 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<void*>(d->d_tag), reinterpret_cast<void*>(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<uint32_t*>(load_bias + d->d_un.d_ptr)[0];
+ nchain = reinterpret_cast<uint32_t*>(load_bias + d->d_un.d_ptr)[1];
+ bucket = reinterpret_cast<uint32_t*>(load_bias + d->d_un.d_ptr + 8);
+ chain = reinterpret_cast<uint32_t*>(load_bias + d->d_un.d_ptr + 8 + nbucket * 4);
+ break;
+
+ case DT_STRTAB:
+ strtab = reinterpret_cast<const char*>(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<ElfW(Sym)*>(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<size_t>(d->d_un.d_val));
+ return false;
+ }
+ break;
+
+ case DT_PLTREL:
+#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;
+ }
#endif
- case DT_JMPREL:
+ break;
+
+ case DT_JMPREL:
#if defined(USE_RELA)
- si->plt_rela = reinterpret_cast<ElfW(Rela)*>(base + d->d_un.d_ptr);
+ plt_rela = reinterpret_cast<ElfW(Rela)*>(load_bias + d->d_un.d_ptr);
#else
- si->plt_rel = reinterpret_cast<ElfW(Rel)*>(base + d->d_un.d_ptr);
+ plt_rel = reinterpret_cast<ElfW(Rel)*>(load_bias + d->d_un.d_ptr);
#endif
- break;
- case DT_PLTRELSZ:
+ break;
+
+ case DT_PLTRELSZ:
#if defined(USE_RELA)
- si->plt_rela_count = d->d_un.d_val / sizeof(ElfW(Rela));
+ plt_rela_count = d->d_un.d_val / sizeof(ElfW(Rela));
#else
- si->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;
+
+ case DT_PLTGOT:
#if defined(__mips__)
- case DT_PLTGOT:
- // Used by mips and mips64.
- si->plt_got = reinterpret_cast<ElfW(Addr)**>(base + d->d_un.d_ptr);
- break;
+ // Used by mips and mips64.
+ plt_got = reinterpret_cast<ElfW(Addr)**>(load_bias + d->d_un.d_ptr);
#endif
- case DT_DEBUG:
- // Set the DT_DEBUG entry to the address of _r_debug for GDB
- // if the dynamic table is writable
+ // 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
// FIXME: not working currently for N64
// The flags for the LOAD and DYNAMIC program headers do not agree.
-// The LOAD section containng the dynamic table has been mapped as
+// 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<uintptr_t>(&_r_debug);
- }
- break;
+ if ((dynamic_flags & PF_W) != 0) {
+ d->d_un.d_val = reinterpret_cast<uintptr_t>(&_r_debug);
+ }
+ break;
#endif
#if defined(USE_RELA)
- case DT_RELA:
- si->rela = reinterpret_cast<ElfW(Rela)*>(base + d->d_un.d_ptr);
- break;
- case DT_RELASZ:
- si->rela_count = d->d_un.d_val / sizeof(ElfW(Rela));
- break;
- case DT_REL:
- DL_ERR("unsupported DT_REL in \"%s\"", si->name);
- return false;
- case DT_RELSZ:
- DL_ERR("unsupported DT_RELSZ in \"%s\"", si->name);
- return false;
+ case DT_RELA:
+ rela = reinterpret_cast<ElfW(Rela)*>(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<size_t>(d->d_un.d_val));
+ return false;
+ }
+ break;
+
+ // ignored (see DT_RELCOUNT comments for details)
+ case DT_RELACOUNT:
+ 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:
- si->rel = reinterpret_cast<ElfW(Rel)*>(base + d->d_un.d_ptr);
- break;
- case DT_RELSZ:
- si->rel_count = d->d_un.d_val / sizeof(ElfW(Rel));
- break;
- case DT_RELA:
- DL_ERR("unsupported DT_RELA in \"%s\"", si->name);
- return false;
+ case DT_REL:
+ rel = reinterpret_cast<ElfW(Rel)*>(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<size_t>(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:
+ break;
+ case DT_RELA:
+ DL_ERR("unsupported DT_RELA in \"%s\"", name);
+ return false;
#endif
- case DT_INIT:
- si->init_func = reinterpret_cast<linker_function_t>(base + d->d_un.d_ptr);
- DEBUG("%s constructors (DT_INIT) found at %p", si->name, si->init_func);
- break;
- case DT_FINI:
- si->fini_func = reinterpret_cast<linker_function_t>(base + d->d_un.d_ptr);
- DEBUG("%s destructors (DT_FINI) found at %p", si->name, si->fini_func);
- break;
- case DT_INIT_ARRAY:
- si->init_array = reinterpret_cast<linker_function_t*>(base + d->d_un.d_ptr);
- DEBUG("%s constructors (DT_INIT_ARRAY) found at %p", si->name, si->init_array);
- break;
- case DT_INIT_ARRAYSZ:
- si->init_array_count = ((unsigned)d->d_un.d_val) / sizeof(ElfW(Addr));
- break;
- case DT_FINI_ARRAY:
- si->fini_array = reinterpret_cast<linker_function_t*>(base + d->d_un.d_ptr);
- DEBUG("%s destructors (DT_FINI_ARRAY) found at %p", si->name, si->fini_array);
- break;
- case DT_FINI_ARRAYSZ:
- si->fini_array_count = ((unsigned)d->d_un.d_val) / sizeof(ElfW(Addr));
- break;
- case DT_PREINIT_ARRAY:
- si->preinit_array = reinterpret_cast<linker_function_t*>(base + d->d_un.d_ptr);
- DEBUG("%s constructors (DT_PREINIT_ARRAY) found at %p", si->name, si->preinit_array);
- break;
- case DT_PREINIT_ARRAYSZ:
- si->preinit_array_count = ((unsigned)d->d_un.d_val) / sizeof(ElfW(Addr));
- break;
- case DT_TEXTREL:
+ case DT_INIT:
+ init_func = reinterpret_cast<linker_function_t>(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<linker_function_t>(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<linker_function_t*>(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<linker_function_t*>(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<linker_function_t*>(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\"", si->name);
- return false;
+ DL_ERR("text relocations (DT_TEXTREL) found in 64-bit ELF file \"%s\"", name);
+ return false;
#else
- si->has_text_relocations = true;
- break;
+ has_text_relocations = true;
+ break;
#endif
- case DT_SYMBOLIC:
- si->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\"", si->name);
- return false;
+ DL_ERR("text relocations (DF_TEXTREL) found in 64-bit ELF file \"%s\"", name);
+ return false;
#else
- si->has_text_relocations = true;
+ has_text_relocations = true;
#endif
- }
- if (d->d_un.d_val & DF_SYMBOLIC) {
- si->has_DT_SYMBOLIC = true;
- }
- break;
+ }
+ if (d->d_un.d_val & DF_SYMBOLIC) {
+ 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<void*>(d->d_un.d_val));
+ }
+ 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<r_debug**>(base + 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_RLD_MAP:
+ // Set the DT_MIPS_RLD_MAP entry to the address of _r_debug for GDB.
+ {
+ r_debug** dp = reinterpret_cast<r_debug**>(load_bias + d->d_un.d_ptr);
+ *dp = &_r_debug;
+ }
+ break;
- case DT_MIPS_SYMTABNO:
- si->mips_symtabno = d->d_un.d_val;
- break;
+ case DT_MIPS_RLD_VERSION:
+ case DT_MIPS_FLAGS:
+ case DT_MIPS_BASE_ADDRESS:
+ case DT_MIPS_UNREFEXTNO:
+ break;
- case DT_MIPS_LOCAL_GOTNO:
- si->mips_local_gotno = d->d_un.d_val;
- break;
+ case DT_MIPS_SYMTABNO:
+ mips_symtabno = d->d_un.d_val;
+ break;
- case DT_MIPS_GOTSYM:
- si->mips_gotsym = 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
+ // Ignored: "Its use has been superseded by the DF_BIND_NOW flag"
+ case DT_BIND_NOW:
+ break;
- default:
- DEBUG("Unused DT entry: type %p arg %p",
- reinterpret_cast<void*>(d->d_tag), reinterpret_cast<void*>(d->d_un.d_val));
- break;
+ // Ignore: bionic does not support symbol versioning...
+ case DT_VERSYM:
+ case DT_VERDEF:
+ case DT_VERDEFNUM:
+ break;
+
+ default:
+ if (!relocating_linker) {
+ DL_WARN("%s: unused DT entry: type %p arg %p", name,
+ reinterpret_cast<void*>(d->d_tag), reinterpret_cast<void*>(d->d_un.d_val));
}
+ break;
}
+ }
- DEBUG("si->base = %p, si->strtab = %p, si->symtab = %p",
- reinterpret_cast<void*>(si->base), si->strtab, si->symtab);
+ DEBUG("si->base = %p, si->strtab = %p, si->symtab = %p",
+ reinterpret_cast<void*>(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 (si->nbucket == 0) {
- DL_ERR("empty/missing DT_HASH in \"%s\" (built with --hash-style=gnu?)", si->name);
- return false;
- }
- if (si->strtab == 0) {
- DL_ERR("empty/missing DT_STRTAB in \"%s\"", si->name);
- return false;
- }
- if (si->symtab == 0) {
- DL_ERR("empty/missing DT_SYMTAB in \"%s\"", si->name);
- return false;
- }
+ // 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;
+}
- // If this is the main executable, then load all of the libraries from LD_PRELOAD now.
- if (si->flags & FLAG_EXE) {
- memset(g_ld_preloads, 0, sizeof(g_ld_preloads));
- size_t preload_count = 0;
- for (size_t i = 0; g_ld_preload_names[i] != NULL; i++) {
- soinfo* lsi = find_library(g_ld_preload_names[i], 0, NULL);
- if (lsi != NULL) {
- g_ld_preloads[preload_count++] = lsi;
- } else {
- // As with glibc, failure to load an LD_PRELOAD library is just a warning.
- DL_WARN("could not load library \"%s\" from LD_PRELOAD for \"%s\"; caused by %s",
- g_ld_preload_names[i], si->name, linker_get_error_buffer());
- }
- }
- }
-
- soinfo** needed = reinterpret_cast<soinfo**>(alloca((1 + needed_count) * sizeof(soinfo*)));
- soinfo** pneeded = needed;
-
- for (ElfW(Dyn)* d = si->dynamic; d->d_tag != DT_NULL; ++d) {
- if (d->d_tag == DT_NEEDED) {
- const char* library_name = si->strtab + d->d_un.d_val;
- DEBUG("%s needs %s", si->name, library_name);
- soinfo* lsi = find_library(library_name, 0, NULL);
- if (lsi == NULL) {
- strlcpy(tmp_err_buf, linker_get_error_buffer(), sizeof(tmp_err_buf));
- DL_ERR("could not load library \"%s\" needed by \"%s\"; caused by %s",
- library_name, si->name, tmp_err_buf);
- return false;
- }
-
- si->add_child(lsi);
- *pneeded++ = lsi;
- }
- }
- *pneeded = NULL;
+bool soinfo::LinkImage(const android_dlextinfo* extinfo) {
#if !defined(__LP64__)
- if (si->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.", si->name);
- if (phdr_table_unprotect_segments(si->phdr, si->phnum, si->load_bias) < 0) {
- DL_ERR("can't unprotect loadable segments for \"%s\": %s",
- si->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 (si->plt_rela != NULL) {
- DEBUG("[ relocating %s plt ]\n", si->name);
- if (soinfo_relocate(si, si->plt_rela, si->plt_rela_count, needed)) {
- return false;
- }
+ if (rela != nullptr) {
+ DEBUG("[ relocating %s ]", name);
+ if (Relocate(rela, rela_count)) {
+ return false;
}
- if (si->rela != NULL) {
- DEBUG("[ relocating %s ]\n", si->name);
- if (soinfo_relocate(si, si->rela, si->rela_count, needed)) {
- return false;
- }
+ }
+ if (plt_rela != nullptr) {
+ DEBUG("[ relocating %s plt ]", name);
+ if (Relocate(plt_rela, plt_rela_count)) {
+ return false;
}
+ }
#else
- if (si->plt_rel != NULL) {
- DEBUG("[ relocating %s plt ]", si->name);
- if (soinfo_relocate(si, si->plt_rel, si->plt_rel_count, needed)) {
- return false;
- }
+ if (rel != nullptr) {
+ DEBUG("[ relocating %s ]", name);
+ if (Relocate(rel, rel_count)) {
+ return false;
}
- if (si->rel != NULL) {
- DEBUG("[ relocating %s ]", si->name);
- if (soinfo_relocate(si, si->rel, si->rel_count, needed)) {
- 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(si, needed)) {
- return false;
- }
+ if (!mips_relocate_got(this)) {
+ return false;
+ }
#endif
- si->flags |= FLAG_LINKED;
- DEBUG("[ finished linking %s ]", si->name);
+ DEBUG("[ finished linking %s ]", name);
#if !defined(__LP64__)
- if (si->has_text_relocations) {
- // All relocations are done, we can protect our segments back to read-only.
- if (phdr_table_protect_segments(si->phdr, si->phnum, si->load_bias) < 0) {
- DL_ERR("can't protect segments for \"%s\": %s",
- si->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(si->phdr, si->phnum, si->load_bias) < 0) {
- DL_ERR("can't enable GNU RELRO protection for \"%s\": %s",
- si->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(si->phdr, si->phnum, si->load_bias,
- extinfo->relro_fd) < 0) {
- DL_ERR("failed serializing GNU RELRO section for \"%s\": %s",
- si->name, strerror(errno));
- return false;
- }
- } else if (extinfo && (extinfo->flags & ANDROID_DLEXT_USE_RELRO)) {
- if (phdr_table_map_gnu_relro(si->phdr, si->phnum, si->load_bias,
- extinfo->relro_fd) < 0) {
- DL_ERR("failed mapping GNU RELRO section for \"%s\": %s",
- si->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(si);
- return true;
+ notify_gdb_of_load(this);
+ return true;
}
/*
@@ -2037,11 +2271,11 @@ static bool soinfo_link_image(soinfo* si, const android_dlextinfo* extinfo) {
static void add_vdso(KernelArgumentBlock& args __unused) {
#if defined(AT_SYSINFO_EHDR)
ElfW(Ehdr)* ehdr_vdso = reinterpret_cast<ElfW(Ehdr)*>(args.getauxval(AT_SYSINFO_EHDR));
- if (ehdr_vdso == NULL) {
+ if (ehdr_vdso == nullptr) {
return;
}
- soinfo* si = soinfo_alloc("[vdso]", NULL);
+ soinfo* si = soinfo_alloc("[vdso]", nullptr, 0);
si->phdr = reinterpret_cast<ElfW(Phdr)*>(reinterpret_cast<char*>(ehdr_vdso) + ehdr_vdso->e_phoff);
si->phnum = ehdr_vdso->e_phnum;
@@ -2049,14 +2283,20 @@ static void add_vdso(KernelArgumentBlock& args __unused) {
si->size = phdr_table_get_load_size(si->phdr, si->phnum);
si->load_bias = get_elf_exec_load_bias(ehdr_vdso);
- soinfo_link_image(si, NULL);
+ si->PrelinkImage();
+ si->LinkImage(nullptr);
#endif
}
/*
* This is linker soinfo for GDB. See details below.
*/
-static soinfo linker_soinfo_for_gdb;
+#if defined(__LP64__)
+#define LINKER_PATH "/system/bin/linker64"
+#else
+#define LINKER_PATH "/system/bin/linker"
+#endif
+static soinfo linker_soinfo_for_gdb(LINKER_PATH, nullptr, 0);
/* gdb expects the linker to be in the debug shared object list.
* Without this, gdb has trouble locating the linker's ".text"
@@ -2066,12 +2306,6 @@ static soinfo linker_soinfo_for_gdb;
* be on the soinfo list.
*/
static void init_linker_info_for_gdb(ElfW(Addr) linker_base) {
-#if defined(__LP64__)
- strlcpy(linker_soinfo_for_gdb.name, "/system/bin/linker64", sizeof(linker_soinfo_for_gdb.name));
-#else
- strlcpy(linker_soinfo_for_gdb.name, "/system/bin/linker", sizeof(linker_soinfo_for_gdb.name));
-#endif
- linker_soinfo_for_gdb.flags = FLAG_NEW_SOINFO;
linker_soinfo_for_gdb.base = linker_base;
/*
@@ -2083,7 +2317,7 @@ static void init_linker_info_for_gdb(ElfW(Addr) linker_base) {
ElfW(Ehdr)* elf_hdr = reinterpret_cast<ElfW(Ehdr)*>(linker_base);
ElfW(Phdr)* phdr = reinterpret_cast<ElfW(Phdr)*>(linker_base + elf_hdr->e_phoff);
phdr_table_get_dynamic_section(phdr, elf_hdr->e_phnum, linker_base,
- &linker_soinfo_for_gdb.dynamic, NULL, NULL);
+ &linker_soinfo_for_gdb.dynamic, nullptr);
insert_soinfo_into_debug_map(&linker_soinfo_for_gdb);
}
@@ -2093,166 +2327,186 @@ static void init_linker_info_for_gdb(ElfW(Addr) linker_base) {
* and other non-local data at this point.
*/
static ElfW(Addr) __linker_init_post_relocation(KernelArgumentBlock& args, ElfW(Addr) linker_base) {
- /* NOTE: we store the args pointer on a special location
- * of the temporary TLS area in order to pass it to
- * the C Library's runtime initializer.
- *
- * The initializer must clear the slot and reset the TLS
- * to point to a different location to ensure that no other
- * shared library constructor can access it.
- */
- __libc_init_tls(args);
-
#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();
+ debuggerd_init();
- // Get a few environment variables.
- const char* LD_DEBUG = linker_env_get("LD_DEBUG");
- if (LD_DEBUG != NULL) {
- g_ld_debug_verbosity = atoi(LD_DEBUG);
- }
+ // 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 = NULL;
- const char* ldpreload_env = NULL;
- if (!get_AT_SECURE()) {
- ldpath_env = linker_env_get("LD_LIBRARY_PATH");
- ldpreload_env = linker_env_get("LD_PRELOAD");
- }
+ // 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 ]");
+ INFO("[ android linker & debugger ]");
- soinfo* si = soinfo_alloc(args.argv[0], NULL);
- if (si == NULL) {
- exit(EXIT_FAILURE);
- }
+ 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);
+ /* 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 = NULL;
- map->l_next = NULL;
+ 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<ElfW(Phdr)*>(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<ElfW(Addr)>(si->phdr) - si->phdr[i].p_vaddr;
- si->base = reinterpret_cast<ElfW(Addr)>(si->phdr) - si->phdr[i].p_offset;
- break;
- }
- }
- si->dynamic = NULL;
- si->ref_count = 1;
+ _r_debug.r_map = map;
+ r_debug_tail = map;
- ElfW(Ehdr)* elf_hdr = reinterpret_cast<ElfW(Ehdr)*>(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);
+ init_linker_info_for_gdb(linker_base);
+
+ // Extract information passed from the kernel.
+ si->phdr = reinterpret_cast<ElfW(Phdr)*>(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<ElfW(Addr)>(si->phdr) - si->phdr[i].p_vaddr;
+ si->base = reinterpret_cast<ElfW(Addr)>(si->phdr) - si->phdr[i].p_offset;
+ break;
}
+ }
+ si->dynamic = nullptr;
+ si->ref_count = 1;
- // 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);
+ ElfW(Ehdr)* elf_hdr = reinterpret_cast<ElfW(Ehdr)*>(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);
+ }
- somain = si;
+ // 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);
- if (!soinfo_link_image(si, NULL)) {
- __libc_format_fd(2, "CANNOT LINK EXECUTABLE: %s\n", linker_get_error_buffer());
- exit(EXIT_FAILURE);
- }
+ somain = si;
+
+ if (!si->PrelinkImage()) {
+ __libc_format_fd(2, "CANNOT LINK EXECUTABLE: %s\n", linker_get_error_buffer());
+ exit(EXIT_FAILURE);
+ }
- add_vdso(args);
+ // 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;
+ }
- si->CallPreInitConstructors();
+ for_each_dt_needed(si, [&](const char* name) {
+ needed_library_name_list.push_back(name);
+ ++needed_libraries_count;
+ });
- for (size_t i = 0; g_ld_preloads[i] != NULL; ++i) {
- g_ld_preloads[i]->CallConstructors();
- }
+ const char* needed_library_names[needed_libraries_count];
+ soinfo* needed_library_si[needed_libraries_count];
- /* After the link_image, 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();
+ 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; i<needed_libraries_count; ++i) {
+ si->add_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();
#if TIMING
- gettimeofday(&t1, NULL);
- 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<void*>(si->entry));
- return si->entry;
+ TRACE("[ Ready to execute '%s' @ %p ]", si->name, reinterpret_cast<void*>(si->entry));
+ return si->entry;
}
/* Compute the load-bias of an existing executable. This shall only
@@ -2290,10 +2544,6 @@ extern "C" void _start();
* function, or other GOT reference will generate a segfault.
*/
extern "C" ElfW(Addr) __linker_init(void* raw_args) {
- // Initialize static variables.
- solist = get_libdl_info();
- sonext = get_libdl_info();
-
KernelArgumentBlock args(raw_args);
ElfW(Addr) linker_addr = args.getauxval(AT_BASE);
@@ -2301,8 +2551,7 @@ extern "C" ElfW(Addr) __linker_init(void* raw_args) {
ElfW(Ehdr)* elf_hdr = reinterpret_cast<ElfW(Ehdr)*>(linker_addr);
ElfW(Phdr)* phdr = reinterpret_cast<ElfW(Phdr)*>(linker_addr + elf_hdr->e_phoff);
- soinfo linker_so;
- memset(&linker_so, 0, sizeof(soinfo));
+ soinfo linker_so("[dynamic linker]", nullptr, 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
@@ -2314,16 +2563,15 @@ extern "C" ElfW(Addr) __linker_init(void* raw_args) {
__libc_fatal("This is %s, the helper program for shared library executables.\n", args.argv[0]);
}
- strcpy(linker_so.name, "[dynamic linker]");
linker_so.base = linker_addr;
linker_so.size = phdr_table_get_load_size(phdr, elf_hdr->e_phnum);
linker_so.load_bias = get_elf_exec_load_bias(elf_hdr);
- linker_so.dynamic = NULL;
+ linker_so.dynamic = nullptr;
linker_so.phdr = phdr;
linker_so.phnum = elf_hdr->e_phnum;
linker_so.flags |= FLAG_LINKER;
- if (!soinfo_link_image(&linker_so, NULL)) {
+ if (!(linker_so.PrelinkImage() && linker_so.LinkImage(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
@@ -2335,9 +2583,17 @@ extern "C" ElfW(Addr) __linker_init(void* raw_args) {
_exit(EXIT_FAILURE);
}
+ __libc_init_tls(args);
+
// Initialize the linker's own global variables
linker_so.CallConstructors();
+ // Initialize static variables. Note that in order to
+ // get correct libdl_info we need to call constructors
+ // before get_libdl_info().
+ solist = get_libdl_info();
+ sonext = get_libdl_info();
+
// We have successfully fixed our own relocations. It's safe to run
// the main part of the linker now.
args.abort_message_ptr = &g_abort_message;
diff --git a/linker/linker.h b/linker/linker.h
index 374652e..fa38c7f 100644
--- a/linker/linker.h
+++ b/linker/linker.h
@@ -30,6 +30,7 @@
#define _LINKER_H_
#include <elf.h>
+#include <inttypes.h>
#include <link.h>
#include <unistd.h>
#include <android/dlext.h>
@@ -88,6 +89,8 @@
#define FLAG_LINKER 0x00000010 // The linker itself
#define FLAG_NEW_SOINFO 0x40000000 // new soinfo format
+#define SOINFO_VERSION 0
+
#define SOINFO_NAME_LEN 128
typedef void (*linker_function_t)();
@@ -133,7 +136,9 @@ struct soinfo {
soinfo* next;
unsigned flags;
+ private:
const char* strtab;
+ public:
ElfW(Sym)* symtab;
size_t nbucket;
@@ -195,29 +200,47 @@ struct soinfo {
bool has_text_relocations;
#endif
bool has_DT_SYMBOLIC;
+
+ soinfo(const char* name, const struct stat* file_stat, off64_t file_offset);
+
void CallConstructors();
void CallDestructors();
void CallPreInitConstructors();
+ bool PrelinkImage();
+ bool LinkImage(const android_dlextinfo* extinfo);
void add_child(soinfo* child);
void remove_all_links();
- void set_st_dev(dev_t st_dev);
- void set_st_ino(ino_t st_ino);
ino_t get_st_ino();
dev_t get_st_dev();
+ off64_t get_file_offset();
soinfo_list_t& get_children();
+ soinfo_list_t& get_parents();
+
+ ElfW(Addr) resolve_symbol_address(ElfW(Sym)* s);
+ 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:
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);
+#else
+ int Relocate(ElfW(Rel)* rel, unsigned count);
+#endif
private:
// This part of the structure is only available
// when FLAG_NEW_SOINFO is set in this->flags.
- unsigned int version;
+ uint32_t version;
+ // version >= 0
dev_t st_dev;
ino_t st_ino;
@@ -225,6 +248,12 @@ struct soinfo {
soinfo_list_t children;
soinfo_list_t parents;
+ // version >= 1
+ off64_t file_offset;
+ int rtld_flags;
+ size_t strtab_size;
+
+ friend soinfo* get_libdl_info();
};
extern soinfo* get_libdl_info();
diff --git a/linker/linker_debug.h b/linker/linker_debug.h
index 3faa38e..0c7a784 100644
--- a/linker/linker_debug.h
+++ b/linker/linker_debug.h
@@ -42,6 +42,7 @@
#define TRACE_DEBUG 1
#define DO_TRACE_LOOKUP 1
#define DO_TRACE_RELO 1
+#define DO_TRACE_IFUNC 1
#define TIMING 0
#define STATS 0
#define COUNT_PAGES 0
diff --git a/linker/linker_environ.cpp b/linker/linker_environ.cpp
index 846624b..daee56f 100644
--- a/linker/linker_environ.cpp
+++ b/linker/linker_environ.cpp
@@ -58,7 +58,7 @@ static void __init_AT_SECURE(KernelArgumentBlock& args) {
// Check if the environment variable definition at 'envstr'
// starts with '<name>=', and if so return the address of the
-// first character after the equal sign. Otherwise return NULL.
+// first character after the equal sign. Otherwise return null.
static const char* env_match(const char* envstr, const char* name) {
size_t i = 0;
@@ -70,7 +70,7 @@ static const char* env_match(const char* envstr, const char* name) {
return envstr + i + 1;
}
- return NULL;
+ return nullptr;
}
static bool __is_valid_environment_variable(const char* name) {
@@ -78,7 +78,7 @@ static bool __is_valid_environment_variable(const char* name) {
// as the maximum size for an env. variable definition.
const int MAX_ENV_LEN = 32*4096;
- if (name == NULL) {
+ if (name == nullptr) {
return false;
}
@@ -136,10 +136,10 @@ static bool __is_unsafe_environment_variable(const char* name) {
"RES_OPTIONS",
"TMPDIR",
"TZDIR",
- NULL
+ nullptr
};
- for (size_t i = 0; UNSAFE_VARIABLE_NAMES[i] != NULL; ++i) {
- if (env_match(name, UNSAFE_VARIABLE_NAMES[i]) != NULL) {
+ for (size_t i = 0; UNSAFE_VARIABLE_NAMES[i] != nullptr; ++i) {
+ if (env_match(name, UNSAFE_VARIABLE_NAMES[i]) != nullptr) {
return true;
}
}
@@ -149,7 +149,7 @@ static bool __is_unsafe_environment_variable(const char* name) {
static void __sanitize_environment_variables() {
char** src = _envp;
char** dst = _envp;
- for (; src[0] != NULL; ++src) {
+ for (; src[0] != nullptr; ++src) {
if (!__is_valid_environment_variable(src[0])) {
continue;
}
@@ -160,11 +160,11 @@ static void __sanitize_environment_variables() {
dst[0] = src[0];
++dst;
}
- dst[0] = NULL;
+ dst[0] = nullptr;
}
void linker_env_init(KernelArgumentBlock& args) {
- // Store environment pointer - can't be NULL.
+ // Store environment pointer - can't be null.
_envp = args.envp;
__init_AT_SECURE(args);
@@ -172,18 +172,18 @@ void linker_env_init(KernelArgumentBlock& args) {
}
const char* linker_env_get(const char* name) {
- if (name == NULL || name[0] == '\0') {
- return NULL;
+ if (name == nullptr || name[0] == '\0') {
+ return nullptr;
}
- for (char** p = _envp; p[0] != NULL; ++p) {
+ for (char** p = _envp; p[0] != nullptr; ++p) {
const char* val = env_match(p[0], name);
- if (val != NULL) {
+ if (val != nullptr) {
if (val[0] == '\0') {
- return NULL; // Return NULL for empty strings.
+ return nullptr; // Return null for empty strings.
}
return val;
}
}
- return NULL;
+ return nullptr;
}
diff --git a/linker/linker_environ.h b/linker/linker_environ.h
index d3f54fd..0f6ac08 100644
--- a/linker/linker_environ.h
+++ b/linker/linker_environ.h
@@ -35,7 +35,7 @@ class KernelArgumentBlock;
extern void linker_env_init(KernelArgumentBlock& args);
// Returns the value of environment variable 'name' if defined and not
-// empty, or NULL otherwise.
+// empty, or null otherwise.
extern const char* linker_env_get(const char* name);
// Returns the value of this program's AT_SECURE variable.
diff --git a/linker/linker_executable.mk b/linker/linker_executable.mk
index 4902a0c..a596a48 100644
--- a/linker/linker_executable.mk
+++ b/linker/linker_executable.mk
@@ -9,6 +9,8 @@
LOCAL_MODULE_CLASS := EXECUTABLES
LOCAL_MODULE_SUFFIX := $(TARGET_EXECUTABLE_SUFFIX)
+# Clang calls /usr/bin/ld: unrecognized option '--icf=safe', http://b/17403674.
+LOCAL_CLANG := false
include $(BUILD_SYSTEM)/dynamic_binary.mk
# See build/core/executable_internal.mk
diff --git a/linker/linker_libc_support.c b/linker/linker_libc_support.c
new file mode 100644
index 0000000..17db6d4
--- /dev/null
+++ b/linker/linker_libc_support.c
@@ -0,0 +1,17 @@
+/*
+ * 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 "../libc/arch-common/bionic/__dso_handle.h"
diff --git a/linker/linker_phdr.cpp b/linker/linker_phdr.cpp
index 0b99d20..4b1c0ca 100644
--- a/linker/linker_phdr.cpp
+++ b/linker/linker_phdr.cpp
@@ -119,15 +119,15 @@
MAYBE_MAP_FLAG((x), PF_R, PROT_READ) | \
MAYBE_MAP_FLAG((x), PF_W, PROT_WRITE))
-ElfReader::ElfReader(const char* name, int fd)
- : name_(name), fd_(fd),
- phdr_num_(0), phdr_mmap_(NULL), phdr_table_(NULL), phdr_size_(0),
- load_start_(NULL), load_size_(0), load_bias_(0),
- loaded_phdr_(NULL) {
+ElfReader::ElfReader(const char* name, int fd, off64_t file_offset)
+ : name_(name), fd_(fd), file_offset_(file_offset),
+ phdr_num_(0), phdr_mmap_(nullptr), phdr_table_(nullptr), phdr_size_(0),
+ load_start_(nullptr), load_size_(0), load_bias_(0),
+ loaded_phdr_(nullptr) {
}
ElfReader::~ElfReader() {
- if (phdr_mmap_ != NULL) {
+ if (phdr_mmap_ != nullptr) {
munmap(phdr_mmap_, phdr_size_);
}
}
@@ -142,11 +142,12 @@ bool ElfReader::Load(const android_dlextinfo* extinfo) {
}
bool ElfReader::ReadElfHeader() {
- ssize_t rc = TEMP_FAILURE_RETRY(read(fd_, &header_, sizeof(header_)));
+ ssize_t rc = TEMP_FAILURE_RETRY(pread64(fd_, &header_, sizeof(header_), file_offset_));
if (rc < 0) {
DL_ERR("can't read file \"%s\": %s", name_, strerror(errno));
return false;
}
+
if (rc != sizeof(header_)) {
DL_ERR("\"%s\" is too small to be an ELF executable: only found %zd bytes", name_,
static_cast<size_t>(rc));
@@ -225,7 +226,7 @@ bool ElfReader::ReadProgramHeader() {
phdr_size_ = page_max - page_min;
- void* mmap_result = mmap(NULL, phdr_size_, PROT_READ, MAP_PRIVATE, fd_, page_min);
+ void* mmap_result = mmap64(nullptr, phdr_size_, PROT_READ, MAP_PRIVATE, fd_, file_offset_ + page_min);
if (mmap_result == MAP_FAILED) {
DL_ERR("\"%s\" phdr mmap failed: %s", name_, strerror(errno));
return false;
@@ -242,7 +243,7 @@ bool ElfReader::ReadProgramHeader() {
* process' address space. If there are no loadable segments, 0 is
* returned.
*
- * If out_min_vaddr or out_max_vaddr are non-NULL, they will be
+ * If out_min_vaddr or out_max_vaddr are not null, they will be
* set to the minimum and maximum addresses of pages to be reserved,
* or 0 if there is nothing to load.
*/
@@ -276,10 +277,10 @@ size_t phdr_table_get_load_size(const ElfW(Phdr)* phdr_table, size_t phdr_count,
min_vaddr = PAGE_START(min_vaddr);
max_vaddr = PAGE_END(max_vaddr);
- if (out_min_vaddr != NULL) {
+ if (out_min_vaddr != nullptr) {
*out_min_vaddr = min_vaddr;
}
- if (out_max_vaddr != NULL) {
+ if (out_max_vaddr != nullptr) {
*out_max_vaddr = max_vaddr;
}
return max_vaddr - min_vaddr;
@@ -301,7 +302,7 @@ bool ElfReader::ReserveAddressSpace(const android_dlextinfo* extinfo) {
size_t reserved_size = 0;
bool reserved_hint = true;
- if (extinfo != NULL) {
+ if (extinfo != nullptr) {
if (extinfo->flags & ANDROID_DLEXT_RESERVED_ADDRESS) {
reserved_size = extinfo->reserved_size;
reserved_hint = false;
@@ -356,12 +357,12 @@ bool ElfReader::LoadSegments() {
ElfW(Addr) file_length = file_end - file_page_start;
if (file_length != 0) {
- void* seg_addr = mmap(reinterpret_cast<void*>(seg_page_start),
+ void* seg_addr = mmap64(reinterpret_cast<void*>(seg_page_start),
file_length,
PFLAGS_TO_PROT(phdr->p_flags),
MAP_FIXED|MAP_PRIVATE,
fd_,
- file_page_start);
+ file_offset_ + file_page_start);
if (seg_addr == MAP_FAILED) {
DL_ERR("couldn't map \"%s\" segment %zd: %s", name_, i, strerror(errno));
return false;
@@ -585,9 +586,9 @@ int phdr_table_map_gnu_relro(const ElfW(Phdr)* phdr_table, size_t phdr_count, El
return -1;
}
off_t file_size = file_stat.st_size;
- void* temp_mapping = NULL;
+ void* temp_mapping = nullptr;
if (file_size > 0) {
- temp_mapping = mmap(NULL, file_size, PROT_READ, MAP_PRIVATE, fd, 0);
+ temp_mapping = mmap(nullptr, file_size, PROT_READ, MAP_PRIVATE, fd, 0);
if (temp_mapping == MAP_FAILED) {
return -1;
}
@@ -667,7 +668,7 @@ int phdr_table_map_gnu_relro(const ElfW(Phdr)* phdr_table, size_t phdr_count, El
* phdr_count -> number of entries in tables
* load_bias -> load bias
* Output:
- * arm_exidx -> address of table in memory (NULL on failure).
+ * arm_exidx -> address of table in memory (null on failure).
* arm_exidx_count -> number of items in table (0 on failure).
* Return:
* 0 on error, -1 on failure (_no_ error code in errno)
@@ -687,49 +688,37 @@ int phdr_table_get_arm_exidx(const ElfW(Phdr)* phdr_table, size_t phdr_count,
*arm_exidx_count = (unsigned)(phdr->p_memsz / 8);
return 0;
}
- *arm_exidx = NULL;
+ *arm_exidx = nullptr;
*arm_exidx_count = 0;
return -1;
}
#endif
/* Return the address and size of the ELF file's .dynamic section in memory,
- * or NULL if missing.
+ * or null if missing.
*
* Input:
* phdr_table -> program header table
* phdr_count -> number of entries in tables
* load_bias -> load bias
* Output:
- * dynamic -> address of table in memory (NULL on failure).
- * dynamic_count -> number of items in table (0 on failure).
+ * dynamic -> address of table in memory (null on failure).
* dynamic_flags -> protection flags for section (unset on failure)
* Return:
* void
*/
void phdr_table_get_dynamic_section(const ElfW(Phdr)* phdr_table, size_t phdr_count,
- ElfW(Addr) load_bias,
- ElfW(Dyn)** dynamic, size_t* dynamic_count, ElfW(Word)* dynamic_flags) {
- const ElfW(Phdr)* phdr = phdr_table;
- const ElfW(Phdr)* phdr_limit = phdr + phdr_count;
-
- for (phdr = phdr_table; phdr < phdr_limit; phdr++) {
- if (phdr->p_type != PT_DYNAMIC) {
- continue;
- }
-
- *dynamic = reinterpret_cast<ElfW(Dyn)*>(load_bias + phdr->p_vaddr);
- if (dynamic_count) {
- *dynamic_count = (unsigned)(phdr->p_memsz / 8);
- }
- if (dynamic_flags) {
- *dynamic_flags = phdr->p_flags;
+ ElfW(Addr) load_bias, ElfW(Dyn)** dynamic,
+ ElfW(Word)* dynamic_flags) {
+ *dynamic = nullptr;
+ for (const ElfW(Phdr)* phdr = phdr_table, *phdr_limit = phdr + phdr_count; phdr < phdr_limit; phdr++) {
+ if (phdr->p_type == PT_DYNAMIC) {
+ *dynamic = reinterpret_cast<ElfW(Dyn)*>(load_bias + phdr->p_vaddr);
+ if (dynamic_flags) {
+ *dynamic_flags = phdr->p_flags;
+ }
+ return;
}
- return;
- }
- *dynamic = NULL;
- if (dynamic_count) {
- *dynamic_count = 0;
}
}
diff --git a/linker/linker_phdr.h b/linker/linker_phdr.h
index 611f1a7..65d302c 100644
--- a/linker/linker_phdr.h
+++ b/linker/linker_phdr.h
@@ -39,7 +39,7 @@
class ElfReader {
public:
- ElfReader(const char* name, int fd);
+ ElfReader(const char* name, int fd, off64_t file_offset);
~ElfReader();
bool Load(const android_dlextinfo* extinfo);
@@ -61,6 +61,7 @@ class ElfReader {
const char* name_;
int fd_;
+ off64_t file_offset_;
ElfW(Ehdr) header_;
size_t phdr_num_;
@@ -81,7 +82,7 @@ class ElfReader {
};
size_t phdr_table_get_load_size(const ElfW(Phdr)* phdr_table, size_t phdr_count,
- ElfW(Addr)* min_vaddr = NULL, ElfW(Addr)* max_vaddr = NULL);
+ ElfW(Addr)* min_vaddr = nullptr, ElfW(Addr)* max_vaddr = nullptr);
int phdr_table_protect_segments(const ElfW(Phdr)* phdr_table, size_t phdr_count, ElfW(Addr) load_bias);
@@ -101,7 +102,7 @@ int phdr_table_get_arm_exidx(const ElfW(Phdr)* phdr_table, size_t phdr_count, El
#endif
void phdr_table_get_dynamic_section(const ElfW(Phdr)* phdr_table, size_t phdr_count,
- ElfW(Addr) load_bias,
- ElfW(Dyn)** dynamic, size_t* dynamic_count, ElfW(Word)* dynamic_flags);
+ ElfW(Addr) load_bias, ElfW(Dyn)** dynamic,
+ ElfW(Word)* dynamic_flags);
#endif /* LINKER_PHDR_H */
diff --git a/linker/tests/linked_list_test.cpp b/linker/tests/linked_list_test.cpp
index b9816fa..09ad687 100644
--- a/linker/tests/linked_list_test.cpp
+++ b/linker/tests/linked_list_test.cpp
@@ -80,7 +80,7 @@ TEST(linked_list, simple) {
});
ASSERT_TRUE(!alloc_called);
- ASSERT_TRUE(!free_called);
+ ASSERT_TRUE(free_called);
ASSERT_EQ("dba", test_list_to_string(list));
alloc_called = free_called = false;
@@ -103,15 +103,114 @@ TEST(linked_list, push_pop) {
ASSERT_EQ("ab", test_list_to_string(list));
list.push_back("c");
ASSERT_EQ("abc", test_list_to_string(list));
- ASSERT_EQ("a", list.pop_front());
+ ASSERT_STREQ("a", list.pop_front());
ASSERT_EQ("bc", test_list_to_string(list));
- ASSERT_EQ("b", list.pop_front());
+ ASSERT_STREQ("b", list.pop_front());
ASSERT_EQ("c", test_list_to_string(list));
- ASSERT_EQ("c", list.pop_front());
+ ASSERT_STREQ("c", list.pop_front());
ASSERT_EQ("", test_list_to_string(list));
ASSERT_TRUE(list.pop_front() == nullptr);
list.push_back("r");
ASSERT_EQ("r", test_list_to_string(list));
- ASSERT_EQ("r", list.pop_front());
+ ASSERT_STREQ("r", list.pop_front());
+ ASSERT_TRUE(list.pop_front() == nullptr);
+}
+
+TEST(linked_list, remove_if_then_pop) {
+ test_list_t list;
+ list.push_back("a");
+ list.push_back("b");
+ list.push_back("c");
+ list.push_back("d");
+ list.remove_if([](const char* c) {
+ return *c == 'b' || *c == 'c';
+ });
+
+ ASSERT_EQ("ad", test_list_to_string(list));
+ ASSERT_STREQ("a", list.pop_front());
+ ASSERT_EQ("d", test_list_to_string(list));
+ ASSERT_STREQ("d", list.pop_front());
ASSERT_TRUE(list.pop_front() == nullptr);
}
+
+TEST(linked_list, copy_to_array) {
+ test_list_t list;
+ const size_t max_size = 128;
+ const char* buf[max_size];
+ memset(buf, 0, sizeof(buf));
+
+ ASSERT_EQ(0U, list.copy_to_array(buf, max_size));
+ ASSERT_EQ(nullptr, buf[0]);
+
+ list.push_back("a");
+ list.push_back("b");
+ list.push_back("c");
+ list.push_back("d");
+
+ memset(buf, 0, sizeof(buf));
+ ASSERT_EQ(2U, list.copy_to_array(buf, 2));
+ ASSERT_STREQ("a", buf[0]);
+ ASSERT_STREQ("b", buf[1]);
+ ASSERT_EQ(nullptr, buf[2]);
+
+ ASSERT_EQ(4U, list.copy_to_array(buf, max_size));
+ ASSERT_STREQ("a", buf[0]);
+ ASSERT_STREQ("b", buf[1]);
+ ASSERT_STREQ("c", buf[2]);
+ ASSERT_STREQ("d", buf[3]);
+ ASSERT_EQ(nullptr, buf[4]);
+
+ memset(buf, 0, sizeof(buf));
+ list.remove_if([](const char* c) {
+ return *c != 'c';
+ });
+ ASSERT_EQ(1U, list.copy_to_array(buf, max_size));
+ ASSERT_STREQ("c", buf[0]);
+ ASSERT_EQ(nullptr, buf[1]);
+
+ memset(buf, 0, sizeof(buf));
+
+ list.remove_if([](const char* c) {
+ return *c == 'c';
+ });
+
+ ASSERT_EQ(0U, list.copy_to_array(buf, max_size));
+ ASSERT_EQ(nullptr, buf[0]);
+}
+
+TEST(linked_list, test_visit) {
+ test_list_t list;
+ list.push_back("a");
+ list.push_back("b");
+ list.push_back("c");
+ list.push_back("d");
+
+ int visits = 0;
+ std::stringstream ss;
+ bool result = list.visit([&](const char* c) {
+ ++visits;
+ ss << c;
+ return true;
+ });
+
+ ASSERT_TRUE(result);
+ ASSERT_EQ(4, visits);
+ ASSERT_EQ("abcd", ss.str());
+
+ visits = 0;
+ ss.str(std::string());
+
+ result = list.visit([&](const char* c) {
+ if (++visits == 3) {
+ return false;
+ }
+
+ ss << c;
+ return true;
+ });
+
+ ASSERT_TRUE(!result);
+ ASSERT_EQ(3, visits);
+ ASSERT_EQ("ab", ss.str());
+}
+