am a5087148: Reimplement clock(3) using clock_gettime(3)
* commit 'a508714800242b294291060641ed35d719bdc857':
Reimplement clock(3) using clock_gettime(3)
diff --git a/libc/Android.mk b/libc/Android.mk
index 9c5e785..92ead26 100644
--- a/libc/Android.mk
+++ b/libc/Android.mk
@@ -503,7 +503,10 @@
libc_common_cflags += -DTARGET_USES_LOGD
endif
-use_clang := false
+use_clang := $(USE_CLANG_PLATFORM_BUILD)
+ifeq ($(use_clang),)
+ use_clang := false
+endif
# Try to catch typical 32-bit assumptions that break with 64-bit pointers.
libc_common_cflags += \
@@ -733,6 +736,13 @@
include $(CLEAR_VARS)
LOCAL_SRC_FILES := $(libc_upstream_openbsd_src_files)
+ifneq (,$(filter $(TARGET_ARCH),x86 x86_64))
+ # Clang has wrong long double size or LDBL_MANT_DIG, http://b/17163651.
+ LOCAL_CLANG := false
+else
+ LOCAL_CLANG := $(use_clang)
+endif
+
LOCAL_CFLAGS := \
$(libc_common_cflags) \
-Wno-sign-compare -Wno-uninitialized -Wno-unused-parameter \
@@ -746,7 +756,6 @@
LOCAL_CPPFLAGS := $(libc_common_cppflags)
LOCAL_C_INCLUDES := $(libc_common_c_includes)
LOCAL_MODULE := libc_openbsd
-LOCAL_CLANG := $(use_clang)
LOCAL_ADDITIONAL_DEPENDENCIES := $(libc_common_additional_dependencies)
LOCAL_SYSTEM_SHARED_LIBRARIES :=
@@ -765,6 +774,13 @@
LOCAL_SRC_FILES_32 := $(libc_upstream_openbsd_gdtoa_src_files_32)
LOCAL_SRC_FILES_64 := $(libc_upstream_openbsd_gdtoa_src_files_64)
+ifneq (,$(filter $(TARGET_ARCH),x86 x86_64))
+ # Clang has wrong long double size or LDBL_MANT_DIG, http://b/17163651.
+ LOCAL_CLANG := false
+else
+ LOCAL_CLANG := $(use_clang)
+endif
+
LOCAL_CFLAGS := \
$(libc_common_cflags) \
-Wno-sign-compare -Wno-uninitialized \
@@ -778,7 +794,6 @@
LOCAL_CPPFLAGS := $(libc_common_cppflags)
LOCAL_C_INCLUDES := $(libc_common_c_includes)
LOCAL_MODULE := libc_gdtoa
-LOCAL_CLANG := $(use_clang)
LOCAL_ADDITIONAL_DEPENDENCIES := $(libc_common_additional_dependencies)
LOCAL_SYSTEM_SHARED_LIBRARIES :=
@@ -796,6 +811,11 @@
LOCAL_CFLAGS := $(libc_common_cflags) \
-Wframe-larger-than=2048 \
+ifeq ($(TARGET_ARCH),x86_64)
+ # Clang assembler has problem with ssse3-strcmp-slm.S, http://b/17302991
+ LOCAL_CLANG_ASFLAGS += -no-integrated-as
+endif
+
LOCAL_CONLYFLAGS := $(libc_common_conlyflags)
LOCAL_CPPFLAGS := $(libc_common_cppflags)
LOCAL_C_INCLUDES := $(libc_common_c_includes)
@@ -1144,6 +1164,7 @@
include $(CLEAR_VARS)
LOCAL_C_INCLUDES := $(libc_common_c_includes)
LOCAL_CFLAGS := $(libc_common_cflags)
+LOCAL_CPPFLAGS := $(libc_common_cppflags)
LOCAL_SRC_FILES := $(libstdcxx_common_src_files)
LOCAL_MODULE:= libstdc++
LOCAL_ADDITIONAL_DEPENDENCIES := $(LOCAL_PATH)/Android.mk
@@ -1156,6 +1177,7 @@
include $(CLEAR_VARS)
LOCAL_C_INCLUDES := $(libc_common_c_includes)
LOCAL_CFLAGS := $(libc_common_cflags)
+LOCAL_CPPFLAGS := $(libc_common_cppflags)
LOCAL_SRC_FILES := $(libstdcxx_common_src_files)
LOCAL_MODULE:= libstdc++
LOCAL_ADDITIONAL_DEPENDENCIES := $(LOCAL_PATH)/Android.mk
diff --git a/libc/arch-arm64/include/machine/elf_machdep.h b/libc/arch-arm64/include/machine/elf_machdep.h
index 2bf8189..6eab313 100644
--- a/libc/arch-arm64/include/machine/elf_machdep.h
+++ b/libc/arch-arm64/include/machine/elf_machdep.h
@@ -99,6 +99,7 @@
#define R_AARCH64_RELATIVE 1027 /* Adjust by program base. */
#define R_AARCH64_TLS_TPREL64 1030
#define R_AARCH64_TLS_DTPREL32 1031
+#define R_AARCH64_IRELATIVE 1032
#define R_TYPE(name) __CONCAT(R_AARCH64_,name)
diff --git a/libc/arch-x86/include/machine/elf_machdep.h b/libc/arch-x86/include/machine/elf_machdep.h
index 442c561..4bce933 100644
--- a/libc/arch-x86/include/machine/elf_machdep.h
+++ b/libc/arch-x86/include/machine/elf_machdep.h
@@ -59,5 +59,6 @@
#define R_386_TLS_GOTDESC 39
#define R_386_TLS_DESC_CALL 40
#define R_386_TLS_DESC 41
+#define R_386_IRELATIVE 42
#define R_TYPE(name) __CONCAT(R_386_,name)
diff --git a/libc/arch-x86_64/include/machine/elf_machdep.h b/libc/arch-x86_64/include/machine/elf_machdep.h
index 20f8c6d..bf1f273 100644
--- a/libc/arch-x86_64/include/machine/elf_machdep.h
+++ b/libc/arch-x86_64/include/machine/elf_machdep.h
@@ -46,6 +46,8 @@
#define R_X86_64_GOTTPOFF 22
#define R_X86_64_TPOFF32 23
+#define R_X86_64_IRELATIVE 37
+
#define R_TYPE(name) __CONCAT(R_X86_64_,name)
#else /* !__i386__ */
diff --git a/libc/include/elf.h b/libc/include/elf.h
index 0975b7a..7a9485a 100644
--- a/libc/include/elf.h
+++ b/libc/include/elf.h
@@ -69,14 +69,15 @@
#define PT_GNU_RELRO 0x6474e552
-#define STB_LOOS 10
-#define STB_HIOS 12
-#define STB_LOPROC 13
-#define STB_HIPROC 15
+#define STB_LOOS 10
+#define STB_HIOS 12
+#define STB_LOPROC 13
+#define STB_HIPROC 15
-#define STT_LOOS 10
-#define STT_HIOS 12
-#define STT_LOPROC 13
-#define STT_HIPROC 15
+#define STT_GNU_IFUNC 10
+#define STT_LOOS 10
+#define STT_HIOS 12
+#define STT_LOPROC 13
+#define STT_HIPROC 15
#endif /* _ELF_H */
diff --git a/libc/private/ScopeGuard.h b/libc/private/ScopeGuard.h
index 183e322..d5a9235 100644
--- a/libc/private/ScopeGuard.h
+++ b/libc/private/ScopeGuard.h
@@ -14,8 +14,10 @@
* limitations under the License.
*/
-#ifndef SCOPE_GUARD_H
-#define SCOPE_GUARD_H
+#ifndef _SCOPE_GUARD_H
+#define _SCOPE_GUARD_H
+
+#include "private/bionic_macros.h"
// TODO: include explicit std::move when it becomes available
template<typename F>
@@ -40,14 +42,12 @@
F f_;
bool active_;
- ScopeGuard() = delete;
- ScopeGuard(const ScopeGuard&) = delete;
- ScopeGuard& operator=(const ScopeGuard&) = delete;
+ DISALLOW_IMPLICIT_CONSTRUCTORS(ScopeGuard);
};
template<typename T>
-ScopeGuard<T> create_scope_guard(T f) {
+ScopeGuard<T> make_scope_guard(T f) {
return ScopeGuard<T>(f);
}
-#endif // SCOPE_GUARD_H
+#endif // _SCOPE_GUARD_H
diff --git a/libc/private/UniquePtr.h b/libc/private/UniquePtr.h
new file mode 100644
index 0000000..5ac7599
--- /dev/null
+++ b/libc/private/UniquePtr.h
@@ -0,0 +1,140 @@
+/*
+ * Copyright (C) 2010 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.
+ */
+
+#ifndef UNIQUE_PTR_H_included
+#define UNIQUE_PTR_H_included
+
+// Default deleter for pointer types.
+template <typename T>
+struct DefaultDelete {
+ enum { type_must_be_complete = sizeof(T) };
+ DefaultDelete() {}
+ void operator()(T* p) const {
+ delete p;
+ }
+};
+
+// Default deleter for array types.
+template <typename T>
+struct DefaultDelete<T[]> {
+ enum { type_must_be_complete = sizeof(T) };
+ void operator()(T* p) const {
+ delete[] p;
+ }
+};
+
+// A smart pointer that deletes the given pointer on destruction.
+// Equivalent to C++0x's std::unique_ptr (a combination of boost::scoped_ptr
+// and boost::scoped_array).
+// Named to be in keeping with Android style but also to avoid
+// collision with any other implementation, until we can switch over
+// to unique_ptr.
+// Use thus:
+// UniquePtr<C> c(new C);
+template <typename T, typename D = DefaultDelete<T> >
+class UniquePtr {
+public:
+ // Construct a new UniquePtr, taking ownership of the given raw pointer.
+ explicit UniquePtr(T* ptr = nullptr) : mPtr(ptr) { }
+
+ UniquePtr(UniquePtr<T, D>&& that) {
+ mPtr = that.mPtr;
+ that.mPtr = nullptr;
+ }
+
+ ~UniquePtr() {
+ reset();
+ }
+
+ // Accessors.
+ T& operator*() const { return *mPtr; }
+ T* operator->() const { return mPtr; }
+ T* get() const { return mPtr; }
+
+ // Returns the raw pointer and hands over ownership to the caller.
+ // The pointer will not be deleted by UniquePtr.
+ T* release() __attribute__((warn_unused_result)) {
+ T* result = mPtr;
+ mPtr = nullptr;
+ return result;
+ }
+
+ // Takes ownership of the given raw pointer.
+ // If this smart pointer previously owned a different raw pointer, that
+ // raw pointer will be freed.
+ void reset(T* ptr = nullptr) {
+ if (ptr != mPtr) {
+ D()(mPtr);
+ mPtr = ptr;
+ }
+ }
+
+private:
+ // The raw pointer.
+ T* mPtr;
+
+ // Comparing unique pointers is probably a mistake, since they're unique.
+ template <typename T2> bool operator==(const UniquePtr<T2>& p) const = delete;
+ template <typename T2> bool operator!=(const UniquePtr<T2>& p) const = delete;
+
+ // Disallow copy and assignment.
+ UniquePtr(const UniquePtr&) = delete;
+ void operator=(const UniquePtr&) = delete;
+};
+
+// Partial specialization for array types. Like std::unique_ptr, this removes
+// operator* and operator-> but adds operator[].
+template <typename T, typename D>
+class UniquePtr<T[], D> {
+public:
+ explicit UniquePtr(T* ptr = NULL) : mPtr(ptr) {
+ }
+ UniquePtr(UniquePtr<T, D>&& that) {
+ mPtr = that.mPtr;
+ that.mPtr = nullptr;
+ }
+
+ ~UniquePtr() {
+ reset();
+ }
+
+ T& operator[](size_t i) const {
+ return mPtr[i];
+ }
+ T* get() const { return mPtr; }
+
+ T* release() __attribute__((warn_unused_result)) {
+ T* result = mPtr;
+ mPtr = NULL;
+ return result;
+ }
+
+ void reset(T* ptr = NULL) {
+ if (ptr != mPtr) {
+ D()(mPtr);
+ mPtr = ptr;
+ }
+ }
+
+private:
+ T* mPtr;
+
+ // Disallow copy and assignment.
+ UniquePtr(const UniquePtr&) = delete;
+ void operator=(const UniquePtr&) = delete;
+};
+
+#endif // UNIQUE_PTR_H_included
diff --git a/libc/private/bionic_macros.h b/libc/private/bionic_macros.h
index 61794bd..491b3ac 100644
--- a/libc/private/bionic_macros.h
+++ b/libc/private/bionic_macros.h
@@ -20,8 +20,8 @@
// DISALLOW_COPY_AND_ASSIGN disallows the copy and operator= functions.
// It goes in the private: declarations in a class.
#define DISALLOW_COPY_AND_ASSIGN(TypeName) \
- TypeName(const TypeName&); \
- void operator=(const TypeName&)
+ TypeName(const TypeName&) = delete; \
+ void operator=(const TypeName&) = delete
// A macro to disallow all the implicit constructors, namely the
// default constructor, copy constructor and operator= functions.
@@ -30,7 +30,7 @@
// that wants to prevent anyone from instantiating it. This is
// especially useful for classes containing only static methods.
#define DISALLOW_IMPLICIT_CONSTRUCTORS(TypeName) \
- TypeName(); \
+ TypeName() = delete; \
DISALLOW_COPY_AND_ASSIGN(TypeName)
#define BIONIC_ALIGN(value, alignment) \
diff --git a/libc/tools/zoneinfo/update-tzdata.py b/libc/tools/zoneinfo/update-tzdata.py
index e800e8f..f5681be 100755
--- a/libc/tools/zoneinfo/update-tzdata.py
+++ b/libc/tools/zoneinfo/update-tzdata.py
@@ -123,18 +123,21 @@
print 'Making ICU data...'
subprocess.check_call(['make'])
- # Copy the output files to their ultimate destination.
+ # Copy the source file to its ultimate destination.
icu_txt_data_dir = '%s/data/misc' % icu_dir
print 'Copying zoneinfo64.txt to %s ...' % icu_txt_data_dir
shutil.copy('zoneinfo64.txt', icu_txt_data_dir)
+ # Regenerate the .dat file.
os.chdir(icu_working_dir)
+ subprocess.check_call(['make', '-j32'])
+
+ # Copy the .dat file to its ultimate destination.
icu_dat_data_dir = '%s/stubdata' % icu_dir
datfiles = glob.glob('data/out/tmp/icudt??l.dat')
if len(datfiles) != 1:
print 'ERROR: Unexpectedly found %d .dat files (%s). Halting.' % (len(datfiles), datfiles)
sys.exit(1)
-
datfile = datfiles[0]
print 'Copying %s to %s ...' % (datfile, icu_dat_data_dir)
shutil.copy(datfile, icu_dat_data_dir)
diff --git a/libc/zoneinfo/tzdata b/libc/zoneinfo/tzdata
index 8d574f5..33bfe6b 100644
--- a/libc/zoneinfo/tzdata
+++ b/libc/zoneinfo/tzdata
Binary files differ
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 @@
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..6565985 100644
--- a/linker/debugger.cpp
+++ b/linker/debugger.cpp
@@ -162,12 +162,12 @@
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 @@
}
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));
}
@@ -230,7 +230,7 @@
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 @@
// 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 @@
// 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..9801fa1 100644
--- a/linker/dlfcn.cpp
+++ b/linker/dlfcn.cpp
@@ -42,7 +42,7 @@
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 @@
}
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 @@
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* 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 @@
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 @@
// 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 @@
// Determine if any symbol in the library contains the specified address.
ElfW(Sym)* sym = dladdr_find_symbol(si, addr);
- if (sym != NULL) {
+ if (sym != nullptr) {
info->dli_sname = si->strtab + sym->st_name;
- info->dli_saddr = reinterpret_cast<void*>(si->load_bias + sym->st_value);
+ info->dli_saddr = reinterpret_cast<void*>(si->resolve_symbol_address(sym));
}
return 1;
@@ -164,7 +164,7 @@
// 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 @@
(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 @@
// 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,17 +232,12 @@
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);
// 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);
@@ -250,6 +245,7 @@
__libdl_info.bucket = g_libdl_buckets;
__libdl_info.chain = g_libdl_chains;
__libdl_info.has_DT_SYMBOLIC = true;
+ __libdl_info.ref_count = 1;
}
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 @@
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 @@
}
template<typename F>
- void for_each(F&& action) {
- for (LinkedListEntry<T>* e = head_; e != nullptr; e = e->next) {
- if (e->element != nullptr) {
- action(e->element);
- }
- }
+ void for_each(F action) {
+ visit([&] (T* si) {
+ action(si);
+ return true;
+ });
}
template<typename F>
- void remove_if(F&& predicate) {
+ bool visit(F action) {
for (LinkedListEntry<T>* e = head_; e != nullptr; e = e->next) {
- if (e->element != nullptr && predicate(e->element)) {
- e->element = nullptr;
+ if (!action(e->element)) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ template<typename F>
+ 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..1befaa6 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 @@
#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;
@@ -96,7 +98,7 @@
"/vendor/lib",
"/system/lib",
#endif
- NULL
+ nullptr
};
#define LDPATH_BUFSIZE (LDPATH_MAX*64)
@@ -115,7 +117,7 @@
__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,
@@ -170,7 +172,6 @@
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() {
@@ -188,7 +189,7 @@
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) {
@@ -287,20 +288,10 @@
static soinfo* soinfo_alloc(const char* name, struct stat* file_stat) {
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);
sonext->next = si;
sonext = si;
@@ -310,7 +301,7 @@
}
static void soinfo_free(soinfo* si) {
- if (si == NULL) {
+ if (si == nullptr) {
return;
}
@@ -318,16 +309,16 @@
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);
- for (trav = solist; trav != NULL; trav = trav->next) {
+ for (trav = solist; trav != nullptr; trav = trav->next) {
if (trav == si)
break;
prev = trav;
}
- if (trav == NULL) {
+ if (trav == nullptr) {
/* si was not in solist */
DL_ERR("name \"%s\" is not in solist!", si->name);
return;
@@ -336,7 +327,7 @@
// clear links to/from si
si->remove_all_links();
- /* prev will never be NULL, because the first entry in solist is
+ /* prev will never be null, because the first entry in solist is
always the static libdl_info.
*/
prev->next = si->next;
@@ -350,7 +341,7 @@
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 +358,9 @@
// 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;
}
}
@@ -405,7 +396,7 @@
}
}
*pcount = 0;
- return NULL;
+ return nullptr;
}
#endif
@@ -414,7 +405,7 @@
* 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) {
+ 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;
@@ -463,7 +454,20 @@
name, si->name, reinterpret_cast<void*>(si->base), hash, hash % si->nbucket);
- return NULL;
+ return nullptr;
+}
+
+soinfo::soinfo(const char* name, const struct stat* file_stat) {
+ memset(this, 0, sizeof(*this));
+
+ strlcpy(this->name, name, sizeof(this->name));
+ flags = FLAG_NEW_SOINFO;
+ version = SOINFO_VERSION;
+
+ if (file_stat != nullptr) {
+ set_st_dev(file_stat->st_dev);
+ set_st_ino(file_stat->st_ino);
+ }
}
static unsigned elfhash(const char* _name) {
@@ -479,11 +483,11 @@
return h;
}
-static ElfW(Sym)* soinfo_do_lookup(soinfo* si, const char* name, soinfo** lsi, soinfo* needed[]) {
+static ElfW(Sym)* soinfo_do_lookup(soinfo* si, const char* name, soinfo** lsi) {
unsigned elf_hash = elfhash(name);
- ElfW(Sym)* s = NULL;
+ ElfW(Sym)* s = nullptr;
- if (si != NULL && somain != NULL) {
+ if (somain != nullptr) {
/*
* Local scope is executable scope. Just start looking into it right away
* for the shortcut.
@@ -491,7 +495,7 @@
if (si == somain) {
s = soinfo_elf_lookup(si, elf_hash, name);
- if (s != NULL) {
+ if (s != nullptr) {
*lsi = si;
goto done;
}
@@ -517,7 +521,7 @@
DEBUG("%s: looking up %s in executable %s",
si->name, name, somain->name);
s = soinfo_elf_lookup(somain, elf_hash, name);
- if (s != NULL) {
+ if (s != nullptr) {
*lsi = somain;
goto done;
}
@@ -543,7 +547,7 @@
* Here we return the first definition found for simplicity. */
s = soinfo_elf_lookup(si, elf_hash, name);
- if (s != NULL) {
+ if (s != nullptr) {
*lsi = si;
goto done;
}
@@ -557,7 +561,7 @@
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) {
+ if (s != nullptr) {
*lsi = somain;
goto done;
}
@@ -574,18 +578,18 @@
}
}
- 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;
+ si->get_children().visit([&](soinfo* child) {
+ DEBUG("%s: looking up %s in %s", si->name, name, child->name);
+ s = soinfo_elf_lookup(child, elf_hash, name);
+ if (s != nullptr) {
+ *lsi = child;
+ return false;
}
- }
+ return true;
+ });
done:
- if (s != 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),
@@ -594,28 +598,90 @@
return s;
}
- return NULL;
+ return nullptr;
}
-// 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 LinkedListEntry<soinfo>* alloc() {
- return g_soinfo_list_allocator_rw.alloc();
+ static void* alloc() {
+ return allocator_.alloc();
}
- static void free(LinkedListEntry<soinfo>* ptr) {
- g_soinfo_list_allocator_rw.free(ptr);
+ 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:
+ 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);
+ }
+
+ 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 +693,6 @@
if (result != nullptr) {
*found = current_soinfo;
- visit_list.clear();
- visited.clear();
return result;
}
visited.push_back(current_soinfo);
@@ -638,8 +702,6 @@
});
}
- visit_list.clear();
- visited.clear();
return nullptr;
}
@@ -651,20 +713,20 @@
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 +736,12 @@
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 +758,12 @@
}
}
- 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 +781,7 @@
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 +800,208 @@
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->strtab + 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;
+ ScopedFd file_guard(-1);
- file_guard.reset(fd);
+ if (extinfo != nullptr && (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 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;
+ 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;
+ }
+
+ // 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) {
+ TRACE("library \"%s\" is already loaded under different name/path \"%s\" - will return existing soinfo", name, si->name);
+ return si;
}
+ }
- // 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;
- }
- }
+ if ((dlflags & RTLD_NOLOAD) != 0) {
+ DL_ERR("library \"%s\" wasn't loaded and RTLD_NOLOAD prevented it", name);
+ return nullptr;
+ }
- if ((dlflags & RTLD_NOLOAD) != 0) {
- return NULL;
- }
+ // Read the ELF header and load the segments.
+ ElfReader elf_reader(name, fd);
+ if (!elf_reader.Load(extinfo)) {
+ return nullptr;
+ }
- // Read the ELF header and load the segments.
- if (!elf_reader.Load(extinfo)) {
- return NULL;
- }
+ soinfo* si = soinfo_alloc(SEARCH_NAME(name), &file_stat);
+ 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();
- 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();
+ if (!si->PrelinkImage()) {
+ soinfo_free(si);
+ return nullptr;
+ }
- // 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);
+ for_each_dt_needed(si, [&] (const char* name) {
+ load_tasks.push_back(LoadTask::create(name, si));
+ });
- if (!soinfo_link_image(si, extinfo)) {
- soinfo_free(si);
- return NULL;
- }
-
- return 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);
- }
-
- if (si != NULL && (si->flags & FLAG_LINKED) == 0) {
- DL_ERR("recursive link to \"%s\"", si->name);
- return NULL;
+ si = load_library(load_tasks, name, dlflags, extinfo);
}
return si;
}
-static soinfo* find_library(const char* name, int dlflags, const android_dlextinfo* extinfo) {
- soinfo* si = find_library_internal(name, dlflags, extinfo);
- if (si != NULL) {
- si->ref_count++;
+static void soinfo_unload(soinfo* si);
+
+static bool is_recursive(soinfo* si, soinfo* parent) {
+ if (parent == nullptr) {
+ return false;
}
+
+ if (si == parent) {
+ DL_ERR("recursive link to \"%s\"", si->name);
+ return true;
+ }
+
+ return !parent->get_parents().visit([&](soinfo* grandparent) {
+ return !is_recursive(si, grandparent);
+ });
+}
+
+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 +1010,24 @@
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);
- }
- }
}
+ } else {
+ 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 +1066,15 @@
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)) {
+ if (extinfo != nullptr && ((extinfo->flags & ~(ANDROID_DLEXT_VALID_FLAG_BITS)) != 0)) {
DL_ERR("invalid extended flags to android_dlopen_ext: %" PRIx64, extinfo->flags);
- return NULL;
+ 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 +1087,40 @@
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 = reinterpret_cast<const char*>(strtab + symtab[sym].st_name);
+ s = soinfo_do_lookup(this, sym_name, &lsi);
+ if (s == nullptr) {
// We only allow an undefined symbol if this is a weak reference...
- s = &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;
}
@@ -978,6 +1144,7 @@
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.
@@ -990,6 +1157,7 @@
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:
@@ -1002,11 +1170,9 @@
}
} 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) {
@@ -1112,10 +1278,17 @@
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:
/*
* ET_EXEC is not supported so this should not happen.
@@ -1126,7 +1299,7 @@
* 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:
TRACE_TYPE(RELO, "RELO TLS_TPREL64 *** %16llx <- %16llx - %16llx\n",
@@ -1159,8 +1332,14 @@
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;
+ 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);
@@ -1195,31 +1374,31 @@
}
#else // REL, not RELA.
-
-static int soinfo_relocate(soinfo* si, ElfW(Rel)* rel, unsigned count, soinfo* needed[]) {
- ElfW(Sym)* s;
- soinfo* lsi;
-
+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 + si->load_bias);
+ ElfW(Addr) reloc = static_cast<ElfW(Addr)>(rel->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 = reinterpret_cast<const char*>(strtab + symtab[sym].st_name);
+ s = soinfo_do_lookup(this, sym_name, &lsi);
+ if (s == nullptr) {
// We only allow an undefined symbol if this is a weak reference...
- s = &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;
}
@@ -1251,6 +1430,7 @@
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.
@@ -1270,11 +1450,9 @@
}
} 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) {
@@ -1314,7 +1492,7 @@
* 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);
+ DL_ERR("%s R_ARM_COPY relocations are not supported", name);
return -1;
#elif defined(__i386__)
case R_386_JMP_SLOT:
@@ -1362,7 +1540,7 @@
if (s) {
*reinterpret_cast<ElfW(Addr)*>(reloc) += sym_addr;
} else {
- *reinterpret_cast<ElfW(Addr)*>(reloc) += si->base;
+ *reinterpret_cast<ElfW(Addr)*>(reloc) += base;
}
break;
#endif
@@ -1379,9 +1557,17 @@
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;
+ 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);
@@ -1393,9 +1579,9 @@
#endif
#if defined(__mips__)
-static bool mips_relocate_got(soinfo* si, soinfo* needed[]) {
+static bool mips_relocate_got(soinfo* si) {
ElfW(Addr)** got = si->plt_got;
- if (got == NULL) {
+ if (got == nullptr) {
return true;
}
unsigned local_gotno = si->mips_local_gotno;
@@ -1425,9 +1611,9 @@
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) {
+ 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) {
@@ -1439,7 +1625,7 @@
// 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);
+ *got = reinterpret_cast<ElfW(Addr)*>(lsi->resolve_symbol_address(s));
}
}
return true;
@@ -1447,7 +1633,7 @@
#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 +1652,7 @@
}
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 +1688,7 @@
// 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 +1706,9 @@
}
void soinfo::CallDestructors() {
+ if (!constructors_called) {
+ return;
+ }
TRACE("\"%s\": calling destructors", name);
// DT_FINI_ARRAY must be parsed in reverse order.
@@ -1534,16 +1723,14 @@
}
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 +1742,7 @@
});
parents.for_each([&] (soinfo* parent) {
- parent->children.for_each([&] (const soinfo* child) {
+ parent->children.remove_if([&] (const soinfo* child) {
return child == this;
});
});
@@ -1566,47 +1753,59 @@
}
void soinfo::set_st_dev(dev_t dev) {
- if ((this->flags & FLAG_NEW_SOINFO) == 0) {
- return;
+ if (has_min_version(0)) {
+ st_dev = dev;
}
-
- st_dev = dev;
}
void soinfo::set_st_ino(ino_t ino) {
- if ((this->flags & FLAG_NEW_SOINFO) == 0) {
- return;
+ if (has_min_version(0)) {
+ st_ino = ino;
}
-
- st_ino = ino;
}
dev_t soinfo::get_st_dev() {
- if ((this->flags & FLAG_NEW_SOINFO) == 0) {
- return 0;
+ if (has_min_version(0)) {
+ return st_dev;
}
- return st_dev;
+ return 0;
};
ino_t soinfo::get_st_ino() {
- if ((this->flags & FLAG_NEW_SOINFO) == 0) {
- return 0;
+ if (has_min_version(0)) {
+ return st_ino;
}
- 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);
}
/* Force any of the closed stdin, stdout and stderr to be associated with
@@ -1670,84 +1869,78 @@
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 debug anything until the linker is relocated */
+ /* We can't log anything until the linker is relocated */
+ bool relocating_linker = (flags & FLAG_LINKER) != 0;
if (!relocating_linker) {
- INFO("[ linking %s ]", si->name);
- DEBUG("si->base = %p si->flags = 0x%08x", reinterpret_cast<void*>(si->base), si->flags);
+ INFO("[ linking %s ]", name);
+ DEBUG("si->base = %p si->flags = 0x%08x", reinterpret_cast<void*>(base), flags);
}
- /* 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 (dynamic == nullptr) {
if (!relocating_linker) {
- DL_ERR("missing PT_DYNAMIC in \"%s\"", si->name);
+ DL_ERR("missing PT_DYNAMIC in \"%s\"", name);
}
return false;
} else {
if (!relocating_linker) {
- DEBUG("dynamic = %p", si->dynamic);
+ 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) {
+ 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_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);
+ 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:
- si->strtab = reinterpret_cast<const char*>(base + d->d_un.d_ptr);
+ strtab = reinterpret_cast<const char*>(load_bias + d->d_un.d_ptr);
break;
case DT_SYMTAB:
- si->symtab = reinterpret_cast<ElfW(Sym)*>(base + d->d_un.d_ptr);
+ symtab = reinterpret_cast<ElfW(Sym)*>(load_bias + d->d_un.d_ptr);
break;
#if !defined(__LP64__)
case DT_PLTREL:
if (d->d_un.d_val != DT_REL) {
- DL_ERR("unsupported DT_RELA in \"%s\"", si->name);
+ DL_ERR("unsupported DT_RELA in \"%s\"", name);
return false;
}
break;
#endif
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:
#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;
#if defined(__mips__)
case DT_PLTGOT:
// Used by mips and mips64.
- si->plt_got = reinterpret_cast<ElfW(Addr)**>(base + d->d_un.d_ptr);
+ plt_got = reinterpret_cast<ElfW(Addr)**>(load_bias + d->d_un.d_ptr);
break;
#endif
case DT_DEBUG:
@@ -1755,7 +1948,7 @@
// 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) {
@@ -1765,67 +1958,67 @@
#endif
#if defined(USE_RELA)
case DT_RELA:
- si->rela = reinterpret_cast<ElfW(Rela)*>(base + d->d_un.d_ptr);
+ rela = reinterpret_cast<ElfW(Rela)*>(load_bias + d->d_un.d_ptr);
break;
case DT_RELASZ:
- si->rela_count = d->d_un.d_val / sizeof(ElfW(Rela));
+ rela_count = d->d_un.d_val / sizeof(ElfW(Rela));
break;
case DT_REL:
- DL_ERR("unsupported DT_REL in \"%s\"", si->name);
+ DL_ERR("unsupported DT_REL in \"%s\"", name);
return false;
case DT_RELSZ:
- DL_ERR("unsupported DT_RELSZ in \"%s\"", si->name);
+ 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);
+ rel = reinterpret_cast<ElfW(Rel)*>(load_bias + d->d_un.d_ptr);
break;
case DT_RELSZ:
- si->rel_count = d->d_un.d_val / sizeof(ElfW(Rel));
+ rel_count = d->d_un.d_val / sizeof(ElfW(Rel));
break;
case DT_RELA:
- DL_ERR("unsupported DT_RELA in \"%s\"", si->name);
+ 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);
+ 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:
- 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);
+ 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:
- 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);
+ 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:
- si->init_array_count = ((unsigned)d->d_un.d_val) / sizeof(ElfW(Addr));
+ 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);
+ 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:
- si->fini_array_count = ((unsigned)d->d_un.d_val) / sizeof(ElfW(Addr));
+ 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);
+ 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:
- si->preinit_array_count = ((unsigned)d->d_un.d_val) / sizeof(ElfW(Addr));
+ 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);
+ DL_ERR("text relocations (DT_TEXTREL) found in 64-bit ELF file \"%s\"", name);
return false;
#else
- si->has_text_relocations = true;
+ has_text_relocations = true;
break;
#endif
case DT_SYMBOLIC:
- si->has_DT_SYMBOLIC = true;
+ has_DT_SYMBOLIC = true;
break;
case DT_NEEDED:
++needed_count;
@@ -1833,14 +2026,14 @@
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);
+ 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;
+ has_DT_SYMBOLIC = true;
}
break;
#if defined(__mips__)
@@ -1851,7 +2044,7 @@
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);
+ r_debug** dp = reinterpret_cast<r_debug**>(load_bias + d->d_un.d_ptr);
*dp = &_r_debug;
}
break;
@@ -1862,15 +2055,15 @@
break;
case DT_MIPS_SYMTABNO:
- si->mips_symtabno = d->d_un.d_val;
+ mips_symtabno = d->d_un.d_val;
break;
case DT_MIPS_LOCAL_GOTNO:
- si->mips_local_gotno = d->d_un.d_val;
+ mips_local_gotno = d->d_un.d_val;
break;
case DT_MIPS_GOTSYM:
- si->mips_gotsym = d->d_un.d_val;
+ mips_gotsym = d->d_un.d_val;
break;
#endif
@@ -1882,150 +2075,116 @@
}
DEBUG("si->base = %p, si->strtab = %p, si->symtab = %p",
- reinterpret_cast<void*>(si->base), si->strtab, si->symtab);
+ 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);
+ if (nbucket == 0) {
+ DL_ERR("empty/missing DT_HASH in \"%s\" (built with --hash-style=gnu?)", name);
return false;
}
- if (si->strtab == 0) {
- DL_ERR("empty/missing DT_STRTAB in \"%s\"", si->name);
+ if (strtab == 0) {
+ DL_ERR("empty/missing DT_STRTAB in \"%s\"", name);
return false;
}
- if (si->symtab == 0) {
- DL_ERR("empty/missing DT_SYMTAB in \"%s\"", si->name);
+ 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) {
+ 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.", si->name);
- if (phdr_table_unprotect_segments(si->phdr, si->phnum, si->load_bias) < 0) {
+ "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",
- si->name, strerror(errno));
+ 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)) {
+ 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)) {
+ 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)) {
+ 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)) {
+ 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)) {
+ 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) {
+ if (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) {
+ if (phdr_table_protect_segments(phdr, phnum, load_bias) < 0) {
DL_ERR("can't protect segments for \"%s\": %s",
- si->name, strerror(errno));
+ 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) {
+ if (phdr_table_protect_gnu_relro(phdr, phnum, load_bias) < 0) {
DL_ERR("can't enable GNU RELRO protection for \"%s\": %s",
- si->name, strerror(errno));
+ 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,
+ if (phdr_table_serialize_gnu_relro(phdr, phnum, load_bias,
extinfo->relro_fd) < 0) {
DL_ERR("failed serializing GNU RELRO section for \"%s\": %s",
- si->name, strerror(errno));
+ 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,
+ if (phdr_table_map_gnu_relro(phdr, phnum, load_bias,
extinfo->relro_fd) < 0) {
DL_ERR("failed mapping GNU RELRO section for \"%s\": %s",
- si->name, strerror(errno));
+ name, strerror(errno));
return false;
}
}
- notify_gdb_of_load(si);
+ notify_gdb_of_load(this);
return true;
}
@@ -2037,11 +2196,11 @@
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);
si->phdr = reinterpret_cast<ElfW(Phdr)*>(reinterpret_cast<char*>(ehdr_vdso) + ehdr_vdso->e_phoff);
si->phnum = ehdr_vdso->e_phnum;
@@ -2049,14 +2208,20 @@
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);
/* gdb expects the linker to be in the debug shared object list.
* Without this, gdb has trouble locating the linker's ".text"
@@ -2066,12 +2231,6 @@
* 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 +2242,7 @@
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,16 +2252,6 @@
* 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);
@@ -2121,14 +2270,14 @@
// Get a few environment variables.
const char* LD_DEBUG = linker_env_get("LD_DEBUG");
- if (LD_DEBUG != NULL) {
+ 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;
+ 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");
@@ -2136,8 +2285,8 @@
INFO("[ android linker & debugger ]");
- soinfo* si = soinfo_alloc(args.argv[0], NULL);
- if (si == NULL) {
+ soinfo* si = soinfo_alloc(args.argv[0], nullptr);
+ if (si == nullptr) {
exit(EXIT_FAILURE);
}
@@ -2147,8 +2296,8 @@
map->l_addr = 0;
map->l_name = args.argv[0];
- map->l_prev = NULL;
- map->l_next = NULL;
+ map->l_prev = nullptr;
+ map->l_next = nullptr;
_r_debug.r_map = map;
r_debug_tail = map;
@@ -2174,7 +2323,7 @@
break;
}
}
- si->dynamic = NULL;
+ si->dynamic = nullptr;
si->ref_count = 1;
ElfW(Ehdr)* elf_hdr = reinterpret_cast<ElfW(Ehdr)*>(si->base);
@@ -2189,7 +2338,38 @@
somain = si;
- if (!soinfo_link_image(si, NULL)) {
+ si->PrelinkImage();
+
+ // Load ld_preloads and dependencies.
+ StringLinkedList needed_library_name_list;
+ size_t needed_libraries_count = 0;
+ size_t ld_preloads_count = 0;
+ while (g_ld_preload_names[ld_preloads_count] != nullptr) {
+ needed_library_name_list.push_back(g_ld_preload_names[ld_preloads_count++]);
+ ++needed_libraries_count;
+ }
+
+ for_each_dt_needed(si, [&](const char* name) {
+ needed_library_name_list.push_back(name);
+ ++needed_libraries_count;
+ });
+
+ const char* needed_library_names[needed_libraries_count];
+ soinfo* needed_library_si[needed_libraries_count];
+
+ memset(needed_library_names, 0, sizeof(needed_library_names));
+ needed_library_name_list.copy_to_array(needed_library_names, needed_libraries_count);
+
+ if (needed_libraries_count > 0 && !find_libraries(needed_library_names, needed_libraries_count, needed_library_si, g_ld_preloads, ld_preloads_count, 0, nullptr)) {
+ __libc_format_fd(2, "CANNOT LINK EXECUTABLE DEPENDENCIES: %s\n", linker_get_error_buffer());
+ exit(EXIT_FAILURE);
+ }
+
+ for (size_t i = 0; 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);
}
@@ -2198,11 +2378,7 @@
si->CallPreInitConstructors();
- for (size_t i = 0; g_ld_preloads[i] != NULL; ++i) {
- g_ld_preloads[i]->CallConstructors();
- }
-
- /* After the link_image, the si->load_bias is initialized.
+ /* 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.
@@ -2211,7 +2387,7 @@
si->CallConstructors();
#if TIMING
- gettimeofday(&t1, NULL);
+ 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)));
@@ -2290,10 +2466,6 @@
* 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 +2473,7 @@
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);
// 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 +2485,15 @@
__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 +2505,17 @@
_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..3abab29 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)();
@@ -194,10 +197,17 @@
#if !defined(__LP64__)
bool has_text_relocations;
#endif
+ // TODO: remove this flag, dynamic linker
+ // should not use it in any way.
bool has_DT_SYMBOLIC;
+
+ soinfo(const char* name, const struct stat* file_stat);
+
void CallConstructors();
void CallDestructors();
void CallPreInitConstructors();
+ bool PrelinkImage();
+ bool LinkImage(const android_dlextinfo* extinfo);
void add_child(soinfo* child);
void remove_all_links();
@@ -208,16 +218,28 @@
dev_t get_st_dev();
soinfo_list_t& get_children();
+ soinfo_list_t& get_parents();
+ ElfW(Addr) resolve_symbol_address(ElfW(Sym)* s);
+
+ bool inline has_min_version(uint32_t min_version) {
+ 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 +247,7 @@
soinfo_list_t children;
soinfo_list_t parents;
+ // version >= 1
};
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 @@
// 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 @@
return envstr + i + 1;
}
- return NULL;
+ return nullptr;
}
static bool __is_valid_environment_variable(const char* name) {
@@ -78,7 +78,7 @@
// 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 @@
"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 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 @@
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 @@
}
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 @@
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..44c8e9e 100644
--- a/linker/linker_phdr.cpp
+++ b/linker/linker_phdr.cpp
@@ -121,13 +121,13 @@
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) {
+ 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_);
}
}
@@ -225,7 +225,7 @@
phdr_size_ = page_max - page_min;
- void* mmap_result = mmap(NULL, phdr_size_, PROT_READ, MAP_PRIVATE, fd_, page_min);
+ void* mmap_result = mmap(nullptr, phdr_size_, PROT_READ, MAP_PRIVATE, fd_, page_min);
if (mmap_result == MAP_FAILED) {
DL_ERR("\"%s\" phdr mmap failed: %s", name_, strerror(errno));
return false;
@@ -242,7 +242,7 @@
* 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 +276,10 @@
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 +301,7 @@
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;
@@ -585,9 +585,9 @@
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 +667,7 @@
* 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 +687,37 @@
*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;
+ 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;
}
-
- *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;
- }
- return;
- }
- *dynamic = NULL;
- if (dynamic_count) {
- *dynamic_count = 0;
}
}
diff --git a/linker/linker_phdr.h b/linker/linker_phdr.h
index 611f1a7..593fb5a 100644
--- a/linker/linker_phdr.h
+++ b/linker/linker_phdr.h
@@ -81,7 +81,7 @@
};
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 +101,7 @@
#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 @@
});
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 @@
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());
+}
+
diff --git a/tests/Android.build.mk b/tests/Android.build.mk
index d4b0396..d54c851 100644
--- a/tests/Android.build.mk
+++ b/tests/Android.build.mk
@@ -37,6 +37,10 @@
LOCAL_FORCE_STATIC_EXECUTABLE := $($(module)_force_static_executable)
+ifneq ($($(module)_multilib),)
+ LOCAL_MULTILIB := $($(module)_multilib)
+endif
+
LOCAL_CFLAGS := \
$(common_cflags) \
$($(module)_cflags) \
diff --git a/tests/Android.mk b/tests/Android.mk
index 8184bf7..69ff811 100644
--- a/tests/Android.mk
+++ b/tests/Android.mk
@@ -112,6 +112,7 @@
system_properties_test.cpp \
time_test.cpp \
uchar_test.cpp \
+ uniqueptr_test.cpp \
unistd_test.cpp \
wchar_test.cpp \
@@ -256,6 +257,7 @@
-Wl,-u,DlSymTestFunction \
bionic-unit-tests_c_includes := \
+ bionic/libc \
$(call include-path-for, libpagemap) \
bionic-unit-tests_shared_libraries_target := \
@@ -356,6 +358,22 @@
$(TARGET_OUT_DATA_NATIVE_TESTS)/bionic-unit-tests/bionic-unit-tests$(NATIVE_TEST_SUFFIX) $(BIONIC_TEST_FLAGS)
endif
+ifeq ($(TARGET_ARCH),$(filter $(TARGET_ARCH),x86_64))
+# add target to run lp32 tests
+bionic-unit-tests-run-on-host32: bionic-unit-tests_32 $(TARGET_OUT_EXECUTABLES)/$(LINKER) $(TARGET_OUT_EXECUTABLES)/sh
+ if [ ! -d /system -o ! -d /system/bin ]; then \
+ echo "Attempting to create /system/bin"; \
+ sudo mkdir -p -m 0777 /system/bin; \
+ fi
+ mkdir -p $(TARGET_OUT_DATA)/local/tmp
+ cp $(TARGET_OUT_EXECUTABLES)/linker /system/bin
+ cp $(TARGET_OUT_EXECUTABLES)/sh /system/bin
+ ANDROID_DATA=$(TARGET_OUT_DATA) \
+ ANDROID_ROOT=$(TARGET_OUT) \
+ LD_LIBRARY_PATH=$(2ND_TARGET_OUT_SHARED_LIBRARIES) \
+ $(2ND_TARGET_OUT_DATA_NATIVE_TESTS)/bionic-unit-tests/bionic-unit-tests32 $(BIONIC_TEST_FLAGS)
+endif
+
endif # linux-x86
include $(call first-makefiles-under,$(LOCAL_PATH))
diff --git a/tests/dlfcn_test.cpp b/tests/dlfcn_test.cpp
index 457fcd5..9c9fbdd 100644
--- a/tests/dlfcn_test.cpp
+++ b/tests/dlfcn_test.cpp
@@ -22,6 +22,8 @@
#include <stdio.h>
#include <stdint.h>
+#include "private/ScopeGuard.h"
+
#include <string>
#define ASSERT_SUBSTR(needle, haystack) \
@@ -87,6 +89,139 @@
ASSERT_EQ(0, dlclose(handle2));
}
+// ifuncs are only supported on intel and arm64 for now
+#if defined(__i386__) || defined(__x86_64__)
+TEST(dlfcn, ifunc) {
+ typedef const char* (*fn_ptr)();
+
+ // ifunc's choice depends on whether IFUNC_CHOICE has a value
+ // first check the set case
+ setenv("IFUNC_CHOICE", "set", 1);
+ void* handle = dlopen("libtest_ifunc.so", RTLD_NOW);
+ ASSERT_TRUE(handle != NULL);
+ fn_ptr foo_ptr = reinterpret_cast<fn_ptr>(dlsym(handle, "foo"));
+ fn_ptr foo_library_ptr = reinterpret_cast<fn_ptr>(dlsym(handle, "foo_library"));
+ ASSERT_TRUE(foo_ptr != NULL);
+ ASSERT_TRUE(foo_library_ptr != NULL);
+ ASSERT_EQ(strncmp("set", foo_ptr(), 3), 0);
+ ASSERT_EQ(strncmp("set", foo_library_ptr(), 3), 0);
+ dlclose(handle);
+
+ // then check the unset case
+ unsetenv("IFUNC_CHOICE");
+ handle = dlopen("libtest_ifunc.so", RTLD_NOW);
+ ASSERT_TRUE(handle != NULL);
+ foo_ptr = reinterpret_cast<fn_ptr>(dlsym(handle, "foo"));
+ foo_library_ptr = reinterpret_cast<fn_ptr>(dlsym(handle, "foo_library"));
+ ASSERT_TRUE(foo_ptr != NULL);
+ ASSERT_TRUE(foo_library_ptr != NULL);
+ ASSERT_EQ(strncmp("unset", foo_ptr(), 5), 0);
+ ASSERT_EQ(strncmp("unset", foo_library_ptr(), 3), 0);
+ dlclose(handle);
+}
+
+TEST(dlfcn, ifunc_ctor_call) {
+ typedef const char* (*fn_ptr)();
+
+ void* handle = dlopen("libtest_ifunc.so", RTLD_NOW);
+ ASSERT_TRUE(handle != nullptr) << dlerror();
+ fn_ptr is_ctor_called = reinterpret_cast<fn_ptr>(dlsym(handle, "is_ctor_called_irelative"));
+ ASSERT_TRUE(is_ctor_called != nullptr) << dlerror();
+ ASSERT_STREQ("false", is_ctor_called());
+
+ is_ctor_called = reinterpret_cast<fn_ptr>(dlsym(handle, "is_ctor_called_jump_slot"));
+ ASSERT_TRUE(is_ctor_called != nullptr) << dlerror();
+ ASSERT_STREQ("true", is_ctor_called());
+ dlclose(handle);
+}
+#endif
+
+TEST(dlfcn, dlopen_check_relocation_dt_needed_order) {
+ // This is the structure of the test library and
+ // its dt_needed libraries
+ // libtest_relo_check_dt_needed_order.so
+ // |
+ // +-> libtest_relo_check_dt_needed_order_1.so
+ // |
+ // +-> libtest_relo_check_dt_needed_order_2.so
+ //
+ // The root library references relo_test_get_answer_lib - which is defined
+ // in both dt_needed libraries, the correct relocation should
+ // use the function defined in libtest_relo_check_dt_needed_order_1.so
+ void* handle = nullptr;
+ auto guard = make_scope_guard([&]() {
+ dlclose(handle);
+ });
+
+ handle = dlopen("libtest_relo_check_dt_needed_order.so", RTLD_NOW);
+ ASSERT_TRUE(handle != nullptr) << dlerror();
+
+ typedef int (*fn_t) (void);
+ fn_t fn = reinterpret_cast<fn_t>(dlsym(handle, "relo_test_get_answer"));
+ ASSERT_TRUE(fn != nullptr) << dlerror();
+ ASSERT_EQ(1, fn());
+}
+
+TEST(dlfcn, dlopen_check_order) {
+ // Here is how the test library and its dt_needed
+ // libraries are arranged
+ //
+ // libtest_check_order.so
+ // |
+ // +-> libtest_check_order_1_left.so
+ // | |
+ // | +-> libtest_check_order_a.so
+ // | |
+ // | +-> libtest_check_order_b.so
+ // |
+ // +-> libtest_check_order_2_right.so
+ // | |
+ // | +-> libtest_check_order_d.so
+ // | |
+ // | +-> libtest_check_order_b.so
+ // |
+ // +-> libtest_check_order_3_c.so
+ //
+ // load order should be (1, 2, 3, a, b, d)
+ //
+ // get_answer() is defined in (2, 3, a, b, c)
+ // get_answer2() is defined in (b, d)
+ void* sym = dlsym(RTLD_DEFAULT, "dlopen_test_get_answer");
+ ASSERT_TRUE(sym == nullptr);
+ void* handle = dlopen("libtest_check_order.so", RTLD_NOW);
+ ASSERT_TRUE(handle != nullptr);
+ typedef int (*fn_t) (void);
+ fn_t fn, fn2;
+ fn = reinterpret_cast<fn_t>(dlsym(RTLD_DEFAULT, "dlopen_test_get_answer"));
+ ASSERT_TRUE(fn != NULL);
+ fn2 = reinterpret_cast<fn_t>(dlsym(RTLD_DEFAULT, "dlopen_test_get_answer2"));
+ ASSERT_TRUE(fn2 != NULL);
+
+ ASSERT_EQ(42, fn());
+ ASSERT_EQ(43, fn2());
+ dlclose(handle);
+}
+
+// libtest_with_dependency_loop.so -> libtest_with_dependency_loop_a.so ->
+// libtest_with_dependency_loop_b.so -> libtest_with_dependency_loop_c.so ->
+// libtest_with_dependency_loop_a.so
+TEST(dlfcn, dlopen_check_loop) {
+ void* handle = dlopen("libtest_with_dependency_loop.so", RTLD_NOW);
+ ASSERT_TRUE(handle == nullptr);
+ ASSERT_STREQ("dlopen failed: recursive link to \"libtest_with_dependency_loop_a.so\"", dlerror());
+ // This symbol should never be exposed
+ void* f = dlsym(RTLD_DEFAULT, "dlopen_test_invalid_function");
+ ASSERT_TRUE(f == nullptr);
+ ASSERT_SUBSTR("undefined symbol: dlopen_test_invalid_function", dlerror());
+
+ // dlopen second time to make sure that the library wasn't loaded even though dlopen returned null.
+ // This may happen if during cleanup the root library or one of the depended libs were not removed
+ // from soinfo list.
+ handle = dlopen("libtest_with_dependency_loop.so", RTLD_NOW | RTLD_NOLOAD);
+ ASSERT_TRUE(handle == nullptr);
+ ASSERT_STREQ("dlopen failed: library \"libtest_with_dependency_loop.so\" wasn't loaded and RTLD_NOLOAD prevented it", dlerror());
+}
+
TEST(dlfcn, dlopen_failure) {
void* self = dlopen("/does/not/exist", RTLD_NOW);
ASSERT_TRUE(self == NULL);
diff --git a/tests/libs/Android.mk b/tests/libs/Android.mk
index 75df539..b355488 100644
--- a/tests/libs/Android.mk
+++ b/tests/libs/Android.mk
@@ -102,6 +102,183 @@
include $(TEST_PATH)/Android.build.mk
# -----------------------------------------------------------------------------
+# Libraries used by dlfcn tests to verify correct load order:
+# libtest_check_order_2_right.so
+# -----------------------------------------------------------------------------
+libtest_check_order_2_right_src_files := \
+ dlopen_testlib_answer.cpp
+
+libtest_check_order_2_right_cflags := -D__ANSWER=42
+module := libtest_check_order_2_right
+build_type := target
+build_target := SHARED_LIBRARY
+include $(TEST_PATH)/Android.build.mk
+
+# -----------------------------------------------------------------------------
+# libtest_check_order_a.so
+# -----------------------------------------------------------------------------
+libtest_check_order_a_src_files := \
+ dlopen_testlib_answer.cpp
+
+libtest_check_order_a_cflags := -D__ANSWER=1
+module := libtest_check_order_a
+build_type := target
+build_target := SHARED_LIBRARY
+include $(TEST_PATH)/Android.build.mk
+
+# -----------------------------------------------------------------------------
+# libtest_check_order_b.so
+# -----------------------------------------------------------------------------
+libtest_check_order_b_src_files := \
+ dlopen_testlib_answer.cpp
+
+libtest_check_order_b_cflags := -D__ANSWER=2 -D__ANSWER2=43
+module := libtest_check_order_b
+build_type := target
+build_target := SHARED_LIBRARY
+include $(TEST_PATH)/Android.build.mk
+
+# -----------------------------------------------------------------------------
+# libtest_check_order_c.so
+# -----------------------------------------------------------------------------
+libtest_check_order_3_c_src_files := \
+ dlopen_testlib_answer.cpp
+
+libtest_check_order_3_c_cflags := -D__ANSWER=3
+module := libtest_check_order_3_c
+build_type := target
+build_target := SHARED_LIBRARY
+include $(TEST_PATH)/Android.build.mk
+
+# -----------------------------------------------------------------------------
+# libtest_check_order_d.so
+# -----------------------------------------------------------------------------
+libtest_check_order_d_src_files := \
+ dlopen_testlib_answer.cpp
+
+libtest_check_order_d_shared_libraries := libtest_check_order_b
+libtest_check_order_d_cflags := -D__ANSWER=4 -D__ANSWER2=4
+module := libtest_check_order_d
+build_type := target
+build_target := SHARED_LIBRARY
+include $(TEST_PATH)/Android.build.mk
+
+# -----------------------------------------------------------------------------
+# libtest_check_order_left.so
+# -----------------------------------------------------------------------------
+libtest_check_order_1_left_src_files := \
+ empty.cpp
+
+libtest_check_order_1_left_shared_libraries := libtest_check_order_a libtest_check_order_b
+
+module := libtest_check_order_1_left
+build_type := target
+build_target := SHARED_LIBRARY
+include $(TEST_PATH)/Android.build.mk
+
+# -----------------------------------------------------------------------------
+# libtest_check_order.so
+# -----------------------------------------------------------------------------
+libtest_check_order_src_files := \
+ empty.cpp
+
+libtest_check_order_shared_libraries := libtest_check_order_1_left \
+ libtest_check_order_2_right libtest_check_order_3_c
+
+module := libtest_check_order
+build_type := target
+build_target := SHARED_LIBRARY
+include $(TEST_PATH)/Android.build.mk
+
+# -----------------------------------------------------------------------------
+# Library with dependency loop used by dlfcn tests
+#
+# libtest_with_dependency_loop -> a -> b -> c -> a
+# -----------------------------------------------------------------------------
+libtest_with_dependency_loop_src_files := dlopen_testlib_invalid.cpp
+
+libtest_with_dependency_loop_shared_libraries := \
+ libtest_with_dependency_loop_a
+
+module := libtest_with_dependency_loop
+build_type := target
+build_target := SHARED_LIBRARY
+include $(TEST_PATH)/Android.build.mk
+
+# -----------------------------------------------------------------------------
+# libtest_with_dependency_loop_a.so
+# -----------------------------------------------------------------------------
+libtest_with_dependency_loop_a_src_files := dlopen_testlib_invalid.cpp
+
+libtest_with_dependency_loop_a_shared_libraries := \
+ libtest_with_dependency_loop_b_tmp
+
+module := libtest_with_dependency_loop_a
+build_type := target
+build_target := SHARED_LIBRARY
+include $(TEST_PATH)/Android.build.mk
+
+# -----------------------------------------------------------------------------
+# libtest_with_dependency_loop_b.so
+#
+# this is temporary placeholder - will be removed
+# -----------------------------------------------------------------------------
+libtest_with_dependency_loop_b_tmp_src_files := dlopen_testlib_invalid.cpp
+libtest_with_dependency_loop_b_tmp_ldflags := -Wl,-soname=libtest_with_dependency_loop_b.so
+
+module := libtest_with_dependency_loop_b_tmp
+build_type := target
+build_target := SHARED_LIBRARY
+include $(TEST_PATH)/Android.build.mk
+
+# -----------------------------------------------------------------------------
+# libtest_with_dependency_loop_b.so
+# -----------------------------------------------------------------------------
+libtest_with_dependency_loop_b_src_files := dlopen_testlib_invalid.cpp
+libtest_with_dependency_loop_b_shared_libraries := libtest_with_dependency_loop_c
+
+module := libtest_with_dependency_loop_b
+build_type := target
+build_target := SHARED_LIBRARY
+include $(TEST_PATH)/Android.build.mk
+
+# -----------------------------------------------------------------------------
+# libtest_with_dependency_loop_c.so
+# -----------------------------------------------------------------------------
+libtest_with_dependency_loop_c_src_files := dlopen_testlib_invalid.cpp
+
+libtest_with_dependency_loop_c_shared_libraries := \
+ libtest_with_dependency_loop_a
+
+module := libtest_with_dependency_loop_c
+build_type := target
+build_target := SHARED_LIBRARY
+include $(TEST_PATH)/Android.build.mk
+
+# -----------------------------------------------------------------------------
+# libtest_relo_check_dt_needed_order.so
+# |
+# +-> libtest_relo_check_dt_needed_order_1.so
+# |
+# +-> libtest_relo_check_dt_needed_order_2.so
+# -----------------------------------------------------------------------------
+libtest_relo_check_dt_needed_order_shared_libraries := \
+ libtest_relo_check_dt_needed_order_1 libtest_relo_check_dt_needed_order_2
+
+libtest_relo_check_dt_needed_order_src_files := dlopen_testlib_relo_check_dt_needed_order.cpp
+libtest_relo_check_dt_needed_order_1_src_files := dlopen_testlib_relo_check_dt_needed_order_1.cpp
+libtest_relo_check_dt_needed_order_2_src_files := dlopen_testlib_relo_check_dt_needed_order_2.cpp
+build_type := target
+build_target := SHARED_LIBRARY
+
+module := libtest_relo_check_dt_needed_order
+include $(TEST_PATH)/Android.build.mk
+module := libtest_relo_check_dt_needed_order_1
+include $(TEST_PATH)/Android.build.mk
+module := libtest_relo_check_dt_needed_order_2
+include $(TEST_PATH)/Android.build.mk
+
+# -----------------------------------------------------------------------------
# Library with dependency used by dlfcn tests
# -----------------------------------------------------------------------------
libtest_with_dependency_src_files := \
@@ -115,6 +292,21 @@
include $(TEST_PATH)/Android.build.mk
# -----------------------------------------------------------------------------
+# Library used by ifunc tests
+# -----------------------------------------------------------------------------
+ifeq ($(TARGET_ARCH),$(filter $(TARGET_ARCH),x86 x86_64))
+ libtest_ifunc_src_files := \
+ dlopen_testlib_ifunc.c
+
+ LOCAL_SDK_VERSION := current
+ module := libtest_ifunc
+ build_type := target
+ build_target := SHARED_LIBRARY
+
+ include $(TEST_PATH)/Android.build.mk
+endif
+
+# -----------------------------------------------------------------------------
# Library used by atexit tests
# -----------------------------------------------------------------------------
diff --git a/tests/libs/dlopen_testlib_answer.cpp b/tests/libs/dlopen_testlib_answer.cpp
new file mode 100644
index 0000000..a4d7504
--- /dev/null
+++ b/tests/libs/dlopen_testlib_answer.cpp
@@ -0,0 +1,25 @@
+/*
+ * Copyright (C) 2014 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+extern "C" int dlopen_test_get_answer() {
+ return __ANSWER;
+}
+
+#ifdef __ANSWER2
+extern "C" int dlopen_test_get_answer2() {
+ return __ANSWER2;
+}
+#endif
diff --git a/tests/libs/dlopen_testlib_ifunc.c b/tests/libs/dlopen_testlib_ifunc.c
new file mode 100644
index 0000000..b68a3dd
--- /dev/null
+++ b/tests/libs/dlopen_testlib_ifunc.c
@@ -0,0 +1,65 @@
+/*
+ * 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 <stdio.h>
+#include <stdlib.h>
+
+static int g_flag = 0;
+
+static void __attribute__((constructor)) init_flag() {
+ g_flag = 1;
+}
+
+static const char* is_ctor_called() __attribute__ ((ifunc("is_ctor_called_ifun")));
+
+const char* foo() __attribute__ ((ifunc ("foo_ifunc")));
+
+// Static linker creates GLOBAL/IFUNC symbol and JUMP_SLOT relocation type for plt segment
+const char* is_ctor_called_jump_slot() __attribute__ ((ifunc("is_ctor_called_ifun")));
+
+const char* is_ctor_called_irelative() {
+ // Call internal ifunc-resolved function with IRELATIVE reloc
+ return is_ctor_called();
+}
+
+const char* return_true() {
+ return "true";
+}
+
+const char* return_false() {
+ return "false";
+}
+
+const char* f1() {
+ return "unset";
+}
+
+const char* f2() {
+ return "set";
+}
+
+void* is_ctor_called_ifun() {
+ return g_flag == 0 ? return_false : return_true;
+}
+
+void* foo_ifunc() {
+ char* choice = getenv("IFUNC_CHOICE");
+ return choice == NULL ? f1 : f2;
+}
+
+const char* foo_library() {
+ return foo();
+}
diff --git a/tests/libs/dlopen_testlib_invalid.cpp b/tests/libs/dlopen_testlib_invalid.cpp
new file mode 100644
index 0000000..f2039c6
--- /dev/null
+++ b/tests/libs/dlopen_testlib_invalid.cpp
@@ -0,0 +1,24 @@
+/*
+ * 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 <stdlib.h>
+
+// This file is used for libraries that are not supposed to
+// be successfully loaded/linked - therefore, this function should
+// not be visible via dlsym - (we are going to use this fact in tests)
+extern "C" int dlopen_test_invalid_function() {
+ abort();
+}
diff --git a/tests/libs/dlopen_testlib_relo_check_dt_needed_order.cpp b/tests/libs/dlopen_testlib_relo_check_dt_needed_order.cpp
new file mode 100644
index 0000000..d8fb543
--- /dev/null
+++ b/tests/libs/dlopen_testlib_relo_check_dt_needed_order.cpp
@@ -0,0 +1,21 @@
+/*
+ * Copyright (C) 2014 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+extern "C" int relo_test_get_answer_lib();
+
+extern "C" int relo_test_get_answer() {
+ return relo_test_get_answer_lib();
+}
diff --git a/tests/libs/dlopen_testlib_relo_check_dt_needed_order_1.cpp b/tests/libs/dlopen_testlib_relo_check_dt_needed_order_1.cpp
new file mode 100644
index 0000000..4c877d0
--- /dev/null
+++ b/tests/libs/dlopen_testlib_relo_check_dt_needed_order_1.cpp
@@ -0,0 +1,19 @@
+/*
+ * Copyright (C) 2014 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+extern "C" int relo_test_get_answer_lib() {
+ return 1;
+}
diff --git a/tests/libs/dlopen_testlib_relo_check_dt_needed_order_2.cpp b/tests/libs/dlopen_testlib_relo_check_dt_needed_order_2.cpp
new file mode 100644
index 0000000..10288a0
--- /dev/null
+++ b/tests/libs/dlopen_testlib_relo_check_dt_needed_order_2.cpp
@@ -0,0 +1,19 @@
+/*
+ * Copyright (C) 2014 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+extern "C" int relo_test_get_answer_lib() {
+ return 2;
+}
diff --git a/tests/math_test.cpp b/tests/math_test.cpp
index b4f5b14..2203db9 100644
--- a/tests/math_test.cpp
+++ b/tests/math_test.cpp
@@ -53,6 +53,8 @@
#include <limits.h>
#include <stdint.h>
+#include <private/ScopeGuard.h>
+
float float_subnormal() {
union {
float f;
@@ -760,6 +762,10 @@
}
TEST(math, lrint) {
+ auto guard = make_scope_guard([]() {
+ fesetenv(FE_DFL_ENV);
+ });
+
fesetround(FE_UPWARD); // lrint/lrintf/lrintl obey the rounding mode.
ASSERT_EQ(1235, lrint(1234.01));
ASSERT_EQ(1235, lrintf(1234.01f));
@@ -780,6 +786,10 @@
}
TEST(math, rint) {
+ auto guard = make_scope_guard([]() {
+ fesetenv(FE_DFL_ENV);
+ });
+
fesetround(FE_UPWARD); // rint/rintf/rintl obey the rounding mode.
feclearexcept(FE_ALL_EXCEPT); // rint/rintf/rintl do set the FE_INEXACT flag.
ASSERT_EQ(1234.0, rint(1234.0));
@@ -806,6 +816,9 @@
}
TEST(math, nearbyint) {
+ auto guard = make_scope_guard([]() {
+ fesetenv(FE_DFL_ENV);
+ });
fesetround(FE_UPWARD); // nearbyint/nearbyintf/nearbyintl obey the rounding mode.
feclearexcept(FE_ALL_EXCEPT); // nearbyint/nearbyintf/nearbyintl don't set the FE_INEXACT flag.
ASSERT_EQ(1234.0, nearbyint(1234.0));
@@ -832,6 +845,9 @@
}
TEST(math, lround) {
+ auto guard = make_scope_guard([]() {
+ fesetenv(FE_DFL_ENV);
+ });
fesetround(FE_UPWARD); // lround ignores the rounding mode.
ASSERT_EQ(1234, lround(1234.01));
ASSERT_EQ(1234, lroundf(1234.01f));
@@ -839,6 +855,9 @@
}
TEST(math, llround) {
+ auto guard = make_scope_guard([]() {
+ fesetenv(FE_DFL_ENV);
+ });
fesetround(FE_UPWARD); // llround ignores the rounding mode.
ASSERT_EQ(1234L, llround(1234.01));
ASSERT_EQ(1234L, llroundf(1234.01f));
@@ -933,6 +952,9 @@
}
TEST(math, round) {
+ auto guard = make_scope_guard([]() {
+ fesetenv(FE_DFL_ENV);
+ });
fesetround(FE_TOWARDZERO); // round ignores the rounding mode and always rounds away from zero.
ASSERT_DOUBLE_EQ(1.0, round(0.5));
ASSERT_DOUBLE_EQ(-1.0, round(-0.5));
@@ -943,6 +965,9 @@
}
TEST(math, roundf) {
+ auto guard = make_scope_guard([]() {
+ fesetenv(FE_DFL_ENV);
+ });
fesetround(FE_TOWARDZERO); // roundf ignores the rounding mode and always rounds away from zero.
ASSERT_FLOAT_EQ(1.0f, roundf(0.5f));
ASSERT_FLOAT_EQ(-1.0f, roundf(-0.5f));
@@ -953,6 +978,9 @@
}
TEST(math, roundl) {
+ auto guard = make_scope_guard([]() {
+ fesetenv(FE_DFL_ENV);
+ });
fesetround(FE_TOWARDZERO); // roundl ignores the rounding mode and always rounds away from zero.
ASSERT_DOUBLE_EQ(1.0L, roundl(0.5L));
ASSERT_DOUBLE_EQ(-1.0L, roundl(-0.5L));
@@ -963,6 +991,9 @@
}
TEST(math, trunc) {
+ auto guard = make_scope_guard([]() {
+ fesetenv(FE_DFL_ENV);
+ });
fesetround(FE_UPWARD); // trunc ignores the rounding mode and always rounds toward zero.
ASSERT_DOUBLE_EQ(1.0, trunc(1.5));
ASSERT_DOUBLE_EQ(-1.0, trunc(-1.5));
@@ -973,6 +1004,9 @@
}
TEST(math, truncf) {
+ auto guard = make_scope_guard([]() {
+ fesetenv(FE_DFL_ENV);
+ });
fesetround(FE_UPWARD); // truncf ignores the rounding mode and always rounds toward zero.
ASSERT_FLOAT_EQ(1.0f, truncf(1.5f));
ASSERT_FLOAT_EQ(-1.0f, truncf(-1.5f));
@@ -983,6 +1017,9 @@
}
TEST(math, truncl) {
+ auto guard = make_scope_guard([]() {
+ fesetenv(FE_DFL_ENV);
+ });
fesetround(FE_UPWARD); // truncl ignores the rounding mode and always rounds toward zero.
ASSERT_DOUBLE_EQ(1.0L, truncl(1.5L));
ASSERT_DOUBLE_EQ(-1.0L, truncl(-1.5L));
diff --git a/tests/pthread_test.cpp b/tests/pthread_test.cpp
index 4a7c6bd..32bb54c 100644
--- a/tests/pthread_test.cpp
+++ b/tests/pthread_test.cpp
@@ -869,7 +869,7 @@
#endif
EXPECT_EQ(rl.rlim_cur, stack_size);
- auto guard = create_scope_guard([&rl, original_rlim_cur]() {
+ auto guard = make_scope_guard([&rl, original_rlim_cur]() {
rl.rlim_cur = original_rlim_cur;
ASSERT_EQ(0, setrlimit(RLIMIT_STACK, &rl));
});
diff --git a/tests/string_test.cpp b/tests/string_test.cpp
index 73c94c6..f1ac9dd 100644
--- a/tests/string_test.cpp
+++ b/tests/string_test.cpp
@@ -173,7 +173,7 @@
const size_t MAX_LEN;
Character *ptr, *ptr1, *ptr2;
size_t n;
- int len[ITER + 1];
+ size_t len[ITER + 1];
private:
Character *glob_ptr, *glob_ptr1, *glob_ptr2;
@@ -186,7 +186,7 @@
n = 0;
len[n++] = 0;
for (size_t i = 1; i < ITER; ++i) {
- int l = (int) exp(log((double) MAX_LEN) * i / ITER);
+ size_t l = static_cast<size_t>(exp(log(static_cast<double>(MAX_LEN)) * i / ITER));
if (l != len[n - 1]) {
len[n++] = l;
}
@@ -392,7 +392,7 @@
}
state.ptr1[state.len[i] - 1] = '\0';
- int pos = random() % state.MAX_LEN;
+ size_t pos = random() % state.MAX_LEN;
char* expected;
if (pos >= state.len[i] - 1) {
if (seek_char == 0) {
@@ -421,7 +421,7 @@
state.ptr1[state.len[i] - 1] = '\0';
state.ptr2[state.len[i] - 1] = '\0';
- int pos = 1 + (random() % (state.MAX_LEN - 1));
+ size_t pos = 1 + (random() % (state.MAX_LEN - 1));
int actual;
int expected;
if (pos >= state.len[i] - 1) {
@@ -510,7 +510,7 @@
state.ptr2[state.MAX_LEN - 1] = '\0';
memcpy(state.ptr, state.ptr2, state.MAX_LEN + state.len[i]);
- int pos = random() % state.MAX_LEN;
+ size_t pos = random() % state.MAX_LEN;
memset(state.ptr1, '\3', pos);
state.ptr1[pos] = '\0';
if (pos < state.len[i]) {
@@ -604,7 +604,7 @@
state.ptr1[state.len[i] - 1] = '\0';
state.ptr2[state.len[i] - 1] = '\0';
- int pos = 1 + (random() % (state.MAX_LEN - 1));
+ size_t pos = 1 + (random() % (state.MAX_LEN - 1));
int actual;
int expected;
if (pos >= state.len[i] - 1) {
@@ -722,7 +722,7 @@
}
state.ptr1[state.len[i] - 1] = '\0';
- int pos = random() % state.MAX_LEN;
+ size_t pos = random() % state.MAX_LEN;
char* expected;
if (pos >= state.len[i] - 1) {
if (seek_char == 0) {
@@ -749,7 +749,7 @@
memset(state.ptr1, ~seek_char, state.len[i]);
- int pos = random() % state.MAX_LEN;
+ size_t pos = random() % state.MAX_LEN;
char* expected;
if (pos >= state.len[i]) {
expected = NULL;
@@ -780,7 +780,7 @@
memset(state.ptr1, ~seek_char, state.len[i]);
- int pos = random() % state.MAX_LEN;
+ size_t pos = random() % state.MAX_LEN;
char* expected;
if (pos >= state.len[i]) {
expected = NULL;
diff --git a/tests/uniqueptr_test.cpp b/tests/uniqueptr_test.cpp
new file mode 100644
index 0000000..4b6608a
--- /dev/null
+++ b/tests/uniqueptr_test.cpp
@@ -0,0 +1,101 @@
+/*
+ * 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 <gtest/gtest.h>
+
+#include <private/UniquePtr.h>
+
+static int cCount = 0;
+struct C {
+ C() { ++cCount; }
+ ~C() { --cCount; }
+};
+
+static bool freed = false;
+struct Freer {
+ void operator() (int* p) {
+ ASSERT_EQ(123, *p);
+ free(p);
+ freed = true;
+ }
+};
+
+TEST(UniquePtr, smoke) {
+ //
+ // UniquePtr<T> tests...
+ //
+
+ // Can we free a single object?
+ {
+ UniquePtr<C> c(new C);
+ ASSERT_TRUE(cCount == 1);
+ }
+ ASSERT_TRUE(cCount == 0);
+ // Does release work?
+ C* rawC;
+ {
+ UniquePtr<C> c(new C);
+ ASSERT_TRUE(cCount == 1);
+ rawC = c.release();
+ }
+ ASSERT_TRUE(cCount == 1);
+ delete rawC;
+ // Does reset work?
+ {
+ UniquePtr<C> c(new C);
+ ASSERT_TRUE(cCount == 1);
+ c.reset(new C);
+ ASSERT_TRUE(cCount == 1);
+ }
+ ASSERT_TRUE(cCount == 0);
+
+ //
+ // UniquePtr<T[]> tests...
+ //
+
+ // Can we free an array?
+ {
+ UniquePtr<C[]> cs(new C[4]);
+ ASSERT_TRUE(cCount == 4);
+ }
+ ASSERT_TRUE(cCount == 0);
+ // Does release work?
+ {
+ UniquePtr<C[]> c(new C[4]);
+ ASSERT_TRUE(cCount == 4);
+ rawC = c.release();
+ }
+ ASSERT_TRUE(cCount == 4);
+ delete[] rawC;
+ // Does reset work?
+ {
+ UniquePtr<C[]> c(new C[4]);
+ ASSERT_TRUE(cCount == 4);
+ c.reset(new C[2]);
+ ASSERT_TRUE(cCount == 2);
+ }
+ ASSERT_TRUE(cCount == 0);
+
+ //
+ // Custom deleter tests...
+ //
+ ASSERT_TRUE(!freed);
+ {
+ UniquePtr<int, Freer> i(reinterpret_cast<int*>(malloc(sizeof(int))));
+ *i = 123;
+ }
+ ASSERT_TRUE(freed);
+}