merge in lmp-mr1-release history after reset to 445111a1c977e94a4233efd54f3690defa4a7582
diff --git a/libc/bionic/system_properties.cpp b/libc/bionic/system_properties.cpp
index a564c39..0e16bf3 100644
--- a/libc/bionic/system_properties.cpp
+++ b/libc/bionic/system_properties.cpp
@@ -475,8 +475,8 @@
 
 static int send_prop_msg(const prop_msg *msg)
 {
-    const int fd = socket(AF_LOCAL, SOCK_STREAM, 0);
-    if (fd < 0) {
+    const int fd = socket(AF_LOCAL, SOCK_STREAM | SOCK_CLOEXEC, 0);
+    if (fd == -1) {
         return -1;
     }
 
diff --git a/libc/include/dlfcn.h b/libc/include/dlfcn.h
index 8dde08c..afa7687 100644
--- a/libc/include/dlfcn.h
+++ b/libc/include/dlfcn.h
@@ -64,6 +64,7 @@
   RTLD_GLOBAL = 2,
 #endif
   RTLD_NOLOAD = 4,
+  RTLD_NODELETE = 0x01000,
 };
 
 #if defined (__LP64__)
diff --git a/libc/include/elf.h b/libc/include/elf.h
index 7a9485a..7de464e 100644
--- a/libc/include/elf.h
+++ b/libc/include/elf.h
@@ -54,6 +54,35 @@
 #define DF_BIND_NOW   0x00000008
 #define DF_STATIC_TLS 0x00000010
 
+#define DF_1_NOW        0x00000001 // Perform complete relocation processing.
+#define DF_1_GLOBAL     0x00000002 // implies RTLD_GLOBAL
+#define DF_1_GROUP      0x00000004
+#define DF_1_NODELETE   0x00000008 // implies RTLD_NODELETE
+#define DF_1_LOADFLTR   0x00000010
+#define DF_1_INITFIRST  0x00000020
+#define DF_1_NOOPEN     0x00000040 // Object can not be used with dlopen(3)
+#define DF_1_ORIGIN     0x00000080
+#define DF_1_DIRECT     0x00000100
+#define DF_1_TRANS      0x00000200
+#define DF_1_INTERPOSE  0x00000400
+#define DF_1_NODEFLIB   0x00000800
+#define DF_1_NODUMP     0x00001000 // Object cannot be dumped with dldump(3)
+#define DF_1_CONFALT    0x00002000
+#define DF_1_ENDFILTEE  0x00004000
+#define DF_1_DISPRELDNE 0x00008000
+#define DF_1_DISPRELPND 0x00010000
+#define DF_1_NODIRECT   0x00020000
+#define DF_1_IGNMULDEF  0x00040000 // Internal use
+#define DF_1_NOKSYMS    0x00080000 // Internal use
+#define DF_1_NOHDR      0x00100000 // Internal use
+#define DF_1_EDITED     0x00200000
+#define DF_1_NORELOC    0x00400000 // Internal use
+#define DF_1_SYMINTPOSE 0x00800000
+#define DF_1_GLOBAUDIT  0x01000000
+#define DF_1_SINGLETON  0x02000000
+#define DF_1_STUB       0x04000000
+#define DF_1_PIE        0x08000000
+
 #define DT_BIND_NOW 24
 #define DT_INIT_ARRAY 25
 #define DT_FINI_ARRAY 26
diff --git a/linker/debugger.cpp b/linker/debugger.cpp
index 6565985..ac466a5 100644
--- a/linker/debugger.cpp
+++ b/linker/debugger.cpp
@@ -215,7 +215,7 @@
     return;
   }
 
-  int s = socket_abstract_client(DEBUGGER_SOCKET_NAME, SOCK_STREAM);
+  int s = socket_abstract_client(DEBUGGER_SOCKET_NAME, SOCK_STREAM | SOCK_CLOEXEC);
   if (s == -1) {
     __libc_format_log(ANDROID_LOG_FATAL, "libc", "Unable to open connection to debuggerd: %s",
                       strerror(errno));
diff --git a/linker/dlfcn.cpp b/linker/dlfcn.cpp
index 3631d2f..367179d 100644
--- a/linker/dlfcn.cpp
+++ b/linker/dlfcn.cpp
@@ -147,7 +147,7 @@
   // Determine if any symbol in the library contains the specified address.
   ElfW(Sym)* sym = dladdr_find_symbol(si, addr);
   if (sym != nullptr) {
-    info->dli_sname = si->strtab + sym->st_name;
+    info->dli_sname = si->get_string(sym->st_name);
     info->dli_saddr = reinterpret_cast<void*>(si->resolve_symbol_address(sym));
   }
 
@@ -232,7 +232,7 @@
 static unsigned g_libdl_chains[] = { 0, 2, 3, 4, 5, 6, 7, 8, 9, 0 };
 #endif
 
-static soinfo __libdl_info("libdl.so", nullptr, 0);
+static soinfo __libdl_info("libdl.so", nullptr, 0, RTLD_GLOBAL);
 
 // This is used by the dynamic linker. Every process gets these symbols for free.
 soinfo* get_libdl_info() {
@@ -244,8 +244,8 @@
     __libdl_info.nchain = sizeof(g_libdl_chains)/sizeof(unsigned);
     __libdl_info.bucket = g_libdl_buckets;
     __libdl_info.chain = g_libdl_chains;
-    __libdl_info.has_DT_SYMBOLIC = true;
     __libdl_info.ref_count = 1;
+    __libdl_info.strtab_size = sizeof(ANDROID_LIBDL_STRTAB);
   }
 
   return &__libdl_info;
diff --git a/linker/linked_list.h b/linker/linked_list.h
index 4e62e20..b088061 100644
--- a/linker/linked_list.h
+++ b/linker/linked_list.h
@@ -36,6 +36,12 @@
     clear();
   }
 
+  LinkedList(LinkedList&& that) {
+    this->head_ = that.head_;
+    this->tail_ = that.tail_;
+    that.head_ = that.tail_ = nullptr;
+  }
+
   void push_front(T* const element) {
     LinkedListEntry<T>* new_entry = Allocator::alloc();
     new_entry->next = head_;
@@ -86,7 +92,7 @@
   }
 
   template<typename F>
-  void for_each(F action) {
+  void for_each(F action) const {
     visit([&] (T* si) {
       action(si);
       return true;
@@ -94,7 +100,7 @@
   }
 
   template<typename F>
-  bool visit(F action) {
+  bool visit(F action) const {
     for (LinkedListEntry<T>* e = head_; e != nullptr; e = e->next) {
       if (!action(e->element)) {
         return false;
@@ -140,6 +146,12 @@
     return false;
   }
 
+  static LinkedList make_list(T* const element) {
+    LinkedList<T, Allocator> one_element_list;
+    one_element_list.push_back(element);
+    return one_element_list;
+  }
+
  private:
   LinkedListEntry<T>* head_;
   LinkedListEntry<T>* tail_;
diff --git a/linker/linker.cpp b/linker/linker.cpp
index 9425c9d..ef6e3e1 100644
--- a/linker/linker.cpp
+++ b/linker/linker.cpp
@@ -88,7 +88,7 @@
 
 static soinfo* solist;
 static soinfo* sonext;
-static soinfo* somain; /* main process, always the one after libdl_info */
+static soinfo* somain; // main process, always the one after libdl_info
 
 static const char* const kDefaultLdPaths[] = {
 #if defined(__LP64__)
@@ -120,22 +120,22 @@
 __LIBC_HIDDEN__ abort_msg_t* g_abort_message = nullptr; // For debuggerd.
 
 enum RelocationKind {
-    kRelocAbsolute = 0,
-    kRelocRelative,
-    kRelocCopy,
-    kRelocSymbol,
-    kRelocMax
+  kRelocAbsolute = 0,
+  kRelocRelative,
+  kRelocCopy,
+  kRelocSymbol,
+  kRelocMax
 };
 
 #if STATS
 struct linker_stats_t {
-    int count[kRelocMax];
+  int count[kRelocMax];
 };
 
 static linker_stats_t linker_stats;
 
 static void count_relocation(RelocationKind kind) {
-    ++linker_stats.count[kind];
+  ++linker_stats.count[kind];
 }
 #else
 static void count_relocation(RelocationKind) {
@@ -147,13 +147,13 @@
 #if defined(__LP64__)
 #define MARK(offset) \
     do { \
-        if ((((offset) >> 12) >> 5) < 4096) \
-            bitmask[((offset) >> 12) >> 5] |= (1 << (((offset) >> 12) & 31)); \
+      if ((((offset) >> 12) >> 5) < 4096) \
+          bitmask[((offset) >> 12) >> 5] |= (1 << (((offset) >> 12) & 31)); \
     } while (0)
 #else
 #define MARK(offset) \
     do { \
-        bitmask[((offset) >> 12) >> 3] |= (1 << (((offset) >> 12) & 7)); \
+      bitmask[((offset) >> 12) >> 3] |= (1 << (((offset) >> 12) & 7)); \
     } while (0)
 #endif
 #else
@@ -165,7 +165,7 @@
 #define DISALLOW_ALLOCATION(return_type, name, ...) \
     return_type name __VA_ARGS__ \
     { \
-        __libc_fatal("ERROR: " #name " called from the dynamic linker!\n"); \
+      __libc_fatal("ERROR: " #name " called from the dynamic linker!\n"); \
     }
 DISALLOW_ALLOCATION(void*, malloc, (size_t u __unused));
 DISALLOW_ALLOCATION(void, free, (void* u __unused));
@@ -182,10 +182,8 @@
   return sizeof(__linker_dl_err_buf);
 }
 
-/*
- * This function is an empty stub where GDB locates a breakpoint to get notified
- * about linker activity.
- */
+// This function is an empty stub where GDB locates a breakpoint to get notified
+// about linker activity.
 extern "C" void __attribute__((noinline)) __attribute__((visibility("default"))) rtld_db_dlactivity();
 
 static pthread_mutex_t g__r_debug_mutex = PTHREAD_MUTEX_INITIALIZER;
@@ -193,76 +191,75 @@
 static link_map* r_debug_tail = 0;
 
 static void insert_soinfo_into_debug_map(soinfo* info) {
-    // Copy the necessary fields into the debug structure.
-    link_map* map = &(info->link_map_head);
-    map->l_addr = info->load_bias;
-    map->l_name = reinterpret_cast<char*>(info->name);
-    map->l_ld = info->dynamic;
+  // Copy the necessary fields into the debug structure.
+  link_map* map = &(info->link_map_head);
+  map->l_addr = info->load_bias;
+  map->l_name = reinterpret_cast<char*>(info->name);
+  map->l_ld = info->dynamic;
 
-    /* Stick the new library at the end of the list.
-     * gdb tends to care more about libc than it does
-     * about leaf libraries, and ordering it this way
-     * reduces the back-and-forth over the wire.
-     */
-    if (r_debug_tail) {
-        r_debug_tail->l_next = map;
-        map->l_prev = r_debug_tail;
-        map->l_next = 0;
-    } else {
-        _r_debug.r_map = map;
-        map->l_prev = 0;
-        map->l_next = 0;
-    }
-    r_debug_tail = map;
+  // Stick the new library at the end of the list.
+  // gdb tends to care more about libc than it does
+  // about leaf libraries, and ordering it this way
+  // reduces the back-and-forth over the wire.
+  if (r_debug_tail) {
+    r_debug_tail->l_next = map;
+    map->l_prev = r_debug_tail;
+    map->l_next = 0;
+  } else {
+    _r_debug.r_map = map;
+    map->l_prev = 0;
+    map->l_next = 0;
+  }
+  r_debug_tail = map;
 }
 
 static void remove_soinfo_from_debug_map(soinfo* info) {
-    link_map* map = &(info->link_map_head);
+  link_map* map = &(info->link_map_head);
 
-    if (r_debug_tail == map) {
-        r_debug_tail = map->l_prev;
-    }
+  if (r_debug_tail == map) {
+    r_debug_tail = map->l_prev;
+  }
 
-    if (map->l_prev) {
-        map->l_prev->l_next = map->l_next;
-    }
-    if (map->l_next) {
-        map->l_next->l_prev = map->l_prev;
-    }
+  if (map->l_prev) {
+    map->l_prev->l_next = map->l_next;
+  }
+  if (map->l_next) {
+    map->l_next->l_prev = map->l_prev;
+  }
 }
 
 static void notify_gdb_of_load(soinfo* info) {
-    if (info->flags & FLAG_EXE) {
-        // GDB already knows about the main executable
-        return;
-    }
+  if (info->flags & FLAG_EXE) {
+    // GDB already knows about the main executable
+    return;
+  }
 
-    ScopedPthreadMutexLocker locker(&g__r_debug_mutex);
+  ScopedPthreadMutexLocker locker(&g__r_debug_mutex);
 
-    _r_debug.r_state = r_debug::RT_ADD;
-    rtld_db_dlactivity();
+  _r_debug.r_state = r_debug::RT_ADD;
+  rtld_db_dlactivity();
 
-    insert_soinfo_into_debug_map(info);
+  insert_soinfo_into_debug_map(info);
 
-    _r_debug.r_state = r_debug::RT_CONSISTENT;
-    rtld_db_dlactivity();
+  _r_debug.r_state = r_debug::RT_CONSISTENT;
+  rtld_db_dlactivity();
 }
 
 static void notify_gdb_of_unload(soinfo* info) {
-    if (info->flags & FLAG_EXE) {
-        // GDB already knows about the main executable
-        return;
-    }
+  if (info->flags & FLAG_EXE) {
+    // GDB already knows about the main executable
+    return;
+  }
 
-    ScopedPthreadMutexLocker locker(&g__r_debug_mutex);
+  ScopedPthreadMutexLocker locker(&g__r_debug_mutex);
 
-    _r_debug.r_state = r_debug::RT_DELETE;
-    rtld_db_dlactivity();
+  _r_debug.r_state = r_debug::RT_DELETE;
+  rtld_db_dlactivity();
 
-    remove_soinfo_from_debug_map(info);
+  remove_soinfo_from_debug_map(info);
 
-    _r_debug.r_state = r_debug::RT_CONSISTENT;
-    rtld_db_dlactivity();
+  _r_debug.r_state = r_debug::RT_CONSISTENT;
+  rtld_db_dlactivity();
 }
 
 void notify_gdb_of_libraries() {
@@ -285,13 +282,13 @@
   g_soinfo_links_allocator.protect_all(protection);
 }
 
-static soinfo* soinfo_alloc(const char* name, struct stat* file_stat, off64_t file_offset) {
+static soinfo* soinfo_alloc(const char* name, struct stat* file_stat, off64_t file_offset, uint32_t rtld_flags) {
   if (strlen(name) >= SOINFO_NAME_LEN) {
     DL_ERR("library name \"%s\" too long", name);
     return nullptr;
   }
 
-  soinfo* si = new (g_soinfo_allocator.alloc()) soinfo(name, file_stat, file_offset);
+  soinfo* si = new (g_soinfo_allocator.alloc()) soinfo(name, file_stat, file_offset, rtld_flags);
 
   sonext->next = si;
   sonext = si;
@@ -301,41 +298,41 @@
 }
 
 static void soinfo_free(soinfo* si) {
-    if (si == nullptr) {
-        return;
+  if (si == nullptr) {
+    return;
+  }
+
+  if (si->base != 0 && si->size != 0) {
+    munmap(reinterpret_cast<void*>(si->base), si->size);
+  }
+
+  soinfo *prev = nullptr, *trav;
+
+  TRACE("name %s: freeing soinfo @ %p", si->name, si);
+
+  for (trav = solist; trav != nullptr; trav = trav->next) {
+    if (trav == si) {
+      break;
     }
+    prev = trav;
+  }
+  if (trav == nullptr) {
+    // si was not in solist
+    DL_ERR("name \"%s\" is not in solist!", si->name);
+    return;
+  }
 
-    if (si->base != 0 && si->size != 0) {
-      munmap(reinterpret_cast<void*>(si->base), si->size);
-    }
+  // clear links to/from si
+  si->remove_all_links();
 
-    soinfo *prev = nullptr, *trav;
+  // prev will never be null, because the first entry in solist is
+  // always the static libdl_info.
+  prev->next = si->next;
+  if (si == sonext) {
+    sonext = prev;
+  }
 
-    TRACE("name %s: freeing soinfo @ %p", si->name, si);
-
-    for (trav = solist; trav != nullptr; trav = trav->next) {
-        if (trav == si)
-            break;
-        prev = trav;
-    }
-    if (trav == nullptr) {
-        /* si was not in solist */
-        DL_ERR("name \"%s\" is not in solist!", si->name);
-        return;
-    }
-
-    // clear links to/from si
-    si->remove_all_links();
-
-    /* prev will never be null, because the first entry in solist is
-       always the static libdl_info.
-    */
-    prev->next = si->next;
-    if (si == sonext) {
-        sonext = prev;
-    }
-
-    g_soinfo_allocator.free(si);
+  g_soinfo_allocator.free(si);
 }
 
 
@@ -377,60 +374,58 @@
 
 #if defined(__arm__)
 
-/* For a given PC, find the .so that it belongs to.
- * Returns the base address of the .ARM.exidx section
- * for that .so, and the number of 8-byte entries
- * in that section (via *pcount).
- *
- * Intended to be called by libc's __gnu_Unwind_Find_exidx().
- *
- * This function is exposed via dlfcn.cpp and libdl.so.
- */
+// For a given PC, find the .so that it belongs to.
+// Returns the base address of the .ARM.exidx section
+// for that .so, and the number of 8-byte entries
+// in that section (via *pcount).
+//
+// Intended to be called by libc's __gnu_Unwind_Find_exidx().
+//
+// This function is exposed via dlfcn.cpp and libdl.so.
 _Unwind_Ptr dl_unwind_find_exidx(_Unwind_Ptr pc, int* pcount) {
-    unsigned addr = (unsigned)pc;
+  unsigned addr = (unsigned)pc;
 
-    for (soinfo* si = solist; si != 0; si = si->next) {
-        if ((addr >= si->base) && (addr < (si->base + si->size))) {
-            *pcount = si->ARM_exidx_count;
-            return (_Unwind_Ptr)si->ARM_exidx;
-        }
+  for (soinfo* si = solist; si != 0; si = si->next) {
+    if ((addr >= si->base) && (addr < (si->base + si->size))) {
+        *pcount = si->ARM_exidx_count;
+        return (_Unwind_Ptr)si->ARM_exidx;
     }
-    *pcount = 0;
-    return nullptr;
+  }
+  *pcount = 0;
+  return nullptr;
 }
 
 #endif
 
-/* Here, we only have to provide a callback to iterate across all the
- * loaded libraries. gcc_eh does the rest. */
+// Here, we only have to provide a callback to iterate across all the
+// loaded libraries. gcc_eh does the rest.
 int dl_iterate_phdr(int (*cb)(dl_phdr_info* info, size_t size, void* data), void* data) {
-    int rv = 0;
-    for (soinfo* si = solist; si != nullptr; si = si->next) {
-        dl_phdr_info dl_info;
-        dl_info.dlpi_addr = si->link_map_head.l_addr;
-        dl_info.dlpi_name = si->link_map_head.l_name;
-        dl_info.dlpi_phdr = si->phdr;
-        dl_info.dlpi_phnum = si->phnum;
-        rv = cb(&dl_info, sizeof(dl_phdr_info), data);
-        if (rv != 0) {
-            break;
-        }
+  int rv = 0;
+  for (soinfo* si = solist; si != nullptr; si = si->next) {
+    dl_phdr_info dl_info;
+    dl_info.dlpi_addr = si->link_map_head.l_addr;
+    dl_info.dlpi_name = si->link_map_head.l_name;
+    dl_info.dlpi_phdr = si->phdr;
+    dl_info.dlpi_phnum = si->phnum;
+    rv = cb(&dl_info, sizeof(dl_phdr_info), data);
+    if (rv != 0) {
+      break;
     }
-    return rv;
+  }
+  return rv;
 }
 
-static ElfW(Sym)* soinfo_elf_lookup(soinfo* si, unsigned hash, const char* name) {
+static ElfW(Sym)* soinfo_elf_lookup(const soinfo* si, unsigned hash, const char* name) {
   ElfW(Sym)* symtab = si->symtab;
-  const char* strtab = si->strtab;
 
   TRACE_TYPE(LOOKUP, "SEARCH %s in %s@%p %x %zd",
              name, si->name, reinterpret_cast<void*>(si->base), hash, hash % si->nbucket);
 
   for (unsigned n = si->bucket[hash % si->nbucket]; n != 0; n = si->chain[n]) {
     ElfW(Sym)* s = symtab + n;
-    if (strcmp(strtab + s->st_name, name)) continue;
+    if (strcmp(si->get_string(s->st_name), name)) continue;
 
-    /* only concern ourselves with global and weak symbol definitions */
+    // only concern ourselves with global and weak symbol definitions
     switch (ELF_ST_BIND(s->st_info)) {
       case STB_GLOBAL:
       case STB_WEAK:
@@ -457,7 +452,7 @@
   return nullptr;
 }
 
-soinfo::soinfo(const char* name, const struct stat* file_stat, off64_t file_offset) {
+soinfo::soinfo(const char* name, const struct stat* file_stat, off64_t file_offset, int rtld_flags) {
   memset(this, 0, sizeof(*this));
 
   strlcpy(this->name, name, sizeof(this->name));
@@ -469,137 +464,89 @@
     this->st_ino = file_stat->st_ino;
     this->file_offset = file_offset;
   }
+
+  this->rtld_flags = rtld_flags;
 }
 
 static unsigned elfhash(const char* _name) {
-    const unsigned char* name = reinterpret_cast<const unsigned char*>(_name);
-    unsigned h = 0, g;
+  const unsigned char* name = reinterpret_cast<const unsigned char*>(_name);
+  unsigned h = 0, g;
 
-    while (*name) {
-        h = (h << 4) + *name++;
-        g = h & 0xf0000000;
-        h ^= g;
-        h ^= g >> 24;
-    }
-    return h;
+  while (*name) {
+    h = (h << 4) + *name++;
+    g = h & 0xf0000000;
+    h ^= g;
+    h ^= g >> 24;
+  }
+  return h;
 }
 
-static ElfW(Sym)* soinfo_do_lookup(soinfo* si, const char* name, soinfo** lsi) {
-    unsigned elf_hash = elfhash(name);
-    ElfW(Sym)* s = nullptr;
+static ElfW(Sym)* soinfo_do_lookup(soinfo* si_from, const char* name, soinfo** si_found_in,
+    const soinfo::soinfo_list_t& global_group, const soinfo::soinfo_list_t& local_group) {
+  unsigned elf_hash = elfhash(name);
+  ElfW(Sym)* s = nullptr;
 
-    if (somain != nullptr) {
-        /*
-         * Local scope is executable scope. Just start looking into it right away
-         * for the shortcut.
-         */
-
-        if (si == somain) {
-            s = soinfo_elf_lookup(si, elf_hash, name);
-            if (s != nullptr) {
-                *lsi = si;
-                goto done;
-            }
-
-            /* Next, look for it in the preloads list */
-            for (int i = 0; g_ld_preloads[i] != NULL; i++) {
-                s = soinfo_elf_lookup(g_ld_preloads[i], elf_hash, name);
-                if (s != NULL) {
-                    *lsi = g_ld_preloads[i];
-                    goto done;
-                }
-            }
-        } else {
-            /* Order of symbol lookup is controlled by DT_SYMBOLIC flag */
-
-            /*
-             * If this object was built with symbolic relocations disabled, the
-             * first place to look to resolve external references is the main
-             * executable.
-             */
-
-            if (!si->has_DT_SYMBOLIC) {
-                DEBUG("%s: looking up %s in executable %s",
-                      si->name, name, somain->name);
-                s = soinfo_elf_lookup(somain, elf_hash, name);
-                if (s != nullptr) {
-                    *lsi = somain;
-                    goto done;
-                }
-
-                /* Next, look for it in the preloads list */
-                for (int i = 0; g_ld_preloads[i] != NULL; i++) {
-                    s = soinfo_elf_lookup(g_ld_preloads[i], elf_hash, name);
-                    if (s != NULL) {
-                        *lsi = g_ld_preloads[i];
-                        goto done;
-                    }
-                }
-            }
-
-            /* Look for symbols in the local scope (the object who is
-             * searching). This happens with C++ templates on x86 for some
-             * reason.
-             *
-             * Notes on weak symbols:
-             * The ELF specs are ambiguous about treatment of weak definitions in
-             * dynamic linking.  Some systems return the first definition found
-             * and some the first non-weak definition.   This is system dependent.
-             * Here we return the first definition found for simplicity.  */
-
-            s = soinfo_elf_lookup(si, elf_hash, name);
-            if (s != nullptr) {
-                *lsi = si;
-                goto done;
-            }
-
-            /*
-             * If this object was built with -Bsymbolic and symbol is not found
-             * in the local scope, try to find the symbol in the main executable.
-             */
-
-            if (si->has_DT_SYMBOLIC) {
-                DEBUG("%s: looking up %s in executable %s after local scope",
-                      si->name, name, somain->name);
-                s = soinfo_elf_lookup(somain, elf_hash, name);
-                if (s != nullptr) {
-                    *lsi = somain;
-                    goto done;
-                }
-
-                /* Next, look for it in the preloads list */
-                for (int i = 0; g_ld_preloads[i] != NULL; i++) {
-                    s = soinfo_elf_lookup(g_ld_preloads[i], elf_hash, name);
-                    if (s != NULL) {
-                        *lsi = g_ld_preloads[i];
-                        goto done;
-                    }
-                }
-            }
-        }
-    }
-
-    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:
+  /* "This element's presence in a shared object library alters the dynamic linker's
+   * symbol resolution algorithm for references within the library. Instead of starting
+   * a symbol search with the executable file, the dynamic linker starts from the shared
+   * object itself. If the shared object fails to supply the referenced symbol, the
+   * dynamic linker then searches the executable file and other shared objects as usual."
+   *
+   * http://www.sco.com/developers/gabi/2012-12-31/ch5.dynamic.html
+   *
+   * Note that this is unlikely since static linker avoids generating
+   * relocations for -Bsymbolic linked dynamic executables.
+   */
+  if (si_from->has_DT_SYMBOLIC) {
+    DEBUG("%s: looking up %s in local scope (DT_SYMBOLIC)", si_from->name, name);
+    s = soinfo_elf_lookup(si_from, elf_hash, name);
     if (s != nullptr) {
-        TRACE_TYPE(LOOKUP, "si %s sym %s s->st_value = %p, "
-                   "found in %s, base = %p, load bias = %p",
-                   si->name, name, reinterpret_cast<void*>(s->st_value),
-                   (*lsi)->name, reinterpret_cast<void*>((*lsi)->base),
-                   reinterpret_cast<void*>((*lsi)->load_bias));
-        return s;
+      *si_found_in = si_from;
     }
+  }
 
-    return nullptr;
+  // 1. Look for it in global_group
+  if (s == nullptr) {
+    global_group.visit([&](soinfo* global_si) {
+      DEBUG("%s: looking up %s in %s (from global group)", si_from->name, name, global_si->name);
+      s = soinfo_elf_lookup(global_si, elf_hash, name);
+      if (s != nullptr) {
+        *si_found_in = global_si;
+        return false;
+      }
+
+      return true;
+    });
+  }
+
+  // 2. Look for it in the local group
+  if (s == nullptr) {
+    local_group.visit([&](soinfo* local_si) {
+      if (local_si == si_from && si_from->has_DT_SYMBOLIC) {
+        // we already did this - skip
+        return true;
+      }
+
+      DEBUG("%s: looking up %s in %s (from local group)", si_from->name, name, local_si->name);
+      s = soinfo_elf_lookup(local_si, elf_hash, name);
+      if (s != nullptr) {
+        *si_found_in = local_si;
+        return false;
+      }
+
+      return true;
+    });
+  }
+
+  if (s != nullptr) {
+    TRACE_TYPE(LOOKUP, "si %s sym %s s->st_value = %p, "
+               "found in %s, base = %p, load bias = %p",
+               si_from->name, name, reinterpret_cast<void*>(s->st_value),
+               (*si_found_in)->name, reinterpret_cast<void*>((*si_found_in)->base),
+               reinterpret_cast<void*>((*si_found_in)->load_bias));
+  }
+
+  return s;
 }
 
 // Each size has it's own allocator.
@@ -677,33 +624,61 @@
 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) {
+// This function walks down the tree of soinfo dependencies
+// in breadth-first order and
+//   * calls action(soinfo* si) for each node, and
+//   * terminates walk if action returns false.
+//
+// walk_dependencies_tree returns false if walk was terminated
+// by the action and true otherwise.
+template<typename F>
+static bool walk_dependencies_tree(soinfo* root_soinfos[], size_t root_soinfos_size, F action) {
   SoinfoLinkedList visit_list;
   SoinfoLinkedList visited;
 
-  visit_list.push_back(si);
-  soinfo* current_soinfo;
-  while ((current_soinfo = visit_list.pop_front()) != nullptr) {
-    if (visited.contains(current_soinfo)) {
+  for (size_t i = 0; i < root_soinfos_size; ++i) {
+    visit_list.push_back(root_soinfos[i]);
+  }
+
+  soinfo* si;
+  while ((si = visit_list.pop_front()) != nullptr) {
+    if (visited.contains(si)) {
       continue;
     }
 
-    ElfW(Sym)* result = soinfo_elf_lookup(current_soinfo, elfhash(name), name);
-
-    if (result != nullptr) {
-      *found = current_soinfo;
-      return result;
+    if (!action(si)) {
+      return false;
     }
-    visited.push_back(current_soinfo);
 
-    current_soinfo->get_children().for_each([&](soinfo* child) {
+    visited.push_back(si);
+
+    si->get_children().for_each([&](soinfo* child) {
       visit_list.push_back(child);
     });
   }
 
-  return nullptr;
+  return true;
+}
+
+
+// This is used by dlsym(3).  It performs symbol lookup only within the
+// specified soinfo object and its dependencies in breadth first order.
+ElfW(Sym)* dlsym_handle_lookup(soinfo* si, soinfo** found, const char* name) {
+  ElfW(Sym)* result = nullptr;
+  uint32_t elf_hash = elfhash(name);
+
+
+  walk_dependencies_tree(&si, 1, [&](soinfo* current_soinfo) {
+    result = soinfo_elf_lookup(current_soinfo, elf_hash, name);
+    if (result != nullptr) {
+      *found = current_soinfo;
+      return false;
+    }
+
+    return true;
+  });
+
+  return result;
 }
 
 /* This is used by dlsym(3) to performs a global symbol lookup. If the
@@ -720,6 +695,10 @@
 
   ElfW(Sym)* s = nullptr;
   for (soinfo* si = start; (s == nullptr) && (si != nullptr); si = si->next) {
+    if ((si->get_rtld_flags() & RTLD_GLOBAL) == 0) {
+      continue;
+    }
+
     s = soinfo_elf_lookup(si, elf_hash, name);
     if (s != nullptr) {
       *found = si;
@@ -805,12 +784,12 @@
 static void for_each_dt_needed(const soinfo* si, F action) {
   for (ElfW(Dyn)* d = si->dynamic; d->d_tag != DT_NULL; ++d) {
     if (d->d_tag == DT_NEEDED) {
-      action(si->strtab + d->d_un.d_val);
+      action(si->get_string(d->d_un.d_val));
     }
   }
 }
 
-static soinfo* load_library(LoadTaskList& load_tasks, const char* name, int dlflags, const android_dlextinfo* extinfo) {
+static soinfo* load_library(LoadTaskList& load_tasks, const char* name, int rtld_flags, const android_dlextinfo* extinfo) {
   int fd = -1;
   off64_t file_offset = 0;
   ScopedFd file_guard(-1);
@@ -855,7 +834,7 @@
     }
   }
 
-  if ((dlflags & RTLD_NOLOAD) != 0) {
+  if ((rtld_flags & RTLD_NOLOAD) != 0) {
     DL_ERR("library \"%s\" wasn't loaded and RTLD_NOLOAD prevented it", name);
     return nullptr;
   }
@@ -866,7 +845,7 @@
     return nullptr;
   }
 
-  soinfo* si = soinfo_alloc(SEARCH_NAME(name), &file_stat, file_offset);
+  soinfo* si = soinfo_alloc(SEARCH_NAME(name), &file_stat, file_offset, rtld_flags);
   if (si == nullptr) {
     return nullptr;
   }
@@ -898,7 +877,7 @@
   return nullptr;
 }
 
-static soinfo* find_library_internal(LoadTaskList& load_tasks, const char* name, int dlflags, const android_dlextinfo* extinfo) {
+static soinfo* find_library_internal(LoadTaskList& load_tasks, const char* name, int rtld_flags, const android_dlextinfo* extinfo) {
 
   soinfo* si = find_loaded_library_by_name(name);
 
@@ -906,7 +885,7 @@
   // of this fact is done by load_library.
   if (si == nullptr) {
     TRACE("[ '%s' has not been found by name.  Trying harder...]", name);
-    si = load_library(load_tasks, name, dlflags, extinfo);
+    si = load_library(load_tasks, name, rtld_flags, extinfo);
   }
 
   return si;
@@ -929,19 +908,51 @@
   });
 }
 
-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));
+// TODO: this is slightly unusual way to construct
+// the global group for relocation. Not every RTLD_GLOBAL
+// library is included in this group for backwards-compatibility
+// reasons.
+//
+// This group consists of the main executable, LD_PRELOADs
+// and libraries with the DF_1_GLOBAL flag set.
+static soinfo::soinfo_list_t make_global_group() {
+  soinfo::soinfo_list_t global_group;
+  for (soinfo* si = somain; si != nullptr; si = si->next) {
+    if ((si->get_dt_flags_1() & DF_1_GLOBAL) != 0) {
+      global_group.push_back(si);
+    }
   }
 
-  // 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;
+  return global_group;
+}
+
+static bool find_libraries(soinfo* start_with, const char* const library_names[], size_t library_names_count, soinfo* soinfos[],
+    soinfo* ld_preloads[], size_t ld_preloads_count, int rtld_flags, const android_dlextinfo* extinfo) {
+  // Step 0: prepare.
+  LoadTaskList load_tasks;
+  for (size_t i = 0; i < library_names_count; ++i) {
+    const char* name = library_names[i];
+    load_tasks.push_back(LoadTask::create(name, start_with));
+  }
+
+  // Construct global_group.
+  soinfo::soinfo_list_t global_group = make_global_group();
+
+  // If soinfos array is null allocate one on stack.
+  // The array is needed in case of failure; for example
+  // when library_names[] = {libone.so, libtwo.so} and libone.so
+  // is loaded correctly but libtwo.so failed for some reason.
+  // In this case libone.so should be unloaded on return.
+  // See also implementation of failure_guard below.
+
+  if (soinfos == nullptr) {
+    size_t soinfos_size = sizeof(soinfo*)*library_names_count;
+    soinfos = reinterpret_cast<soinfo**>(alloca(soinfos_size));
+    memset(soinfos, 0, soinfos_size);
+  }
+
+  // list of libraries to link - see step 2.
+  size_t soinfos_count = 0;
 
   auto failure_guard = make_scope_guard([&]() {
     // Housekeeping
@@ -949,14 +960,14 @@
       LoadTask::deleter(t);
     });
 
-    for (size_t i = 0; i<soinfos_size; ++i) {
+    for (size_t i = 0; i<soinfos_count; ++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);
+    soinfo* si = find_library_internal(load_tasks, task->get_name(), rtld_flags, extinfo);
     if (si == nullptr) {
       return false;
     }
@@ -971,37 +982,52 @@
     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;
+    // When ld_preloads is not null, the first
+    // ld_preloads_count libs are in fact ld_preloads.
+    if (ld_preloads != nullptr && soinfos_count < ld_preloads_count) {
+      // Add LD_PRELOADed libraries to the global group for future runs.
+      // There is no need to explicitly add them to the global group
+      // for this run because they are going to appear in the local
+      // group in the correct order.
+      si->set_dt_flags_1(si->get_dt_flags_1() | DF_1_GLOBAL);
+      ld_preloads[soinfos_count] = si;
     }
 
-    if (soinfos_size<library_names_size) {
-      soinfos[soinfos_size++] = si;
+    if (soinfos_count < library_names_count) {
+      soinfos[soinfos_count++] = si;
     }
   }
 
   // Step 2: link libraries.
-  soinfo* si;
-  while ((si = found_libs.pop_front()) != nullptr) {
+  soinfo::soinfo_list_t local_group;
+  walk_dependencies_tree(
+      start_with == nullptr ? soinfos : &start_with,
+      start_with == nullptr ? soinfos_count : 1,
+      [&] (soinfo* si) {
+    local_group.push_back(si);
+    return true;
+  });
+
+  bool linked = local_group.visit([&](soinfo* si) {
     if ((si->flags & FLAG_LINKED) == 0) {
-      if (!si->LinkImage(extinfo)) {
+      if (!si->LinkImage(global_group, local_group, extinfo)) {
         return false;
       }
       si->flags |= FLAG_LINKED;
     }
+
+    return true;
+  });
+
+  if (linked) {
+    failure_guard.disable();
   }
 
-  // All is well - found_libs and load_tasks are empty at this point
-  // and all libs are successfully linked.
-  failure_guard.disable();
-  return true;
+  return linked;
 }
 
-static soinfo* find_library(const char* name, int dlflags, const android_dlextinfo* extinfo) {
+static soinfo* find_library(const char* name, int rtld_flags, const android_dlextinfo* extinfo) {
   if (name == nullptr) {
     somain->ref_count++;
     return somain;
@@ -1009,7 +1035,7 @@
 
   soinfo* si;
 
-  if (!find_libraries(&name, 1, &si, nullptr, 0, dlflags, extinfo)) {
+  if (!find_libraries(nullptr, &name, 1, &si, nullptr, 0, rtld_flags, extinfo)) {
     return nullptr;
   }
 
@@ -1017,6 +1043,11 @@
 }
 
 static void soinfo_unload(soinfo* si) {
+  if (!si->can_unload()) {
+    TRACE("not unloading '%s' - the binary is flagged with NODELETE", si->name);
+    return;
+  }
+
   if (si->ref_count == 1) {
     TRACE("unloading '%s'", si->name);
     si->CallDestructors();
@@ -1075,7 +1106,7 @@
 }
 
 soinfo* do_dlopen(const char* name, int flags, const android_dlextinfo* extinfo) {
-  if ((flags & ~(RTLD_NOW|RTLD_LAZY|RTLD_LOCAL|RTLD_GLOBAL|RTLD_NOLOAD)) != 0) {
+  if ((flags & ~(RTLD_NOW|RTLD_LAZY|RTLD_LOCAL|RTLD_GLOBAL|RTLD_NODELETE|RTLD_NOLOAD)) != 0) {
     DL_ERR("invalid flags to dlopen: %x", flags);
     return nullptr;
   }
@@ -1115,7 +1146,7 @@
 }
 
 #if defined(USE_RELA)
-int soinfo::Relocate(ElfW(Rela)* rela, unsigned count) {
+int soinfo::Relocate(ElfW(Rela)* rela, unsigned count, const soinfo_list_t& global_group, const soinfo_list_t& local_group) {
   for (size_t idx = 0; idx < count; ++idx, ++rela) {
     unsigned type = ELFW(R_TYPE)(rela->r_info);
     unsigned sym = ELFW(R_SYM)(rela->r_info);
@@ -1132,8 +1163,8 @@
     soinfo* lsi = nullptr;
 
     if (sym != 0) {
-      sym_name = reinterpret_cast<const char*>(strtab + symtab[sym].st_name);
-      s = soinfo_do_lookup(this, sym_name, &lsi);
+      sym_name = get_string(symtab[sym].st_name);
+      s = soinfo_do_lookup(this, sym_name, &lsi, global_group,local_group);
       if (s == nullptr) {
         // We only allow an undefined symbol if this is a weak reference...
         s = &symtab[sym];
@@ -1156,35 +1187,35 @@
 
         switch (type) {
 #if defined(__aarch64__)
-        case R_AARCH64_JUMP_SLOT:
-        case R_AARCH64_GLOB_DAT:
-        case R_AARCH64_ABS64:
-        case R_AARCH64_ABS32:
-        case R_AARCH64_ABS16:
-        case R_AARCH64_RELATIVE:
-        case R_AARCH64_IRELATIVE:
-          /*
-           * The sym_addr was initialized to be zero above, or the relocation
-           * code below does not care about value of sym_addr.
-           * No need to do anything.
-           */
-          break;
+          case R_AARCH64_JUMP_SLOT:
+          case R_AARCH64_GLOB_DAT:
+          case R_AARCH64_ABS64:
+          case R_AARCH64_ABS32:
+          case R_AARCH64_ABS16:
+          case R_AARCH64_RELATIVE:
+          case R_AARCH64_IRELATIVE:
+            /*
+             * The sym_addr was initialized to be zero above, or the relocation
+             * code below does not care about value of sym_addr.
+             * No need to do anything.
+             */
+            break;
 #elif defined(__x86_64__)
-        case R_X86_64_JUMP_SLOT:
-        case R_X86_64_GLOB_DAT:
-        case R_X86_64_32:
-        case R_X86_64_64:
-        case R_X86_64_RELATIVE:
-        case R_X86_64_IRELATIVE:
-          // No need to do anything.
-          break;
-        case R_X86_64_PC32:
-          sym_addr = reloc;
-          break;
+          case R_X86_64_JUMP_SLOT:
+          case R_X86_64_GLOB_DAT:
+          case R_X86_64_32:
+          case R_X86_64_64:
+          case R_X86_64_RELATIVE:
+          case R_X86_64_IRELATIVE:
+            // No need to do anything.
+            break;
+          case R_X86_64_PC32:
+            sym_addr = reloc;
+            break;
 #endif
-        default:
-          DL_ERR("unknown weak reloc type %d @ %p (%zu)", type, rela, idx);
-          return -1;
+          default:
+            DL_ERR("unknown weak reloc type %d @ %p (%zu)", type, rela, idx);
+            return -1;
         }
       } else {
         // We got a definition.
@@ -1195,119 +1226,119 @@
 
     switch (type) {
 #if defined(__aarch64__)
-    case R_AARCH64_JUMP_SLOT:
+      case R_AARCH64_JUMP_SLOT:
         count_relocation(kRelocAbsolute);
         MARK(rela->r_offset);
         TRACE_TYPE(RELO, "RELO JMP_SLOT %16llx <- %16llx %s\n",
                    reloc, (sym_addr + rela->r_addend), sym_name);
         *reinterpret_cast<ElfW(Addr)*>(reloc) = (sym_addr + rela->r_addend);
         break;
-    case R_AARCH64_GLOB_DAT:
+      case R_AARCH64_GLOB_DAT:
         count_relocation(kRelocAbsolute);
         MARK(rela->r_offset);
         TRACE_TYPE(RELO, "RELO GLOB_DAT %16llx <- %16llx %s\n",
                    reloc, (sym_addr + rela->r_addend), sym_name);
         *reinterpret_cast<ElfW(Addr)*>(reloc) = (sym_addr + rela->r_addend);
         break;
-    case R_AARCH64_ABS64:
+      case R_AARCH64_ABS64:
         count_relocation(kRelocAbsolute);
         MARK(rela->r_offset);
         TRACE_TYPE(RELO, "RELO ABS64 %16llx <- %16llx %s\n",
                    reloc, (sym_addr + rela->r_addend), sym_name);
         *reinterpret_cast<ElfW(Addr)*>(reloc) += (sym_addr + rela->r_addend);
         break;
-    case R_AARCH64_ABS32:
+      case R_AARCH64_ABS32:
         count_relocation(kRelocAbsolute);
         MARK(rela->r_offset);
         TRACE_TYPE(RELO, "RELO ABS32 %16llx <- %16llx %s\n",
                    reloc, (sym_addr + rela->r_addend), sym_name);
         if ((static_cast<ElfW(Addr)>(INT32_MIN) <= (*reinterpret_cast<ElfW(Addr)*>(reloc) + (sym_addr + rela->r_addend))) &&
             ((*reinterpret_cast<ElfW(Addr)*>(reloc) + (sym_addr + rela->r_addend)) <= static_cast<ElfW(Addr)>(UINT32_MAX))) {
-            *reinterpret_cast<ElfW(Addr)*>(reloc) += (sym_addr + rela->r_addend);
+          *reinterpret_cast<ElfW(Addr)*>(reloc) += (sym_addr + rela->r_addend);
         } else {
-            DL_ERR("0x%016llx out of range 0x%016llx to 0x%016llx",
-                   (*reinterpret_cast<ElfW(Addr)*>(reloc) + (sym_addr + rela->r_addend)),
-                   static_cast<ElfW(Addr)>(INT32_MIN),
-                   static_cast<ElfW(Addr)>(UINT32_MAX));
-            return -1;
+          DL_ERR("0x%016llx out of range 0x%016llx to 0x%016llx",
+                 (*reinterpret_cast<ElfW(Addr)*>(reloc) + (sym_addr + rela->r_addend)),
+                 static_cast<ElfW(Addr)>(INT32_MIN),
+                 static_cast<ElfW(Addr)>(UINT32_MAX));
+          return -1;
         }
         break;
-    case R_AARCH64_ABS16:
+      case R_AARCH64_ABS16:
         count_relocation(kRelocAbsolute);
         MARK(rela->r_offset);
         TRACE_TYPE(RELO, "RELO ABS16 %16llx <- %16llx %s\n",
                    reloc, (sym_addr + rela->r_addend), sym_name);
         if ((static_cast<ElfW(Addr)>(INT16_MIN) <= (*reinterpret_cast<ElfW(Addr)*>(reloc) + (sym_addr + rela->r_addend))) &&
             ((*reinterpret_cast<ElfW(Addr)*>(reloc) + (sym_addr + rela->r_addend)) <= static_cast<ElfW(Addr)>(UINT16_MAX))) {
-            *reinterpret_cast<ElfW(Addr)*>(reloc) += (sym_addr + rela->r_addend);
+          *reinterpret_cast<ElfW(Addr)*>(reloc) += (sym_addr + rela->r_addend);
         } else {
-            DL_ERR("0x%016llx out of range 0x%016llx to 0x%016llx",
-                   (*reinterpret_cast<ElfW(Addr)*>(reloc) + (sym_addr + rela->r_addend)),
-                   static_cast<ElfW(Addr)>(INT16_MIN),
-                   static_cast<ElfW(Addr)>(UINT16_MAX));
-            return -1;
+          DL_ERR("0x%016llx out of range 0x%016llx to 0x%016llx",
+                 (*reinterpret_cast<ElfW(Addr)*>(reloc) + (sym_addr + rela->r_addend)),
+                 static_cast<ElfW(Addr)>(INT16_MIN),
+                 static_cast<ElfW(Addr)>(UINT16_MAX));
+          return -1;
         }
         break;
-    case R_AARCH64_PREL64:
+      case R_AARCH64_PREL64:
         count_relocation(kRelocRelative);
         MARK(rela->r_offset);
         TRACE_TYPE(RELO, "RELO REL64 %16llx <- %16llx - %16llx %s\n",
                    reloc, (sym_addr + rela->r_addend), rela->r_offset, sym_name);
         *reinterpret_cast<ElfW(Addr)*>(reloc) += (sym_addr + rela->r_addend) - rela->r_offset;
         break;
-    case R_AARCH64_PREL32:
+      case R_AARCH64_PREL32:
         count_relocation(kRelocRelative);
         MARK(rela->r_offset);
         TRACE_TYPE(RELO, "RELO REL32 %16llx <- %16llx - %16llx %s\n",
                    reloc, (sym_addr + rela->r_addend), rela->r_offset, sym_name);
         if ((static_cast<ElfW(Addr)>(INT32_MIN) <= (*reinterpret_cast<ElfW(Addr)*>(reloc) + ((sym_addr + rela->r_addend) - rela->r_offset))) &&
             ((*reinterpret_cast<ElfW(Addr)*>(reloc) + ((sym_addr + rela->r_addend) - rela->r_offset)) <= static_cast<ElfW(Addr)>(UINT32_MAX))) {
-            *reinterpret_cast<ElfW(Addr)*>(reloc) += ((sym_addr + rela->r_addend) - rela->r_offset);
+          *reinterpret_cast<ElfW(Addr)*>(reloc) += ((sym_addr + rela->r_addend) - rela->r_offset);
         } else {
-            DL_ERR("0x%016llx out of range 0x%016llx to 0x%016llx",
-                   (*reinterpret_cast<ElfW(Addr)*>(reloc) + ((sym_addr + rela->r_addend) - rela->r_offset)),
-                   static_cast<ElfW(Addr)>(INT32_MIN),
-                   static_cast<ElfW(Addr)>(UINT32_MAX));
-            return -1;
+          DL_ERR("0x%016llx out of range 0x%016llx to 0x%016llx",
+                 (*reinterpret_cast<ElfW(Addr)*>(reloc) + ((sym_addr + rela->r_addend) - rela->r_offset)),
+                 static_cast<ElfW(Addr)>(INT32_MIN),
+                 static_cast<ElfW(Addr)>(UINT32_MAX));
+          return -1;
         }
         break;
-    case R_AARCH64_PREL16:
+      case R_AARCH64_PREL16:
         count_relocation(kRelocRelative);
         MARK(rela->r_offset);
         TRACE_TYPE(RELO, "RELO REL16 %16llx <- %16llx - %16llx %s\n",
                    reloc, (sym_addr + rela->r_addend), rela->r_offset, sym_name);
         if ((static_cast<ElfW(Addr)>(INT16_MIN) <= (*reinterpret_cast<ElfW(Addr)*>(reloc) + ((sym_addr + rela->r_addend) - rela->r_offset))) &&
             ((*reinterpret_cast<ElfW(Addr)*>(reloc) + ((sym_addr + rela->r_addend) - rela->r_offset)) <= static_cast<ElfW(Addr)>(UINT16_MAX))) {
-            *reinterpret_cast<ElfW(Addr)*>(reloc) += ((sym_addr + rela->r_addend) - rela->r_offset);
+          *reinterpret_cast<ElfW(Addr)*>(reloc) += ((sym_addr + rela->r_addend) - rela->r_offset);
         } else {
-            DL_ERR("0x%016llx out of range 0x%016llx to 0x%016llx",
-                   (*reinterpret_cast<ElfW(Addr)*>(reloc) + ((sym_addr + rela->r_addend) - rela->r_offset)),
-                   static_cast<ElfW(Addr)>(INT16_MIN),
-                   static_cast<ElfW(Addr)>(UINT16_MAX));
-            return -1;
+          DL_ERR("0x%016llx out of range 0x%016llx to 0x%016llx",
+                 (*reinterpret_cast<ElfW(Addr)*>(reloc) + ((sym_addr + rela->r_addend) - rela->r_offset)),
+                 static_cast<ElfW(Addr)>(INT16_MIN),
+                 static_cast<ElfW(Addr)>(UINT16_MAX));
+          return -1;
         }
         break;
 
-    case R_AARCH64_RELATIVE:
+      case R_AARCH64_RELATIVE:
         count_relocation(kRelocRelative);
         MARK(rela->r_offset);
         if (sym) {
-            DL_ERR("odd RELATIVE form...");
-            return -1;
+          DL_ERR("odd RELATIVE form...");
+          return -1;
         }
         TRACE_TYPE(RELO, "RELO RELATIVE %16llx <- %16llx\n",
                    reloc, (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_IRELATIVE:
+        count_relocation(kRelocRelative);
+        MARK(rela->r_offset);
+        TRACE_TYPE(RELO, "RELO IRELATIVE %16llx <- %16llx\n", reloc, (base + rela->r_addend));
+        *reinterpret_cast<ElfW(Addr)*>(reloc) = call_ifunc_resolver(base + rela->r_addend);
+        break;
 
-    case R_AARCH64_COPY:
+      case R_AARCH64_COPY:
         /*
          * ET_EXEC is not supported so this should not happen.
          *
@@ -1319,334 +1350,334 @@
          */
         DL_ERR("%s R_AARCH64_COPY relocations are not supported", name);
         return -1;
-    case R_AARCH64_TLS_TPREL64:
+      case R_AARCH64_TLS_TPREL64:
         TRACE_TYPE(RELO, "RELO TLS_TPREL64 *** %16llx <- %16llx - %16llx\n",
                    reloc, (sym_addr + rela->r_addend), rela->r_offset);
         break;
-    case R_AARCH64_TLS_DTPREL32:
+      case R_AARCH64_TLS_DTPREL32:
         TRACE_TYPE(RELO, "RELO TLS_DTPREL32 *** %16llx <- %16llx - %16llx\n",
                    reloc, (sym_addr + rela->r_addend), rela->r_offset);
         break;
 #elif defined(__x86_64__)
-    case R_X86_64_JUMP_SLOT:
-      count_relocation(kRelocAbsolute);
-      MARK(rela->r_offset);
-      TRACE_TYPE(RELO, "RELO JMP_SLOT %08zx <- %08zx %s", static_cast<size_t>(reloc),
-                 static_cast<size_t>(sym_addr + rela->r_addend), sym_name);
-      *reinterpret_cast<ElfW(Addr)*>(reloc) = sym_addr + rela->r_addend;
-      break;
-    case R_X86_64_GLOB_DAT:
-      count_relocation(kRelocAbsolute);
-      MARK(rela->r_offset);
-      TRACE_TYPE(RELO, "RELO GLOB_DAT %08zx <- %08zx %s", static_cast<size_t>(reloc),
-                 static_cast<size_t>(sym_addr + rela->r_addend), sym_name);
-      *reinterpret_cast<ElfW(Addr)*>(reloc) = sym_addr + rela->r_addend;
-      break;
-    case R_X86_64_RELATIVE:
-      count_relocation(kRelocRelative);
-      MARK(rela->r_offset);
-      if (sym) {
-        DL_ERR("odd RELATIVE form...");
-        return -1;
-      }
-      TRACE_TYPE(RELO, "RELO RELATIVE %08zx <- +%08zx", static_cast<size_t>(reloc),
-                 static_cast<size_t>(base));
-      *reinterpret_cast<ElfW(Addr)*>(reloc) = base + rela->r_addend;
-      break;
-    case R_X86_64_IRELATIVE:
-      count_relocation(kRelocRelative);
-      MARK(rela->r_offset);
-      TRACE_TYPE(RELO, "RELO IRELATIVE %16llx <- %16llx\n", reloc, (base + rela->r_addend));
-      *reinterpret_cast<ElfW(Addr)*>(reloc) = call_ifunc_resolver(base + rela->r_addend);
-      break;
-    case R_X86_64_32:
-      count_relocation(kRelocRelative);
-      MARK(rela->r_offset);
-      TRACE_TYPE(RELO, "RELO R_X86_64_32 %08zx <- +%08zx %s", static_cast<size_t>(reloc),
-                 static_cast<size_t>(sym_addr), sym_name);
-      *reinterpret_cast<ElfW(Addr)*>(reloc) = sym_addr + rela->r_addend;
-      break;
-    case R_X86_64_64:
-      count_relocation(kRelocRelative);
-      MARK(rela->r_offset);
-      TRACE_TYPE(RELO, "RELO R_X86_64_64 %08zx <- +%08zx %s", static_cast<size_t>(reloc),
-                 static_cast<size_t>(sym_addr), sym_name);
-      *reinterpret_cast<ElfW(Addr)*>(reloc) = sym_addr + rela->r_addend;
-      break;
-    case R_X86_64_PC32:
-      count_relocation(kRelocRelative);
-      MARK(rela->r_offset);
-      TRACE_TYPE(RELO, "RELO R_X86_64_PC32 %08zx <- +%08zx (%08zx - %08zx) %s",
-                 static_cast<size_t>(reloc), static_cast<size_t>(sym_addr - reloc),
-                 static_cast<size_t>(sym_addr), static_cast<size_t>(reloc), sym_name);
-      *reinterpret_cast<ElfW(Addr)*>(reloc) = sym_addr + rela->r_addend - reloc;
-      break;
+      case R_X86_64_JUMP_SLOT:
+        count_relocation(kRelocAbsolute);
+        MARK(rela->r_offset);
+        TRACE_TYPE(RELO, "RELO JMP_SLOT %08zx <- %08zx %s", static_cast<size_t>(reloc),
+                   static_cast<size_t>(sym_addr + rela->r_addend), sym_name);
+        *reinterpret_cast<ElfW(Addr)*>(reloc) = sym_addr + rela->r_addend;
+        break;
+      case R_X86_64_GLOB_DAT:
+        count_relocation(kRelocAbsolute);
+        MARK(rela->r_offset);
+        TRACE_TYPE(RELO, "RELO GLOB_DAT %08zx <- %08zx %s", static_cast<size_t>(reloc),
+                   static_cast<size_t>(sym_addr + rela->r_addend), sym_name);
+        *reinterpret_cast<ElfW(Addr)*>(reloc) = sym_addr + rela->r_addend;
+        break;
+      case R_X86_64_RELATIVE:
+        count_relocation(kRelocRelative);
+        MARK(rela->r_offset);
+        if (sym) {
+          DL_ERR("odd RELATIVE form...");
+          return -1;
+        }
+        TRACE_TYPE(RELO, "RELO RELATIVE %08zx <- +%08zx", static_cast<size_t>(reloc),
+                   static_cast<size_t>(base));
+        *reinterpret_cast<ElfW(Addr)*>(reloc) = base + rela->r_addend;
+        break;
+      case R_X86_64_IRELATIVE:
+        count_relocation(kRelocRelative);
+        MARK(rela->r_offset);
+        TRACE_TYPE(RELO, "RELO IRELATIVE %16llx <- %16llx\n", reloc, (base + rela->r_addend));
+        *reinterpret_cast<ElfW(Addr)*>(reloc) = call_ifunc_resolver(base + rela->r_addend);
+        break;
+      case R_X86_64_32:
+        count_relocation(kRelocRelative);
+        MARK(rela->r_offset);
+        TRACE_TYPE(RELO, "RELO R_X86_64_32 %08zx <- +%08zx %s", static_cast<size_t>(reloc),
+                   static_cast<size_t>(sym_addr), sym_name);
+        *reinterpret_cast<ElfW(Addr)*>(reloc) = sym_addr + rela->r_addend;
+        break;
+      case R_X86_64_64:
+        count_relocation(kRelocRelative);
+        MARK(rela->r_offset);
+        TRACE_TYPE(RELO, "RELO R_X86_64_64 %08zx <- +%08zx %s", static_cast<size_t>(reloc),
+                   static_cast<size_t>(sym_addr), sym_name);
+        *reinterpret_cast<ElfW(Addr)*>(reloc) = sym_addr + rela->r_addend;
+        break;
+      case R_X86_64_PC32:
+        count_relocation(kRelocRelative);
+        MARK(rela->r_offset);
+        TRACE_TYPE(RELO, "RELO R_X86_64_PC32 %08zx <- +%08zx (%08zx - %08zx) %s",
+                   static_cast<size_t>(reloc), static_cast<size_t>(sym_addr - reloc),
+                   static_cast<size_t>(sym_addr), static_cast<size_t>(reloc), sym_name);
+        *reinterpret_cast<ElfW(Addr)*>(reloc) = sym_addr + rela->r_addend - reloc;
+        break;
 #endif
 
-    default:
-      DL_ERR("unknown reloc type %d @ %p (%zu)", type, rela, idx);
-      return -1;
+      default:
+        DL_ERR("unknown reloc type %d @ %p (%zu)", type, rela, idx);
+        return -1;
     }
   }
   return 0;
 }
 
 #else // REL, not RELA.
-int soinfo::Relocate(ElfW(Rel)* rel, unsigned count) {
-    for (size_t idx = 0; idx < count; ++idx, ++rel) {
-        unsigned type = ELFW(R_TYPE)(rel->r_info);
-        // TODO: don't use unsigned for 'sym'. Use uint32_t or ElfW(Addr) instead.
-        unsigned sym = ELFW(R_SYM)(rel->r_info);
-        ElfW(Addr) reloc = static_cast<ElfW(Addr)>(rel->r_offset + load_bias);
-        ElfW(Addr) sym_addr = 0;
-        const char* sym_name = nullptr;
+int soinfo::Relocate(ElfW(Rel)* rel, unsigned count, const soinfo_list_t& global_group, const soinfo_list_t& local_group) {
+  for (size_t idx = 0; idx < count; ++idx, ++rel) {
+    unsigned type = ELFW(R_TYPE)(rel->r_info);
+    // TODO: don't use unsigned for 'sym'. Use uint32_t or ElfW(Addr) instead.
+    unsigned sym = ELFW(R_SYM)(rel->r_info);
+    ElfW(Addr) reloc = static_cast<ElfW(Addr)>(rel->r_offset + load_bias);
+    ElfW(Addr) sym_addr = 0;
+    const char* sym_name = nullptr;
 
-        DEBUG("Processing '%s' relocation at index %zd", name, idx);
-        if (type == 0) { // R_*_NONE
-            continue;
+    DEBUG("Processing '%s' relocation at index %zd", name, idx);
+    if (type == 0) { // R_*_NONE
+      continue;
+    }
+
+    ElfW(Sym)* s = nullptr;
+    soinfo* lsi = nullptr;
+
+    if (sym != 0) {
+      sym_name = get_string(symtab[sym].st_name);
+      s = soinfo_do_lookup(this, sym_name, &lsi, global_group, local_group);
+      if (s == nullptr) {
+        // We only allow an undefined symbol if this is a weak reference...
+        s = &symtab[sym];
+        if (ELF_ST_BIND(s->st_info) != STB_WEAK) {
+          DL_ERR("cannot locate symbol \"%s\" referenced by \"%s\"...", sym_name, name);
+          return -1;
         }
 
-        ElfW(Sym)* s = nullptr;
-        soinfo* lsi = nullptr;
+        /* IHI0044C AAELF 4.5.1.1:
 
-        if (sym != 0) {
-            sym_name = reinterpret_cast<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 = &symtab[sym];
-                if (ELF_ST_BIND(s->st_info) != STB_WEAK) {
-                    DL_ERR("cannot locate symbol \"%s\" referenced by \"%s\"...", sym_name, name);
-                    return -1;
-                }
+           Libraries are not searched to resolve weak references.
+           It is not an error for a weak reference to remain
+           unsatisfied.
 
-                /* IHI0044C AAELF 4.5.1.1:
-
-                   Libraries are not searched to resolve weak references.
-                   It is not an error for a weak reference to remain
-                   unsatisfied.
-
-                   During linking, the value of an undefined weak reference is:
-                   - Zero if the relocation type is absolute
-                   - The address of the place if the relocation is pc-relative
-                   - The address of nominal base address if the relocation
-                     type is base-relative.
-                  */
-
-                switch (type) {
-#if defined(__arm__)
-                case R_ARM_JUMP_SLOT:
-                case R_ARM_GLOB_DAT:
-                case R_ARM_ABS32:
-                case R_ARM_RELATIVE:    /* Don't care. */
-                    // sym_addr was initialized to be zero above or relocation
-                    // code below does not care about value of sym_addr.
-                    // No need to do anything.
-                    break;
-#elif defined(__i386__)
-                case R_386_JMP_SLOT:
-                case R_386_GLOB_DAT:
-                case R_386_32:
-                case R_386_RELATIVE:    /* Don't care. */
-                case R_386_IRELATIVE:
-                    // sym_addr was initialized to be zero above or relocation
-                    // code below does not care about value of sym_addr.
-                    // No need to do anything.
-                    break;
-                case R_386_PC32:
-                    sym_addr = reloc;
-                    break;
-#endif
-
-#if defined(__arm__)
-                case R_ARM_COPY:
-                    // Fall through. Can't really copy if weak symbol is not found at run-time.
-#endif
-                default:
-                    DL_ERR("unknown weak reloc type %d @ %p (%zu)", type, rel, idx);
-                    return -1;
-                }
-            } else {
-                // We got a definition.
-                sym_addr = lsi->resolve_symbol_address(s);
-            }
-            count_relocation(kRelocSymbol);
-        }
+           During linking, the value of an undefined weak reference is:
+           - Zero if the relocation type is absolute
+           - The address of the place if the relocation is pc-relative
+           - The address of nominal base address if the relocation
+             type is base-relative.
+        */
 
         switch (type) {
 #if defined(__arm__)
-        case R_ARM_JUMP_SLOT:
-            count_relocation(kRelocAbsolute);
-            MARK(rel->r_offset);
-            TRACE_TYPE(RELO, "RELO JMP_SLOT %08x <- %08x %s", reloc, sym_addr, sym_name);
-            *reinterpret_cast<ElfW(Addr)*>(reloc) = sym_addr;
+          case R_ARM_JUMP_SLOT:
+          case R_ARM_GLOB_DAT:
+          case R_ARM_ABS32:
+          case R_ARM_RELATIVE:    /* Don't care. */
+            // sym_addr was initialized to be zero above or relocation
+            // code below does not care about value of sym_addr.
+            // No need to do anything.
             break;
-        case R_ARM_GLOB_DAT:
-            count_relocation(kRelocAbsolute);
-            MARK(rel->r_offset);
-            TRACE_TYPE(RELO, "RELO GLOB_DAT %08x <- %08x %s", reloc, sym_addr, sym_name);
-            *reinterpret_cast<ElfW(Addr)*>(reloc) = sym_addr;
-            break;
-        case R_ARM_ABS32:
-            count_relocation(kRelocAbsolute);
-            MARK(rel->r_offset);
-            TRACE_TYPE(RELO, "RELO ABS %08x <- %08x %s", reloc, sym_addr, sym_name);
-            *reinterpret_cast<ElfW(Addr)*>(reloc) += sym_addr;
-            break;
-        case R_ARM_REL32:
-            count_relocation(kRelocRelative);
-            MARK(rel->r_offset);
-            TRACE_TYPE(RELO, "RELO REL32 %08x <- %08x - %08x %s",
-                       reloc, sym_addr, rel->r_offset, sym_name);
-            *reinterpret_cast<ElfW(Addr)*>(reloc) += sym_addr - rel->r_offset;
-            break;
-        case R_ARM_COPY:
-            /*
-             * ET_EXEC is not supported so this should not happen.
-             *
-             * http://infocenter.arm.com/help/topic/com.arm.doc.ihi0044d/IHI0044D_aaelf.pdf
-             *
-             * Section 4.7.1.10 "Dynamic relocations"
-             * R_ARM_COPY may only appear in executable objects where e_type is
-             * set to ET_EXEC.
-             */
-            DL_ERR("%s R_ARM_COPY relocations are not supported", name);
-            return -1;
 #elif defined(__i386__)
-        case R_386_JMP_SLOT:
-            count_relocation(kRelocAbsolute);
-            MARK(rel->r_offset);
-            TRACE_TYPE(RELO, "RELO JMP_SLOT %08x <- %08x %s", reloc, sym_addr, sym_name);
-            *reinterpret_cast<ElfW(Addr)*>(reloc) = sym_addr;
+          case R_386_JMP_SLOT:
+          case R_386_GLOB_DAT:
+          case R_386_32:
+          case R_386_RELATIVE:    /* Don't care. */
+          case R_386_IRELATIVE:
+            // sym_addr was initialized to be zero above or relocation
+            // code below does not care about value of sym_addr.
+            // No need to do anything.
             break;
-        case R_386_GLOB_DAT:
-            count_relocation(kRelocAbsolute);
-            MARK(rel->r_offset);
-            TRACE_TYPE(RELO, "RELO GLOB_DAT %08x <- %08x %s", reloc, sym_addr, sym_name);
-            *reinterpret_cast<ElfW(Addr)*>(reloc) = sym_addr;
-            break;
-        case R_386_32:
-            count_relocation(kRelocRelative);
-            MARK(rel->r_offset);
-            TRACE_TYPE(RELO, "RELO R_386_32 %08x <- +%08x %s", reloc, sym_addr, sym_name);
-            *reinterpret_cast<ElfW(Addr)*>(reloc) += sym_addr;
-            break;
-        case R_386_PC32:
-            count_relocation(kRelocRelative);
-            MARK(rel->r_offset);
-            TRACE_TYPE(RELO, "RELO R_386_PC32 %08x <- +%08x (%08x - %08x) %s",
-                       reloc, (sym_addr - reloc), sym_addr, reloc, sym_name);
-            *reinterpret_cast<ElfW(Addr)*>(reloc) += (sym_addr - reloc);
-            break;
-#elif defined(__mips__)
-        case R_MIPS_REL32:
-#if defined(__LP64__)
-            // MIPS Elf64_Rel entries contain compound relocations
-            // We only handle the R_MIPS_NONE|R_MIPS_64|R_MIPS_REL32 case
-            if (ELF64_R_TYPE2(rel->r_info) != R_MIPS_64 ||
-                ELF64_R_TYPE3(rel->r_info) != R_MIPS_NONE) {
-                DL_ERR("Unexpected compound relocation type:%d type2:%d type3:%d @ %p (%zu)",
-                       type, (unsigned)ELF64_R_TYPE2(rel->r_info),
-                       (unsigned)ELF64_R_TYPE3(rel->r_info), rel, idx);
-                return -1;
-            }
-#endif
-            count_relocation(kRelocAbsolute);
-            MARK(rel->r_offset);
-            TRACE_TYPE(RELO, "RELO REL32 %08zx <- %08zx %s", static_cast<size_t>(reloc),
-                       static_cast<size_t>(sym_addr), sym_name ? sym_name : "*SECTIONHDR*");
-            if (s) {
-                *reinterpret_cast<ElfW(Addr)*>(reloc) += sym_addr;
-            } else {
-                *reinterpret_cast<ElfW(Addr)*>(reloc) += base;
-            }
+          case R_386_PC32:
+            sym_addr = reloc;
             break;
 #endif
 
 #if defined(__arm__)
-        case R_ARM_RELATIVE:
-#elif defined(__i386__)
-        case R_386_RELATIVE:
+          case R_ARM_COPY:
+            // Fall through. Can't really copy if weak symbol is not found at run-time.
 #endif
-            count_relocation(kRelocRelative);
-            MARK(rel->r_offset);
-            if (sym) {
-                DL_ERR("odd RELATIVE form...");
-                return -1;
-            }
-            TRACE_TYPE(RELO, "RELO RELATIVE %p <- +%p",
-                       reinterpret_cast<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);
+          default:
+            DL_ERR("unknown weak reloc type %d @ %p (%zu)", type, rel, idx);
             return -1;
         }
+      } else {
+        // We got a definition.
+        sym_addr = lsi->resolve_symbol_address(s);
+      }
+      count_relocation(kRelocSymbol);
     }
-    return 0;
+
+    switch (type) {
+#if defined(__arm__)
+      case R_ARM_JUMP_SLOT:
+        count_relocation(kRelocAbsolute);
+        MARK(rel->r_offset);
+        TRACE_TYPE(RELO, "RELO JMP_SLOT %08x <- %08x %s", reloc, sym_addr, sym_name);
+        *reinterpret_cast<ElfW(Addr)*>(reloc) = sym_addr;
+        break;
+      case R_ARM_GLOB_DAT:
+        count_relocation(kRelocAbsolute);
+        MARK(rel->r_offset);
+        TRACE_TYPE(RELO, "RELO GLOB_DAT %08x <- %08x %s", reloc, sym_addr, sym_name);
+        *reinterpret_cast<ElfW(Addr)*>(reloc) = sym_addr;
+        break;
+      case R_ARM_ABS32:
+        count_relocation(kRelocAbsolute);
+        MARK(rel->r_offset);
+        TRACE_TYPE(RELO, "RELO ABS %08x <- %08x %s", reloc, sym_addr, sym_name);
+        *reinterpret_cast<ElfW(Addr)*>(reloc) += sym_addr;
+        break;
+      case R_ARM_REL32:
+        count_relocation(kRelocRelative);
+        MARK(rel->r_offset);
+        TRACE_TYPE(RELO, "RELO REL32 %08x <- %08x - %08x %s",
+                   reloc, sym_addr, rel->r_offset, sym_name);
+        *reinterpret_cast<ElfW(Addr)*>(reloc) += sym_addr - rel->r_offset;
+        break;
+      case R_ARM_COPY:
+        /*
+         * ET_EXEC is not supported so this should not happen.
+         *
+         * http://infocenter.arm.com/help/topic/com.arm.doc.ihi0044d/IHI0044D_aaelf.pdf
+         *
+         * Section 4.7.1.10 "Dynamic relocations"
+         * R_ARM_COPY may only appear in executable objects where e_type is
+         * set to ET_EXEC.
+         */
+        DL_ERR("%s R_ARM_COPY relocations are not supported", name);
+        return -1;
+#elif defined(__i386__)
+      case R_386_JMP_SLOT:
+        count_relocation(kRelocAbsolute);
+        MARK(rel->r_offset);
+        TRACE_TYPE(RELO, "RELO JMP_SLOT %08x <- %08x %s", reloc, sym_addr, sym_name);
+        *reinterpret_cast<ElfW(Addr)*>(reloc) = sym_addr;
+        break;
+      case R_386_GLOB_DAT:
+        count_relocation(kRelocAbsolute);
+        MARK(rel->r_offset);
+        TRACE_TYPE(RELO, "RELO GLOB_DAT %08x <- %08x %s", reloc, sym_addr, sym_name);
+        *reinterpret_cast<ElfW(Addr)*>(reloc) = sym_addr;
+        break;
+      case R_386_32:
+        count_relocation(kRelocRelative);
+        MARK(rel->r_offset);
+        TRACE_TYPE(RELO, "RELO R_386_32 %08x <- +%08x %s", reloc, sym_addr, sym_name);
+        *reinterpret_cast<ElfW(Addr)*>(reloc) += sym_addr;
+        break;
+      case R_386_PC32:
+        count_relocation(kRelocRelative);
+        MARK(rel->r_offset);
+        TRACE_TYPE(RELO, "RELO R_386_PC32 %08x <- +%08x (%08x - %08x) %s",
+                   reloc, (sym_addr - reloc), sym_addr, reloc, sym_name);
+        *reinterpret_cast<ElfW(Addr)*>(reloc) += (sym_addr - reloc);
+        break;
+#elif defined(__mips__)
+      case R_MIPS_REL32:
+#if defined(__LP64__)
+        // MIPS Elf64_Rel entries contain compound relocations
+        // We only handle the R_MIPS_NONE|R_MIPS_64|R_MIPS_REL32 case
+        if (ELF64_R_TYPE2(rel->r_info) != R_MIPS_64 ||
+            ELF64_R_TYPE3(rel->r_info) != R_MIPS_NONE) {
+          DL_ERR("Unexpected compound relocation type:%d type2:%d type3:%d @ %p (%zu)",
+                 type, (unsigned)ELF64_R_TYPE2(rel->r_info),
+                 (unsigned)ELF64_R_TYPE3(rel->r_info), rel, idx);
+          return -1;
+        }
+#endif
+        count_relocation(kRelocAbsolute);
+        MARK(rel->r_offset);
+        TRACE_TYPE(RELO, "RELO REL32 %08zx <- %08zx %s", static_cast<size_t>(reloc),
+                   static_cast<size_t>(sym_addr), sym_name ? sym_name : "*SECTIONHDR*");
+        if (s) {
+          *reinterpret_cast<ElfW(Addr)*>(reloc) += sym_addr;
+        } else {
+          *reinterpret_cast<ElfW(Addr)*>(reloc) += base;
+        }
+        break;
+#endif
+
+#if defined(__arm__)
+      case R_ARM_RELATIVE:
+#elif defined(__i386__)
+      case R_386_RELATIVE:
+#endif
+        count_relocation(kRelocRelative);
+        MARK(rel->r_offset);
+        if (sym) {
+          DL_ERR("odd RELATIVE form...");
+          return -1;
+        }
+        TRACE_TYPE(RELO, "RELO RELATIVE %p <- +%p",
+                   reinterpret_cast<void*>(reloc), reinterpret_cast<void*>(base));
+        *reinterpret_cast<ElfW(Addr)*>(reloc) += base;
+        break;
+#if defined(__i386__)
+      case R_386_IRELATIVE:
+        count_relocation(kRelocRelative);
+        MARK(rel->r_offset);
+        TRACE_TYPE(RELO, "RELO IRELATIVE %p <- %p", reinterpret_cast<void*>(reloc), reinterpret_cast<void*>(base));
+        *reinterpret_cast<ElfW(Addr)*>(reloc) = call_ifunc_resolver(base + *reinterpret_cast<ElfW(Addr)*>(reloc));
+        break;
+#endif
+
+      default:
+        DL_ERR("unknown reloc type %d @ %p (%zu)", type, rel, idx);
+        return -1;
+    }
+  }
+  return 0;
 }
 #endif
 
 #if defined(__mips__)
-static bool mips_relocate_got(soinfo* si) {
-    ElfW(Addr)** got = si->plt_got;
-    if (got == nullptr) {
-        return true;
-    }
-    unsigned local_gotno = si->mips_local_gotno;
-    unsigned gotsym = si->mips_gotsym;
-    unsigned symtabno = si->mips_symtabno;
-    ElfW(Sym)* symtab = si->symtab;
-
-    // got[0] is the address of the lazy resolver function.
-    // got[1] may be used for a GNU extension.
-    // Set it to a recognizable address in case someone calls it (should be _rtld_bind_start).
-    // FIXME: maybe this should be in a separate routine?
-    if ((si->flags & FLAG_LINKER) == 0) {
-        size_t g = 0;
-        got[g++] = reinterpret_cast<ElfW(Addr)*>(0xdeadbeef);
-        if (reinterpret_cast<intptr_t>(got[g]) < 0) {
-            got[g++] = reinterpret_cast<ElfW(Addr)*>(0xdeadfeed);
-        }
-        // Relocate the local GOT entries.
-        for (; g < local_gotno; g++) {
-            got[g] = reinterpret_cast<ElfW(Addr)*>(reinterpret_cast<uintptr_t>(got[g]) + si->load_bias);
-        }
-    }
-
-    // Now for the global GOT entries...
-    ElfW(Sym)* sym = symtab + gotsym;
-    got = si->plt_got + local_gotno;
-    for (size_t g = gotsym; g < symtabno; g++, sym++, got++) {
-        // This is an undefined reference... try to locate it.
-        const char* sym_name = si->strtab + sym->st_name;
-        soinfo* lsi = nullptr;
-        ElfW(Sym)* s = soinfo_do_lookup(si, sym_name, &lsi);
-        if (s == nullptr) {
-            // We only allow an undefined symbol if this is a weak reference.
-            s = &symtab[g];
-            if (ELF_ST_BIND(s->st_info) != STB_WEAK) {
-                DL_ERR("cannot locate \"%s\"...", sym_name);
-                return false;
-            }
-            *got = 0;
-        } else {
-            // FIXME: is this sufficient?
-            // For reference see NetBSD link loader
-            // http://cvsweb.netbsd.org/bsdweb.cgi/src/libexec/ld.elf_so/arch/mips/mips_reloc.c?rev=1.53&content-type=text/x-cvsweb-markup
-            *got = reinterpret_cast<ElfW(Addr)*>(lsi->resolve_symbol_address(s));
-        }
-    }
+static bool mips_relocate_got(soinfo* si, const soinfo::soinfo_list_t& global_group, const soinfo::soinfo_list_t& local_group) {
+  ElfW(Addr)** got = si->plt_got;
+  if (got == nullptr) {
     return true;
+  }
+  unsigned local_gotno = si->mips_local_gotno;
+  unsigned gotsym = si->mips_gotsym;
+  unsigned symtabno = si->mips_symtabno;
+  ElfW(Sym)* symtab = si->symtab;
+
+  // got[0] is the address of the lazy resolver function.
+  // got[1] may be used for a GNU extension.
+  // Set it to a recognizable address in case someone calls it (should be _rtld_bind_start).
+  // FIXME: maybe this should be in a separate routine?
+  if ((si->flags & FLAG_LINKER) == 0) {
+    size_t g = 0;
+    got[g++] = reinterpret_cast<ElfW(Addr)*>(0xdeadbeef);
+    if (reinterpret_cast<intptr_t>(got[g]) < 0) {
+      got[g++] = reinterpret_cast<ElfW(Addr)*>(0xdeadfeed);
+    }
+    // Relocate the local GOT entries.
+    for (; g < local_gotno; g++) {
+      got[g] = reinterpret_cast<ElfW(Addr)*>(reinterpret_cast<uintptr_t>(got[g]) + si->load_bias);
+    }
+  }
+
+  // Now for the global GOT entries...
+  ElfW(Sym)* sym = symtab + gotsym;
+  got = si->plt_got + local_gotno;
+  for (size_t g = gotsym; g < symtabno; g++, sym++, got++) {
+    // This is an undefined reference... try to locate it.
+    const char* sym_name = si->get_string(sym->st_name);
+    soinfo* lsi = nullptr;
+    ElfW(Sym)* s = soinfo_do_lookup(si, sym_name, &lsi, global_group, local_group);
+    if (s == nullptr) {
+      // We only allow an undefined symbol if this is a weak reference.
+      s = &symtab[g];
+      if (ELF_ST_BIND(s->st_info) != STB_WEAK) {
+        DL_ERR("cannot locate \"%s\"...", sym_name);
+        return false;
+      }
+      *got = 0;
+    } else {
+      // FIXME: is this sufficient?
+      // For reference see NetBSD link loader
+      // http://cvsweb.netbsd.org/bsdweb.cgi/src/libexec/ld.elf_so/arch/mips/mips_reloc.c?rev=1.53&content-type=text/x-cvsweb-markup
+      *got = reinterpret_cast<ElfW(Addr)*>(lsi->resolve_symbol_address(s));
+    }
+  }
+  return true;
 }
 #endif
 
@@ -1770,7 +1801,7 @@
   children.clear();
 }
 
-dev_t soinfo::get_st_dev() {
+dev_t soinfo::get_st_dev() const {
   if (has_min_version(0)) {
     return st_dev;
   }
@@ -1778,7 +1809,7 @@
   return 0;
 };
 
-ino_t soinfo::get_st_ino() {
+ino_t soinfo::get_st_ino() const {
   if (has_min_version(0)) {
     return st_ino;
   }
@@ -1786,7 +1817,7 @@
   return 0;
 }
 
-off64_t soinfo::get_file_offset() {
+off64_t soinfo::get_file_offset() const {
   if (has_min_version(1)) {
     return file_offset;
   }
@@ -1794,6 +1825,35 @@
   return 0;
 }
 
+uint32_t soinfo::get_rtld_flags() const {
+  if (has_min_version(1)) {
+    return rtld_flags;
+  }
+
+  return 0;
+}
+
+uint32_t soinfo::get_dt_flags_1() const {
+  if (has_min_version(1)) {
+    return dt_flags_1;
+  }
+
+  return 0;
+}
+void soinfo::set_dt_flags_1(uint32_t dt_flags_1) {
+  if (has_min_version(1)) {
+    if ((dt_flags_1 & DF_1_GLOBAL) != 0) {
+      rtld_flags |= RTLD_GLOBAL;
+    }
+
+    if ((dt_flags_1 & DF_1_NODELETE) != 0) {
+      rtld_flags |= RTLD_NODELETE;
+    }
+
+    this->dt_flags_1 = dt_flags_1;
+  }
+}
+
 // This is a return on get_children()/get_parents() if
 // 'this->flags' does not have FLAG_NEW_SOINFO set.
 static soinfo::soinfo_list_t g_empty_list;
@@ -1822,65 +1882,77 @@
   return static_cast<ElfW(Addr)>(s->st_value + load_bias);
 }
 
+const char* soinfo::get_string(ElfW(Word) index) const {
+  if (has_min_version(1) && (index >= strtab_size)) {
+    __libc_fatal("%s: strtab out of bounds error; STRSZ=%zd, name=%d", name, strtab_size, index);
+  }
+
+  return strtab + index;
+}
+
+bool soinfo::can_unload() const {
+  return (get_rtld_flags() & (RTLD_NODELETE | RTLD_GLOBAL)) == 0;
+}
+
 /* Force any of the closed stdin, stdout and stderr to be associated with
    /dev/null. */
 static int nullify_closed_stdio() {
-    int dev_null, i, status;
-    int return_value = 0;
+  int dev_null, i, status;
+  int return_value = 0;
 
-    dev_null = TEMP_FAILURE_RETRY(open("/dev/null", O_RDWR));
-    if (dev_null < 0) {
-        DL_ERR("cannot open /dev/null: %s", strerror(errno));
-        return -1;
-    }
-    TRACE("[ Opened /dev/null file-descriptor=%d]", dev_null);
+  dev_null = TEMP_FAILURE_RETRY(open("/dev/null", O_RDWR));
+  if (dev_null < 0) {
+    DL_ERR("cannot open /dev/null: %s", strerror(errno));
+    return -1;
+  }
+  TRACE("[ Opened /dev/null file-descriptor=%d]", dev_null);
 
-    /* If any of the stdio file descriptors is valid and not associated
-       with /dev/null, dup /dev/null to it.  */
-    for (i = 0; i < 3; i++) {
-        /* If it is /dev/null already, we are done. */
-        if (i == dev_null) {
-            continue;
-        }
-
-        TRACE("[ Nullifying stdio file descriptor %d]", i);
-        status = TEMP_FAILURE_RETRY(fcntl(i, F_GETFL));
-
-        /* If file is opened, we are good. */
-        if (status != -1) {
-            continue;
-        }
-
-        /* The only error we allow is that the file descriptor does not
-           exist, in which case we dup /dev/null to it. */
-        if (errno != EBADF) {
-            DL_ERR("fcntl failed: %s", strerror(errno));
-            return_value = -1;
-            continue;
-        }
-
-        /* Try dupping /dev/null to this stdio file descriptor and
-           repeat if there is a signal.  Note that any errors in closing
-           the stdio descriptor are lost.  */
-        status = TEMP_FAILURE_RETRY(dup2(dev_null, i));
-        if (status < 0) {
-            DL_ERR("dup2 failed: %s", strerror(errno));
-            return_value = -1;
-            continue;
-        }
+  /* If any of the stdio file descriptors is valid and not associated
+     with /dev/null, dup /dev/null to it.  */
+  for (i = 0; i < 3; i++) {
+    /* If it is /dev/null already, we are done. */
+    if (i == dev_null) {
+      continue;
     }
 
-    /* If /dev/null is not one of the stdio file descriptors, close it. */
-    if (dev_null > 2) {
-        TRACE("[ Closing /dev/null file-descriptor=%d]", dev_null);
-        status = TEMP_FAILURE_RETRY(close(dev_null));
-        if (status == -1) {
-            DL_ERR("close failed: %s", strerror(errno));
-            return_value = -1;
-        }
+    TRACE("[ Nullifying stdio file descriptor %d]", i);
+    status = TEMP_FAILURE_RETRY(fcntl(i, F_GETFL));
+
+    /* If file is opened, we are good. */
+    if (status != -1) {
+      continue;
     }
 
-    return return_value;
+    /* The only error we allow is that the file descriptor does not
+       exist, in which case we dup /dev/null to it. */
+    if (errno != EBADF) {
+      DL_ERR("fcntl failed: %s", strerror(errno));
+      return_value = -1;
+      continue;
+    }
+
+    /* Try dupping /dev/null to this stdio file descriptor and
+       repeat if there is a signal.  Note that any errors in closing
+       the stdio descriptor are lost.  */
+    status = TEMP_FAILURE_RETRY(dup2(dev_null, i));
+    if (status < 0) {
+      DL_ERR("dup2 failed: %s", strerror(errno));
+      return_value = -1;
+      continue;
+    }
+  }
+
+  /* If /dev/null is not one of the stdio file descriptors, close it. */
+  if (dev_null > 2) {
+    TRACE("[ Closing /dev/null file-descriptor=%d]", dev_null);
+    status = TEMP_FAILURE_RETRY(close(dev_null));
+    if (status == -1) {
+      DL_ERR("close failed: %s", strerror(errno));
+      return_value = -1;
+    }
+  }
+
+  return return_value;
 }
 
 bool soinfo::PrelinkImage() {
@@ -1888,318 +1960,404 @@
   ElfW(Word) dynamic_flags = 0;
   phdr_table_get_dynamic_section(phdr, phnum, load_bias, &dynamic, &dynamic_flags);
 
-    /* We can't log anything until the linker is relocated */
-    bool relocating_linker = (flags & FLAG_LINKER) != 0;
-    if (!relocating_linker) {
-        INFO("[ linking %s ]", name);
-        DEBUG("si->base = %p si->flags = 0x%08x", reinterpret_cast<void*>(base), flags);
-    }
+  /* We can't log anything until the linker is relocated */
+  bool relocating_linker = (flags & FLAG_LINKER) != 0;
+  if (!relocating_linker) {
+    INFO("[ linking %s ]", name);
+    DEBUG("si->base = %p si->flags = 0x%08x", reinterpret_cast<void*>(base), flags);
+  }
 
-    if (dynamic == nullptr) {
-        if (!relocating_linker) {
-            DL_ERR("missing PT_DYNAMIC in \"%s\"", name);
-        }
-        return false;
-    } else {
-        if (!relocating_linker) {
-            DEBUG("dynamic = %p", dynamic);
-        }
+  if (dynamic == nullptr) {
+    if (!relocating_linker) {
+      DL_ERR("missing PT_DYNAMIC in \"%s\"", name);
     }
+    return false;
+  } else {
+    if (!relocating_linker) {
+      DEBUG("dynamic = %p", dynamic);
+    }
+  }
 
 #if defined(__arm__)
-    (void) phdr_table_get_arm_exidx(phdr, phnum, load_bias,
-                                    &ARM_exidx, &ARM_exidx_count);
+  (void) phdr_table_get_arm_exidx(phdr, phnum, load_bias,
+                                  &ARM_exidx, &ARM_exidx_count);
 #endif
 
-    // Extract useful information from dynamic section.
-    uint32_t needed_count = 0;
-    for (ElfW(Dyn)* d = dynamic; d->d_tag != DT_NULL; ++d) {
-        DEBUG("d = %p, d[0](tag) = %p d[1](val) = %p",
-              d, reinterpret_cast<void*>(d->d_tag), reinterpret_cast<void*>(d->d_un.d_val));
-        switch (d->d_tag) {
-        case DT_HASH:
-            nbucket = reinterpret_cast<uint32_t*>(load_bias + d->d_un.d_ptr)[0];
-            nchain = reinterpret_cast<uint32_t*>(load_bias + d->d_un.d_ptr)[1];
-            bucket = reinterpret_cast<uint32_t*>(load_bias + d->d_un.d_ptr + 8);
-            chain = reinterpret_cast<uint32_t*>(load_bias + d->d_un.d_ptr + 8 + nbucket * 4);
-            break;
-        case DT_STRTAB:
-            strtab = reinterpret_cast<const char*>(load_bias + d->d_un.d_ptr);
-            break;
-        case DT_SYMTAB:
-            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\"", name);
-                return false;
-            }
-            break;
-#endif
-        case DT_JMPREL:
+  // Extract useful information from dynamic section.
+  uint32_t needed_count = 0;
+  for (ElfW(Dyn)* d = dynamic; d->d_tag != DT_NULL; ++d) {
+    DEBUG("d = %p, d[0](tag) = %p d[1](val) = %p",
+          d, reinterpret_cast<void*>(d->d_tag), reinterpret_cast<void*>(d->d_un.d_val));
+    switch (d->d_tag) {
+      case DT_SONAME:
+        // TODO: glibc dynamic linker uses this name for
+        // initial library lookup; consider doing the same here.
+        break;
+
+      case DT_HASH:
+        nbucket = reinterpret_cast<uint32_t*>(load_bias + d->d_un.d_ptr)[0];
+        nchain = reinterpret_cast<uint32_t*>(load_bias + d->d_un.d_ptr)[1];
+        bucket = reinterpret_cast<uint32_t*>(load_bias + d->d_un.d_ptr + 8);
+        chain = reinterpret_cast<uint32_t*>(load_bias + d->d_un.d_ptr + 8 + nbucket * 4);
+        break;
+
+      case DT_STRTAB:
+        strtab = reinterpret_cast<const char*>(load_bias + d->d_un.d_ptr);
+        break;
+
+      case DT_STRSZ:
+        strtab_size = d->d_un.d_val;
+        break;
+
+      case DT_SYMTAB:
+        symtab = reinterpret_cast<ElfW(Sym)*>(load_bias + d->d_un.d_ptr);
+        break;
+
+      case DT_SYMENT:
+        if (d->d_un.d_val != sizeof(ElfW(Sym))) {
+          DL_ERR("invalid DT_SYMENT: %zd", static_cast<size_t>(d->d_un.d_val));
+          return false;
+        }
+        break;
+
+      case DT_PLTREL:
 #if defined(USE_RELA)
-            plt_rela = reinterpret_cast<ElfW(Rela)*>(load_bias + d->d_un.d_ptr);
+        if (d->d_un.d_val != DT_RELA) {
+          DL_ERR("unsupported DT_PLTREL in \"%s\"; expected DT_RELA", name);
+          return false;
+        }
 #else
-            plt_rel = reinterpret_cast<ElfW(Rel)*>(load_bias + d->d_un.d_ptr);
+        if (d->d_un.d_val != DT_REL) {
+          DL_ERR("unsupported DT_PLTREL in \"%s\"; expected DT_REL", name);
+          return false;
+        }
 #endif
-            break;
-        case DT_PLTRELSZ:
+        break;
+
+      case DT_JMPREL:
 #if defined(USE_RELA)
-            plt_rela_count = d->d_un.d_val / sizeof(ElfW(Rela));
+        plt_rela = reinterpret_cast<ElfW(Rela)*>(load_bias + d->d_un.d_ptr);
 #else
-            plt_rel_count = d->d_un.d_val / sizeof(ElfW(Rel));
+        plt_rel = reinterpret_cast<ElfW(Rel)*>(load_bias + d->d_un.d_ptr);
 #endif
-            break;
+        break;
+
+      case DT_PLTRELSZ:
+#if defined(USE_RELA)
+        plt_rela_count = d->d_un.d_val / sizeof(ElfW(Rela));
+#else
+        plt_rel_count = d->d_un.d_val / sizeof(ElfW(Rel));
+#endif
+        break;
+
+      case DT_PLTGOT:
 #if defined(__mips__)
-        case DT_PLTGOT:
-            // Used by mips and mips64.
-            plt_got = reinterpret_cast<ElfW(Addr)**>(load_bias + d->d_un.d_ptr);
-            break;
+        // Used by mips and mips64.
+        plt_got = reinterpret_cast<ElfW(Addr)**>(load_bias + d->d_un.d_ptr);
 #endif
-        case DT_DEBUG:
-            // Set the DT_DEBUG entry to the address of _r_debug for GDB
-            // if the dynamic table is writable
+        // Ignore for other platforms... (because RTLD_LAZY is not supported)
+        break;
+
+      case DT_DEBUG:
+        // Set the DT_DEBUG entry to the address of _r_debug for GDB
+        // if the dynamic table is writable
 // FIXME: not working currently for N64
 // The flags for the LOAD and DYNAMIC program headers do not agree.
 // The LOAD section containing the dynamic table has been mapped as
 // read-only, but the DYNAMIC header claims it is writable.
 #if !(defined(__mips__) && defined(__LP64__))
-            if ((dynamic_flags & PF_W) != 0) {
-                d->d_un.d_val = reinterpret_cast<uintptr_t>(&_r_debug);
-            }
-            break;
+        if ((dynamic_flags & PF_W) != 0) {
+          d->d_un.d_val = reinterpret_cast<uintptr_t>(&_r_debug);
+        }
+        break;
 #endif
 #if defined(USE_RELA)
-         case DT_RELA:
-            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_REL:
-            DL_ERR("unsupported DT_REL in \"%s\"", name);
-            return false;
-        case DT_RELSZ:
-            DL_ERR("unsupported DT_RELSZ in \"%s\"", name);
-            return false;
-#else
-        case DT_REL:
-            rel = reinterpret_cast<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_RELA:
-            DL_ERR("unsupported DT_RELA in \"%s\"", name);
-            return false;
-#endif
-        case DT_INIT:
-            init_func = reinterpret_cast<linker_function_t>(load_bias + d->d_un.d_ptr);
-            DEBUG("%s constructors (DT_INIT) found at %p", name, init_func);
-            break;
-        case DT_FINI:
-            fini_func = reinterpret_cast<linker_function_t>(load_bias + d->d_un.d_ptr);
-            DEBUG("%s destructors (DT_FINI) found at %p", name, fini_func);
-            break;
-        case DT_INIT_ARRAY:
-            init_array = reinterpret_cast<linker_function_t*>(load_bias + d->d_un.d_ptr);
-            DEBUG("%s constructors (DT_INIT_ARRAY) found at %p", name, init_array);
-            break;
-        case DT_INIT_ARRAYSZ:
-            init_array_count = ((unsigned)d->d_un.d_val) / sizeof(ElfW(Addr));
-            break;
-        case DT_FINI_ARRAY:
-            fini_array = reinterpret_cast<linker_function_t*>(load_bias + d->d_un.d_ptr);
-            DEBUG("%s destructors (DT_FINI_ARRAY) found at %p", name, fini_array);
-            break;
-        case DT_FINI_ARRAYSZ:
-            fini_array_count = ((unsigned)d->d_un.d_val) / sizeof(ElfW(Addr));
-            break;
-        case DT_PREINIT_ARRAY:
-            preinit_array = reinterpret_cast<linker_function_t*>(load_bias + d->d_un.d_ptr);
-            DEBUG("%s constructors (DT_PREINIT_ARRAY) found at %p", name, preinit_array);
-            break;
-        case DT_PREINIT_ARRAYSZ:
-            preinit_array_count = ((unsigned)d->d_un.d_val) / sizeof(ElfW(Addr));
-            break;
-        case DT_TEXTREL:
-#if defined(__LP64__)
-            DL_ERR("text relocations (DT_TEXTREL) found in 64-bit ELF file \"%s\"", name);
-            return false;
-#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) {
-#if defined(__LP64__)
-                DL_ERR("text relocations (DF_TEXTREL) found in 64-bit ELF file \"%s\"", name);
-                return false;
-#else
-                has_text_relocations = true;
-#endif
-            }
-            if (d->d_un.d_val & DF_SYMBOLIC) {
-                has_DT_SYMBOLIC = true;
-            }
-            break;
-#if defined(__mips__)
-        case DT_STRSZ:
-        case DT_SYMENT:
-        case DT_RELENT:
-             break;
-        case DT_MIPS_RLD_MAP:
-            // Set the DT_MIPS_RLD_MAP entry to the address of _r_debug for GDB.
-            {
-              r_debug** dp = reinterpret_cast<r_debug**>(load_bias + d->d_un.d_ptr);
-              *dp = &_r_debug;
-            }
-            break;
-        case DT_MIPS_RLD_VERSION:
-        case DT_MIPS_FLAGS:
-        case DT_MIPS_BASE_ADDRESS:
-        case DT_MIPS_UNREFEXTNO:
-            break;
+      case DT_RELA:
+        rela = reinterpret_cast<ElfW(Rela)*>(load_bias + d->d_un.d_ptr);
+        break;
 
-        case DT_MIPS_SYMTABNO:
-            mips_symtabno = d->d_un.d_val;
-            break;
+      case DT_RELASZ:
+        rela_count = d->d_un.d_val / sizeof(ElfW(Rela));
+        break;
 
-        case DT_MIPS_LOCAL_GOTNO:
-            mips_local_gotno = d->d_un.d_val;
-            break;
-
-        case DT_MIPS_GOTSYM:
-            mips_gotsym = d->d_un.d_val;
-            break;
-#endif
-
-        default:
-            DEBUG("Unused DT entry: type %p arg %p",
-                  reinterpret_cast<void*>(d->d_tag), reinterpret_cast<void*>(d->d_un.d_val));
-            break;
+      case DT_RELAENT:
+        if (d->d_un.d_val != sizeof(ElfW(Rela))) {
+          DL_ERR("invalid DT_RELAENT: %zd", static_cast<size_t>(d->d_un.d_val));
+          return false;
         }
-    }
+        break;
 
-    DEBUG("si->base = %p, si->strtab = %p, si->symtab = %p",
-          reinterpret_cast<void*>(base), strtab, symtab);
+      // ignored (see DT_RELCOUNT comments for details)
+      case DT_RELACOUNT:
+        break;
 
-    // Sanity checks.
-    if (relocating_linker && needed_count != 0) {
-        DL_ERR("linker cannot have DT_NEEDED dependencies on other libraries");
+      case DT_REL:
+        DL_ERR("unsupported DT_REL in \"%s\"", name);
         return false;
-    }
-    if (nbucket == 0) {
-        DL_ERR("empty/missing DT_HASH in \"%s\" (built with --hash-style=gnu?)", name);
+
+      case DT_RELSZ:
+        DL_ERR("unsupported DT_RELSZ in \"%s\"", name);
         return false;
-    }
-    if (strtab == 0) {
-        DL_ERR("empty/missing DT_STRTAB in \"%s\"", name);
+#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));
+          return false;
+        }
+        break;
+
+      // "Indicates that all RELATIVE relocations have been concatenated together,
+      // and specifies the RELATIVE relocation count."
+      //
+      // TODO: Spec also mentions that this can be used to optimize relocation process;
+      // Not currently used by bionic linker - ignored.
+      case DT_RELCOUNT:
+        break;
+      case DT_RELA:
+        DL_ERR("unsupported DT_RELA in \"%s\"", name);
         return false;
-    }
-    if (symtab == 0) {
-        DL_ERR("empty/missing DT_SYMTAB in \"%s\"", name);
+#endif
+      case DT_INIT:
+        init_func = reinterpret_cast<linker_function_t>(load_bias + d->d_un.d_ptr);
+        DEBUG("%s constructors (DT_INIT) found at %p", name, init_func);
+        break;
+
+      case DT_FINI:
+        fini_func = reinterpret_cast<linker_function_t>(load_bias + d->d_un.d_ptr);
+        DEBUG("%s destructors (DT_FINI) found at %p", name, fini_func);
+        break;
+
+      case DT_INIT_ARRAY:
+        init_array = reinterpret_cast<linker_function_t*>(load_bias + d->d_un.d_ptr);
+        DEBUG("%s constructors (DT_INIT_ARRAY) found at %p", name, init_array);
+        break;
+
+      case DT_INIT_ARRAYSZ:
+        init_array_count = ((unsigned)d->d_un.d_val) / sizeof(ElfW(Addr));
+        break;
+
+      case DT_FINI_ARRAY:
+        fini_array = reinterpret_cast<linker_function_t*>(load_bias + d->d_un.d_ptr);
+        DEBUG("%s destructors (DT_FINI_ARRAY) found at %p", name, fini_array);
+        break;
+
+      case DT_FINI_ARRAYSZ:
+        fini_array_count = ((unsigned)d->d_un.d_val) / sizeof(ElfW(Addr));
+        break;
+
+      case DT_PREINIT_ARRAY:
+        preinit_array = reinterpret_cast<linker_function_t*>(load_bias + d->d_un.d_ptr);
+        DEBUG("%s constructors (DT_PREINIT_ARRAY) found at %p", name, preinit_array);
+        break;
+
+      case DT_PREINIT_ARRAYSZ:
+        preinit_array_count = ((unsigned)d->d_un.d_val) / sizeof(ElfW(Addr));
+        break;
+
+      case DT_TEXTREL:
+#if defined(__LP64__)
+        DL_ERR("text relocations (DT_TEXTREL) found in 64-bit ELF file \"%s\"", name);
         return false;
+#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) {
+#if defined(__LP64__)
+          DL_ERR("text relocations (DF_TEXTREL) found in 64-bit ELF file \"%s\"", name);
+          return false;
+#else
+          has_text_relocations = true;
+#endif
+        }
+        if (d->d_un.d_val & DF_SYMBOLIC) {
+          has_DT_SYMBOLIC = true;
+        }
+        break;
+
+      case DT_FLAGS_1:
+        set_dt_flags_1(d->d_un.d_val);
+
+        if ((d->d_un.d_val & ~SUPPORTED_DT_FLAGS_1) != 0) {
+          DL_WARN("Unsupported flags DT_FLAGS_1=%p", reinterpret_cast<void*>(d->d_un.d_val));
+        }
+        break;
+#if defined(__mips__)
+      case DT_MIPS_RLD_MAP:
+        // Set the DT_MIPS_RLD_MAP entry to the address of _r_debug for GDB.
+        {
+          r_debug** dp = reinterpret_cast<r_debug**>(load_bias + d->d_un.d_ptr);
+          *dp = &_r_debug;
+        }
+        break;
+
+      case DT_MIPS_RLD_VERSION:
+      case DT_MIPS_FLAGS:
+      case DT_MIPS_BASE_ADDRESS:
+      case DT_MIPS_UNREFEXTNO:
+        break;
+
+      case DT_MIPS_SYMTABNO:
+        mips_symtabno = d->d_un.d_val;
+        break;
+
+      case DT_MIPS_LOCAL_GOTNO:
+        mips_local_gotno = d->d_un.d_val;
+        break;
+
+      case DT_MIPS_GOTSYM:
+        mips_gotsym = d->d_un.d_val;
+        break;
+#endif
+      // Ignored: "Its use has been superseded by the DF_BIND_NOW flag"
+      case DT_BIND_NOW:
+        break;
+
+      // Ignore: bionic does not support symbol versioning...
+      case DT_VERSYM:
+      case DT_VERDEF:
+      case DT_VERDEFNUM:
+        break;
+
+      default:
+        if (!relocating_linker) {
+          DL_WARN("%s: unused DT entry: type %p arg %p", name,
+              reinterpret_cast<void*>(d->d_tag), reinterpret_cast<void*>(d->d_un.d_val));
+        }
+        break;
     }
-    return true;
+  }
+
+  DEBUG("si->base = %p, si->strtab = %p, si->symtab = %p",
+        reinterpret_cast<void*>(base), strtab, symtab);
+
+  // Sanity checks.
+  if (relocating_linker && needed_count != 0) {
+    DL_ERR("linker cannot have DT_NEEDED dependencies on other libraries");
+    return false;
+  }
+  if (nbucket == 0) {
+    DL_ERR("empty/missing DT_HASH in \"%s\" (built with --hash-style=gnu?)", name);
+    return false;
+  }
+  if (strtab == 0) {
+    DL_ERR("empty/missing DT_STRTAB in \"%s\"", name);
+    return false;
+  }
+  if (symtab == 0) {
+    DL_ERR("empty/missing DT_SYMTAB in \"%s\"", name);
+    return false;
+  }
+  return true;
 }
 
-bool soinfo::LinkImage(const android_dlextinfo* extinfo) {
+bool soinfo::LinkImage(const soinfo_list_t& global_group, const soinfo_list_t& local_group, const android_dlextinfo* extinfo) {
 
 #if !defined(__LP64__)
-    if (has_text_relocations) {
-        // Make segments writable to allow text relocations to work properly. We will later call
-        // phdr_table_protect_segments() after all of them are applied and all constructors are run.
-        DL_WARN("%s has text relocations. This is wasting memory and prevents "
-                "security hardening. Please fix.", name);
-        if (phdr_table_unprotect_segments(phdr, phnum, load_bias) < 0) {
-            DL_ERR("can't unprotect loadable segments for \"%s\": %s",
-                   name, strerror(errno));
-            return false;
-        }
+  if (has_text_relocations) {
+    // Make segments writable to allow text relocations to work properly. We will later call
+    // phdr_table_protect_segments() after all of them are applied and all constructors are run.
+    DL_WARN("%s has text relocations. This is wasting memory and prevents "
+            "security hardening. Please fix.", name);
+    if (phdr_table_unprotect_segments(phdr, phnum, load_bias) < 0) {
+      DL_ERR("can't unprotect loadable segments for \"%s\": %s",
+             name, strerror(errno));
+      return false;
     }
+  }
 #endif
 
 #if defined(USE_RELA)
-    if (rela != nullptr) {
-        DEBUG("[ relocating %s ]", name);
-        if (Relocate(rela, rela_count)) {
-            return false;
-        }
+  if (rela != nullptr) {
+    DEBUG("[ relocating %s ]", name);
+    if (Relocate(rela, rela_count, global_group, local_group)) {
+      return false;
     }
-    if (plt_rela != nullptr) {
-        DEBUG("[ relocating %s plt ]", name);
-        if (Relocate(plt_rela, plt_rela_count)) {
-            return false;
-        }
+  }
+  if (plt_rela != nullptr) {
+    DEBUG("[ relocating %s plt ]", name);
+    if (Relocate(plt_rela, plt_rela_count, global_group, local_group)) {
+      return false;
     }
+  }
 #else
-    if (rel != nullptr) {
-        DEBUG("[ relocating %s ]", name);
-        if (Relocate(rel, rel_count)) {
-            return false;
-        }
+  if (rel != nullptr) {
+    DEBUG("[ relocating %s ]", name);
+    if (Relocate(rel, rel_count, global_group, local_group)) {
+      return false;
     }
-    if (plt_rel != nullptr) {
-        DEBUG("[ relocating %s plt ]", name);
-        if (Relocate(plt_rel, plt_rel_count)) {
-            return false;
-        }
+  }
+  if (plt_rel != nullptr) {
+    DEBUG("[ relocating %s plt ]", name);
+    if (Relocate(plt_rel, plt_rel_count, global_group, local_group)) {
+      return false;
     }
+  }
 #endif
 
 #if defined(__mips__)
-    if (!mips_relocate_got(this)) {
-        return false;
-    }
+  if (!mips_relocate_got(this, global_group, local_group)) {
+    return false;
+  }
 #endif
 
-    DEBUG("[ finished linking %s ]", name);
+  DEBUG("[ finished linking %s ]", name);
 
 #if !defined(__LP64__)
-    if (has_text_relocations) {
-        // All relocations are done, we can protect our segments back to read-only.
-        if (phdr_table_protect_segments(phdr, phnum, load_bias) < 0) {
-            DL_ERR("can't protect segments for \"%s\": %s",
-                   name, strerror(errno));
-            return false;
-        }
+  if (has_text_relocations) {
+    // All relocations are done, we can protect our segments back to read-only.
+    if (phdr_table_protect_segments(phdr, phnum, load_bias) < 0) {
+      DL_ERR("can't protect segments for \"%s\": %s",
+             name, strerror(errno));
+      return false;
     }
+  }
 #endif
 
-    /* We can also turn on GNU RELRO protection */
-    if (phdr_table_protect_gnu_relro(phdr, phnum, load_bias) < 0) {
-        DL_ERR("can't enable GNU RELRO protection for \"%s\": %s",
-               name, strerror(errno));
-        return false;
-    }
+  /* We can also turn on GNU RELRO protection */
+  if (phdr_table_protect_gnu_relro(phdr, phnum, load_bias) < 0) {
+    DL_ERR("can't enable GNU RELRO protection for \"%s\": %s",
+           name, strerror(errno));
+    return false;
+  }
 
-    /* Handle serializing/sharing the RELRO segment */
-    if (extinfo && (extinfo->flags & ANDROID_DLEXT_WRITE_RELRO)) {
-      if (phdr_table_serialize_gnu_relro(phdr, phnum, load_bias,
-                                         extinfo->relro_fd) < 0) {
-        DL_ERR("failed serializing GNU RELRO section for \"%s\": %s",
-               name, strerror(errno));
-        return false;
-      }
-    } else if (extinfo && (extinfo->flags & ANDROID_DLEXT_USE_RELRO)) {
-      if (phdr_table_map_gnu_relro(phdr, phnum, load_bias,
-                                   extinfo->relro_fd) < 0) {
-        DL_ERR("failed mapping GNU RELRO section for \"%s\": %s",
-               name, strerror(errno));
-        return false;
-      }
+  /* Handle serializing/sharing the RELRO segment */
+  if (extinfo && (extinfo->flags & ANDROID_DLEXT_WRITE_RELRO)) {
+    if (phdr_table_serialize_gnu_relro(phdr, phnum, load_bias,
+                                       extinfo->relro_fd) < 0) {
+      DL_ERR("failed serializing GNU RELRO section for \"%s\": %s",
+             name, strerror(errno));
+      return false;
     }
+  } else if (extinfo && (extinfo->flags & ANDROID_DLEXT_USE_RELRO)) {
+    if (phdr_table_map_gnu_relro(phdr, phnum, load_bias,
+                                 extinfo->relro_fd) < 0) {
+      DL_ERR("failed mapping GNU RELRO section for \"%s\": %s",
+             name, strerror(errno));
+      return false;
+    }
+  }
 
-    notify_gdb_of_load(this);
-    return true;
+  notify_gdb_of_load(this);
+  return true;
 }
 
 /*
@@ -2214,7 +2372,7 @@
     return;
   }
 
-  soinfo* si = soinfo_alloc("[vdso]", nullptr, 0);
+  soinfo* si = soinfo_alloc("[vdso]", nullptr, 0, 0);
 
   si->phdr = reinterpret_cast<ElfW(Phdr)*>(reinterpret_cast<char*>(ehdr_vdso) + ehdr_vdso->e_phoff);
   si->phnum = ehdr_vdso->e_phnum;
@@ -2223,7 +2381,7 @@
   si->load_bias = get_elf_exec_load_bias(ehdr_vdso);
 
   si->PrelinkImage();
-  si->LinkImage(nullptr);
+  si->LinkImage(g_empty_list, soinfo::soinfo_list_t::make_list(si), nullptr);
 #endif
 }
 
@@ -2235,7 +2393,7 @@
 #else
 #define LINKER_PATH "/system/bin/linker"
 #endif
-static soinfo linker_soinfo_for_gdb(LINKER_PATH, nullptr, 0);
+static soinfo linker_soinfo_for_gdb(LINKER_PATH, nullptr, 0, 0);
 
 /* gdb expects the linker to be in the debug shared object list.
  * Without this, gdb has trouble locating the linker's ".text"
@@ -2267,182 +2425,175 @@
  */
 static ElfW(Addr) __linker_init_post_relocation(KernelArgumentBlock& args, ElfW(Addr) linker_base) {
 #if TIMING
-    struct timeval t0, t1;
-    gettimeofday(&t0, 0);
+  struct timeval t0, t1;
+  gettimeofday(&t0, 0);
 #endif
 
-    // Initialize environment functions, and get to the ELF aux vectors table.
-    linker_env_init(args);
+  // Initialize environment functions, and get to the ELF aux vectors table.
+  linker_env_init(args);
 
-    // If this is a setuid/setgid program, close the security hole described in
-    // ftp://ftp.freebsd.org/pub/FreeBSD/CERT/advisories/FreeBSD-SA-02:23.stdio.asc
-    if (get_AT_SECURE()) {
-        nullify_closed_stdio();
+  // If this is a setuid/setgid program, close the security hole described in
+  // ftp://ftp.freebsd.org/pub/FreeBSD/CERT/advisories/FreeBSD-SA-02:23.stdio.asc
+  if (get_AT_SECURE()) {
+    nullify_closed_stdio();
+  }
+
+  debuggerd_init();
+
+  // Get a few environment variables.
+  const char* LD_DEBUG = linker_env_get("LD_DEBUG");
+  if (LD_DEBUG != nullptr) {
+    g_ld_debug_verbosity = atoi(LD_DEBUG);
+  }
+
+  // Normally, these are cleaned by linker_env_init, but the test
+  // doesn't cost us anything.
+  const char* ldpath_env = nullptr;
+  const char* ldpreload_env = nullptr;
+  if (!get_AT_SECURE()) {
+    ldpath_env = linker_env_get("LD_LIBRARY_PATH");
+    ldpreload_env = linker_env_get("LD_PRELOAD");
+  }
+
+  INFO("[ android linker & debugger ]");
+
+  soinfo* si = soinfo_alloc(args.argv[0], nullptr, 0, RTLD_GLOBAL);
+  if (si == nullptr) {
+    exit(EXIT_FAILURE);
+  }
+
+  /* bootstrap the link map, the main exe always needs to be first */
+  si->flags |= FLAG_EXE;
+  link_map* map = &(si->link_map_head);
+
+  map->l_addr = 0;
+  map->l_name = args.argv[0];
+  map->l_prev = nullptr;
+  map->l_next = nullptr;
+
+  _r_debug.r_map = map;
+  r_debug_tail = map;
+
+  init_linker_info_for_gdb(linker_base);
+
+  // Extract information passed from the kernel.
+  si->phdr = reinterpret_cast<ElfW(Phdr)*>(args.getauxval(AT_PHDR));
+  si->phnum = args.getauxval(AT_PHNUM);
+  si->entry = args.getauxval(AT_ENTRY);
+
+  /* Compute the value of si->base. We can't rely on the fact that
+   * the first entry is the PHDR because this will not be true
+   * for certain executables (e.g. some in the NDK unit test suite)
+   */
+  si->base = 0;
+  si->size = phdr_table_get_load_size(si->phdr, si->phnum);
+  si->load_bias = 0;
+  for (size_t i = 0; i < si->phnum; ++i) {
+    if (si->phdr[i].p_type == PT_PHDR) {
+      si->load_bias = reinterpret_cast<ElfW(Addr)>(si->phdr) - si->phdr[i].p_vaddr;
+      si->base = reinterpret_cast<ElfW(Addr)>(si->phdr) - si->phdr[i].p_offset;
+      break;
     }
+  }
+  si->dynamic = nullptr;
+  si->ref_count = 1;
 
-    debuggerd_init();
+  ElfW(Ehdr)* elf_hdr = reinterpret_cast<ElfW(Ehdr)*>(si->base);
+  if (elf_hdr->e_type != ET_DYN) {
+    __libc_format_fd(2, "error: only position independent executables (PIE) are supported.\n");
+    exit(EXIT_FAILURE);
+  }
 
-    // Get a few environment variables.
-    const char* LD_DEBUG = linker_env_get("LD_DEBUG");
-    if (LD_DEBUG != nullptr) {
-      g_ld_debug_verbosity = atoi(LD_DEBUG);
-    }
+  // Use LD_LIBRARY_PATH and LD_PRELOAD (but only if we aren't setuid/setgid).
+  parse_LD_LIBRARY_PATH(ldpath_env);
+  parse_LD_PRELOAD(ldpreload_env);
 
-    // Normally, these are cleaned by linker_env_init, but the test
-    // doesn't cost us anything.
-    const char* ldpath_env = nullptr;
-    const char* ldpreload_env = nullptr;
-    if (!get_AT_SECURE()) {
-      ldpath_env = linker_env_get("LD_LIBRARY_PATH");
-      ldpreload_env = linker_env_get("LD_PRELOAD");
-    }
+  somain = si;
 
-    INFO("[ android linker & debugger ]");
+  si->PrelinkImage();
 
-    soinfo* si = soinfo_alloc(args.argv[0], nullptr, 0);
-    if (si == nullptr) {
-        exit(EXIT_FAILURE);
-    }
+  // add somain to global group
+  si->set_dt_flags_1(si->get_dt_flags_1() | DF_1_GLOBAL);
 
-    /* bootstrap the link map, the main exe always needs to be first */
-    si->flags |= FLAG_EXE;
-    link_map* map = &(si->link_map_head);
+  // 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;
+  }
 
-    map->l_addr = 0;
-    map->l_name = args.argv[0];
-    map->l_prev = nullptr;
-    map->l_next = nullptr;
+  for_each_dt_needed(si, [&](const char* name) {
+    needed_library_name_list.push_back(name);
+    ++needed_libraries_count;
+  });
 
-    _r_debug.r_map = map;
-    r_debug_tail = map;
+  const char* needed_library_names[needed_libraries_count];
 
-    init_linker_info_for_gdb(linker_base);
+  memset(needed_library_names, 0, sizeof(needed_library_names));
+  needed_library_name_list.copy_to_array(needed_library_names, needed_libraries_count);
 
-    // Extract information passed from the kernel.
-    si->phdr = reinterpret_cast<ElfW(Phdr)*>(args.getauxval(AT_PHDR));
-    si->phnum = args.getauxval(AT_PHNUM);
-    si->entry = args.getauxval(AT_ENTRY);
+  if (needed_libraries_count > 0 && !find_libraries(si, needed_library_names, needed_libraries_count, nullptr, g_ld_preloads, ld_preloads_count, RTLD_GLOBAL, nullptr)) {
+    __libc_format_fd(2, "CANNOT LINK EXECUTABLE: %s\n", linker_get_error_buffer());
+    exit(EXIT_FAILURE);
+  }
 
-    /* Compute the value of si->base. We can't rely on the fact that
-     * the first entry is the PHDR because this will not be true
-     * for certain executables (e.g. some in the NDK unit test suite)
-     */
-    si->base = 0;
-    si->size = phdr_table_get_load_size(si->phdr, si->phnum);
-    si->load_bias = 0;
-    for (size_t i = 0; i < si->phnum; ++i) {
-      if (si->phdr[i].p_type == PT_PHDR) {
-        si->load_bias = reinterpret_cast<ElfW(Addr)>(si->phdr) - si->phdr[i].p_vaddr;
-        si->base = reinterpret_cast<ElfW(Addr)>(si->phdr) - si->phdr[i].p_offset;
-        break;
-      }
-    }
-    si->dynamic = nullptr;
-    si->ref_count = 1;
+  add_vdso(args);
 
-    ElfW(Ehdr)* elf_hdr = reinterpret_cast<ElfW(Ehdr)*>(si->base);
-    if (elf_hdr->e_type != ET_DYN) {
-        __libc_format_fd(2, "error: only position independent executables (PIE) are supported.\n");
-        exit(EXIT_FAILURE);
-    }
+  si->CallPreInitConstructors();
 
-    // Use LD_LIBRARY_PATH and LD_PRELOAD (but only if we aren't setuid/setgid).
-    parse_LD_LIBRARY_PATH(ldpath_env);
-    parse_LD_PRELOAD(ldpreload_env);
-
-    somain = si;
-
-    si->PrelinkImage();
-
-    // Load ld_preloads and dependencies.
-    StringLinkedList needed_library_name_list;
-    size_t needed_libraries_count = 0;
-    size_t ld_preloads_count = 0;
-    while (g_ld_preload_names[ld_preloads_count] != nullptr) {
-      needed_library_name_list.push_back(g_ld_preload_names[ld_preloads_count++]);
-      ++needed_libraries_count;
-    }
-
-    for_each_dt_needed(si, [&](const char* name) {
-      needed_library_name_list.push_back(name);
-      ++needed_libraries_count;
-    });
-
-    const char* needed_library_names[needed_libraries_count];
-    soinfo* needed_library_si[needed_libraries_count];
-
-    memset(needed_library_names, 0, sizeof(needed_library_names));
-    needed_library_name_list.copy_to_array(needed_library_names, needed_libraries_count);
-
-    if (needed_libraries_count > 0 && !find_libraries(needed_library_names, needed_libraries_count, needed_library_si, g_ld_preloads, ld_preloads_count, 0, nullptr)) {
-        __libc_format_fd(2, "CANNOT LINK EXECUTABLE DEPENDENCIES: %s\n", linker_get_error_buffer());
-        exit(EXIT_FAILURE);
-    }
-
-    for (size_t i = 0; i<needed_libraries_count; ++i) {
-      si->add_child(needed_library_si[i]);
-    }
-
-    if (!si->LinkImage(nullptr)) {
-        __libc_format_fd(2, "CANNOT LINK EXECUTABLE: %s\n", linker_get_error_buffer());
-        exit(EXIT_FAILURE);
-    }
-
-    add_vdso(args);
-
-    si->CallPreInitConstructors();
-
-    /* After the PrelinkImage, the si->load_bias is initialized.
-     * For so lib, the map->l_addr will be updated in notify_gdb_of_load.
-     * We need to update this value for so exe here. So Unwind_Backtrace
-     * for some arch like x86 could work correctly within so exe.
-     */
-    map->l_addr = si->load_bias;
-    si->CallConstructors();
+  /* After the PrelinkImage, the si->load_bias is initialized.
+   * For so lib, the map->l_addr will be updated in notify_gdb_of_load.
+   * We need to update this value for so exe here. So Unwind_Backtrace
+   * for some arch like x86 could work correctly within so exe.
+   */
+  map->l_addr = si->load_bias;
+  si->CallConstructors();
 
 #if TIMING
-    gettimeofday(&t1, nullptr);
-    PRINT("LINKER TIME: %s: %d microseconds", args.argv[0], (int) (
-               (((long long)t1.tv_sec * 1000000LL) + (long long)t1.tv_usec) -
-               (((long long)t0.tv_sec * 1000000LL) + (long long)t0.tv_usec)));
+  gettimeofday(&t1, nullptr);
+  PRINT("LINKER TIME: %s: %d microseconds", args.argv[0], (int) (
+           (((long long)t1.tv_sec * 1000000LL) + (long long)t1.tv_usec) -
+           (((long long)t0.tv_sec * 1000000LL) + (long long)t0.tv_usec)));
 #endif
 #if STATS
-    PRINT("RELO STATS: %s: %d abs, %d rel, %d copy, %d symbol", args.argv[0],
-           linker_stats.count[kRelocAbsolute],
-           linker_stats.count[kRelocRelative],
-           linker_stats.count[kRelocCopy],
-           linker_stats.count[kRelocSymbol]);
+  PRINT("RELO STATS: %s: %d abs, %d rel, %d copy, %d symbol", args.argv[0],
+         linker_stats.count[kRelocAbsolute],
+         linker_stats.count[kRelocRelative],
+         linker_stats.count[kRelocCopy],
+         linker_stats.count[kRelocSymbol]);
 #endif
 #if COUNT_PAGES
-    {
-        unsigned n;
-        unsigned i;
-        unsigned count = 0;
-        for (n = 0; n < 4096; n++) {
-            if (bitmask[n]) {
-                unsigned x = bitmask[n];
+  {
+    unsigned n;
+    unsigned i;
+    unsigned count = 0;
+    for (n = 0; n < 4096; n++) {
+      if (bitmask[n]) {
+        unsigned x = bitmask[n];
 #if defined(__LP64__)
-                for (i = 0; i < 32; i++) {
+        for (i = 0; i < 32; i++) {
 #else
-                for (i = 0; i < 8; i++) {
+        for (i = 0; i < 8; i++) {
 #endif
-                    if (x & 1) {
-                        count++;
-                    }
-                    x >>= 1;
-                }
-            }
+          if (x & 1) {
+            count++;
+          }
+          x >>= 1;
         }
-        PRINT("PAGES MODIFIED: %s: %d (%dKB)", args.argv[0], count, count * 4);
+      }
     }
+    PRINT("PAGES MODIFIED: %s: %d (%dKB)", args.argv[0], count, count * 4);
+  }
 #endif
 
 #if TIMING || STATS || COUNT_PAGES
-    fflush(stdout);
+  fflush(stdout);
 #endif
 
-    TRACE("[ Ready to execute '%s' @ %p ]", si->name, reinterpret_cast<void*>(si->entry));
-    return si->entry;
+  TRACE("[ Ready to execute '%s' @ %p ]", si->name, reinterpret_cast<void*>(si->entry));
+  return si->entry;
 }
 
 /* Compute the load-bias of an existing executable. This shall only
@@ -2487,7 +2638,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("[dynamic linker]", nullptr, 0);
+  soinfo linker_so("[dynamic linker]", nullptr, 0, 0);
 
   // If the linker is not acting as PT_INTERP entry_point is equal to
   // _start. Which means that the linker is running as an executable and
@@ -2507,7 +2658,13 @@
   linker_so.phnum = elf_hdr->e_phnum;
   linker_so.flags |= FLAG_LINKER;
 
-  if (!(linker_so.PrelinkImage() && linker_so.LinkImage(nullptr))) {
+  // This might not be obvious... The reasons why we pass g_empty_list
+  // in place of local_group here are (1) we do not really need it, because
+  // linker is built with DT_SYMBOLIC and therefore relocates its symbols against
+  // itself without having to look into local_group and (2) allocators
+  // are not yet initialized, and therefore we cannot use linked_list.push_*
+  // functions at this point.
+  if (!(linker_so.PrelinkImage() && linker_so.LinkImage(g_empty_list, g_empty_list, nullptr))) {
     // It would be nice to print an error message, but if the linker
     // can't link itself, there's no guarantee that we'll be able to
     // call write() (because it involves a GOT reference). We may as
diff --git a/linker/linker.h b/linker/linker.h
index 3b140ac..0a98b40 100644
--- a/linker/linker.h
+++ b/linker/linker.h
@@ -89,7 +89,9 @@
 #define FLAG_LINKER     0x00000010 // The linker itself
 #define FLAG_NEW_SOINFO 0x40000000 // new soinfo format
 
-#define SOINFO_VERSION 0
+#define SUPPORTED_DT_FLAGS_1 (DF_1_NOW | DF_1_GLOBAL | DF_1_NODELETE)
+
+#define SOINFO_VERSION 1
 
 #define SOINFO_NAME_LEN 128
 
@@ -134,15 +136,17 @@
 #endif
 
   soinfo* next;
-  unsigned flags;
+  uint32_t flags;
 
+ private:
   const char* strtab;
+ public:
   ElfW(Sym)* symtab;
 
   size_t nbucket;
   size_t nchain;
-  unsigned* bucket;
-  unsigned* chain;
+  uint32_t* bucket;
+  uint32_t* chain;
 
 #if defined(__mips__) || !defined(__LP64__)
   // This is only used by mips and mips64, but needs to be here for
@@ -177,12 +181,12 @@
 
 #if defined(__arm__)
   // ARM EABI section used for stack unwinding.
-  unsigned* ARM_exidx;
+  uint32_t* ARM_exidx;
   size_t ARM_exidx_count;
 #elif defined(__mips__)
-  unsigned mips_symtabno;
-  unsigned mips_local_gotno;
-  unsigned mips_gotsym;
+  uint32_t mips_symtabno;
+  uint32_t mips_local_gotno;
+  uint32_t mips_gotsym;
 #endif
 
   size_t ref_count;
@@ -199,36 +203,44 @@
 #endif
   bool has_DT_SYMBOLIC;
 
-  soinfo(const char* name, const struct stat* file_stat, off64_t file_offset);
+  soinfo(const char* name, const struct stat* file_stat, off64_t file_offset, int rtld_flags);
 
   void CallConstructors();
   void CallDestructors();
   void CallPreInitConstructors();
   bool PrelinkImage();
-  bool LinkImage(const android_dlextinfo* extinfo);
+  bool LinkImage(const soinfo_list_t& global_group, const soinfo_list_t& local_group, const android_dlextinfo* extinfo);
 
   void add_child(soinfo* child);
   void remove_all_links();
 
-  ino_t get_st_ino();
-  dev_t get_st_dev();
-  off64_t get_file_offset();
+  ino_t get_st_ino() const;
+  dev_t get_st_dev() const;
+  off64_t get_file_offset() const;
+
+  uint32_t get_rtld_flags() const;
+  uint32_t get_dt_flags_1() const;
+  void set_dt_flags_1(uint32_t dt_flags_1);
 
   soinfo_list_t& get_children();
   soinfo_list_t& get_parents();
 
   ElfW(Addr) resolve_symbol_address(ElfW(Sym)* s);
 
-  bool inline has_min_version(uint32_t min_version) {
+  const char* get_string(ElfW(Word) index) const;
+  bool can_unload() const;
+
+  bool inline has_min_version(uint32_t min_version) const {
     return (flags & FLAG_NEW_SOINFO) != 0 && version >= min_version;
   }
+
  private:
   void CallArray(const char* array_name, linker_function_t* functions, size_t count, bool reverse);
   void CallFunction(const char* function_name, linker_function_t function);
 #if defined(USE_RELA)
-  int Relocate(ElfW(Rela)* rela, unsigned count);
+  int Relocate(ElfW(Rela)* rela, unsigned count, const soinfo_list_t& global_group, const soinfo_list_t& local_group);
 #else
-  int Relocate(ElfW(Rel)* rel, unsigned count);
+  int Relocate(ElfW(Rel)* rel, unsigned count, const soinfo_list_t& global_group, const soinfo_list_t& local_group);
 #endif
 
  private:
@@ -246,9 +258,14 @@
 
   // version >= 1
   off64_t file_offset;
+  uint32_t rtld_flags;
+  uint32_t dt_flags_1;
+  size_t strtab_size;
+
+  friend soinfo* get_libdl_info();
 };
 
-extern soinfo* get_libdl_info();
+soinfo* get_libdl_info();
 
 void do_android_get_LD_LIBRARY_PATH(char*, size_t);
 void do_android_update_LD_LIBRARY_PATH(const char* ld_library_path);
diff --git a/tests/Android.build.mk b/tests/Android.build.mk
index d54c851..63729da 100644
--- a/tests/Android.build.mk
+++ b/tests/Android.build.mk
@@ -15,6 +15,7 @@
 #
 
 include $(CLEAR_VARS)
+LOCAL_ADDITIONAL_DEPENDENCIES := $(common_additional_dependencies)
 
 LOCAL_MODULE := $(module)
 LOCAL_MODULE_TAGS := $(module_tag)
diff --git a/tests/Android.mk b/tests/Android.mk
index 407f21b..5a1127b 100644
--- a/tests/Android.mk
+++ b/tests/Android.mk
@@ -28,6 +28,8 @@
 build_host := false
 endif
 
+common_additional_dependencies := $(LOCAL_PATH)/Android.mk $(LOCAL_PATH)/Android.build.mk
+
 # -----------------------------------------------------------------------------
 # All standard tests.
 # -----------------------------------------------------------------------------
@@ -223,6 +225,7 @@
 
 bionic-unit-tests_src_files := \
     atexit_test.cpp \
+    dl_test.cpp \
     dlext_test.cpp \
     dlfcn_test.cpp \
 
@@ -235,8 +238,7 @@
 bionic-unit-tests_cppflags := $(test_cppflags)
 
 bionic-unit-tests_ldflags := \
-    -Wl,--export-dynamic \
-    -Wl,-u,DlSymTestFunction \
+    -Wl,--export-dynamic
 
 bionic-unit-tests_c_includes := \
     bionic/libc \
@@ -245,6 +247,12 @@
 bionic-unit-tests_shared_libraries_target := \
     libdl \
     libpagemap \
+    libdl_preempt_test_1 \
+    libdl_preempt_test_2
+
+ifneq ($(filter $(TARGET_ARCH),arm arm64),$(TARGET_ARCH))
+bionic-unit-tests_shared_libraries_target += libdl_test_df_1_global
+endif
 
 module := bionic-unit-tests
 module_tag := optional
@@ -283,6 +291,16 @@
 
 bionic-unit-tests-glibc_src_files := \
     atexit_test.cpp \
+    dlfcn_test.cpp \
+    dl_test.cpp \
+
+bionic-unit-tests-glibc_shared_libraries := \
+    libdl_preempt_test_1 \
+    libdl_preempt_test_2
+
+ifneq ($(filter $(TARGET_ARCH),arm arm64),$(TARGET_ARCH))
+bionic-unit-tests-glibc_shared_libraries += libdl_test_df_1_global
+endif
 
 bionic-unit-tests-glibc_whole_static_libraries := \
     libBionicStandardTests \
@@ -290,8 +308,12 @@
 bionic-unit-tests-glibc_ldlibs := \
     -lrt -ldl \
 
+bionic-unit-tests-glibc_c_includes := \
+    bionic/libc \
+
 bionic-unit-tests-glibc_cflags := $(test_cflags)
 bionic-unit-tests-glibc_cppflags := $(test_cppflags)
+bionic-unit-tests-glibc_ldflags := -Wl,--export-dynamic
 
 module := bionic-unit-tests-glibc
 module_tag := optional
diff --git a/tests/dl_test.cpp b/tests/dl_test.cpp
new file mode 100644
index 0000000..74c7b51
--- /dev/null
+++ b/tests/dl_test.cpp
@@ -0,0 +1,72 @@
+/*
+ * Copyright (C) 2012 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <gtest/gtest.h>
+
+#include <dlfcn.h>
+#include <libgen.h>
+#include <limits.h>
+#include <stdio.h>
+#include <stdint.h>
+
+#include <string>
+
+extern "C" int main_global_default_serial() {
+  return 3370318;
+}
+
+extern "C" int main_global_protected_serial() {
+  return 2716057;
+}
+
+// The following functions are defined in DT_NEEDED
+// libdl_preempt_test.so library.
+
+// This one calls main_global_default_serial
+extern "C" int main_global_default_get_serial();
+
+// This one calls main_global_protected_serial
+extern "C" int main_global_protected_get_serial();
+
+// This one calls lib_global_default_serial
+extern "C" int lib_global_default_get_serial();
+
+// This one calls lib_global_protected_serial
+extern "C" int lib_global_protected_get_serial();
+
+// This test verifies that the global default function
+// main_global_default_serial() is preempted by
+// the function defined above.
+TEST(dl, main_preempts_global_default) {
+  ASSERT_EQ(3370318, main_global_default_get_serial());
+}
+
+// This one makes sure that the global protected
+// symbols do not get preempted
+TEST(dl, main_does_not_preempt_global_protected) {
+  ASSERT_EQ(3370318, main_global_protected_get_serial());
+}
+
+// check same things for lib
+TEST(dl, lib_preempts_global_default) {
+  ASSERT_EQ(3370318, lib_global_default_get_serial());
+}
+
+TEST(dl, lib_does_not_preempt_global_protected) {
+  ASSERT_EQ(3370318, lib_global_protected_get_serial());
+}
+
+// TODO: Add tests for LD_PRELOADs
diff --git a/tests/dlfcn_test.cpp b/tests/dlfcn_test.cpp
index 9c9fbdd..2f0d430 100644
--- a/tests/dlfcn_test.cpp
+++ b/tests/dlfcn_test.cpp
@@ -162,51 +162,250 @@
   ASSERT_EQ(1, fn());
 }
 
-TEST(dlfcn, dlopen_check_order) {
+TEST(dlfcn, dlopen_check_order_dlsym) {
   // Here is how the test library and its dt_needed
   // libraries are arranged
   //
-  //  libtest_check_order.so
+  //  libtest_check_order_children.so
   //  |
-  //  +-> libtest_check_order_1_left.so
+  //  +-> ..._1_left.so
   //  |   |
-  //  |   +-> libtest_check_order_a.so
+  //  |   +-> ..._a.so
   //  |   |
-  //  |   +-> libtest_check_order_b.so
+  //  |   +-> ...r_b.so
   //  |
-  //  +-> libtest_check_order_2_right.so
+  //  +-> ..._2_right.so
   //  |   |
-  //  |   +-> libtest_check_order_d.so
+  //  |   +-> ..._d.so
   //  |       |
-  //  |       +-> libtest_check_order_b.so
+  //  |       +-> ..._b.so
   //  |
-  //  +-> libtest_check_order_3_c.so
+  //  +-> ..._3_c.so
   //
   //  load order should be (1, 2, 3, a, b, d)
   //
   // get_answer() is defined in (2, 3, a, b, c)
   // get_answer2() is defined in (b, d)
-  void* sym = dlsym(RTLD_DEFAULT, "dlopen_test_get_answer");
+  void* sym = dlsym(RTLD_DEFAULT, "check_order_dlsym_get_answer");
   ASSERT_TRUE(sym == nullptr);
-  void* handle = dlopen("libtest_check_order.so", RTLD_NOW);
-  ASSERT_TRUE(handle != nullptr);
+  void* handle = dlopen("libtest_check_order_dlsym.so", RTLD_NOW | RTLD_GLOBAL);
+  ASSERT_TRUE(handle != nullptr) << dlerror();
   typedef int (*fn_t) (void);
   fn_t fn, fn2;
-  fn = reinterpret_cast<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);
+  fn = reinterpret_cast<fn_t>(dlsym(RTLD_DEFAULT, "check_order_dlsym_get_answer"));
+  ASSERT_TRUE(fn != NULL) << dlerror();
+  fn2 = reinterpret_cast<fn_t>(dlsym(RTLD_DEFAULT, "check_order_dlsym_get_answer2"));
+  ASSERT_TRUE(fn2 != NULL) << dlerror();
 
   ASSERT_EQ(42, fn());
   ASSERT_EQ(43, fn2());
   dlclose(handle);
 }
 
+TEST(dlfcn, dlopen_check_order_reloc_siblings) {
+  // This is how this one works:
+  // we lookup and call get_answer which is defined in '_2.so'
+  // and in turn calls external get_answer_impl() defined in _1.so and in '_[a-f].so'
+  // the correct _impl() is implemented by '_a.so';
+  //
+  // Note that this is test for RTLD_LOCAL (TODO: test for GLOBAL?)
+  //
+  // Here is the picture:
+  //
+  // libtest_check_order_reloc_siblings.so
+  // |
+  // +-> ..._1.so <- empty
+  // |   |
+  // |   +-> ..._a.so <- exports correct answer_impl()
+  // |   |
+  // |   +-> ..._b.so <- every other letter exporting incorrect one.
+  // |
+  // +-> ..._2.so <- empty
+  // |   |
+  // |   +-> ..._c.so
+  // |   |
+  // |   +-> ..._d.so
+  // |
+  // +-> ..._3.so <- empty
+  //     |
+  //     +-> ..._e.so
+  //     |
+  //     +-> ..._f.so <- exports get_answer() that calls get_anser_impl();
+  //                     implements incorrect get_answer_impl()
+
+  void* handle = dlopen("libtest_check_order_reloc_siblings.so", RTLD_NOW | RTLD_NOLOAD);
+  ASSERT_TRUE(handle == nullptr);
+#ifdef __BIONIC__
+  // TODO: glibc returns nullptr on dlerror() here. Is it bug?
+  ASSERT_STREQ("dlopen failed: library \"libtest_check_order_reloc_siblings.so\" wasn't loaded and RTLD_NOLOAD prevented it", dlerror());
+#endif
+
+  handle = dlopen("libtest_check_order_reloc_siblings.so", RTLD_NOW | RTLD_LOCAL);
+  ASSERT_TRUE(handle != nullptr) << dlerror();
+
+  typedef int (*fn_t) (void);
+  fn_t fn = reinterpret_cast<fn_t>(dlsym(handle, "check_order_reloc_get_answer"));
+  ASSERT_TRUE(fn != nullptr) << dlerror();
+  ASSERT_EQ(42, fn());
+
+  ASSERT_EQ(0, dlclose(handle));
+}
+
+TEST(dlfcn, dlopen_check_order_reloc_siblings_with_preload) {
+  // This test uses the same library as dlopen_check_order_reloc_siblings.
+  // Unlike dlopen_check_order_reloc_siblings it preloads
+  // libtest_check_order_reloc_siblings_1.so (first dependency) prior to
+  // dlopen(libtest_check_order_reloc_siblings.so)
+
+  void* handle = dlopen("libtest_check_order_reloc_siblings.so", RTLD_NOW | RTLD_NOLOAD);
+  ASSERT_TRUE(handle == nullptr);
+  handle = dlopen("libtest_check_order_reloc_siblings_1.so", RTLD_NOW | RTLD_NOLOAD);
+  ASSERT_TRUE(handle == nullptr);
+
+  void* handle_for_1 = dlopen("libtest_check_order_reloc_siblings_1.so", RTLD_NOW | RTLD_LOCAL);
+  ASSERT_TRUE(handle_for_1 != nullptr) << dlerror();
+
+  handle = dlopen("libtest_check_order_reloc_siblings.so", RTLD_NOW | RTLD_LOCAL);
+  ASSERT_TRUE(handle != nullptr) << dlerror();
+
+  ASSERT_EQ(0, dlclose(handle_for_1));
+
+  typedef int (*fn_t) (void);
+  fn_t fn = reinterpret_cast<fn_t>(dlsym(handle, "check_order_reloc_get_answer"));
+  ASSERT_TRUE(fn != nullptr) << dlerror();
+  ASSERT_EQ(42, fn());
+
+  ASSERT_EQ(0, dlclose(handle));
+}
+
+TEST(dlfcn, dlopen_check_order_reloc_nephew) {
+  // This is how this one works:
+  // we lookup and call nephew_get_answer which is defined in '_2.so'
+  // and in turn calls external get_answer_impl() defined in '_[a-f].so'
+  // the correct _impl() is implemented by '_a.so';
+  //
+  // Here is the picture:
+  //
+  // libtest_check_order_reloc_siblings.so
+  // |
+  // +-> ..._1.so <- empty
+  // |   |
+  // |   +-> ..._a.so <- exports correct answer_impl()
+  // |   |
+  // |   +-> ..._b.so <- every other letter exporting incorrect one.
+  // |
+  // +-> ..._2.so <- empty
+  // |   |
+  // |   +-> ..._c.so
+  // |   |
+  // |   +-> ..._d.so
+  // |
+  // +-> ..._3.so <- nephew_get_answer() that calls get_answer_impl();
+  //     |
+  //     +-> ..._e.so
+  //     |
+  //     +-> ..._f.so
+
+  void* handle = dlopen("libtest_check_order_reloc_siblings.so", RTLD_NOW | RTLD_NOLOAD);
+  ASSERT_TRUE(handle == nullptr);
+#ifdef __BIONIC__
+  // TODO: glibc returns nullptr on dlerror() here. Is it bug?
+  ASSERT_STREQ("dlopen failed: library \"libtest_check_order_reloc_siblings.so\" wasn't loaded and RTLD_NOLOAD prevented it", dlerror());
+#endif
+
+  handle = dlopen("libtest_check_order_reloc_siblings.so", RTLD_NOW | RTLD_LOCAL);
+  ASSERT_TRUE(handle != nullptr) << dlerror();
+
+  typedef int (*fn_t) (void);
+  fn_t fn = reinterpret_cast<fn_t>(dlsym(handle, "check_order_reloc_nephew_get_answer"));
+  ASSERT_TRUE(fn != nullptr) << dlerror();
+  ASSERT_EQ(42, fn());
+
+  ASSERT_EQ(0, dlclose(handle));
+}
+
+extern "C" int check_order_reloc_root_get_answer_impl() {
+  return 42;
+}
+
+TEST(dlfcn, dlopen_check_order_reloc_main_executable) {
+  // This is how this one works:
+  // we lookup and call get_answer3 which is defined in 'root.so'
+  // and in turn calls external root_get_answer_impl() defined in _2.so and
+  // above the correct _impl() is one in the executable.
+  //
+  // libtest_check_order_reloc_root.so
+  // |
+  // +-> ..._1.so <- empty
+  // |
+  // +-> ..._2.so <- gives incorrect answer for answer_main_impl()
+  //
+
+  void* handle = dlopen("libtest_check_order_reloc_root.so", RTLD_NOW | RTLD_NOLOAD);
+  ASSERT_TRUE(handle == nullptr);
+#ifdef __BIONIC__
+  // TODO: glibc returns nullptr on dlerror() here. Is it bug?
+  ASSERT_STREQ("dlopen failed: library \"libtest_check_order_reloc_root.so\" wasn't loaded and RTLD_NOLOAD prevented it", dlerror());
+#endif
+
+  handle = dlopen("libtest_check_order_reloc_root.so", RTLD_NOW | RTLD_LOCAL);
+  ASSERT_TRUE(handle != nullptr) << dlerror();
+
+  typedef int (*fn_t) (void);
+  fn_t fn = reinterpret_cast<fn_t>(dlsym(handle, "check_order_reloc_root_get_answer"));
+  ASSERT_TRUE(fn != nullptr) << dlerror();
+  ASSERT_EQ(42, fn());
+
+  ASSERT_EQ(0, dlclose(handle));
+}
+
+TEST(dlfcn, dlopen_check_rtld_local) {
+  void* sym = dlsym(RTLD_DEFAULT, "dlopen_testlib_simple_func");
+  ASSERT_TRUE(sym == nullptr);
+
+  // implicit RTLD_LOCAL
+  void* handle = dlopen("libtest_simple.so", RTLD_NOW);
+  sym = dlsym(RTLD_DEFAULT, "dlopen_testlib_simple_func");
+  ASSERT_TRUE(sym == nullptr);
+  ASSERT_SUBSTR("undefined symbol: dlopen_testlib_simple_func", dlerror());
+  sym = dlsym(handle, "dlopen_testlib_simple_func");
+  ASSERT_TRUE(sym != nullptr);
+  ASSERT_TRUE(reinterpret_cast<bool (*)(void)>(sym)());
+  dlclose(handle);
+
+  // explicit RTLD_LOCAL
+  handle = dlopen("libtest_simple.so", RTLD_NOW | RTLD_LOCAL);
+  sym = dlsym(RTLD_DEFAULT, "dlopen_testlib_simple_func");
+  ASSERT_TRUE(sym == nullptr);
+  ASSERT_SUBSTR("undefined symbol: dlopen_testlib_simple_func", dlerror());
+  sym = dlsym(handle, "dlopen_testlib_simple_func");
+  ASSERT_TRUE(sym != nullptr);
+  ASSERT_TRUE(reinterpret_cast<bool (*)(void)>(sym)());
+  dlclose(handle);
+}
+
+TEST(dlfcn, dlopen_check_rtld_global) {
+  void* sym = dlsym(RTLD_DEFAULT, "dlopen_testlib_simple_func");
+  ASSERT_TRUE(sym == nullptr);
+
+  void* handle = dlopen("libtest_simple.so", RTLD_NOW | RTLD_GLOBAL);
+  ASSERT_TRUE(handle != nullptr) << dlerror();
+  sym = dlsym(RTLD_DEFAULT, "dlopen_testlib_simple_func");
+  ASSERT_TRUE(sym != nullptr) << dlerror();
+  ASSERT_TRUE(reinterpret_cast<bool (*)(void)>(sym)());
+  dlclose(handle);
+
+  // RTLD_GLOBAL implies RTLD_NODELETE, let's check that
+  void* sym_after_dlclose = dlsym(RTLD_DEFAULT, "dlopen_testlib_simple_func");
+  ASSERT_EQ(sym, sym_after_dlclose);
+}
+
 // libtest_with_dependency_loop.so -> libtest_with_dependency_loop_a.so ->
 // 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);
+#if defined(__BIONIC__)
   ASSERT_TRUE(handle == nullptr);
   ASSERT_STREQ("dlopen failed: recursive link to \"libtest_with_dependency_loop_a.so\"", dlerror());
   // This symbol should never be exposed
@@ -220,6 +419,98 @@
   handle = dlopen("libtest_with_dependency_loop.so", RTLD_NOW | RTLD_NOLOAD);
   ASSERT_TRUE(handle == nullptr);
   ASSERT_STREQ("dlopen failed: library \"libtest_with_dependency_loop.so\" wasn't loaded and RTLD_NOLOAD prevented it", dlerror());
+#else // glibc allows recursive links
+  ASSERT_TRUE(handle != nullptr);
+  dlclose(handle);
+#endif
+}
+
+TEST(dlfcn, dlopen_nodelete) {
+  static bool is_unloaded = false;
+
+  void* handle = dlopen("libtest_nodelete_1.so", RTLD_NOW | RTLD_NODELETE);
+  ASSERT_TRUE(handle != nullptr) << dlerror();
+  void (*set_unload_flag_ptr)(bool*);
+  set_unload_flag_ptr = reinterpret_cast<void (*)(bool*)>(dlsym(handle, "dlopen_nodelete_1_set_unload_flag_ptr"));
+  ASSERT_TRUE(set_unload_flag_ptr != nullptr) << dlerror();
+  set_unload_flag_ptr(&is_unloaded);
+
+  uint32_t* taxicab_number = reinterpret_cast<uint32_t*>(dlsym(handle, "dlopen_nodelete_1_taxicab_number"));
+  ASSERT_TRUE(taxicab_number != nullptr) << dlerror();
+  ASSERT_EQ(1729U, *taxicab_number);
+  *taxicab_number = 2;
+
+  dlclose(handle);
+  ASSERT_TRUE(!is_unloaded);
+
+  uint32_t* taxicab_number_after_dlclose = reinterpret_cast<uint32_t*>(dlsym(handle, "dlopen_nodelete_1_taxicab_number"));
+  ASSERT_EQ(taxicab_number_after_dlclose, taxicab_number);
+  ASSERT_EQ(2U, *taxicab_number_after_dlclose);
+
+
+  handle = dlopen("libtest_nodelete_1.so", RTLD_NOW);
+  uint32_t* taxicab_number2 = reinterpret_cast<uint32_t*>(dlsym(handle, "dlopen_nodelete_1_taxicab_number"));
+  ASSERT_EQ(taxicab_number2, taxicab_number);
+
+  ASSERT_EQ(2U, *taxicab_number2);
+
+  dlclose(handle);
+  ASSERT_TRUE(!is_unloaded);
+}
+
+TEST(dlfcn, dlopen_nodelete_on_second_dlopen) {
+  static bool is_unloaded = false;
+
+  void* handle = dlopen("libtest_nodelete_2.so", RTLD_NOW);
+  ASSERT_TRUE(handle != nullptr) << dlerror();
+  void (*set_unload_flag_ptr)(bool*);
+  set_unload_flag_ptr = reinterpret_cast<void (*)(bool*)>(dlsym(handle, "dlopen_nodelete_2_set_unload_flag_ptr"));
+  ASSERT_TRUE(set_unload_flag_ptr != nullptr) << dlerror();
+  set_unload_flag_ptr(&is_unloaded);
+
+  uint32_t* taxicab_number = reinterpret_cast<uint32_t*>(dlsym(handle, "dlopen_nodelete_2_taxicab_number"));
+  ASSERT_TRUE(taxicab_number != nullptr) << dlerror();
+
+  ASSERT_EQ(1729U, *taxicab_number);
+  *taxicab_number = 2;
+
+  // This RTLD_NODELETE should be ignored
+  void* handle1 = dlopen("libtest_nodelete_2.so", RTLD_NOW | RTLD_NODELETE);
+  ASSERT_TRUE(handle1 != nullptr) << dlerror();
+  ASSERT_EQ(handle, handle1);
+
+  dlclose(handle1);
+  dlclose(handle);
+
+  ASSERT_TRUE(is_unloaded);
+}
+
+TEST(dlfcn, dlopen_nodelete_dt_flags_1) {
+  static bool is_unloaded = false;
+
+  void* handle = dlopen("libtest_nodelete_dt_flags_1.so", RTLD_NOW);
+  ASSERT_TRUE(handle != nullptr) << dlerror();
+  void (*set_unload_flag_ptr)(bool*);
+  set_unload_flag_ptr = reinterpret_cast<void (*)(bool*)>(dlsym(handle, "dlopen_nodelete_dt_flags_1_set_unload_flag_ptr"));
+  ASSERT_TRUE(set_unload_flag_ptr != nullptr) << dlerror();
+  set_unload_flag_ptr(&is_unloaded);
+
+  dlclose(handle);
+  ASSERT_TRUE(!is_unloaded);
+}
+
+TEST(dlfcn, dlsym_df_1_global) {
+#if !defined(__arm__) && !defined(__aarch64__)
+  void* handle = dlopen("libtest_dlsym_df_1_global.so", RTLD_NOW);
+  ASSERT_TRUE(handle != nullptr) << dlerror();
+  int (*get_answer)();
+  get_answer = reinterpret_cast<int (*)()>(dlsym(handle, "dl_df_1_global_get_answer"));
+  ASSERT_TRUE(get_answer != nullptr) << dlerror();
+  ASSERT_EQ(42, get_answer());
+  ASSERT_EQ(0, dlclose(handle));
+#else
+  GTEST_LOG_(INFO) << "This test does nothing on arm/arm64 (to be reenabled once b/18137520 or b/18130452 are fixed).\n";
+#endif
 }
 
 TEST(dlfcn, dlopen_failure) {
diff --git a/tests/libs/Android.build.dlopen_check_order_dlsym.mk b/tests/libs/Android.build.dlopen_check_order_dlsym.mk
new file mode 100644
index 0000000..73d8c1a
--- /dev/null
+++ b/tests/libs/Android.build.dlopen_check_order_dlsym.mk
@@ -0,0 +1,90 @@
+#
+# Copyright (C) 2012 The Android Open Source Project
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+# -----------------------------------------------------------------------------
+# Libraries used by dlfcn tests to verify correct load order:
+# libtest_check_order_2_right.so
+# -----------------------------------------------------------------------------
+libtest_check_order_dlsym_2_right_src_files := \
+    dlopen_check_order_dlsym_answer.cpp
+
+libtest_check_order_dlsym_2_right_cflags := -D__ANSWER=42
+module := libtest_check_order_dlsym_2_right
+include $(LOCAL_PATH)/Android.build.testlib.mk
+
+# -----------------------------------------------------------------------------
+# libtest_check_order_a.so
+# -----------------------------------------------------------------------------
+libtest_check_order_dlsym_a_src_files := \
+    dlopen_check_order_dlsym_answer.cpp
+
+libtest_check_order_dlsym_a_cflags := -D__ANSWER=1
+module := libtest_check_order_dlsym_a
+include $(LOCAL_PATH)/Android.build.testlib.mk
+
+# -----------------------------------------------------------------------------
+# libtest_check_order_b.so
+# -----------------------------------------------------------------------------
+libtest_check_order_dlsym_b_src_files := \
+    dlopen_check_order_dlsym_answer.cpp
+
+libtest_check_order_dlsym_b_cflags := -D__ANSWER=2 -D__ANSWER2=43
+module := libtest_check_order_dlsym_b
+include $(LOCAL_PATH)/Android.build.testlib.mk
+
+# -----------------------------------------------------------------------------
+# libtest_check_order_c.so
+# -----------------------------------------------------------------------------
+libtest_check_order_dlsym_3_c_src_files := \
+    dlopen_check_order_dlsym_answer.cpp
+
+libtest_check_order_dlsym_3_c_cflags := -D__ANSWER=3
+module := libtest_check_order_dlsym_3_c
+include $(LOCAL_PATH)/Android.build.testlib.mk
+
+# -----------------------------------------------------------------------------
+# libtest_check_order_d.so
+# -----------------------------------------------------------------------------
+libtest_check_order_dlsym_d_src_files := \
+   dlopen_check_order_dlsym_answer.cpp
+
+libtest_check_order_dlsym_d_shared_libraries := libtest_check_order_dlsym_b
+libtest_check_order_dlsym_d_cflags := -D__ANSWER=4 -D__ANSWER2=4
+module := libtest_check_order_dlsym_d
+include $(LOCAL_PATH)/Android.build.testlib.mk
+
+# -----------------------------------------------------------------------------
+# libtest_check_order_left.so
+# -----------------------------------------------------------------------------
+libtest_check_order_dlsym_1_left_src_files := \
+    empty.cpp
+
+libtest_check_order_dlsym_1_left_shared_libraries := libtest_check_order_dlsym_a libtest_check_order_dlsym_b
+
+module := libtest_check_order_dlsym_1_left
+include $(LOCAL_PATH)/Android.build.testlib.mk
+
+# -----------------------------------------------------------------------------
+# libtest_check_order.so
+# -----------------------------------------------------------------------------
+libtest_check_order_dlsym_src_files := \
+    empty.cpp
+
+libtest_check_order_dlsym_shared_libraries := libtest_check_order_dlsym_1_left \
+  libtest_check_order_dlsym_2_right libtest_check_order_dlsym_3_c
+
+module := libtest_check_order_dlsym
+include $(LOCAL_PATH)/Android.build.testlib.mk
diff --git a/tests/libs/Android.build.dlopen_check_order_reloc_main_executable.mk b/tests/libs/Android.build.dlopen_check_order_reloc_main_executable.mk
new file mode 100644
index 0000000..639696b
--- /dev/null
+++ b/tests/libs/Android.build.dlopen_check_order_reloc_main_executable.mk
@@ -0,0 +1,56 @@
+#
+# Copyright (C) 2012 The Android Open Source Project
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+# -----------------------------------------------------------------------------
+# Libraries used by dlfcn tests to verify correct relocation order:
+# libtest_check_order_reloc_root*.so
+# -----------------------------------------------------------------------------
+
+
+# -----------------------------------------------------------------------------
+# ..._1.so - empty
+# -----------------------------------------------------------------------------
+libtest_check_order_reloc_root_1_src_files := \
+    empty.cpp
+
+
+module := libtest_check_order_reloc_root_1
+include $(LOCAL_PATH)/Android.build.testlib.mk
+
+
+# -----------------------------------------------------------------------------
+# ..._2.so - this one has the incorrect answer
+# -----------------------------------------------------------------------------
+libtest_check_order_reloc_root_2_src_files := \
+    dlopen_check_order_reloc_root_answer_impl.cpp
+
+libtest_check_order_reloc_root_2_cflags := -D__ANSWER=2
+
+module := libtest_check_order_reloc_root_2
+include $(LOCAL_PATH)/Android.build.testlib.mk
+
+# -----------------------------------------------------------------------------
+# libtest_check_order_reloc_root.so <- implements get_answer3()
+# -----------------------------------------------------------------------------
+libtest_check_order_reloc_root_src_files := \
+    dlopen_check_order_reloc_root_answer.cpp
+
+libtest_check_order_reloc_root_shared_libraries := \
+    libtest_check_order_reloc_root_1 \
+    libtest_check_order_reloc_root_2
+
+module := libtest_check_order_reloc_root
+include $(LOCAL_PATH)/Android.build.testlib.mk
diff --git a/tests/libs/Android.build.dlopen_check_order_reloc_siblings.mk b/tests/libs/Android.build.dlopen_check_order_reloc_siblings.mk
new file mode 100644
index 0000000..0f1a2b4
--- /dev/null
+++ b/tests/libs/Android.build.dlopen_check_order_reloc_siblings.mk
@@ -0,0 +1,133 @@
+#
+# Copyright (C) 2014 The Android Open Source Project
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+# -----------------------------------------------------------------------------
+# Libraries used by dlfcn tests to verify correct relocation order:
+# libtest_check_order_reloc_siblings*.so
+# -----------------------------------------------------------------------------
+
+# -----------------------------------------------------------------------------
+# ..._1.so - empty
+# -----------------------------------------------------------------------------
+libtest_check_order_reloc_siblings_1_src_files := \
+    empty.cpp
+
+libtest_check_order_reloc_siblings_1_shared_libraries := \
+    libtest_check_order_reloc_siblings_a \
+    libtest_check_order_reloc_siblings_b
+
+module := libtest_check_order_reloc_siblings_1
+include $(LOCAL_PATH)/Android.build.testlib.mk
+
+
+# -----------------------------------------------------------------------------
+# ..._2.so - empty
+# -----------------------------------------------------------------------------
+libtest_check_order_reloc_siblings_2_src_files := \
+    empty.cpp
+
+libtest_check_order_reloc_siblings_2_shared_libraries := \
+    libtest_check_order_reloc_siblings_c \
+    libtest_check_order_reloc_siblings_d
+
+module := libtest_check_order_reloc_siblings_2
+include $(LOCAL_PATH)/Android.build.testlib.mk
+
+# -----------------------------------------------------------------------------
+# ..._3.so - get_answer2();
+# -----------------------------------------------------------------------------
+libtest_check_order_reloc_siblings_3_src_files := \
+    dlopen_check_order_reloc_nephew_answer.cpp
+
+libtest_check_order_reloc_siblings_3_shared_libraries := \
+    libtest_check_order_reloc_siblings_e \
+    libtest_check_order_reloc_siblings_f
+
+module := libtest_check_order_reloc_siblings_3
+include $(LOCAL_PATH)/Android.build.testlib.mk
+
+# -----------------------------------------------------------------------------
+# ..._a.so <- correct impl
+# -----------------------------------------------------------------------------
+libtest_check_order_reloc_siblings_a_src_files := \
+    dlopen_check_order_reloc_answer_impl.cpp
+
+libtest_check_order_reloc_siblings_a_cflags := -D__ANSWER=42
+module := libtest_check_order_reloc_siblings_a
+include $(LOCAL_PATH)/Android.build.testlib.mk
+
+# -----------------------------------------------------------------------------
+# ..._b.so
+# -----------------------------------------------------------------------------
+libtest_check_order_reloc_siblings_b_src_files := \
+    dlopen_check_order_reloc_answer_impl.cpp
+
+libtest_check_order_reloc_siblings_b_cflags := -D__ANSWER=1
+module := libtest_check_order_reloc_siblings_b
+include $(LOCAL_PATH)/Android.build.testlib.mk
+
+# -----------------------------------------------------------------------------
+# ..._c.so
+# -----------------------------------------------------------------------------
+libtest_check_order_reloc_siblings_c_src_files := \
+    dlopen_check_order_reloc_answer_impl.cpp
+
+libtest_check_order_reloc_siblings_c_cflags := -D__ANSWER=2
+module := libtest_check_order_reloc_siblings_c
+include $(LOCAL_PATH)/Android.build.testlib.mk
+
+# -----------------------------------------------------------------------------
+# ..._d.so
+# -----------------------------------------------------------------------------
+libtest_check_order_reloc_siblings_d_src_files := \
+    dlopen_check_order_reloc_answer_impl.cpp
+
+libtest_check_order_reloc_siblings_d_cflags := -D__ANSWER=3
+module := libtest_check_order_reloc_siblings_d
+include $(LOCAL_PATH)/Android.build.testlib.mk
+
+# -----------------------------------------------------------------------------
+# ..._e.so
+# -----------------------------------------------------------------------------
+libtest_check_order_reloc_siblings_e_src_files := \
+    dlopen_check_order_reloc_answer_impl.cpp
+
+libtest_check_order_reloc_siblings_e_cflags := -D__ANSWER=4
+module := libtest_check_order_reloc_siblings_e
+include $(LOCAL_PATH)/Android.build.testlib.mk
+
+# -----------------------------------------------------------------------------
+# ..._f.so <- get_answer()
+# -----------------------------------------------------------------------------
+libtest_check_order_reloc_siblings_f_src_files := \
+    dlopen_check_order_reloc_answer.cpp
+
+module := libtest_check_order_reloc_siblings_f
+include $(LOCAL_PATH)/Android.build.testlib.mk
+
+# -----------------------------------------------------------------------------
+# libtest_check_order_reloc_siblings.so
+# -----------------------------------------------------------------------------
+libtest_check_order_reloc_siblings_src_files := \
+    empty.cpp
+
+libtest_check_order_reloc_siblings_shared_libraries := \
+    libtest_check_order_reloc_siblings_1 \
+    libtest_check_order_reloc_siblings_2 \
+    libtest_check_order_reloc_siblings_3
+
+module := libtest_check_order_reloc_siblings
+include $(LOCAL_PATH)/Android.build.testlib.mk
diff --git a/tests/libs/Android.build.testlib.mk b/tests/libs/Android.build.testlib.mk
new file mode 100644
index 0000000..5b688e4
--- /dev/null
+++ b/tests/libs/Android.build.testlib.mk
@@ -0,0 +1,22 @@
+#
+# Copyright (C) 2014 The Android Open Source Project
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+build_target := SHARED_LIBRARY
+build_type := host
+include $(TEST_PATH)/Android.build.mk
+build_type := target
+include $(TEST_PATH)/Android.build.mk
+
diff --git a/tests/libs/Android.mk b/tests/libs/Android.mk
index ee97c61..7d959d4 100644
--- a/tests/libs/Android.mk
+++ b/tests/libs/Android.mk
@@ -17,6 +17,16 @@
 LOCAL_PATH := $(call my-dir)
 TEST_PATH := $(LOCAL_PATH)/..
 
+common_cppflags += -std=gnu++11
+common_additional_dependencies := \
+    $(LOCAL_PATH)/Android.mk \
+    $(LOCAL_PATH)/Android.build.dlext_testzip.mk \
+    $(LOCAL_PATH)/Android.build.dlopen_check_order_dlsym.mk \
+    $(LOCAL_PATH)/Android.build.dlopen_check_order_reloc_siblings.mk \
+    $(LOCAL_PATH)/Android.build.dlopen_check_order_reloc_main_executable.mk \
+    $(LOCAL_PATH)/Android.build.testlib.mk \
+    $(TEST_PATH)/Android.build.mk
+
 # -----------------------------------------------------------------------------
 # Library used by dlfcn tests.
 # -----------------------------------------------------------------------------
@@ -29,9 +39,7 @@
 
 module := no-elf-hash-table-library
 module_tag := optional
-build_type := target
-build_target := SHARED_LIBRARY
-include $(TEST_PATH)/Android.build.mk
+include $(LOCAL_PATH)/Android.build.testlib.mk
 endif
 
 # -----------------------------------------------------------------------------
@@ -45,15 +53,13 @@
 
 module := libdlext_test
 module_tag := optional
-build_type := target
-build_target := SHARED_LIBRARY
-include $(TEST_PATH)/Android.build.mk
+include $(LOCAL_PATH)/Android.build.testlib.mk
 
 # -----------------------------------------------------------------------------
 # create symlink to libdlext_test.so for symlink test
 # -----------------------------------------------------------------------------
 # Use = instead of := to defer the evaluation of $@
-$(LOCAL_INSTALLED_MODULE): PRIVATE_POST_INSTALL_CMD = \
+$(TARGET_OUT)/lib/libdlext_test.so: PRIVATE_POST_INSTALL_CMD = \
     $(hide) cd $(dir $@) && ln -sf $(notdir $@) libdlext_test_v2.so
 
 ifneq ($(TARGET_2ND_ARCH),)
@@ -62,6 +68,13 @@
     $(hide) cd $(dir $@) && ln -sf $(notdir $@) libdlext_test_v2.so
 endif
 
+# host symlinks
+$(HOST_OUT)/lib64/libdlext_test.so: PRIVATE_POST_INSTALL_CMD = \
+    $(hide) cd $(dir $@) && ln -sf $(notdir $@) libdlext_test_v2.so
+
+$(HOST_OUT)/lib/libdlext_test.so: PRIVATE_POST_INSTALL_CMD = \
+    $(hide) cd $(dir $@) && ln -sf $(notdir $@) libdlext_test_v2.so
+
 # -----------------------------------------------------------------------------
 # Library used by dlext tests - without GNU RELRO program header
 # -----------------------------------------------------------------------------
@@ -108,98 +121,51 @@
     dlopen_testlib_simple.cpp
 
 module := libtest_simple
-build_type := target
-build_target := SHARED_LIBRARY
-include $(TEST_PATH)/Android.build.mk
+include $(LOCAL_PATH)/Android.build.testlib.mk
 
 # -----------------------------------------------------------------------------
-# Libraries used by dlfcn tests to verify correct load order:
-# libtest_check_order_2_right.so
+# Library used by dlfcn nodelete tests
 # -----------------------------------------------------------------------------
-libtest_check_order_2_right_src_files := \
-    dlopen_testlib_answer.cpp
+libtest_nodelete_1_src_files := \
+    dlopen_nodelete_1.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
+module := libtest_nodelete_1
+include $(LOCAL_PATH)/Android.build.testlib.mk
 
 # -----------------------------------------------------------------------------
-# libtest_check_order_a.so
+# Library used by dlfcn nodelete tests
 # -----------------------------------------------------------------------------
-libtest_check_order_a_src_files := \
-    dlopen_testlib_answer.cpp
+libtest_nodelete_2_src_files := \
+    dlopen_nodelete_2.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
+module := libtest_nodelete_2
+include $(LOCAL_PATH)/Android.build.testlib.mk
 
 # -----------------------------------------------------------------------------
-# libtest_check_order_b.so
+# Library used by dlfcn nodelete tests
 # -----------------------------------------------------------------------------
-libtest_check_order_b_src_files := \
-    dlopen_testlib_answer.cpp
+libtest_nodelete_dt_flags_1_src_files := \
+    dlopen_nodelete_dt_flags_1.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_nodelete_dt_flags_1_ldflags := -Wl,-z,nodelete
+
+module := libtest_nodelete_dt_flags_1
+include $(LOCAL_PATH)/Android.build.testlib.mk
 
 # -----------------------------------------------------------------------------
-# libtest_check_order_c.so
+# Build libtest_check_order_dlsym.so with its dependencies.
 # -----------------------------------------------------------------------------
-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
+include $(LOCAL_PATH)/Android.build.dlopen_check_order_dlsym.mk
 
 # -----------------------------------------------------------------------------
-# libtest_check_order_d.so
+# Build libtest_check_order_siblings.so with its dependencies.
 # -----------------------------------------------------------------------------
-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
+include $(LOCAL_PATH)/Android.build.dlopen_check_order_reloc_siblings.mk
 
 # -----------------------------------------------------------------------------
-# libtest_check_order_left.so
+# Build libtest_check_order_root.so with its dependencies.
 # -----------------------------------------------------------------------------
-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
+include $(LOCAL_PATH)/Android.build.dlopen_check_order_reloc_main_executable.mk
 
 # -----------------------------------------------------------------------------
 # Library with dependency loop used by dlfcn tests
@@ -212,9 +178,7 @@
     libtest_with_dependency_loop_a
 
 module := libtest_with_dependency_loop
-build_type := target
-build_target := SHARED_LIBRARY
-include $(TEST_PATH)/Android.build.mk
+include $(LOCAL_PATH)/Android.build.testlib.mk
 
 # -----------------------------------------------------------------------------
 # libtest_with_dependency_loop_a.so
@@ -225,9 +189,7 @@
     libtest_with_dependency_loop_b_tmp
 
 module := libtest_with_dependency_loop_a
-build_type := target
-build_target := SHARED_LIBRARY
-include $(TEST_PATH)/Android.build.mk
+include $(LOCAL_PATH)/Android.build.testlib.mk
 
 # -----------------------------------------------------------------------------
 # libtest_with_dependency_loop_b.so
@@ -238,9 +200,7 @@
 libtest_with_dependency_loop_b_tmp_ldflags := -Wl,-soname=libtest_with_dependency_loop_b.so
 
 module := libtest_with_dependency_loop_b_tmp
-build_type := target
-build_target := SHARED_LIBRARY
-include $(TEST_PATH)/Android.build.mk
+include $(LOCAL_PATH)/Android.build.testlib.mk
 
 # -----------------------------------------------------------------------------
 # libtest_with_dependency_loop_b.so
@@ -249,9 +209,7 @@
 libtest_with_dependency_loop_b_shared_libraries := libtest_with_dependency_loop_c
 
 module := libtest_with_dependency_loop_b
-build_type := target
-build_target := SHARED_LIBRARY
-include $(TEST_PATH)/Android.build.mk
+include $(LOCAL_PATH)/Android.build.testlib.mk
 
 # -----------------------------------------------------------------------------
 # libtest_with_dependency_loop_c.so
@@ -262,9 +220,7 @@
     libtest_with_dependency_loop_a
 
 module := libtest_with_dependency_loop_c
-build_type := target
-build_target := SHARED_LIBRARY
-include $(TEST_PATH)/Android.build.mk
+include $(LOCAL_PATH)/Android.build.testlib.mk
 
 # -----------------------------------------------------------------------------
 # libtest_relo_check_dt_needed_order.so
@@ -279,15 +235,13 @@
 libtest_relo_check_dt_needed_order_src_files := dlopen_testlib_relo_check_dt_needed_order.cpp
 libtest_relo_check_dt_needed_order_1_src_files := dlopen_testlib_relo_check_dt_needed_order_1.cpp
 libtest_relo_check_dt_needed_order_2_src_files := dlopen_testlib_relo_check_dt_needed_order_2.cpp
-build_type := target
-build_target := SHARED_LIBRARY
 
 module := libtest_relo_check_dt_needed_order
-include $(TEST_PATH)/Android.build.mk
+include $(LOCAL_PATH)/Android.build.testlib.mk
 module := libtest_relo_check_dt_needed_order_1
-include $(TEST_PATH)/Android.build.mk
+include $(LOCAL_PATH)/Android.build.testlib.mk
 module := libtest_relo_check_dt_needed_order_2
-include $(TEST_PATH)/Android.build.mk
+include $(LOCAL_PATH)/Android.build.testlib.mk
 
 # -----------------------------------------------------------------------------
 # Library with dependency used by dlfcn tests
@@ -298,22 +252,30 @@
 libtest_with_dependency_shared_libraries := libdlext_test
 
 module := libtest_with_dependency
-build_type := target
-build_target := SHARED_LIBRARY
-include $(TEST_PATH)/Android.build.mk
+include $(LOCAL_PATH)/Android.build.testlib.mk
 
 # -----------------------------------------------------------------------------
 # Library used by ifunc tests
 # -----------------------------------------------------------------------------
+libtest_ifunc_src_files := \
+    dlopen_testlib_ifunc.c
+
+libtest_ifunc_clang_host := false
+module := libtest_ifunc
+build_target := SHARED_LIBRARY
+
+build_type := host
+include $(TEST_PATH)/Android.build.mk
+
 ifeq ($(TARGET_ARCH),$(filter $(TARGET_ARCH),x86 x86_64))
-    libtest_ifunc_src_files := \
-        dlopen_testlib_ifunc.c
+    ifeq ($(TARGET_ARCH),arm64)
+      libtest_ifunc_multilib := 64
+      # TODO: This is a workaround - remove it once gcc
+      # removes its Android ifunc checks
+      libtest_ifunc_cflags := -mglibc
+    endif
 
-    LOCAL_SDK_VERSION := current
-    module := libtest_ifunc
     build_type := target
-    build_target := SHARED_LIBRARY
-
     include $(TEST_PATH)/Android.build.mk
 endif
 
@@ -325,11 +287,43 @@
     atexit_testlib.cpp
 
 module := libtest_atexit
-build_target := SHARED_LIBRARY
-build_type := target
-include $(TEST_PATH)/Android.build.mk
-build_type := host
-include $(TEST_PATH)/Android.build.mk
+include $(LOCAL_PATH)/Android.build.testlib.mk
+
+# -----------------------------------------------------------------------------
+# This library is used by dl_load test to check symbol preempting
+# by main executable
+# -----------------------------------------------------------------------------
+libdl_preempt_test_1_src_files := dl_preempt_library_1.cpp
+
+module := libdl_preempt_test_1
+include $(LOCAL_PATH)/Android.build.testlib.mk
+
+# -----------------------------------------------------------------------------
+# This library is used by dl_load test to check symbol preempting
+# by libdl_preempt_test_1.so
+# -----------------------------------------------------------------------------
+libdl_preempt_test_2_src_files := dl_preempt_library_2.cpp
+
+module := libdl_preempt_test_2
+include $(LOCAL_PATH)/Android.build.testlib.mk
+
+# -----------------------------------------------------------------------------
+# Library with DF_1_GLOBAL
+# -----------------------------------------------------------------------------
+# TODO: re-enable arm once b/18137520 or b/18130452 are fixed
+ifeq ($(filter $(TARGET_ARCH),arm arm64),)
+libdl_test_df_1_global_src_files := dl_df_1_global.cpp
+libdl_test_df_1_global_ldflags := -fuse-ld=bfd -Wl,-z,global
+module := libdl_test_df_1_global
+include $(LOCAL_PATH)/Android.build.testlib.mk
+endif
+
+# -----------------------------------------------------------------------------
+# Library using symbol from libdl_test_df_1_global
+# -----------------------------------------------------------------------------
+libtest_dlsym_df_1_global_src_files := dl_df_1_use_global.cpp
+module := libtest_dlsym_df_1_global
+include $(LOCAL_PATH)/Android.build.testlib.mk
 
 # -----------------------------------------------------------------------------
 # Library with weak function
@@ -338,14 +332,4 @@
     dlsym_weak_function.cpp
 
 module := libtest_dlsym_weak_func
-build_target := SHARED_LIBRARY
-build_type := target
-include $(TEST_PATH)/Android.build.mk
-build_type := host
-include $(TEST_PATH)/Android.build.mk
-
-LOCAL_ADDITIONAL_DEPENDENCIES := \
-    $(LOCAL_PATH)/Android.mk \
-    $(LOCAL_PATH)/Android.build.dlext_testzip.mk \
-    $(LOCAL_PATH)/Android.build.testlib.mk \
-    $(TEST_PATH)/Android.build.mk
+include $(LOCAL_PATH)/Android.build.testlib.mk
diff --git a/tests/libs/dlopen_testlib_answer.cpp b/tests/libs/dl_df_1_global.cpp
similarity index 80%
copy from tests/libs/dlopen_testlib_answer.cpp
copy to tests/libs/dl_df_1_global.cpp
index a4d7504..39856fd 100644
--- a/tests/libs/dlopen_testlib_answer.cpp
+++ b/tests/libs/dl_df_1_global.cpp
@@ -14,12 +14,6 @@
  * limitations under the License.
  */
 
-extern "C" int dlopen_test_get_answer() {
-  return __ANSWER;
+extern "C" int dl_df_1_global_get_answer_impl() {
+  return 42;
 }
-
-#ifdef __ANSWER2
-extern "C" int dlopen_test_get_answer2() {
-  return __ANSWER2;
-}
-#endif
diff --git a/tests/libs/dlopen_testlib_answer.cpp b/tests/libs/dl_df_1_use_global.cpp
similarity index 78%
copy from tests/libs/dlopen_testlib_answer.cpp
copy to tests/libs/dl_df_1_use_global.cpp
index a4d7504..e14910d 100644
--- a/tests/libs/dlopen_testlib_answer.cpp
+++ b/tests/libs/dl_df_1_use_global.cpp
@@ -14,12 +14,10 @@
  * limitations under the License.
  */
 
-extern "C" int dlopen_test_get_answer() {
-  return __ANSWER;
+extern "C" int __attribute__((weak)) dl_df_1_global_get_answer_impl() {
+  return 0;
 }
 
-#ifdef __ANSWER2
-extern "C" int dlopen_test_get_answer2() {
-  return __ANSWER2;
+extern "C" int dl_df_1_global_get_answer() {
+  return dl_df_1_global_get_answer_impl();
 }
-#endif
diff --git a/tests/libs/dl_preempt_library_1.cpp b/tests/libs/dl_preempt_library_1.cpp
new file mode 100644
index 0000000..b4d81d5
--- /dev/null
+++ b/tests/libs/dl_preempt_library_1.cpp
@@ -0,0 +1,45 @@
+/*
+ * Copyright (C) 2014 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+// This one should be preempted by the function
+// defined in the main executable.
+extern "C" int __attribute__((weak)) main_global_default_serial() {
+  return 2716057;
+}
+
+// Even though this one is defined by the main
+// executable it should not be preempted
+// because of protected visibility
+extern "C" int __attribute__((weak, visibility("protected"))) main_global_protected_serial() {
+  return 3370318;
+}
+
+extern "C" int main_global_default_get_serial() {
+  return main_global_default_serial();
+}
+
+extern "C" int main_global_protected_get_serial() {
+  return main_global_protected_serial();
+}
+
+// Trying to preempt functions from a DT_NEEDED .so
+extern "C" int lib_global_default_serial() {
+  return 3370318;
+}
+
+extern "C" int lib_global_protected_serial() {
+  return 2716057;
+}
diff --git a/tests/libs/dl_preempt_library_2.cpp b/tests/libs/dl_preempt_library_2.cpp
new file mode 100644
index 0000000..8df9a16
--- /dev/null
+++ b/tests/libs/dl_preempt_library_2.cpp
@@ -0,0 +1,37 @@
+/*
+ * Copyright (C) 2014 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+// This one should be preempted by the function
+// defined in libdl_preempt_test_1.so
+extern "C" int __attribute__((weak)) lib_global_default_serial() {
+  return 2716057;
+}
+
+// Even though this one is defined by
+// libdl_preempt_test_1.so it should not be
+// preempted because of protected visibility
+extern "C" int __attribute__((weak,visibility("protected"))) lib_global_protected_serial() {
+  return 3370318;
+}
+
+extern "C" int lib_global_default_get_serial() {
+  return lib_global_default_serial();
+}
+
+extern "C" int lib_global_protected_get_serial() {
+  return lib_global_protected_serial();
+}
+
diff --git a/tests/libs/dlopen_testlib_answer.cpp b/tests/libs/dlopen_check_order_dlsym_answer.cpp
similarity index 87%
rename from tests/libs/dlopen_testlib_answer.cpp
rename to tests/libs/dlopen_check_order_dlsym_answer.cpp
index a4d7504..2ae6cf7 100644
--- a/tests/libs/dlopen_testlib_answer.cpp
+++ b/tests/libs/dlopen_check_order_dlsym_answer.cpp
@@ -14,12 +14,12 @@
  * limitations under the License.
  */
 
-extern "C" int dlopen_test_get_answer() {
+extern "C" int check_order_dlsym_get_answer() {
   return __ANSWER;
 }
 
 #ifdef __ANSWER2
-extern "C" int dlopen_test_get_answer2() {
+extern "C" int check_order_dlsym_get_answer2() {
   return __ANSWER2;
 }
 #endif
diff --git a/tests/libs/dlopen_testlib_answer.cpp b/tests/libs/dlopen_check_order_reloc_answer.cpp
similarity index 77%
copy from tests/libs/dlopen_testlib_answer.cpp
copy to tests/libs/dlopen_check_order_reloc_answer.cpp
index a4d7504..036670b 100644
--- a/tests/libs/dlopen_testlib_answer.cpp
+++ b/tests/libs/dlopen_check_order_reloc_answer.cpp
@@ -14,12 +14,10 @@
  * limitations under the License.
  */
 
-extern "C" int dlopen_test_get_answer() {
-  return __ANSWER;
+extern "C" int __attribute__((weak)) check_order_reloc_get_answer_impl() {
+  return 0;
 }
 
-#ifdef __ANSWER2
-extern "C" int dlopen_test_get_answer2() {
-  return __ANSWER2;
+extern "C" int check_order_reloc_get_answer() {
+  return check_order_reloc_get_answer_impl();
 }
-#endif
diff --git a/tests/libs/dlopen_testlib_answer.cpp b/tests/libs/dlopen_check_order_reloc_answer_impl.cpp
similarity index 82%
copy from tests/libs/dlopen_testlib_answer.cpp
copy to tests/libs/dlopen_check_order_reloc_answer_impl.cpp
index a4d7504..324b905 100644
--- a/tests/libs/dlopen_testlib_answer.cpp
+++ b/tests/libs/dlopen_check_order_reloc_answer_impl.cpp
@@ -14,12 +14,6 @@
  * limitations under the License.
  */
 
-extern "C" int dlopen_test_get_answer() {
+extern "C" int check_order_reloc_get_answer_impl() {
   return __ANSWER;
 }
-
-#ifdef __ANSWER2
-extern "C" int dlopen_test_get_answer2() {
-  return __ANSWER2;
-}
-#endif
diff --git a/tests/libs/dlopen_testlib_answer.cpp b/tests/libs/dlopen_check_order_reloc_nephew_answer.cpp
similarity index 80%
copy from tests/libs/dlopen_testlib_answer.cpp
copy to tests/libs/dlopen_check_order_reloc_nephew_answer.cpp
index a4d7504..065d1be 100644
--- a/tests/libs/dlopen_testlib_answer.cpp
+++ b/tests/libs/dlopen_check_order_reloc_nephew_answer.cpp
@@ -14,12 +14,8 @@
  * limitations under the License.
  */
 
-extern "C" int dlopen_test_get_answer() {
-  return __ANSWER;
-}
+extern "C" int check_order_reloc_get_answer_impl();
 
-#ifdef __ANSWER2
-extern "C" int dlopen_test_get_answer2() {
-  return __ANSWER2;
+extern "C" int check_order_reloc_nephew_get_answer() {
+  return check_order_reloc_get_answer_impl();
 }
-#endif
diff --git a/tests/libs/dlopen_testlib_answer.cpp b/tests/libs/dlopen_check_order_reloc_root_answer.cpp
similarity index 79%
copy from tests/libs/dlopen_testlib_answer.cpp
copy to tests/libs/dlopen_check_order_reloc_root_answer.cpp
index a4d7504..b21abd7 100644
--- a/tests/libs/dlopen_testlib_answer.cpp
+++ b/tests/libs/dlopen_check_order_reloc_root_answer.cpp
@@ -14,12 +14,8 @@
  * limitations under the License.
  */
 
-extern "C" int dlopen_test_get_answer() {
-  return __ANSWER;
-}
+extern "C" int check_order_reloc_root_get_answer_impl();
 
-#ifdef __ANSWER2
-extern "C" int dlopen_test_get_answer2() {
-  return __ANSWER2;
+extern "C" int check_order_reloc_root_get_answer() {
+  return check_order_reloc_root_get_answer_impl();
 }
-#endif
diff --git a/tests/libs/dlopen_testlib_answer.cpp b/tests/libs/dlopen_check_order_reloc_root_answer_impl.cpp
similarity index 82%
copy from tests/libs/dlopen_testlib_answer.cpp
copy to tests/libs/dlopen_check_order_reloc_root_answer_impl.cpp
index a4d7504..25fb9ac 100644
--- a/tests/libs/dlopen_testlib_answer.cpp
+++ b/tests/libs/dlopen_check_order_reloc_root_answer_impl.cpp
@@ -14,12 +14,6 @@
  * limitations under the License.
  */
 
-extern "C" int dlopen_test_get_answer() {
+extern "C" int check_order_reloc_root_get_answer_impl() {
   return __ANSWER;
 }
-
-#ifdef __ANSWER2
-extern "C" int dlopen_test_get_answer2() {
-  return __ANSWER2;
-}
-#endif
diff --git a/tests/libs/dlopen_testlib_answer.cpp b/tests/libs/dlopen_nodelete_1.cpp
similarity index 64%
copy from tests/libs/dlopen_testlib_answer.cpp
copy to tests/libs/dlopen_nodelete_1.cpp
index a4d7504..9438978 100644
--- a/tests/libs/dlopen_testlib_answer.cpp
+++ b/tests/libs/dlopen_nodelete_1.cpp
@@ -14,12 +14,18 @@
  * limitations under the License.
  */
 
-extern "C" int dlopen_test_get_answer() {
-  return __ANSWER;
+#include <stdint.h>
+#include <stdlib.h>
+
+uint32_t dlopen_nodelete_1_taxicab_number = 1729;
+static bool* unload_flag_ptr = nullptr;
+
+extern "C" void dlopen_nodelete_1_set_unload_flag_ptr(bool* ptr) {
+  unload_flag_ptr = ptr;
 }
 
-#ifdef __ANSWER2
-extern "C" int dlopen_test_get_answer2() {
-  return __ANSWER2;
+static void __attribute__((destructor)) unload_guard() {
+  if (unload_flag_ptr != nullptr) {
+    *unload_flag_ptr = true;
+  }
 }
-#endif
diff --git a/tests/libs/dlopen_testlib_answer.cpp b/tests/libs/dlopen_nodelete_2.cpp
similarity index 64%
copy from tests/libs/dlopen_testlib_answer.cpp
copy to tests/libs/dlopen_nodelete_2.cpp
index a4d7504..b5ab5c1 100644
--- a/tests/libs/dlopen_testlib_answer.cpp
+++ b/tests/libs/dlopen_nodelete_2.cpp
@@ -14,12 +14,18 @@
  * limitations under the License.
  */
 
-extern "C" int dlopen_test_get_answer() {
-  return __ANSWER;
+#include <stdint.h>
+#include <stdlib.h>
+
+uint32_t dlopen_nodelete_2_taxicab_number = 1729;
+static bool* unload_flag_ptr = nullptr;
+
+extern "C" void dlopen_nodelete_2_set_unload_flag_ptr(bool* ptr) {
+  unload_flag_ptr = ptr;
 }
 
-#ifdef __ANSWER2
-extern "C" int dlopen_test_get_answer2() {
-  return __ANSWER2;
+static void __attribute__((destructor)) unload_guard() {
+  if (unload_flag_ptr != nullptr) {
+    *unload_flag_ptr = true;
+  }
 }
-#endif
diff --git a/tests/libs/dlopen_testlib_answer.cpp b/tests/libs/dlopen_nodelete_dt_flags_1.cpp
similarity index 66%
copy from tests/libs/dlopen_testlib_answer.cpp
copy to tests/libs/dlopen_nodelete_dt_flags_1.cpp
index a4d7504..39c0a7e 100644
--- a/tests/libs/dlopen_testlib_answer.cpp
+++ b/tests/libs/dlopen_nodelete_dt_flags_1.cpp
@@ -14,12 +14,17 @@
  * limitations under the License.
  */
 
-extern "C" int dlopen_test_get_answer() {
-  return __ANSWER;
+#include <stdint.h>
+#include <stdlib.h>
+
+static bool* unload_flag_ptr = nullptr;
+
+extern "C" void dlopen_nodelete_dt_flags_1_set_unload_flag_ptr(bool* ptr) {
+  unload_flag_ptr = ptr;
 }
 
-#ifdef __ANSWER2
-extern "C" int dlopen_test_get_answer2() {
-  return __ANSWER2;
+static void __attribute__((destructor)) unload_guard() {
+  if (unload_flag_ptr != nullptr) {
+    *unload_flag_ptr = true;
+  }
 }
-#endif
diff --git a/tests/libs/dlopen_testlib_simple.cpp b/tests/libs/dlopen_testlib_simple.cpp
index afe54b4..3226955 100644
--- a/tests/libs/dlopen_testlib_simple.cpp
+++ b/tests/libs/dlopen_testlib_simple.cpp
@@ -14,10 +14,11 @@
  * limitations under the License.
  */
 
+#include <stdint.h>
 #include <stdlib.h>
 
 uint32_t dlopen_testlib_taxicab_number = 1729;
 
-bool dlopen_testlib_simple_func() {
+extern "C" bool dlopen_testlib_simple_func() {
   return true;
 }