Merge "Use default hidden visibility to build libc_dns."
diff --git a/libc/Android.mk b/libc/Android.mk
index 3eaed90..5e86dac 100644
--- a/libc/Android.mk
+++ b/libc/Android.mk
@@ -265,6 +265,7 @@
 
 libc_upstream_netbsd_src_files := \
     upstream-netbsd/common/lib/libc/hash/sha1/sha1.c \
+    upstream-netbsd/common/lib/libc/stdlib/random.c \
     upstream-netbsd/lib/libc/gen/ftw.c \
     upstream-netbsd/lib/libc/gen/nftw.c \
     upstream-netbsd/lib/libc/gen/nice.c \
@@ -288,6 +289,8 @@
     upstream-netbsd/lib/libc/stdlib/mrand48.c \
     upstream-netbsd/lib/libc/stdlib/nrand48.c \
     upstream-netbsd/lib/libc/stdlib/_rand48.c \
+    upstream-netbsd/lib/libc/stdlib/rand.c \
+    upstream-netbsd/lib/libc/stdlib/rand_r.c \
     upstream-netbsd/lib/libc/stdlib/seed48.c \
     upstream-netbsd/lib/libc/stdlib/srand48.c \
     upstream-netbsd/lib/libc/stdlib/tdelete.c \
@@ -416,7 +419,6 @@
     upstream-openbsd/lib/libc/stdio/putc.c \
     upstream-openbsd/lib/libc/stdio/putchar.c \
     upstream-openbsd/lib/libc/stdio/puts.c \
-    upstream-openbsd/lib/libc/stdio/putw.c \
     upstream-openbsd/lib/libc/stdio/putwc.c \
     upstream-openbsd/lib/libc/stdio/putwchar.c \
     upstream-openbsd/lib/libc/stdio/refill.c \
diff --git a/libc/arch-arm/arm.mk b/libc/arch-arm/arm.mk
index 7c423ab..260d72e 100644
--- a/libc/arch-arm/arm.mk
+++ b/libc/arch-arm/arm.mk
@@ -5,6 +5,7 @@
     bionic/legacy_32_bit_support.cpp \
     bionic/ndk_cruft.cpp \
     bionic/time64.c \
+    upstream-openbsd/lib/libc/stdio/putw.c \
 
 # These are shared by all the 32-bit targets, but not the 64-bit ones.
 libc_bionic_src_files_arm := \
diff --git a/libc/arch-mips/mips.mk b/libc/arch-mips/mips.mk
index 64b0fb2..c964e67 100644
--- a/libc/arch-mips/mips.mk
+++ b/libc/arch-mips/mips.mk
@@ -5,6 +5,7 @@
     bionic/legacy_32_bit_support.cpp \
     bionic/ndk_cruft.cpp \
     bionic/time64.c \
+    upstream-openbsd/lib/libc/stdio/putw.c \
 
 # These are shared by all the 32-bit targets, but not the 64-bit ones.
 libc_bionic_src_files_mips += \
diff --git a/libc/arch-x86/x86.mk b/libc/arch-x86/x86.mk
index 0f22169..3dc71d1 100644
--- a/libc/arch-x86/x86.mk
+++ b/libc/arch-x86/x86.mk
@@ -5,6 +5,7 @@
     bionic/legacy_32_bit_support.cpp \
     bionic/ndk_cruft.cpp \
     bionic/time64.c \
+    upstream-openbsd/lib/libc/stdio/putw.c \
 
 # Fortify implementations of libc functions.
 libc_common_src_files_x86 += \
diff --git a/libc/bionic/malloc_debug_check.cpp b/libc/bionic/malloc_debug_check.cpp
index 0575595..faf61bf 100644
--- a/libc/bionic/malloc_debug_check.cpp
+++ b/libc/bionic/malloc_debug_check.cpp
@@ -326,14 +326,19 @@
     }
 }
 
-extern "C" void* chk_malloc(size_t size) {
+extern "C" void* chk_malloc(size_t bytes) {
 //  log_message("%s: %s\n", __FILE__, __FUNCTION__);
 
-    hdr_t* hdr = static_cast<hdr_t*>(Malloc(malloc)(sizeof(hdr_t) + size + sizeof(ftr_t)));
+    size_t size = sizeof(hdr_t) + bytes + sizeof(ftr_t);
+    if (size < bytes) { // Overflow
+        errno = ENOMEM;
+        return NULL;
+    }
+    hdr_t* hdr = static_cast<hdr_t*>(Malloc(malloc)(size));
     if (hdr) {
         hdr->base = hdr;
         hdr->bt_depth = get_backtrace(hdr->bt, MAX_BACKTRACE_DEPTH);
-        add(hdr, size);
+        add(hdr, bytes);
         return user(hdr);
     }
     return NULL;
@@ -411,15 +416,15 @@
     }
 }
 
-extern "C" void* chk_realloc(void* ptr, size_t size) {
+extern "C" void* chk_realloc(void* ptr, size_t bytes) {
 //  log_message("%s: %s\n", __FILE__, __FUNCTION__);
 
     if (!ptr) {
-        return chk_malloc(size);
+        return chk_malloc(bytes);
     }
 
 #ifdef REALLOC_ZERO_BYTES_FREE
-    if (!size) {
+    if (!bytes) {
         chk_free(ptr);
         return NULL;
     }
@@ -432,7 +437,7 @@
         int depth = get_backtrace(bt, MAX_BACKTRACE_DEPTH);
         if (hdr->tag == BACKLOG_TAG) {
             log_message("+++ REALLOCATION %p SIZE %d OF FREED MEMORY!\n",
-                       user(hdr), size, hdr->size);
+                       user(hdr), bytes, hdr->size);
             log_message("+++ ALLOCATION %p SIZE %d ALLOCATED HERE:\n",
                        user(hdr), hdr->size);
             log_backtrace(hdr->bt, hdr->bt_depth);
@@ -451,47 +456,54 @@
             del_from_backlog(hdr);
         } else {
             log_message("+++ REALLOCATION %p SIZE %d IS CORRUPTED OR NOT ALLOCATED VIA TRACKER!\n",
-                       user(hdr), size);
+                       user(hdr), bytes);
             log_backtrace(bt, depth);
             // just get a whole new allocation and leak the old one
-            return Malloc(realloc)(0, size);
-            // return realloc(user(hdr), size); // assuming it was allocated externally
+            return Malloc(realloc)(0, bytes);
+            // return realloc(user(hdr), bytes); // assuming it was allocated externally
         }
     }
 
+    size_t size = sizeof(hdr_t) + bytes + sizeof(ftr_t);
+    if (size < bytes) { // Overflow
+        errno = ENOMEM;
+        return NULL;
+    }
     if (hdr->base != hdr) {
         // An allocation from memalign, so create another allocation and
         // copy the data out.
-        void* newMem = Malloc(malloc)(sizeof(hdr_t) + size + sizeof(ftr_t));
-        if (newMem) {
-            memcpy(newMem, hdr, sizeof(hdr_t) + hdr->size);
-            Malloc(free)(hdr->base);
-            hdr = static_cast<hdr_t*>(newMem);
-        } else {
-            Malloc(free)(hdr->base);
-            hdr = NULL;
+        void* newMem = Malloc(malloc)(size);
+        if (newMem == NULL) {
+            return NULL;
         }
+        memcpy(newMem, hdr, sizeof(hdr_t) + hdr->size);
+        Malloc(free)(hdr->base);
+        hdr = static_cast<hdr_t*>(newMem);
     } else {
-        hdr = static_cast<hdr_t*>(Malloc(realloc)(hdr, sizeof(hdr_t) + size + sizeof(ftr_t)));
+        hdr = static_cast<hdr_t*>(Malloc(realloc)(hdr, size));
     }
     if (hdr) {
         hdr->base = hdr;
         hdr->bt_depth = get_backtrace(hdr->bt, MAX_BACKTRACE_DEPTH);
-        add(hdr, size);
+        add(hdr, bytes);
         return user(hdr);
     }
-
     return NULL;
 }
 
-extern "C" void* chk_calloc(int nmemb, size_t size) {
+extern "C" void* chk_calloc(size_t nmemb, size_t bytes) {
 //  log_message("%s: %s\n", __FILE__, __FUNCTION__);
-    size_t total_size = nmemb * size;
-    hdr_t* hdr = static_cast<hdr_t*>(Malloc(calloc)(1, sizeof(hdr_t) + total_size + sizeof(ftr_t)));
+    size_t total_bytes = nmemb * bytes;
+    size_t size = sizeof(hdr_t) + total_bytes + sizeof(ftr_t);
+    if (size < total_bytes || (nmemb && SIZE_MAX / nmemb < bytes)) { // Overflow
+        errno = ENOMEM;
+        return NULL;
+    }
+    hdr_t* hdr = static_cast<hdr_t*>(Malloc(calloc)(1, size));
     if (hdr) {
         hdr->base = hdr;
         hdr->bt_depth = get_backtrace(hdr->bt, MAX_BACKTRACE_DEPTH);
-        add(hdr, total_size);
+        add(hdr, total_bytes);
         return user(hdr);
     }
     return NULL;
@@ -509,6 +521,33 @@
     return hdr->size;
 }
 
+extern "C" struct mallinfo chk_mallinfo() {
+  return Malloc(mallinfo)();
+}
+
+extern "C" int chk_posix_memalign(void** memptr, size_t alignment, size_t size) {
+  if ((alignment & (alignment - 1)) != 0) {
+    return EINVAL;
+  }
+  int saved_errno = errno;
+  *memptr = chk_memalign(alignment, size);
+  errno = saved_errno;
+  return (*memptr != NULL) ? 0 : ENOMEM;
+}
+
+extern "C" void* chk_pvalloc(size_t bytes) {
+  size_t pagesize = sysconf(_SC_PAGESIZE);
+  size_t size = (bytes + pagesize - 1) & ~(pagesize - 1);
+  if (size < bytes) { // Overflow
+    return NULL;
+  }
+  return chk_memalign(pagesize, size);
+}
+
+extern "C" void* chk_valloc(size_t size) {
+  return chk_memalign(sysconf(_SC_PAGESIZE), size);
+}
+
 static void ReportMemoryLeaks() {
   // Use /proc/self/exe link to obtain the program name for logging
   // purposes. If it's not available, we set it to "<unknown>".
diff --git a/libc/bionic/malloc_debug_common.cpp b/libc/bionic/malloc_debug_common.cpp
index 77ec080..6677c22 100644
--- a/libc/bionic/malloc_debug_common.cpp
+++ b/libc/bionic/malloc_debug_common.cpp
@@ -26,19 +26,17 @@
  * SUCH DAMAGE.
  */
 
-/*
- * Contains definition of structures, global variables, and implementation of
- * routines that are used by malloc leak detection code and other components in
- * the system. The trick is that some components expect these data and
- * routines to be defined / implemented in libc.so library, regardless
- * whether or not MALLOC_LEAK_CHECK macro is defined. To make things even
- * more tricky, malloc leak detection code, implemented in
- * libc_malloc_debug.so also requires access to these variables and routines
- * (to fill allocation entry hash table, for example). So, all relevant
- * variables and routines are defined / implemented here and exported
- * to all, leak detection code and other components via dynamic (libc.so),
- * or static (libc.a) linking.
- */
+// Contains definition of structures, global variables, and implementation of
+// routines that are used by malloc leak detection code and other components in
+// the system. The trick is that some components expect these data and
+// routines to be defined / implemented in libc.so library, regardless
+// whether or not MALLOC_LEAK_CHECK macro is defined. To make things even
+// more tricky, malloc leak detection code, implemented in
+// libc_malloc_debug.so also requires access to these variables and routines
+// (to fill allocation entry hash table, for example). So, all relevant
+// variables and routines are defined / implemented here and exported
+// to all, leak detection code and other components via dynamic (libc.so),
+// or static (libc.a) linking.
 
 #include "malloc_debug_common.h"
 
@@ -56,7 +54,16 @@
 // Support for malloc debugging.
 // Table for dispatching malloc calls, initialized with default dispatchers.
 static const MallocDebug __libc_malloc_default_dispatch __attribute__((aligned(32))) = {
-  Malloc(malloc), Malloc(free), Malloc(calloc), Malloc(realloc), Malloc(memalign), Malloc(malloc_usable_size),
+  Malloc(calloc),
+  Malloc(free),
+  Malloc(mallinfo),
+  Malloc(malloc),
+  Malloc(malloc_usable_size),
+  Malloc(memalign),
+  Malloc(posix_memalign),
+  Malloc(pvalloc),
+  Malloc(realloc),
+  Malloc(valloc),
 };
 
 // Selector of dispatch table to use for dispatching malloc calls.
@@ -97,176 +104,174 @@
 // =============================================================================
 
 static int hash_entry_compare(const void* arg1, const void* arg2) {
-    int result;
+  int result;
 
-    const HashEntry* e1 = *static_cast<HashEntry* const*>(arg1);
-    const HashEntry* e2 = *static_cast<HashEntry* const*>(arg2);
+  const HashEntry* e1 = *static_cast<HashEntry* const*>(arg1);
+  const HashEntry* e2 = *static_cast<HashEntry* const*>(arg2);
 
-    // if one or both arg pointers are null, deal gracefully
-    if (e1 == NULL) {
-        result = (e2 == NULL) ? 0 : 1;
-    } else if (e2 == NULL) {
-        result = -1;
+  // if one or both arg pointers are null, deal gracefully
+  if (e1 == NULL) {
+    result = (e2 == NULL) ? 0 : 1;
+  } else if (e2 == NULL) {
+    result = -1;
+  } else {
+    size_t nbAlloc1 = e1->allocations;
+    size_t nbAlloc2 = e2->allocations;
+    size_t size1 = e1->size & ~SIZE_FLAG_MASK;
+    size_t size2 = e2->size & ~SIZE_FLAG_MASK;
+    size_t alloc1 = nbAlloc1 * size1;
+    size_t alloc2 = nbAlloc2 * size2;
+
+    // sort in descending order by:
+    // 1) total size
+    // 2) number of allocations
+    //
+    // This is used for sorting, not determination of equality, so we don't
+    // need to compare the bit flags.
+    if (alloc1 > alloc2) {
+      result = -1;
+    } else if (alloc1 < alloc2) {
+      result = 1;
     } else {
-        size_t nbAlloc1 = e1->allocations;
-        size_t nbAlloc2 = e2->allocations;
-        size_t size1 = e1->size & ~SIZE_FLAG_MASK;
-        size_t size2 = e2->size & ~SIZE_FLAG_MASK;
-        size_t alloc1 = nbAlloc1 * size1;
-        size_t alloc2 = nbAlloc2 * size2;
-
-        // sort in descending order by:
-        // 1) total size
-        // 2) number of allocations
-        //
-        // This is used for sorting, not determination of equality, so we don't
-        // need to compare the bit flags.
-        if (alloc1 > alloc2) {
-            result = -1;
-        } else if (alloc1 < alloc2) {
-            result = 1;
-        } else {
-            if (nbAlloc1 > nbAlloc2) {
-                result = -1;
-            } else if (nbAlloc1 < nbAlloc2) {
-                result = 1;
-            } else {
-                result = 0;
-            }
-        }
+      if (nbAlloc1 > nbAlloc2) {
+        result = -1;
+      } else if (nbAlloc1 < nbAlloc2) {
+        result = 1;
+      } else {
+        result = 0;
+      }
     }
-    return result;
+  }
+  return result;
 }
 
-/*
- * Retrieve native heap information.
- *
- * "*info" is set to a buffer we allocate
- * "*overallSize" is set to the size of the "info" buffer
- * "*infoSize" is set to the size of a single entry
- * "*totalMemory" is set to the sum of all allocations we're tracking; does
- *   not include heap overhead
- * "*backtraceSize" is set to the maximum number of entries in the back trace
- */
+// Retrieve native heap information.
+//
+// "*info" is set to a buffer we allocate
+// "*overallSize" is set to the size of the "info" buffer
+// "*infoSize" is set to the size of a single entry
+// "*totalMemory" is set to the sum of all allocations we're tracking; does
+//   not include heap overhead
+// "*backtraceSize" is set to the maximum number of entries in the back trace
 
+// =============================================================================
 // Exported for use by ddms.
+// =============================================================================
 extern "C" void get_malloc_leak_info(uint8_t** info, size_t* overallSize,
-        size_t* infoSize, size_t* totalMemory, size_t* backtraceSize) {
-    // don't do anything if we have invalid arguments
-    if (info == NULL || overallSize == NULL || infoSize == NULL ||
-            totalMemory == NULL || backtraceSize == NULL) {
-        return;
+    size_t* infoSize, size_t* totalMemory, size_t* backtraceSize) {
+  // Don't do anything if we have invalid arguments.
+  if (info == NULL || overallSize == NULL || infoSize == NULL ||
+    totalMemory == NULL || backtraceSize == NULL) {
+    return;
+  }
+  *totalMemory = 0;
+
+  ScopedPthreadMutexLocker locker(&g_hash_table.lock);
+  if (g_hash_table.count == 0) {
+    *info = NULL;
+    *overallSize = 0;
+    *infoSize = 0;
+    *backtraceSize = 0;
+    return;
+  }
+
+  HashEntry** list = static_cast<HashEntry**>(Malloc(malloc)(sizeof(void*) * g_hash_table.count));
+
+  // Get the entries into an array to be sorted.
+  size_t index = 0;
+  for (size_t i = 0 ; i < HASHTABLE_SIZE ; ++i) {
+    HashEntry* entry = g_hash_table.slots[i];
+    while (entry != NULL) {
+      list[index] = entry;
+      *totalMemory = *totalMemory + ((entry->size & ~SIZE_FLAG_MASK) * entry->allocations);
+      index++;
+      entry = entry->next;
     }
-    *totalMemory = 0;
+  }
 
-    ScopedPthreadMutexLocker locker(&g_hash_table.lock);
+  // XXX: the protocol doesn't allow variable size for the stack trace (yet)
+  *infoSize = (sizeof(size_t) * 2) + (sizeof(uintptr_t) * BACKTRACE_SIZE);
+  *overallSize = *infoSize * g_hash_table.count;
+  *backtraceSize = BACKTRACE_SIZE;
 
-    if (g_hash_table.count == 0) {
-        *info = NULL;
-        *overallSize = 0;
-        *infoSize = 0;
-        *backtraceSize = 0;
-        return;
-    }
-
-    HashEntry** list = static_cast<HashEntry**>(Malloc(malloc)(sizeof(void*) * g_hash_table.count));
-
-    // get the entries into an array to be sorted
-    int index = 0;
-    for (size_t i = 0 ; i < HASHTABLE_SIZE ; ++i) {
-        HashEntry* entry = g_hash_table.slots[i];
-        while (entry != NULL) {
-            list[index] = entry;
-            *totalMemory = *totalMemory +
-                ((entry->size & ~SIZE_FLAG_MASK) * entry->allocations);
-            index++;
-            entry = entry->next;
-        }
-    }
-
-    // XXX: the protocol doesn't allow variable size for the stack trace (yet)
-    *infoSize = (sizeof(size_t) * 2) + (sizeof(uintptr_t) * BACKTRACE_SIZE);
-    *overallSize = *infoSize * g_hash_table.count;
-    *backtraceSize = BACKTRACE_SIZE;
-
-    // now get a byte array big enough for this
-    *info = static_cast<uint8_t*>(Malloc(malloc)(*overallSize));
-
-    if (*info == NULL) {
-        *overallSize = 0;
-        Malloc(free)(list);
-        return;
-    }
-
-    qsort(list, g_hash_table.count, sizeof(void*), hash_entry_compare);
-
-    uint8_t* head = *info;
-    const int count = g_hash_table.count;
-    for (int i = 0 ; i < count ; ++i) {
-        HashEntry* entry = list[i];
-        size_t entrySize = (sizeof(size_t) * 2) + (sizeof(uintptr_t) * entry->numEntries);
-        if (entrySize < *infoSize) {
-            /* we're writing less than a full entry, clear out the rest */
-            memset(head + entrySize, 0, *infoSize - entrySize);
-        } else {
-            /* make sure the amount we're copying doesn't exceed the limit */
-            entrySize = *infoSize;
-        }
-        memcpy(head, &(entry->size), entrySize);
-        head += *infoSize;
-    }
-
+  // now get a byte array big enough for this
+  *info = static_cast<uint8_t*>(Malloc(malloc)(*overallSize));
+  if (*info == NULL) {
+    *overallSize = 0;
     Malloc(free)(list);
+    return;
+  }
+
+  qsort(list, g_hash_table.count, sizeof(void*), hash_entry_compare);
+
+  uint8_t* head = *info;
+  const size_t count = g_hash_table.count;
+  for (size_t i = 0 ; i < count ; ++i) {
+    HashEntry* entry = list[i];
+    size_t entrySize = (sizeof(size_t) * 2) + (sizeof(uintptr_t) * entry->numEntries);
+    if (entrySize < *infoSize) {
+      // We're writing less than a full entry, clear out the rest.
+      memset(head + entrySize, 0, *infoSize - entrySize);
+    } else {
+      // Make sure the amount we're copying doesn't exceed the limit.
+      entrySize = *infoSize;
+    }
+    memcpy(head, &(entry->size), entrySize);
+    head += *infoSize;
+  }
+
+  Malloc(free)(list);
 }
 
-// Exported for use by ddms.
 extern "C" void free_malloc_leak_info(uint8_t* info) {
-    Malloc(free)(info);
+  Malloc(free)(info);
 }
 
-extern "C" struct mallinfo mallinfo() {
-    return Malloc(mallinfo)();
-}
-
-extern "C" void* valloc(size_t bytes) {
-    return Malloc(valloc)(bytes);
-}
-
-extern "C" void* pvalloc(size_t bytes) {
-    return Malloc(pvalloc)(bytes);
-}
-
-extern "C" int posix_memalign(void** memptr, size_t alignment, size_t size) {
-    return Malloc(posix_memalign)(memptr, alignment, size);
-}
-
-extern "C" void* malloc(size_t bytes) {
-    return __libc_malloc_dispatch->malloc(bytes);
+// =============================================================================
+// Allocation functions
+// =============================================================================
+extern "C" void* calloc(size_t n_elements, size_t elem_size) {
+  return __libc_malloc_dispatch->calloc(n_elements, elem_size);
 }
 
 extern "C" void free(void* mem) {
-    __libc_malloc_dispatch->free(mem);
+  __libc_malloc_dispatch->free(mem);
 }
 
-extern "C" void* calloc(size_t n_elements, size_t elem_size) {
-    return __libc_malloc_dispatch->calloc(n_elements, elem_size);
+extern "C" struct mallinfo mallinfo() {
+  return __libc_malloc_dispatch->mallinfo();
 }
 
-extern "C" void* realloc(void* oldMem, size_t bytes) {
-    return __libc_malloc_dispatch->realloc(oldMem, bytes);
-}
-
-extern "C" void* memalign(size_t alignment, size_t bytes) {
-    return __libc_malloc_dispatch->memalign(alignment, bytes);
+extern "C" void* malloc(size_t bytes) {
+  return __libc_malloc_dispatch->malloc(bytes);
 }
 
 extern "C" size_t malloc_usable_size(const void* mem) {
-    return __libc_malloc_dispatch->malloc_usable_size(mem);
+  return __libc_malloc_dispatch->malloc_usable_size(mem);
 }
 
-/* We implement malloc debugging only in libc.so, so code below
- * must be excluded if we compile this file for static libc.a
- */
+extern "C" void* memalign(size_t alignment, size_t bytes) {
+  return __libc_malloc_dispatch->memalign(alignment, bytes);
+}
+
+extern "C" int posix_memalign(void** memptr, size_t alignment, size_t size) {
+  return __libc_malloc_dispatch->posix_memalign(memptr, alignment, size);
+}
+
+extern "C" void* pvalloc(size_t bytes) {
+  return __libc_malloc_dispatch->pvalloc(bytes);
+}
+
+extern "C" void* realloc(void* oldMem, size_t bytes) {
+  return __libc_malloc_dispatch->realloc(oldMem, bytes);
+}
+
+extern "C" void* valloc(size_t bytes) {
+  return __libc_malloc_dispatch->valloc(bytes);
+}
+
+// We implement malloc debugging only in libc.so, so the code below
+// must be excluded if we compile this file for static libc.a
 #ifndef LIBC_STATIC
 #include <sys/system_properties.h>
 #include <dlfcn.h>
@@ -275,227 +280,222 @@
 
 template<typename FunctionType>
 static void InitMallocFunction(void* malloc_impl_handler, FunctionType* func, const char* prefix, const char* suffix) {
-    char symbol[128];
-    snprintf(symbol, sizeof(symbol), "%s_%s", prefix, suffix);
-    *func = reinterpret_cast<FunctionType>(dlsym(malloc_impl_handler, symbol));
-    if (*func == NULL) {
-        error_log("%s: dlsym(\"%s\") failed", getprogname(), symbol);
-    }
+  char symbol[128];
+  snprintf(symbol, sizeof(symbol), "%s_%s", prefix, suffix);
+  *func = reinterpret_cast<FunctionType>(dlsym(malloc_impl_handler, symbol));
+  if (*func == NULL) {
+    error_log("%s: dlsym(\"%s\") failed", getprogname(), symbol);
+  }
 }
 
 static void InitMalloc(void* malloc_impl_handler, MallocDebug* table, const char* prefix) {
-    __libc_format_log(ANDROID_LOG_INFO, "libc", "%s: using libc.debug.malloc %d (%s)\n",
-                      getprogname(), g_malloc_debug_level, prefix);
+  __libc_format_log(ANDROID_LOG_INFO, "libc", "%s: using libc.debug.malloc %d (%s)\n",
+                    getprogname(), g_malloc_debug_level, prefix);
 
-    InitMallocFunction<MallocDebugMalloc>(malloc_impl_handler, &table->malloc, prefix, "malloc");
-    InitMallocFunction<MallocDebugFree>(malloc_impl_handler, &table->free, prefix, "free");
-    InitMallocFunction<MallocDebugCalloc>(malloc_impl_handler, &table->calloc, prefix, "calloc");
-    InitMallocFunction<MallocDebugRealloc>(malloc_impl_handler, &table->realloc, prefix, "realloc");
-    InitMallocFunction<MallocDebugMemalign>(malloc_impl_handler, &table->memalign, prefix, "memalign");
-    InitMallocFunction<MallocDebugMallocUsableSize>(malloc_impl_handler, &table->malloc_usable_size, prefix, "malloc_usable_size");
+  InitMallocFunction<MallocDebugCalloc>(malloc_impl_handler, &table->calloc, prefix, "calloc");
+  InitMallocFunction<MallocDebugFree>(malloc_impl_handler, &table->free, prefix, "free");
+  InitMallocFunction<MallocDebugMallinfo>(malloc_impl_handler, &table->mallinfo, prefix, "mallinfo");
+  InitMallocFunction<MallocDebugMalloc>(malloc_impl_handler, &table->malloc, prefix, "malloc");
+  InitMallocFunction<MallocDebugMallocUsableSize>(malloc_impl_handler, &table->malloc_usable_size, prefix, "malloc_usable_size");
+  InitMallocFunction<MallocDebugMemalign>(malloc_impl_handler, &table->memalign, prefix, "memalign");
+  InitMallocFunction<MallocDebugPosixMemalign>(malloc_impl_handler, &table->posix_memalign, prefix, "posix_memalign");
+  InitMallocFunction<MallocDebugPvalloc>(malloc_impl_handler, &table->pvalloc, prefix, "pvalloc");
+  InitMallocFunction<MallocDebugRealloc>(malloc_impl_handler, &table->realloc, prefix, "realloc");
+  InitMallocFunction<MallocDebugValloc>(malloc_impl_handler, &table->valloc, prefix, "valloc");
 }
 
-/* Initializes memory allocation framework once per process. */
+// Initializes memory allocation framework once per process.
 static void malloc_init_impl() {
-    const char* so_name = NULL;
-    MallocDebugInit malloc_debug_initialize = NULL;
-    unsigned int qemu_running = 0;
-    unsigned int memcheck_enabled = 0;
-    char env[PROP_VALUE_MAX];
-    char memcheck_tracing[PROP_VALUE_MAX];
-    char debug_program[PROP_VALUE_MAX];
+  const char* so_name = NULL;
+  MallocDebugInit malloc_debug_initialize = NULL;
+  unsigned int qemu_running = 0;
+  unsigned int memcheck_enabled = 0;
+  char env[PROP_VALUE_MAX];
+  char memcheck_tracing[PROP_VALUE_MAX];
+  char debug_program[PROP_VALUE_MAX];
 
-    /* Get custom malloc debug level. Note that emulator started with
-     * memory checking option will have priority over debug level set in
-     * libc.debug.malloc system property. */
-    if (__system_property_get("ro.kernel.qemu", env) && atoi(env)) {
-        qemu_running = 1;
-        if (__system_property_get("ro.kernel.memcheck", memcheck_tracing)) {
-            if (memcheck_tracing[0] != '0') {
-                // Emulator has started with memory tracing enabled. Enforce it.
-                g_malloc_debug_level = 20;
-                memcheck_enabled = 1;
-            }
-        }
+  // Get custom malloc debug level. Note that emulator started with
+  // memory checking option will have priority over debug level set in
+  // libc.debug.malloc system property.
+  if (__system_property_get("ro.kernel.qemu", env) && atoi(env)) {
+    qemu_running = 1;
+    if (__system_property_get("ro.kernel.memcheck", memcheck_tracing)) {
+      if (memcheck_tracing[0] != '0') {
+        // Emulator has started with memory tracing enabled. Enforce it.
+        g_malloc_debug_level = 20;
+        memcheck_enabled = 1;
+      }
     }
+  }
 
-    /* If debug level has not been set by memcheck option in the emulator,
-     * lets grab it from libc.debug.malloc system property. */
-    if (g_malloc_debug_level == 0 && __system_property_get("libc.debug.malloc", env)) {
-        g_malloc_debug_level = atoi(env);
+  // If debug level has not been set by memcheck option in the emulator,
+  // lets grab it from libc.debug.malloc system property.
+  if (g_malloc_debug_level == 0 && __system_property_get("libc.debug.malloc", env)) {
+    g_malloc_debug_level = atoi(env);
+  }
+
+  // Debug level 0 means that we should use default allocation routines.
+  if (g_malloc_debug_level == 0) {
+    return;
+  }
+
+  // If libc.debug.malloc.program is set and is not a substring of progname,
+  // then exit.
+  if (__system_property_get("libc.debug.malloc.program", debug_program)) {
+    if (!strstr(getprogname(), debug_program)) {
+      return;
     }
+  }
 
-    /* Debug level 0 means that we should use default allocation routines. */
-    if (g_malloc_debug_level == 0) {
-        return;
+  // mksh is way too leaky. http://b/7291287.
+  if (g_malloc_debug_level >= 10) {
+    if (strcmp(getprogname(), "sh") == 0 || strcmp(getprogname(), "/system/bin/sh") == 0) {
+      return;
     }
+  }
 
-    /* If libc.debug.malloc.program is set and is not a substring of progname,
-     * then exit.
-     */
-    if (__system_property_get("libc.debug.malloc.program", debug_program)) {
-        if (!strstr(getprogname(), debug_program)) {
-            return;
-        }
-    }
-
-    // mksh is way too leaky. http://b/7291287.
-    if (g_malloc_debug_level >= 10) {
-        if (strcmp(getprogname(), "sh") == 0 || strcmp(getprogname(), "/system/bin/sh") == 0) {
-            return;
-        }
-    }
-
-    // Choose the appropriate .so for the requested debug level.
-    switch (g_malloc_debug_level) {
-        case 1:
-        case 5:
-        case 10:
-            so_name = "libc_malloc_debug_leak.so";
-            break;
-        case 20:
-            // Quick check: debug level 20 can only be handled in emulator.
-            if (!qemu_running) {
-                error_log("%s: Debug level %d can only be set in emulator\n",
-                          getprogname(), g_malloc_debug_level);
-                return;
-            }
-            // Make sure that memory checking has been enabled in emulator.
-            if (!memcheck_enabled) {
-                error_log("%s: Memory checking is not enabled in the emulator\n",
-                          getprogname());
-                return;
-            }
-            so_name = "libc_malloc_debug_qemu.so";
-            break;
-        default:
-            error_log("%s: Debug level %d is unknown\n", getprogname(), g_malloc_debug_level);
-            return;
-    }
-
-    // Load .so that implements the required malloc debugging functionality.
-    void* malloc_impl_handle = dlopen(so_name, RTLD_LAZY);
-    if (malloc_impl_handle == NULL) {
-        error_log("%s: Missing module %s required for malloc debug level %d: %s",
-                  getprogname(), so_name, g_malloc_debug_level, dlerror());
-        return;
-    }
-
-    // Initialize malloc debugging in the loaded module.
-    malloc_debug_initialize = reinterpret_cast<MallocDebugInit>(dlsym(malloc_impl_handle,
-                                                                      "malloc_debug_initialize"));
-    if (malloc_debug_initialize == NULL) {
-        error_log("%s: Initialization routine is not found in %s\n",
-                  getprogname(), so_name);
-        dlclose(malloc_impl_handle);
-        return;
-    }
-    if (malloc_debug_initialize(&g_hash_table) == -1) {
-        dlclose(malloc_impl_handle);
-        return;
-    }
-
-    if (g_malloc_debug_level == 20) {
-        // For memory checker we need to do extra initialization.
-        typedef int (*MemCheckInit)(int, const char*);
-        MemCheckInit memcheck_initialize =
-            reinterpret_cast<MemCheckInit>(dlsym(malloc_impl_handle,
-                                                 "memcheck_initialize"));
-        if (memcheck_initialize == NULL) {
-            error_log("%s: memcheck_initialize routine is not found in %s\n",
-                      getprogname(), so_name);
-            dlclose(malloc_impl_handle);
-            return;
-        }
-
-        if (memcheck_initialize(MALLOC_ALIGNMENT, memcheck_tracing)) {
-            dlclose(malloc_impl_handle);
-            return;
-        }
-    }
-
-    // Initialize malloc dispatch table with appropriate routines.
-    static MallocDebug malloc_dispatch_table __attribute__((aligned(32))) = {
-        Malloc(malloc),
-        Malloc(free),
-        Malloc(calloc),
-        Malloc(realloc),
-        Malloc(memalign),
-        Malloc(malloc_usable_size)
-    };
-
-    switch (g_malloc_debug_level) {
-        case 1:
-            InitMalloc(malloc_impl_handle, &malloc_dispatch_table, "leak");
-            break;
-        case 5:
-            InitMalloc(malloc_impl_handle, &malloc_dispatch_table, "fill");
-            break;
-        case 10:
-            InitMalloc(malloc_impl_handle, &malloc_dispatch_table, "chk");
-            break;
-        case 20:
-            InitMalloc(malloc_impl_handle, &malloc_dispatch_table, "qemu_instrumented");
-            break;
-        default:
-            break;
-    }
-
-    // Make sure dispatch table is initialized
-    if ((malloc_dispatch_table.malloc == NULL) ||
-        (malloc_dispatch_table.free == NULL) ||
-        (malloc_dispatch_table.calloc == NULL) ||
-        (malloc_dispatch_table.realloc == NULL) ||
-        (malloc_dispatch_table.memalign == NULL) ||
-        (malloc_dispatch_table.malloc_usable_size == NULL)) {
-        error_log("%s: some symbols for libc.debug.malloc level %d were not found (see above)",
+  // Choose the appropriate .so for the requested debug level.
+  switch (g_malloc_debug_level) {
+    case 1:
+    case 5:
+    case 10:
+      so_name = "libc_malloc_debug_leak.so";
+      break;
+    case 20:
+      // Quick check: debug level 20 can only be handled in emulator.
+      if (!qemu_running) {
+        error_log("%s: Debug level %d can only be set in emulator\n",
                   getprogname(), g_malloc_debug_level);
-        dlclose(malloc_impl_handle);
-    } else {
-        __libc_malloc_dispatch = &malloc_dispatch_table;
-        libc_malloc_impl_handle = malloc_impl_handle;
+        return;
+      }
+      // Make sure that memory checking has been enabled in emulator.
+      if (!memcheck_enabled) {
+        error_log("%s: Memory checking is not enabled in the emulator\n", getprogname());
+        return;
+      }
+      so_name = "libc_malloc_debug_qemu.so";
+      break;
+    default:
+      error_log("%s: Debug level %d is unknown\n", getprogname(), g_malloc_debug_level);
+      return;
+  }
+
+  // Load .so that implements the required malloc debugging functionality.
+  void* malloc_impl_handle = dlopen(so_name, RTLD_LAZY);
+  if (malloc_impl_handle == NULL) {
+    error_log("%s: Missing module %s required for malloc debug level %d: %s",
+              getprogname(), so_name, g_malloc_debug_level, dlerror());
+    return;
+  }
+
+  // Initialize malloc debugging in the loaded module.
+  malloc_debug_initialize = reinterpret_cast<MallocDebugInit>(dlsym(malloc_impl_handle,
+                                                                    "malloc_debug_initialize"));
+  if (malloc_debug_initialize == NULL) {
+    error_log("%s: Initialization routine is not found in %s\n", getprogname(), so_name);
+    dlclose(malloc_impl_handle);
+    return;
+  }
+  if (malloc_debug_initialize(&g_hash_table) == -1) {
+    dlclose(malloc_impl_handle);
+    return;
+  }
+
+  if (g_malloc_debug_level == 20) {
+    // For memory checker we need to do extra initialization.
+    typedef int (*MemCheckInit)(int, const char*);
+    MemCheckInit memcheck_initialize =
+      reinterpret_cast<MemCheckInit>(dlsym(malloc_impl_handle, "memcheck_initialize"));
+    if (memcheck_initialize == NULL) {
+      error_log("%s: memcheck_initialize routine is not found in %s\n",
+                getprogname(), so_name);
+      dlclose(malloc_impl_handle);
+      return;
     }
+
+    if (memcheck_initialize(MALLOC_ALIGNMENT, memcheck_tracing)) {
+      dlclose(malloc_impl_handle);
+      return;
+    }
+  }
+
+  // No need to init the dispatch table because we can only get
+  // here if debug level is 1, 5, 10, or 20.
+  static MallocDebug malloc_dispatch_table __attribute__((aligned(32)));
+  switch (g_malloc_debug_level) {
+    case 1:
+      InitMalloc(malloc_impl_handle, &malloc_dispatch_table, "leak");
+      break;
+    case 5:
+      InitMalloc(malloc_impl_handle, &malloc_dispatch_table, "fill");
+      break;
+    case 10:
+      InitMalloc(malloc_impl_handle, &malloc_dispatch_table, "chk");
+      break;
+    case 20:
+      InitMalloc(malloc_impl_handle, &malloc_dispatch_table, "qemu_instrumented");
+      break;
+    default:
+      break;
+  }
+
+  // Make sure dispatch table is initialized
+  if ((malloc_dispatch_table.calloc == NULL) ||
+      (malloc_dispatch_table.free == NULL) ||
+      (malloc_dispatch_table.mallinfo == NULL) ||
+      (malloc_dispatch_table.malloc == NULL) ||
+      (malloc_dispatch_table.malloc_usable_size == NULL) ||
+      (malloc_dispatch_table.memalign == NULL) ||
+      (malloc_dispatch_table.posix_memalign == NULL) ||
+      (malloc_dispatch_table.pvalloc == NULL) ||
+      (malloc_dispatch_table.realloc == NULL) ||
+      (malloc_dispatch_table.valloc == NULL)) {
+    error_log("%s: some symbols for libc.debug.malloc level %d were not found (see above)",
+              getprogname(), g_malloc_debug_level);
+    dlclose(malloc_impl_handle);
+  } else {
+    __libc_malloc_dispatch = &malloc_dispatch_table;
+    libc_malloc_impl_handle = malloc_impl_handle;
+  }
 }
 
 static void malloc_fini_impl() {
-    // Our BSD stdio implementation doesn't close the standard streams, it only flushes them.
-    // And it doesn't do that until its atexit handler is run, and we run first!
-    // It's great that other unclosed FILE*s show up as malloc leaks, but we need to manually
-    // clean up the standard streams ourselves.
-    fclose(stdin);
-    fclose(stdout);
-    fclose(stderr);
+  // Our BSD stdio implementation doesn't close the standard streams, it only flushes them.
+  // And it doesn't do that until its atexit handler is run, and we run first!
+  // It's great that other unclosed FILE*s show up as malloc leaks, but we need to manually
+  // clean up the standard streams ourselves.
+  fclose(stdin);
+  fclose(stdout);
+  fclose(stderr);
 
-    if (libc_malloc_impl_handle != NULL) {
-        MallocDebugFini malloc_debug_finalize =
-            reinterpret_cast<MallocDebugFini>(dlsym(libc_malloc_impl_handle,
-                                                    "malloc_debug_finalize"));
-        if (malloc_debug_finalize != NULL) {
-            malloc_debug_finalize(g_malloc_debug_level);
-        }
+  if (libc_malloc_impl_handle != NULL) {
+    MallocDebugFini malloc_debug_finalize =
+      reinterpret_cast<MallocDebugFini>(dlsym(libc_malloc_impl_handle, "malloc_debug_finalize"));
+    if (malloc_debug_finalize != NULL) {
+      malloc_debug_finalize(g_malloc_debug_level);
     }
+  }
 }
 
 #endif  // !LIBC_STATIC
 
-/* Initializes memory allocation framework.
- * This routine is called from __libc_init routines implemented
- * in libc_init_static.c and libc_init_dynamic.c files.
- */
+// Initializes memory allocation framework.
+// This routine is called from __libc_init routines implemented
+// in libc_init_static.c and libc_init_dynamic.c files.
 extern "C" __LIBC_HIDDEN__ void malloc_debug_init() {
-#if defined(USE_DL_PREFIX) && !defined(LIBC_STATIC)
+#if !defined(LIBC_STATIC)
   static pthread_once_t malloc_init_once_ctl = PTHREAD_ONCE_INIT;
   if (pthread_once(&malloc_init_once_ctl, malloc_init_impl)) {
     error_log("Unable to initialize malloc_debug component.");
   }
-#endif  // USE_DL_PREFIX && !LIBC_STATIC
+#endif  // !LIBC_STATIC
 }
 
 extern "C" __LIBC_HIDDEN__ void malloc_debug_fini() {
-#if defined(USE_DL_PREFIX) && !defined(LIBC_STATIC)
+#if !defined(LIBC_STATIC)
   static pthread_once_t malloc_fini_once_ctl = PTHREAD_ONCE_INIT;
   if (pthread_once(&malloc_fini_once_ctl, malloc_fini_impl)) {
     error_log("Unable to finalize malloc_debug component.");
   }
-#endif  // USE_DL_PREFIX && !LIBC_STATIC
+#endif  // !LIBC_STATIC
 }
diff --git a/libc/bionic/malloc_debug_common.h b/libc/bionic/malloc_debug_common.h
index 21cb44c..8052a17 100644
--- a/libc/bionic/malloc_debug_common.h
+++ b/libc/bionic/malloc_debug_common.h
@@ -83,19 +83,27 @@
 };
 
 /* Entry in malloc dispatch table. */
-typedef void* (*MallocDebugMalloc)(size_t);
-typedef void (*MallocDebugFree)(void*);
 typedef void* (*MallocDebugCalloc)(size_t, size_t);
-typedef void* (*MallocDebugRealloc)(void*, size_t);
-typedef void* (*MallocDebugMemalign)(size_t, size_t);
+typedef void (*MallocDebugFree)(void*);
+typedef struct mallinfo (*MallocDebugMallinfo)();
+typedef void* (*MallocDebugMalloc)(size_t);
 typedef size_t (*MallocDebugMallocUsableSize)(const void*);
+typedef void* (*MallocDebugMemalign)(size_t, size_t);
+typedef int (*MallocDebugPosixMemalign)(void**, size_t, size_t);
+typedef void* (*MallocDebugPvalloc)(size_t);
+typedef void* (*MallocDebugRealloc)(void*, size_t);
+typedef void* (*MallocDebugValloc)(size_t);
 struct MallocDebug {
-  MallocDebugMalloc malloc;
-  MallocDebugFree free;
   MallocDebugCalloc calloc;
-  MallocDebugRealloc realloc;
-  MallocDebugMemalign memalign;
+  MallocDebugFree free;
+  MallocDebugMallinfo mallinfo;
+  MallocDebugMalloc malloc;
   MallocDebugMallocUsableSize malloc_usable_size;
+  MallocDebugMemalign memalign;
+  MallocDebugPosixMemalign posix_memalign;
+  MallocDebugPvalloc pvalloc;
+  MallocDebugRealloc realloc;
+  MallocDebugValloc valloc;
 };
 
 typedef bool (*MallocDebugInit)(HashTable*);
diff --git a/libc/bionic/malloc_debug_leak.cpp b/libc/bionic/malloc_debug_leak.cpp
index aa7c072..2cc38cc 100644
--- a/libc/bionic/malloc_debug_leak.cpp
+++ b/libc/bionic/malloc_debug_leak.cpp
@@ -250,6 +250,33 @@
     return Malloc(malloc_usable_size)(mem);
 }
 
+extern "C" struct mallinfo fill_mallinfo() {
+  return Malloc(mallinfo)();
+}
+
+extern "C" int fill_posix_memalign(void** memptr, size_t alignment, size_t size) {
+  if ((alignment & (alignment - 1)) != 0) {
+    return EINVAL;
+  }
+  int saved_errno = errno;
+  *memptr = fill_memalign(alignment, size);
+  errno = saved_errno;
+  return (*memptr != NULL) ? 0 : ENOMEM;
+}
+
+extern "C" void* fill_pvalloc(size_t bytes) {
+  size_t pagesize = sysconf(_SC_PAGESIZE);
+  size_t size = (bytes + pagesize - 1) & ~(pagesize - 1);
+  if (size < bytes) { // Overflow
+    return NULL;
+  }
+  return fill_memalign(pagesize, size);
+}
+
+extern "C" void* fill_valloc(size_t size) {
+  return fill_memalign(sysconf(_SC_PAGESIZE), size);
+}
+
 // =============================================================================
 // malloc leak functions
 // =============================================================================
@@ -265,6 +292,7 @@
 
     size_t size = bytes + sizeof(AllocationEntry);
     if (size < bytes) { // Overflow.
+        errno = ENOMEM;
         return NULL;
     }
 
@@ -327,6 +355,7 @@
     // Fail on overflow - just to be safe even though this code runs only
     // within the debugging C library, not the production one.
     if (n_elements && SIZE_MAX / n_elements < elem_size) {
+        errno = ENOMEM;
         return NULL;
     }
     size_t size = n_elements * elem_size;
@@ -350,6 +379,7 @@
     } else if (header->guard != GUARD) {
         debug_log("WARNING bad header guard: '0x%x'! and invalid entry: %p\n",
                    header->guard, header->entry);
+        errno = ENOMEM;
         return NULL;
     }
 
@@ -358,8 +388,8 @@
         size_t oldSize = header->entry->size & ~SIZE_FLAG_MASK;
         size_t copySize = (oldSize <= bytes) ? oldSize : bytes;
         memcpy(newMem, oldMem, copySize);
+        leak_free(oldMem);
     }
-    leak_free(oldMem);
 
     return newMem;
 }
@@ -428,3 +458,30 @@
     }
     return 0;
 }
+
+extern "C" struct mallinfo leak_mallinfo() {
+  return Malloc(mallinfo)();
+}
+
+extern "C" int leak_posix_memalign(void** memptr, size_t alignment, size_t size) {
+  if ((alignment & (alignment - 1)) != 0) {
+    return EINVAL;
+  }
+  int saved_errno = errno;
+  *memptr = leak_memalign(alignment, size);
+  errno = saved_errno;
+  return (*memptr != NULL) ? 0 : ENOMEM;
+}
+
+extern "C" void* leak_pvalloc(size_t bytes) {
+  size_t pagesize = sysconf(_SC_PAGESIZE);
+  size_t size = (bytes + pagesize - 1) & ~(pagesize - 1);
+  if (size < bytes) { // Overflow
+    return NULL;
+  }
+  return leak_memalign(pagesize, size);
+}
+
+extern "C" void* leak_valloc(size_t size) {
+  return leak_memalign(sysconf(_SC_PAGESIZE), size);
+}
diff --git a/libc/bionic/malloc_debug_qemu.cpp b/libc/bionic/malloc_debug_qemu.cpp
index 2dda767..4272482 100644
--- a/libc/bionic/malloc_debug_qemu.cpp
+++ b/libc/bionic/malloc_debug_qemu.cpp
@@ -573,12 +573,16 @@
 // API routines
 // =============================================================================
 
-extern "C" void* qemu_instrumented_malloc(size_t bytes);
-extern "C" void  qemu_instrumented_free(void* mem);
-extern "C" void* qemu_instrumented_calloc(size_t n_elements, size_t elem_size);
-extern "C" void* qemu_instrumented_realloc(void* mem, size_t bytes);
-extern "C" void* qemu_instrumented_memalign(size_t alignment, size_t bytes);
-extern "C" size_t qemu_instrumented_malloc_usable_size(const void* mem);
+extern "C" void* qemu_instrumented_calloc(size_t, size_t);
+extern "C" void  qemu_instrumented_free(void*);
+extern "C" struct mallinfo qemu_instrumented_mallinfo();
+extern "C" void* qemu_instrumented_malloc(size_t);
+extern "C" size_t qemu_instrumented_malloc_usable_size(const void*);
+extern "C" void* qemu_instrumented_memalign(size_t, size_t);
+extern "C" int qemu_instrumented_posix_memalign(void**, size_t, size_t);
+extern "C" void* qemu_instrumented_pvalloc(size_t);
+extern "C" void* qemu_instrumented_realloc(void*, size_t);
+extern "C" void* qemu_instrumented_valloc(size_t);
 
 /* Initializes malloc debugging instrumentation for the emulator.
  * This routine is called from malloc_init_impl routine implemented in
@@ -680,10 +684,17 @@
     desc.prefix_size = DEFAULT_PREFIX_SIZE;
     desc.requested_bytes = bytes;
     desc.suffix_size = DEFAULT_SUFFIX_SIZE;
-    desc.ptr = Malloc(malloc)(mallocdesc_alloc_size(&desc));
+    size_t size = mallocdesc_alloc_size(&desc);
+    if (size < bytes) { // Overflow
+        qemu_error_log("<libc_pid=%03u, pid=%03u> malloc: malloc(%zu) overflow caused failure.",
+                       malloc_pid, getpid(), bytes);
+        errno = ENOMEM;
+        return NULL;
+    }
+    desc.ptr = Malloc(malloc)(size);
     if (desc.ptr == NULL) {
-        qemu_error_log("<libc_pid=%03u, pid=%03u> malloc(%zd): malloc(%u) failed.",
-                  malloc_pid, getpid(), bytes, mallocdesc_alloc_size(&desc));
+        qemu_error_log("<libc_pid=%03u, pid=%03u> malloc(%zu): malloc(%u) failed.",
+                       malloc_pid, getpid(), bytes, size);
         return NULL;
     }
 
@@ -692,12 +703,13 @@
         log_mdesc(error, &desc, "<libc_pid=%03u, pid=%03u>: malloc: notify_malloc failed for ",
                   malloc_pid, getpid());
         Malloc(free)(desc.ptr);
+        errno = ENOMEM;
         return NULL;
     } else {
 #if TEST_ACCESS_VIOLATIONS
         test_access_violation(&desc);
 #endif  // TEST_ACCESS_VIOLATIONS
-        log_mdesc(info, &desc, "+++ <libc_pid=%03u, pid=%03u> malloc(%zd) -> ",
+        log_mdesc(info, &desc, "+++ <libc_pid=%03u, pid=%03u> malloc(%zu) -> ",
                   malloc_pid, getpid(), bytes);
         return mallocdesc_user_ptr(&desc);
     }
@@ -754,13 +766,16 @@
     if (n_elements == 0 || elem_size == 0) {
         // Just let go zero bytes allocation.
         qemu_info_log("::: <libc_pid=%03u, pid=%03u>: Zero calloc redir to malloc",
-                 malloc_pid, getpid());
+                      malloc_pid, getpid());
         return qemu_instrumented_malloc(0);
     }
 
     // Fail on overflow - just to be safe even though this code runs only
     // within the debugging C library, not the production one.
     if (n_elements && SIZE_MAX / n_elements < elem_size) {
+        qemu_error_log("<libc_pid=%03u, pid=%03u> calloc: calloc(%zu, %zu) overflow caused failure.",
+                       malloc_pid, getpid(), n_elements, elem_size);
+        errno = ENOMEM;
         return NULL;
     }
 
@@ -786,6 +801,12 @@
     }
     desc.requested_bytes = n_elements * elem_size;
     size_t total_size = desc.requested_bytes + desc.prefix_size + desc.suffix_size;
+    if (total_size < desc.requested_bytes) { // Overflow
+        qemu_error_log("<libc_pid=%03u, pid=%03u> calloc: calloc(%zu, %zu) overflow caused failure.",
+                       malloc_pid, getpid(), n_elements, elem_size);
+        errno = ENOMEM;
+        return NULL;
+    }
     size_t total_elements = total_size / elem_size;
     total_size %= elem_size;
     if (total_size != 0) {
@@ -795,22 +816,23 @@
     }
     desc.ptr = Malloc(calloc)(total_elements, elem_size);
     if (desc.ptr == NULL) {
-        error_log("<libc_pid=%03u, pid=%03u> calloc: calloc(%zd(%zd), %zd) (prx=%u, sfx=%u) failed.",
+        error_log("<libc_pid=%03u, pid=%03u> calloc: calloc(%zu(%zu), %zu) (prx=%u, sfx=%u) failed.",
                    malloc_pid, getpid(), n_elements, total_elements, elem_size,
                    desc.prefix_size, desc.suffix_size);
         return NULL;
     }
 
     if (notify_qemu_malloc(&desc)) {
-        log_mdesc(error, &desc, "<libc_pid=%03u, pid=%03u>: calloc(%zd(%zd), %zd): notify_malloc failed for ",
+        log_mdesc(error, &desc, "<libc_pid=%03u, pid=%03u>: calloc(%zu(%zu), %zu): notify_malloc failed for ",
                   malloc_pid, getpid(), n_elements, total_elements, elem_size);
         Malloc(free)(desc.ptr);
+        errno = ENOMEM;
         return NULL;
     } else {
 #if TEST_ACCESS_VIOLATIONS
         test_access_violation(&desc);
 #endif  // TEST_ACCESS_VIOLATIONS
-        log_mdesc(info, &desc, "### <libc_pid=%03u, pid=%03u> calloc(%zd(%zd), %zd) -> ",
+        log_mdesc(info, &desc, "### <libc_pid=%03u, pid=%03u> calloc(%zu(%zu), %zu) -> ",
                   malloc_pid, getpid(), n_elements, total_elements, elem_size);
         return mallocdesc_user_ptr(&desc);
     }
@@ -823,22 +845,17 @@
  * should not expect that pointer returned after shrinking will remain the same.
  */
 extern "C" void* qemu_instrumented_realloc(void* mem, size_t bytes) {
-    MallocDesc new_desc;
-    MallocDesc cur_desc;
-    size_t to_copy;
-    void* ret;
-
     if (mem == NULL) {
         // Nothing to realloc. just do regular malloc.
-        qemu_info_log("::: <libc_pid=%03u, pid=%03u>: realloc(%p, %zd) redir to malloc",
-                 malloc_pid, getpid(), mem, bytes);
+        qemu_info_log("::: <libc_pid=%03u, pid=%03u>: realloc(%p, %zu) redir to malloc",
+                      malloc_pid, getpid(), mem, bytes);
         return qemu_instrumented_malloc(bytes);
     }
 
     if (bytes == 0) {
         // This is a "free" condition.
-        qemu_info_log("::: <libc_pid=%03u, pid=%03u>: realloc(%p, %zd) redir to free and malloc",
-                 malloc_pid, getpid(), mem, bytes);
+        qemu_info_log("::: <libc_pid=%03u, pid=%03u>: realloc(%p, %zu) redir to free and malloc",
+                      malloc_pid, getpid(), mem, bytes);
         qemu_instrumented_free(mem);
 
         // This is what realloc does for a "free" realloc.
@@ -846,10 +863,12 @@
     }
 
     // Query emulator for the reallocating block information.
+    MallocDesc cur_desc;
     if (query_qemu_malloc_info(mem, &cur_desc, 2)) {
         // Note that this violation should be already caught in the emulator.
-        error_log("<libc_pid=%03u, pid=%03u>: realloc(%p, %zd) query_info failed.",
+        error_log("<libc_pid=%03u, pid=%03u>: realloc(%p, %zu) query_info failed.",
                   malloc_pid, getpid(), mem, bytes);
+        errno = ENOMEM;
         return NULL;
     }
 
@@ -861,8 +880,9 @@
      * for this memory block. Note that this violation should be already caught
      * in the emulator.*/
     if (mem != mallocdesc_user_ptr(&cur_desc)) {
-        log_mdesc(error, &cur_desc, "<libc_pid=%03u, pid=%03u>: realloc(%p, %zd) is invalid for ",
+        log_mdesc(error, &cur_desc, "<libc_pid=%03u, pid=%03u>: realloc(%p, %zu) is invalid for ",
                   malloc_pid, getpid(), mem, bytes);
+        errno = ENOMEM;
         return NULL;
     }
 
@@ -872,31 +892,38 @@
      * for this block that is stored in the emulator. */
 
     // Initialize descriptor for the new block.
+    MallocDesc new_desc;
     new_desc.prefix_size = DEFAULT_PREFIX_SIZE;
     new_desc.requested_bytes = bytes;
     new_desc.suffix_size = DEFAULT_SUFFIX_SIZE;
-    new_desc.ptr = Malloc(malloc)(mallocdesc_alloc_size(&new_desc));
-    if (new_desc.ptr == NULL) {
-        log_mdesc(error, &cur_desc, "<libc_pid=%03u, pid=%03u>: realloc(%p, %zd): malloc(%u) failed on ",
-                  malloc_pid, getpid(), mem, bytes,
-                  mallocdesc_alloc_size(&new_desc));
+    size_t new_size = mallocdesc_alloc_size(&new_desc);
+    if (new_size < bytes) { // Overflow
+        qemu_error_log("<libc_pid=%03u, pid=%03u>: realloc(%p, %zu): malloc(%u) failed due to overflow",
+                       malloc_pid, getpid(), mem, bytes, new_size);
+        errno = ENOMEM;
         return NULL;
     }
-    ret = mallocdesc_user_ptr(&new_desc);
+    new_desc.ptr = Malloc(malloc)(new_size);
+    if (new_desc.ptr == NULL) {
+        log_mdesc(error, &cur_desc, "<libc_pid=%03u, pid=%03u>: realloc(%p, %zu): malloc(%u) failed on ",
+                  malloc_pid, getpid(), mem, bytes, new_size);
+        return NULL;
+    }
+    void* new_mem = mallocdesc_user_ptr(&new_desc);
 
     // Copy user data from old block to the new one.
-    to_copy = bytes < cur_desc.requested_bytes ? bytes :
-                                                 cur_desc.requested_bytes;
+    size_t to_copy = bytes < cur_desc.requested_bytes ? bytes : cur_desc.requested_bytes;
     if (to_copy != 0) {
-        memcpy(ret, mallocdesc_user_ptr(&cur_desc), to_copy);
+        memcpy(new_mem, mallocdesc_user_ptr(&cur_desc), to_copy);
     }
 
     // Register new block with emulator.
     if (notify_qemu_malloc(&new_desc)) {
-        log_mdesc(error, &new_desc, "<libc_pid=%03u, pid=%03u>: realloc(%p, %zd) notify_malloc failed -> ",
+        log_mdesc(error, &new_desc, "<libc_pid=%03u, pid=%03u>: realloc(%p, %zu) notify_malloc failed -> ",
                   malloc_pid, getpid(), mem, bytes);
         log_mdesc(error, &cur_desc, "                                                                <- ");
         Malloc(free)(new_desc.ptr);
+        errno = ENOMEM;
         return NULL;
     }
 
@@ -906,21 +933,22 @@
 
     // Free old block.
     if (notify_qemu_free(mem)) {
-        log_mdesc(error, &cur_desc, "<libc_pid=%03u, pid=%03u>: realloc(%p, %zd): notify_free failed for ",
+        log_mdesc(error, &cur_desc, "<libc_pid=%03u, pid=%03u>: realloc(%p, %zu): notify_free failed for ",
                   malloc_pid, getpid(), mem, bytes);
         /* Since we registered new decriptor with the emulator, we need
          * to unregister it before freeing newly allocated block. */
         notify_qemu_free(mallocdesc_user_ptr(&new_desc));
         Malloc(free)(new_desc.ptr);
+        errno = ENOMEM;
         return NULL;
     }
     Malloc(free)(cur_desc.ptr);
 
-    log_mdesc(info, &new_desc, "=== <libc_pid=%03u, pid=%03u>: realloc(%p, %zd) -> ",
+    log_mdesc(info, &new_desc, "=== <libc_pid=%03u, pid=%03u>: realloc(%p, %zu) -> ",
               malloc_pid, getpid(), mem, bytes);
     log_mdesc(info, &cur_desc, "                                               <- ");
 
-    return ret;
+    return new_mem;
 }
 
 /* This routine serves as entry point for 'memalign'.
@@ -931,28 +959,38 @@
 
     if (bytes == 0) {
         // Just let go zero bytes allocation.
-        qemu_info_log("::: <libc_pid=%03u, pid=%03u>: memalign(%zx, %zd) redir to malloc",
+        qemu_info_log("::: <libc_pid=%03u, pid=%03u>: memalign(%zx, %zu) redir to malloc",
                  malloc_pid, getpid(), alignment, bytes);
         return qemu_instrumented_malloc(0);
     }
 
-    /* Prefix size for aligned allocation must be equal to the alignment used
-     * for allocation in order to ensure proper alignment of the returned
-     * pointer, in case that alignment requirement is greater than prefix
-     * size. */
-    desc.prefix_size = alignment > DEFAULT_PREFIX_SIZE ? alignment :
-                                                         DEFAULT_PREFIX_SIZE;
+    // Prefix size for aligned allocation must be equal to the alignment used
+    // for allocation in order to ensure proper alignment of the returned
+    // pointer. in case that alignment requirement is greater than prefix
+    // size.
+    if (alignment < DEFAULT_PREFIX_SIZE) {
+        alignment = DEFAULT_PREFIX_SIZE;
+    } else if (alignment & (alignment - 1)) {
+        alignment = 1L << (31 - __builtin_clz(alignment));
+    }
+    desc.prefix_size = alignment;
     desc.requested_bytes = bytes;
     desc.suffix_size = DEFAULT_SUFFIX_SIZE;
-    desc.ptr = Malloc(memalign)(desc.prefix_size, mallocdesc_alloc_size(&desc));
+    size_t size = mallocdesc_alloc_size(&desc);
+    if (size < bytes) { // Overflow
+        qemu_error_log("<libc_pid=%03u, pid=%03u> memalign(%zx, %zu): malloc(%u) failed due to overflow.",
+                       malloc_pid, getpid(), alignment, bytes, size);
+
+        return NULL;
+    }
+    desc.ptr = Malloc(memalign)(desc.prefix_size, size);
     if (desc.ptr == NULL) {
-        error_log("<libc_pid=%03u, pid=%03u> memalign(%zx, %zd): malloc(%u) failed.",
-                  malloc_pid, getpid(), alignment, bytes,
-                  mallocdesc_alloc_size(&desc));
+        error_log("<libc_pid=%03u, pid=%03u> memalign(%zx, %zu): malloc(%u) failed.",
+                  malloc_pid, getpid(), alignment, bytes, size);
         return NULL;
     }
     if (notify_qemu_malloc(&desc)) {
-        log_mdesc(error, &desc, "<libc_pid=%03u, pid=%03u>: memalign(%zx, %zd): notify_malloc failed for ",
+        log_mdesc(error, &desc, "<libc_pid=%03u, pid=%03u>: memalign(%zx, %zu): notify_malloc failed for ",
                   malloc_pid, getpid(), alignment, bytes);
         Malloc(free)(desc.ptr);
         return NULL;
@@ -962,7 +1000,7 @@
     test_access_violation(&desc);
 #endif  // TEST_ACCESS_VIOLATIONS
 
-    log_mdesc(info, &desc, "@@@ <libc_pid=%03u, pid=%03u> memalign(%zx, %zd) -> ",
+    log_mdesc(info, &desc, "@@@ <libc_pid=%03u, pid=%03u> memalign(%zx, %zu) -> ",
               malloc_pid, getpid(), alignment, bytes);
     return mallocdesc_user_ptr(&desc);
 }
@@ -990,3 +1028,34 @@
     /* during instrumentation, we can't really report anything more than requested_bytes */
     return cur_desc.requested_bytes;
 }
+
+extern "C" struct mallinfo qemu_instrumented_mallinfo() {
+  return Malloc(mallinfo)();
+}
+
+extern "C" int qemu_instrumented_posix_memalign(void** memptr, size_t alignment, size_t size) {
+  if ((alignment & (alignment - 1)) != 0) {
+    qemu_error_log("<libc_pid=%03u, pid=%03u> posix_memalign(%p, %zu, %zu): invalid alignment.",
+                   malloc_pid, getpid(), memptr, alignment, size);
+    return EINVAL;
+  }
+  int saved_errno = errno;
+  *memptr = qemu_instrumented_memalign(alignment, size);
+  errno = saved_errno;
+  return (*memptr != NULL) ? 0 : ENOMEM;
+}
+
+extern "C" void* qemu_instrumented_pvalloc(size_t bytes) {
+  size_t pagesize = sysconf(_SC_PAGESIZE);
+  size_t size = (bytes + pagesize - 1) & ~(pagesize - 1);
+  if (size < bytes) { // Overflow
+    qemu_error_log("<libc_pid=%03u, pid=%03u> pvalloc(%zu): overflow (%zu).",
+                   malloc_pid, getpid(), bytes, size);
+    return NULL;
+  }
+  return qemu_instrumented_memalign(pagesize, size);
+}
+
+extern "C" void* qemu_instrumented_valloc(size_t size) {
+  return qemu_instrumented_memalign(sysconf(_SC_PAGESIZE), size);
+}
diff --git a/libc/include/stdio.h b/libc/include/stdio.h
index efc5492..62acb3a 100644
--- a/libc/include/stdio.h
+++ b/libc/include/stdio.h
@@ -337,8 +337,6 @@
 		__printflike(2, 3);
 char	*fgetln(FILE * __restrict, size_t * __restrict);
 int	 fpurge(FILE *);
-int	 getw(FILE *);
-int	 putw(int, FILE *);
 void	 setbuffer(FILE *, char *, int);
 int	 setlinebuf(FILE *);
 int	 vasprintf(char ** __restrict, const char * __restrict,
diff --git a/libc/include/stdlib.h b/libc/include/stdlib.h
index 0f862c3..0f985e2 100644
--- a/libc/include/stdlib.h
+++ b/libc/include/stdlib.h
@@ -105,20 +105,15 @@
 extern void arc4random_addrandom(unsigned char *, int);
 
 #define RAND_MAX 0x7fffffff
-static __inline__ int rand(void) {
-    return (int)lrand48();
-}
-static __inline__ void srand(unsigned int __s) {
-    srand48(__s);
-}
-static __inline__ long random(void)
-{
-    return lrand48();
-}
-static __inline__ void srandom(unsigned int __s)
-{
-    srand48(__s);
-}
+
+int rand(void);
+int rand_r(unsigned int*);
+void srand(unsigned int);
+
+char* initstate(unsigned int, char*, size_t);
+long random(void);
+char* setstate(char*);
+void srandom(unsigned int);
 
 /* Basic PTY functions.  These only work if devpts is mounted! */
 
diff --git a/libc/upstream-dlmalloc/malloc.c b/libc/upstream-dlmalloc/malloc.c
index 3ef9b61..4362f49 100644
--- a/libc/upstream-dlmalloc/malloc.c
+++ b/libc/upstream-dlmalloc/malloc.c
@@ -5317,12 +5317,19 @@
   return dlmemalign(pagesz, bytes);
 }
 
+/* BEGIN android-changed: added overflow check */
 void* dlpvalloc(size_t bytes) {
   size_t pagesz;
+  size_t size;
   ensure_initialization();
   pagesz = mparams.page_size;
-  return dlmemalign(pagesz, (bytes + pagesz - SIZE_T_ONE) & ~(pagesz - SIZE_T_ONE));
+  size = (bytes + pagesz - SIZE_T_ONE) & ~(pagesz - SIZE_T_ONE);
+  if (size < bytes) {
+    return NULL;
+  }
+  return dlmemalign(pagesz, size);
 }
+/* END android-change */
 
 void** dlindependent_calloc(size_t n_elements, size_t elem_size,
                             void* chunks[]) {
diff --git a/libc/upstream-netbsd/common/lib/libc/stdlib/random.c b/libc/upstream-netbsd/common/lib/libc/stdlib/random.c
new file mode 100644
index 0000000..e7503c7
--- /dev/null
+++ b/libc/upstream-netbsd/common/lib/libc/stdlib/random.c
@@ -0,0 +1,530 @@
+/*	$NetBSD: random.c,v 1.4 2014/06/12 20:59:46 christos Exp $	*/
+
+/*
+ * Copyright (c) 1983, 1993
+ *	The Regents of the University of California.  All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of the University nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#if !defined(_KERNEL) && !defined(_STANDALONE)
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)random.c	8.2 (Berkeley) 5/19/95";
+#else
+__RCSID("$NetBSD: random.c,v 1.4 2014/06/12 20:59:46 christos Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+
+#include <assert.h>
+#include <errno.h>
+#include <stdlib.h>
+#include "reentrant.h"
+
+#ifdef __weak_alias
+__weak_alias(initstate,_initstate)
+__weak_alias(random,_random)
+__weak_alias(setstate,_setstate)
+__weak_alias(srandom,_srandom)
+#endif
+
+
+#ifdef _REENTRANT
+static mutex_t random_mutex = MUTEX_INITIALIZER;
+#endif
+#else
+#include <lib/libkern/libkern.h>
+#define mutex_lock(a)	(void)0
+#define mutex_unlock(a) (void)0
+#endif
+
+#ifndef SMALL_RANDOM
+static void srandom_unlocked(unsigned int);
+static long random_unlocked(void);
+
+#define USE_BETTER_RANDOM
+
+/*
+ * random.c:
+ *
+ * An improved random number generation package.  In addition to the standard
+ * rand()/srand() like interface, this package also has a special state info
+ * interface.  The initstate() routine is called with a seed, an array of
+ * bytes, and a count of how many bytes are being passed in; this array is
+ * then initialized to contain information for random number generation with
+ * that much state information.  Good sizes for the amount of state
+ * information are 32, 64, 128, and 256 bytes.  The state can be switched by
+ * calling the setstate() routine with the same array as was initiallized
+ * with initstate().  By default, the package runs with 128 bytes of state
+ * information and generates far better random numbers than a linear
+ * congruential generator.  If the amount of state information is less than
+ * 32 bytes, a simple linear congruential R.N.G. is used.
+ *
+ * Internally, the state information is treated as an array of ints; the
+ * zeroeth element of the array is the type of R.N.G. being used (small
+ * integer); the remainder of the array is the state information for the
+ * R.N.G.  Thus, 32 bytes of state information will give 7 ints worth of
+ * state information, which will allow a degree seven polynomial.  (Note:
+ * the zeroeth word of state information also has some other information
+ * stored in it -- see setstate() for details).
+ * 
+ * The random number generation technique is a linear feedback shift register
+ * approach, employing trinomials (since there are fewer terms to sum up that
+ * way).  In this approach, the least significant bit of all the numbers in
+ * the state table will act as a linear feedback shift register, and will
+ * have period 2^deg - 1 (where deg is the degree of the polynomial being
+ * used, assuming that the polynomial is irreducible and primitive).  The
+ * higher order bits will have longer periods, since their values are also
+ * influenced by pseudo-random carries out of the lower bits.  The total
+ * period of the generator is approximately deg*(2**deg - 1); thus doubling
+ * the amount of state information has a vast influence on the period of the
+ * generator.  Note: the deg*(2**deg - 1) is an approximation only good for
+ * large deg, when the period of the shift register is the dominant factor.
+ * With deg equal to seven, the period is actually much longer than the
+ * 7*(2**7 - 1) predicted by this formula.
+ *
+ * Modified 28 December 1994 by Jacob S. Rosenberg.
+ * The following changes have been made:
+ * All references to the type u_int have been changed to unsigned long.
+ * All references to type int have been changed to type long.  Other
+ * cleanups have been made as well.  A warning for both initstate and
+ * setstate has been inserted to the effect that on Sparc platforms
+ * the 'arg_state' variable must be forced to begin on word boundaries.
+ * This can be easily done by casting a long integer array to char *.
+ * The overall logic has been left STRICTLY alone.  This software was
+ * tested on both a VAX and Sun SpacsStation with exactly the same
+ * results.  The new version and the original give IDENTICAL results.
+ * The new version is somewhat faster than the original.  As the
+ * documentation says:  "By default, the package runs with 128 bytes of
+ * state information and generates far better random numbers than a linear
+ * congruential generator.  If the amount of state information is less than
+ * 32 bytes, a simple linear congruential R.N.G. is used."  For a buffer of
+ * 128 bytes, this new version runs about 19 percent faster and for a 16
+ * byte buffer it is about 5 percent faster.
+ *
+ * Modified 07 January 2002 by Jason R. Thorpe.
+ * The following changes have been made:
+ * All the references to "long" have been changed back to "int".  This
+ * fixes memory corruption problems on LP64 platforms.
+ */
+
+/*
+ * For each of the currently supported random number generators, we have a
+ * break value on the amount of state information (you need at least this
+ * many bytes of state info to support this random number generator), a degree
+ * for the polynomial (actually a trinomial) that the R.N.G. is based on, and
+ * the separation between the two lower order coefficients of the trinomial.
+ */
+#define	TYPE_0		0		/* linear congruential */
+#define	BREAK_0		8
+#define	DEG_0		0
+#define	SEP_0		0
+
+#define	TYPE_1		1		/* x**7 + x**3 + 1 */
+#define	BREAK_1		32
+#define	DEG_1		7
+#define	SEP_1		3
+
+#define	TYPE_2		2		/* x**15 + x + 1 */
+#define	BREAK_2		64
+#define	DEG_2		15
+#define	SEP_2		1
+
+#define	TYPE_3		3		/* x**31 + x**3 + 1 */
+#define	BREAK_3		128
+#define	DEG_3		31
+#define	SEP_3		3
+
+#define	TYPE_4		4		/* x**63 + x + 1 */
+#define	BREAK_4		256
+#define	DEG_4		63
+#define	SEP_4		1
+
+/*
+ * Array versions of the above information to make code run faster --
+ * relies on fact that TYPE_i == i.
+ */
+#define	MAX_TYPES	5		/* max number of types above */
+
+static const int degrees[MAX_TYPES] =	{ DEG_0, DEG_1, DEG_2, DEG_3, DEG_4 };
+static const int seps[MAX_TYPES] =	{ SEP_0, SEP_1, SEP_2, SEP_3, SEP_4 };
+
+/*
+ * Initially, everything is set up as if from:
+ *
+ *	initstate(1, &randtbl, 128);
+ *
+ * Note that this initialization takes advantage of the fact that srandom()
+ * advances the front and rear pointers 10*rand_deg times, and hence the
+ * rear pointer which starts at 0 will also end up at zero; thus the zeroeth
+ * element of the state information, which contains info about the current
+ * position of the rear pointer is just
+ *
+ *	MAX_TYPES * (rptr - state) + TYPE_3 == TYPE_3.
+ */
+
+/* LINTED */
+static int randtbl[DEG_3 + 1] = {
+	TYPE_3,
+#ifdef USE_BETTER_RANDOM
+	0x991539b1, 0x16a5bce3, 0x6774a4cd,
+	0x3e01511e, 0x4e508aaa, 0x61048c05,
+	0xf5500617, 0x846b7115, 0x6a19892c,
+	0x896a97af, 0xdb48f936, 0x14898454,
+	0x37ffd106, 0xb58bff9c, 0x59e17104,
+	0xcf918a49, 0x09378c83, 0x52c7a471,
+	0x8d293ea9, 0x1f4fc301, 0xc3db71be,
+	0x39b44e1c, 0xf8a44ef9, 0x4c8b80b1,
+	0x19edc328, 0x87bf4bdd, 0xc9b240e5,
+	0xe9ee4b1b, 0x4382aee7, 0x535b6b41,
+	0xf3bec5da,
+#else
+	0x9a319039, 0x32d9c024, 0x9b663182,
+	0x5da1f342, 0xde3b81e0, 0xdf0a6fb5,
+	0xf103bc02, 0x48f340fb, 0x7449e56b,
+	0xbeb1dbb0, 0xab5c5918, 0x946554fd,
+	0x8c2e680f, 0xeb3d799f, 0xb11ee0b7,
+	0x2d436b86, 0xda672e2a, 0x1588ca88,
+	0xe369735d, 0x904f35f7, 0xd7158fd6,
+	0x6fa6f051, 0x616e6b96, 0xac94efdc,
+	0x36413f93, 0xc622c298, 0xf5a42ab8,
+	0x8a88d77b, 0xf5ad9d0e, 0x8999220b,
+	0x27fb47b9,
+#endif /* USE_BETTER_RANDOM */
+};
+
+/*
+ * fptr and rptr are two pointers into the state info, a front and a rear
+ * pointer.  These two pointers are always rand_sep places aparts, as they
+ * cycle cyclically through the state information.  (Yes, this does mean we
+ * could get away with just one pointer, but the code for random() is more
+ * efficient this way).  The pointers are left positioned as they would be
+ * from the call
+ *
+ *	initstate(1, randtbl, 128);
+ *
+ * (The position of the rear pointer, rptr, is really 0 (as explained above
+ * in the initialization of randtbl) because the state table pointer is set
+ * to point to randtbl[1] (as explained below).
+ */
+static int *fptr = &randtbl[SEP_3 + 1];
+static int *rptr = &randtbl[1];
+
+/*
+ * The following things are the pointer to the state information table, the
+ * type of the current generator, the degree of the current polynomial being
+ * used, and the separation between the two pointers.  Note that for efficiency
+ * of random(), we remember the first location of the state information, not
+ * the zeroeth.  Hence it is valid to access state[-1], which is used to
+ * store the type of the R.N.G.  Also, we remember the last location, since
+ * this is more efficient than indexing every time to find the address of
+ * the last element to see if the front and rear pointers have wrapped.
+ */
+static int *state = &randtbl[1];
+static int rand_type = TYPE_3;
+static int rand_deg = DEG_3;
+static int rand_sep = SEP_3;
+static int *end_ptr = &randtbl[DEG_3 + 1];
+
+/*
+ * srandom:
+ *
+ * Initialize the random number generator based on the given seed.  If the
+ * type is the trivial no-state-information type, just remember the seed.
+ * Otherwise, initializes state[] based on the given "seed" via a linear
+ * congruential generator.  Then, the pointers are set to known locations
+ * that are exactly rand_sep places apart.  Lastly, it cycles the state
+ * information a given number of times to get rid of any initial dependencies
+ * introduced by the L.C.R.N.G.  Note that the initialization of randtbl[]
+ * for default usage relies on values produced by this routine.
+ */
+static void
+srandom_unlocked(unsigned int x)
+{
+	int i;
+
+	if (rand_type == TYPE_0)
+		state[0] = x;
+	else {
+		state[0] = x;
+		for (i = 1; i < rand_deg; i++) {
+#ifdef USE_BETTER_RANDOM
+			int x1, hi, lo, t;
+
+			/*
+			 * Compute x[n + 1] = (7^5 * x[n]) mod (2^31 - 1).
+			 * From "Random number generators: good ones are hard
+			 * to find", Park and Miller, Communications of the ACM,
+			 * vol. 31, no. 10,
+			 * October 1988, p. 1195.
+			 */
+			x1 = state[i - 1];
+			hi = x1 / 127773;
+			lo = x1 % 127773;
+			t = 16807 * lo - 2836 * hi;
+			if (t <= 0)
+				t += 0x7fffffff;
+			state[i] = t;
+#else
+			state[i] = 1103515245 * state[i - 1] + 12345;
+#endif /* USE_BETTER_RANDOM */
+		}
+		fptr = &state[rand_sep];
+		rptr = &state[0];
+		for (i = 0; i < 10 * rand_deg; i++)
+			(void)random_unlocked();
+	}
+}
+
+void
+srandom(unsigned int x)
+{
+
+	mutex_lock(&random_mutex);
+	srandom_unlocked(x);
+	mutex_unlock(&random_mutex);
+}
+
+/*
+ * initstate:
+ *
+ * Initialize the state information in the given array of n bytes for future
+ * random number generation.  Based on the number of bytes we are given, and
+ * the break values for the different R.N.G.'s, we choose the best (largest)
+ * one we can and set things up for it.  srandom() is then called to
+ * initialize the state information.
+ * 
+ * Note that on return from srandom(), we set state[-1] to be the type
+ * multiplexed with the current value of the rear pointer; this is so
+ * successive calls to initstate() won't lose this information and will be
+ * able to restart with setstate().
+ * 
+ * Note: the first thing we do is save the current state, if any, just like
+ * setstate() so that it doesn't matter when initstate is called.
+ *
+ * Returns a pointer to the old state.
+ *
+ * Note: The Sparc platform requires that arg_state begin on an int
+ * word boundary; otherwise a bus error will occur. Even so, lint will
+ * complain about mis-alignment, but you should disregard these messages.
+ */
+char *
+initstate(
+	unsigned int seed,		/* seed for R.N.G. */
+	char *arg_state,		/* pointer to state array */
+	size_t n)			/* # bytes of state info */
+{
+	void *ostate = (void *)(&state[-1]);
+	int *int_arg_state;
+
+	_DIAGASSERT(arg_state != NULL);
+
+	int_arg_state = (int *)(void *)arg_state;
+
+	mutex_lock(&random_mutex);
+	if (rand_type == TYPE_0)
+		state[-1] = rand_type;
+	else
+		state[-1] = MAX_TYPES * (int)(rptr - state) + rand_type;
+	if (n < BREAK_0) {
+		mutex_unlock(&random_mutex);
+		return (NULL);
+	} else if (n < BREAK_1) {
+		rand_type = TYPE_0;
+		rand_deg = DEG_0;
+		rand_sep = SEP_0;
+	} else if (n < BREAK_2) {
+		rand_type = TYPE_1;
+		rand_deg = DEG_1;
+		rand_sep = SEP_1;
+	} else if (n < BREAK_3) {
+		rand_type = TYPE_2;
+		rand_deg = DEG_2;
+		rand_sep = SEP_2;
+	} else if (n < BREAK_4) {
+		rand_type = TYPE_3;
+		rand_deg = DEG_3;
+		rand_sep = SEP_3;
+	} else {
+		rand_type = TYPE_4;
+		rand_deg = DEG_4;
+		rand_sep = SEP_4;
+	}
+	state = (int *) (int_arg_state + 1); /* first location */
+	end_ptr = &state[rand_deg];	/* must set end_ptr before srandom */
+	srandom_unlocked(seed);
+	if (rand_type == TYPE_0)
+		int_arg_state[0] = rand_type;
+	else
+		int_arg_state[0] = MAX_TYPES * (int)(rptr - state) + rand_type;
+	mutex_unlock(&random_mutex);
+	return((char *)ostate);
+}
+
+/*
+ * setstate:
+ *
+ * Restore the state from the given state array.
+ *
+ * Note: it is important that we also remember the locations of the pointers
+ * in the current state information, and restore the locations of the pointers
+ * from the old state information.  This is done by multiplexing the pointer
+ * location into the zeroeth word of the state information.
+ *
+ * Note that due to the order in which things are done, it is OK to call
+ * setstate() with the same state as the current state.
+ *
+ * Returns a pointer to the old state information.
+ *
+ * Note: The Sparc platform requires that arg_state begin on a long
+ * word boundary; otherwise a bus error will occur. Even so, lint will
+ * complain about mis-alignment, but you should disregard these messages.
+ */
+char *
+setstate(char *arg_state)		/* pointer to state array */
+{
+	int *new_state;
+	int type;
+	int rear;
+	void *ostate = (void *)(&state[-1]);
+
+	_DIAGASSERT(arg_state != NULL);
+
+	new_state = (int *)(void *)arg_state;
+	type = (int)(new_state[0] % MAX_TYPES);
+	rear = (int)(new_state[0] / MAX_TYPES);
+
+	mutex_lock(&random_mutex);
+	if (rand_type == TYPE_0)
+		state[-1] = rand_type;
+	else
+		state[-1] = MAX_TYPES * (int)(rptr - state) + rand_type;
+	switch(type) {
+	case TYPE_0:
+	case TYPE_1:
+	case TYPE_2:
+	case TYPE_3:
+	case TYPE_4:
+		rand_type = type;
+		rand_deg = degrees[type];
+		rand_sep = seps[type];
+		break;
+	default:
+		mutex_unlock(&random_mutex);
+		return (NULL);
+	}
+	state = (int *) (new_state + 1);
+	if (rand_type != TYPE_0) {
+		rptr = &state[rear];
+		fptr = &state[(rear + rand_sep) % rand_deg];
+	}
+	end_ptr = &state[rand_deg];		/* set end_ptr too */
+	mutex_unlock(&random_mutex);
+	return((char *)ostate);
+}
+
+/*
+ * random:
+ *
+ * If we are using the trivial TYPE_0 R.N.G., just do the old linear
+ * congruential bit.  Otherwise, we do our fancy trinomial stuff, which is
+ * the same in all the other cases due to all the global variables that have
+ * been set up.  The basic operation is to add the number at the rear pointer
+ * into the one at the front pointer.  Then both pointers are advanced to
+ * the next location cyclically in the table.  The value returned is the sum
+ * generated, reduced to 31 bits by throwing away the "least random" low bit.
+ *
+ * Note: the code takes advantage of the fact that both the front and
+ * rear pointers can't wrap on the same call by not testing the rear
+ * pointer if the front one has wrapped.
+ *
+ * Returns a 31-bit random number.
+ */
+static long
+random_unlocked(void)
+{
+	int i;
+	int *f, *r;
+
+	if (rand_type == TYPE_0) {
+		i = state[0];
+		state[0] = i = (i * 1103515245 + 12345) & 0x7fffffff;
+	} else {
+		/*
+		 * Use local variables rather than static variables for speed.
+		 */
+		f = fptr; r = rptr;
+		*f += *r;
+		/* chucking least random bit */
+		i = ((unsigned int)*f >> 1) & 0x7fffffff;
+		if (++f >= end_ptr) {
+			f = state;
+			++r;
+		}
+		else if (++r >= end_ptr) {
+			r = state;
+		}
+
+		fptr = f; rptr = r;
+	}
+	return(i);
+}
+
+long
+random(void)
+{
+	long r;
+
+	mutex_lock(&random_mutex);
+	r = random_unlocked();
+	mutex_unlock(&random_mutex);
+	return (r);
+}
+#else
+long
+random(void)
+{
+	static u_long randseed = 1;
+	long x, hi, lo, t;
+ 
+	/*
+	 * Compute x[n + 1] = (7^5 * x[n]) mod (2^31 - 1).
+	 * From "Random number generators: good ones are hard to find",
+	 * Park and Miller, Communications of the ACM, vol. 31, no. 10,
+	 * October 1988, p. 1195.
+	 */
+	x = randseed;
+	hi = x / 127773;
+	lo = x % 127773;
+	t = 16807 * lo - 2836 * hi;
+	if (t <= 0)
+		t += 0x7fffffff;
+	randseed = t;
+	return (t);
+}
+#endif /* SMALL_RANDOM */
diff --git a/libc/upstream-netbsd/lib/libc/stdlib/rand.c b/libc/upstream-netbsd/lib/libc/stdlib/rand.c
new file mode 100644
index 0000000..4909d14
--- /dev/null
+++ b/libc/upstream-netbsd/lib/libc/stdlib/rand.c
@@ -0,0 +1,57 @@
+/*	$NetBSD: rand.c,v 1.12 2012/06/25 22:32:45 abs Exp $	*/
+
+/*-
+ * Copyright (c) 1990, 1993
+ *	The Regents of the University of California.  All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of the University nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)rand.c	8.1 (Berkeley) 6/14/93";
+#else
+__RCSID("$NetBSD: rand.c,v 1.12 2012/06/25 22:32:45 abs Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include <sys/types.h>
+#include <stdlib.h>
+
+static u_long next = 1;
+
+int
+rand(void)
+{
+	/* LINTED integer overflow */
+	return (int)((next = next * 1103515245 + 12345) % ((u_long)RAND_MAX + 1));
+}
+
+void
+srand(u_int seed)
+{
+	next = seed;
+}
diff --git a/libc/upstream-netbsd/lib/libc/stdlib/rand_r.c b/libc/upstream-netbsd/lib/libc/stdlib/rand_r.c
new file mode 100644
index 0000000..272b2bd
--- /dev/null
+++ b/libc/upstream-netbsd/lib/libc/stdlib/rand_r.c
@@ -0,0 +1,51 @@
+/*	$NetBSD: rand_r.c,v 1.6 2012/06/25 22:32:45 abs Exp $	*/
+
+/*-
+ * Copyright (c) 1990 The Regents of the University of California.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of the University nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char *sccsid = "from: @(#)rand.c	5.6 (Berkeley) 6/24/91";
+#else
+__RCSID("$NetBSD: rand_r.c,v 1.6 2012/06/25 22:32:45 abs Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include <assert.h>
+#include <errno.h>
+#include <stdlib.h>
+
+int
+rand_r(unsigned int *seed)
+{
+	_DIAGASSERT(seed != NULL);
+
+	return ((*seed = *seed * 1103515245 + 12345) & RAND_MAX);
+}
diff --git a/tests/TemporaryFile.h b/tests/TemporaryFile.h
index a7b13b0..c4ee2d5 100644
--- a/tests/TemporaryFile.h
+++ b/tests/TemporaryFile.h
@@ -14,6 +14,7 @@
  * limitations under the License.
  */
 
+#include <fcntl.h>
 #include <unistd.h>
 
 template<int (*mk_fn)(char*)>
@@ -39,6 +40,11 @@
     unlink(filename);
   }
 
+  void reopen() {
+    close(fd);
+    fd = open(filename, O_RDWR);
+  }
+
   int fd;
   char filename[1024];
 
diff --git a/tests/malloc_test.cpp b/tests/malloc_test.cpp
index 12a5ffa..ed98f15 100644
--- a/tests/malloc_test.cpp
+++ b/tests/malloc_test.cpp
@@ -16,18 +16,26 @@
 
 #include <gtest/gtest.h>
 
+#include <limits.h>
+#include <stdint.h>
 #include <stdlib.h>
 #include <malloc.h>
+#include <unistd.h>
 
 TEST(malloc, malloc_std) {
   // Simple malloc test.
   void *ptr = malloc(100);
   ASSERT_TRUE(ptr != NULL);
   ASSERT_LE(100U, malloc_usable_size(ptr));
-
   free(ptr);
 }
 
+TEST(malloc, malloc_overflow) {
+  errno = 0;
+  ASSERT_EQ(NULL, malloc(SIZE_MAX));
+  ASSERT_EQ(ENOMEM, errno);
+}
+
 TEST(malloc, calloc_std) {
   // Simple calloc test.
   size_t alloc_len = 100;
@@ -37,24 +45,67 @@
   for (size_t i = 0; i < alloc_len; i++) {
     ASSERT_EQ(0, ptr[i]);
   }
-
   free(ptr);
 }
 
+TEST(malloc, calloc_illegal) {
+  errno = 0;
+  ASSERT_EQ(NULL, calloc(-1, 100));
+  ASSERT_EQ(ENOMEM, errno);
+}
+
+TEST(malloc, calloc_overflow) {
+  errno = 0;
+  ASSERT_EQ(NULL, calloc(1, SIZE_MAX));
+  ASSERT_EQ(ENOMEM, errno);
+  errno = 0;
+  ASSERT_EQ(NULL, calloc(SIZE_MAX, SIZE_MAX));
+  ASSERT_EQ(ENOMEM, errno);
+  errno = 0;
+  ASSERT_EQ(NULL, calloc(2, SIZE_MAX));
+  ASSERT_EQ(ENOMEM, errno);
+  errno = 0;
+  ASSERT_EQ(NULL, calloc(SIZE_MAX, 2));
+  ASSERT_EQ(ENOMEM, errno);
+}
+
 TEST(malloc, memalign_multiple) {
   // Memalign test where the alignment is any value.
   for (size_t i = 0; i <= 12; i++) {
     for (size_t alignment = 1 << i; alignment < (1U << (i+1)); alignment++) {
-      char *ptr = (char*)memalign(alignment, 100);
-      ASSERT_TRUE(ptr != NULL) << alignment;
-      ASSERT_LE(100U, malloc_usable_size(ptr));
-      ASSERT_EQ(0, (intptr_t)ptr % (1 << i));
-
+      char *ptr = reinterpret_cast<char*>(memalign(alignment, 100));
+      ASSERT_TRUE(ptr != NULL) << "Failed at alignment " << alignment;
+      ASSERT_LE(100U, malloc_usable_size(ptr)) << "Failed at alignment " << alignment;
+      ASSERT_EQ(0U, reinterpret_cast<uintptr_t>(ptr) % ((1U << i)))
+          << "Failed at alignment " << alignment;
       free(ptr);
     }
   }
 }
 
+TEST(malloc, memalign_overflow) {
+  ASSERT_EQ(NULL, memalign(4096, SIZE_MAX));
+}
+
+TEST(malloc, memalign_non_power2) {
+  void* ptr;
+  for (size_t align = 0; align <= 256; align++) {
+    ptr = memalign(align, 1024);
+    ASSERT_TRUE(ptr != NULL) << "Failed at align " << align;
+    free(ptr);
+  }
+}
+
+TEST(malloc, posix_memalign_non_power2) {
+  void* ptr;
+  ASSERT_EQ(EINVAL, posix_memalign(&ptr, 17, 1024));
+}
+
+TEST(malloc, posix_memalign_overflow) {
+  void* ptr;
+  ASSERT_NE(0, posix_memalign(&ptr, 16, SIZE_MAX));
+}
+
 TEST(malloc, memalign_realloc) {
   // Memalign and then realloc the pointer a couple of times.
   for (size_t alignment = 1; alignment <= 4096; alignment <<= 1) {
@@ -87,7 +138,6 @@
     for (size_t i = 0; i < 250; i++) {
       ASSERT_EQ(0x67, ptr[i]);
     }
-
     free(ptr);
   }
 }
@@ -105,7 +155,6 @@
   for (size_t i = 0; i < 100; i++) {
     ASSERT_EQ(67, ptr[i]);
   }
-
   free(ptr);
 }
 
@@ -122,7 +171,6 @@
   for (size_t i = 0; i < 100; i++) {
     ASSERT_EQ(67, ptr[i]);
   }
-
   free(ptr);
 }
 
@@ -161,9 +209,9 @@
   for (size_t i = 0; i < 150; i++) {
     ASSERT_EQ(0x23, ptr[i]);
   }
-
   free(ptr);
 }
+
 TEST(malloc, calloc_realloc_larger) {
   // Realloc to a larger size, calloc is used for the original allocation.
   char *ptr = (char *)calloc(1, 100);
@@ -176,7 +224,6 @@
   for (size_t i = 0; i < 100; i++) {
     ASSERT_EQ(0, ptr[i]);
   }
-
   free(ptr);
 }
 
@@ -192,7 +239,6 @@
   for (size_t i = 0; i < 100; i++) {
     ASSERT_EQ(0, ptr[i]);
   }
-
   free(ptr);
 }
 
@@ -230,21 +276,42 @@
   for (size_t i = 0; i < 150; i++) {
     ASSERT_EQ(0, ptr[i]);
   }
-
   free(ptr);
 }
 
-TEST(malloc, posix_memalign_non_power2) {
-  void* ptr;
-
-  ASSERT_EQ(EINVAL, posix_memalign(&ptr, 17, 1024));
+TEST(malloc, realloc_overflow) {
+  errno = 0;
+  ASSERT_EQ(NULL, realloc(NULL, SIZE_MAX));
+  ASSERT_EQ(ENOMEM, errno);
+  void* ptr = malloc(100);
+  ASSERT_TRUE(ptr != NULL);
+  errno = 0;
+  ASSERT_EQ(NULL, realloc(ptr, SIZE_MAX));
+  ASSERT_EQ(ENOMEM, errno);
+  free(ptr);
 }
 
-TEST(malloc, memalign_non_power2) {
-  void* ptr;
-  for (size_t align = 0; align <= 256; align++) {
-    ptr = memalign(align, 1024);
-    ASSERT_TRUE(ptr != NULL) << "Failed at align " << align;
-    free(ptr);
-  }
+TEST(malloc, pvalloc_std) {
+  size_t pagesize = sysconf(_SC_PAGESIZE);
+  void* ptr = pvalloc(100);
+  ASSERT_TRUE(ptr != NULL);
+  ASSERT_TRUE((reinterpret_cast<uintptr_t>(ptr) & (pagesize-1)) == 0);
+  ASSERT_LE(pagesize, malloc_usable_size(ptr));
+  free(ptr);
+}
+
+TEST(malloc, pvalloc_overflow) {
+  ASSERT_EQ(NULL, pvalloc(SIZE_MAX));
+}
+
+TEST(malloc, valloc_std) {
+  size_t pagesize = sysconf(_SC_PAGESIZE);
+  void* ptr = pvalloc(100);
+  ASSERT_TRUE(ptr != NULL);
+  ASSERT_TRUE((reinterpret_cast<uintptr_t>(ptr) & (pagesize-1)) == 0);
+  free(ptr);
+}
+
+TEST(malloc, valloc_overflow) {
+  ASSERT_EQ(NULL, valloc(SIZE_MAX));
 }
diff --git a/tests/stdio_test.cpp b/tests/stdio_test.cpp
index e291f52..18dae9c 100644
--- a/tests/stdio_test.cpp
+++ b/tests/stdio_test.cpp
@@ -532,10 +532,6 @@
 #endif
 
   errno = 0;
-  EXPECT_EQ(EOF, putw(1234, fp));
-  EXPECT_EQ(EBADF, errno);
-
-  errno = 0;
   EXPECT_EQ(0U, fwrite("hello", 1, 2, fp));
   EXPECT_EQ(EBADF, errno);
 
diff --git a/tests/stdlib_test.cpp b/tests/stdlib_test.cpp
index 978a60f..7c86d76 100644
--- a/tests/stdlib_test.cpp
+++ b/tests/stdlib_test.cpp
@@ -35,27 +35,34 @@
   EXPECT_DOUBLE_EQ(0.061637783047395089, drand48());
 }
 
-TEST(stdlib, lrand48_random_rand) {
+TEST(stdlib, lrand48) {
   srand48(0x01020304);
   EXPECT_EQ(1409163720, lrand48());
   EXPECT_EQ(397769746, lrand48());
   EXPECT_EQ(902267124, lrand48());
   EXPECT_EQ(132366131, lrand48());
+}
 
-#if defined(__BIONIC__)
-  // On bionic, random(3) is equivalent to lrand48...
+TEST(stdlib, random) {
   srandom(0x01020304);
-  EXPECT_EQ(1409163720, random());
-  EXPECT_EQ(397769746, random());
-  EXPECT_EQ(902267124, random());
-  EXPECT_EQ(132366131, random());
+  EXPECT_EQ(55436735, random());
+  EXPECT_EQ(1399865117, random());
+  EXPECT_EQ(2032643283, random());
+  EXPECT_EQ(571329216, random());
+}
 
-  // ...and rand(3) is the bottom 32 bits.
+TEST(stdlib, rand) {
   srand(0x01020304);
-  EXPECT_EQ(static_cast<int>(1409163720), rand());
-  EXPECT_EQ(static_cast<int>(397769746), rand());
-  EXPECT_EQ(static_cast<int>(902267124), rand());
-  EXPECT_EQ(static_cast<int>(132366131), rand());
+#if defined(__BIONIC__)
+  EXPECT_EQ(1675538669, rand());
+  EXPECT_EQ(1678228258, rand());
+  EXPECT_EQ(1352350131, rand());
+  EXPECT_EQ(824068976, rand());
+#else
+  EXPECT_EQ(55436735, rand());
+  EXPECT_EQ(1399865117, rand());
+  EXPECT_EQ(2032643283, rand());
+  EXPECT_EQ(571329216, rand());
 #endif
 }
 
diff --git a/tests/sys_mman_test.cpp b/tests/sys_mman_test.cpp
index 6ac279f..75ccfa3 100644
--- a/tests/sys_mman_test.cpp
+++ b/tests/sys_mman_test.cpp
@@ -17,14 +17,158 @@
 #include <gtest/gtest.h>
 
 #include <sys/mman.h>
+#include <sys/types.h>
 #include <unistd.h>
 
-TEST(sys_mman, mmap_negative) {
-  off_t off = -sysconf(_SC_PAGE_SIZE); // Aligned but negative.
-  ASSERT_EQ(MAP_FAILED, mmap(NULL, 4096, PROT_READ|PROT_WRITE, MAP_ANON|MAP_PRIVATE, -1, off));
+#include "TemporaryFile.h"
+
+TEST(sys_mman, mmap_std) {
+  void* map = mmap(NULL, 4096, PROT_READ | PROT_WRITE, MAP_ANON | MAP_PRIVATE, -1, 0);
+  ASSERT_NE(MAP_FAILED, map);
+  ASSERT_EQ(0, munmap(map, 4096));
 }
 
-TEST(sys_mman, mmap64_negative) {
-  off64_t off64 = -sysconf(_SC_PAGE_SIZE); // Aligned but negative.
-  ASSERT_EQ(MAP_FAILED, mmap64(NULL, 4096, PROT_READ|PROT_WRITE, MAP_ANON|MAP_PRIVATE, -1, off64));
+TEST(sys_mman, mmap64_std) {
+  void* map = mmap64(NULL, 4096, PROT_READ | PROT_WRITE, MAP_ANON | MAP_PRIVATE, -1, 0);
+  ASSERT_NE(MAP_FAILED, map);
+  ASSERT_EQ(0, munmap(map, 4096));
+}
+
+TEST(sys_mman, mmap_file_bad_offset) {
+  TemporaryFile tf;
+
+  void* map = mmap(NULL, 100, PROT_READ, MAP_SHARED, tf.fd, 1);
+  ASSERT_EQ(MAP_FAILED, map);
+}
+
+TEST(sys_mman, mmap64_file_bad_offset) {
+  TemporaryFile tf;
+
+  void* map = mmap64(NULL, 100, PROT_READ, MAP_SHARED, tf.fd, 1);
+  ASSERT_EQ(MAP_FAILED, map);
+}
+
+#define STR_SSIZE(str) static_cast<ssize_t>(sizeof(str))
+
+#define STRING_MSG  "012345678\nabcdefgh\n"
+#define INITIAL_MSG "000000000\n00000000\n"
+
+TEST(sys_mman, mmap_file_read) {
+  TemporaryFile tf;
+
+  ASSERT_EQ(STR_SSIZE(STRING_MSG), write(tf.fd, STRING_MSG, sizeof(STRING_MSG)));
+
+  void* map = mmap(NULL, sizeof(STRING_MSG), PROT_READ, MAP_SHARED, tf.fd, 0);
+  ASSERT_NE(MAP_FAILED, map);
+
+  char* data = reinterpret_cast<char*>(map);
+  ASSERT_STREQ(STRING_MSG, data);
+
+  ASSERT_EQ(0, munmap(map, sizeof(STRING_MSG)));
+}
+
+TEST(sys_mman, mmap_file_write) {
+  TemporaryFile tf;
+
+  ASSERT_EQ(STR_SSIZE(INITIAL_MSG), write(tf.fd, INITIAL_MSG, sizeof(INITIAL_MSG)));
+  lseek(tf.fd, 0, SEEK_SET);
+
+  void* map = mmap(NULL, sizeof(STRING_MSG), PROT_WRITE, MAP_SHARED, tf.fd, 0);
+  ASSERT_NE(MAP_FAILED, map);
+  close(tf.fd);
+
+  memcpy(map, STRING_MSG, sizeof(STRING_MSG));
+
+  ASSERT_EQ(0, munmap(map, sizeof(STRING_MSG)));
+
+  tf.reopen();
+  char buf[sizeof(STRING_MSG)];
+  memset(buf, 0, sizeof(STRING_MSG));
+  ASSERT_EQ(STR_SSIZE(STRING_MSG), read(tf.fd, buf, sizeof(STRING_MSG)));
+
+  ASSERT_STREQ(STRING_MSG, buf);
+}
+
+#define PAGE0_MSG "00PAGE00"
+#define PAGE1_MSG "111PAGE111"
+#define PAGE2_MSG "2222PAGE2222"
+#define END_MSG "E"
+
+TEST(sys_mman, mmap_file_read_at_offset) {
+  TemporaryFile tf;
+  size_t pagesize = sysconf(_SC_PAGESIZE);
+
+  // Create the file with three pages worth of data.
+  ASSERT_EQ(STR_SSIZE(PAGE0_MSG), write(tf.fd, PAGE0_MSG, sizeof(PAGE0_MSG)));
+  ASSERT_NE(-1, lseek(tf.fd, pagesize, SEEK_SET));
+  ASSERT_EQ(STR_SSIZE(PAGE1_MSG), write(tf.fd, PAGE1_MSG, sizeof(PAGE1_MSG)));
+  ASSERT_NE(-1, lseek(tf.fd, 2 * pagesize, SEEK_SET));
+  ASSERT_EQ(STR_SSIZE(PAGE2_MSG), write(tf.fd, PAGE2_MSG, sizeof(PAGE2_MSG)));
+  ASSERT_NE(-1, lseek(tf.fd, 3 * pagesize - sizeof(END_MSG), SEEK_SET));
+  ASSERT_EQ(STR_SSIZE(END_MSG), write(tf.fd, END_MSG, sizeof(END_MSG)));
+
+  ASSERT_NE(-1, lseek(tf.fd, 0, SEEK_SET));
+
+  void* map = mmap(NULL, pagesize, PROT_READ, MAP_SHARED, tf.fd, pagesize);
+  ASSERT_NE(MAP_FAILED, map);
+
+  char* data = reinterpret_cast<char*>(map);
+  ASSERT_STREQ(PAGE1_MSG, data);
+
+  ASSERT_EQ(0, munmap(map, pagesize));
+
+  map = mmap(NULL, pagesize, PROT_READ, MAP_SHARED, tf.fd, 2 * pagesize);
+  ASSERT_NE(MAP_FAILED, map);
+
+  data = reinterpret_cast<char*>(map);
+  ASSERT_STREQ(PAGE2_MSG, data);
+  ASSERT_STREQ(END_MSG, data+pagesize-sizeof(END_MSG));
+
+  ASSERT_EQ(0, munmap(map, pagesize));
+}
+
+#define NEWPAGE1_MSG "1NEW1PAGE1"
+#define NEWPAGE2_MSG "22NEW22PAGE22"
+
+TEST(sys_mman, mmap_file_write_at_offset) {
+  TemporaryFile tf;
+  size_t pagesize = sysconf(_SC_PAGESIZE);
+
+  // Create the file with three pages worth of data.
+  ASSERT_EQ(STR_SSIZE(PAGE0_MSG), write(tf.fd, PAGE0_MSG, sizeof(PAGE0_MSG)));
+  ASSERT_NE(-1, lseek(tf.fd, pagesize, SEEK_SET));
+  ASSERT_EQ(STR_SSIZE(PAGE1_MSG), write(tf.fd, PAGE1_MSG, sizeof(PAGE1_MSG)));
+  ASSERT_NE(-1, lseek(tf.fd, 2 * pagesize, SEEK_SET));
+  ASSERT_EQ(STR_SSIZE(PAGE2_MSG), write(tf.fd, PAGE2_MSG, sizeof(PAGE2_MSG)));
+  ASSERT_NE(-1, lseek(tf.fd, 3 * pagesize - sizeof(END_MSG), SEEK_SET));
+  ASSERT_EQ(STR_SSIZE(END_MSG), write(tf.fd, END_MSG, sizeof(END_MSG)));
+
+  ASSERT_NE(-1, lseek(tf.fd, 0, SEEK_SET));
+
+  void* map = mmap(NULL, pagesize, PROT_WRITE, MAP_SHARED, tf.fd, pagesize);
+  ASSERT_NE(MAP_FAILED, map);
+  close(tf.fd);
+
+  memcpy(map, NEWPAGE1_MSG, sizeof(NEWPAGE1_MSG));
+  ASSERT_EQ(0, munmap(map, pagesize));
+
+  tf.reopen();
+  map = mmap(NULL, pagesize, PROT_WRITE, MAP_SHARED, tf.fd, 2 * pagesize);
+  ASSERT_NE(MAP_FAILED, map);
+  close(tf.fd);
+
+  memcpy(map, NEWPAGE2_MSG, sizeof(NEWPAGE2_MSG));
+  ASSERT_EQ(0, munmap(map, pagesize));
+
+  tf.reopen();
+  char buf[pagesize];
+  ASSERT_EQ(static_cast<ssize_t>(pagesize), read(tf.fd, buf, pagesize));
+  ASSERT_STREQ(PAGE0_MSG, buf);
+  ASSERT_NE(-1, lseek(tf.fd, pagesize, SEEK_SET));
+  ASSERT_EQ(static_cast<ssize_t>(pagesize), read(tf.fd, buf, pagesize));
+  ASSERT_STREQ(NEWPAGE1_MSG, buf);
+  ASSERT_NE(-1, lseek(tf.fd, 2 * pagesize, SEEK_SET));
+  ASSERT_EQ(static_cast<ssize_t>(pagesize), read(tf.fd, buf, pagesize));
+  ASSERT_STREQ(NEWPAGE2_MSG, buf);
+  ASSERT_STREQ(END_MSG, buf+pagesize-sizeof(END_MSG));
 }