merge in jb-mr2-release history after reset to jb-mr2-dev
diff --git a/libc/Android.mk b/libc/Android.mk
index f146759..21d3089 100644
--- a/libc/Android.mk
+++ b/libc/Android.mk
@@ -111,35 +111,8 @@
 	string/strspn.c \
 	string/strstr.c \
 	string/strtok.c \
-	wchar/wcpcpy.c \
-	wchar/wcpncpy.c \
-	wchar/wcscasecmp.c \
-	wchar/wcscat.c \
-	wchar/wcschr.c \
-	wchar/wcscmp.c \
-	wchar/wcscpy.c \
-	wchar/wcscspn.c \
-	wchar/wcsdup.c \
-	wchar/wcslcat.c \
-	wchar/wcslcpy.c \
-	wchar/wcslen.c \
-	wchar/wcsncasecmp.c \
-	wchar/wcsncat.c \
-	wchar/wcsncmp.c \
-	wchar/wcsncpy.c \
-	wchar/wcsnlen.c \
-	wchar/wcspbrk.c \
-	wchar/wcsrchr.c \
-	wchar/wcsspn.c \
-	wchar/wcsstr.c \
-	wchar/wcstok.c \
 	wchar/wcswidth.c \
 	wchar/wcsxfrm.c \
-	wchar/wmemchr.c \
-	wchar/wmemcmp.c \
-	wchar/wmemcpy.c \
-	wchar/wmemmove.c \
-	wchar/wmemset.c \
 	tzcode/asctime.c \
 	tzcode/difftime.c \
 	tzcode/localtime.c \
@@ -318,6 +291,33 @@
 
 libc_upstream_freebsd_src_files := \
     upstream-freebsd/lib/libc/stdlib/realpath.c \
+    upstream-freebsd/lib/libc/string/wcpcpy.c \
+    upstream-freebsd/lib/libc/string/wcpncpy.c \
+    upstream-freebsd/lib/libc/string/wcscasecmp.c \
+    upstream-freebsd/lib/libc/string/wcscat.c \
+    upstream-freebsd/lib/libc/string/wcschr.c \
+    upstream-freebsd/lib/libc/string/wcscmp.c \
+    upstream-freebsd/lib/libc/string/wcscpy.c \
+    upstream-freebsd/lib/libc/string/wcscspn.c \
+    upstream-freebsd/lib/libc/string/wcsdup.c \
+    upstream-freebsd/lib/libc/string/wcslcat.c \
+    upstream-freebsd/lib/libc/string/wcslcpy.c \
+    upstream-freebsd/lib/libc/string/wcslen.c \
+    upstream-freebsd/lib/libc/string/wcsncasecmp.c \
+    upstream-freebsd/lib/libc/string/wcsncat.c \
+    upstream-freebsd/lib/libc/string/wcsncmp.c \
+    upstream-freebsd/lib/libc/string/wcsncpy.c \
+    upstream-freebsd/lib/libc/string/wcsnlen.c \
+    upstream-freebsd/lib/libc/string/wcspbrk.c \
+    upstream-freebsd/lib/libc/string/wcsrchr.c \
+    upstream-freebsd/lib/libc/string/wcsspn.c \
+    upstream-freebsd/lib/libc/string/wcsstr.c \
+    upstream-freebsd/lib/libc/string/wcstok.c \
+    upstream-freebsd/lib/libc/string/wmemchr.c \
+    upstream-freebsd/lib/libc/string/wmemcmp.c \
+    upstream-freebsd/lib/libc/string/wmemcpy.c \
+    upstream-freebsd/lib/libc/string/wmemmove.c \
+    upstream-freebsd/lib/libc/string/wmemset.c \
 
 libc_upstream_netbsd_src_files := \
     upstream-netbsd/common/lib/libc/hash/sha1/sha1.c \
diff --git a/libc/arch-arm/bionic/memcpy.a15.S b/libc/arch-arm/bionic/memcpy.a15.S
index d1bfb7c..516e20c 100644
--- a/libc/arch-arm/bionic/memcpy.a15.S
+++ b/libc/arch-arm/bionic/memcpy.a15.S
@@ -26,12 +26,6 @@
  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-#if (defined (__OPTIMIZE_SIZE__) || defined (PREFER_SIZE_OVER_SPEED) || \
-     (!(defined (__ARM_ARCH_7A__))))
-
-        /* Do nothing here. See memcpy-stub.c in the same directory. */
-
-#else
     /* Prototype: void *memcpy (void *dst, const void *src, size_t count).  */
 
         /* Use the version of memcpy implemented using LDRD and STRD.
@@ -50,16 +44,12 @@
        destination register must be even and the second consecutive in
        ARM state, but not in Thumb state.  */
 
+#include <machine/cpu-features.h>
+#include <machine/asm.h>
+
         .syntax         unified
 
-#if defined (__thumb__)
-        .thumb
-        .thumb_func
-#endif
-
-        .global memcpy
-        .type   memcpy, %function
-memcpy:
+ENTRY(memcpy)
 
        /* Assumes that n >= 0, and dst, src are valid pointers.
           If there is at least 8 bytes to copy, use LDRD/STRD.
@@ -69,12 +59,16 @@
           When less than 8 left, copy a word and then byte by byte.  */
 
        /* Save registers (r0 holds the return value):
-          optimized push {r0, r4, r5, lr}.
+          optimized push {r0, r4, r5, r6, r7, lr}.
           To try and improve performance, stack layout changed,
           i.e., not keeping the stack looking like users expect
           (highest numbered register at highest address).  */
-        push {r0, lr}
-        strd r4, r5, [sp, #-8]!
+        .save   {r0, lr}
+        push    {r0, lr}
+        .save   {r4, r5}
+        strd    r4, r5, [sp, #-8]!
+        .save   {r6, r7}
+        strd    r6, r7, [sp, #-8]!
 
        /* TODO: Add debug frame directives.
           We don't need exception unwind directives, because the code below
@@ -194,9 +188,11 @@
         strbcs  r5, [r0]
 
 return:
-        /* Restore registers: optimized pop {r0, r4, r5, pc}   */
+        /* Restore registers: optimized pop {r0, r4, r5, r6, r7, pc}   */
+        /* This is the only return point of memcpy.  */
+        ldrd r6, r7, [sp], #8
         ldrd r4, r5, [sp], #8
-        pop {r0, pc}           /* This is the only return point of memcpy.  */
+        pop {r0, pc}
 
 #ifndef __ARM_FEATURE_UNALIGNED
 
@@ -223,12 +219,6 @@
        /* Get here if there is more than 8 bytes to copy.
           The number of bytes to copy is r2+8, r2 >= 0.  */
 
-       /* Save registers: push { r6, r7 }.
-          We need additional registers for LDRD and STRD, because in ARM state
-          the first destination register must be even and the second
-      consecutive.  */
-       strd     r6, r7, [sp, #-8]!
-
        subs     r2, r2, #56
        blt      4f         /* Go to misaligned copy of less than 64 bytes.  */
 
@@ -259,10 +249,6 @@
        /* Restore the count if there is more than 7 bytes to copy.  */
         adds    r2, r2, #56
 
-       /* If less than 8 bytes to copy,
-          restore registers saved for this loop: optimized poplt { r6, r7 }. */
-        itt     lt
-        ldrdlt  r6, r7, [sp], #8
         blt     6f          /* Go to misaligned copy of less than 8 bytes.  */
 
 5:
@@ -278,9 +264,6 @@
         subs    r2, r2, #8
         bge     5b                        /* If there is more to copy.  */
 
-        /* Restore registers saved for this loop: optimized pop { r6, r7 }.  */
-        ldrd    r6, r7, [sp], #8
-
 6:
         /* Get here if there less than 8 bytes to copy (-8 <= r2 < 0)
            and they are misaligned.  */
@@ -420,4 +403,4 @@
 
 #endif  /* not __ARM_FEATURE_UNALIGNED  */
 
-#endif  /* memcpy */
+END(memcpy)
diff --git a/libc/include/wchar.h b/libc/include/wchar.h
index ef88e04..a4e19f0 100644
--- a/libc/include/wchar.h
+++ b/libc/include/wchar.h
@@ -149,6 +149,11 @@
 extern wint_t		 towctrans(wint_t, wctrans_t);
 extern wctrans_t	 wctrans (const char *);
 
+#if _XOPEN_SOURCE >= 700 || _POSIX_C_SOURCE >= 200809L
+wchar_t* wcsdup(const wchar_t*);
+size_t wcsnlen(const wchar_t*, size_t);
+#endif
+
 __END_DECLS
 
 #endif /* _WCHAR_H_ */
diff --git a/libc/wchar/wcpcpy.c b/libc/upstream-freebsd/lib/libc/string/wcpcpy.c
similarity index 100%
rename from libc/wchar/wcpcpy.c
rename to libc/upstream-freebsd/lib/libc/string/wcpcpy.c
diff --git a/libc/wchar/wcpncpy.c b/libc/upstream-freebsd/lib/libc/string/wcpncpy.c
similarity index 100%
rename from libc/wchar/wcpncpy.c
rename to libc/upstream-freebsd/lib/libc/string/wcpncpy.c
diff --git a/libc/wchar/wcscasecmp.c b/libc/upstream-freebsd/lib/libc/string/wcscasecmp.c
similarity index 100%
rename from libc/wchar/wcscasecmp.c
rename to libc/upstream-freebsd/lib/libc/string/wcscasecmp.c
diff --git a/libc/wchar/wcscat.c b/libc/upstream-freebsd/lib/libc/string/wcscat.c
similarity index 100%
rename from libc/wchar/wcscat.c
rename to libc/upstream-freebsd/lib/libc/string/wcscat.c
diff --git a/libc/wchar/wcschr.c b/libc/upstream-freebsd/lib/libc/string/wcschr.c
similarity index 100%
rename from libc/wchar/wcschr.c
rename to libc/upstream-freebsd/lib/libc/string/wcschr.c
diff --git a/libc/wchar/wcscmp.c b/libc/upstream-freebsd/lib/libc/string/wcscmp.c
similarity index 100%
rename from libc/wchar/wcscmp.c
rename to libc/upstream-freebsd/lib/libc/string/wcscmp.c
diff --git a/libc/wchar/wcscpy.c b/libc/upstream-freebsd/lib/libc/string/wcscpy.c
similarity index 100%
rename from libc/wchar/wcscpy.c
rename to libc/upstream-freebsd/lib/libc/string/wcscpy.c
diff --git a/libc/wchar/wcscspn.c b/libc/upstream-freebsd/lib/libc/string/wcscspn.c
similarity index 100%
rename from libc/wchar/wcscspn.c
rename to libc/upstream-freebsd/lib/libc/string/wcscspn.c
diff --git a/libc/wchar/wcsdup.c b/libc/upstream-freebsd/lib/libc/string/wcsdup.c
similarity index 100%
rename from libc/wchar/wcsdup.c
rename to libc/upstream-freebsd/lib/libc/string/wcsdup.c
diff --git a/libc/wchar/wcslcat.c b/libc/upstream-freebsd/lib/libc/string/wcslcat.c
similarity index 100%
rename from libc/wchar/wcslcat.c
rename to libc/upstream-freebsd/lib/libc/string/wcslcat.c
diff --git a/libc/wchar/wcslcpy.c b/libc/upstream-freebsd/lib/libc/string/wcslcpy.c
similarity index 100%
rename from libc/wchar/wcslcpy.c
rename to libc/upstream-freebsd/lib/libc/string/wcslcpy.c
diff --git a/libc/wchar/wcslen.c b/libc/upstream-freebsd/lib/libc/string/wcslen.c
similarity index 100%
rename from libc/wchar/wcslen.c
rename to libc/upstream-freebsd/lib/libc/string/wcslen.c
diff --git a/libc/wchar/wcsncasecmp.c b/libc/upstream-freebsd/lib/libc/string/wcsncasecmp.c
similarity index 100%
rename from libc/wchar/wcsncasecmp.c
rename to libc/upstream-freebsd/lib/libc/string/wcsncasecmp.c
diff --git a/libc/wchar/wcsncat.c b/libc/upstream-freebsd/lib/libc/string/wcsncat.c
similarity index 100%
rename from libc/wchar/wcsncat.c
rename to libc/upstream-freebsd/lib/libc/string/wcsncat.c
diff --git a/libc/wchar/wcsncmp.c b/libc/upstream-freebsd/lib/libc/string/wcsncmp.c
similarity index 100%
rename from libc/wchar/wcsncmp.c
rename to libc/upstream-freebsd/lib/libc/string/wcsncmp.c
diff --git a/libc/wchar/wcsncpy.c b/libc/upstream-freebsd/lib/libc/string/wcsncpy.c
similarity index 100%
rename from libc/wchar/wcsncpy.c
rename to libc/upstream-freebsd/lib/libc/string/wcsncpy.c
diff --git a/libc/wchar/wcsnlen.c b/libc/upstream-freebsd/lib/libc/string/wcsnlen.c
similarity index 100%
rename from libc/wchar/wcsnlen.c
rename to libc/upstream-freebsd/lib/libc/string/wcsnlen.c
diff --git a/libc/wchar/wcspbrk.c b/libc/upstream-freebsd/lib/libc/string/wcspbrk.c
similarity index 100%
rename from libc/wchar/wcspbrk.c
rename to libc/upstream-freebsd/lib/libc/string/wcspbrk.c
diff --git a/libc/wchar/wcsrchr.c b/libc/upstream-freebsd/lib/libc/string/wcsrchr.c
similarity index 100%
rename from libc/wchar/wcsrchr.c
rename to libc/upstream-freebsd/lib/libc/string/wcsrchr.c
diff --git a/libc/wchar/wcsspn.c b/libc/upstream-freebsd/lib/libc/string/wcsspn.c
similarity index 100%
rename from libc/wchar/wcsspn.c
rename to libc/upstream-freebsd/lib/libc/string/wcsspn.c
diff --git a/libc/wchar/wcsstr.c b/libc/upstream-freebsd/lib/libc/string/wcsstr.c
similarity index 100%
rename from libc/wchar/wcsstr.c
rename to libc/upstream-freebsd/lib/libc/string/wcsstr.c
diff --git a/libc/wchar/wcstok.c b/libc/upstream-freebsd/lib/libc/string/wcstok.c
similarity index 100%
rename from libc/wchar/wcstok.c
rename to libc/upstream-freebsd/lib/libc/string/wcstok.c
diff --git a/libc/wchar/wmemchr.c b/libc/upstream-freebsd/lib/libc/string/wmemchr.c
similarity index 100%
rename from libc/wchar/wmemchr.c
rename to libc/upstream-freebsd/lib/libc/string/wmemchr.c
diff --git a/libc/wchar/wmemcmp.c b/libc/upstream-freebsd/lib/libc/string/wmemcmp.c
similarity index 100%
rename from libc/wchar/wmemcmp.c
rename to libc/upstream-freebsd/lib/libc/string/wmemcmp.c
diff --git a/libc/wchar/wmemcpy.c b/libc/upstream-freebsd/lib/libc/string/wmemcpy.c
similarity index 100%
rename from libc/wchar/wmemcpy.c
rename to libc/upstream-freebsd/lib/libc/string/wmemcpy.c
diff --git a/libc/wchar/wmemmove.c b/libc/upstream-freebsd/lib/libc/string/wmemmove.c
similarity index 100%
rename from libc/wchar/wmemmove.c
rename to libc/upstream-freebsd/lib/libc/string/wmemmove.c
diff --git a/libc/wchar/wmemset.c b/libc/upstream-freebsd/lib/libc/string/wmemset.c
similarity index 100%
rename from libc/wchar/wmemset.c
rename to libc/upstream-freebsd/lib/libc/string/wmemset.c
diff --git a/libc/zoneinfo/tzdata b/libc/zoneinfo/tzdata
index 019650e..bd59e05 100644
--- a/libc/zoneinfo/tzdata
+++ b/libc/zoneinfo/tzdata
Binary files differ
diff --git a/linker/debugger.cpp b/linker/debugger.cpp
index 492ca4b..586cd2f 100644
--- a/linker/debugger.cpp
+++ b/linker/debugger.cpp
@@ -174,7 +174,7 @@
  * Catches fatal signals so we can ask debuggerd to ptrace us before
  * we crash.
  */
-void debugger_signal_handler(int n, siginfo_t* info, void*) {
+void debuggerd_signal_handler(int n, siginfo_t* info, void*) {
     /*
      * It's possible somebody cleared the SA_SIGINFO flag, which would mean
      * our "info" arg holds an undefined value.
@@ -245,10 +245,10 @@
     }
 }
 
-void debugger_init() {
+void debuggerd_init() {
     struct sigaction act;
     memset(&act, 0, sizeof(act));
-    act.sa_sigaction = debugger_signal_handler;
+    act.sa_sigaction = debuggerd_signal_handler;
     act.sa_flags = SA_RESTART | SA_SIGINFO;
     sigemptyset(&act.sa_mask);
 
diff --git a/linker/dlfcn.cpp b/linker/dlfcn.cpp
index a5f8944..0b38ec4 100644
--- a/linker/dlfcn.cpp
+++ b/linker/dlfcn.cpp
@@ -64,7 +64,7 @@
   ScopedPthreadMutexLocker locker(&gDlMutex);
   soinfo* result = do_dlopen(filename, flags);
   if (result == NULL) {
-    __bionic_format_dlerror("dlopen failed", linker_get_error());
+    __bionic_format_dlerror("dlopen failed", linker_get_error_buffer());
     return NULL;
   }
   return result;
@@ -85,18 +85,18 @@
   soinfo* found = NULL;
   Elf32_Sym* sym = NULL;
   if (handle == RTLD_DEFAULT) {
-    sym = lookup(symbol, &found, NULL);
+    sym = dlsym_linear_lookup(symbol, &found, NULL);
   } else if (handle == RTLD_NEXT) {
     void* ret_addr = __builtin_return_address(0);
     soinfo* si = find_containing_library(ret_addr);
 
     sym = NULL;
     if (si && si->next) {
-      sym = lookup(symbol, &found, si->next);
+      sym = dlsym_linear_lookup(symbol, &found, si->next);
     }
   } else {
-    found = (soinfo*) handle;
-    sym = soinfo_lookup(found, symbol);
+    found = reinterpret_cast<soinfo*>(handle);
+    sym = dlsym_handle_lookup(found, symbol);
   }
 
   if (sym != NULL) {
@@ -131,7 +131,7 @@
   info->dli_fbase = (void*) si->base;
 
   // Determine if any symbol in the library contains the specified address.
-  Elf32_Sym *sym = soinfo_find_symbol(si, addr);
+  Elf32_Sym *sym = dladdr_find_symbol(si, addr);
   if (sym != NULL) {
     info->dli_sname = si->strtab + sym->st_name;
     info->dli_saddr = (void*)(si->load_bias + sym->st_value);
diff --git a/linker/linker.cpp b/linker/linker.cpp
index d36b1f6..db0c9f1 100755
--- a/linker/linker.cpp
+++ b/linker/linker.cpp
@@ -41,7 +41,6 @@
 
 // Private C library headers.
 #include <private/bionic_tls.h>
-#include <private/debug_format.h>
 #include <private/KernelArgumentBlock.h>
 #include <private/logd.h>
 #include <private/ScopedPthreadMutexLocker.h>
@@ -87,9 +86,9 @@
 static struct soinfo_pool_t* gSoInfoPools = NULL;
 static soinfo* gSoInfoFreeList = NULL;
 
-static soinfo *solist = &libdl_info;
-static soinfo *sonext = &libdl_info;
-static soinfo *somain; /* main process, always the one after libdl_info */
+static soinfo* solist = &libdl_info;
+static soinfo* sonext = &libdl_info;
+static soinfo* somain; /* main process, always the one after libdl_info */
 
 static const char* const gSoPaths[] = {
   "/vendor/lib",
@@ -103,9 +102,9 @@
 static char gLdPreloadsBuffer[LDPRELOAD_BUFSIZE];
 static const char* gLdPreloadNames[LDPRELOAD_MAX + 1];
 
-static soinfo *preloads[LDPRELOAD_MAX + 1];
+static soinfo* gLdPreloads[LDPRELOAD_MAX + 1];
 
-static int debug_verbosity;
+__LIBC_HIDDEN__ int gLdDebugVerbosity;
 
 enum RelocationKind {
     kRelocAbsolute = 0,
@@ -158,17 +157,15 @@
 
 static char tmp_err_buf[768];
 static char __linker_dl_err_buf[768];
-#define DL_ERR(fmt, x...) \
-    do { \
-        __libc_format_buffer(__linker_dl_err_buf, sizeof(__linker_dl_err_buf), fmt, ##x); \
-        /* If LD_DEBUG is set high enough, send every dlerror(3) message to the log. */ \
-        DEBUG(fmt "\n", ##x); \
-    } while(0)
 
-const char* linker_get_error() {
+char* linker_get_error_buffer() {
   return &__linker_dl_err_buf[0];
 }
 
+size_t linker_get_error_buffer_size() {
+  return sizeof(__linker_dl_err_buf);
+}
+
 /*
  * This function is an empty stub where GDB locates a breakpoint to get notified
  * about linker activity.
@@ -332,13 +329,13 @@
 
     TRACE("name %s: freeing soinfo @ %p\n", si->name, si);
 
-    for(trav = solist; trav != NULL; trav = trav->next){
+    for (trav = solist; trav != NULL; trav = trav->next) {
         if (trav == si)
             break;
         prev = trav;
     }
     if (trav == NULL) {
-        /* si was not ni solist */
+        /* si was not in solist */
         DL_ERR("name \"%s\" is not in solist!", si->name);
         return;
     }
@@ -347,7 +344,9 @@
        always the static libdl_info.
     */
     prev->next = si->next;
-    if (si == sonext) sonext = prev;
+    if (si == sonext) {
+        sonext = prev;
+    }
     si->next = gSoInfoFreeList;
     gSoInfoFreeList = si;
 }
@@ -440,27 +439,27 @@
 
 #endif
 
-static Elf32_Sym *soinfo_elf_lookup(soinfo *si, unsigned hash, const char *name)
-{
-    Elf32_Sym *s;
-    Elf32_Sym *symtab = si->symtab;
-    const char *strtab = si->strtab;
+static Elf32_Sym* soinfo_elf_lookup(soinfo* si, unsigned hash, const char* name) {
+    Elf32_Sym* s;
+    Elf32_Sym* symtab = si->symtab;
+    const char* strtab = si->strtab;
     unsigned n;
 
     TRACE_TYPE(LOOKUP, "SEARCH %s in %s@0x%08x %08x %d\n",
                name, si->name, si->base, hash, hash % si->nbucket);
     n = hash % si->nbucket;
 
-    for(n = si->bucket[hash % si->nbucket]; n != 0; n = si->chain[n]){
+    for (n = si->bucket[hash % si->nbucket]; n != 0; n = si->chain[n]) {
         s = symtab + n;
-        if(strcmp(strtab + s->st_name, name)) continue;
+        if (strcmp(strtab + s->st_name, name)) continue;
 
             /* only concern ourselves with global and weak symbol definitions */
         switch(ELF32_ST_BIND(s->st_info)){
         case STB_GLOBAL:
         case STB_WEAK:
-            if(s->st_shndx == SHN_UNDEF)
+            if (s->st_shndx == SHN_UNDEF) {
                 continue;
+            }
 
             TRACE_TYPE(LOOKUP, "FOUND %s in %s (%08x) %d\n",
                        name, si->name, s->st_value, s->st_size);
@@ -471,9 +470,8 @@
     return NULL;
 }
 
-static unsigned elfhash(const char *_name)
-{
-    const unsigned char *name = (const unsigned char *) _name;
+static unsigned elfhash(const char* _name) {
+    const unsigned char* name = (const unsigned char*) _name;
     unsigned h = 0, g;
 
     while(*name) {
@@ -485,13 +483,9 @@
     return h;
 }
 
-static Elf32_Sym *
-soinfo_do_lookup(soinfo *si, const char *name, soinfo **lsi,
-                 soinfo *needed[])
-{
+static Elf32_Sym* soinfo_do_lookup(soinfo* si, const char* name, soinfo** lsi, soinfo* needed[]) {
     unsigned elf_hash = elfhash(name);
-    Elf32_Sym *s = NULL;
-    int i;
+    Elf32_Sym* s = NULL;
 
     if (si != NULL && somain != NULL) {
 
@@ -559,15 +553,15 @@
     }
 
     /* Next, look for it in the preloads list */
-    for(i = 0; preloads[i] != NULL; i++) {
-        s = soinfo_elf_lookup(preloads[i], elf_hash, name);
-        if(s != NULL) {
-            *lsi = preloads[i];
+    for (int i = 0; gLdPreloads[i] != NULL; i++) {
+        s = soinfo_elf_lookup(gLdPreloads[i], elf_hash, name);
+        if (s != NULL) {
+            *lsi = gLdPreloads[i];
             goto done;
         }
     }
 
-    for(i = 0; needed[i] != NULL; i++) {
+    for (int i = 0; needed[i] != NULL; i++) {
         DEBUG("%s: looking up %s in %s\n",
               si->name, name, needed[i]->name);
         s = soinfo_elf_lookup(needed[i], elf_hash, name);
@@ -578,7 +572,7 @@
     }
 
 done:
-    if(s != NULL) {
+    if (s != NULL) {
         TRACE_TYPE(LOOKUP, "si %s sym %s s->st_value = 0x%08x, "
                    "found in %s, base = 0x%08x, load bias = 0x%08x\n",
                    si->name, name, s->st_value,
@@ -589,17 +583,26 @@
     return NULL;
 }
 
-/* This is used by dl_sym().  It performs symbol lookup only within the
+/* This is used by dlsym(3).  It performs symbol lookup only within the
    specified soinfo object and not in any of its dependencies.
+
+   TODO: Only looking in the specified soinfo seems wrong. dlsym(3) says
+   that it should do a breadth first search through the dependency
+   tree. This agrees with the ELF spec (aka System V Application
+   Binary Interface) where in Chapter 5 it discuss resolving "Shared
+   Object Dependencies" in breadth first search order.
  */
-Elf32_Sym *soinfo_lookup(soinfo *si, const char *name)
+Elf32_Sym* dlsym_handle_lookup(soinfo* si, const char* name)
 {
     return soinfo_elf_lookup(si, elfhash(name), name);
 }
 
-/* This is used by dl_sym().  It performs a global symbol lookup.
+/* This is used by dlsym(3) to performs a global symbol lookup. If the
+   start value is null (for RTLD_DEFAULT), the search starts at the
+   beginning of the global solist. Otherwise the search starts at the
+   specified soinfo (for RTLD_NEXT).
  */
-Elf32_Sym* lookup(const char* name, soinfo** found, soinfo* start) {
+Elf32_Sym* dlsym_linear_lookup(const char* name, soinfo** found, soinfo* start) {
   unsigned elf_hash = elfhash(name);
 
   if (start == NULL) {
@@ -623,31 +626,25 @@
   return s;
 }
 
-soinfo *find_containing_library(const void *addr)
-{
-    soinfo *si;
-
-    for(si = solist; si != NULL; si = si->next)
-    {
-        if((unsigned)addr >= si->base && (unsigned)addr - si->base < si->size) {
+soinfo* find_containing_library(const void* addr) {
+    for (soinfo* si = solist; si != NULL; si = si->next) {
+        if ((unsigned)addr >= si->base && (unsigned)addr - si->base < si->size) {
             return si;
         }
     }
-
     return NULL;
 }
 
-Elf32_Sym *soinfo_find_symbol(soinfo* si, const void *addr)
-{
+Elf32_Sym* dladdr_find_symbol(soinfo* si, const void* addr) {
     unsigned int i;
     unsigned soaddr = (unsigned)addr - si->base;
 
     /* Search the library's symbol table for any defined symbol which
      * contains this address */
-    for(i=0; i<si->nchain; i++) {
+    for (i=0; i<si->nchain; i++) {
         Elf32_Sym *sym = &si->symtab[i];
 
-        if(sym->st_shndx != SHN_UNDEF &&
+        if (sym->st_shndx != SHN_UNDEF &&
            soaddr >= sym->st_value &&
            soaddr < sym->st_value + sym->st_size) {
             return sym;
@@ -658,12 +655,10 @@
 }
 
 #if 0
-static void dump(soinfo *si)
+static void dump(soinfo* si)
 {
-    Elf32_Sym *s = si->symtab;
-    unsigned n;
-
-    for(n = 0; n < si->nchain; n++) {
+    Elf32_Sym* s = si->symtab;
+    for (unsigned n = 0; n < si->nchain; n++) {
         TRACE("%04d> %08x: %02x %04x %08x %08x %s\n", n, s,
                s->st_info, s->st_shndx, s->st_value, s->st_size,
                si->strtab + s->st_name);
@@ -708,197 +703,34 @@
   return fd;
 }
 
-// Returns 'true' if the library is prelinked or on failure so we error out
-// either way. We no longer support prelinking.
-static bool is_prelinked(int fd, const char* name)
-{
-    struct prelink_info_t {
-        long mmap_addr;
-        char tag[4]; // "PRE ".
-    };
-
-    off_t sz = lseek(fd, -sizeof(prelink_info_t), SEEK_END);
-    if (sz < 0) {
-        DL_ERR("lseek failed: %s", strerror(errno));
-        return true;
-    }
-
-    prelink_info_t info;
-    int rc = TEMP_FAILURE_RETRY(read(fd, &info, sizeof(info)));
-    if (rc != sizeof(info)) {
-        DL_ERR("could not read prelink_info_t structure for \"%s\": %s", name, strerror(errno));
-        return true;
-    }
-
-    if (memcmp(info.tag, "PRE ", 4) == 0) {
-        DL_ERR("prelinked libraries no longer supported: %s", name);
-        return true;
-    }
-    return false;
-}
-
-/* verify_elf_header
- *      Verifies the content of an ELF header.
- *
- * Args:
- *
- * Returns:
- *       0 on success
- *      -1 if no valid ELF object is found @ base.
- */
-static int
-verify_elf_header(const Elf32_Ehdr* hdr)
-{
-    if (hdr->e_ident[EI_MAG0] != ELFMAG0) return -1;
-    if (hdr->e_ident[EI_MAG1] != ELFMAG1) return -1;
-    if (hdr->e_ident[EI_MAG2] != ELFMAG2) return -1;
-    if (hdr->e_ident[EI_MAG3] != ELFMAG3) return -1;
-    if (hdr->e_type != ET_DYN) return -1;
-
-    /* TODO: Should we verify anything else in the header? */
-#ifdef ANDROID_ARM_LINKER
-    if (hdr->e_machine != EM_ARM) return -1;
-#elif defined(ANDROID_X86_LINKER)
-    if (hdr->e_machine != EM_386) return -1;
-#elif defined(ANDROID_MIPS_LINKER)
-    if (hdr->e_machine != EM_MIPS) return -1;
-#endif
-    return 0;
-}
-
-struct scoped_fd {
-    ~scoped_fd() {
-        if (fd != -1) {
-            close(fd);
-        }
-    }
-    int fd;
-};
-
-struct soinfo_ptr {
-    soinfo_ptr(const char* name) {
-        const char* bname = strrchr(name, '/');
-        ptr = soinfo_alloc(bname ? bname + 1 : name);
-    }
-    ~soinfo_ptr() {
-        soinfo_free(ptr);
-    }
-    soinfo* release() {
-        soinfo* result = ptr;
-        ptr = NULL;
-        return result;
-    }
-    soinfo* ptr;
-};
-
-// TODO: rewrite linker_phdr.h to use a class, then lose this.
-struct phdr_ptr {
-    phdr_ptr() : phdr_mmap(NULL) {}
-    ~phdr_ptr() {
-        if (phdr_mmap != NULL) {
-            phdr_table_unload(phdr_mmap, phdr_size);
-        }
-    }
-    void* phdr_mmap;
-    Elf32_Addr phdr_size;
-};
-
 static soinfo* load_library(const char* name) {
     // Open the file.
-    scoped_fd fd;
-    fd.fd = open_library(name);
-    if (fd.fd == -1) {
+    int fd = open_library(name);
+    if (fd == -1) {
         DL_ERR("library \"%s\" not found", name);
         return NULL;
     }
 
-    // Read the ELF header.
-    Elf32_Ehdr header[1];
-    int ret = TEMP_FAILURE_RETRY(read(fd.fd, (void*)header, sizeof(header)));
-    if (ret < 0) {
-        DL_ERR("can't read file \"%s\": %s", name, strerror(errno));
-        return NULL;
-    }
-    if (ret != (int)sizeof(header)) {
-        DL_ERR("too small to be an ELF executable: %s", name);
-        return NULL;
-    }
-    if (verify_elf_header(header) < 0) {
-        DL_ERR("not a valid ELF executable: %s", name);
+    // Read the ELF header and load the segments.
+    ElfReader elf_reader(name, fd);
+    if (!elf_reader.Load()) {
         return NULL;
     }
 
-    // Read the program header table.
-    const Elf32_Phdr* phdr_table;
-    phdr_ptr phdr_holder;
-    ret = phdr_table_load(fd.fd, header->e_phoff, header->e_phnum,
-                          &phdr_holder.phdr_mmap, &phdr_holder.phdr_size, &phdr_table);
-    if (ret < 0) {
-        DL_ERR("can't load program header table: %s: %s", name, strerror(errno));
+    const char* bname = strrchr(name, '/');
+    soinfo* si = soinfo_alloc(bname ? bname + 1 : name);
+    if (si == NULL) {
         return NULL;
     }
-    size_t phdr_count = header->e_phnum;
-
-    // Get the load extents.
-    Elf32_Addr ext_sz = phdr_table_get_load_size(phdr_table, phdr_count);
-    TRACE("[ '%s' wants sz=0x%08x ]\n", name, ext_sz);
-    if (ext_sz == 0) {
-        DL_ERR("no loadable segments in file: %s", name);
-        return NULL;
-    }
-
-    // We no longer support pre-linked libraries.
-    if (is_prelinked(fd.fd, name)) {
-        return NULL;
-    }
-
-    // Reserve address space for all loadable segments.
-    void* load_start = NULL;
-    Elf32_Addr load_size = 0;
-    Elf32_Addr load_bias = 0;
-    ret = phdr_table_reserve_memory(phdr_table,
-                                    phdr_count,
-                                    &load_start,
-                                    &load_size,
-                                    &load_bias);
-    if (ret < 0) {
-        DL_ERR("can't reserve %d bytes in address space for \"%s\": %s",
-               ext_sz, name, strerror(errno));
-        return NULL;
-    }
-
-    TRACE("[ allocated memory for %s @ %p (0x%08x) ]\n", name, load_start, load_size);
-
-    /* Map all the segments in our address space with default protections */
-    ret = phdr_table_load_segments(phdr_table,
-                                   phdr_count,
-                                   load_bias,
-                                   fd.fd);
-    if (ret < 0) {
-        DL_ERR("can't map loadable segments for \"%s\": %s",
-               name, strerror(errno));
-        return NULL;
-    }
-
-    soinfo_ptr si(name);
-    if (si.ptr == NULL) {
-        return NULL;
-    }
-
-    si.ptr->base = (Elf32_Addr) load_start;
-    si.ptr->size = load_size;
-    si.ptr->load_bias = load_bias;
-    si.ptr->flags = 0;
-    si.ptr->entry = 0;
-    si.ptr->dynamic = (unsigned *)-1;
-    si.ptr->phnum = phdr_count;
-    si.ptr->phdr = phdr_table_get_loaded_phdr(phdr_table, phdr_count, load_bias);
-    if (si.ptr->phdr == NULL) {
-        DL_ERR("can't find loaded PHDR for \"%s\"", name);
-        return NULL;
-    }
-
-    return si.release();
+    si->base = elf_reader.load_start();
+    si->size = elf_reader.load_size();
+    si->load_bias = elf_reader.load_bias();
+    si->flags = 0;
+    si->entry = 0;
+    si->dynamic = NULL;
+    si->phnum = elf_reader.phdr_count();
+    si->phdr = elf_reader.loaded_phdr();
+    return si;
 }
 
 static soinfo *find_loaded_library(const char *name)
@@ -912,8 +744,8 @@
     bname = strrchr(name, '/');
     bname = bname ? bname + 1 : name;
 
-    for(si = solist; si != NULL; si = si->next){
-        if(!strcmp(bname, si->name)) {
+    for (si = solist; si != NULL; si = si->next) {
+        if (!strcmp(bname, si->name)) {
             return si;
         }
     }
@@ -967,9 +799,10 @@
     TRACE("unloading '%s'\n", si->name);
     si->CallDestructors();
 
-    for (unsigned* d = si->dynamic; *d; d += 2) {
-      if (d[0] == DT_NEEDED) {
-        soinfo* lsi = find_loaded_library(si->strtab + d[1]);
+    for (Elf32_Dyn* d = si->dynamic; d->d_tag != DT_NEEDED; ++d) {
+      if (d->d_tag == DT_NEEDED) {
+        const char* library_name = si->strtab + d->d_un.d_val;
+        soinfo* lsi = find_loaded_library(library_name);
         if (lsi != NULL) {
           TRACE("%s needs to unload %s\n", si->name, lsi->name);
           soinfo_unload(lsi);
@@ -1022,30 +855,30 @@
  * ideal. They should probably be either uint32_t, Elf32_Addr, or unsigned
  * long.
  */
-static int soinfo_relocate(soinfo *si, Elf32_Rel *rel, unsigned count,
-                           soinfo *needed[])
+static int soinfo_relocate(soinfo* si, Elf32_Rel* rel, unsigned count,
+                           soinfo* needed[])
 {
-    Elf32_Sym *symtab = si->symtab;
-    const char *strtab = si->strtab;
-    Elf32_Sym *s;
-    Elf32_Rel *start = rel;
-    soinfo *lsi;
+    Elf32_Sym* symtab = si->symtab;
+    const char* strtab = si->strtab;
+    Elf32_Sym* s;
+    Elf32_Rel* start = rel;
+    soinfo* lsi;
 
     for (size_t idx = 0; idx < count; ++idx, ++rel) {
         unsigned type = ELF32_R_TYPE(rel->r_info);
         unsigned sym = ELF32_R_SYM(rel->r_info);
         unsigned reloc = (unsigned)(rel->r_offset + si->load_bias);
         unsigned sym_addr = 0;
-        char *sym_name = NULL;
+        char* sym_name = NULL;
 
         DEBUG("Processing '%s' relocation at index %d\n", si->name, idx);
         if (type == 0) { // R_*_NONE
             continue;
         }
-        if(sym != 0) {
+        if (sym != 0) {
             sym_name = (char *)(strtab + symtab[sym].st_name);
             s = soinfo_do_lookup(si, sym_name, &lsi, needed);
-            if(s == NULL) {
+            if (s == NULL) {
                 /* We only allow an undefined symbol if this is a weak
                    reference..   */
                 s = &symtab[sym];
@@ -1103,7 +936,7 @@
             } else {
                 /* We got a definition.  */
 #if 0
-                if((base == 0) && (si->base != 0)){
+                if ((base == 0) && (si->base != 0)) {
                         /* linking from libraries to main image is bad */
                     DL_ERR("cannot locate \"%s\"...",
                            strtab + symtab[sym].st_name);
@@ -1300,9 +1133,9 @@
     sym = symtab + gotsym;
     got = si->plt_got + local_gotno;
     for (g = gotsym; g < symtabno; g++, sym++, got++) {
-        const char *sym_name;
-        Elf32_Sym *s;
-        soinfo *lsi;
+        const char* sym_name;
+        Elf32_Sym* s;
+        soinfo* lsi;
 
         /* This is an undefined reference... try to locate it */
         sym_name = si->strtab + sym->st_name;
@@ -1407,10 +1240,11 @@
     return;
   }
 
-  if (dynamic) {
-    for (unsigned* d = dynamic; *d; d += 2) {
-      if (d[0] == DT_NEEDED) {
-        soinfo* lsi = find_loaded_library(strtab + d[1]);
+  if (dynamic != NULL) {
+    for (Elf32_Dyn* d = dynamic; d->d_tag != DT_NULL; ++d) {
+      if (d->d_tag == DT_NEEDED) {
+        const char* library_name = strtab + d->d_un.d_val;
+        soinfo* lsi = find_loaded_library(library_name);
         if (lsi == NULL) {
           DL_ERR("\"%s\": could not initialize dependent library", name);
         } else {
@@ -1495,8 +1329,7 @@
     Elf32_Addr base = si->load_bias;
     const Elf32_Phdr *phdr = si->phdr;
     int phnum = si->phnum;
-    int relocating_linker = (si->flags & FLAG_LINKER) != 0;
-    soinfo **needed, **pneeded;
+    bool relocating_linker = (si->flags & FLAG_LINKER) != 0;
 
     /* We can't debug anything until the linker is relocated */
     if (!relocating_linker) {
@@ -1526,81 +1359,82 @@
 #endif
 
     /* extract useful information from dynamic section */
-    for (unsigned* d = si->dynamic; *d; ++d) {
-        DEBUG("d = %p, d[0] = 0x%08x d[1] = 0x%08x\n", d, d[0], d[1]);
-        switch(*d++){
+    uint32_t needed_count = 0;
+    for (Elf32_Dyn* d = si->dynamic; d->d_tag != DT_NULL; ++d) {
+        DEBUG("d = %p, d[0](tag) = 0x%08x d[1](val) = 0x%08x\n", d, d->d_tag, d->d_un.d_val);
+        switch(d->d_tag){
         case DT_HASH:
-            si->nbucket = ((unsigned *) (base + *d))[0];
-            si->nchain = ((unsigned *) (base + *d))[1];
-            si->bucket = (unsigned *) (base + *d + 8);
-            si->chain = (unsigned *) (base + *d + 8 + si->nbucket * 4);
+            si->nbucket = ((unsigned *) (base + d->d_un.d_ptr))[0];
+            si->nchain = ((unsigned *) (base + d->d_un.d_ptr))[1];
+            si->bucket = (unsigned *) (base + d->d_un.d_ptr + 8);
+            si->chain = (unsigned *) (base + d->d_un.d_ptr + 8 + si->nbucket * 4);
             break;
         case DT_STRTAB:
-            si->strtab = (const char *) (base + *d);
+            si->strtab = (const char *) (base + d->d_un.d_ptr);
             break;
         case DT_SYMTAB:
-            si->symtab = (Elf32_Sym *) (base + *d);
+            si->symtab = (Elf32_Sym *) (base + d->d_un.d_ptr);
             break;
         case DT_PLTREL:
-            if(*d != DT_REL) {
+            if (d->d_un.d_val != DT_REL) {
                 DL_ERR("unsupported DT_RELA in \"%s\"", si->name);
                 return false;
             }
             break;
         case DT_JMPREL:
-            si->plt_rel = (Elf32_Rel*) (base + *d);
+            si->plt_rel = (Elf32_Rel*) (base + d->d_un.d_ptr);
             break;
         case DT_PLTRELSZ:
-            si->plt_rel_count = *d / 8;
+            si->plt_rel_count = d->d_un.d_val / sizeof(Elf32_Rel);
             break;
         case DT_REL:
-            si->rel = (Elf32_Rel*) (base + *d);
+            si->rel = (Elf32_Rel*) (base + d->d_un.d_ptr);
             break;
         case DT_RELSZ:
-            si->rel_count = *d / 8;
+            si->rel_count = d->d_un.d_val / sizeof(Elf32_Rel);
             break;
         case DT_PLTGOT:
             /* Save this in case we decide to do lazy binding. We don't yet. */
-            si->plt_got = (unsigned *)(base + *d);
+            si->plt_got = (unsigned *)(base + d->d_un.d_ptr);
             break;
         case DT_DEBUG:
             // Set the DT_DEBUG entry to the address of _r_debug for GDB
             // if the dynamic table is writable
             if ((dynamic_flags & PF_W) != 0) {
-                *d = (int) &_r_debug;
+                d->d_un.d_val = (int) &_r_debug;
             }
             break;
          case DT_RELA:
             DL_ERR("unsupported DT_RELA in \"%s\"", si->name);
             return false;
         case DT_INIT:
-            si->init_func = (void (*)(void))(base + *d);
+            si->init_func = (void (*)(void))(base + d->d_un.d_ptr);
             DEBUG("%s constructors (init func) found at %p\n", si->name, si->init_func);
             break;
         case DT_FINI:
-            si->fini_func = (void (*)(void))(base + *d);
+            si->fini_func = (void (*)(void))(base + d->d_un.d_ptr);
             DEBUG("%s destructors (fini func) found at %p\n", si->name, si->fini_func);
             break;
         case DT_INIT_ARRAY:
-            si->init_array = (unsigned *)(base + *d);
+            si->init_array = (unsigned *)(base + d->d_un.d_ptr);
             DEBUG("%s constructors (init_array) found at %p\n", si->name, si->init_array);
             break;
         case DT_INIT_ARRAYSZ:
-            si->init_array_count = ((unsigned)*d) / sizeof(Elf32_Addr);
+            si->init_array_count = ((unsigned)d->d_un.d_val) / sizeof(Elf32_Addr);
             break;
         case DT_FINI_ARRAY:
-            si->fini_array = (unsigned *)(base + *d);
+            si->fini_array = (unsigned *)(base + d->d_un.d_ptr);
             DEBUG("%s destructors (fini_array) found at %p\n", si->name, si->fini_array);
             break;
         case DT_FINI_ARRAYSZ:
-            si->fini_array_count = ((unsigned)*d) / sizeof(Elf32_Addr);
+            si->fini_array_count = ((unsigned)d->d_un.d_val) / sizeof(Elf32_Addr);
             break;
         case DT_PREINIT_ARRAY:
-            si->preinit_array = (unsigned *)(base + *d);
+            si->preinit_array = (unsigned *)(base + d->d_un.d_ptr);
             DEBUG("%s constructors (preinit_array) found at %p\n", si->name, si->preinit_array);
             break;
         case DT_PREINIT_ARRAYSZ:
-            si->preinit_array_count = ((unsigned)*d) / sizeof(Elf32_Addr);
+            si->preinit_array_count = ((unsigned)d->d_un.d_val) / sizeof(Elf32_Addr);
             break;
         case DT_TEXTREL:
             si->has_text_relocations = true;
@@ -1608,18 +1442,21 @@
         case DT_SYMBOLIC:
             si->has_DT_SYMBOLIC = true;
             break;
-#if defined(DT_FLAGS)
+        case DT_NEEDED:
+            ++needed_count;
+            break;
+#if defined DT_FLAGS
+        // TODO: why is DT_FLAGS not defined?
         case DT_FLAGS:
-            if (*d & DF_TEXTREL) {
+            if (d->d_un.d_val & DF_TEXTREL) {
                 si->has_text_relocations = true;
             }
-            if (*d & DF_SYMBOLIC) {
+            if (d->d_un.d_val & DF_SYMBOLIC) {
                 si->has_DT_SYMBOLIC = true;
             }
             break;
 #endif
 #if defined(ANDROID_MIPS_LINKER)
-        case DT_NEEDED:
         case DT_STRSZ:
         case DT_SYMENT:
         case DT_RELENT:
@@ -1627,7 +1464,7 @@
         case DT_MIPS_RLD_MAP:
             // Set the DT_MIPS_RLD_MAP entry to the address of _r_debug for GDB.
             {
-              r_debug** dp = (r_debug**) *d;
+              r_debug** dp = (r_debug**) d->d_un.d_ptr;
               *dp = &_r_debug;
             }
             break;
@@ -1638,19 +1475,19 @@
             break;
 
         case DT_MIPS_SYMTABNO:
-            si->mips_symtabno = *d;
+            si->mips_symtabno = d->d_un.d_val;
             break;
 
         case DT_MIPS_LOCAL_GOTNO:
-            si->mips_local_gotno = *d;
+            si->mips_local_gotno = d->d_un.d_val;
             break;
 
         case DT_MIPS_GOTSYM:
-            si->mips_gotsym = *d;
+            si->mips_gotsym = d->d_un.d_val;
             break;
 
         default:
-            DEBUG("Unused DT entry: type 0x%08x arg 0x%08x\n", d[-1], d[0]);
+            DEBUG("Unused DT entry: type 0x%08x arg 0x%08x\n", d->d_tag, d->d_un.d_val);
             break;
 #endif
         }
@@ -1660,6 +1497,10 @@
           si->base, si->strtab, si->symtab);
 
     // Sanity checks.
+    if (relocating_linker && needed_count != 0) {
+        DL_ERR("linker cannot have DT_NEEDED dependencies on other libraries");
+        return false;
+    }
     if (si->nbucket == 0) {
         DL_ERR("empty/missing DT_HASH in \"%s\" (built with --hash-style=gnu?)", si->name);
         return false;
@@ -1675,30 +1516,31 @@
 
     /* if this is the main executable, then load all of the preloads now */
     if (si->flags & FLAG_EXE) {
-        memset(preloads, 0, sizeof(preloads));
+        memset(gLdPreloads, 0, sizeof(gLdPreloads));
         for (size_t i = 0; gLdPreloadNames[i] != NULL; i++) {
             soinfo* lsi = find_library(gLdPreloadNames[i]);
             if (lsi == NULL) {
-                strlcpy(tmp_err_buf, linker_get_error(), sizeof(tmp_err_buf));
+                strlcpy(tmp_err_buf, linker_get_error_buffer(), sizeof(tmp_err_buf));
                 DL_ERR("could not load library \"%s\" needed by \"%s\"; caused by %s",
                        gLdPreloadNames[i], si->name, tmp_err_buf);
                 return false;
             }
-            preloads[i] = lsi;
+            gLdPreloads[i] = lsi;
         }
     }
 
-    /* dynamic_count is an upper bound for the number of needed libs */
-    pneeded = needed = (soinfo**) alloca((1 + dynamic_count) * sizeof(soinfo*));
+    soinfo** needed = (soinfo**) alloca((1 + needed_count) * sizeof(soinfo*));
+    soinfo** pneeded = needed;
 
-    for (unsigned* d = si->dynamic; *d; d += 2) {
-        if (d[0] == DT_NEEDED) {
-            DEBUG("%s needs %s\n", si->name, si->strtab + d[1]);
-            soinfo* lsi = find_library(si->strtab + d[1]);
+    for (Elf32_Dyn* d = si->dynamic; d->d_tag != DT_NULL; ++d) {
+        if (d->d_tag == DT_NEEDED) {
+            const char* library_name = si->strtab + d->d_un.d_val;
+            DEBUG("%s needs %s\n", si->name, library_name);
+            soinfo* lsi = find_library(library_name);
             if (lsi == NULL) {
-                strlcpy(tmp_err_buf, linker_get_error(), sizeof(tmp_err_buf));
+                strlcpy(tmp_err_buf, linker_get_error_buffer(), sizeof(tmp_err_buf));
                 DL_ERR("could not load library \"%s\" needed by \"%s\"; caused by %s",
-                       si->strtab + d[1], si->name, tmp_err_buf);
+                       library_name, si->name, tmp_err_buf);
                 return false;
             }
             *pneeded++ = lsi;
@@ -1719,15 +1561,15 @@
         }
     }
 
-    if (si->plt_rel) {
+    if (si->plt_rel != NULL) {
         DEBUG("[ relocating %s plt ]\n", si->name );
-        if(soinfo_relocate(si, si->plt_rel, si->plt_rel_count, needed)) {
+        if (soinfo_relocate(si, si->plt_rel, si->plt_rel_count, needed)) {
             return false;
         }
     }
-    if (si->rel) {
+    if (si->rel != NULL) {
         DEBUG("[ relocating %s ]\n", si->name );
-        if(soinfo_relocate(si, si->rel, si->rel_count, needed)) {
+        if (soinfo_relocate(si, si->rel, si->rel_count, needed)) {
             return false;
         }
     }
@@ -1791,12 +1633,12 @@
     // Initialize environment functions, and get to the ELF aux vectors table.
     linker_env_init(args);
 
-    debugger_init();
+    debuggerd_init();
 
     // Get a few environment variables.
     const char* LD_DEBUG = linker_env_get("LD_DEBUG");
     if (LD_DEBUG != NULL) {
-      debug_verbosity = atoi(LD_DEBUG);
+      gLdDebugVerbosity = atoi(LD_DEBUG);
     }
 
     // Normally, these are cleaned by linker_env_init, but the test
@@ -1827,29 +1669,31 @@
     _r_debug.r_map = map;
     r_debug_tail = map;
 
-        /* gdb expects the linker to be in the debug shared object list.
-         * Without this, gdb has trouble locating the linker's ".text"
-         * and ".plt" sections. Gdb could also potentially use this to
-         * relocate the offset of our exported 'rtld_db_dlactivity' symbol.
-         * Don't use soinfo_alloc(), because the linker shouldn't
-         * be on the soinfo list.
-         */
-    static soinfo linker_soinfo;
-    strlcpy(linker_soinfo.name, "/system/bin/linker", sizeof(linker_soinfo.name));
-    linker_soinfo.flags = 0;
-    linker_soinfo.base = linker_base;
-
-    /*
-     * Set the dynamic field in the link map otherwise gdb will complain with
-     * the following:
-     *   warning: .dynamic section for "/system/bin/linker" is not at the
-     *   expected address (wrong library or version mismatch?)
+    /* gdb expects the linker to be in the debug shared object list.
+     * Without this, gdb has trouble locating the linker's ".text"
+     * and ".plt" sections. Gdb could also potentially use this to
+     * relocate the offset of our exported 'rtld_db_dlactivity' symbol.
+     * Don't use soinfo_alloc(), because the linker shouldn't
+     * be on the soinfo list.
      */
-    Elf32_Ehdr *elf_hdr = (Elf32_Ehdr *) linker_base;
-    Elf32_Phdr *phdr = (Elf32_Phdr*)((unsigned char*) linker_base + elf_hdr->e_phoff);
-    phdr_table_get_dynamic_section(phdr, elf_hdr->e_phnum, linker_base,
-                                   &linker_soinfo.dynamic, NULL, NULL);
-    insert_soinfo_into_debug_map(&linker_soinfo);
+    {
+        static soinfo linker_soinfo;
+        strlcpy(linker_soinfo.name, "/system/bin/linker", sizeof(linker_soinfo.name));
+        linker_soinfo.flags = 0;
+        linker_soinfo.base = linker_base;
+
+        /*
+         * Set the dynamic field in the link map otherwise gdb will complain with
+         * the following:
+         *   warning: .dynamic section for "/system/bin/linker" is not at the
+         *   expected address (wrong library or version mismatch?)
+         */
+        Elf32_Ehdr *elf_hdr = (Elf32_Ehdr *) linker_base;
+        Elf32_Phdr *phdr = (Elf32_Phdr*)((unsigned char*) linker_base + elf_hdr->e_phoff);
+        phdr_table_get_dynamic_section(phdr, elf_hdr->e_phnum, linker_base,
+                                       &linker_soinfo.dynamic, NULL, NULL);
+        insert_soinfo_into_debug_map(&linker_soinfo);
+    }
 
     // Extract information passed from the kernel.
     si->phdr = reinterpret_cast<Elf32_Phdr*>(args.getauxval(AT_PHDR));
@@ -1870,7 +1714,7 @@
         break;
       }
     }
-    si->dynamic = (unsigned *)-1;
+    si->dynamic = NULL;
     si->refcount = 1;
 
     // Use LD_LIBRARY_PATH and LD_PRELOAD (but only if we aren't setuid/setgid).
@@ -1880,22 +1724,20 @@
     somain = si;
 
     if (!soinfo_link_image(si)) {
-        const char* msg = "CANNOT LINK EXECUTABLE\n";
-        write(2, __linker_dl_err_buf, strlen(__linker_dl_err_buf));
-        write(2, msg, strlen(msg));
+        __libc_format_fd(2, "CANNOT LINK EXECUTABLE: %s\n", linker_get_error_buffer());
         exit(EXIT_FAILURE);
     }
 
     si->CallPreInitConstructors();
 
-    for (size_t i = 0; preloads[i] != NULL; ++i) {
-        preloads[i]->CallConstructors();
+    for (size_t i = 0; gLdPreloads[i] != NULL; ++i) {
+        gLdPreloads[i]->CallConstructors();
     }
 
-    /*After the link_image, the si->load_bias is initialized.
-     *For so lib, the map->l_addr will be updated in notify_gdb_of_load.
-     *We need to update this value for so exe here. So Unwind_Backtrace
-     *for some arch like x86 could work correctly within so exe.
+    /* After the link_image, the si->load_bias is initialized.
+     * For so lib, the map->l_addr will be updated in notify_gdb_of_load.
+     * We need to update this value for so exe here. So Unwind_Backtrace
+     * for some arch like x86 could work correctly within so exe.
      */
     map->l_addr = si->load_bias;
     si->CallConstructors();
@@ -1919,11 +1761,13 @@
         unsigned n;
         unsigned i;
         unsigned count = 0;
-        for(n = 0; n < 4096; n++){
-            if(bitmask[n]){
+        for (n = 0; n < 4096; n++) {
+            if (bitmask[n]) {
                 unsigned x = bitmask[n];
-                for(i = 0; i < 8; i++){
-                    if(x & 1) count++;
+                for (i = 0; i < 8; i++) {
+                    if (x & 1) {
+                        count++;
+                    }
                     x >>= 1;
                 }
             }
@@ -1989,7 +1833,7 @@
   linker_so.base = linker_addr;
   linker_so.size = phdr_table_get_load_size(phdr, elf_hdr->e_phnum);
   linker_so.load_bias = get_elf_exec_load_bias(elf_hdr);
-  linker_so.dynamic = (unsigned*) -1;
+  linker_so.dynamic = NULL;
   linker_so.phdr = phdr;
   linker_so.phnum = elf_hdr->e_phnum;
   linker_so.flags |= FLAG_LINKER;
diff --git a/linker/linker.h b/linker/linker.h
index cf6fff9..cef6905 100644
--- a/linker/linker.h
+++ b/linker/linker.h
@@ -36,6 +36,15 @@
 
 #include <link.h>
 
+#include <private/debug_format.h>
+
+#define DL_ERR(fmt, x...) \
+    do { \
+      __libc_format_buffer(linker_get_error_buffer(), linker_get_error_buffer_size(), fmt, ##x); \
+      /* If LD_DEBUG is set high enough, log every dlerror(3) message. */ \
+      DEBUG("%s\n", linker_get_error_buffer()); \
+    } while(0)
+
 // Returns the address of the page containing address 'x'.
 #define PAGE_START(x)  ((x) & PAGE_MASK)
 
@@ -50,10 +59,10 @@
 
 struct link_map {
   uintptr_t l_addr;
-  char * l_name;
+  char*  l_name;
   uintptr_t l_ld;
-  struct link_map * l_next;
-  struct link_map * l_prev;
+  struct link_map* l_next;
+  struct link_map* l_prev;
 };
 
 // Values for r_debug->state
@@ -87,7 +96,7 @@
 
   int unused;  // DO NOT USE, maintained for compatibility.
 
-  unsigned* dynamic;
+  Elf32_Dyn* dynamic;
 
   unsigned unused2; // DO NOT USE, maintained for compatibility
   unsigned unused3; // DO NOT USE, maintained for compatibility
@@ -167,14 +176,16 @@
 soinfo* do_dlopen(const char* name, int flags);
 int do_dlclose(soinfo* si);
 
-Elf32_Sym* lookup(const char* name, soinfo** found, soinfo* start);
+Elf32_Sym* dlsym_linear_lookup(const char* name, soinfo** found, soinfo* start);
 soinfo* find_containing_library(const void* addr);
-const char* linker_get_error();
 
-Elf32_Sym* soinfo_find_symbol(soinfo* si, const void* addr);
-Elf32_Sym* soinfo_lookup(soinfo* si, const char* name);
+Elf32_Sym* dladdr_find_symbol(soinfo* si, const void* addr);
+Elf32_Sym* dlsym_handle_lookup(soinfo* si, const char* name);
 
-void debugger_init();
+void debuggerd_init();
 extern "C" void notify_gdb_of_libraries();
 
+char* linker_get_error_buffer();
+size_t linker_get_error_buffer_size();
+
 #endif
diff --git a/linker/linker_debug.h b/linker/linker_debug.h
index b326d00..bf9ef92 100644
--- a/linker/linker_debug.h
+++ b/linker/linker_debug.h
@@ -54,15 +54,17 @@
 
 #include <private/debug_format.h>
 
+__LIBC_HIDDEN__ extern int gLdDebugVerbosity;
+
 #if LINKER_DEBUG_TO_LOG
 #define _PRINTVF(v,x...)                                        \
     do {                                                          \
-        if (debug_verbosity > (v)) __libc_format_log(5-(v),"linker",x);  \
+        if (gLdDebugVerbosity > (v)) __libc_format_log(5-(v),"linker",x);  \
     } while (0)
 #else /* !LINKER_DEBUG_TO_LOG */
 #define _PRINTVF(v,x...)                           \
     do {                                             \
-        if (debug_verbosity > (v)) __libc_format_fd(1, x);  \
+        if (gLdDebugVerbosity > (v)) __libc_format_fd(1, x);  \
     } while (0)
 #endif /* !LINKER_DEBUG_TO_LOG */
 
diff --git a/linker/linker_phdr.cpp b/linker/linker_phdr.cpp
index 94260fa..64dbb70 100644
--- a/linker/linker_phdr.cpp
+++ b/linker/linker_phdr.cpp
@@ -26,10 +26,13 @@
  * SUCH DAMAGE.
  */
 
+#include "linker_phdr.h"
+
 #include <errno.h>
 #include <sys/mman.h>
 
-#include "linker_phdr.h"
+#include "linker.h"
+#include "linker_debug.h"
 
 /**
   TECHNICAL NOTE ON ELF LOADING.
@@ -112,66 +115,116 @@
                                       MAYBE_MAP_FLAG((x), PF_R, PROT_READ) | \
                                       MAYBE_MAP_FLAG((x), PF_W, PROT_WRITE))
 
-/* Load the program header table from an ELF file into a read-only private
- * anonymous mmap-ed block.
- *
- * Input:
- *   fd           -> file descriptor
- *   phdr_offset  -> file offset of phdr table
- *   phdr_num     -> number of entries in the table.
- *
- * Output:
- *   phdr_mmap    -> address of mmap block in memory.
- *   phdr_memsize -> size of mmap block in memory.
- *   phdr_table   -> address of first entry in memory.
- *
- * Return:
- *   -1 on error, or 0 on success.
- */
-int phdr_table_load(int                fd,
-                    Elf32_Addr         phdr_offset,
-                    Elf32_Half         phdr_num,
-                    void**             phdr_mmap,
-                    Elf32_Addr*        phdr_size,
-                    const Elf32_Phdr** phdr_table)
-{
-    Elf32_Addr  page_min, page_max, page_offset;
-    void*       mmap_result;
-
-    /* Just like the kernel, we only accept program header tables that
-     * are smaller than 64KB. */
-    if (phdr_num < 1 || phdr_num > 65536/sizeof(Elf32_Phdr)) {
-        errno = EINVAL;
-        return -1;
-    }
-
-    page_min = PAGE_START(phdr_offset);
-    page_max = PAGE_END(phdr_offset + phdr_num*sizeof(Elf32_Phdr));
-    page_offset = PAGE_OFFSET(phdr_offset);
-
-    mmap_result = mmap(NULL,
-                       page_max - page_min,
-                       PROT_READ,
-                       MAP_PRIVATE,
-                       fd,
-                       page_min);
-
-    if (mmap_result == MAP_FAILED) {
-        return -1;
-    }
-
-    *phdr_mmap = mmap_result;
-    *phdr_size = page_max - page_min;
-    *phdr_table = (Elf32_Phdr*)((char*)mmap_result + page_offset);
-
-    return 0;
+ElfReader::ElfReader(const char* name, int fd)
+    : name_(name), fd_(fd),
+      phdr_num_(0), phdr_mmap_(NULL), phdr_table_(NULL), phdr_size_(0),
+      load_start_(NULL), load_size_(0), load_bias_(0),
+      loaded_phdr_(NULL) {
 }
 
-void phdr_table_unload(void* phdr_mmap, Elf32_Addr phdr_memsize)
-{
-    munmap(phdr_mmap, phdr_memsize);
+ElfReader::~ElfReader() {
+  if (fd_ != -1) {
+    close(fd_);
+  }
+  if (phdr_mmap_ != NULL) {
+    munmap(phdr_mmap_, phdr_size_);
+  }
 }
 
+bool ElfReader::Load() {
+  return ReadElfHeader() &&
+         VerifyElfHeader() &&
+         ReadProgramHeader() &&
+         ReserveAddressSpace() &&
+         LoadSegments() &&
+         FindPhdr();
+}
+
+bool ElfReader::ReadElfHeader() {
+  ssize_t rc = TEMP_FAILURE_RETRY(read(fd_, &header_, sizeof(header_)));
+  if (rc < 0) {
+    DL_ERR("can't read file \"%s\": %s", name_, strerror(errno));
+    return false;
+  }
+  if (rc != sizeof(header_)) {
+    DL_ERR("\"%s\" is too small to be an ELF executable", name_);
+    return false;
+  }
+  return true;
+}
+
+bool ElfReader::VerifyElfHeader() {
+  if (header_.e_ident[EI_MAG0] != ELFMAG0 ||
+      header_.e_ident[EI_MAG1] != ELFMAG1 ||
+      header_.e_ident[EI_MAG2] != ELFMAG2 ||
+      header_.e_ident[EI_MAG3] != ELFMAG3) {
+    DL_ERR("\"%s\" has bad ELF magic", name_);
+    return false;
+  }
+
+  if (header_.e_ident[EI_CLASS] != ELFCLASS32) {
+    DL_ERR("\"%s\" not 32-bit: %d", name_, header_.e_ident[EI_CLASS]);
+    return false;
+  }
+  if (header_.e_ident[EI_DATA] != ELFDATA2LSB) {
+    DL_ERR("\"%s\" not little-endian: %d", name_, header_.e_ident[EI_DATA]);
+    return false;
+  }
+
+  if (header_.e_type != ET_DYN) {
+    DL_ERR("\"%s\" has unexpected e_type: %d", name_, header_.e_type);
+    return false;
+  }
+
+  if (header_.e_version != EV_CURRENT) {
+    DL_ERR("\"%s\" has unexpected e_version: %d", name_, header_.e_version);
+    return false;
+  }
+
+  if (header_.e_machine !=
+#ifdef ANDROID_ARM_LINKER
+      EM_ARM
+#elif defined(ANDROID_MIPS_LINKER)
+      EM_MIPS
+#elif defined(ANDROID_X86_LINKER)
+      EM_386
+#endif
+  ) {
+    DL_ERR("\"%s\" has unexpected e_machine: %d", name_, header_.e_machine);
+    return false;
+  }
+
+  return true;
+}
+
+// Loads the program header table from an ELF file into a read-only private
+// anonymous mmap-ed block.
+bool ElfReader::ReadProgramHeader() {
+  phdr_num_ = header_.e_phnum;
+
+  // Like the kernel, we only accept program header tables that
+  // are smaller than 64KiB.
+  if (phdr_num_ < 1 || phdr_num_ > 65536/sizeof(Elf32_Phdr)) {
+    DL_ERR("\"%s\" has invalid e_phnum: %d", name_, phdr_num_);
+    return false;
+  }
+
+  Elf32_Addr page_min = PAGE_START(header_.e_phoff);
+  Elf32_Addr page_max = PAGE_END(header_.e_phoff + (phdr_num_ * sizeof(Elf32_Phdr)));
+  Elf32_Addr page_offset = PAGE_OFFSET(header_.e_phoff);
+
+  phdr_size_ = page_max - page_min;
+
+  void* mmap_result = mmap(NULL, phdr_size_, PROT_READ, MAP_PRIVATE, fd_, page_min);
+  if (mmap_result == MAP_FAILED) {
+    DL_ERR("\"%s\" phdr mmap failed: %s", name_, strerror(errno));
+    return false;
+  }
+
+  phdr_mmap_ = mmap_result;
+  phdr_table_ = reinterpret_cast<Elf32_Phdr*>(reinterpret_cast<char*>(mmap_result) + page_offset);
+  return true;
+}
 
 /* Compute the extent of all loadable segments in an ELF program header
  * table. This corresponds to the page-aligned size in bytes that needs to be
@@ -211,134 +264,100 @@
     return max_vaddr - min_vaddr;
 }
 
-/* Reserve a virtual address range big enough to hold all loadable
- * segments of a program header table. This is done by creating a
- * private anonymous mmap() with PROT_NONE.
- *
- * Input:
- *   phdr_table    -> program header table
- *   phdr_count    -> number of entries in the tables
- * Output:
- *   load_start    -> first page of reserved address space range
- *   load_size     -> size in bytes of reserved address space range
- *   load_bias     -> load bias, as described in technical note above.
- *
- * Return:
- *   0 on success, -1 otherwise. Error code in errno.
- */
-int
-phdr_table_reserve_memory(const Elf32_Phdr* phdr_table,
-                          size_t phdr_count,
-                          void** load_start,
-                          Elf32_Addr* load_size,
-                          Elf32_Addr* load_bias)
-{
-    Elf32_Addr size = phdr_table_get_load_size(phdr_table, phdr_count);
-    if (size == 0) {
-        errno = EINVAL;
-        return -1;
-    }
+// Reserve a virtual address range big enough to hold all loadable
+// segments of a program header table. This is done by creating a
+// private anonymous mmap() with PROT_NONE.
+bool ElfReader::ReserveAddressSpace() {
+  load_size_ = phdr_table_get_load_size(phdr_table_, phdr_num_);
+  if (load_size_ == 0) {
+    DL_ERR("\"%s\" has no loadable segments", name_);
+    return false;
+  }
 
-    int mmap_flags = MAP_PRIVATE | MAP_ANONYMOUS;
-    void* start = mmap(NULL, size, PROT_NONE, mmap_flags, -1, 0);
-    if (start == MAP_FAILED) {
-        return -1;
-    }
+  int mmap_flags = MAP_PRIVATE | MAP_ANONYMOUS;
+  void* start = mmap(NULL, load_size_, PROT_NONE, mmap_flags, -1, 0);
+  if (start == MAP_FAILED) {
+    DL_ERR("couldn't reserve %d bytes of address space for \"%s\"", load_size_, name_);
+    return false;
+  }
 
-    *load_start = start;
-    *load_size  = size;
-    *load_bias  = 0;
+  load_start_ = start;
+  load_bias_ = 0;
 
-    for (size_t i = 0; i < phdr_count; ++i) {
-        const Elf32_Phdr* phdr = &phdr_table[i];
-        if (phdr->p_type == PT_LOAD) {
-            *load_bias = (Elf32_Addr)start - PAGE_START(phdr->p_vaddr);
-            break;
-        }
+  for (size_t i = 0; i < phdr_num_; ++i) {
+    const Elf32_Phdr* phdr = &phdr_table_[i];
+    if (phdr->p_type == PT_LOAD) {
+      load_bias_ = reinterpret_cast<Elf32_Addr>(start) - PAGE_START(phdr->p_vaddr);
+      break;
     }
-    return 0;
+  }
+  return true;
 }
 
-/* Map all loadable segments in process' address space.
- * This assumes you already called phdr_table_reserve_memory to
- * reserve the address space range for the library.
- *
- * Input:
- *   phdr_table    -> program header table
- *   phdr_count    -> number of entries in the table
- *   load_bias     -> load offset.
- *   fd            -> input file descriptor.
- *
- * Return:
- *   0 on success, -1 otherwise. Error code in errno.
- */
-int
-phdr_table_load_segments(const Elf32_Phdr* phdr_table,
-                         int               phdr_count,
-                         Elf32_Addr        load_bias,
-                         int               fd)
-{
-    int nn;
+// Map all loadable segments in process' address space.
+// This assumes you already called phdr_table_reserve_memory to
+// reserve the address space range for the library.
+// TODO: assert assumption.
+bool ElfReader::LoadSegments() {
+  for (size_t i = 0; i < phdr_num_; ++i) {
+    const Elf32_Phdr* phdr = &phdr_table_[i];
 
-    for (nn = 0; nn < phdr_count; nn++) {
-        const Elf32_Phdr* phdr = &phdr_table[nn];
-        void* seg_addr;
-
-        if (phdr->p_type != PT_LOAD)
-            continue;
-
-        /* Segment addresses in memory */
-        Elf32_Addr seg_start = phdr->p_vaddr + load_bias;
-        Elf32_Addr seg_end   = seg_start + phdr->p_memsz;
-
-        Elf32_Addr seg_page_start = PAGE_START(seg_start);
-        Elf32_Addr seg_page_end   = PAGE_END(seg_end);
-
-        Elf32_Addr seg_file_end   = seg_start + phdr->p_filesz;
-
-        /* File offsets */
-        Elf32_Addr file_start = phdr->p_offset;
-        Elf32_Addr file_end   = file_start + phdr->p_filesz;
-
-        Elf32_Addr file_page_start = PAGE_START(file_start);
-
-        seg_addr = mmap((void*)seg_page_start,
-                        file_end - file_page_start,
-                        PFLAGS_TO_PROT(phdr->p_flags),
-                        MAP_FIXED|MAP_PRIVATE,
-                        fd,
-                        file_page_start);
-
-        if (seg_addr == MAP_FAILED) {
-            return -1;
-        }
-
-        /* if the segment is writable, and does not end on a page boundary,
-         * zero-fill it until the page limit. */
-        if ((phdr->p_flags & PF_W) != 0 && PAGE_OFFSET(seg_file_end) > 0) {
-            memset((void*)seg_file_end, 0, PAGE_SIZE - PAGE_OFFSET(seg_file_end));
-        }
-
-        seg_file_end = PAGE_END(seg_file_end);
-
-        /* seg_file_end is now the first page address after the file
-         * content. If seg_end is larger, we need to zero anything
-         * between them. This is done by using a private anonymous
-         * map for all extra pages.
-         */
-        if (seg_page_end > seg_file_end) {
-            void* zeromap = mmap((void*)seg_file_end,
-                                    seg_page_end - seg_file_end,
-                                    PFLAGS_TO_PROT(phdr->p_flags),
-                                    MAP_FIXED|MAP_ANONYMOUS|MAP_PRIVATE,
-                                    -1,
-                                    0);
-            if (zeromap == MAP_FAILED) {
-                return -1;
-            }
-        }
+    if (phdr->p_type != PT_LOAD) {
+      continue;
     }
-    return 0;
+
+    // Segment addresses in memory.
+    Elf32_Addr seg_start = phdr->p_vaddr + load_bias_;
+    Elf32_Addr seg_end   = seg_start + phdr->p_memsz;
+
+    Elf32_Addr seg_page_start = PAGE_START(seg_start);
+    Elf32_Addr seg_page_end   = PAGE_END(seg_end);
+
+    Elf32_Addr seg_file_end   = seg_start + phdr->p_filesz;
+
+    // File offsets.
+    Elf32_Addr file_start = phdr->p_offset;
+    Elf32_Addr file_end   = file_start + phdr->p_filesz;
+
+    Elf32_Addr file_page_start = PAGE_START(file_start);
+
+    void* seg_addr = mmap((void*)seg_page_start,
+                          file_end - file_page_start,
+                          PFLAGS_TO_PROT(phdr->p_flags),
+                          MAP_FIXED|MAP_PRIVATE,
+                          fd_,
+                          file_page_start);
+    if (seg_addr == MAP_FAILED) {
+      DL_ERR("couldn't map \"%s\" segment %d: %s", name_, i, strerror(errno));
+      return false;
+    }
+
+    // if the segment is writable, and does not end on a page boundary,
+    // zero-fill it until the page limit.
+    if ((phdr->p_flags & PF_W) != 0 && PAGE_OFFSET(seg_file_end) > 0) {
+      memset((void*)seg_file_end, 0, PAGE_SIZE - PAGE_OFFSET(seg_file_end));
+    }
+
+    seg_file_end = PAGE_END(seg_file_end);
+
+    // seg_file_end is now the first page address after the file
+    // content. If seg_end is larger, we need to zero anything
+    // between them. This is done by using a private anonymous
+    // map for all extra pages.
+    if (seg_page_end > seg_file_end) {
+      void* zeromap = mmap((void*)seg_file_end,
+                           seg_page_end - seg_file_end,
+                           PFLAGS_TO_PROT(phdr->p_flags),
+                           MAP_FIXED|MAP_ANONYMOUS|MAP_PRIVATE,
+                           -1,
+                           0);
+      if (zeromap == MAP_FAILED) {
+        DL_ERR("couldn't zero fill \"%s\" gap: %s", name_, strerror(errno));
+        return false;
+      }
+    }
+  }
+  return true;
 }
 
 /* Used internally. Used to set the protection bits of all loaded segments
@@ -550,7 +569,7 @@
 phdr_table_get_dynamic_section(const Elf32_Phdr* phdr_table,
                                int               phdr_count,
                                Elf32_Addr        load_bias,
-                               Elf32_Addr**      dynamic,
+                               Elf32_Dyn**       dynamic,
                                size_t*           dynamic_count,
                                Elf32_Word*       dynamic_flags)
 {
@@ -562,7 +581,7 @@
             continue;
         }
 
-        *dynamic = (Elf32_Addr*)(load_bias + phdr->p_vaddr);
+        *dynamic = reinterpret_cast<Elf32_Dyn*>(load_bias + phdr->p_vaddr);
         if (dynamic_count) {
             *dynamic_count = (unsigned)(phdr->p_memsz / 8);
         }
@@ -577,72 +596,55 @@
     }
 }
 
-/* Return the address of the program header table as it appears in the loaded
- * segments in memory. This is in contrast with the input 'phdr_table' which
- * is temporary and will be released before the library is relocated.
- *
- * Input:
- *   phdr_table  -> program header table
- *   phdr_count  -> number of entries in tables
- *   load_bias   -> load bias
- * Return:
- *   Address of loaded program header table on success (it has
- *   'phdr_count' entries), or NULL on failure (no error code).
- */
-const Elf32_Phdr*
-phdr_table_get_loaded_phdr(const Elf32_Phdr*   phdr_table,
-                           int                 phdr_count,
-                           Elf32_Addr          load_bias)
-{
-    const Elf32_Phdr* phdr = phdr_table;
-    const Elf32_Phdr* phdr_limit = phdr + phdr_count;
-    Elf32_Addr  loaded = 0;
-    Elf32_Addr  loaded_end;
+// Returns the address of the program header table as it appears in the loaded
+// segments in memory. This is in contrast with 'phdr_table_' which
+// is temporary and will be released before the library is relocated.
+bool ElfReader::FindPhdr() {
+  const Elf32_Phdr* phdr_limit = phdr_table_ + phdr_num_;
 
-    /* If there is a PT_PHDR, use it directly */
-    for (phdr = phdr_table; phdr < phdr_limit; phdr++) {
-        if (phdr->p_type == PT_PHDR) {
-            loaded = load_bias + phdr->p_vaddr;
-            goto CHECK;
-        }
+  // If there is a PT_PHDR, use it directly.
+  for (const Elf32_Phdr* phdr = phdr_table_; phdr < phdr_limit; ++phdr) {
+    if (phdr->p_type == PT_PHDR) {
+      return CheckPhdr(load_bias_ + phdr->p_vaddr);
     }
+  }
 
-    /* Otherwise, check the first loadable segment. If its file offset
-     * is 0, it starts with the ELF header, and we can trivially find the
-     * loaded program header from it. */
-    for (phdr = phdr_table; phdr < phdr_limit; phdr++) {
-        if (phdr->p_type == PT_LOAD) {
-            if (phdr->p_offset == 0) {
-                Elf32_Addr  elf_addr = load_bias + phdr->p_vaddr;
-                const Elf32_Ehdr* ehdr = (const Elf32_Ehdr*)(void*)elf_addr;
-                Elf32_Addr  offset = ehdr->e_phoff;
-                loaded = (Elf32_Addr)ehdr + offset;
-                goto CHECK;
-            }
-            break;
-        }
+  // Otherwise, check the first loadable segment. If its file offset
+  // is 0, it starts with the ELF header, and we can trivially find the
+  // loaded program header from it.
+  for (const Elf32_Phdr* phdr = phdr_table_; phdr < phdr_limit; ++phdr) {
+    if (phdr->p_type == PT_LOAD) {
+      if (phdr->p_offset == 0) {
+        Elf32_Addr  elf_addr = load_bias_ + phdr->p_vaddr;
+        const Elf32_Ehdr* ehdr = (const Elf32_Ehdr*)(void*)elf_addr;
+        Elf32_Addr  offset = ehdr->e_phoff;
+        return CheckPhdr((Elf32_Addr)ehdr + offset);
+      }
+      break;
     }
+  }
 
-    /* We didn't find it, let the client know. He may be able to
-     * keep a copy of the input phdr_table instead. */
-    return NULL;
+  DL_ERR("can't find loaded phdr for \"%s\"", name_);
+  return false;
+}
 
-CHECK:
-    /* Ensure that our program header is actually within a loadable
-     * segment. This should help catch badly-formed ELF files that
-     * would cause the linker to crash later when trying to access it.
-     */
-    loaded_end = loaded + phdr_count*sizeof(Elf32_Phdr);
-
-    for (phdr = phdr_table; phdr < phdr_limit; phdr++) {
-        if (phdr->p_type != PT_LOAD)
-            continue;
-        Elf32_Addr seg_start = phdr->p_vaddr + load_bias;
-        Elf32_Addr seg_end   = phdr->p_filesz + seg_start;
-
-        if (seg_start <= loaded && loaded_end <= seg_end) {
-            return (const Elf32_Phdr*)loaded;
-        }
+// Ensures that our program header is actually within a loadable
+// segment. This should help catch badly-formed ELF files that
+// would cause the linker to crash later when trying to access it.
+bool ElfReader::CheckPhdr(Elf32_Addr loaded) {
+  const Elf32_Phdr* phdr_limit = phdr_table_ + phdr_num_;
+  Elf32_Addr loaded_end = loaded + (phdr_num_ * sizeof(Elf32_Phdr));
+  for (Elf32_Phdr* phdr = phdr_table_; phdr < phdr_limit; ++phdr) {
+    if (phdr->p_type != PT_LOAD) {
+      continue;
     }
-    return NULL;
+    Elf32_Addr seg_start = phdr->p_vaddr + load_bias_;
+    Elf32_Addr seg_end = phdr->p_filesz + seg_start;
+    if (seg_start <= loaded && loaded_end <= seg_end) {
+      loaded_phdr_ = reinterpret_cast<const Elf32_Phdr*>(loaded);
+      return true;
+    }
+  }
+  DL_ERR("\"%s\" loaded phdr %x not in loadable segment", name_, loaded);
+  return false;
 }
diff --git a/linker/linker_phdr.h b/linker/linker_phdr.h
index d9a4820..a31d1d9 100644
--- a/linker/linker_phdr.h
+++ b/linker/linker_phdr.h
@@ -37,33 +37,50 @@
 
 #include "linker.h"
 
-int
-phdr_table_load(int                fd,
-                Elf32_Addr         phdr_offset,
-                Elf32_Half         phdr_num,
-                void**             phdr_mmap,
-                Elf32_Addr*        phdr_size,
-                const Elf32_Phdr** phdr_table);
+class ElfReader {
+ public:
+  ElfReader(const char* name, int fd);
+  ~ElfReader();
 
-void
-phdr_table_unload(void* phdr_mmap, Elf32_Addr phdr_memsize);
+  bool Load();
 
-Elf32_Addr
-phdr_table_get_load_size(const Elf32_Phdr* phdr_table,
-                         size_t phdr_count);
+  size_t phdr_count() { return phdr_num_; }
+  Elf32_Addr load_start() { return reinterpret_cast<Elf32_Addr>(load_start_); }
+  Elf32_Addr load_size() { return load_size_; }
+  Elf32_Addr load_bias() { return load_bias_; }
+  const Elf32_Phdr* loaded_phdr() { return loaded_phdr_; }
 
-int
-phdr_table_reserve_memory(const Elf32_Phdr* phdr_table,
-                          size_t phdr_count,
-                          void** load_start,
-                          Elf32_Addr* load_size,
-                          Elf32_Addr* load_bias);
+ private:
+  bool ReadElfHeader();
+  bool VerifyElfHeader();
+  bool ReadProgramHeader();
+  bool ReserveAddressSpace();
+  bool LoadSegments();
+  bool FindPhdr();
+  bool CheckPhdr(Elf32_Addr);
 
-int
-phdr_table_load_segments(const Elf32_Phdr* phdr_table,
-                         int               phdr_count,
-                         Elf32_Addr        load_bias,
-                         int               fd);
+  const char* name_;
+  int fd_;
+
+  Elf32_Ehdr header_;
+  size_t phdr_num_;
+
+  void* phdr_mmap_;
+  Elf32_Phdr* phdr_table_;
+  Elf32_Addr phdr_size_;
+
+  // First page of reserved address space.
+  void* load_start_;
+  // Size in bytes of reserved address space.
+  Elf32_Addr load_size_;
+  // Load bias.
+  Elf32_Addr load_bias_;
+
+  // Loaded phdr.
+  const Elf32_Phdr* loaded_phdr_;
+};
+
+Elf32_Addr phdr_table_get_load_size(const Elf32_Phdr* phdr, size_t phnum);
 
 int
 phdr_table_protect_segments(const Elf32_Phdr* phdr_table,
@@ -80,10 +97,6 @@
                              int               phdr_count,
                              Elf32_Addr        load_bias);
 
-const Elf32_Phdr*
-phdr_table_get_loaded_phdr(const Elf32_Phdr*   phdr_table,
-                           int                 phdr_count,
-                           Elf32_Addr          load_bias);
 
 #ifdef ANDROID_ARM_LINKER
 int
@@ -98,7 +111,7 @@
 phdr_table_get_dynamic_section(const Elf32_Phdr* phdr_table,
                                int               phdr_count,
                                Elf32_Addr        load_bias,
-                               Elf32_Addr**      dynamic,
+                               Elf32_Dyn**       dynamic,
                                size_t*           dynamic_count,
                                Elf32_Word*       dynamic_flags);