staticbool is_system_library(const std::string& realpath) { for (constauto& dir : g_default_namespace.get_default_library_paths()) { if (file_is_in_dir(realpath, dir)) { returntrue;
}
} returnfalse;
}
// Checks if the file exists and not a directory. staticbool file_exists(constchar* path) { struct stat s;
if (stat(path, &s) != 0) { returnfalse;
}
return S_ISREG(s.st_mode);
}
static std::string resolve_soname(const std::string& name) { // We assume that soname equals to basename here
// TODO(dimitry): consider having honest absolute-path -> soname resolution // note that since we might end up refusing to load this library because // it is not in shared libs list we need to get the soname without actually loading // the library. // // On the other hand there are several places where we already assume that // soname == basename in particular for any not-loaded library mentioned // in DT_NEEDED list. return basename(name.c_str());
}
// TODO(dimitry): The exempt-list is a workaround for http://b/26394120 --- // gradually remove libraries from this list until it is gone. staticbool is_exempt_lib(android_namespace_t* ns, constchar* name, const soinfo* needed_by) { staticconstchar* const kLibraryExemptList[] = { "libandroid_runtime.so", "libbinder.so", "libcrypto.so", "libcutils.so", "libexpat.so", "libgui.so", "libmedia.so", "libnativehelper.so", "libssl.so", "libstagefright.so", "libsqlite.so", "libui.so", "libutils.so",
nullptr
};
// If you're targeting N, you don't get the exempt-list. if (get_application_target_sdk_version() >= 24) { returnfalse;
}
// if the library needed by a system library - implicitly assume it // is exempt unless it is in the list of shared libraries for one or // more linked namespaces if (needed_by != nullptr && is_system_library(needed_by->get_realpath())) { return !maybe_accessible_via_namespace_links(ns, name);
}
// if this is an absolute path - make sure it points to /system/lib(64) if (name[0] == '/' && dirname(name) == kSystemLibDir) { // and reduce the path to basename
name = basename(name);
}
for (size_t i = 0; kLibraryExemptList[i] != nullptr; ++i) { if (strcmp(name, kLibraryExemptList[i]) == 0) { returntrue;
}
}
staticvoid notify_gdb_of_load(soinfo* info) { if (info->is_linker() || info->is_main_executable()) { // gdb already knows about the linker and the main executable. return;
}
link_map* map = &(info->link_map_head);
map->l_addr = info->load_bias; // link_map l_name field is not const.
map->l_name = const_cast<char*>(info->get_realpath());
map->l_ld = info->dynamic;
staticbool realpath_fd(int fd, std::string* realpath) { // proc_self_fd needs to be large enough to hold "/proc/self/fd/" plus an // integer, plus the NULL terminator. char proc_self_fd[32];
async_safe_format_buffer(proc_self_fd, sizeof(proc_self_fd), "/proc/self/fd/%d", fd);
char buf[PATH_MAX]; auto length = readlink(proc_self_fd, buf, sizeof(buf)); if (length == -1) { if (is_proc_mounted()) {
DL_WARN("readlink(\"%s\" [fd=%d]) failed: %m", proc_self_fd, fd);
} returnfalse;
}
realpath->assign(buf, length); returntrue;
}
// Returns the address of the current thread's copy of a TLS module. If the current thread doesn't // have a copy yet, allocate one on-demand if should_alloc is true, and return nullptr otherwise. staticinlinevoid* get_tls_block_for_this_thread(const soinfo_tls* si_tls, bool should_alloc) { const TlsModule& tls_mod = get_tls_module(si_tls->module_id); if (tls_mod.static_offset != SIZE_MAX) { const StaticTlsLayout& layout = __libc_shared_globals()->static_tls_layout; char* static_tls = reinterpret_cast<char*>(__get_bionic_tcb()) - layout.offset_bionic_tcb(); return static_tls + tls_mod.static_offset;
} elseif (should_alloc) { const TlsIndex ti { si_tls->module_id, static_cast<size_t>(0 - TLS_DTV_OFFSET) }; return TLS_GET_ADDR(&ti);
} else {
TlsDtv* dtv = __get_tcb_dtv(__get_bionic_tcb()); if (dtv->generation < tls_mod.first_generation) return nullptr; return dtv->modules[__tls_module_id_to_idx(si_tls->module_id)];
}
}
#ifdefined(__arm__)
// For a given PC, find the .so that it belongs to. // Returns the base address of the .ARM.exidx section // for that .so, and the number of 8-byte entries // in that section (via *pcount). // // Intended to be called by libc's __gnu_Unwind_Find_exidx().
_Unwind_Ptr do_dl_unwind_find_exidx(_Unwind_Ptr pc, int* pcount) { if (soinfo* si = find_containing_library(reinterpret_cast<void*>(pc))) {
*pcount = si->ARM_exidx_count; returnreinterpret_cast<_Unwind_Ptr>(si->ARM_exidx);
}
*pcount = 0; return0;
}
#endif
// Here, we only have to provide a callback to iterate across all the // loaded libraries. gcc_eh does the rest. int do_dl_iterate_phdr(int (*cb)(dl_phdr_info* info, size_t size, void* data), void* data) { int rv = 0; for (soinfo* si = solist_get_head(); si != nullptr; si = si->next) {
dl_phdr_info dl_info;
dl_info.dlpi_addr = si->link_map_head.l_addr;
dl_info.dlpi_name = si->link_map_head.l_name;
dl_info.dlpi_phdr = si->phdr;
dl_info.dlpi_phnum = si->phnum;
dl_info.dlpi_adds = g_module_load_counter;
dl_info.dlpi_subs = g_module_unload_counter; if (soinfo_tls* tls_module = si->get_tls()) {
dl_info.dlpi_tls_modid = tls_module->module_id;
dl_info.dlpi_tls_data = get_tls_block_for_this_thread(tls_module, /*should_alloc=*/false);
} else {
dl_info.dlpi_tls_modid = 0;
dl_info.dlpi_tls_data = nullptr;
}
// needed_by is NULL iff dlopen is called from memory that isn't part of any known soinfo. static LoadTask* create(constchar* _Nonnull name, soinfo* _Nullable needed_by,
android_namespace_t* _Nonnull start_from,
std::unordered_map<const soinfo*, ElfReader>* _Nonnull readers_map) {
LoadTask* ptr = TypeBasedAllocator<LoadTask>::alloc(); returnnew (ptr) LoadTask(name, needed_by, start_from, readers_map);
}
// This function walks down the tree of soinfo dependencies // in breadth-first order and // * calls action(soinfo* si) for each node, and // * terminates walk if action returns kWalkStop // * skips children of the node if action // return kWalkSkip // // walk_dependencies_tree returns false if walk was terminated // by the action and true otherwise. template<typename F> staticbool walk_dependencies_tree(soinfo* root_soinfo, F action) {
SoinfoLinkedList visit_list;
SoinfoLinkedList visited;
visit_list.push_back(root_soinfo);
soinfo* si; while ((si = visit_list.pop_front()) != nullptr) { if (visited.contains(si)) { continue;
}
if (!ns->is_accessible(current_soinfo)) { return kWalkSkip;
}
result = current_soinfo->find_symbol_by_name(symbol_name, vi); if (result != nullptr) {
*found = current_soinfo; return kWalkStop;
}
return kWalkContinue;
});
return result;
}
/* This is used by dlsym(3) to performs a global symbol lookup. If the startvalueisnull(forRTLD_DEFAULT),thesearchstartsatthe beginningoftheglobalsolist.Otherwisethesearchstartsatthe specifiedsoinfo(forRTLD_NEXT).
*/ staticconst ElfW(Sym)* dlsym_linear_lookup(android_namespace_t* ns, constchar* name, const version_info* vi,
soinfo** found,
soinfo* caller, void* handle) {
SymbolName symbol_name(name);
auto& soinfo_list = ns->soinfo_list(); auto start = soinfo_list.begin();
if (handle == RTLD_NEXT) { if (caller == nullptr) { return nullptr;
} else { auto it = soinfo_list.find(caller);
CHECK (it != soinfo_list.end());
start = ++it;
}
}
const ElfW(Sym)* s = nullptr; for (auto it = start, end = soinfo_list.end(); it != end; ++it) {
soinfo* si = *it; // Do not skip RTLD_LOCAL libraries in dlsym(RTLD_DEFAULT, ...) // if the library is opened by an application with target sdk version < 23. // See http://b/21565766 if ((si->get_rtld_flags() & RTLD_GLOBAL) == 0 && si->get_target_sdk_version() >= 23) { continue;
}
s = si->find_symbol_by_name(symbol_name, vi); if (s != nullptr) {
*found = si; break;
}
}
// If not found - use dlsym_handle_lookup_impl for caller's local_group if (s == nullptr && caller != nullptr) {
soinfo* local_group_root = caller->get_local_group_root();
if (s != nullptr) {
LD_DEBUG(lookup, "%s s->st_value = %p, found->base = %p",
name, reinterpret_cast<void*>(s->st_value), reinterpret_cast<void*>((*found)->base));
}
return s;
}
// This is used by dlsym(3). It performs symbol lookup only within the // specified soinfo object and its dependencies in breadth first order. staticconst ElfW(Sym)* dlsym_handle_lookup(soinfo* si,
soinfo** found, constchar* name, const version_info* vi) { // According to man dlopen(3) and posix docs in the case when si is handle // of the main executable we need to search not only in the executable and its // dependencies but also in all libraries loaded with RTLD_GLOBAL. // // Since RTLD_GLOBAL is always set for the main executable and all dt_needed shared // libraries and they are loaded in breath-first (correct) order we can just execute // dlsym(RTLD_DEFAULT, ...); instead of doing two stage lookup. if (si == solist_get_executable()) { return dlsym_linear_lookup(&g_default_namespace, name, vi, found, nullptr, RTLD_DEFAULT);
}
SymbolName symbol_name(name); // note that the namespace is not the namespace associated with caller_addr // we use ns associated with root si intentionally here. Using caller_ns // causes problems when user uses dlopen_ext to open a library in the separate // namespace and then calls dlsym() on the handle. return dlsym_handle_lookup_impl(si->get_primary_namespace(), si, nullptr, found, symbol_name, vi);
}
soinfo* find_containing_library(constvoid* p) { // Addresses within a library may be tagged if they point to globals. Untag // them so that the bounds check succeeds.
ElfW(Addr) address = reinterpret_cast<ElfW(Addr)>(untag_address(p)); for (soinfo* si = solist_get_head(); si != nullptr; si = si->next) { if (address < si->base || address - si->base >= si->size) { continue;
}
ElfW(Addr) vaddr = address - si->load_bias; for (size_t i = 0; i != si->phnum; ++i) { const ElfW(Phdr)* phdr = &si->phdr[i]; if (phdr->p_type != PT_LOAD) { continue;
} if (vaddr >= phdr->p_vaddr && vaddr < phdr->p_vaddr + phdr->p_memsz) { return si;
}
}
} return nullptr;
}
class ZipArchiveCache { public:
ZipArchiveCache() {}
~ZipArchiveCache();
constchar* const path = normalized_path.c_str();
LD_DEBUG(any, "Trying zip file open from path \"%s\" -> normalized \"%s\"", input_path, path);
// Treat an '!/' separator inside a path as the separator between the name // of the zip file on disk and the subdirectory to search within it. // For example, if path is "foo.zip!/bar/bas/x.so", then we search for // "bar/bas/x.so" within "foo.zip". constchar* const separator = strstr(path, kZipFileSeparator); if (separator == nullptr) { return -1;
}
char buf[512]; if (strlcpy(buf, path, sizeof(buf)) >= sizeof(buf)) {
DL_WARN("ignoring very long library path: %s", path); return -1;
}
if (FindEntry(handle, file_path, &entry) != 0) { // Entry was not found.
close(fd); return -1;
}
// Check if it is properly stored if (entry.method != kCompressStored || (entry.offset % page_size()) != 0) {
close(fd); return -1;
}
*file_offset = entry.offset;
if (realpath_fd(fd, realpath)) {
*realpath += separator;
} else { if (is_proc_mounted()) {
DL_WARN("unable to get realpath for the library \"%s\". Will use given path.",
normalized_path.c_str());
}
*realpath = normalized_path;
}
return fd;
}
staticbool format_path(char* buf, size_t buf_size, constchar* path, constchar* name) { int n = async_safe_format_buffer(buf, buf_size, "%s/%s", path, name); if (n < 0 || n >= static_cast<int>(buf_size)) {
DL_WARN("ignoring very long library path: %s/%s", path, name); returnfalse;
}
if (fd == -1) {
fd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_CLOEXEC)); if (fd != -1) {
*file_offset = 0; if (!realpath_fd(fd, realpath)) { if (is_proc_mounted()) {
DL_WARN("unable to get realpath for the library \"%s\". Will use given path.", path);
}
*realpath = path;
}
}
}
// If the name contains a slash, we should attempt to open it directly and not search the paths. if (strchr(name, '/') != nullptr) { return open_library_at_path(zip_archive_cache, name, file_offset, realpath);
}
// LD_LIBRARY_PATH has the highest priority. We don't have to check accessibility when searching // the namespace's path lists, because anything found on a namespace path list should always be // accessible. int fd = open_library_on_paths(zip_archive_cache, name, file_offset, ns->get_ld_library_paths(), realpath);
// Try the DT_RUNPATH, and verify that the library is accessible. if (fd == -1 && needed_by != nullptr) {
fd = open_library_on_paths(zip_archive_cache, name, file_offset, needed_by->get_dt_runpath(), realpath); if (fd != -1 && !ns->is_accessible(*realpath)) {
close(fd);
fd = -1;
}
}
// Finally search the namespace's main search path list. if (fd == -1) {
fd = open_library_on_paths(zip_archive_cache, name, file_offset, ns->get_default_library_paths(), realpath);
}
if ((file_offset % page_size()) != 0) {
DL_OPEN_ERR("file offset for the library \"%s\" is not page-aligned: %" PRId64, name, file_offset); returnfalse;
} if (file_offset < 0) {
DL_OPEN_ERR("file offset for the library \"%s\" is negative: %" PRId64, name, file_offset); returnfalse;
}
struct stat file_stat; if (TEMP_FAILURE_RETRY(fstat(task->get_fd(), &file_stat)) != 0) {
DL_OPEN_ERR("unable to stat file for the library \"%s\": %m", name); returnfalse;
} if (file_offset >= file_stat.st_size) {
DL_OPEN_ERR("file offset for the library \"%s\" >= file size: %" PRId64 " >= %" PRId64,
name, file_offset, file_stat.st_size); returnfalse;
}
// Check for symlink and other situations where // file can have different names, unless ANDROID_DLEXT_FORCE_LOAD is set if (extinfo == nullptr || (extinfo->flags & ANDROID_DLEXT_FORCE_LOAD) == 0) {
soinfo* si = nullptr; if (find_loaded_library_by_inode(ns, file_stat, file_offset, search_linked_namespaces, &si)) {
LD_LOG(kLogDlopen, "load_library(ns=%s, task=%s): Already loaded under different name/path \"%s\" - " "will return existing soinfo",
ns->get_name(), name, si->get_realpath());
task->set_soinfo(si); returntrue;
}
}
if ((rtld_flags & RTLD_NOLOAD) != 0) {
DL_OPEN_ERR("library \"%s\" wasn't loaded and RTLD_NOLOAD prevented it", name); returnfalse;
}
struct statfs fs_stat; if (TEMP_FAILURE_RETRY(fstatfs(task->get_fd(), &fs_stat)) != 0) {
DL_OPEN_ERR("unable to fstatfs file for the library \"%s\": %m", name); returnfalse;
}
// do not check accessibility using realpath if fd is located on tmpfs // this enables use of memfd_create() for apps if ((fs_stat.f_type != TMPFS_MAGIC) && (!ns->is_accessible(realpath))) { // TODO(dimitry): workaround for http://b/26394120 - the exempt-list
const soinfo* needed_by = task->is_dt_needed() ? task->get_needed_by() : nullptr; if (is_exempt_lib(ns, name, needed_by)) { // print warning only if needed by non-system library if (needed_by == nullptr || !is_system_library(needed_by->get_realpath())) { const soinfo* needed_or_dlopened_by = task->get_needed_by(); constchar* sopath = needed_or_dlopened_by == nullptr ? "(unknown)" :
needed_or_dlopened_by->get_realpath(); // is_exempt_lib() always returns true for targetSdkVersion < 24, // so no need to check the return value of DL_ERROR_AFTER(). // We still call it rather than DL_WARN() to get the extra clarification.
DL_ERROR_AFTER(24, "library \"%s\" (\"%s\") needed or dlopened by \"%s\" " "is not accessible by namespace \"%s\"",
name, realpath.c_str(), sopath, ns->get_name());
add_dlwarning(sopath, "unauthorized access to", name);
}
} else { // do not load libraries if they are not accessible for the specified namespace. constchar* needed_or_dlopened_by = task->get_needed_by() == nullptr ? "(unknown)" :
task->get_needed_by()->get_realpath();
DL_OPEN_ERR("library \"%s\" needed or dlopened by \"%s\" is not accessible for the namespace \"%s\"",
name, needed_or_dlopened_by, ns->get_name());
// do not print this if a library is in the list of shared libraries for linked namespaces if (!maybe_accessible_via_namespace_links(ns, name)) {
DL_WARN("library \"%s\" (\"%s\") needed or dlopened by \"%s\" is not accessible for the" " namespace: [name=\"%s\", ld_library_paths=\"%s\", default_library_paths=\"%s\"," " permitted_paths=\"%s\"]",
name, realpath.c_str(),
needed_or_dlopened_by,
ns->get_name(),
android::base::Join(ns->get_ld_library_paths(), ':').c_str(),
android::base::Join(ns->get_default_library_paths(), ':').c_str(),
android::base::Join(ns->get_permitted_paths(), ':').c_str());
} returnfalse;
}
}
soinfo* si = soinfo_alloc(ns, realpath.c_str(), &file_stat, file_offset, rtld_flags);
task->set_soinfo(si);
// Read the ELF header and some of the segments. if (!task->read(realpath.c_str(), file_stat.st_size)) {
task->remove_cached_elf_reader();
task->set_soinfo(nullptr);
soinfo_free(si); returnfalse;
}
// Find and set DT_RUNPATH, DT_SONAME, and DT_FLAGS_1. // Note that these field values are temporary and are // going to be overwritten on soinfo::prelink_image // with values from PT_LOAD segments. const ElfReader& elf_reader = task->get_elf_reader(); for (const ElfW(Dyn)* d = elf_reader.dynamic(); d->d_tag != DT_NULL; ++d) { if (d->d_tag == DT_RUNPATH) {
si->set_dt_runpath(elf_reader.get_string(d->d_un.d_val));
} if (d->d_tag == DT_SONAME) {
si->set_soname(elf_reader.get_string(d->d_un.d_val));
} // We need to identify a DF_1_GLOBAL library early so we can link it to namespaces. if (d->d_tag == DT_FLAGS_1) {
si->set_dt_flags_1(d->d_un.d_val);
}
}
#if !defined(__ANDROID__) // Bionic on the host currently uses some Android prebuilts, which don't set // DT_RUNPATH with any relative paths, so they can't find their dependencies. // b/118058804 if (si->get_dt_runpath().empty()) {
si->set_dt_runpath("$ORIGIN/../lib64:$ORIGIN/lib64");
} #endif
for (const ElfW(Dyn)* d = elf_reader.dynamic(); d->d_tag != DT_NULL; ++d) { if (d->d_tag == DT_NEEDED) { constchar* name = fix_dt_needed(elf_reader.get_string(d->d_un.d_val), elf_reader.name());
LD_LOG(kLogDlopen, "load_library(ns=%s, task=%s): Adding DT_NEEDED task: %s",
ns->get_name(), task->get_name(), name);
load_tasks->push_back(LoadTask::create(name, si, ns, task->get_readers_map()));
}
}
std::string realpath; if (!realpath_fd(extinfo->library_fd, &realpath)) { if (is_proc_mounted()) {
DL_WARN("unable to get realpath for the library \"%s\" by extinfo->library_fd. " "Will use given name.",
name);
}
realpath = name;
}
// Open the file.
off64_t file_offset;
std::string realpath; int fd = open_library(ns, zip_archive_cache, name, needed_by, &file_offset, &realpath); if (fd == -1) { if (task->is_dt_needed()) { if (needed_by->is_main_executable()) {
DL_OPEN_ERR("library \"%s\" not found: needed by main executable", name);
} else {
DL_OPEN_ERR("library \"%s\" not found: needed by %s in namespace %s", name,
needed_by->get_realpath(), task->get_start_from()->get_name());
}
} else {
DL_OPEN_ERR("library \"%s\" not found", name);
} returnfalse;
}
// Returns true if library was found and false otherwise staticbool find_loaded_library_by_soname(android_namespace_t* ns, constchar* name, bool search_linked_namespaces,
soinfo** candidate) {
*candidate = nullptr;
// Ignore filename with path. if (strchr(name, '/') != nullptr) { returnfalse;
}
bool found = find_loaded_library_by_soname(ns, name, candidate);
if (!found && search_linked_namespaces) { // if a library was not found - look into linked namespaces for (auto& link : ns->linked_namespaces()) { if (!link.is_accessible(name)) { continue;
}
if (!namespace_link.is_accessible(soname.c_str())) { // the library is not accessible via namespace_link
LD_LOG(kLogDlopen, "find_library_in_linked_namespace(ns=%s, task=%s): Not accessible (soname=%s)",
ns->get_name(), task->get_name(), soname.c_str()); returnfalse;
}
// if library is already loaded - return it if (loaded) {
LD_LOG(kLogDlopen, "find_library_in_linked_namespace(ns=%s, task=%s): Already loaded",
ns->get_name(), task->get_name());
task->set_soinfo(candidate); returntrue;
}
// returning true with empty soinfo means that the library is okay to be // loaded in the namespace but has not yet been loaded there before.
LD_LOG(kLogDlopen, "find_library_in_linked_namespace(ns=%s, task=%s): Ok to load", ns->get_name(),
task->get_name());
task->set_soinfo(nullptr); returntrue;
}
// Library might still be loaded, the accurate detection // of this fact is done by load_library.
LD_DEBUG(any, "[ \"%s\" find_loaded_library_by_soname failed (*candidate=%s@%p). Trying harder... ]",
task->get_name(), candidate == nullptr ? "n/a" : candidate->get_realpath(), candidate);
// TODO(dimitry): workaround for http://b/26394120 (the exempt-list) if (ns->is_exempt_list_enabled() && is_exempt_lib(ns, task->get_name(), task->get_needed_by())) { // For the libs in the exempt-list, switch to the default namespace and then // try the load again from there. The library could be loaded from the // default namespace or from another namespace (e.g. runtime) that is linked // from the default namespace.
LD_LOG(kLogDlopen, "find_library_internal(ns=%s, task=%s): Exempt system library - trying namespace %s",
ns->get_name(), task->get_name(), g_default_namespace.get_name());
ns = &g_default_namespace; if (load_library(ns, task, zip_archive_cache, load_tasks, rtld_flags, true/* search_linked_namespaces */)) { returntrue;
}
} // END OF WORKAROUND
// if a library was not found - look into linked namespaces // preserve current dlerror in the case it fails.
DlErrorRestorer dlerror_restorer;
LD_LOG(kLogDlopen, "find_library_internal(ns=%s, task=%s): Trying %zu linked namespaces",
ns->get_name(), task->get_name(), ns->linked_namespaces().size()); for (auto& linked_namespace : ns->linked_namespaces()) { if (find_library_in_linked_namespace(linked_namespace, task)) { // Library is already loaded. if (task->get_soinfo() != nullptr) { // n.b. This code path runs when find_library_in_linked_namespace found an already-loaded // library by soname. That should only be possible with a exempt-list lookup, where we // switch the namespace, because otherwise, find_library_in_linked_namespace is duplicating // the soname scan done in this function's first call to find_loaded_library_by_soname. returntrue;
}
if (load_library(linked_namespace.linked_namespace(), task, zip_archive_cache, load_tasks,
rtld_flags, false/* search_linked_namespaces */)) {
LD_LOG(kLogDlopen, "find_library_internal(ns=%s, task=%s): Found in linked namespace %s",
ns->get_name(), task->get_name(), linked_namespace.linked_namespace()->get_name()); returntrue;
}
}
}
returnfalse;
}
staticvoid soinfo_unload(soinfo* si);
staticvoid shuffle(std::vector<LoadTask*>* v) { if (!__libc_arc4random_ready()) return;
for (size_t i = 0, size = v->size(); i < size; ++i) {
size_t n = size - i;
size_t r = arc4random_uniform(n);
std::swap((*v)[n-1], (*v)[r]);
}
}
// add_as_children - add first-level loaded libraries (i.e. library_names[], but // not their transitive dependencies) as children of the start_with library. // This is false when find_libraries is called for dlopen(), when newly loaded // libraries must form a disjoint tree. bool find_libraries(android_namespace_t* ns,
soinfo* start_with, constchar* const library_names[],
size_t library_names_count,
soinfo* soinfos[],
std::vector<soinfo*>* ld_preloads,
size_t ld_preloads_count, int rtld_flags, const android_dlextinfo* extinfo, bool add_as_children,
std::vector<android_namespace_t*>* namespaces) { // Step 0: prepare.
std::unordered_map<const soinfo*, ElfReader> readers_map;
LoadTaskList load_tasks;
for (size_t i = 0; i < library_names_count; ++i) { constchar* name = library_names[i];
load_tasks.push_back(LoadTask::create(name, start_with, ns, &readers_map));
}
// If soinfos array is null allocate one on stack. // The array is needed in case of failure; for example // when library_names[] = {libone.so, libtwo.so} and libone.so // is loaded correctly but libtwo.so failed for some reason. // In this case libone.so should be unloaded on return. // See also implementation of failure_guard below.
// Step 1: expand the list of load_tasks to include // all DT_NEEDED libraries (do not load them just yet) for (size_t i = 0; i<load_tasks.size(); ++i) {
LoadTask* task = load_tasks[i];
soinfo* needed_by = task->get_needed_by();
// Note: start from the namespace that is stored in the LoadTask. This namespace // is different from the current namespace when the LoadTask is for a transitive // dependency and the lib that created the LoadTask is not found in the // current namespace but in one of the linked namespaces.
android_namespace_t* start_ns = const_cast<android_namespace_t*>(task->get_start_from());
if (!find_library_internal(start_ns, task, &zip_archive_cache, &load_tasks, rtld_flags)) { returnfalse;
}
soinfo* si = task->get_soinfo();
if (is_dt_needed) {
needed_by->add_child(si);
}
// When ld_preloads is not null, the first // ld_preloads_count libs are in fact ld_preloads. bool is_ld_preload = false; if (ld_preloads != nullptr && soinfos_count < ld_preloads_count) {
ld_preloads->push_back(si);
is_ld_preload = true;
}
if (soinfos_count < library_names_count) {
soinfos[soinfos_count++] = si;
}
// Add the new global group members to all initial namespaces. Do this secondary namespace setup // at the same time that libraries are added to their primary namespace so that the order of // global group members is the same in the every namespace. Only add a library to a namespace // once, even if it appears multiple times in the dependency graph. if (is_ld_preload || (si->get_dt_flags_1() & DF_1_GLOBAL) != 0) { if (!si->is_linked() && namespaces != nullptr && !new_global_group_members.contains(si)) {
new_global_group_members.push_back(si); for (auto linked_ns : *namespaces) { if (si->get_primary_namespace() != linked_ns) {
linked_ns->add_soinfo(si);
si->add_secondary_namespace(linked_ns);
}
}
}
}
}
// Step 2: Load libraries in random order (see b/24047022)
LoadTaskList load_list; for (auto&& task : load_tasks) {
soinfo* si = task->get_soinfo(); auto pred = [&](const LoadTask* t) { return t->get_soinfo() == si;
};
// If the executable depends on itself (directly or indirectly), then the executable ends up on // the list of LoadTask objects (b/328822319). It is already loaded, so don't try to load it // again, which will fail because its ElfReader isn't ready. This can happen if ldd is invoked // on a shared library that depends on itself, which happens with HWASan-ified Bionic libraries // like libc.so, libm.so, etc. if (!si->is_linked() && !si->is_main_executable() &&
std::find_if(load_list.begin(), load_list.end(), pred) == load_list.end()) {
load_list.push_back(task);
}
} bool reserved_address_recursive = false; if (extinfo) {
reserved_address_recursive = extinfo->flags & ANDROID_DLEXT_RESERVED_ADDRESS_RECURSIVE;
} if (!reserved_address_recursive) { // Shuffle the load order in the normal case, but not if we are loading all // the libraries to a reserved address range.
shuffle(&load_list);
}
// Set up address space parameters.
address_space_params extinfo_params, default_params;
size_t relro_fd_offset = 0; if (extinfo) { if (extinfo->flags & ANDROID_DLEXT_RESERVED_ADDRESS) {
extinfo_params.start_addr = extinfo->reserved_addr;
extinfo_params.reserved_size = extinfo->reserved_size;
extinfo_params.must_use_address = true;
} elseif (extinfo->flags & ANDROID_DLEXT_RESERVED_ADDRESS_HINT) {
extinfo_params.start_addr = extinfo->reserved_addr;
extinfo_params.reserved_size = extinfo->reserved_size;
}
}
// The WebView loader uses RELRO sharing in order to promote page sharing of the large RELRO // segment, as it's full of C++ vtables. Because MTE globals, by default, applies random tags to // each global variable, the RELRO segment is polluted and unique for each process. In order to // allow sharing, but still provide some protection, we use deterministic global tagging schemes // for DSOs that are loaded through android_dlopen_ext, such as those loaded by WebView. bool dlext_use_relro =
extinfo && extinfo->flags & (ANDROID_DLEXT_WRITE_RELRO | ANDROID_DLEXT_USE_RELRO);
// Step 3: pre-link all DT_NEEDED libraries in breadth first order. bool any_memtag_stack = false; for (auto&& task : load_tasks) {
soinfo* si = task->get_soinfo(); if (!si->is_linked() && !si->prelink_image(dlext_use_relro)) { returnfalse;
} // si->memtag_stack() needs to be called after si->prelink_image() which populates // the dynamic section. if (si->memtag_stack()) {
any_memtag_stack = true;
LD_LOG(kLogDlopen, "... load_library requesting stack MTE for: realpath=\"%s\", soname=\"%s\"",
si->get_realpath(), si->get_soname());
}
register_soinfo_tls(si);
} if (any_memtag_stack) { if (auto* cb = __libc_shared_globals()->memtag_stack_dlopen_callback) {
cb();
} else { // find_library is used by the initial linking step, so we communicate that we // want memtag_stack enabled to __libc_init_mte.
__libc_shared_globals()->initial_memtag_stack_abi = true;
}
}
// Step 4: Construct the global group. DF_1_GLOBAL bit is force set for LD_PRELOADed libs because // they must be added to the global group. Note: The DF_1_GLOBAL bit for a library is normally set // in step 3. if (ld_preloads != nullptr) { for (auto&& si : *ld_preloads) {
si->set_dt_flags_1(si->get_dt_flags_1() | DF_1_GLOBAL);
}
}
// Step 5: Collect roots of local_groups. // Whenever needed_by->si link crosses a namespace boundary it forms its own local_group. // Here we collect new roots to link them separately later on. Note that we need to avoid // collecting duplicates. Also the order is important. They need to be linked in the same // BFS order we link individual libraries.
std::vector<soinfo*> local_group_roots; if (start_with != nullptr && add_as_children) {
local_group_roots.push_back(start_with);
} else {
CHECK(soinfos_count == 1);
local_group_roots.push_back(soinfos[0]);
}
if (!si->is_linked() && si->get_primary_namespace() != needed_by_ns) { auto it = std::find(local_group_roots.begin(), local_group_roots.end(), si);
LD_LOG(kLogDlopen, "Crossing namespace boundary (si=%s@%p, si_ns=%s@%p, needed_by=%s@%p, ns=%s@%p, needed_by_ns=%s@%p) adding to local_group_roots: %s",
si->get_realpath(),
si,
si->get_primary_namespace()->get_name(),
si->get_primary_namespace(),
needed_by == nullptr ? "(nullptr)" : needed_by->get_realpath(),
needed_by,
ns->get_name(),
ns,
needed_by_ns->get_name(),
needed_by_ns,
it == local_group_roots.end() ? "yes" : "no");
if (it == local_group_roots.end()) {
local_group_roots.push_back(si);
}
}
}
// Step 6: Link all local groups for (auto root : local_group_roots) {
soinfo_list_t local_group;
android_namespace_t* local_group_ns = root->get_primary_namespace();
bool linked = local_group.visit([&](soinfo* si) { // Even though local group may contain accessible soinfos from other namespaces // we should avoid linking them (because if they are not linked -> they // are in the local_group_roots and will be linked later). if (!si->is_linked() && si->get_primary_namespace() == local_group_ns) { const android_dlextinfo* link_extinfo = nullptr; if (si == soinfos[0] || reserved_address_recursive) { // Only forward extinfo for the first library unless the recursive // flag is set.
link_extinfo = extinfo;
} if (__libc_shared_globals()->load_hook) {
__libc_shared_globals()->load_hook(si->load_bias, si->phdr, si->phnum);
}
lookup_list.set_dt_symbolic_lib(si->has_DT_SYMBOLIC ? si : nullptr); if (!si->link_image(lookup_list, local_group_root, link_extinfo, &relro_fd_offset) ||
!get_cfi_shadow()->AfterLoad(si, solist_get_head())) { returnfalse;
}
}
returntrue;
});
if (!linked) { returnfalse;
}
}
// Step 7: Mark all load_tasks as linked and increment refcounts // for references between load_groups (at this point it does not matter if // referenced load_groups were loaded by previous dlopen or as part of this // one on step 6) if (start_with != nullptr && add_as_children) {
start_with->set_linked();
}
for (auto&& task : load_tasks) {
soinfo* si = task->get_soinfo();
si->set_linked();
}
for (auto&& task : load_tasks) {
soinfo* si = task->get_soinfo();
soinfo* needed_by = task->get_needed_by(); if (needed_by != nullptr &&
needed_by != start_with &&
needed_by->get_local_group_root() != si->get_local_group_root()) {
si->increment_ref_count();
}
}
returntrue;
}
static soinfo* find_library(android_namespace_t* ns, constchar* name, int rtld_flags, const android_dlextinfo* extinfo,
soinfo* needed_by) {
soinfo* si = nullptr;
if (!root->can_unload()) {
LD_LOG(kLogDlopen, "... dlclose(root=\"%s\"@%p) ... not unloading - the load group is flagged with NODELETE",
root->get_realpath(),
root); return;
}
if (is_linked) { while ((si = external_unload_list.pop_front()) != nullptr) {
LD_LOG(kLogDlopen, "... dlclose: unloading external reference \"%s\"@%p ...",
si->get_realpath(),
si);
soinfo_unload(si);
}
} else {
LD_LOG(kLogDlopen, "... dlclose: unload_si was not linked - not unloading external references ...");
}
}
staticvoid soinfo_unload(soinfo* unload_si) { // Note that the library can be loaded but not linked; // in which case there is no root but we still need // to walk the tree and unload soinfos involved. // // This happens on unsuccessful dlopen, when one of // the DT_NEEDED libraries could not be linked/found. bool is_linked = unload_si->is_linked();
soinfo* root = is_linked ? unload_si->get_local_group_root() : unload_si;
LD_LOG(kLogDlopen, "... dlclose(realpath=\"%s\"@%p) ... load group root is \"%s\"@%p",
unload_si->get_realpath(),
unload_si,
root->get_realpath(),
root);
size_t ref_count = is_linked ? root->decrement_ref_count() : 0; if (ref_count > 0) {
LD_LOG(kLogDlopen, "... dlclose(root=\"%s\"@%p) ... not unloading - decrementing ref_count to %zd",
root->get_realpath(),
root,
ref_count); return;
}
void do_android_get_LD_LIBRARY_PATH(char* buffer, size_t buffer_size) { // Use basic string manipulation calls to avoid snprintf. // snprintf indirectly calls pthread_getspecific to get the size of a buffer. // When debug malloc is enabled, this call returns 0. This in turn causes // snprintf to do nothing, which causes libraries to fail to load. // See b/17302493 for further details. // Once the above bug is fixed, this code can be modified to use // snprintf again. constauto& default_ld_paths = g_default_namespace.get_default_library_paths();
if (buffer_size < required_size) {
async_safe_fatal("android_get_LD_LIBRARY_PATH failed, buffer too small: " "buffer len %zu, required len %zu", buffer_size, required_size);
}
char* end = buffer; for (size_t i = 0; i < default_ld_paths.size(); ++i) { if (i > 0) *end++ = ':';
end = stpcpy(end, default_ld_paths[i].c_str());
}
}
if ((flags & ~(RTLD_NOW|RTLD_LAZY|RTLD_LOCAL|RTLD_GLOBAL|RTLD_NODELETE|RTLD_NOLOAD)) != 0) {
DL_OPEN_ERR("invalid flags to dlopen: %x", flags); return nullptr;
}
if (extinfo != nullptr) { if ((extinfo->flags & ~(ANDROID_DLEXT_VALID_FLAG_BITS)) != 0) {
DL_OPEN_ERR("invalid extended flags to android_dlopen_ext: 0x%" PRIx64, extinfo->flags); return nullptr;
}
if ((extinfo->flags & ANDROID_DLEXT_USE_LIBRARY_FD) == 0 &&
(extinfo->flags & ANDROID_DLEXT_USE_LIBRARY_FD_OFFSET) != 0) {
DL_OPEN_ERR("invalid extended flag combination (ANDROID_DLEXT_USE_LIBRARY_FD_OFFSET without " "ANDROID_DLEXT_USE_LIBRARY_FD): 0x%" PRIx64, extinfo->flags); return nullptr;
}
if ((extinfo->flags & ANDROID_DLEXT_USE_NAMESPACE) != 0) { if (extinfo->library_namespace == nullptr) {
DL_OPEN_ERR("ANDROID_DLEXT_USE_NAMESPACE is set but extinfo->library_namespace is null"); return nullptr;
}
ns = extinfo->library_namespace;
}
}
// Workaround for dlopen(/system/lib/<soname>) when .so is in /apex. http://b/121248172 // The workaround works only when targetSdkVersion < Q.
std::string name_to_apex; if (translateSystemPathToApexPath(name, &name_to_apex)) { constchar* new_name = name_to_apex.c_str();
LD_LOG(kLogDlopen, "dlopen considering translation from %s to APEX path %s",
name,
new_name); // Some APEXs could be optionally disabled. Only translate the path // when the old file is absent and the new file exists. // TODO(b/124218500): Re-enable it once app compat issue is resolved /* if(file_exists(name)){ LD_LOG(kLogDlopen,"dlopen%sexists,nottranslating",name); }else
*/ if (!file_exists(new_name)) {
LD_LOG(kLogDlopen, "dlopen %s does not exist, not translating",
new_name);
} else {
LD_LOG(kLogDlopen, "dlopen translation accepted: using %s", new_name);
name = new_name;
}
} // End Workaround for dlopen(/system/lib/<soname>) when .so is in /apex.
std::string translated_name_holder;
assert(!g_is_hwasan || !g_is_asan); constchar* translated_name = name; if (g_is_asan && translated_name != nullptr && translated_name[0] == '/') { char original_path[PATH_MAX]; if (realpath(name, original_path) != nullptr) {
translated_name_holder = std::string(kAsanLibDirPrefix) + original_path; if (file_exists(translated_name_holder.c_str())) {
soinfo* si = nullptr; if (find_loaded_library_by_realpath(ns, original_path, true, &si)) {
DL_WARN("linker_asan dlopen NOT translating \"%s\" -> \"%s\": library already loaded", name,
translated_name_holder.c_str());
} else {
DL_WARN("linker_asan dlopen translating \"%s\" -> \"%s\"", name, translated_name);
translated_name = translated_name_holder.c_str();
}
}
}
} elseif (g_is_hwasan && translated_name != nullptr && translated_name[0] == '/') { char original_path[PATH_MAX]; if (realpath(name, original_path) != nullptr) { // Keep this the same as CreateHwasanPath in system/linkerconfig/modules/namespace.cc.
std::string path(original_path); auto slash = path.rfind('/'); if (slash != std::string::npos || slash != path.size() - 1) {
translated_name_holder = path.substr(0, slash) + "/hwasan" + path.substr(slash);
} if (!translated_name_holder.empty() && file_exists(translated_name_holder.c_str())) {
soinfo* si = nullptr; if (find_loaded_library_by_realpath(ns, original_path, true, &si)) {
DL_WARN("linker_hwasan dlopen NOT translating \"%s\" -> \"%s\": library already loaded",
name, translated_name_holder.c_str());
} else {
DL_WARN("linker_hwasan dlopen translating \"%s\" -> \"%s\"", name, translated_name);
translated_name = translated_name_holder.c_str();
}
}
}
}
ProtectedDataGuard guard;
soinfo* si = find_library(ns, translated_name, flags, extinfo, caller);
loading_trace.End();
int do_dladdr(constvoid* addr, Dl_info* info) { // Determine if this address can be found in any library currently mapped.
soinfo* si = find_containing_library(addr); if (si == nullptr) { return0;
}
memset(info, 0, sizeof(Dl_info));
info->dli_fname = si->get_realpath(); // Address at which the shared object is loaded.
info->dli_fbase = reinterpret_cast<void*>(si->base);
// Determine if any symbol in the library contains the specified address.
ElfW(Sym)* sym = si->find_symbol_by_address(addr); if (sym != nullptr) {
info->dli_sname = si->get_string(sym->st_name);
info->dli_saddr = reinterpret_cast<void*>(si->resolve_symbol_address(sym));
}
return1;
}
static soinfo* soinfo_from_handle(void* handle) { if ((reinterpret_cast<uintptr_t>(handle) & 1) != 0) { auto it = g_soinfo_handles_map.find(reinterpret_cast<uintptr_t>(handle)); if (it == g_soinfo_handles_map.end()) { return nullptr;
} else { return it->second;
}
}
if (sym != nullptr) {
uint32_t bind = ELF_ST_BIND(sym->st_info);
uint32_t type = ELF_ST_TYPE(sym->st_info);
if ((bind == STB_GLOBAL || bind == STB_WEAK) && sym->st_shndx != 0) { // EPAN means that sections might be marked unreadable. check that // the symbol resides in a readable section.
auto section_readable = [sym, found]() { for (size_t i = 0; i < found->phnum; ++i) { if (found->phdr[i].p_type == PT_LOAD) {
uint64_t start_addr = found->phdr[i].p_vaddr + found->load_bias;
uint64_t end_addr = start_addr + found->phdr[i].p_memsz;
uint64_t sym_addr = found->resolve_symbol_address(sym); if (sym_addr >= start_addr && sym_addr < end_addr) { if (!(found->phdr[i].p_flags & PF_R)) { returnfalse;
} break;
}
}
} returntrue;
};
if (type == STT_TLS) { // For a TLS symbol, dlsym returns the address of the current thread's // copy of the symbol. const soinfo_tls* tls_module = found->get_tls(); if (tls_module == nullptr) {
DL_SYM_ERR("TLS symbol \"%s\" in solib \"%s\" with no TLS segment",
sym_name, found->get_realpath()); returnfalse;
} void* tls_block = get_tls_block_for_this_thread(tls_module, /*should_alloc=*/true);
*symbol = static_cast<char*>(tls_block) + sym->st_value;
} elseif (__libc_mte_enabled() && section_readable()) {
*symbol = get_tagged_address(reinterpret_cast<void*>(found->resolve_symbol_address(sym)));
} else {
*symbol = reinterpret_cast<void*>(found->resolve_symbol_address(sym));
}
failure_guard.Disable();
LD_LOG(kLogDlsym, "... dlsym successful: sym_name=\"%s\", sym_ver=\"%s\", found in=\"%s\", address=%p",
sym_name, sym_ver, found->get_soname(), *symbol); returntrue;
}
DL_SYM_ERR("symbol \"%s\" found but not global", symbol_display_name(sym_name, sym_ver).c_str()); returnfalse;
}
// Make ns as the anonymous namespace that is a namespace used when // we fail to determine the caller address (e.g., call from mono-jited code) // Since there can be multiple anonymous namespace in a process, subsequent // call to this function causes an error. staticbool set_anonymous_namespace(android_namespace_t* ns) { if (!g_anonymous_namespace_set && ns != nullptr) {
CHECK(ns->is_also_used_as_anonymous());
g_anonymous_namespace = ns;
g_anonymous_namespace_set = true; returntrue;
} returnfalse;
}
// TODO(b/130388701) remove this. Currently, this is used only for testing // where we don't have classloader namespace. bool init_anonymous_namespace(constchar* shared_lib_sonames, constchar* library_search_path) {
ProtectedDataGuard guard;
// Test-only feature: we need to change the anonymous namespace multiple times // while the test is running.
g_anonymous_namespace_set = false;
// create anonymous namespace // When the caller is nullptr - create_namespace will take global group // from the anonymous namespace, which is fine because anonymous namespace // is still pointing to the default one.
android_namespace_t* anon_ns =
create_namespace(nullptr, "(anonymous)",
nullptr,
library_search_path,
ANDROID_NAMESPACE_TYPE_ISOLATED |
ANDROID_NAMESPACE_TYPE_ALSO_USED_AS_ANONYMOUS,
nullptr,
&g_default_namespace);
staticvoid add_soinfos_to_namespace(const soinfo_list_t& soinfos, android_namespace_t* ns) {
ns->add_soinfos(soinfos); for (auto si : soinfos) {
si->add_secondary_namespace(ns);
}
}
std::vector<std::string> fix_lib_paths(std::vector<std::string> paths) { // For the bootstrap linker, insert /system/${LIB}/bootstrap in front of /system/${LIB} in any // namespace search path. The bootstrap linker should prefer to use the bootstrap bionic libraries // (e.g. libc.so). #if !defined(RELEASE_DEPRECATE_RUNTIME_APEX) && !defined(__ANDROID_APEX__) for (size_t i = 0; i < paths.size(); ++i) { if (paths[i] == kSystemLibDir) {
paths.insert(paths.begin() + i, std::string(kSystemLibDir) + "/bootstrap");
++i;
}
} #endif return paths;
}
android_namespace_t* create_namespace(constvoid* caller_addr, constchar* name, constchar* ld_library_path, constchar* default_library_path,
uint64_t type, constchar* permitted_when_isolated_path,
android_namespace_t* parent_namespace) { if (parent_namespace == nullptr) { // if parent_namespace is nullptr -> set it to the caller namespace
soinfo* caller_soinfo = find_containing_library(caller_addr);
// If shared - clone the parent namespace
add_soinfos_to_namespace(parent_namespace->soinfo_list(), ns); // and copy parent namespace links for (auto& link : parent_namespace->linked_namespaces()) {
ns->add_linked_namespace(link.linked_namespace(), link.shared_lib_sonames(),
link.allow_all_shared_libs());
}
} else { // If not shared - copy only the shared group
add_soinfos_to_namespace(parent_namespace->get_shared_group(), ns);
}
if (namespace_from == nullptr) {
DL_ERR("error linking namespaces: namespace_from is null."); returnfalse;
}
if (shared_lib_sonames == nullptr || shared_lib_sonames[0] == '\0') {
DL_ERR("error linking namespaces \"%s\"->\"%s\": the list of shared libraries is empty.",
namespace_from->get_name(), namespace_to->get_name()); returnfalse;
}
if (target_si == nullptr) {
DL_ERR("cannot find \"%s\" from verneed[%zd] in DT_NEEDED list for \"%s\"",
target_soname, i, si_from->get_realpath()); returnfalse;
}
if (verdef->vd_version != 1) {
DL_ERR("unsupported verdef[%zd] vd_version: %d (expected 1) library: %s",
i, verdef->vd_version, si->get_realpath()); returnfalse;
}
if ((verdef->vd_flags & VER_FLG_BASE) != 0) { // "this is the version of the file itself. It must not be used for // matching a symbol. It can be used to match references." // // http://www.akkadia.org/drepper/symbol-versioning continue;
}
if (verdef->vd_cnt == 0) {
DL_ERR("invalid verdef[%zd] vd_cnt == 0 (version without a name)", i); returnfalse;
}
if (!for_each_verdef(si,
[&](size_t, const ElfW(Verdef)* verdef, const ElfW(Verdaux)* verdaux) { if (verdef->vd_hash == vi->elf_hash &&
strcmp(vi->name, si->get_string(verdaux->vda_name)) == 0) {
result = verdef->vd_ndx; returntrue;
}
returnfalse;
}
)) { // verdef should have already been validated in prelink_image.
async_safe_fatal("invalid verdef after prelinking: %s, %s",
si->get_realpath(), linker_get_error_buffer());
}
return result;
}
// Validate the library's verdef section. On error, returns false and invokes DL_ERR. bool validate_verdef_section(const soinfo* si) { return for_each_verdef(si,
[&](size_t, const ElfW(Verdef)*, const ElfW(Verdaux)*) { returnfalse;
});
}
// TODO (dimitry): Methods below need to be moved out of soinfo // and in more isolated file in order minimize dependencies on // unnecessary object in the linker binary. Consider making them // independent from soinfo (?). bool soinfo::lookup_version_info(const VersionTracker& version_tracker, ElfW(Word) sym, constchar* sym_name, const version_info** vi) { const ElfW(Versym)* sym_ver_ptr = get_versym(sym);
ElfW(Versym) sym_ver = sym_ver_ptr == nullptr ? 0 : *sym_ver_ptr;
if (*vi == nullptr) {
DL_ERR("cannot find verneed/verdef for version index=%d " "referenced by symbol \"%s\" at \"%s\"", sym_ver, sym_name, get_realpath()); returnfalse;
}
} else { // there is no version info
*vi = nullptr;
}
// Process relocations in SHT_RELR section (experimental). // Details of the encoding are described in this post: // https://groups.google.com/d/msg/generic-abi/bX460iggiKg/Pi9aSwwABgAJ bool relocate_relr(const ElfW(Relr) * begin, const ElfW(Relr) * end, ElfW(Addr) load_bias, bool has_memtag_globals) {
constexpr size_t wordsize = sizeof(ElfW(Addr));
ElfW(Addr) base = 0; for (const ElfW(Relr)* current = begin; current < end; ++current) {
ElfW(Relr) entry = *current;
ElfW(Addr) offset;
if ((entry&1) == 0) { // Even entry: encodes the offset for next relocation.
offset = static_cast<ElfW(Addr)>(entry);
apply_relr_reloc(offset, load_bias, has_memtag_globals); // Set base offset for subsequent bitmap entries.
base = offset + wordsize; continue;
}
// Odd entry: encodes bitmap for relocations starting at base.
offset = base; while (entry != 0) {
entry >>= 1; if ((entry&1) != 0) {
apply_relr_reloc(offset, load_bias, has_memtag_globals);
}
offset += wordsize;
}
// Advance base offset by 63 words for 64-bit platforms, // or 31 words for 32-bit platforms.
base += (8*wordsize - 1) * wordsize;
} returntrue;
}
// An empty list of soinfos static soinfo_list_t g_empty_list;
TlsSegment tls_segment; if (__bionic_get_tls_segment(phdr, phnum, load_bias, &tls_segment)) { // The loader does not (currently) support ELF TLS, so it shouldn't have // a TLS segment.
CHECK(!relocating_linker && "TLS not supported in loader"); if (!__bionic_check_tls_align(tls_segment.aligned_size.align.value)) {
DL_ERR("TLS segment alignment in \"%s\" is not a power of 2: %zu", get_realpath(),
tls_segment.aligned_size.align.value); returnfalse;
}
tls_ = std::make_unique<soinfo_tls>();
tls_->segment = tls_segment;
}
// Extract useful information from dynamic section. // Note that: "Except for the DT_NULL element at the end of the array, // and the relative order of DT_NEEDED elements, entries may appear in any order." // // source: http://www.sco.com/developers/gabi/1998-04-29/ch5.dynamic.html
uint32_t needed_count = 0; for (ElfW(Dyn)* d = dynamic; d->d_tag != DT_NULL; ++d) {
LD_DEBUG(dynamic, "dynamic entry @%p: d_tag=%p, d_val=%p",
d, reinterpret_cast<void*>(d->d_tag), reinterpret_cast<void*>(d->d_un.d_val)); switch (d->d_tag) { case DT_SONAME: // this is parsed after we have strtab initialized (see below). break;
if (!powerof2(gnu_maskwords_)) {
DL_ERR("invalid maskwords for gnu_hash = 0x%x, in \"%s\" expecting power to two",
gnu_maskwords_, get_realpath()); returnfalse;
}
--gnu_maskwords_;
flags_ |= FLAG_GNU_HASH; break;
case DT_STRTAB:
strtab_ = reinterpret_cast<constchar*>(load_bias + d->d_un.d_ptr); break;
case DT_STRSZ:
strtab_size_ = d->d_un.d_val; break;
case DT_SYMTAB:
symtab_ = reinterpret_cast<ElfW(Sym)*>(load_bias + d->d_un.d_ptr); break;
case DT_SYMENT: if (d->d_un.d_val != sizeof(ElfW(Sym))) {
DL_ERR("invalid DT_SYMENT: %zd in \"%s\"", static_cast<size_t>(d->d_un.d_val), get_realpath()); returnfalse;
} break;
case DT_PLTREL: #ifdefined(USE_RELA) if (d->d_un.d_val != DT_RELA) {
DL_ERR("unsupported DT_PLTREL in \"%s\"; expected DT_RELA", get_realpath()); returnfalse;
} #else if (d->d_un.d_val != DT_REL) {
DL_ERR("unsupported DT_PLTREL in \"%s\"; expected DT_REL", get_realpath()); returnfalse;
} #endif break;
case DT_PLTGOT: // Ignored (because RTLD_LAZY is not supported). break;
case DT_DEBUG: // Set the DT_DEBUG entry to the address of _r_debug for GDB // if the dynamic table is writable if ((dynamic_flags & PF_W) != 0) {
d->d_un.d_val = reinterpret_cast<uintptr_t>(&_r_debug);
} break; #ifdefined(USE_RELA) case DT_RELA:
rela_ = reinterpret_cast<ElfW(Rela)*>(load_bias + d->d_un.d_ptr); break;
case DT_RELASZ:
rela_count_ = d->d_un.d_val / sizeof(ElfW(Rela)); break;
case DT_ANDROID_RELA:
android_relocs_ = reinterpret_cast<uint8_t*>(load_bias + d->d_un.d_ptr); break;
case DT_ANDROID_RELASZ:
android_relocs_size_ = d->d_un.d_val; break;
case DT_ANDROID_REL:
DL_ERR("unsupported DT_ANDROID_REL in \"%s\"", get_realpath()); returnfalse;
case DT_ANDROID_RELSZ:
DL_ERR("unsupported DT_ANDROID_RELSZ in \"%s\"", get_realpath()); returnfalse;
case DT_RELAENT: if (d->d_un.d_val != sizeof(ElfW(Rela))) {
DL_ERR("invalid DT_RELAENT: %zd", static_cast<size_t>(d->d_un.d_val)); returnfalse;
} break;
// Ignored (see DT_RELCOUNT comments for details). case DT_RELACOUNT: break;
case DT_REL:
DL_ERR("unsupported DT_REL in \"%s\"", get_realpath()); returnfalse;
case DT_RELSZ:
DL_ERR("unsupported DT_RELSZ in \"%s\"", get_realpath()); returnfalse;
#else case DT_REL:
rel_ = reinterpret_cast<ElfW(Rel)*>(load_bias + d->d_un.d_ptr); break;
case DT_RELSZ:
rel_count_ = d->d_un.d_val / sizeof(ElfW(Rel)); break;
case DT_RELENT: if (d->d_un.d_val != sizeof(ElfW(Rel))) {
DL_ERR("invalid DT_RELENT: %zd", static_cast<size_t>(d->d_un.d_val)); returnfalse;
} break;
case DT_ANDROID_REL:
android_relocs_ = reinterpret_cast<uint8_t*>(load_bias + d->d_un.d_ptr); break;
case DT_ANDROID_RELSZ:
android_relocs_size_ = d->d_un.d_val; break;
case DT_ANDROID_RELA:
DL_ERR("unsupported DT_ANDROID_RELA in \"%s\"", get_realpath()); returnfalse;
case DT_ANDROID_RELASZ:
DL_ERR("unsupported DT_ANDROID_RELASZ in \"%s\"", get_realpath()); returnfalse;
// "Indicates that all RELATIVE relocations have been concatenated together, // and specifies the RELATIVE relocation count." // // TODO: Spec also mentions that this can be used to optimize relocation process; // Not currently used by bionic linker - ignored. case DT_RELCOUNT: break;
case DT_RELA:
DL_ERR("unsupported DT_RELA in \"%s\"", get_realpath()); returnfalse;
case DT_RELASZ:
DL_ERR("unsupported DT_RELASZ in \"%s\"", get_realpath()); returnfalse;
#endif case DT_RELR: case DT_ANDROID_RELR:
relr_ = reinterpret_cast<ElfW(Relr)*>(load_bias + d->d_un.d_ptr); break;
case DT_RELRSZ: case DT_ANDROID_RELRSZ:
relr_count_ = d->d_un.d_val / sizeof(ElfW(Relr)); break;
case DT_RELRENT: case DT_ANDROID_RELRENT: if (d->d_un.d_val != sizeof(ElfW(Relr))) {
DL_ERR("invalid DT_RELRENT: %zd", static_cast<size_t>(d->d_un.d_val)); returnfalse;
} break;
// Ignored (see DT_RELCOUNT comments for details). // There is no DT_RELRCOUNT specifically because it would only be ignored. case DT_ANDROID_RELRCOUNT: break;
case DT_INIT:
init_func_ = reinterpret_cast<linker_ctor_function_t>(load_bias + d->d_un.d_ptr);
LD_DEBUG(dynamic, "%s constructors (DT_INIT) found at %p", get_realpath(), init_func_); break;
case DT_FINI:
fini_func_ = reinterpret_cast<linker_dtor_function_t>(load_bias + d->d_un.d_ptr);
LD_DEBUG(dynamic, "%s destructors (DT_FINI) found at %p", get_realpath(), fini_func_); break;
case DT_INIT_ARRAY:
init_array_ = reinterpret_cast<linker_ctor_function_t*>(load_bias + d->d_un.d_ptr);
LD_DEBUG(dynamic, "%s constructors (DT_INIT_ARRAY) found at %p", get_realpath(), init_array_); break;
case DT_INIT_ARRAYSZ:
init_array_count_ = static_cast<uint32_t>(d->d_un.d_val) / sizeof(ElfW(Addr)); break;
case DT_FINI_ARRAY:
fini_array_ = reinterpret_cast<linker_dtor_function_t*>(load_bias + d->d_un.d_ptr);
LD_DEBUG(dynamic, "%s destructors (DT_FINI_ARRAY) found at %p", get_realpath(), fini_array_); break;
case DT_FINI_ARRAYSZ:
fini_array_count_ = static_cast<uint32_t>(d->d_un.d_val) / sizeof(ElfW(Addr)); break;
case DT_PREINIT_ARRAY:
preinit_array_ = reinterpret_cast<linker_ctor_function_t*>(load_bias + d->d_un.d_ptr);
LD_DEBUG(dynamic, "%s constructors (DT_PREINIT_ARRAY) found at %p", get_realpath(), preinit_array_); break;
case DT_PREINIT_ARRAYSZ:
preinit_array_count_ = static_cast<uint32_t>(d->d_un.d_val) / sizeof(ElfW(Addr)); break;
case DT_TEXTREL: #ifdefined(__LP64__)
DL_ERR("\"%s\" has text relocations", get_realpath()); returnfalse; #else
has_text_relocations = true; break; #endif
case DT_SYMBOLIC:
has_DT_SYMBOLIC = true; break;
case DT_NEEDED:
++needed_count; break;
case DT_FLAGS: if (d->d_un.d_val & DF_TEXTREL) { #ifdefined(__LP64__)
DL_ERR("\"%s\" has text relocations", get_realpath()); returnfalse; #else
has_text_relocations = true; #endif
} if (d->d_un.d_val & DF_SYMBOLIC) {
has_DT_SYMBOLIC = true;
} break;
// Ignored: "Its use has been superseded by the DF_BIND_NOW flag" case DT_BIND_NOW: break;
case DT_VERSYM:
versym_ = reinterpret_cast<ElfW(Versym)*>(load_bias + d->d_un.d_ptr); break;
case DT_VERDEF:
verdef_ptr_ = load_bias + d->d_un.d_ptr; break; case DT_VERDEFNUM:
verdef_cnt_ = d->d_un.d_val; break;
case DT_VERNEED:
verneed_ptr_ = load_bias + d->d_un.d_ptr; break;
case DT_VERNEEDNUM:
verneed_cnt_ = d->d_un.d_val; break;
case DT_RUNPATH: // this is parsed after we have strtab initialized (see below). break;
case DT_TLSDESC_GOT: case DT_TLSDESC_PLT: // These DT entries are used for lazy TLSDESC relocations. Bionic // resolves everything eagerly, so these can be ignored. break;
#ifdefined(__aarch64__) case DT_AARCH64_BTI_PLT: case DT_AARCH64_PAC_PLT: case DT_AARCH64_VARIANT_PCS: // Ignored: AArch64 processor-specific dynamic array tags. break; case DT_AARCH64_MEMTAG_MODE:
memtag_dynamic_entries_.has_memtag_mode = true;
memtag_dynamic_entries_.memtag_mode = d->d_un.d_val; break; case DT_AARCH64_MEMTAG_HEAP:
memtag_dynamic_entries_.memtag_heap = d->d_un.d_val; break; // The AArch64 MemtagABI originally erroneously defined // DT_AARCH64_MEMTAG_STACK as `d_ptr`, which is why the dynamic tag value // is odd (`0x7000000c`). `d_val` is clearly the correct semantics, and so // this was fixed in the ABI, but the value (0x7000000c) didn't change // because we already had Android binaries floating around with dynamic // entries, and didn't want to create a whole new dynamic entry and // reserve a value just to fix that tiny mistake. P.S. lld was always // outputting DT_AARCH64_MEMTAG_STACK as `d_val` anyway. case DT_AARCH64_MEMTAG_STACK:
memtag_dynamic_entries_.memtag_stack = d->d_un.d_val; break; // Same as above, except DT_AARCH64_MEMTAG_GLOBALS was incorrectly defined // as `d_val` (hence an even value of `0x7000000d`), when it should have // been `d_ptr` all along. lld has always outputted this as `d_ptr`. case DT_AARCH64_MEMTAG_GLOBALS:
memtag_dynamic_entries_.memtag_globals = reinterpret_cast<void*>(load_bias + d->d_un.d_ptr); break; case DT_AARCH64_MEMTAG_GLOBALSSZ:
memtag_dynamic_entries_.memtag_globalssz = d->d_un.d_val; break; #endif
// Validity checks. if (relocating_linker && needed_count != 0) {
DL_ERR("linker cannot have DT_NEEDED dependencies on other libraries"); returnfalse;
} if (nbucket_ == 0 && gnu_nbucket_ == 0) {
DL_ERR("empty/missing DT_HASH/DT_GNU_HASH in \"%s\" " "(new hash type from the future?)", get_realpath()); returnfalse;
} if (strtab_ == nullptr) {
DL_ERR("empty/missing DT_STRTAB in \"%s\"", get_realpath()); returnfalse;
} if (symtab_ == nullptr) {
DL_ERR("empty/missing DT_SYMTAB in \"%s\"", get_realpath()); returnfalse;
}
// Second pass - parse entries relying on strtab. Skip this while relocating the linker so as to // avoid doing heap allocations until later in the linker's initialization. if (!relocating_linker) { for (ElfW(Dyn)* d = dynamic; d->d_tag != DT_NULL; ++d) { switch (d->d_tag) { case DT_SONAME:
set_soname(get_string(d->d_un.d_val)); break; case DT_RUNPATH:
set_dt_runpath(get_string(d->d_un.d_val)); break;
}
}
}
// Before API 23, the linker used the basename in place of DT_SONAME. // After we switched, apps with libraries without a DT_SONAME stopped working: // they could no longer be found by DT_NEEDED from another library. // The main executable does not need to have a DT_SONAME. // The linker has a DT_SONAME, but the soname_ field is initialized later on. if (soname_.empty() && this != solist_get_executable() && !relocating_linker &&
get_application_target_sdk_version() < 23) {
soname_ = basename(realpath_.c_str()); // The `if` above means we don't get here for targetSdkVersion >= 23, // so no need to check the return value of DL_ERROR_AFTER(). // We still call it rather than DL_WARN() to get the extra clarification.
DL_ERROR_AFTER(23, "\"%s\" has no DT_SONAME (will use %s instead)",
get_realpath(), soname_.c_str());
}
// Validate each library's verdef section once, so we don't have to validate // it each time we look up a symbol with a version. if (!validate_verdef_section(this)) returnfalse;
// MTE globals requires remapping data segments with PROT_MTE as anonymous mappings, because file // based mappings may not be backed by tag-capable memory (see "MAP_ANONYMOUS" on // https://www.kernel.org/doc/html/latest/arch/arm64/memory-tagging-extension.html). This is only // done if the binary has MTE globals (evidenced by the dynamic table entries), as it destroys // page sharing. It's also only done on devices that support MTE, because the act of remapping // pages is unnecessary on non-MTE devices (where we might still run MTE-globals enabled code). if (should_tag_memtag_globals() &&
remap_memtag_globals_segments(phdr, phnum, base) == 0) {
tag_globals(dlext_use_relro);
protect_memtag_globals_ro_segments(phdr, phnum, base);
}
#if !defined(__LP64__) if (has_text_relocations) { if (DL_ERROR_AFTER(23, "\"%s\" has text relocations", get_realpath())) { returnfalse;
}
add_dlwarning(get_realpath(), "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. if (phdr_table_unprotect_segments(phdr, phnum, load_bias, should_pad_segments_,
should_use_16kib_app_compat_) < 0) {
DL_ERR("can't unprotect loadable segments for \"%s\": %m", get_realpath()); returnfalse;
}
} #endif
if (this != solist_get_vdso() && !relocate(lookup_list)) { returnfalse;
}
#if !defined(__LP64__) if (has_text_relocations) { // All relocations are done, we can protect our segments back to read-only. if (phdr_table_protect_segments(phdr, phnum, load_bias, should_pad_segments_,
should_use_16kib_app_compat_) < 0) {
DL_ERR("can't protect segments for \"%s\": %m", get_realpath()); returnfalse;
}
} #endif
// We can also turn on GNU RELRO protection if we're not linking the dynamic linker // itself --- it can't make system calls yet, and will have to call protect_relro later. if (!is_linker() && !protect_relro()) { returnfalse;
}
// Now that we've finished linking we can apply execute permission to code segments in compat // loaded binaries, and remove write permission from .text and GNU RELRO in RX|RW compat mode. if (!protect_16kib_app_compat_code()) { returnfalse;
}
bool is_linker_config_expected(constchar* executable_path) { // Do not raise message from a host environment which is expected to miss generated linker // configuration. #if !defined(__ANDROID__) returnfalse; #endif
if (strcmp(executable_path, "/system/bin/init") == 0) { // Generated linker configuration can be missed from processes executed // with init binary returnfalse;
}
returntrue;
}
static std::string get_ld_config_file_path(constchar* executable_path) { #ifdef USE_LD_CONFIG_FILE // This is a debugging/testing only feature. Must not be available on // production builds. constchar* ld_config_file_env = getenv("LD_CONFIG_FILE"); if (ld_config_file_env != nullptr && file_exists(ld_config_file_env)) { return ld_config_file_env;
} #endif
std::string path = get_ld_config_file_apex_path(executable_path); if (!path.empty()) { if (file_exists(path.c_str())) { return path;
}
DL_WARN("Warning: couldn't read config file \"%s\" for \"%s\"",
path.c_str(), executable_path);
}
path = kLdConfigArchFilePath; if (file_exists(path.c_str())) { return path;
}
if (file_exists(kLdGeneratedConfigFilePath)) { return kLdGeneratedConfigFilePath;
}
if (is_linker_config_expected(executable_path)) {
DL_WARN("Warning: failed to find generated linker configuration from \"%s\"",
kLdGeneratedConfigFilePath);
}
path = get_ld_config_file_vndk_path(); if (file_exists(path.c_str())) { return path;
}
#ifdefined(__aarch64__) // HWASan is only supported on AArch64. // The AT_SECURE restriction is because this is a debug feature that does // not need to work on secure binaries, it doesn't hurt to disallow the // environment variable for them, as it impacts the program execution. char* hwasan_env = getenv("LD_HWASAN");
g_is_hwasan = (bname != nullptr &&
strcmp(bname, "linker_hwasan64") == 0) ||
(hwasan_env != nullptr && !getauxval(AT_SECURE) && strcmp(hwasan_env, "1") == 0);
__libc_shared_globals()->is_hwasan = g_is_hwasan; #endif
}
// 3. Establish links between namespaces for (auto& ns_config : namespace_configs) { auto it_from = namespaces.find(ns_config->name());
CHECK(it_from != namespaces.end());
android_namespace_t* namespace_from = it_from->second; for (const NamespaceLinkConfig& ns_link : ns_config->links()) { auto it_to = namespaces.find(ns_link.ns_name());
CHECK(it_to != namespaces.end());
android_namespace_t* namespace_to = it_to->second; if (ns_link.allow_all_shared_libs()) {
link_namespaces_all_libs(namespace_from, namespace_to);
} else {
link_namespaces(namespace_from, namespace_to, ns_link.shared_libs().c_str());
}
}
} // we can no longer rely on the fact that libdl.so is part of default namespace // this is why we want to add ld-android.so to all namespaces from ld.config.txt
soinfo* ld_android_so = solist_get_linker();
// we also need vdso to be available for all namespaces (if present)
soinfo* vdso = solist_get_vdso(); for (auto it : namespaces) { if (it.second != &g_default_namespace) {
it.second->add_soinfo(ld_android_so); if (vdso != nullptr) {
it.second->add_soinfo(vdso);
} // somain and ld_preloads are added to these namespaces after LD_PRELOAD libs are linked
}
}
// This function finds a namespace exported in ld.config.txt by its name. // A namespace can be exported by setting .visible property to true.
android_namespace_t* get_exported_namespace(constchar* name) { if (name == nullptr) { return nullptr;
} auto it = g_exported_namespaces.find(std::string(name)); if (it == g_exported_namespaces.end()) { return nullptr;
} return it->second;
}
void purge_unused_memory() { // For now, we only purge the memory used by LoadTask because we know those // are temporary objects. // // Purging other LinkerBlockAllocator hardly yields much because they hold // information about namespaces and opened libraries, which are not freed // when the control leaves the linker. // // Purging BionicAllocator may give us a few dirty pages back, but those pages // would be already zeroed out, so they compress easily in ZRAM. Therefore, // it is not worth munmap()'ing those pages.
TypeBasedAllocator<LoadTask>::purge();
}
Messung V0.5 in Prozent
¤ Dauer der Verarbeitung: 0.61 Sekunden
(vorverarbeitet am 2026-06-28)
¤
Die Informationen auf dieser Webseite wurden
nach bestem Wissen sorgfältig zusammengestellt. Es wird jedoch weder Vollständigkeit, noch Richtigkeit,
noch Qualität der bereit gestellten Informationen zugesichert.
Bemerkung:
Die farbliche Syntaxdarstellung und die Messung sind noch experimentell.