Merge "Revert "Register __libc_fini as early as possible.""
diff --git a/libc/bionic/ndk_cruft.cpp b/libc/bionic/ndk_cruft.cpp
index 0c72019..45ead62 100644
--- a/libc/bionic/ndk_cruft.cpp
+++ b/libc/bionic/ndk_cruft.cpp
@@ -303,4 +303,9 @@
   return strchr(str, ch);
 }
 
+// This was removed from BSD.
+extern "C" void arc4random_stir(void) {
+  // The current implementation stirs itself as needed.
+}
+
 #endif
diff --git a/libc/bionic/sigaction.cpp b/libc/bionic/sigaction.cpp
index 225a823..e1a031f 100644
--- a/libc/bionic/sigaction.cpp
+++ b/libc/bionic/sigaction.cpp
@@ -64,10 +64,6 @@
     bionic_old_action->sa_mask = kernel_old_action.sa_mask;
 #ifdef SA_RESTORER
     bionic_old_action->sa_restorer = kernel_old_action.sa_restorer;
-
-    if (bionic_old_action->sa_restorer == &__rt_sigreturn) {
-      bionic_old_action->sa_flags &= ~SA_RESTORER;
-    }
 #endif
   }
 
diff --git a/libc/include/sys/cdefs.h b/libc/include/sys/cdefs.h
index b223afd..5082327 100644
--- a/libc/include/sys/cdefs.h
+++ b/libc/include/sys/cdefs.h
@@ -362,13 +362,22 @@
  * do it in <sys/cdefs.h> instead because that's where our existing
  * _POSIX_C_SOURCE tests were, and we're already confident that <sys/cdefs.h>
  * is included everywhere it should be.
+ *
+ * The _GNU_SOURCE test needs to come before any _BSD_SOURCE or _POSIX* tests
+ * because _GNU_SOURCE implies everything else.
  */
-#if defined(_BSD_SOURCE)
-# define __USE_BSD 1
-#endif
-
 #if defined(_GNU_SOURCE)
 # define __USE_GNU 1
+# undef _POSIX_SOURCE
+# define _POSIX_SOURCE 1
+# undef _POSIX_C_SOURCE
+# define _POSIX_C_SOURCE 200809L
+# undef _BSD_SOURCE
+# define _BSD_SOURCE 1
+#endif
+
+#if defined(_BSD_SOURCE)
+# define __USE_BSD 1
 #endif
 
 /*-
diff --git a/libc/private/ScopeGuard.h b/libc/private/ScopeGuard.h
new file mode 100644
index 0000000..183e322
--- /dev/null
+++ b/libc/private/ScopeGuard.h
@@ -0,0 +1,53 @@
+/*
+ * 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.
+ */
+
+#ifndef SCOPE_GUARD_H
+#define SCOPE_GUARD_H
+
+// TODO: include explicit std::move when it becomes available
+template<typename F>
+class ScopeGuard {
+ public:
+  ScopeGuard(F f) : f_(f), active_(true) {}
+
+  ScopeGuard(ScopeGuard&& that) : f_(that.f_), active_(that.active_) {
+    that.active_ = false;
+  }
+
+  ~ScopeGuard() {
+    if (active_) {
+      f_();
+    }
+  }
+
+  void disable() {
+    active_ = false;
+  }
+ private:
+  F f_;
+  bool active_;
+
+  ScopeGuard() = delete;
+  ScopeGuard(const ScopeGuard&) = delete;
+  ScopeGuard& operator=(const ScopeGuard&) = delete;
+};
+
+template<typename T>
+ScopeGuard<T> create_scope_guard(T f) {
+  return ScopeGuard<T>(f);
+}
+
+#endif  // SCOPE_GUARD_H
diff --git a/libc/private/UniquePtr.h b/libc/private/UniquePtr.h
new file mode 100644
index 0000000..5ac7599
--- /dev/null
+++ b/libc/private/UniquePtr.h
@@ -0,0 +1,140 @@
+/*
+ * Copyright (C) 2010 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef UNIQUE_PTR_H_included
+#define UNIQUE_PTR_H_included
+
+// Default deleter for pointer types.
+template <typename T>
+struct DefaultDelete {
+    enum { type_must_be_complete = sizeof(T) };
+    DefaultDelete() {}
+    void operator()(T* p) const {
+        delete p;
+    }
+};
+
+// Default deleter for array types.
+template <typename T>
+struct DefaultDelete<T[]> {
+    enum { type_must_be_complete = sizeof(T) };
+    void operator()(T* p) const {
+        delete[] p;
+    }
+};
+
+// A smart pointer that deletes the given pointer on destruction.
+// Equivalent to C++0x's std::unique_ptr (a combination of boost::scoped_ptr
+// and boost::scoped_array).
+// Named to be in keeping with Android style but also to avoid
+// collision with any other implementation, until we can switch over
+// to unique_ptr.
+// Use thus:
+//   UniquePtr<C> c(new C);
+template <typename T, typename D = DefaultDelete<T> >
+class UniquePtr {
+public:
+    // Construct a new UniquePtr, taking ownership of the given raw pointer.
+    explicit UniquePtr(T* ptr = nullptr) : mPtr(ptr) { }
+
+    UniquePtr(UniquePtr<T, D>&& that) {
+      mPtr = that.mPtr;
+      that.mPtr = nullptr;
+    }
+
+    ~UniquePtr() {
+        reset();
+    }
+
+    // Accessors.
+    T& operator*() const { return *mPtr; }
+    T* operator->() const { return mPtr; }
+    T* get() const { return mPtr; }
+
+    // Returns the raw pointer and hands over ownership to the caller.
+    // The pointer will not be deleted by UniquePtr.
+    T* release() __attribute__((warn_unused_result)) {
+        T* result = mPtr;
+        mPtr = nullptr;
+        return result;
+    }
+
+    // Takes ownership of the given raw pointer.
+    // If this smart pointer previously owned a different raw pointer, that
+    // raw pointer will be freed.
+    void reset(T* ptr = nullptr) {
+        if (ptr != mPtr) {
+            D()(mPtr);
+            mPtr = ptr;
+        }
+    }
+
+private:
+    // The raw pointer.
+    T* mPtr;
+
+    // Comparing unique pointers is probably a mistake, since they're unique.
+    template <typename T2> bool operator==(const UniquePtr<T2>& p) const = delete;
+    template <typename T2> bool operator!=(const UniquePtr<T2>& p) const = delete;
+
+    // Disallow copy and assignment.
+    UniquePtr(const UniquePtr&) = delete;
+    void operator=(const UniquePtr&) = delete;
+};
+
+// Partial specialization for array types. Like std::unique_ptr, this removes
+// operator* and operator-> but adds operator[].
+template <typename T, typename D>
+class UniquePtr<T[], D> {
+public:
+    explicit UniquePtr(T* ptr = NULL) : mPtr(ptr) {
+    }
+    UniquePtr(UniquePtr<T, D>&& that) {
+      mPtr = that.mPtr;
+      that.mPtr = nullptr;
+    }
+
+    ~UniquePtr() {
+        reset();
+    }
+
+    T& operator[](size_t i) const {
+        return mPtr[i];
+    }
+    T* get() const { return mPtr; }
+
+    T* release() __attribute__((warn_unused_result)) {
+        T* result = mPtr;
+        mPtr = NULL;
+        return result;
+    }
+
+    void reset(T* ptr = NULL) {
+        if (ptr != mPtr) {
+            D()(mPtr);
+            mPtr = ptr;
+        }
+    }
+
+private:
+    T* mPtr;
+
+    // Disallow copy and assignment.
+    UniquePtr(const UniquePtr&) = delete;
+    void operator=(const UniquePtr&) = delete;
+};
+
+#endif  // UNIQUE_PTR_H_included
diff --git a/libm/Android.mk b/libm/Android.mk
index 994caa0..f59b71f 100644
--- a/libm/Android.mk
+++ b/libm/Android.mk
@@ -255,6 +255,10 @@
 # libm.a for target.
 #
 include $(CLEAR_VARS)
+ifneq (,$(filter $(TARGET_ARCH),x86 x86_64))
+# Clang has wrong long double sizes for x86.
+LOCAL_CLANG := false
+endif
 LOCAL_MODULE:= libm
 LOCAL_ADDITIONAL_DEPENDENCIES := $(LOCAL_PATH)/Android.mk
 LOCAL_ARM_MODE := arm
@@ -287,6 +291,10 @@
 # libm.so for target.
 #
 include $(CLEAR_VARS)
+ifneq (,$(filter $(TARGET_ARCH),x86 x86_64))
+# Clang has wrong long double sizes for x86.
+LOCAL_CLANG := false
+endif
 LOCAL_MODULE:= libm
 LOCAL_ADDITIONAL_DEPENDENCIES := $(LOCAL_PATH)/Android.mk
 LOCAL_SYSTEM_SHARED_LIBRARIES := libc
diff --git a/linker/dlfcn.cpp b/linker/dlfcn.cpp
index 38484d9..3024b3c 100644
--- a/linker/dlfcn.cpp
+++ b/linker/dlfcn.cpp
@@ -245,6 +245,7 @@
     __libdl_info.bucket = g_libdl_buckets;
     __libdl_info.chain = g_libdl_chains;
     __libdl_info.has_DT_SYMBOLIC = true;
+    __libdl_info.ref_count = 1;
   }
 
   return &__libdl_info;
diff --git a/linker/linker.cpp b/linker/linker.cpp
index 9eb7440..610489e 100644
--- a/linker/linker.cpp
+++ b/linker/linker.cpp
@@ -44,6 +44,8 @@
 #include "private/KernelArgumentBlock.h"
 #include "private/ScopedPthreadMutexLocker.h"
 #include "private/ScopedFd.h"
+#include "private/ScopeGuard.h"
+#include "private/UniquePtr.h"
 
 #include "linker.h"
 #include "linker_debug.h"
@@ -170,7 +172,6 @@
 DISALLOW_ALLOCATION(void*, realloc, (void* u1 __unused, size_t u2 __unused));
 DISALLOW_ALLOCATION(void*, calloc, (size_t u1 __unused, size_t u2 __unused));
 
-static char tmp_err_buf[768];
 static char __linker_dl_err_buf[768];
 
 char* linker_get_error_buffer() {
@@ -512,7 +513,7 @@
     unsigned elf_hash = elfhash(name);
     ElfW(Sym)* s = nullptr;
 
-    if (si != nullptr && somain != nullptr) {
+    if (somain != nullptr) {
         /*
          * Local scope is executable scope. Just start looking into it right away
          * for the shortcut.
@@ -657,22 +658,47 @@
   }
 };
 
+class LoadTask {
+ public:
+  struct deleter_t {
+    void operator()(LoadTask* t) {
+      TypeBasedAllocator<LoadTask>::free(t);
+    }
+  };
+
+  typedef UniquePtr<LoadTask, deleter_t> unique_ptr;
+
+  static deleter_t deleter;
+
+  static LoadTask* create(const char* name, soinfo* needed_by) {
+    LoadTask* ptr = TypeBasedAllocator<LoadTask>::alloc();
+    return new (ptr) LoadTask(name, needed_by);
+  }
+
+  const char* get_name() {
+    return name_;
+  }
+
+  soinfo* get_needed_by() {
+    return needed_by_;
+  }
+ private:
+  LoadTask(const char* name, soinfo* needed_by)
+    : name_(name), needed_by_(needed_by) {}
+
+  const char* name_;
+  soinfo* needed_by_;
+
+  DISALLOW_IMPLICIT_CONSTRUCTORS(LoadTask);
+};
+
 template <typename T>
 using linked_list_t = LinkedList<T, TypeBasedAllocator<LinkedListEntry<T>>>;
 
 typedef linked_list_t<soinfo> SoinfoLinkedList;
+typedef linked_list_t<const char> StringLinkedList;
+typedef linked_list_t<LoadTask> LoadTaskList;
 
-static LinkerAllocator<LinkedListEntry<soinfo>> g_soinfo_list_allocator_rw;
-class SoinfoListAllocatorRW {
- public:
-  static LinkedListEntry<soinfo>* alloc() {
-    return g_soinfo_list_allocator_rw.alloc();
-  }
-
-  static void free(LinkedListEntry<soinfo>* ptr) {
-    g_soinfo_list_allocator_rw.free(ptr);
-  }
-};
 
 // This is used by dlsym(3).  It performs symbol lookup only within the
 // specified soinfo object and its dependencies in breadth first order.
@@ -798,73 +824,80 @@
   return fd;
 }
 
-static soinfo* load_library(const char* name, int dlflags, const android_dlextinfo* extinfo) {
-    int fd = -1;
-    ScopedFd file_guard(-1);
-
-    if (extinfo != nullptr && (extinfo->flags & ANDROID_DLEXT_USE_LIBRARY_FD) != 0) {
-      fd = extinfo->library_fd;
-    } else {
-      // Open the file.
-      fd = open_library(name);
-      if (fd == -1) {
-        DL_ERR("library \"%s\" not found", name);
-        return nullptr;
-      }
-
-      file_guard.reset(fd);
+template<typename F>
+static void for_each_dt_needed(const soinfo* si, F action) {
+  for (ElfW(Dyn)* d = si->dynamic; d->d_tag != DT_NULL; ++d) {
+    if (d->d_tag == DT_NEEDED) {
+      action(si->strtab + d->d_un.d_val);
     }
+  }
+}
 
-    ElfReader elf_reader(name, fd);
+static soinfo* load_library(LoadTaskList& load_tasks, const char* name, int dlflags, const android_dlextinfo* extinfo) {
+  int fd = -1;
+  ScopedFd file_guard(-1);
 
-    struct stat file_stat;
-    if (TEMP_FAILURE_RETRY(fstat(fd, &file_stat)) != 0) {
-      DL_ERR("unable to stat file for the library %s: %s", name, strerror(errno));
+  if (extinfo != nullptr && (extinfo->flags & ANDROID_DLEXT_USE_LIBRARY_FD) != 0) {
+    fd = extinfo->library_fd;
+  } else {
+    // Open the file.
+    fd = open_library(name);
+    if (fd == -1) {
+      DL_ERR("library \"%s\" not found", name);
       return nullptr;
     }
 
-    // Check for symlink and other situations where
-    // file can have different names.
-    for (soinfo* si = solist; si != nullptr; si = si->next) {
-      if (si->get_st_dev() != 0 &&
-          si->get_st_ino() != 0 &&
-          si->get_st_dev() == file_stat.st_dev &&
-          si->get_st_ino() == file_stat.st_ino) {
-        TRACE("library \"%s\" is already loaded under different name/path \"%s\" - will return existing soinfo", name, si->name);
-        return si;
-      }
+    file_guard.reset(fd);
+  }
+
+  struct stat file_stat;
+  if (TEMP_FAILURE_RETRY(fstat(fd, &file_stat)) != 0) {
+    DL_ERR("unable to stat file for the library %s: %s", name, strerror(errno));
+    return nullptr;
+  }
+
+  // Check for symlink and other situations where
+  // file can have different names.
+  for (soinfo* si = solist; si != nullptr; si = si->next) {
+    if (si->get_st_dev() != 0 &&
+        si->get_st_ino() != 0 &&
+        si->get_st_dev() == file_stat.st_dev &&
+        si->get_st_ino() == file_stat.st_ino) {
+      TRACE("library \"%s\" is already loaded under different name/path \"%s\" - will return existing soinfo", name, si->name);
+      return si;
     }
+  }
 
-    if ((dlflags & RTLD_NOLOAD) != 0) {
-      return nullptr;
-    }
+  if ((dlflags & RTLD_NOLOAD) != 0) {
+    return nullptr;
+  }
 
-    // Read the ELF header and load the segments.
-    if (!elf_reader.Load(extinfo)) {
-        return nullptr;
-    }
+  // Read the ELF header and load the segments.
+  ElfReader elf_reader(name, fd);
+  if (!elf_reader.Load(extinfo)) {
+    return nullptr;
+  }
 
-    soinfo* si = soinfo_alloc(SEARCH_NAME(name), &file_stat);
-    if (si == nullptr) {
-        return nullptr;
-    }
-    si->base = elf_reader.load_start();
-    si->size = elf_reader.load_size();
-    si->load_bias = elf_reader.load_bias();
-    si->phnum = elf_reader.phdr_count();
-    si->phdr = elf_reader.loaded_phdr();
+  soinfo* si = soinfo_alloc(SEARCH_NAME(name), &file_stat);
+  if (si == nullptr) {
+    return nullptr;
+  }
+  si->base = elf_reader.load_start();
+  si->size = elf_reader.load_size();
+  si->load_bias = elf_reader.load_bias();
+  si->phnum = elf_reader.phdr_count();
+  si->phdr = elf_reader.loaded_phdr();
 
-    // At this point we know that whatever is loaded @ base is a valid ELF
-    // shared library whose segments are properly mapped in.
-    TRACE("[ load_library base=%p size=%zu name='%s' ]",
-          reinterpret_cast<void*>(si->base), si->size, si->name);
+  if (!si->PrelinkImage()) {
+    soinfo_free(si);
+    return nullptr;
+  }
 
-    if (!si->LinkImage(extinfo)) {
-      soinfo_free(si);
-      return nullptr;
-    }
+  for_each_dt_needed(si, [&] (const char* name) {
+    load_tasks.push_back(LoadTask::create(name, si));
+  });
 
-    return si;
+  return si;
 }
 
 static soinfo *find_loaded_library_by_name(const char* name) {
@@ -877,33 +910,122 @@
   return nullptr;
 }
 
-static soinfo* find_library_internal(const char* name, int dlflags, const android_dlextinfo* extinfo) {
-  if (name == nullptr) {
-    return somain;
-  }
+static soinfo* find_library_internal(LoadTaskList& load_tasks, const char* name, int dlflags, const android_dlextinfo* extinfo) {
 
   soinfo* si = find_loaded_library_by_name(name);
 
   // Library might still be loaded, the accurate detection
-  // of this fact is done by load_library
+  // of this fact is done by load_library.
   if (si == nullptr) {
     TRACE("[ '%s' has not been found by name.  Trying harder...]", name);
-    si = load_library(name, dlflags, extinfo);
-  }
-
-  if (si != nullptr && (si->flags & FLAG_LINKED) == 0) {
-    DL_ERR("recursive link to \"%s\"", si->name);
-    return nullptr;
+    si = load_library(load_tasks, name, dlflags, extinfo);
   }
 
   return si;
 }
 
-static soinfo* find_library(const char* name, int dlflags, const android_dlextinfo* extinfo) {
-  soinfo* si = find_library_internal(name, dlflags, extinfo);
-  if (si != nullptr) {
-    si->ref_count++;
+static void soinfo_unload(soinfo* si);
+
+static bool is_recursive(soinfo* si, soinfo* parent) {
+  if (parent == nullptr) {
+    return false;
   }
+
+  if (si == parent) {
+    DL_ERR("recursive link to \"%s\"", si->name);
+    return true;
+  }
+
+  return !parent->get_parents().visit([&](soinfo* grandparent) {
+    return !is_recursive(si, grandparent);
+  });
+}
+
+static bool find_libraries(const char* const library_names[], size_t library_names_size, soinfo* soinfos[],
+    soinfo* ld_preloads[], size_t ld_preloads_size, int dlflags, const android_dlextinfo* extinfo) {
+  // Step 0: prepare.
+  LoadTaskList load_tasks;
+  for (size_t i = 0; i < library_names_size; ++i) {
+    const char* name = library_names[i];
+    load_tasks.push_back(LoadTask::create(name, nullptr));
+  }
+
+  // Libraries added to this list in reverse order so that we can
+  // start linking from bottom-up - see step 2.
+  SoinfoLinkedList found_libs;
+  size_t soinfos_size = 0;
+
+  auto failure_guard = create_scope_guard([&]() {
+    // Housekeeping
+    load_tasks.for_each([] (LoadTask* t) {
+      LoadTask::deleter(t);
+    });
+
+    for (size_t i = 0; i<soinfos_size; ++i) {
+      soinfo_unload(soinfos[i]);
+    }
+  });
+
+  // Step 1: load and pre-link all DT_NEEDED libraries in breadth first order.
+  for (LoadTask::unique_ptr task(load_tasks.pop_front()); task.get() != nullptr; task.reset(load_tasks.pop_front())) {
+    soinfo* si = find_library_internal(load_tasks, task->get_name(), dlflags, extinfo);
+    if (si == nullptr) {
+      return false;
+    }
+
+    soinfo* needed_by = task->get_needed_by();
+
+    if (is_recursive(si, needed_by)) {
+      soinfo_free(si);
+      return false;
+    }
+
+    si->ref_count++;
+    if (needed_by != nullptr) {
+      needed_by->add_child(si);
+    }
+    found_libs.push_front(si);
+
+    // When ld_preloads is not null first
+    // ld_preloads_size libs are in fact ld_preloads.
+    if (ld_preloads != nullptr && soinfos_size < ld_preloads_size) {
+      ld_preloads[soinfos_size] = si;
+    }
+
+    if (soinfos_size<library_names_size) {
+      soinfos[soinfos_size++] = si;
+    }
+  }
+
+  // Step 2: link libraries.
+  soinfo* si;
+  while ((si = found_libs.pop_front()) != nullptr) {
+    if ((si->flags & FLAG_LINKED) == 0) {
+      if (!si->LinkImage(extinfo)) {
+        return false;
+      }
+      si->flags |= FLAG_LINKED;
+    }
+  }
+
+  // All is well - found_libs and load_tasks are empty at this point
+  // and all libs are successfully linked.
+  failure_guard.disable();
+  return true;
+}
+
+static soinfo* find_library(const char* name, int dlflags, const android_dlextinfo* extinfo) {
+  if (name == nullptr) {
+    somain->ref_count++;
+    return somain;
+  }
+
+  soinfo* si;
+
+  if (!find_libraries(&name, 1, &si, nullptr, 0, dlflags, extinfo)) {
+    return nullptr;
+  }
+
   return si;
 }
 
@@ -925,20 +1047,17 @@
         soinfo_unload(children[i]);
       }
     } else {
-      for (ElfW(Dyn)* d = si->dynamic; d->d_tag != DT_NULL; ++d) {
-        if (d->d_tag == DT_NEEDED) {
-          const char* library_name = si->strtab + d->d_un.d_val;
-          TRACE("%s needs to unload %s", si->name, library_name);
-          soinfo* needed = find_library(library_name, RTLD_NOLOAD, nullptr);
-          if (needed != nullptr) {
-            soinfo_unload(needed);
-          } else {
-            // Not found: for example if symlink was deleted between dlopen and dlclose
-            // Since we cannot really handle errors at this point - print and continue.
-            PRINT("warning: couldn't find %s needed by %s on unload.", library_name, si->name);
-          }
+      for_each_dt_needed(si, [&] (const char* library_name) {
+        TRACE("deprecated (old format of soinfo): %s needs to unload %s", si->name, library_name);
+        soinfo* needed = find_library(library_name, RTLD_NOLOAD, nullptr);
+        if (needed != nullptr) {
+          soinfo_unload(needed);
+        } else {
+          // Not found: for example if symlink was deleted between dlopen and dlclose
+          // Since we cannot really handle errors at this point - print and continue.
+          PRINT("warning: couldn't find %s needed by %s on unload.", library_name, si->name);
         }
-      }
+      });
     }
 
     notify_gdb_of_unload(si);
@@ -1047,9 +1166,6 @@
 
 #if defined(USE_RELA)
 int soinfo::Relocate(ElfW(Rela)* rela, unsigned count) {
-  ElfW(Sym)* s;
-  soinfo* lsi;
-
   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);
@@ -1061,6 +1177,10 @@
     if (type == 0) { // R_*_NONE
       continue;
     }
+
+    ElfW(Sym)* s = nullptr;
+    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);
@@ -1119,8 +1239,6 @@
         sym_addr = static_cast<ElfW(Addr)>(s->st_value + lsi->load_bias);
       }
       count_relocation(kRelocSymbol);
-    } else {
-      s = nullptr;
     }
 
     switch (type) {
@@ -1314,9 +1432,6 @@
 
 #else // REL, not RELA.
 int soinfo::Relocate(ElfW(Rel)* rel, unsigned count) {
-    ElfW(Sym)* s;
-    soinfo* lsi;
-
     for (size_t idx = 0; idx < count; ++idx, ++rel) {
         unsigned type = ELFW(R_TYPE)(rel->r_info);
         // TODO: don't use unsigned for 'sym'. Use uint32_t or ElfW(Addr) instead.
@@ -1329,6 +1444,10 @@
         if (type == 0) { // R_*_NONE
             continue;
         }
+
+        ElfW(Sym)* s = nullptr;
+        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);
@@ -1390,8 +1509,6 @@
                 sym_addr = static_cast<ElfW(Addr)>(s->st_value + lsi->load_bias);
             }
             count_relocation(kRelocSymbol);
-        } else {
-            s = nullptr;
         }
 
         switch (type) {
@@ -1546,7 +1663,7 @@
     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;
+        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.
@@ -1643,6 +1760,9 @@
 }
 
 void soinfo::CallDestructors() {
+  if (!constructors_called) {
+    return;
+  }
   TRACE("\"%s\": calling destructors", name);
 
   // DT_FINI_ARRAY must be parsed in reverse order.
@@ -1728,7 +1848,7 @@
   return false;
 }
 
-// This is a return on get_children() in case
+// This is a return on get_children()/get_parents() if
 // 'this->flags' does not have FLAG_NEW_SOINFO set.
 static soinfo::soinfo_list_t g_empty_list;
 
@@ -1740,6 +1860,14 @@
   return g_empty_list;
 }
 
+soinfo::soinfo_list_t& soinfo::get_parents() {
+  if ((this->flags & FLAG_NEW_SOINFO) == 0) {
+    return g_empty_list;
+  }
+
+  return this->parents;
+}
+
 /* Force any of the closed stdin, stdout and stderr to be associated with
    /dev/null. */
 static int nullify_closed_stdio() {
@@ -1801,20 +1929,18 @@
     return return_value;
 }
 
-bool soinfo::LinkImage(const android_dlextinfo* extinfo) {
-    bool relocating_linker = (flags & FLAG_LINKER) != 0;
+bool soinfo::PrelinkImage() {
+    phdr_table_get_dynamic_section(phdr, phnum, load_bias, &dynamic);
 
-    /* We can't debug anything until the linker is relocated */
+    /* We can't log anything until the linker is relocated */
+    bool relocating_linker = (flags & FLAG_LINKER) != 0;
     if (!relocating_linker) {
         INFO("[ linking %s ]", name);
         DEBUG("si->base = %p si->flags = 0x%08x", reinterpret_cast<void*>(base), flags);
     }
 
     /* Extract dynamic section */
-    size_t dynamic_count;
-    ElfW(Word) dynamic_flags;
-    phdr_table_get_dynamic_section(phdr, phnum, load_bias, &dynamic,
-                                   &dynamic_count, &dynamic_flags);
+    ElfW(Word) dynamic_flags = phdr->p_flags;
     if (dynamic == nullptr) {
         if (!relocating_linker) {
             DL_ERR("missing PT_DYNAMIC in \"%s\"", name);
@@ -1882,7 +2008,7 @@
             // if the dynamic table is writable
 // FIXME: not working currently for N64
 // The flags for the LOAD and DYNAMIC program headers do not agree.
-// The LOAD section containng the dynamic table has been mapped as
+// The LOAD section containing the dynamic table has been mapped as
 // read-only, but the DYNAMIC header claims it is writable.
 #if !(defined(__mips__) && defined(__LP64__))
             if ((dynamic_flags & PF_W) != 0) {
@@ -2028,38 +2154,10 @@
         DL_ERR("empty/missing DT_SYMTAB in \"%s\"", name);
         return false;
     }
+    return true;
+}
 
-    // If this is the main executable, then load all of the libraries from LD_PRELOAD now.
-    if (flags & FLAG_EXE) {
-        memset(g_ld_preloads, 0, sizeof(g_ld_preloads));
-        size_t preload_count = 0;
-        for (size_t i = 0; g_ld_preload_names[i] != nullptr; i++) {
-            soinfo* lsi = find_library(g_ld_preload_names[i], 0, nullptr);
-            if (lsi != nullptr) {
-                g_ld_preloads[preload_count++] = lsi;
-            } else {
-                // As with glibc, failure to load an LD_PRELOAD library is just a warning.
-                DL_WARN("could not load library \"%s\" from LD_PRELOAD for \"%s\"; caused by %s",
-                        g_ld_preload_names[i], name, linker_get_error_buffer());
-            }
-        }
-    }
-
-    for (ElfW(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;
-            DEBUG("%s needs %s", name, library_name);
-            soinfo* lsi = find_library(library_name, 0, nullptr);
-            if (lsi == nullptr) {
-                strlcpy(tmp_err_buf, linker_get_error_buffer(), sizeof(tmp_err_buf));
-                DL_ERR("could not load library \"%s\" needed by \"%s\"; caused by %s",
-                       library_name, name, tmp_err_buf);
-                return false;
-            }
-
-            add_child(lsi);
-        }
-    }
+bool soinfo::LinkImage(const android_dlextinfo* extinfo) {
 
 #if !defined(__LP64__)
     if (has_text_relocations) {
@@ -2121,7 +2219,6 @@
     }
 #endif
 
-    flags |= FLAG_LINKED;
     DEBUG("[ finished linking %s ]", name);
 
 #if !defined(__LP64__)
@@ -2183,6 +2280,7 @@
   si->size = phdr_table_get_load_size(si->phdr, si->phnum);
   si->load_bias = get_elf_exec_load_bias(ehdr_vdso);
 
+  si->PrelinkImage();
   si->LinkImage(nullptr);
 #endif
 }
@@ -2216,7 +2314,7 @@
   ElfW(Ehdr)* elf_hdr = reinterpret_cast<ElfW(Ehdr)*>(linker_base);
   ElfW(Phdr)* phdr = reinterpret_cast<ElfW(Phdr)*>(linker_base + elf_hdr->e_phoff);
   phdr_table_get_dynamic_section(phdr, elf_hdr->e_phnum, linker_base,
-                                 &linker_soinfo_for_gdb.dynamic, nullptr, nullptr);
+                                 &linker_soinfo_for_gdb.dynamic);
   insert_soinfo_into_debug_map(&linker_soinfo_for_gdb);
 }
 
@@ -2312,6 +2410,37 @@
 
     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);
@@ -2321,11 +2450,7 @@
 
     si->CallPreInitConstructors();
 
-    for (size_t i = 0; g_ld_preloads[i] != nullptr; ++i) {
-        g_ld_preloads[i]->CallConstructors();
-    }
-
-    /* After the LinkImage, the si->load_bias is initialized.
+    /* After the PrelinkImage, the si->load_bias is initialized.
      * For so lib, the map->l_addr will be updated in notify_gdb_of_load.
      * We need to update this value for so exe here. So Unwind_Backtrace
      * for some arch like x86 could work correctly within so exe.
@@ -2440,7 +2565,7 @@
   linker_so.phnum = elf_hdr->e_phnum;
   linker_so.flags |= FLAG_LINKER;
 
-  if (!linker_so.LinkImage(nullptr)) {
+  if (!(linker_so.PrelinkImage() && linker_so.LinkImage(nullptr))) {
     // It would be nice to print an error message, but if the linker
     // can't link itself, there's no guarantee that we'll be able to
     // call write() (because it involves a GOT reference). We may as
diff --git a/linker/linker.h b/linker/linker.h
index 6547d68..3024d3a 100644
--- a/linker/linker.h
+++ b/linker/linker.h
@@ -204,6 +204,7 @@
   void CallConstructors();
   void CallDestructors();
   void CallPreInitConstructors();
+  bool PrelinkImage();
   bool LinkImage(const android_dlextinfo* extinfo);
 
   void add_child(soinfo* child);
@@ -217,6 +218,7 @@
   bool get_has_ifuncs();
 
   soinfo_list_t& get_children();
+  soinfo_list_t& get_parents();
 
   bool inline has_min_version(uint32_t min_version) {
     return (flags & FLAG_NEW_SOINFO) != 0 && version >= min_version;
diff --git a/linker/linker_phdr.cpp b/linker/linker_phdr.cpp
index 1bbd577..4365172 100644
--- a/linker/linker_phdr.cpp
+++ b/linker/linker_phdr.cpp
@@ -702,34 +702,17 @@
  *   load_bias   -> load bias
  * Output:
  *   dynamic       -> address of table in memory (null on failure).
- *   dynamic_count -> number of items in table (0 on failure).
- *   dynamic_flags -> protection flags for section (unset on failure)
  * Return:
  *   void
  */
 void phdr_table_get_dynamic_section(const ElfW(Phdr)* phdr_table, size_t phdr_count,
-                                    ElfW(Addr) load_bias,
-                                    ElfW(Dyn)** dynamic, size_t* dynamic_count, ElfW(Word)* dynamic_flags) {
-  const ElfW(Phdr)* phdr = phdr_table;
-  const ElfW(Phdr)* phdr_limit = phdr + phdr_count;
-
-  for (phdr = phdr_table; phdr < phdr_limit; phdr++) {
-    if (phdr->p_type != PT_DYNAMIC) {
-      continue;
-    }
-
-    *dynamic = reinterpret_cast<ElfW(Dyn)*>(load_bias + phdr->p_vaddr);
-    if (dynamic_count) {
-      *dynamic_count = (unsigned)(phdr->p_memsz / 8);
-    }
-    if (dynamic_flags) {
-      *dynamic_flags = phdr->p_flags;
-    }
-    return;
-  }
+                                    ElfW(Addr) load_bias, ElfW(Dyn)** dynamic) {
   *dynamic = nullptr;
-  if (dynamic_count) {
-    *dynamic_count = 0;
+  for (const ElfW(Phdr)* phdr = phdr_table, *phdr_limit = phdr + phdr_count; phdr < phdr_limit; phdr++) {
+    if (phdr->p_type == PT_DYNAMIC) {
+      *dynamic = reinterpret_cast<ElfW(Dyn)*>(load_bias + phdr->p_vaddr);
+      return;
+    }
   }
 }
 
diff --git a/linker/linker_phdr.h b/linker/linker_phdr.h
index 50708a0..d4c3ce8 100644
--- a/linker/linker_phdr.h
+++ b/linker/linker_phdr.h
@@ -101,7 +101,6 @@
 #endif
 
 void phdr_table_get_dynamic_section(const ElfW(Phdr)* phdr_table, size_t phdr_count,
-                                    ElfW(Addr) load_bias,
-                                    ElfW(Dyn)** dynamic, size_t* dynamic_count, ElfW(Word)* dynamic_flags);
+                                    ElfW(Addr) load_bias, ElfW(Dyn)** dynamic);
 
 #endif /* LINKER_PHDR_H */
diff --git a/tests/Android.mk b/tests/Android.mk
index 26014ac..cb588d7 100644
--- a/tests/Android.mk
+++ b/tests/Android.mk
@@ -114,6 +114,7 @@
     system_properties_test.cpp \
     time_test.cpp \
     uchar_test.cpp \
+    uniqueptr_test.cpp \
     unistd_test.cpp \
     wchar_test.cpp \
 
diff --git a/tests/dlext_test.cpp b/tests/dlext_test.cpp
index 9a96b67..7bd59c8 100644
--- a/tests/dlext_test.cpp
+++ b/tests/dlext_test.cpp
@@ -260,6 +260,11 @@
 }
 
 TEST_F(DlExtRelroSharingTest, VerifyMemorySaving) {
+  if (geteuid() != 0) {
+    GTEST_LOG_(INFO) << "This test must be run as root.\n";
+    return;
+  }
+
   ASSERT_NO_FATAL_FAILURE(CreateRelroFile(LIBNAME));
   int relro_fd = open(relro_file_, O_RDONLY);
   ASSERT_NOERROR(relro_fd);
diff --git a/tests/dlfcn_test.cpp b/tests/dlfcn_test.cpp
index 6bdde44..ccfd743 100644
--- a/tests/dlfcn_test.cpp
+++ b/tests/dlfcn_test.cpp
@@ -130,6 +130,55 @@
 }
 #endif
 
+TEST(dlfcn, dlopen_check_order) {
+  // Here is how the test library and its dt_needed
+  // libraries are arranged
+  //
+  //  libtest_check_order.so
+  //  |
+  //  +-> libtest_check_order_1_left.so
+  //  |   |
+  //  |   +-> libtest_check_order_a.so
+  //  |   |
+  //  |   +-> libtest_check_order_b.so
+  //  |
+  //  +-> libtest_check_order_2_right.so
+  //  |   |
+  //  |   +-> libtest_check_order_d.so
+  //  |       |
+  //  |       +-> libtest_check_order_b.so
+  //  |
+  //  +-> libtest_check_order_3_c.so
+  //
+  //  load order should be (1, 2, 3, a, b, d)
+  //
+  // get_answer() is defined in (2, 3, a, b, c)
+  // get_answer2() is defined in (b, d)
+  void* sym = dlsym(RTLD_DEFAULT, "dlopen_test_get_answer");
+  ASSERT_TRUE(sym == nullptr);
+  void* handle = dlopen("libtest_check_order.so", RTLD_NOW);
+  ASSERT_TRUE(handle != nullptr);
+  typedef int (*fn_t) (void);
+  fn_t fn, fn2;
+  fn = reinterpret_cast<fn_t>(dlsym(RTLD_DEFAULT, "dlopen_test_get_answer"));
+  ASSERT_TRUE(fn != NULL);
+  fn2 = reinterpret_cast<fn_t>(dlsym(RTLD_DEFAULT, "dlopen_test_get_answer2"));
+  ASSERT_TRUE(fn2 != NULL);
+
+  ASSERT_EQ(42, fn());
+  ASSERT_EQ(43, fn2());
+  dlclose(handle);
+}
+
+// libtest_with_dependency_loop.so -> libtest_with_dependency_loop_a.so ->
+// libtest_with_dependency_loop_b.so -> libtest_with_dependency_loop_c.so ->
+// libtest_with_dependency_loop_a.so
+TEST(dlfcn, dlopen_check_loop) {
+  void* handle = dlopen("libtest_with_dependency_loop.so", RTLD_NOW);
+  ASSERT_TRUE(handle == NULL);
+  ASSERT_STREQ("dlopen failed: recursive link to \"libtest_with_dependency_loop_a.so\"", dlerror());
+}
+
 TEST(dlfcn, dlopen_failure) {
   void* self = dlopen("/does/not/exist", RTLD_NOW);
   ASSERT_TRUE(self == NULL);
diff --git a/tests/libs/Android.mk b/tests/libs/Android.mk
index b1cc836..2ceb15b 100644
--- a/tests/libs/Android.mk
+++ b/tests/libs/Android.mk
@@ -103,6 +103,160 @@
 include $(TEST_PATH)/Android.build.mk
 
 # -----------------------------------------------------------------------------
+# Libraries used by dlfcn tests to verify correct load order:
+# libtest_check_order_2_right.so
+# -----------------------------------------------------------------------------
+libtest_check_order_2_right_src_files := \
+    dlopen_testlib_answer.cpp
+
+libtest_check_order_2_right_cflags := -D__ANSWER=42
+module := libtest_check_order_2_right
+build_type := target
+build_target := SHARED_LIBRARY
+include $(TEST_PATH)/Android.build.mk
+
+# -----------------------------------------------------------------------------
+# libtest_check_order_a.so
+# -----------------------------------------------------------------------------
+libtest_check_order_a_src_files := \
+    dlopen_testlib_answer.cpp
+
+libtest_check_order_a_cflags := -D__ANSWER=1
+module := libtest_check_order_a
+build_type := target
+build_target := SHARED_LIBRARY
+include $(TEST_PATH)/Android.build.mk
+
+# -----------------------------------------------------------------------------
+# libtest_check_order_b.so
+# -----------------------------------------------------------------------------
+libtest_check_order_b_src_files := \
+    dlopen_testlib_answer.cpp
+
+libtest_check_order_b_cflags := -D__ANSWER=2 -D__ANSWER2=43
+module := libtest_check_order_b
+build_type := target
+build_target := SHARED_LIBRARY
+include $(TEST_PATH)/Android.build.mk
+
+# -----------------------------------------------------------------------------
+# libtest_check_order_c.so
+# -----------------------------------------------------------------------------
+libtest_check_order_3_c_src_files := \
+    dlopen_testlib_answer.cpp
+
+libtest_check_order_3_c_cflags := -D__ANSWER=3
+module := libtest_check_order_3_c
+build_type := target
+build_target := SHARED_LIBRARY
+include $(TEST_PATH)/Android.build.mk
+
+# -----------------------------------------------------------------------------
+# libtest_check_order_d.so
+# -----------------------------------------------------------------------------
+libtest_check_order_d_src_files := \
+   dlopen_testlib_answer.cpp
+
+libtest_check_order_d_shared_libraries := libtest_check_order_b
+libtest_check_order_d_cflags := -D__ANSWER=4 -D__ANSWER2=4
+module := libtest_check_order_d
+build_type := target
+build_target := SHARED_LIBRARY
+include $(TEST_PATH)/Android.build.mk
+
+# -----------------------------------------------------------------------------
+# libtest_check_order_left.so
+# -----------------------------------------------------------------------------
+libtest_check_order_1_left_src_files := \
+    empty.cpp
+
+libtest_check_order_1_left_shared_libraries := libtest_check_order_a libtest_check_order_b
+
+module := libtest_check_order_1_left
+build_type := target
+build_target := SHARED_LIBRARY
+include $(TEST_PATH)/Android.build.mk
+
+# -----------------------------------------------------------------------------
+# libtest_check_order.so
+# -----------------------------------------------------------------------------
+libtest_check_order_src_files := \
+    empty.cpp
+
+libtest_check_order_shared_libraries := libtest_check_order_1_left \
+  libtest_check_order_2_right libtest_check_order_3_c
+
+module := libtest_check_order
+build_type := target
+build_target := SHARED_LIBRARY
+include $(TEST_PATH)/Android.build.mk
+
+# -----------------------------------------------------------------------------
+# Library with dependency loop used by dlfcn tests
+#
+# libtest_with_dependency_loop -> a -> b -> c -> a
+# -----------------------------------------------------------------------------
+libtest_with_dependency_loop_src_files := empty.cpp
+
+libtest_with_dependency_loop_shared_libraries := \
+    libtest_with_dependency_loop_a
+
+module := libtest_with_dependency_loop
+build_type := target
+build_target := SHARED_LIBRARY
+include $(TEST_PATH)/Android.build.mk
+
+# -----------------------------------------------------------------------------
+# libtest_with_dependency_loop_a.so
+# -----------------------------------------------------------------------------
+libtest_with_dependency_loop_a_src_files := empty.cpp
+
+libtest_with_dependency_loop_a_shared_libraries := \
+    libtest_with_dependency_loop_b_tmp
+
+module := libtest_with_dependency_loop_a
+build_type := target
+build_target := SHARED_LIBRARY
+include $(TEST_PATH)/Android.build.mk
+
+# -----------------------------------------------------------------------------
+# libtest_with_dependency_loop_b.so
+#
+# this is temporary placeholder - will be removed
+# -----------------------------------------------------------------------------
+libtest_with_dependency_loop_b_tmp_src_files := empty.cpp
+libtest_with_dependency_loop_b_tmp_ldflags := -Wl,-soname=libtest_with_dependency_loop_b.so
+
+module := libtest_with_dependency_loop_b_tmp
+build_type := target
+build_target := SHARED_LIBRARY
+include $(TEST_PATH)/Android.build.mk
+
+# -----------------------------------------------------------------------------
+# libtest_with_dependency_loop_b.so
+# -----------------------------------------------------------------------------
+libtest_with_dependency_loop_b_src_files := empty.cpp
+libtest_with_dependency_loop_b_shared_libraries := libtest_with_dependency_loop_c
+
+module := libtest_with_dependency_loop_b
+build_type := target
+build_target := SHARED_LIBRARY
+include $(TEST_PATH)/Android.build.mk
+
+# -----------------------------------------------------------------------------
+# libtest_with_dependency_loop_c.so
+# -----------------------------------------------------------------------------
+libtest_with_dependency_loop_c_src_files := empty.cpp
+
+libtest_with_dependency_loop_c_shared_libraries := \
+    libtest_with_dependency_loop_a
+
+module := libtest_with_dependency_loop_c
+build_type := target
+build_target := SHARED_LIBRARY
+include $(TEST_PATH)/Android.build.mk
+
+# -----------------------------------------------------------------------------
 # Library with dependency used by dlfcn tests
 # -----------------------------------------------------------------------------
 libtest_with_dependency_src_files := \
diff --git a/tests/libs/dlopen_testlib_answer.cpp b/tests/libs/dlopen_testlib_answer.cpp
new file mode 100644
index 0000000..a4d7504
--- /dev/null
+++ b/tests/libs/dlopen_testlib_answer.cpp
@@ -0,0 +1,25 @@
+/*
+ * Copyright (C) 2014 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+extern "C" int dlopen_test_get_answer() {
+  return __ANSWER;
+}
+
+#ifdef __ANSWER2
+extern "C" int dlopen_test_get_answer2() {
+  return __ANSWER2;
+}
+#endif
diff --git a/tests/signal_test.cpp b/tests/signal_test.cpp
index 89b8088..e53fd3a 100644
--- a/tests/signal_test.cpp
+++ b/tests/signal_test.cpp
@@ -14,10 +14,10 @@
  * limitations under the License.
  */
 
-#include <gtest/gtest.h>
+#include <signal.h>
 
 #include <errno.h>
-#include <signal.h>
+#include <gtest/gtest.h>
 
 #include "ScopedSignalHandler.h"
 
@@ -198,13 +198,19 @@
 static void EmptySignalAction(int, siginfo_t*, void*) {}
 
 TEST(signal, sigaction) {
+  // Both bionic and glibc set SA_RESTORER when talking to the kernel on arm,
+  // arm64, x86, and x86-64. The version of glibc we're using also doesn't
+  // define SA_RESTORER, but luckily it's the same value everywhere, and mips
+  // doesn't use the bit for anything.
+  static const int sa_restorer = 0x4000000;
+
   // See what's currently set for SIGALRM.
   struct sigaction original_sa;
   memset(&original_sa, 0, sizeof(original_sa));
   ASSERT_EQ(0, sigaction(SIGALRM, NULL, &original_sa));
   ASSERT_TRUE(original_sa.sa_handler == NULL);
   ASSERT_TRUE(original_sa.sa_sigaction == NULL);
-  ASSERT_TRUE(original_sa.sa_flags == 0);
+  ASSERT_EQ(0, original_sa.sa_flags & ~sa_restorer);
 
   // Set a traditional sa_handler signal handler.
   struct sigaction sa;
@@ -219,7 +225,7 @@
   ASSERT_EQ(0, sigaction(SIGALRM, NULL, &sa));
   ASSERT_TRUE(sa.sa_handler == EmptySignalHandler);
   ASSERT_TRUE((void*) sa.sa_sigaction == (void*) sa.sa_handler);
-  ASSERT_TRUE(sa.sa_flags == SA_ONSTACK);
+  ASSERT_EQ(SA_ONSTACK, sa.sa_flags & ~sa_restorer);
 
   // Set a new-style sa_sigaction signal handler.
   memset(&sa, 0, sizeof(sa));
@@ -233,7 +239,7 @@
   ASSERT_EQ(0, sigaction(SIGALRM, NULL, &sa));
   ASSERT_TRUE(sa.sa_sigaction == EmptySignalAction);
   ASSERT_TRUE((void*) sa.sa_sigaction == (void*) sa.sa_handler);
-  ASSERT_TRUE(sa.sa_flags == (SA_ONSTACK | SA_SIGINFO));
+  ASSERT_EQ((SA_ONSTACK | SA_SIGINFO), sa.sa_flags & ~sa_restorer);
 
   // Put everything back how it was.
   ASSERT_EQ(0, sigaction(SIGALRM, &original_sa, NULL));
diff --git a/tests/string_test.cpp b/tests/string_test.cpp
index 7db8e21..ad0040a 100644
--- a/tests/string_test.cpp
+++ b/tests/string_test.cpp
@@ -137,8 +137,7 @@
   ASSERT_STREQ("Unknown signal 1001", strsignal1001);
 }
 
-// TODO: where did these numbers come from?
-#define POS_ITER    10
+// TODO: where did this number come from?
 #define ITER        500
 
 // For every length we want to test, vary and change alignment
@@ -147,8 +146,9 @@
 // These tests contributed by Intel Corporation.
 // TODO: make these tests more intention-revealing and less random.
 template<class Character>
-struct StringTestState {
-  StringTestState(size_t MAX_LEN) : MAX_LEN(MAX_LEN) {
+class StringTestState {
+ public:
+  StringTestState(size_t MAX_LEN) : MAX_LEN(MAX_LEN), align1_index_(0), align2_index_(0) {
     int max_alignment = 64;
 
     // TODO: fix the tests to not sometimes use twice their specified "MAX_LEN".
@@ -167,15 +167,30 @@
     free(glob_ptr2);
   }
 
-  void NewIteration() {
-    int alignments[] = { 24, 32, 16, 48, 1, 2, 3, 0, 5, 11 };
-    int usable_alignments = 10;
-    int align1 = alignments[random() % (usable_alignments - 1)];
-    int align2 = alignments[random() % (usable_alignments - 1)];
+  void BeginIterations() {
+    align1_index_ = 0;
+    align2_index_ = 0;
 
-    ptr = glob_ptr + align1;
-    ptr1 = glob_ptr1 + align1;
-    ptr2 = glob_ptr2 + align2;
+    ResetPointers();
+  }
+
+  bool HasNextIteration() {
+    return (align1_index_ != (alignments_size - 1) || align2_index_ != (alignments_size - 1));
+  }
+
+  void NextIteration() {
+    if (align1_index_ == (alignments_size - 1) && align2_index_ == (alignments_size - 1)) {
+      return;
+    }
+
+    if (align1_index_ == (alignments_size - 1)) {
+      align1_index_ = 0;
+      align2_index_++;
+    } else {
+      align1_index_++;
+    }
+
+    ResetPointers();
   }
 
   const size_t MAX_LEN;
@@ -184,7 +199,10 @@
   int len[ITER + 1];
 
  private:
+  static size_t alignments[];
+  static size_t alignments_size;
   Character *glob_ptr, *glob_ptr1, *glob_ptr2;
+  size_t align1_index_, align2_index_;
 
   // Calculate input lengths and fill state.len with them.
   // Test small lengths with more density than big ones. Manually push
@@ -201,19 +219,33 @@
     }
     len[n++] = MAX_LEN;
   }
+
+  void ResetPointers() {
+    if (align1_index_ == alignments_size || align2_index_ == alignments_size) {
+      ptr = ptr1 = ptr2 = nullptr;
+    } else {
+      ptr = glob_ptr + alignments[align1_index_];
+      ptr1 = glob_ptr1 + alignments[align1_index_];
+      ptr2 = glob_ptr2 + alignments[align2_index_];
+    }
+  }
 };
 
+template<class Character>
+size_t StringTestState<Character>::alignments[] = { 24, 32, 16, 48, 0, 1, 2, 3, 4, 5, 6, 7, 11 };
+
+template<class Character>
+size_t StringTestState<Character>::alignments_size = sizeof(alignments)/sizeof(size_t);
+
 TEST(string, strcat) {
   StringTestState<char> state(SMALL);
   for (size_t i = 1; i < state.n; i++) {
-    for (size_t j = 0; j < POS_ITER; j++) {
-      state.NewIteration();
-
+    for (state.BeginIterations(); state.HasNextIteration(); state.NextIteration()) {
       memset(state.ptr2, '\2', state.MAX_LEN);
       state.ptr2[state.MAX_LEN - 1] = '\0';
       memcpy(state.ptr, state.ptr2, 2 * state.MAX_LEN);
 
-      memset(state.ptr1, random() & 255, state.len[i]);
+      memset(state.ptr1, 'L', state.len[i]);
       state.ptr1[random() % state.len[i]] = '\0';
       state.ptr1[state.len[i] - 1] = '\0';
 
@@ -386,13 +418,11 @@
 }
 
 TEST(string, strchr) {
-  int seek_char = random() & 255;
+  int seek_char = 'R';
 
   StringTestState<char> state(SMALL);
   for (size_t i = 1; i < state.n; i++) {
-    for (size_t j = 0; j < POS_ITER; j++) {
-      state.NewIteration();
-
+    for (state.BeginIterations(); state.HasNextIteration(); state.NextIteration()) {
       if (~seek_char > 0) {
         memset(state.ptr1, ~seek_char, state.len[i]);
       } else {
@@ -421,9 +451,7 @@
 TEST(string, strcmp) {
   StringTestState<char> state(SMALL);
   for (size_t i = 1; i < state.n; i++) {
-    for (size_t j = 0; j < POS_ITER; j++) {
-      state.NewIteration();
-
+    for (state.BeginIterations(); state.HasNextIteration(); state.NextIteration()) {
       memset(state.ptr1, 'v', state.MAX_LEN);
       memset(state.ptr2, 'n', state.MAX_LEN);
       state.ptr1[state.len[i] - 1] = '\0';
@@ -457,9 +485,7 @@
 
 TEST(string, stpcpy) {
   StringTestState<char> state(SMALL);
-  for (size_t j = 0; j < POS_ITER; j++) {
-    state.NewIteration();
-
+  for (state.BeginIterations(); state.HasNextIteration(); state.NextIteration()) {
     size_t pos = random() % state.MAX_LEN;
 
     memset(state.ptr1, '\2', pos);
@@ -483,9 +509,7 @@
 
 TEST(string, strcpy) {
   StringTestState<char> state(SMALL);
-  for (size_t j = 0; j < POS_ITER; j++) {
-    state.NewIteration();
-
+  for (state.BeginIterations(); state.HasNextIteration(); state.NextIteration()) {
     size_t pos = random() % state.MAX_LEN;
 
     memset(state.ptr1, '\2', pos);
@@ -511,9 +535,7 @@
 #if defined(__BIONIC__)
   StringTestState<char> state(SMALL);
   for (size_t i = 0; i < state.n; i++) {
-    for (size_t j = 0; j < POS_ITER; j++) {
-      state.NewIteration();
-
+    for (state.BeginIterations(); state.HasNextIteration(); state.NextIteration()) {
       memset(state.ptr2, '\2', state.MAX_LEN + state.len[i]);
       state.ptr2[state.MAX_LEN - 1] = '\0';
       memcpy(state.ptr, state.ptr2, state.MAX_LEN + state.len[i]);
@@ -541,13 +563,8 @@
 TEST(string, strlcpy) {
 #if defined(__BIONIC__)
   StringTestState<char> state(SMALL);
-  for (size_t j = 0; j < POS_ITER; j++) {
-    state.NewIteration();
-
-    int rand = random() & 255;
-    if (rand < 1) {
-      rand = 1;
-    }
+  for (state.BeginIterations(); state.HasNextIteration(); state.NextIteration()) {
+    int rand = 'O';
     memset(state.ptr1, rand, state.MAX_LEN);
 
     size_t pos = random() % state.MAX_LEN;
@@ -556,7 +573,7 @@
     }
     memcpy(state.ptr, state.ptr1, state.MAX_LEN);
 
-    memset(state.ptr2, random() & 255, state.MAX_LEN);
+    memset(state.ptr2, 'I', state.MAX_LEN);
     memcpy(state.ptr + state.MAX_LEN, state.ptr2, state.MAX_LEN);
 
     if (pos > state.MAX_LEN - 1) {
@@ -578,14 +595,12 @@
 TEST(string, strncat) {
   StringTestState<char> state(SMALL);
   for (size_t i = 1; i < state.n; i++) {
-    for (size_t j = 0; j < POS_ITER; j++) {
-      state.NewIteration();
-
+    for (state.BeginIterations(); state.HasNextIteration(); state.NextIteration()) {
       memset(state.ptr2, '\2', state.MAX_LEN);
       state.ptr2[state.MAX_LEN - 1] = '\0';
       memcpy(state.ptr, state.ptr2, 2 * state.MAX_LEN);
 
-      memset(state.ptr1, random() & 255, state.len[i]);
+      memset(state.ptr1, 'I', state.len[i]);
       state.ptr1[random() % state.len[i]] = '\0';
       state.ptr1[state.len[i] - 1] = '\0';
 
@@ -604,9 +619,7 @@
 TEST(string, strncmp) {
   StringTestState<char> state(SMALL);
   for (size_t i = 1; i < state.n; i++) {
-    for (size_t j = 0; j < POS_ITER; j++) {
-      state.NewIteration();
-
+    for (state.BeginIterations(); state.HasNextIteration(); state.NextIteration()) {
       memset(state.ptr1, 'v', state.MAX_LEN);
       memset(state.ptr2, 'n', state.MAX_LEN);
       state.ptr1[state.len[i] - 1] = '\0';
@@ -640,12 +653,8 @@
 
 TEST(string, stpncpy) {
   StringTestState<char> state(SMALL);
-  for (size_t j = 0; j < ITER; j++) {
-    state.NewIteration();
-
-    // Choose a random value to fill the string, except \0 (string terminator),
-    // or \1 (guarantees it's different from anything in ptr2).
-    memset(state.ptr1, (random() % 254) + 2, state.MAX_LEN);
+  for (state.BeginIterations(); state.HasNextIteration(); state.NextIteration()) {
+    memset(state.ptr1, 'J', state.MAX_LEN);
     // Choose a random size for our src buffer.
     size_t ptr1_len = random() % state.MAX_LEN;
     state.ptr1[ptr1_len] = '\0';
@@ -679,12 +688,10 @@
 
 TEST(string, strncpy) {
   StringTestState<char> state(SMALL);
-  for (size_t j = 0; j < ITER; j++) {
-    state.NewIteration();
-
+  for (state.BeginIterations(); state.HasNextIteration(); state.NextIteration()) {
     // Choose a random value to fill the string, except \0 (string terminator),
     // or \1 (guarantees it's different from anything in ptr2).
-    memset(state.ptr1, (random() % 254) + 2, state.MAX_LEN);
+    memset(state.ptr1, 'K', state.MAX_LEN);
     // Choose a random size for our src buffer.
     size_t ptr1_len = random() % state.MAX_LEN;
     state.ptr1[ptr1_len] = '\0';
@@ -717,12 +724,10 @@
 }
 
 TEST(string, strrchr) {
-  int seek_char = random() & 255;
+  int seek_char = 'M';
   StringTestState<char> state(SMALL);
   for (size_t i = 1; i < state.n; i++) {
-    for (size_t j = 0; j < POS_ITER; j++) {
-      state.NewIteration();
-
+    for (state.BeginIterations(); state.HasNextIteration(); state.NextIteration()) {
       if (~seek_char > 0) {
         memset(state.ptr1, ~seek_char, state.len[i]);
       } else {
@@ -749,12 +754,10 @@
 }
 
 TEST(string, memchr) {
-  int seek_char = random() & 255;
+  int seek_char = 'N';
   StringTestState<char> state(SMALL);
   for (size_t i = 0; i < state.n; i++) {
-    for (size_t j = 0; j < POS_ITER; j++) {
-      state.NewIteration();
-
+    for (state.BeginIterations(); state.HasNextIteration(); state.NextIteration()) {
       memset(state.ptr1, ~seek_char, state.len[i]);
 
       int pos = random() % state.MAX_LEN;
@@ -780,12 +783,10 @@
 }
 
 TEST(string, memrchr) {
-  int seek_char = random() & 255;
+  int seek_char = 'P';
   StringTestState<char> state(SMALL);
   for (size_t i = 0; i < state.n; i++) {
-    for (size_t j = 0; j < POS_ITER; j++) {
-      state.NewIteration();
-
+    for (state.BeginIterations(); state.HasNextIteration(); state.NextIteration()) {
       memset(state.ptr1, ~seek_char, state.len[i]);
 
       int pos = random() % state.MAX_LEN;
@@ -805,11 +806,9 @@
 TEST(string, memcmp) {
   StringTestState<char> state(SMALL);
   for (size_t i = 0; i < state.n; i++) {
-    for (size_t j = 0; j < POS_ITER; j++) {
-      state.NewIteration();
-
-      int c1 = random() & 0xff;
-      int c2 = random() & 0xff;
+    for (state.BeginIterations(); state.HasNextIteration(); state.NextIteration()) {
+      int c1 = 'A';
+      int c2 = 'N';
       memset(state.ptr1, c1, state.MAX_LEN);
       memset(state.ptr2, c1, state.MAX_LEN);
 
@@ -828,9 +827,7 @@
   StringTestState<wchar_t> state(SMALL);
 
   for (size_t i = 0; i < state.n; i++) {
-    for (size_t j = 0; j < POS_ITER; j++) {
-      state.NewIteration();
-
+    for (state.BeginIterations(); state.HasNextIteration(); state.NextIteration()) {
       long long mask = ((long long) 1 << 8 * sizeof(wchar_t)) - 1;
       int c1 = rand() & mask;
       int c2 = rand() & mask;
@@ -850,11 +847,9 @@
 
 TEST(string, memcpy) {
   StringTestState<char> state(LARGE);
-  int rand = random() & 255;
+  int rand = 4;
   for (size_t i = 0; i < state.n - 1; i++) {
-    for (size_t j = 0; j < POS_ITER; j++) {
-      state.NewIteration();
-
+    for (state.BeginIterations(); state.HasNextIteration(); state.NextIteration()) {
       size_t pos = random() % (state.MAX_LEN - state.len[i]);
 
       memset(state.ptr1, rand, state.len[i]);
@@ -872,11 +867,9 @@
 
 TEST(string, memset) {
   StringTestState<char> state(LARGE);
-  char ch = random () & 255;
+  char ch = 'P';
   for (size_t i = 0; i < state.n - 1; i++) {
-    for (size_t j = 0; j < POS_ITER; j++) {
-      state.NewIteration();
-
+    for (state.BeginIterations(); state.HasNextIteration(); state.NextIteration()) {
       memset(state.ptr1, ~ch, state.MAX_LEN);
       memcpy(state.ptr2, state.ptr1, state.MAX_LEN);
 
@@ -895,14 +888,12 @@
 TEST(string, memmove) {
   StringTestState<char> state(LARGE);
   for (size_t i = 0; i < state.n - 1; i++) {
-    for (size_t j = 0; j < POS_ITER; j++) {
-      state.NewIteration();
-
-      memset(state.ptr1, random() & 255, 2 * state.MAX_LEN);
+    for (state.BeginIterations(); state.HasNextIteration(); state.NextIteration()) {
+      memset(state.ptr1, 'Q', 2 * state.MAX_LEN);
 
       size_t pos = random() % (state.MAX_LEN - state.len[i]);
 
-      memset(state.ptr1, random() & 255, state.len[i]);
+      memset(state.ptr1, 'R', state.len[i]);
       memcpy(state.ptr2, state.ptr1, 2 * state.MAX_LEN);
       memcpy(state.ptr, state.ptr1, state.len[i]);
       memcpy(state.ptr1 + pos, state.ptr, state.len[i]);
@@ -928,8 +919,8 @@
 
   for (int i = 0; i < 5; i++) {
     char* ptr2 = glob_ptr2 + alignments[i];
-    memset(ptr1, random() & 255, 2 * len);
-    memset(ptr1, random() & 255, len);
+    memset(ptr1, 'S', 2 * len);
+    memset(ptr1, 'T', len);
     memcpy(ptr2, ptr1, 2 * len);
     memcpy(ptr, ptr1, len);
     memcpy(ptr1 + pos, ptr, len);
@@ -995,11 +986,9 @@
 TEST(string, bcopy) {
   StringTestState<char> state(LARGE);
   for (size_t i = 0; i < state.n; i++) {
-    for (size_t j = 0; j < POS_ITER; j++) {
-      state.NewIteration();
-
-      memset(state.ptr1, random() & 255, state.MAX_LEN);
-      memset(state.ptr1 + state.MAX_LEN, random() & 255, state.MAX_LEN);
+    for (state.BeginIterations(); state.HasNextIteration(); state.NextIteration()) {
+      memset(state.ptr1, '4', state.MAX_LEN);
+      memset(state.ptr1 + state.MAX_LEN, 'a', state.MAX_LEN);
       memcpy(state.ptr2, state.ptr1, 2 * state.MAX_LEN);
 
       size_t start = random() % (2 * state.MAX_LEN - state.len[i]);
@@ -1013,10 +1002,8 @@
 
 TEST(string, bzero) {
   StringTestState<char> state(LARGE);
-  for (size_t j = 0; j < ITER; j++) {
-    state.NewIteration();
-
-    memset(state.ptr1, random() & 255, state.MAX_LEN);
+  for (state.BeginIterations(); state.HasNextIteration(); state.NextIteration()) {
+    memset(state.ptr1, 'R', state.MAX_LEN);
 
     size_t start = random() % state.MAX_LEN;
     size_t end = start + random() % (state.MAX_LEN - start);
diff --git a/tests/uniqueptr_test.cpp b/tests/uniqueptr_test.cpp
new file mode 100644
index 0000000..4b6608a
--- /dev/null
+++ b/tests/uniqueptr_test.cpp
@@ -0,0 +1,101 @@
+/*
+ * Copyright (C) 2014 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <gtest/gtest.h>
+
+#include <private/UniquePtr.h>
+
+static int cCount = 0;
+struct C {
+  C() { ++cCount; }
+  ~C() { --cCount; }
+};
+
+static bool freed = false;
+struct Freer {
+  void operator() (int* p) {
+    ASSERT_EQ(123, *p);
+    free(p);
+    freed = true;
+  }
+};
+
+TEST(UniquePtr, smoke) {
+  //
+  // UniquePtr<T> tests...
+  //
+
+  // Can we free a single object?
+  {
+    UniquePtr<C> c(new C);
+    ASSERT_TRUE(cCount == 1);
+  }
+  ASSERT_TRUE(cCount == 0);
+  // Does release work?
+  C* rawC;
+  {
+      UniquePtr<C> c(new C);
+      ASSERT_TRUE(cCount == 1);
+      rawC = c.release();
+  }
+  ASSERT_TRUE(cCount == 1);
+  delete rawC;
+  // Does reset work?
+  {
+      UniquePtr<C> c(new C);
+      ASSERT_TRUE(cCount == 1);
+      c.reset(new C);
+      ASSERT_TRUE(cCount == 1);
+  }
+  ASSERT_TRUE(cCount == 0);
+
+  //
+  // UniquePtr<T[]> tests...
+  //
+
+  // Can we free an array?
+  {
+      UniquePtr<C[]> cs(new C[4]);
+      ASSERT_TRUE(cCount == 4);
+  }
+  ASSERT_TRUE(cCount == 0);
+  // Does release work?
+  {
+      UniquePtr<C[]> c(new C[4]);
+      ASSERT_TRUE(cCount == 4);
+      rawC = c.release();
+  }
+  ASSERT_TRUE(cCount == 4);
+  delete[] rawC;
+  // Does reset work?
+  {
+      UniquePtr<C[]> c(new C[4]);
+      ASSERT_TRUE(cCount == 4);
+      c.reset(new C[2]);
+      ASSERT_TRUE(cCount == 2);
+  }
+  ASSERT_TRUE(cCount == 0);
+
+  //
+  // Custom deleter tests...
+  //
+  ASSERT_TRUE(!freed);
+  {
+      UniquePtr<int, Freer> i(reinterpret_cast<int*>(malloc(sizeof(int))));
+      *i = 123;
+  }
+  ASSERT_TRUE(freed);
+}