Merge "add 64-bit bionic implementation for denver arch"
diff --git a/benchmarks/benchmark_main.cpp b/benchmarks/benchmark_main.cpp
index f8e85bb..d60670b 100644
--- a/benchmarks/benchmark_main.cpp
+++ b/benchmarks/benchmark_main.cpp
@@ -32,6 +32,7 @@
 typedef std::map<std::string, ::testing::Benchmark*> BenchmarkMap;
 typedef BenchmarkMap::iterator BenchmarkMapIt;
 static BenchmarkMap g_benchmarks;
+static int g_name_column_width = 20;
 
 static int Round(int n) {
   int base = 1;
@@ -164,7 +165,7 @@
     snprintf(full_name, sizeof(full_name), "%s", name_);
   }
 
-  printf("%-20s %10d %10" PRId64 "%s\n", full_name,
+  printf("%-*s %10d %10" PRId64 "%s\n", g_name_column_width, full_name,
          iterations, g_benchmark_total_time_ns/iterations, throughput);
   fflush(stdout);
 }
@@ -194,12 +195,17 @@
     exit(EXIT_FAILURE);
   }
 
+  for (BenchmarkMapIt it = g_benchmarks.begin(); it != g_benchmarks.end(); ++it) {
+    int name_width = static_cast<int>(strlen(it->second->Name()));
+    g_name_column_width = std::max(g_name_column_width, name_width);
+  }
+
   bool need_header = true;
   for (BenchmarkMapIt it = g_benchmarks.begin(); it != g_benchmarks.end(); ++it) {
     ::testing::Benchmark* b = it->second;
     if (b->ShouldRun(argc, argv)) {
       if (need_header) {
-        printf("%-20s %10s %10s\n", "", "iterations", "ns/op");
+        printf("%-*s %10s %10s\n", g_name_column_width, "", "iterations", "ns/op");
         fflush(stdout);
         need_header = false;
       }
diff --git a/libc/Android.mk b/libc/Android.mk
index cd5cb02..2747a3e 100644
--- a/libc/Android.mk
+++ b/libc/Android.mk
@@ -43,9 +43,7 @@
     bionic/err.c \
     bionic/ether_aton.c \
     bionic/ether_ntoa.c \
-    bionic/ftime.c \
     bionic/fts.c \
-    bionic/getdtablesize.c \
     bionic/gethostname.c \
     bionic/getpriority.c \
     bionic/getpt.c \
@@ -265,6 +263,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 \
@@ -272,8 +271,6 @@
     upstream-netbsd/lib/libc/gen/psignal.c \
     upstream-netbsd/lib/libc/gen/utime.c \
     upstream-netbsd/lib/libc/gen/utmp.c \
-    upstream-netbsd/lib/libc/isc/ev_streams.c \
-    upstream-netbsd/lib/libc/isc/ev_timers.c \
     upstream-netbsd/lib/libc/regex/regcomp.c \
     upstream-netbsd/lib/libc/regex/regerror.c \
     upstream-netbsd/lib/libc/regex/regexec.c \
@@ -290,6 +287,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 \
@@ -418,7 +417,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 \
@@ -503,7 +501,7 @@
 
 ifeq ($(MALLOC_IMPL),jemalloc)
   libc_common_cflags += -DUSE_JEMALLOC
-  libc_malloc_src := bionic/jemalloc.cpp
+  libc_malloc_src := bionic/jemalloc_wrapper.cpp
 else
   libc_common_cflags += -DUSE_DLMALLOC
   libc_malloc_src := bionic/dlmalloc.c
@@ -617,15 +615,21 @@
 
 include $(CLEAR_VARS)
 
-LOCAL_SRC_FILES := $(call all-c-files-under,dns)
+LOCAL_SRC_FILES := \
+    $(call all-c-files-under,dns) \
+    upstream-netbsd/lib/libc/isc/ev_streams.c \
+    upstream-netbsd/lib/libc/isc/ev_timers.c \
+
 LOCAL_CFLAGS := \
     $(libc_common_cflags) \
     -DANDROID_CHANGES \
     -DINET6 \
+    -fvisibility=hidden \
     -I$(LOCAL_PATH)/dns/include \
     -I$(LOCAL_PATH)/private \
     -I$(LOCAL_PATH)/upstream-netbsd/lib/libc/include \
-    -include upstream-netbsd/android/include/netbsd-compat.h \
+    -I$(LOCAL_PATH)/upstream-netbsd/android/include \
+    -include netbsd-compat.h \
 #    -Werror \
 
 LOCAL_CONLYFLAGS := $(libc_common_conlyflags)
diff --git a/libc/SYSCALLS.TXT b/libc/SYSCALLS.TXT
index 9389c9c..369b23c 100644
--- a/libc/SYSCALLS.TXT
+++ b/libc/SYSCALLS.TXT
@@ -275,10 +275,6 @@
 int __sched_getaffinity:sched_getaffinity(pid_t pid, size_t setsize, cpu_set_t* set)  all
 int __getcpu:getcpu(unsigned*, unsigned*, void*) all
 
-# io priorities
-int ioprio_set(int which, int who, int ioprio) all
-int ioprio_get(int which, int who) all
-
 # other
 int     uname(struct utsname*)  all
 mode_t  umask(mode_t)  all
diff --git a/libc/arch-arm/arm.mk b/libc/arch-arm/arm.mk
index 7c423ab..38301bc 100644
--- a/libc/arch-arm/arm.mk
+++ b/libc/arch-arm/arm.mk
@@ -5,13 +5,13 @@
     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 := \
     bionic/mmap.cpp
 
 libc_common_src_files_arm += \
-    bionic/index.cpp \
     bionic/memchr.c \
     bionic/memrchr.c \
     bionic/strchr.cpp \
@@ -56,7 +56,6 @@
     arch-arm/bionic/_exit_with_stack_teardown.S \
     arch-arm/bionic/__get_sp.S \
     arch-arm/bionic/libgcc_compat.c \
-    arch-arm/bionic/memcmp16.S \
     arch-arm/bionic/memcmp.S \
     arch-arm/bionic/_setjmp.S \
     arch-arm/bionic/setjmp.S \
diff --git a/libc/arch-arm/bionic/memcmp16.S b/libc/arch-arm/bionic/memcmp16.S
deleted file mode 100644
index 3f2f2f1..0000000
--- a/libc/arch-arm/bionic/memcmp16.S
+++ /dev/null
@@ -1,234 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *  * Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- *  * 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.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS 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
- * COPYRIGHT OWNER 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 <machine/cpu-features.h>
-#include <private/bionic_asm.h>
-
-/*
- * Optimized memcmp16() for ARM9.
- * This would not be optimal on XScale or ARM11, where more prefetching
- * and use of pld will be needed.
- * The 2 major optimzations here are
- * (1) The main loop compares 16 bytes at a time
- * (2) The loads are scheduled in a way they won't stall
- */
-
-ENTRY(__memcmp16)
-        pld         [r0, #0]
-        pld         [r1, #0]
-
-        /* take of the case where length is nul or the buffers are the same */
-        cmp         r0, r1
-        cmpne       r2, #0
-        moveq       r0, #0
-        bxeq        lr
-
-        /* since r0 hold the result, move the first source
-         * pointer somewhere else
-         */
-
-        mov         r3, r0
-
-         /* make sure we have at least 12 words, this simplify things below
-          * and avoid some overhead for small blocks
-          */
-
-        cmp         r2, #12
-        bpl         0f
-
-        /* small blocks (less then 12 words) */
-        pld         [r0, #32]
-        pld         [r1, #32]
-
-1:      ldrh        r0, [r3], #2
-        ldrh        ip, [r1], #2
-        subs        r0, r0, ip
-        bxne        lr
-        subs        r2, r2, #1
-        bne         1b
-        bx          lr
-
-
-        /* save registers */
-0:      stmfd       sp!, {r4, lr}
-        .cfi_def_cfa_offset 8
-        .cfi_rel_offset r4, 0
-        .cfi_rel_offset lr, 4
-
-        /* align first pointer to word boundary */
-        tst         r3, #2
-        beq         0f
-
-        ldrh        r0, [r3], #2
-        ldrh        ip, [r1], #2
-        sub         r2, r2, #1
-        subs        r0, r0, ip
-        /* restore registers and return */
-        ldmnefd     sp!, {r4, lr}
-        bxne        lr
-
-
-0:      /* here the first pointer is aligned, and we have at least 3 words
-         * to process.
-         */
-
-        /* see if the pointers are congruent */
-        eor         r0, r3, r1
-        ands        r0, r0, #2
-        bne         5f
-
-        /* congruent case, 16 half-words per iteration
-         * We need to make sure there are at least 16+2 words left
-         * because we effectively read ahead one long word, and we could
-         * read past the buffer (and segfault) if we're not careful.
-         */
-
-        ldr         ip, [r1]
-        subs        r2, r2, #(16 + 2)
-        bmi         1f
-
-0:
-        pld         [r3, #64]
-        pld         [r1, #64]
-        ldr         r0, [r3], #4
-        ldr         lr, [r1, #4]!
-        eors        r0, r0, ip
-        ldreq       r0, [r3], #4
-        ldreq       ip, [r1, #4]!
-        eoreqs      r0, r0, lr
-        ldreq       r0, [r3], #4
-        ldreq       lr, [r1, #4]!
-        eoreqs      r0, r0, ip
-        ldreq       r0, [r3], #4
-        ldreq       ip, [r1, #4]!
-        eoreqs      r0, r0, lr
-        ldreq       r0, [r3], #4
-        ldreq       lr, [r1, #4]!
-        eoreqs      r0, r0, ip
-        ldreq       r0, [r3], #4
-        ldreq       ip, [r1, #4]!
-        eoreqs      r0, r0, lr
-        ldreq       r0, [r3], #4
-        ldreq       lr, [r1, #4]!
-        eoreqs      r0, r0, ip
-        ldreq       r0, [r3], #4
-        ldreq       ip, [r1, #4]!
-        eoreqs      r0, r0, lr
-        bne         2f
-        subs        r2, r2, #16
-        bhs         0b
-
-        /* do we have at least 2 words left? */
-1:      adds        r2, r2, #(16 - 2 + 2)
-        bmi         4f
-
-        /* finish off 2 words at a time */
-3:      ldr         r0, [r3], #4
-        ldr         ip, [r1], #4
-        eors        r0, r0, ip
-        bne         2f
-        subs        r2, r2, #2
-        bhs         3b
-
-        /* are we done? */
-4:      adds        r2, r2, #2
-        bne         8f
-        /* restore registers and return */
-        mov         r0, #0
-        ldmfd       sp!, {r4, lr}
-        bx          lr
-
-2:      /* the last 2 words are different, restart them */
-        ldrh        r0, [r3, #-4]
-        ldrh        ip, [r1, #-4]
-        subs        r0, r0, ip
-        ldreqh      r0, [r3, #-2]
-        ldreqh      ip, [r1, #-2]
-        subeqs      r0, r0, ip
-        /* restore registers and return */
-        ldmfd       sp!, {r4, lr}
-        bx          lr
-
-        /* process the last few words */
-8:      ldrh        r0, [r3], #2
-        ldrh        ip, [r1], #2
-        subs        r0, r0, ip
-        bne         9f
-        subs        r2, r2, #1
-        bne         8b
-
-9:      /* restore registers and return */
-        ldmfd       sp!, {r4, lr}
-        bx          lr
-
-
-5:      /*************** non-congruent case ***************/
-
-        /* align the unaligned pointer */
-        bic         r1, r1, #3
-        ldr         lr, [r1], #4
-        sub         r2, r2, #8
-
-6:
-        pld         [r3, #64]
-        pld         [r1, #64]
-        mov         ip, lr, lsr #16
-        ldr         lr, [r1], #4
-        ldr         r0, [r3], #4
-        orr         ip, ip, lr, lsl #16
-        eors        r0, r0, ip
-        moveq       ip, lr, lsr #16
-        ldreq       lr, [r1], #4
-        ldreq       r0, [r3], #4
-        orreq       ip, ip, lr, lsl #16
-        eoreqs      r0, r0, ip
-        moveq       ip, lr, lsr #16
-        ldreq       lr, [r1], #4
-        ldreq       r0, [r3], #4
-        orreq       ip, ip, lr, lsl #16
-        eoreqs      r0, r0, ip
-        moveq       ip, lr, lsr #16
-        ldreq       lr, [r1], #4
-        ldreq       r0, [r3], #4
-        orreq       ip, ip, lr, lsl #16
-        eoreqs      r0, r0, ip
-        bne         7f
-        subs        r2, r2, #8
-        bhs         6b
-        sub         r1, r1, #2
-        /* are we done? */
-        adds        r2, r2, #8
-        moveq       r0, #0
-        beq         9b
-        /* finish off the remaining bytes */
-        b           8b
-
-7:      /* fix up the 2 pointers and fallthrough... */
-        sub         r1, r1, #2
-        b           2b
-END(__memcmp16)
diff --git a/libc/arch-arm/syscalls/ioprio_get.S b/libc/arch-arm/syscalls/ioprio_get.S
deleted file mode 100644
index 19e04ed..0000000
--- a/libc/arch-arm/syscalls/ioprio_get.S
+++ /dev/null
@@ -1,14 +0,0 @@
-/* Generated by gensyscalls.py. Do not edit. */
-
-#include <private/bionic_asm.h>
-
-ENTRY(ioprio_get)
-    mov     ip, r7
-    ldr     r7, =__NR_ioprio_get
-    swi     #0
-    mov     r7, ip
-    cmn     r0, #(MAX_ERRNO + 1)
-    bxls    lr
-    neg     r0, r0
-    b       __set_errno
-END(ioprio_get)
diff --git a/libc/arch-arm/syscalls/ioprio_set.S b/libc/arch-arm/syscalls/ioprio_set.S
deleted file mode 100644
index 9b94efb..0000000
--- a/libc/arch-arm/syscalls/ioprio_set.S
+++ /dev/null
@@ -1,14 +0,0 @@
-/* Generated by gensyscalls.py. Do not edit. */
-
-#include <private/bionic_asm.h>
-
-ENTRY(ioprio_set)
-    mov     ip, r7
-    ldr     r7, =__NR_ioprio_set
-    swi     #0
-    mov     r7, ip
-    cmn     r0, #(MAX_ERRNO + 1)
-    bxls    lr
-    neg     r0, r0
-    b       __set_errno
-END(ioprio_set)
diff --git a/libc/arch-arm64/arm64.mk b/libc/arch-arm64/arm64.mk
index 8920f5f..e44ee31 100644
--- a/libc/arch-arm64/arm64.mk
+++ b/libc/arch-arm64/arm64.mk
@@ -2,7 +2,6 @@
 
 libc_common_src_files_arm64 := \
     bionic/memchr.c \
-    bionic/__memcmp16.cpp \
     bionic/memrchr.c \
     bionic/strchr.cpp \
     bionic/strrchr.cpp \
diff --git a/libc/arch-arm64/syscalls/ioprio_get.S b/libc/arch-arm64/syscalls/ioprio_get.S
deleted file mode 100644
index 7e394c6..0000000
--- a/libc/arch-arm64/syscalls/ioprio_get.S
+++ /dev/null
@@ -1,14 +0,0 @@
-/* Generated by gensyscalls.py. Do not edit. */
-
-#include <private/bionic_asm.h>
-
-ENTRY(ioprio_get)
-    mov     x8, __NR_ioprio_get
-    svc     #0
-
-    cmn     x0, #(MAX_ERRNO + 1)
-    cneg    x0, x0, hi
-    b.hi    __set_errno
-
-    ret
-END(ioprio_get)
diff --git a/libc/arch-arm64/syscalls/ioprio_set.S b/libc/arch-arm64/syscalls/ioprio_set.S
deleted file mode 100644
index ca43ed6..0000000
--- a/libc/arch-arm64/syscalls/ioprio_set.S
+++ /dev/null
@@ -1,14 +0,0 @@
-/* Generated by gensyscalls.py. Do not edit. */
-
-#include <private/bionic_asm.h>
-
-ENTRY(ioprio_set)
-    mov     x8, __NR_ioprio_set
-    svc     #0
-
-    cmn     x0, #(MAX_ERRNO + 1)
-    cneg    x0, x0, hi
-    b.hi    __set_errno
-
-    ret
-END(ioprio_set)
diff --git a/libc/arch-mips/bionic/memcmp16.S b/libc/arch-mips/bionic/memcmp16.S
deleted file mode 100644
index f9d14a9..0000000
--- a/libc/arch-mips/bionic/memcmp16.S
+++ /dev/null
@@ -1,50 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *  * Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- *  * 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.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS 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
- * COPYRIGHT OWNER 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 <private/bionic_asm.h>
-
-// u4 __memcmp16(const u2*, const u2*, size_t);
-ENTRY(__memcmp16)
-	li	t0,0
-	li	t1,0
-	beqz	a2,done		/* 0 length string */ 
-	beq	a0,a1,done		/* strings are identical */
-
-	/* Unoptimised... */
-1:	lhu	t0,0(a0)
-	lhu	t1,0(a1)
-	addu	a1,2
-	bne	t0,t1,done
-	addu	a0,2
-	subu	a2,1
-	bnez	a2,1b
-
-done:
-	subu	v0,t0,t1
-	j	ra
-END(__memcmp16)
diff --git a/libc/arch-mips/mips.mk b/libc/arch-mips/mips.mk
index 64b0fb2..fe5e24d 100644
--- a/libc/arch-mips/mips.mk
+++ b/libc/arch-mips/mips.mk
@@ -5,13 +5,13 @@
     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 += \
      bionic/mmap.cpp
 
 libc_common_src_files_mips += \
-    bionic/index.cpp \
     bionic/memchr.c \
     bionic/memcmp.c \
     bionic/memmove.c \
@@ -60,7 +60,6 @@
     arch-mips/bionic/cacheflush.cpp \
     arch-mips/bionic/_exit_with_stack_teardown.S \
     arch-mips/bionic/__get_sp.S \
-    arch-mips/bionic/memcmp16.S \
     arch-mips/bionic/_setjmp.S \
     arch-mips/bionic/setjmp.S \
     arch-mips/bionic/sigsetjmp.S \
diff --git a/libc/arch-mips/syscalls/ioprio_get.S b/libc/arch-mips/syscalls/ioprio_get.S
deleted file mode 100644
index fbc8b17..0000000
--- a/libc/arch-mips/syscalls/ioprio_get.S
+++ /dev/null
@@ -1,19 +0,0 @@
-/* Generated by gensyscalls.py. Do not edit. */
-
-#include <private/bionic_asm.h>
-
-ENTRY(ioprio_get)
-    .set noreorder
-    .cpload t9
-    li v0, __NR_ioprio_get
-    syscall
-    bnez a3, 1f
-    move a0, v0
-    j ra
-    nop
-1:
-    la t9,__set_errno
-    j t9
-    nop
-    .set reorder
-END(ioprio_get)
diff --git a/libc/arch-mips/syscalls/ioprio_set.S b/libc/arch-mips/syscalls/ioprio_set.S
deleted file mode 100644
index d0320ed..0000000
--- a/libc/arch-mips/syscalls/ioprio_set.S
+++ /dev/null
@@ -1,19 +0,0 @@
-/* Generated by gensyscalls.py. Do not edit. */
-
-#include <private/bionic_asm.h>
-
-ENTRY(ioprio_set)
-    .set noreorder
-    .cpload t9
-    li v0, __NR_ioprio_set
-    syscall
-    bnez a3, 1f
-    move a0, v0
-    j ra
-    nop
-1:
-    la t9,__set_errno
-    j t9
-    nop
-    .set reorder
-END(ioprio_set)
diff --git a/libc/arch-mips64/bionic/memcmp16.S b/libc/arch-mips64/bionic/memcmp16.S
deleted file mode 100644
index 1c58c1b..0000000
--- a/libc/arch-mips64/bionic/memcmp16.S
+++ /dev/null
@@ -1,53 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *  * Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- *  * 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.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS 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
- * COPYRIGHT OWNER 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.
- */
-	.text
-
-#include <private/bionic_asm.h>
-
-/*
- * u4 __memcmp16(const u2* s0, const u2* s1, size_t count);
- */
-LEAF(__memcmp16,0)
-	move	t0,$0
-	move	t1,$0
-	beqz	a2,.L_done		/* 0 length string */
-	beq	a0,a1,.L_done		/* strings are identical */
-
-	/* Unoptimised... */
-1:	lhu	t0,0(a0)
-	lhu	t1,0(a1)
-	PTR_ADDU a1,2
-	bne	t0,t1,.L_done
-	PTR_ADDU a0,2
-	SUBU	a2,1
-	bnez	a2,1b
-
-.L_done:
-	SUBU	v0,t0,t1
-	j	ra
-	END(__memcmp16)
diff --git a/libc/arch-mips64/mips64.mk b/libc/arch-mips64/mips64.mk
index fce957b..6f7a928 100644
--- a/libc/arch-mips64/mips64.mk
+++ b/libc/arch-mips64/mips64.mk
@@ -42,7 +42,6 @@
     arch-mips64/bionic/__bionic_clone.S \
     arch-mips64/bionic/_exit_with_stack_teardown.S \
     arch-mips64/bionic/__get_sp.S \
-    arch-mips64/bionic/memcmp16.S \
     arch-mips64/bionic/_setjmp.S \
     arch-mips64/bionic/setjmp.S \
     arch-mips64/bionic/sigsetjmp.S \
diff --git a/libc/arch-mips64/syscalls/ioprio_get.S b/libc/arch-mips64/syscalls/ioprio_get.S
deleted file mode 100644
index 711890c..0000000
--- a/libc/arch-mips64/syscalls/ioprio_get.S
+++ /dev/null
@@ -1,25 +0,0 @@
-/* Generated by gensyscalls.py. Do not edit. */
-
-#include <private/bionic_asm.h>
-
-ENTRY(ioprio_get)
-    .set push
-    .set noreorder
-    li v0, __NR_ioprio_get
-    syscall
-    bnez a3, 1f
-    move a0, v0
-    j ra
-    nop
-1:
-    move t0, ra
-    bal     2f
-    nop
-2:
-    .cpsetup ra, t1, 2b
-    LA t9,__set_errno
-    .cpreturn
-    j t9
-    move ra, t0
-    .set pop
-END(ioprio_get)
diff --git a/libc/arch-mips64/syscalls/ioprio_set.S b/libc/arch-mips64/syscalls/ioprio_set.S
deleted file mode 100644
index 738403a..0000000
--- a/libc/arch-mips64/syscalls/ioprio_set.S
+++ /dev/null
@@ -1,25 +0,0 @@
-/* Generated by gensyscalls.py. Do not edit. */
-
-#include <private/bionic_asm.h>
-
-ENTRY(ioprio_set)
-    .set push
-    .set noreorder
-    li v0, __NR_ioprio_set
-    syscall
-    bnez a3, 1f
-    move a0, v0
-    j ra
-    nop
-1:
-    move t0, ra
-    bal     2f
-    nop
-2:
-    .cpsetup ra, t1, 2b
-    LA t9,__set_errno
-    .cpreturn
-    j t9
-    move ra, t0
-    .set pop
-END(ioprio_set)
diff --git a/libc/arch-x86/atom/atom.mk b/libc/arch-x86/atom/atom.mk
index bf408b4..3f28fb2 100644
--- a/libc/arch-x86/atom/atom.mk
+++ b/libc/arch-x86/atom/atom.mk
@@ -1,6 +1,5 @@
 libc_bionic_src_files_x86 += \
     arch-x86/atom/string/sse2-bzero-atom.S \
-    arch-x86/atom/string/sse2-index-atom.S \
     arch-x86/atom/string/sse2-memchr-atom.S \
     arch-x86/atom/string/sse2-memrchr-atom.S \
     arch-x86/atom/string/sse2-memset-atom.S \
@@ -14,7 +13,6 @@
     arch-x86/atom/string/sse2-wcscmp-atom.S \
     arch-x86/atom/string/ssse3-bcopy-atom.S \
     arch-x86/atom/string/ssse3-memcmp-atom.S \
-    arch-x86/atom/string/ssse3-memcmp16-atom.S \
     arch-x86/atom/string/ssse3-memcpy-atom.S \
     arch-x86/atom/string/ssse3-memmove-atom.S \
     arch-x86/atom/string/ssse3-strcat-atom.S \
diff --git a/libc/arch-x86/atom/string/sse2-index-atom.S b/libc/arch-x86/atom/string/sse2-index-atom.S
deleted file mode 100644
index d51e1d4..0000000
--- a/libc/arch-x86/atom/string/sse2-index-atom.S
+++ /dev/null
@@ -1,32 +0,0 @@
-/*
-Copyright (c) 2011, Intel Corporation
-All rights reserved.
-
-Redistribution and use in source and binary forms, with or without
-modification, are permitted provided that the following conditions are met:
-
-    * Redistributions of source code must retain the above copyright notice,
-    * this list of conditions and the following disclaimer.
-
-    * 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.
-
-    * Neither the name of Intel Corporation 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 COPYRIGHT HOLDERS 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 COPYRIGHT OWNER 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.
-*/
-
-#define strchr  index
-#include "sse2-strchr-atom.S"
diff --git a/libc/arch-x86/atom/string/ssse3-memcmp16-atom.S b/libc/arch-x86/atom/string/ssse3-memcmp16-atom.S
deleted file mode 100644
index 1be8f3d..0000000
--- a/libc/arch-x86/atom/string/ssse3-memcmp16-atom.S
+++ /dev/null
@@ -1,37 +0,0 @@
-/*
-Copyright (c) 2013, Intel Corporation
-All rights reserved.
-
-Redistribution and use in source and binary forms, with or without
-modification, are permitted provided that the following conditions are met:
-
-    * Redistributions of source code must retain the above copyright notice,
-    * this list of conditions and the following disclaimer.
-
-    * 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.
-
-    * Neither the name of Intel Corporation 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 COPYRIGHT HOLDERS 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 COPYRIGHT OWNER 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.
-*/
-
-#define MEMCMP  __memcmp16
-
-/* int __memcmp16(const unsigned short *ptr1, const unsigned short *ptr2, size_t n); */
-
-#define USE_UTF16
-#define USE_AS_MEMCMP16 1
-#include "ssse3-memcmp-atom.S"
diff --git a/libc/arch-x86/generic/generic.mk b/libc/arch-x86/generic/generic.mk
index c8b40ee..4aee5dc 100644
--- a/libc/arch-x86/generic/generic.mk
+++ b/libc/arch-x86/generic/generic.mk
@@ -1,5 +1,4 @@
 libc_bionic_src_files_x86 += \
-    arch-x86/atom/string/sse2-index-atom.S \
     arch-x86/atom/string/sse2-memchr-atom.S \
     arch-x86/atom/string/sse2-memrchr-atom.S \
     arch-x86/atom/string/sse2-strchr-atom.S \
@@ -28,7 +27,6 @@
     arch-x86/atom/string/ssse3-strcmp-atom.S \
     arch-x86/atom/string/ssse3-strncmp-atom.S \
     arch-x86/atom/string/ssse3-strcat-atom.S \
-    arch-x86/atom/string/ssse3-memcmp16-atom.S \
     arch-x86/atom/string/ssse3-wcscat-atom.S \
     arch-x86/atom/string/ssse3-wcscpy-atom.S
 else
@@ -36,7 +34,6 @@
     arch-x86/generic/string/strcmp.S \
     arch-x86/generic/string/strncmp.S \
     arch-x86/generic/string/strcat.S \
-    bionic/__memcmp16.cpp \
     upstream-freebsd/lib/libc/string/wcscpy.c \
     upstream-freebsd/lib/libc/string/wcscat.c \
     upstream-openbsd/lib/libc/string/strlcat.c \
diff --git a/libc/arch-x86/silvermont/silvermont.mk b/libc/arch-x86/silvermont/silvermont.mk
index b951ad5..176bee3 100644
--- a/libc/arch-x86/silvermont/silvermont.mk
+++ b/libc/arch-x86/silvermont/silvermont.mk
@@ -17,7 +17,6 @@
     arch-x86/atom/string/sse2-memrchr-atom.S \
     arch-x86/atom/string/sse2-strchr-atom.S \
     arch-x86/atom/string/sse2-strrchr-atom.S \
-    arch-x86/atom/string/sse2-index-atom.S \
     arch-x86/atom/string/sse2-strnlen-atom.S \
     arch-x86/atom/string/sse2-wcschr-atom.S \
     arch-x86/atom/string/sse2-wcsrchr-atom.S \
@@ -29,6 +28,5 @@
     arch-x86/atom/string/ssse3-strcmp-atom.S \
     arch-x86/atom/string/ssse3-strncmp-atom.S \
     arch-x86/atom/string/ssse3-strcat-atom.S \
-    arch-x86/atom/string/ssse3-memcmp16-atom.S \
     arch-x86/atom/string/ssse3-wcscat-atom.S \
     arch-x86/atom/string/ssse3-wcscpy-atom.S
diff --git a/libc/arch-x86/syscalls/ioprio_get.S b/libc/arch-x86/syscalls/ioprio_get.S
deleted file mode 100644
index 491c2f3..0000000
--- a/libc/arch-x86/syscalls/ioprio_get.S
+++ /dev/null
@@ -1,26 +0,0 @@
-/* Generated by gensyscalls.py. Do not edit. */
-
-#include <private/bionic_asm.h>
-
-ENTRY(ioprio_get)
-    pushl   %ebx
-    .cfi_def_cfa_offset 8
-    .cfi_rel_offset ebx, 0
-    pushl   %ecx
-    .cfi_adjust_cfa_offset 4
-    .cfi_rel_offset ecx, 0
-    mov     12(%esp), %ebx
-    mov     16(%esp), %ecx
-    movl    $__NR_ioprio_get, %eax
-    int     $0x80
-    cmpl    $-MAX_ERRNO, %eax
-    jb      1f
-    negl    %eax
-    pushl   %eax
-    call    __set_errno
-    addl    $4, %esp
-1:
-    popl    %ecx
-    popl    %ebx
-    ret
-END(ioprio_get)
diff --git a/libc/arch-x86/syscalls/ioprio_set.S b/libc/arch-x86/syscalls/ioprio_set.S
deleted file mode 100644
index e80602c..0000000
--- a/libc/arch-x86/syscalls/ioprio_set.S
+++ /dev/null
@@ -1,31 +0,0 @@
-/* Generated by gensyscalls.py. Do not edit. */
-
-#include <private/bionic_asm.h>
-
-ENTRY(ioprio_set)
-    pushl   %ebx
-    .cfi_def_cfa_offset 8
-    .cfi_rel_offset ebx, 0
-    pushl   %ecx
-    .cfi_adjust_cfa_offset 4
-    .cfi_rel_offset ecx, 0
-    pushl   %edx
-    .cfi_adjust_cfa_offset 4
-    .cfi_rel_offset edx, 0
-    mov     16(%esp), %ebx
-    mov     20(%esp), %ecx
-    mov     24(%esp), %edx
-    movl    $__NR_ioprio_set, %eax
-    int     $0x80
-    cmpl    $-MAX_ERRNO, %eax
-    jb      1f
-    negl    %eax
-    pushl   %eax
-    call    __set_errno
-    addl    $4, %esp
-1:
-    popl    %edx
-    popl    %ecx
-    popl    %ebx
-    ret
-END(ioprio_set)
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/arch-x86_64/syscalls/ioprio_get.S b/libc/arch-x86_64/syscalls/ioprio_get.S
deleted file mode 100644
index 729a288..0000000
--- a/libc/arch-x86_64/syscalls/ioprio_get.S
+++ /dev/null
@@ -1,15 +0,0 @@
-/* Generated by gensyscalls.py. Do not edit. */
-
-#include <private/bionic_asm.h>
-
-ENTRY(ioprio_get)
-    movl    $__NR_ioprio_get, %eax
-    syscall
-    cmpq    $-MAX_ERRNO, %rax
-    jb      1f
-    negl    %eax
-    movl    %eax, %edi
-    call    __set_errno
-1:
-    ret
-END(ioprio_get)
diff --git a/libc/arch-x86_64/syscalls/ioprio_set.S b/libc/arch-x86_64/syscalls/ioprio_set.S
deleted file mode 100644
index 477fe61..0000000
--- a/libc/arch-x86_64/syscalls/ioprio_set.S
+++ /dev/null
@@ -1,15 +0,0 @@
-/* Generated by gensyscalls.py. Do not edit. */
-
-#include <private/bionic_asm.h>
-
-ENTRY(ioprio_set)
-    movl    $__NR_ioprio_set, %eax
-    syscall
-    cmpq    $-MAX_ERRNO, %rax
-    jb      1f
-    negl    %eax
-    movl    %eax, %edi
-    call    __set_errno
-1:
-    ret
-END(ioprio_set)
diff --git a/libc/arch-x86_64/x86_64.mk b/libc/arch-x86_64/x86_64.mk
index ee91d0f..234cf67 100644
--- a/libc/arch-x86_64/x86_64.mk
+++ b/libc/arch-x86_64/x86_64.mk
@@ -37,7 +37,6 @@
     arch-x86_64/bionic/__set_tls.c \
     arch-x86_64/bionic/sigsetjmp.S \
     arch-x86_64/bionic/syscall.S \
-    bionic/__memcmp16.cpp \
 
 libc_bionic_src_files_x86_64 += \
     arch-x86_64/string/sse2-memcpy-slm.S \
diff --git a/libc/bionic/__memcmp16.cpp b/libc/bionic/__memcmp16.cpp
deleted file mode 100644
index eb3a08b..0000000
--- a/libc/bionic/__memcmp16.cpp
+++ /dev/null
@@ -1,43 +0,0 @@
-/*
-Copyright (c) 2013 Intel Corporation
-All rights reserved.
-
-Redistribution and use in source and binary forms, with or without
-modification, are permitted provided that the following conditions are met:
-
-    * Redistributions of source code must retain the above copyright notice,
-    * this list of conditions and the following disclaimer.
-
-    * 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.
-
-    * Neither the name of Intel Corporation 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 COPYRIGHT HOLDERS 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 COPYRIGHT OWNER 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 <stddef.h>
-
-// Unoptimized version of __memcmp16.
-extern "C" int __memcmp16(const unsigned short* lhs, const unsigned short* rhs, size_t n) {
-  for (size_t i = 0; i < n; i++) {
-    if (*lhs != *rhs) {
-      return *lhs - *rhs;
-    }
-    lhs++;
-    rhs++;
-  }
-  return 0;
-}
diff --git a/libc/bionic/ftime.c b/libc/bionic/ftime.c
deleted file mode 100644
index 6513593..0000000
--- a/libc/bionic/ftime.c
+++ /dev/null
@@ -1,49 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *  * Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- *  * 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.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS 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
- * COPYRIGHT OWNER 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/timeb.h>
-
-int ftime(struct timeb *tb)
-{
-    struct timeval  tv;
-    struct timezone tz;
-
-    if (gettimeofday (&tv, &tz) < 0)
-        return -1;
-
-    tb->time    = tv.tv_sec;
-    tb->millitm = (tv.tv_usec + 500) / 1000;
-
-    if (tb->millitm == 1000) {
-        ++tb->time;
-        tb->millitm = 0;
-    }
-    tb->timezone = tz.tz_minuteswest;
-    tb->dstflag  = tz.tz_dsttime;
-
-    return 0;
-}
diff --git a/libc/bionic/getdtablesize.c b/libc/bionic/getdtablesize.c
deleted file mode 100644
index 91315a5..0000000
--- a/libc/bionic/getdtablesize.c
+++ /dev/null
@@ -1,39 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *  * Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- *  * 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.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS 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
- * COPYRIGHT OWNER 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/resource.h>
-#include <sys/sysconf.h>
-
-int getdtablesize()
-{
-    struct rlimit r;
-
-    if (getrlimit(RLIMIT_NOFILE, &r) < 0) {
-        return sysconf(_SC_OPEN_MAX);
-    }
-    return r.rlim_cur;
-}
diff --git a/libc/bionic/jemalloc.cpp b/libc/bionic/jemalloc_wrapper.cpp
similarity index 77%
rename from libc/bionic/jemalloc.cpp
rename to libc/bionic/jemalloc_wrapper.cpp
index 625d789..d1fe960 100644
--- a/libc/bionic/jemalloc.cpp
+++ b/libc/bionic/jemalloc_wrapper.cpp
@@ -14,13 +14,19 @@
  * limitations under the License.
  */
 
+#include <sys/param.h>
 #include <unistd.h>
 
 #include "jemalloc.h"
+#include "private/bionic_macros.h"
 
 void* je_pvalloc(size_t bytes) {
   size_t pagesize = sysconf(_SC_PAGESIZE);
-  return je_memalign(pagesize, (bytes + pagesize - 1) & ~(pagesize - 1));
+  size_t size = BIONIC_ALIGN(bytes, pagesize);
+  if (size < bytes) {
+    return NULL;
+  }
+  return je_memalign(pagesize, size);
 }
 
 #ifdef je_memalign
@@ -31,11 +37,9 @@
 // but this is not true. Both glibc and dlmalloc round up to the next power
 // of 2, so we'll do the same.
 void* je_memalign_round_up_boundary(size_t boundary, size_t size) {
-  unsigned int power_of_2 = static_cast<unsigned int>(boundary);
-  if (power_of_2 != 0) {
-    power_of_2 = 1UL << (sizeof(unsigned int)*8 - 1 - __builtin_clz(power_of_2));
-    if (power_of_2 != boundary) {
-      boundary = power_of_2 << 1;
+  if (boundary != 0) {
+    if (!powerof2(boundary)) {
+      boundary = BIONIC_ROUND_UP_POWER_OF_2(boundary);
     }
   } else {
     boundary = 1;
diff --git a/libc/bionic/malloc_debug_check.cpp b/libc/bionic/malloc_debug_check.cpp
index 0575595..e4e4c2e 100644
--- a/libc/bionic/malloc_debug_check.cpp
+++ b/libc/bionic/malloc_debug_check.cpp
@@ -38,6 +38,7 @@
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
+#include <sys/param.h>
 #include <sys/socket.h>
 #include <sys/system_properties.h>
 #include <sys/types.h>
@@ -47,8 +48,9 @@
 
 #include "debug_mapinfo.h"
 #include "debug_stacktrace.h"
-#include "private/libc_logging.h"
 #include "malloc_debug_common.h"
+#include "private/bionic_macros.h"
+#include "private/libc_logging.h"
 #include "private/ScopedPthreadMutexLocker.h"
 
 #define MAX_BACKTRACE_DEPTH 16
@@ -326,14 +328,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;
@@ -345,8 +352,8 @@
     }
 
     // Make the alignment a power of two.
-    if (alignment & (alignment-1)) {
-        alignment = 1L << (31 - __builtin_clz(alignment));
+    if (!powerof2(alignment)) {
+        alignment = BIONIC_ROUND_UP_POWER_OF_2(alignment);
     }
 
     // here, alignment is at least MALLOC_ALIGNMENT<<1 bytes
@@ -411,15 +418,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 +439,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 +458,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 +523,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 (!powerof2(alignment)) {
+    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 = BIONIC_ALIGN(bytes, pagesize);
+  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..cbca160 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,20 @@
 // 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),
+#if defined(HAVE_DEPRECATED_MALLOC_FUNCS)
+  Malloc(pvalloc),
+#endif
+  Malloc(realloc),
+#if defined(HAVE_DEPRECATED_MALLOC_FUNCS)
+  Malloc(valloc),
+#endif
 };
 
 // Selector of dispatch table to use for dispatching malloc calls.
@@ -97,176 +108,178 @@
 // =============================================================================
 
 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);
+}
+
+#if defined(HAVE_DEPRECATED_MALLOC_FUNCS)
+extern "C" void* pvalloc(size_t bytes) {
+  return __libc_malloc_dispatch->pvalloc(bytes);
+}
+#endif
+
+extern "C" void* realloc(void* oldMem, size_t bytes) {
+  return __libc_malloc_dispatch->realloc(oldMem, bytes);
+}
+
+#if defined(HAVE_DEPRECATED_MALLOC_FUNCS)
+extern "C" void* valloc(size_t bytes) {
+  return __libc_malloc_dispatch->valloc(bytes);
+}
+#endif
+
+// 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 +288,231 @@
 
 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");
+#if defined(HAVE_DEPRECATED_MALLOC_FUNCS)
+  InitMallocFunction<MallocDebugPvalloc>(malloc_impl_handler, &table->pvalloc, prefix, "pvalloc");
+#endif
+  InitMallocFunction<MallocDebugRealloc>(malloc_impl_handler, &table->realloc, prefix, "realloc");
+#if defined(HAVE_DEPRECATED_MALLOC_FUNCS)
+  InitMallocFunction<MallocDebugValloc>(malloc_impl_handler, &table->valloc, prefix, "valloc");
+#endif
 }
 
-/* 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) ||
+#if defined(HAVE_DEPRECATED_MALLOC_FUNCS)
+      (malloc_dispatch_table.pvalloc == NULL) ||
+#endif
+      (malloc_dispatch_table.realloc == NULL)
+#if defined(HAVE_DEPRECATED_MALLOC_FUNCS)
+      || (malloc_dispatch_table.valloc == NULL)
+#endif
+      ) {
+    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..fb2f03d 100644
--- a/libc/bionic/malloc_debug_common.h
+++ b/libc/bionic/malloc_debug_common.h
@@ -37,6 +37,7 @@
 #include <stdint.h>
 #include <stdlib.h>
 
+#include "private/bionic_config.h"
 #include "private/libc_logging.h"
 
 #define HASHTABLE_SIZE      1543
@@ -83,19 +84,36 @@
 };
 
 /* 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);
+#if defined(HAVE_DEPRECATED_MALLOC_FUNCS)
+typedef void* (*MallocDebugPvalloc)(size_t);
+#endif
+typedef void* (*MallocDebugRealloc)(void*, size_t);
+#if defined(HAVE_DEPRECATED_MALLOC_FUNCS)
+typedef void* (*MallocDebugValloc)(size_t);
+#endif
+
 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;
+#if defined(HAVE_DEPRECATED_MALLOC_FUNCS)
+  MallocDebugPvalloc pvalloc;
+#endif
+  MallocDebugRealloc realloc;
+#if defined(HAVE_DEPRECATED_MALLOC_FUNCS)
+  MallocDebugValloc valloc;
+#endif
 };
 
 typedef bool (*MallocDebugInit)(HashTable*);
diff --git a/libc/bionic/malloc_debug_leak.cpp b/libc/bionic/malloc_debug_leak.cpp
index aa7c072..308d40b 100644
--- a/libc/bionic/malloc_debug_leak.cpp
+++ b/libc/bionic/malloc_debug_leak.cpp
@@ -37,6 +37,7 @@
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
+#include <sys/param.h>
 #include <sys/select.h>
 #include <sys/socket.h>
 #include <sys/system_properties.h>
@@ -48,6 +49,7 @@
 #include "debug_stacktrace.h"
 #include "malloc_debug_common.h"
 
+#include "private/bionic_macros.h"
 #include "private/libc_logging.h"
 #include "private/ScopedPthreadMutexLocker.h"
 
@@ -250,6 +252,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 (!powerof2(alignment)) {
+    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 = BIONIC_ALIGN(bytes, pagesize);
+  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 +294,7 @@
 
     size_t size = bytes + sizeof(AllocationEntry);
     if (size < bytes) { // Overflow.
+        errno = ENOMEM;
         return NULL;
     }
 
@@ -327,6 +357,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 +381,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 +390,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;
 }
@@ -371,8 +403,8 @@
     }
 
     // need to make sure it's a power of two
-    if (alignment & (alignment-1)) {
-        alignment = 1L << (31 - __builtin_clz(alignment));
+    if (!powerof2(alignment)) {
+        alignment = BIONIC_ROUND_UP_POWER_OF_2(alignment);
     }
 
     // here, alignment is at least MALLOC_ALIGNMENT<<1 bytes
@@ -428,3 +460,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 (!powerof2(alignment)) {
+    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 = BIONIC_ALIGN(bytes, pagesize);
+  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..fd5161a 100644
--- a/libc/bionic/malloc_debug_qemu.cpp
+++ b/libc/bionic/malloc_debug_qemu.cpp
@@ -47,11 +47,13 @@
 #include <stdio.h>
 #include <fcntl.h>
 #include <sys/mman.h>
+#include <sys/param.h>
 #include <pthread.h>
 #include <unistd.h>
 #include <errno.h>
-#include "private/libc_logging.h"
 #include "malloc_debug_common.h"
+#include "private/bionic_macros.h"
+#include "private/libc_logging.h"
 
 /* This file should be included into the build only when
  * MALLOC_QEMU_INSTRUMENT macro is defined. */
@@ -573,12 +575,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 +686,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(%zu) failed.",
+                       malloc_pid, getpid(), bytes, size);
         return NULL;
     }
 
@@ -692,12 +705,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 +768,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 +803,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 +818,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 +847,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 +865,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 +882,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 +894,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(%zu) 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(%zu) 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 +935,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 +961,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 (!powerof2(alignment)) {
+        alignment = BIONIC_ROUND_UP_POWER_OF_2(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(%zu) 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(%zu) 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 +1002,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 +1030,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 = BIONIC_ALIGN(bytes, pagesize);
+  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/bionic/ndk_cruft.cpp b/libc/bionic/ndk_cruft.cpp
index 15a3206..e3e640a 100644
--- a/libc/bionic/ndk_cruft.cpp
+++ b/libc/bionic/ndk_cruft.cpp
@@ -36,6 +36,7 @@
 #include <signal.h>
 #include <stdio.h>
 #include <stdlib.h>
+#include <string.h>
 #include <sys/resource.h>
 #include <sys/syscall.h>
 #include <sys/time.h>
@@ -250,4 +251,55 @@
   return 0;
 }
 
+// This was removed from POSIX 2004.
+extern "C" pid_t wait3(int* status, int options, struct rusage* rusage) {
+  return wait4(-1, status, options, rusage);
+}
+
+// This was removed from POSIX 2004.
+extern "C" int getdtablesize() {
+  struct rlimit r;
+
+  if (getrlimit(RLIMIT_NOFILE, &r) < 0) {
+    return sysconf(_SC_OPEN_MAX);
+  }
+
+  return r.rlim_cur;
+}
+
+// Only used by ftime, which was removed from POSIX.
+struct timeb {
+  time_t          time;
+  unsigned short  millitm;
+  short           timezone;
+  short           dstflag;
+};
+
+// This was removed from POSIX 2008.
+extern "C" int ftime(struct timeb* tb) {
+  struct timeval  tv;
+  struct timezone tz;
+
+  if (gettimeofday(&tv, &tz) < 0)
+    return -1;
+
+  tb->time    = tv.tv_sec;
+  tb->millitm = (tv.tv_usec + 500) / 1000;
+
+  if (tb->millitm == 1000) {
+    ++tb->time;
+    tb->millitm = 0;
+  }
+
+  tb->timezone = tz.tz_minuteswest;
+  tb->dstflag  = tz.tz_dsttime;
+
+  return 0;
+}
+
+// This was removed from POSIX 2008.
+extern "C" char* index(const char* str, int ch) {
+  return strchr(str, ch);
+}
+
 #endif
diff --git a/libc/bionic/pthread_create.cpp b/libc/bionic/pthread_create.cpp
index c4cb262..c83b5a0 100644
--- a/libc/bionic/pthread_create.cpp
+++ b/libc/bionic/pthread_create.cpp
@@ -33,6 +33,7 @@
 
 #include "pthread_internal.h"
 
+#include "private/bionic_macros.h"
 #include "private/bionic_ssp.h"
 #include "private/bionic_tls.h"
 #include "private/libc_logging.h"
@@ -183,8 +184,8 @@
   }
 
   // Make sure the stack size and guard size are multiples of PAGE_SIZE.
-  thread->attr.stack_size = (thread->attr.stack_size + (PAGE_SIZE-1)) & ~(PAGE_SIZE-1);
-  thread->attr.guard_size = (thread->attr.guard_size + (PAGE_SIZE-1)) & ~(PAGE_SIZE-1);
+  thread->attr.stack_size = BIONIC_ALIGN(thread->attr.stack_size, PAGE_SIZE);
+  thread->attr.guard_size = BIONIC_ALIGN(thread->attr.guard_size, PAGE_SIZE);
 
   if (thread->attr.stack_base == NULL) {
     // The caller didn't provide a stack, so allocate one.
diff --git a/libc/bionic/system_properties.cpp b/libc/bionic/system_properties.cpp
index 7618586..a564c39 100644
--- a/libc/bionic/system_properties.cpp
+++ b/libc/bionic/system_properties.cpp
@@ -55,9 +55,6 @@
 #include "private/bionic_futex.h"
 #include "private/bionic_macros.h"
 
-#define ALIGN(x, a) (((x) + (a - 1)) & ~(a - 1))
-
-
 static const char property_service_socket[] = "/dev/socket/" PROP_SERVICE_NAME;
 
 
@@ -301,7 +298,7 @@
 static void *allocate_obj(const size_t size, uint32_t *const off)
 {
     prop_area *pa = __system_property_area__;
-    const size_t aligned = ALIGN(size, sizeof(uint32_t));
+    const size_t aligned = BIONIC_ALIGN(size, sizeof(uint32_t));
     if (pa->bytes_used + aligned > pa_data_size) {
         return NULL;
     }
diff --git a/libc/bionic/wait.cpp b/libc/bionic/wait.cpp
index cd75c10..e5c93aa 100644
--- a/libc/bionic/wait.cpp
+++ b/libc/bionic/wait.cpp
@@ -35,10 +35,6 @@
   return wait4(-1, status, 0, NULL);
 }
 
-pid_t wait3(int* status, int options, struct rusage* rusage) {
-  return wait4(-1, status, options, rusage);
-}
-
 pid_t waitpid(pid_t pid, int* status, int options) {
   return wait4(pid, status, options, NULL);
 }
diff --git a/libc/dns/include/resolv_netid.h b/libc/dns/include/resolv_netid.h
index 991a0bf..bada18a 100644
--- a/libc/dns/include/resolv_netid.h
+++ b/libc/dns/include/resolv_netid.h
@@ -50,20 +50,27 @@
 
 struct addrinfo;
 
-struct hostent *android_gethostbyaddrfornet(const void *, socklen_t, int, unsigned, unsigned);
-struct hostent *android_gethostbyaddrfornet_proxy(const void *, socklen_t, int , unsigned);
-struct hostent *android_gethostbynamefornet(const char *, int, unsigned, unsigned);
+#define __used_in_netd __attribute__((visibility ("default")))
+
+struct hostent *android_gethostbyaddrfornet(const void *, socklen_t, int, unsigned, unsigned) __used_in_netd;
+struct hostent *android_gethostbynamefornet(const char *, int, unsigned, unsigned) __used_in_netd;
 int android_getaddrinfofornet(const char *, const char *, const struct addrinfo *, unsigned,
-		unsigned, struct addrinfo **);
-int android_getnameinfofornet(const struct sockaddr *, socklen_t, char *, size_t, char *, size_t,
-		 int, unsigned, unsigned);
+		unsigned, struct addrinfo **) __used_in_netd;
 
 /* set name servers for a network */
 extern void _resolv_set_nameservers_for_net(unsigned netid,
-    const char** servers, int numservers, const char *domains);
+    const char** servers, int numservers, const char *domains) __used_in_netd;
 
 /* flush the cache associated with a certain network */
-extern void _resolv_flush_cache_for_net(unsigned netid);
+extern void _resolv_flush_cache_for_net(unsigned netid) __used_in_netd;
+
+/* delete the cache associated with a certain network */
+extern void _resolv_delete_cache_for_net(unsigned netid) __used_in_netd;
+
+/* Internal use only. */
+struct hostent *android_gethostbyaddrfornet_proxy(const void *, socklen_t, int , unsigned);
+int android_getnameinfofornet(const struct sockaddr *, socklen_t, char *, size_t, char *, size_t,
+		 int, unsigned, unsigned);
 
 __END_DECLS
 
diff --git a/libc/dns/include/resolv_private.h b/libc/dns/include/resolv_private.h
index 8914fae..f4c67f3 100644
--- a/libc/dns/include/resolv_private.h
+++ b/libc/dns/include/resolv_private.h
@@ -60,6 +60,9 @@
 #include "resolv_static.h"
 #include <net/if.h>
 
+/* Despite this file's name, it's part of libresolv. On Android, that means it's part of libc :-( */
+#pragma GCC visibility push(default)
+
 /*
  * Revision information.  This is the release date in YYYYMMDD format.
  * It can change every day so the right thing to do with it is use it
@@ -279,8 +282,9 @@
 
 /* Things involving an internal (static) resolver context. */
 __BEGIN_DECLS
-extern struct __res_state *__res_get_state(void);
-extern void __res_put_state(struct __res_state *);
+
+__LIBC_HIDDEN__ extern struct __res_state *__res_get_state(void);
+__LIBC_HIDDEN__ extern void __res_put_state(struct __res_state *);
 
 #ifndef ANDROID_CHANGES
 /*
@@ -320,7 +324,7 @@
 void		p_query(const u_char *);
 void		res_close(void);
 int		res_init(void);
-int		res_opt(int, u_char *, int, int);
+__LIBC_HIDDEN__ int		res_opt(int, u_char *, int, int);
 int		res_isourserver(const struct sockaddr_in *);
 int		res_mkquery(int, const char *, int, int, const u_char *, int, const u_char *, u_char *, int);
 int		res_query(const char *, int, int, u_char *, int);
@@ -339,11 +343,11 @@
  * Make them go away if a client is including this
  *
  */
-extern const struct res_sym __p_key_syms[];
-extern const struct res_sym __p_cert_syms[];
+__LIBC_HIDDEN__ extern const struct res_sym __p_key_syms[];
+__LIBC_HIDDEN__ extern const struct res_sym __p_cert_syms[];
 extern const struct res_sym __p_class_syms[];
 extern const struct res_sym __p_type_syms[];
-extern const struct res_sym __p_rcode_syms[];
+__LIBC_HIDDEN__ extern const struct res_sym __p_rcode_syms[];
 #endif /* SHARED_LIBBIND */
 
 #ifndef ANDROID_CHANGES
@@ -434,7 +438,7 @@
 const char *	p_time(uint32_t);
 const char *	p_type(int);
 const char *	p_rcode(int);
-const char *	p_sockun(union res_sockaddr_union, char *, size_t);
+__LIBC_HIDDEN__ const char *	p_sockun(union res_sockaddr_union, char *, size_t);
 const u_char *	p_cdnname(const u_char *, const u_char *, int, FILE *);
 const u_char *	p_cdname(const u_char *, const u_char *, FILE *);
 const u_char *	p_fqnname(const u_char *, const u_char *,
@@ -448,12 +452,12 @@
 				     const u_char *);
 int		res_queriesmatch(const u_char *, const u_char *,
 				      const u_char *, const u_char *);
-const char *	p_section(int, int);
+__LIBC_HIDDEN__ const char *	p_section(int, int);
 /* Things involving a resolver context. */
 int		res_ninit(res_state);
 int		res_nisourserver(const res_state, const struct sockaddr_in *);
 void		fp_resstat(const res_state, FILE *);
-void		res_pquery(const res_state, const u_char *, int, FILE *);
+__LIBC_HIDDEN__ void		res_pquery(const res_state, const u_char *, int, FILE *);
 const char *	res_hostalias(const res_state, const char *, char *, size_t);
 int		res_nquery(res_state, const char *, int, int, u_char *, int);
 int		res_nsearch(res_state, const char *, int, int, u_char *, int);
@@ -471,29 +475,31 @@
 				      char *, size_t,
 				      union res_sockaddr_union *, int);
 void		res_nclose(res_state);
-int		res_nopt(res_state, int, u_char *, int, int);
+__LIBC_HIDDEN__ int		res_nopt(res_state, int, u_char *, int, int);
 void		res_send_setqhook(res_send_qhook);
 void		res_send_setrhook(res_send_rhook);
-int		__res_vinit(res_state, int);
+__LIBC_HIDDEN__ int		__res_vinit(res_state, int);
 void		res_destroyservicelist(void);
 const char *	res_servicename(uint16_t, const char *);
 const char *	res_protocolname(int);
 void		res_destroyprotolist(void);
 void		res_buildprotolist(void);
-const char *	res_get_nibblesuffix(res_state);
-const char *	res_get_nibblesuffix2(res_state);
-void		res_ndestroy(res_state);
-uint16_t	res_nametoclass(const char *, int *);
-uint16_t	res_nametotype(const char *, int *);
-void		res_setservers(res_state,
+__LIBC_HIDDEN__ const char *	res_get_nibblesuffix(res_state);
+__LIBC_HIDDEN__ const char *	res_get_nibblesuffix2(res_state);
+__LIBC_HIDDEN__ void		res_ndestroy(res_state);
+__LIBC_HIDDEN__ uint16_t	res_nametoclass(const char *, int *);
+__LIBC_HIDDEN__ uint16_t	res_nametotype(const char *, int *);
+__LIBC_HIDDEN__ void		res_setservers(res_state,
 				    const union res_sockaddr_union *, int);
-int		res_getservers(res_state,
+__LIBC_HIDDEN__ int		res_getservers(res_state,
 				    union res_sockaddr_union *, int);
 
-void res_setnetid(res_state, unsigned);
-void res_setmark(res_state, unsigned);
+__LIBC_HIDDEN__ void res_setnetid(res_state, unsigned);
+__LIBC_HIDDEN__ void res_setmark(res_state, unsigned);
 u_int  res_randomid(void);
 
 __END_DECLS
 
+#pragma GCC visibility pop
+
 #endif /* !_RESOLV_PRIVATE_H_ */
diff --git a/libc/include/malloc.h b/libc/include/malloc.h
index 9a4e324..e6ea276 100644
--- a/libc/include/malloc.h
+++ b/libc/include/malloc.h
@@ -35,9 +35,6 @@
 extern void* memalign(size_t alignment, size_t byte_count) __mallocfunc __wur __attribute__((alloc_size(2)));
 extern size_t malloc_usable_size(const void* p);
 
-extern void* valloc(size_t byte_count) __mallocfunc __wur __attribute__((alloc_size(1)));
-extern void* pvalloc(size_t byte_count) __mallocfunc __wur __attribute__((alloc_size(1)));
-
 #ifndef STRUCT_MALLINFO_DECLARED
 #define STRUCT_MALLINFO_DECLARED 1
 struct mallinfo {
diff --git a/libc/include/netdb.h b/libc/include/netdb.h
index ead5954..527d5c1 100644
--- a/libc/include/netdb.h
+++ b/libc/include/netdb.h
@@ -196,6 +196,8 @@
 #define	SCOPE_DELIMITER	'%'
 
 __BEGIN_DECLS
+#pragma GCC visibility push(default)
+
 /* BIONIC-BEGIN */
 #define  h_errno   (*__get_h_errno())
 int*  __get_h_errno(void);
@@ -245,6 +247,7 @@
 void setnetgrent(const char *);
 void setservent(int);
 
+#pragma GCC visibility pop
 __END_DECLS
 
 #endif /* !_NETDB_H_ */
diff --git a/libc/include/resolv.h b/libc/include/resolv.h
index 36b93ee..c8899ed 100644
--- a/libc/include/resolv.h
+++ b/libc/include/resolv.h
@@ -37,6 +37,7 @@
 #include <netinet/in.h>
 
 __BEGIN_DECLS
+#pragma GCC visibility push(default)
 
 struct res_state;
 
@@ -52,6 +53,7 @@
 extern int dn_comp(const char*, u_char*, int, u_char**, u_char**);
 extern int dn_expand(const u_char*, const u_char*, const u_char*, char*, int);
 
+#pragma GCC visibility pop
 __END_DECLS
 
 #endif /* _RESOLV_H_ */
diff --git a/libc/include/stdio.h b/libc/include/stdio.h
index efc5492..e532de4 100644
--- a/libc/include/stdio.h
+++ b/libc/include/stdio.h
@@ -254,7 +254,9 @@
 int vdprintf(int, const char * __restrict, __va_list) __printflike(2, 0);
 
 #ifndef __AUDIT__
+#if !defined(__STDC_VERSION__) || __STDC_VERSION__ < 201112L
 char* gets(char*) __warnattr("gets is very unsafe; consider using fgets");
+#endif
 int sprintf(char* __restrict, const char* __restrict, ...)
     __printflike(2, 3) __warnattr("sprintf is often misused; please use snprintf");
 char* tmpnam(char*) __warnattr("tmpnam possibly used unsafely; consider using mkstemp");
@@ -337,8 +339,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..266aa5e 100644
--- a/libc/include/stdlib.h
+++ b/libc/include/stdlib.h
@@ -105,20 +105,21 @@
 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);
-}
+
+/* Work around x86/x86-64 libvpx build breakage caused by postproc_x86.c. */
+#if (defined(__i386__) || defined(__x86_64__)) && defined(rand)
+#undef rand
+#define __rand lrand48
+#endif
+
+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/include/sys/ioctl.h b/libc/include/sys/ioctl.h
index 49d452c..a1014dc 100644
--- a/libc/include/sys/ioctl.h
+++ b/libc/include/sys/ioctl.h
@@ -38,6 +38,7 @@
 #include <asm/ioctls.h>
 #include <asm/termbits.h>
 #include <sys/ioctl_compat.h>
+#include <linux/tty.h>
 
 __BEGIN_DECLS
 
diff --git a/libc/include/sys/timeb.h b/libc/include/sys/timeb.h
deleted file mode 100644
index cf6f255..0000000
--- a/libc/include/sys/timeb.h
+++ /dev/null
@@ -1,47 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *  * Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- *  * 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.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS 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
- * COPYRIGHT OWNER 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.
- */
-#ifndef _SYS_TIMEB_H
-#define _SYS_TIMEB_H
-
-#include <sys/cdefs.h>
-#include <sys/time.h>
-
-__BEGIN_DECLS
-
-struct timeb {
-    time_t          time;
-    unsigned short  millitm;
-    short           timezone;
-    short           dstflag;
-};
-
-extern int  ftime(struct timeb*  timebuf);
-
-__END_DECLS
-
-#endif /* _SYS_TIMEB_H */
diff --git a/libc/include/sys/wait.h b/libc/include/sys/wait.h
index b30b7ec..8d9a5f6 100644
--- a/libc/include/sys/wait.h
+++ b/libc/include/sys/wait.h
@@ -47,7 +47,6 @@
 
 extern pid_t  wait(int *);
 extern pid_t  waitpid(pid_t, int *, int);
-extern pid_t  wait3(int *, int, struct rusage *);
 extern pid_t  wait4(pid_t, int *, int, struct rusage *);
 
 /* Posix states that idtype_t should be an enumeration type, but
diff --git a/libc/include/unistd.h b/libc/include/unistd.h
index ee6d7b1..afe5f1a 100644
--- a/libc/include/unistd.h
+++ b/libc/include/unistd.h
@@ -164,8 +164,6 @@
 
 extern int gethostname(char *, size_t);
 
-extern int getdtablesize(void);
-
 extern void *__brk(void *);
 extern int brk(void *);
 extern void *sbrk(ptrdiff_t);
diff --git a/libc/private/bionic_config.h b/libc/private/bionic_config.h
new file mode 100644
index 0000000..0c9811c
--- /dev/null
+++ b/libc/private/bionic_config.h
@@ -0,0 +1,26 @@
+/*
+ * Copyright (C) 2014 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef _BIONIC_CONFIG_H_
+#define _BIONIC_CONFIG_H_
+
+// valloc(3) and pvalloc(3) were removed from POSIX 2004. We do not include them
+// for LP64, but the symbols remain in LP32 for binary compatibility.
+#if !defined(__LP64__)
+#define HAVE_DEPRECATED_MALLOC_FUNCS 1
+#endif
+
+#endif // _BIONIC_CONFIG_H_
diff --git a/libc/private/bionic_macros.h b/libc/private/bionic_macros.h
index 34da501..a3a6985 100644
--- a/libc/private/bionic_macros.h
+++ b/libc/private/bionic_macros.h
@@ -33,4 +33,10 @@
   TypeName();                                    \
   DISALLOW_COPY_AND_ASSIGN(TypeName)
 
+#define BIONIC_ALIGN(value, alignment) \
+  (((value) + (alignment) - 1) & ~((alignment) - 1))
+
+#define BIONIC_ROUND_UP_POWER_OF_2(value) \
+  (1UL << (sizeof(value) * 8 - 1 - __builtin_clz(value)))
+
 #endif // _BIONIC_MACROS_H_
diff --git a/libc/private/bionic_tls.h b/libc/private/bionic_tls.h
index b52013f..56a61be 100644
--- a/libc/private/bionic_tls.h
+++ b/libc/private/bionic_tls.h
@@ -31,6 +31,7 @@
 
 #include <sys/cdefs.h>
 #include <sys/limits.h>
+#include "bionic_macros.h"
 #include "__get_tls.h"
 
 __BEGIN_DECLS
@@ -84,8 +85,6 @@
 #define BIONIC_TLS_RESERVED_SLOTS GLOBAL_INIT_THREAD_LOCAL_BUFFER_COUNT
 #endif
 
-#define BIONIC_ALIGN(x, a) (((x) + (a - 1)) & ~(a - 1))
-
 /*
  * Maximum number of elements in the TLS array.
  * This includes space for pthread keys and our own internal slots.
diff --git a/libc/stdlib/atexit.c b/libc/stdlib/atexit.c
index c607206..05f2faa 100644
--- a/libc/stdlib/atexit.c
+++ b/libc/stdlib/atexit.c
@@ -37,7 +37,6 @@
 #include "atexit.h"
 #include "private/thread_private.h"
 
-int __atexit_invalid = 1;
 struct atexit *__atexit;
 
 /*
@@ -131,8 +130,6 @@
 		    sizeof(p->fns[0]);
 		p->next = __atexit;
 		__atexit = p;
-		if (__atexit_invalid)
-			__atexit_invalid = 0;
 	}
 	fnp = &p->fns[p->ind++];
 	fnp->cxa_func = func;
@@ -159,8 +156,6 @@
 	int n, pgsize = getpagesize(), original_ind;
 	static int call_depth;
 
-	if (__atexit_invalid)
-		return;
 	_ATEXIT_LOCK();
 	call_depth++;
 
diff --git a/libc/stdlib/atexit.h b/libc/stdlib/atexit.h
index 2e88ad6..b530ade 100644
--- a/libc/stdlib/atexit.h
+++ b/libc/stdlib/atexit.h
@@ -45,8 +45,7 @@
 
 __BEGIN_DECLS
 
-extern int __atexit_invalid;
-extern struct atexit *__atexit;		/* points to head of LIFO stack */
+__LIBC_HIDDEN__ extern struct atexit *__atexit;		/* points to head of LIFO stack */
 
 int	__cxa_atexit(void (*)(void *), void *, void *);
 void	__cxa_finalize(void *);
diff --git a/libc/tools/check-symbols-glibc.py b/libc/tools/check-symbols-glibc.py
index d0e00f3..58a10e0 100755
--- a/libc/tools/check-symbols-glibc.py
+++ b/libc/tools/check-symbols-glibc.py
@@ -11,7 +11,6 @@
 arch = re.sub(r'.*/linux-x86/([^/]+)/.*', r'\1', toolchain)
 
 def GetSymbolsFromSo(so_file):
-
   # Example readelf output:
   #   264: 0001623c     4 FUNC    GLOBAL DEFAULT    8 cabsf
   #   266: 00016244     4 FUNC    GLOBAL DEFAULT    8 dremf
@@ -23,13 +22,13 @@
   symbols = set()
 
   for line in subprocess.check_output(['readelf', '--dyn-syms', '-W', so_file]).split('\n'):
-     if ' HIDDEN ' in line or ' UND ' in line:
-       continue
-     m = r.match(line)
-     if m:
-       symbol = m.group(2)
-       symbol = re.sub('@.*', '', symbol)
-       symbols.add(symbol)
+    if ' HIDDEN ' in line or ' UND ' in line:
+      continue
+    m = r.match(line)
+    if m:
+      symbol = m.group(2)
+      symbol = re.sub('@.*', '', symbol)
+      symbols.add(symbol)
 
   return symbols
 
@@ -46,9 +45,23 @@
     symbols = symbols | GetSymbolsFromSo(f)
   return symbols
 
+def MangleGlibcNameToBionic(name):
+  if name in glibc_to_bionic_names:
+    return glibc_to_bionic_names[name]
+  return name
+
+glibc_to_bionic_names = {
+  '__res_init': 'res_init',
+  '__res_mkquery': 'res_mkquery',
+  '__res_query': 'res_query',
+  '__res_search': 'res_search',
+}
+
 glibc = GetSymbolsFromSystemSo('libc.so.*', 'librt.so.*', 'libpthread.so.*', 'libresolv.so.*', 'libm.so.*')
 bionic = GetSymbolsFromAndroidSo('libc.so', 'libm.so')
 
+glibc = map(MangleGlibcNameToBionic, glibc)
+
 # bionic includes various BSD symbols to ease porting other BSD-licensed code.
 bsd_stuff = set([
   'basename_r',
diff --git a/libc/tzcode/localtime.c b/libc/tzcode/localtime.c
index c40569c..0033652 100644
--- a/libc/tzcode/localtime.c
+++ b/libc/tzcode/localtime.c
@@ -281,7 +281,7 @@
 #endif /* defined ALTZONE */
 #ifdef ALL_STATE
     if (sp == NULL) {
-        tzname[0] = tzname[1] = gmt;
+        tzname[0] = tzname[1] = (char *) gmt;
         return;
     }
 #endif /* defined ALL_STATE */
@@ -332,11 +332,11 @@
 }
 
 static int
-differ_by_repeat(const time_t t1, const time_t t0)
+differ_by_repeat(const time_t t1 __unused, const time_t t0 __unused)
 {
     if (TYPE_BIT(time_t) - TYPE_SIGNED(time_t) < SECSPERREPEAT_BITS)
         return 0;
-#if __LP64__ // 32-bit Android only has a signed 32-bit time_t; 64-bit Android is fixed.
+#if defined(__LP64__) // 32-bit Android only has a signed 32-bit time_t; 64-bit Android is fixed.
     return t1 - t0 == SECSPERREPEAT;
 #endif
 }
@@ -2108,10 +2108,6 @@
 #include <stdint.h>
 #include <arpa/inet.h> // For ntohl(3).
 
-static int to_int(unsigned char* s) {
-  return (s[0] << 24) | (s[1] << 16) | (s[2] << 8) | s[3];
-}
-
 static int __bionic_open_tzdata_path(const char* path_prefix_variable, const char* path_suffix,
                                      const char* olson_id, int* data_size) {
   const char* path_prefix = getenv(path_prefix_variable);
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/bionic/index.cpp b/libc/upstream-netbsd/lib/libc/stdlib/rand.c
similarity index 69%
copy from libc/bionic/index.cpp
copy to libc/upstream-netbsd/lib/libc/stdlib/rand.c
index cc22d81..4909d14 100644
--- a/libc/bionic/index.cpp
+++ b/libc/upstream-netbsd/lib/libc/stdlib/rand.c
@@ -1,6 +1,8 @@
+/*	$NetBSD: rand.c,v 1.12 2012/06/25 22:32:45 abs Exp $	*/
+
 /*-
- * Copyright (c) 1990 The Regents of the University of California.
- * All rights reserved.
+ * 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
@@ -27,9 +29,29 @@
  * SUCH DAMAGE.
  */
 
-#undef _FORTIFY_SOURCE
-#include <string.h>
+#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 */
 
-char* index(const char* p, int ch) {
-  return __strchr_chk(p, ch, __BIONIC_FORTIFY_UNKNOWN_SIZE);
+#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/bionic/index.cpp b/libc/upstream-netbsd/lib/libc/stdlib/rand_r.c
similarity index 75%
rename from libc/bionic/index.cpp
rename to libc/upstream-netbsd/lib/libc/stdlib/rand_r.c
index cc22d81..272b2bd 100644
--- a/libc/bionic/index.cpp
+++ b/libc/upstream-netbsd/lib/libc/stdlib/rand_r.c
@@ -1,3 +1,5 @@
+/*	$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.
@@ -27,9 +29,23 @@
  * SUCH DAMAGE.
  */
 
-#undef _FORTIFY_SOURCE
-#include <string.h>
+#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 */
 
-char* index(const char* p, int ch) {
-  return __strchr_chk(p, ch, __BIONIC_FORTIFY_UNKNOWN_SIZE);
+#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/libc/zoneinfo/tzdata b/libc/zoneinfo/tzdata
index b3c9444..a5ae1f6 100644
--- a/libc/zoneinfo/tzdata
+++ b/libc/zoneinfo/tzdata
Binary files differ
diff --git a/libm/Android.mk b/libm/Android.mk
index b67395f..90b4906 100644
--- a/libm/Android.mk
+++ b/libm/Android.mk
@@ -1,3 +1,4 @@
+ifneq ($(TARGET_USE_PRIVATE_LIBM),true)
 LOCAL_PATH:= $(call my-dir)
 
 # TODO: this comes from from upstream's libc, not libm, but it's an
@@ -291,3 +292,4 @@
 LOCAL_SYSTEM_SHARED_LIBRARIES := libc
 LOCAL_WHOLE_STATIC_LIBRARIES := libm
 include $(BUILD_SHARED_LIBRARY)
+endif
diff --git a/libstdc++/include/cstdio b/libstdc++/include/cstdio
index 3c8b5c6..2948d85 100644
--- a/libstdc++/include/cstdio
+++ b/libstdc++/include/cstdio
@@ -63,7 +63,9 @@
 using ::fwrite;
 using ::getc;
 using ::getchar;
+#if !defined(__STDC_VERSION__) || __STDC_VERSION__ < 201112L
 using ::gets;
+#endif
 using ::perror;
 using ::printf;
 using ::putc;
diff --git a/linker/Android.mk b/linker/Android.mk
index 811cf6e..68e801d 100644
--- a/linker/Android.mk
+++ b/linker/Android.mk
@@ -16,6 +16,7 @@
 LOCAL_SRC_FILES_x86     := arch/x86/begin.c
 LOCAL_SRC_FILES_x86_64  := arch/x86_64/begin.S
 LOCAL_SRC_FILES_mips    := arch/mips/begin.S
+LOCAL_SRC_FILES_mips64  := arch/mips64/begin.S
 
 LOCAL_LDFLAGS := \
     -shared \
diff --git a/linker/dlfcn.cpp b/linker/dlfcn.cpp
index 6d63ad6..0b60ef5 100644
--- a/linker/dlfcn.cpp
+++ b/linker/dlfcn.cpp
@@ -118,7 +118,7 @@
   if (sym != NULL) {
     unsigned bind = ELF_ST_BIND(sym->st_info);
 
-    if (bind == STB_GLOBAL && sym->st_shndx != 0) {
+    if ((bind == STB_GLOBAL || bind == STB_WEAK) && sym->st_shndx != 0) {
       return reinterpret_cast<void*>(sym->st_value + found->load_bias);
     }
 
diff --git a/linker/linker.cpp b/linker/linker.cpp
index a22233d..e202aaf 100644
--- a/linker/linker.cpp
+++ b/linker/linker.cpp
@@ -59,6 +59,7 @@
  *
  * open issues / todo:
  *
+ * - are we doing everything we should for ARM_COPY relocations?
  * - cleaner error reporting
  * - after linking, set as much stuff as possible to READONLY
  *   and NOEXEC
@@ -1037,17 +1038,52 @@
         break;
 
     case R_AARCH64_COPY:
-        /*
-         * ET_EXEC is not supported so this should not happen.
-         *
-         * http://infocenter.arm.com/help/topic/com.arm.doc.ihi0044d/IHI0044D_aaelf.pdf
-         *
-         * Section 4.7.1.10 "Dynamic relocations"
-         * R_AARCH64_COPY may only appear in executable objects where e_type is
-         * set to ET_EXEC.
-         */
-        DL_ERR("%s R_AARCH64_COPY relocations are not supported", si->name);
-        return -1;
+        if ((si->flags & FLAG_EXE) == 0) {
+            /*
+              * http://infocenter.arm.com/help/topic/com.arm.doc.ihi0044d/IHI0044D_aaelf.pdf
+              *
+              * Section 4.7.1.10 "Dynamic relocations"
+              * R_AARCH64_COPY may only appear in executable objects where e_type is
+              * set to ET_EXEC.
+              *
+              * FLAG_EXE is set for both ET_DYN and ET_EXEC executables.
+              * We should explicitly disallow ET_DYN executables from having
+              * R_AARCH64_COPY relocations.
+              */
+            DL_ERR("%s R_AARCH64_COPY relocations only supported for ET_EXEC", si->name);
+            return -1;
+        }
+        count_relocation(kRelocCopy);
+        MARK(rela->r_offset);
+        TRACE_TYPE(RELO, "RELO COPY %16llx <- %lld @ %16llx %s\n",
+                   reloc,
+                   s->st_size,
+                   (sym_addr + rela->r_addend),
+                   sym_name);
+        if (reloc == (sym_addr + rela->r_addend)) {
+            ElfW(Sym)* src = soinfo_do_lookup(NULL, sym_name, &lsi, needed);
+
+            if (src == NULL) {
+                DL_ERR("%s R_AARCH64_COPY relocation source cannot be resolved", si->name);
+                return -1;
+            }
+            if (lsi->has_DT_SYMBOLIC) {
+                DL_ERR("%s invalid R_AARCH64_COPY relocation against DT_SYMBOLIC shared "
+                       "library %s (built with -Bsymbolic?)", si->name, lsi->name);
+                return -1;
+            }
+            if (s->st_size < src->st_size) {
+                DL_ERR("%s R_AARCH64_COPY relocation size mismatch (%lld < %lld)",
+                       si->name, s->st_size, src->st_size);
+                return -1;
+            }
+            memcpy(reinterpret_cast<void*>(reloc),
+                   reinterpret_cast<void*>(src->st_value + lsi->load_bias), src->st_size);
+        } else {
+            DL_ERR("%s R_AARCH64_COPY relocation target cannot be resolved", si->name);
+            return -1;
+        }
+        break;
     case R_AARCH64_TLS_TPREL64:
         TRACE_TYPE(RELO, "RELO TLS_TPREL64 *** %16llx <- %16llx - %16llx\n",
                    reloc, (sym_addr + rela->r_addend), rela->r_offset);
@@ -1225,17 +1261,48 @@
             *reinterpret_cast<ElfW(Addr)*>(reloc) += sym_addr - rel->r_offset;
             break;
         case R_ARM_COPY:
-            /*
-             * ET_EXEC is not supported so this should not happen.
-             *
-             * http://infocenter.arm.com/help/topic/com.arm.doc.ihi0044d/IHI0044D_aaelf.pdf
-             *
-             * Section 4.7.1.10 "Dynamic relocations"
-             * R_ARM_COPY may only appear in executable objects where e_type is
-             * set to ET_EXEC.
-             */
-            DL_ERR("%s R_ARM_COPY relocations are not supported", si->name);
-            return -1;
+            if ((si->flags & FLAG_EXE) == 0) {
+                /*
+                 * http://infocenter.arm.com/help/topic/com.arm.doc.ihi0044d/IHI0044D_aaelf.pdf
+                 *
+                 * Section 4.7.1.10 "Dynamic relocations"
+                 * R_ARM_COPY may only appear in executable objects where e_type is
+                 * set to ET_EXEC.
+                 *
+                 * TODO: FLAG_EXE is set for both ET_DYN and ET_EXEC executables.
+                 * We should explicitly disallow ET_DYN executables from having
+                 * R_ARM_COPY relocations.
+                 */
+                DL_ERR("%s R_ARM_COPY relocations only supported for ET_EXEC", si->name);
+                return -1;
+            }
+            count_relocation(kRelocCopy);
+            MARK(rel->r_offset);
+            TRACE_TYPE(RELO, "RELO %08x <- %d @ %08x %s", reloc, s->st_size, sym_addr, sym_name);
+            if (reloc == sym_addr) {
+                ElfW(Sym)* src = soinfo_do_lookup(NULL, sym_name, &lsi, needed);
+
+                if (src == NULL) {
+                    DL_ERR("%s R_ARM_COPY relocation source cannot be resolved", si->name);
+                    return -1;
+                }
+                if (lsi->has_DT_SYMBOLIC) {
+                    DL_ERR("%s invalid R_ARM_COPY relocation against DT_SYMBOLIC shared "
+                           "library %s (built with -Bsymbolic?)", si->name, lsi->name);
+                    return -1;
+                }
+                if (s->st_size < src->st_size) {
+                    DL_ERR("%s R_ARM_COPY relocation size mismatch (%d < %d)",
+                           si->name, s->st_size, src->st_size);
+                    return -1;
+                }
+                memcpy(reinterpret_cast<void*>(reloc),
+                       reinterpret_cast<void*>(src->st_value + lsi->load_bias), src->st_size);
+            } else {
+                DL_ERR("%s R_ARM_COPY relocation target cannot be resolved", si->name);
+                return -1;
+            }
+            break;
 #elif defined(__i386__)
         case R_386_JMP_SLOT:
             count_relocation(kRelocAbsolute);
@@ -2105,11 +2172,13 @@
     si->dynamic = NULL;
     si->ref_count = 1;
 
+#if defined(__LP64__)
     ElfW(Ehdr)* elf_hdr = reinterpret_cast<ElfW(Ehdr)*>(si->base);
     if (elf_hdr->e_type != ET_DYN) {
         __libc_format_fd(2, "error: only position independent executables (PIE) are supported.\n");
         exit(EXIT_FAILURE);
     }
+#endif
 
     // Use LD_LIBRARY_PATH and LD_PRELOAD (but only if we aren't setuid/setgid).
     parse_LD_LIBRARY_PATH(ldpath_env);
diff --git a/tests/Android.build.mk b/tests/Android.build.mk
index e65ec16..6433d55 100644
--- a/tests/Android.build.mk
+++ b/tests/Android.build.mk
@@ -36,10 +36,6 @@
 
 LOCAL_FORCE_STATIC_EXECUTABLE := $($(module)_force_static_executable)
 
-LOCAL_ADDITIONAL_DEPENDENCIES := \
-    $(LOCAL_PATH)/Android.mk \
-    $(LOCAL_PATH)/Android.build.mk \
-
 LOCAL_CFLAGS := \
     $(common_cflags) \
     $($(module)_cflags) \
diff --git a/tests/Android.mk b/tests/Android.mk
index c2e76b6..47e6272 100644
--- a/tests/Android.mk
+++ b/tests/Android.mk
@@ -115,9 +115,18 @@
 libBionicStandardTests_cflags := \
     $(test_cflags) \
 
+ifeq ($(MALLOC_IMPL),jemalloc)
+  libBionicStandardTests_cflags += -DUSE_JEMALLOC
+else
+  libBionicStandardTests_cflags += -DUSE_DLMALLOC
+endif
+
 libBionicStandardTests_cppflags := \
     $(test_cppflags) \
 
+libBionicStandardTests_c_includes := \
+    bionic/libc \
+
 libBionicStandardTests_ldlibs_host := \
     -lrt \
 
@@ -224,88 +233,6 @@
 include $(LOCAL_PATH)/Android.build.mk
 
 # -----------------------------------------------------------------------------
-# Library used by dlfcn tests.
-# -----------------------------------------------------------------------------
-ifneq ($(TARGET_ARCH),$(filter $(TARGET_ARCH),mips mips64))
-no-elf-hash-table-library_src_files := \
-    empty.cpp \
-
-no-elf-hash-table-library_ldflags := \
-    -Wl,--hash-style=gnu \
-
-module := no-elf-hash-table-library
-module_tag := optional
-build_type := target
-build_target := SHARED_LIBRARY
-include $(LOCAL_PATH)/Android.build.mk
-endif
-
-# -----------------------------------------------------------------------------
-# Library used by dlext tests - with/without GNU RELRO program header
-# -----------------------------------------------------------------------------
-libdlext_test_src_files := \
-    dlext_test_library.cpp \
-
-libdlext_test_ldflags := \
-    -Wl,-z,relro \
-
-module := libdlext_test
-module_tag := optional
-build_type := target
-build_target := SHARED_LIBRARY
-include $(LOCAL_PATH)/Android.build.mk
-
-# -----------------------------------------------------------------------------
-# create symlink to libdlext_test.so for symlink test
-# -----------------------------------------------------------------------------
-# Use = instead of := to defer the evaluation of $@
-$(LOCAL_INSTALLED_MODULE): PRIVATE_POST_INSTALL_CMD = \
-    $(hide) cd $(dir $@) && ln -sf $(notdir $@) libdlext_test_v2.so
-ifneq ($(TARGET_2ND_ARCH),)
-# link 64 bit .so
-$(TARGET_OUT)/lib64/libdlext_test.so: PRIVATE_POST_INSTALL_CMD = \
-    $(hide) cd $(dir $@) && ln -sf $(notdir $@) libdlext_test_v2.so
-endif
-
-libdlext_test_norelro_src_files := \
-    dlext_test_library.cpp \
-
-libdlext_test_norelro_ldflags := \
-    -Wl,-z,norelro \
-
-module := libdlext_test_norelro
-module_tag := optional
-build_type := target
-build_target := SHARED_LIBRARY
-include $(LOCAL_PATH)/Android.build.mk
-
-# -----------------------------------------------------------------------------
-# Library used by dlfcn tests
-# -----------------------------------------------------------------------------
-libtest_simple_src_files := \
-    dlopen_testlib_simple.cpp
-
-module := libtest_simple
-build_type := target
-build_target := SHARED_LIBRARY
-include $(LOCAL_PATH)/Android.build.mk
-
-
-# -----------------------------------------------------------------------------
-# Library used by atexit tests
-# -----------------------------------------------------------------------------
-
-libtest_atexit_src_files := \
-    atexit_testlib.cpp
-
-module := libtest_atexit
-build_target := SHARED_LIBRARY
-build_type := target
-include $(LOCAL_PATH)/Android.build.mk
-build_type := host
-include $(LOCAL_PATH)/Android.build.mk
-
-# -----------------------------------------------------------------------------
 # Tests for the device using bionic's .so. Run with:
 #   adb shell /data/nativetest/bionic-unit-tests/bionic-unit-tests
 # -----------------------------------------------------------------------------
@@ -429,4 +356,5 @@
 
 endif # linux-x86
 
+include $(call first-makefiles-under,$(LOCAL_PATH))
 endif # !BUILD_TINY_ANDROID
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/dlfcn_test.cpp b/tests/dlfcn_test.cpp
index 49cbb7d..8b89183 100644
--- a/tests/dlfcn_test.cpp
+++ b/tests/dlfcn_test.cpp
@@ -254,6 +254,18 @@
   ASSERT_TRUE(addr != NULL);
 }
 
+TEST(dlfcn, dlsym_weak_func) {
+  dlerror();
+  void* handle = dlopen("libtest_dlsym_weak_func.so",RTLD_NOW);
+  ASSERT_TRUE(handle != NULL);
+
+  int (*weak_func)();
+  weak_func = reinterpret_cast<int (*)()>(dlsym(handle, "weak_func"));
+  ASSERT_TRUE(weak_func != NULL) << "dlerror: " << dlerror();
+  EXPECT_EQ(42, weak_func());
+  dlclose(handle);
+}
+
 TEST(dlfcn, dlopen_symlink) {
   void* handle1 = dlopen("libdlext_test.so", RTLD_NOW);
   void* handle2 = dlopen("libdlext_test_v2.so", RTLD_NOW);
diff --git a/tests/libs/Android.mk b/tests/libs/Android.mk
new file mode 100644
index 0000000..67ea562
--- /dev/null
+++ b/tests/libs/Android.mk
@@ -0,0 +1,117 @@
+#
+# Copyright (C) 2012 The Android Open Source Project
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+LOCAL_PATH := $(call my-dir)
+TEST_PATH := $(LOCAL_PATH)/..
+
+# -----------------------------------------------------------------------------
+# Library used by dlfcn tests.
+# -----------------------------------------------------------------------------
+ifneq ($(TARGET_ARCH),$(filter $(TARGET_ARCH),mips mips64))
+no-elf-hash-table-library_src_files := \
+    empty.cpp \
+
+no-elf-hash-table-library_ldflags := \
+    -Wl,--hash-style=gnu \
+
+module := no-elf-hash-table-library
+module_tag := optional
+build_type := target
+build_target := SHARED_LIBRARY
+include $(TEST_PATH)/Android.build.mk
+endif
+
+# -----------------------------------------------------------------------------
+# Library used by dlext tests - with GNU RELRO program header
+# -----------------------------------------------------------------------------
+libdlext_test_src_files := \
+    dlext_test_library.cpp \
+
+libdlext_test_ldflags := \
+    -Wl,-z,relro \
+
+module := libdlext_test
+module_tag := optional
+build_type := target
+build_target := SHARED_LIBRARY
+include $(TEST_PATH)/Android.build.mk
+
+# -----------------------------------------------------------------------------
+# create symlink to libdlext_test.so for symlink test
+# -----------------------------------------------------------------------------
+# Use = instead of := to defer the evaluation of $@
+$(LOCAL_INSTALLED_MODULE): PRIVATE_POST_INSTALL_CMD = \
+    $(hide) cd $(dir $@) && ln -sf $(notdir $@) libdlext_test_v2.so
+
+ifneq ($(TARGET_2ND_ARCH),)
+# link 64 bit .so
+$(TARGET_OUT)/lib64/libdlext_test.so: PRIVATE_POST_INSTALL_CMD = \
+    $(hide) cd $(dir $@) && ln -sf $(notdir $@) libdlext_test_v2.so
+endif
+
+# -----------------------------------------------------------------------------
+# Library used by dlext tests - without GNU RELRO program header
+# -----------------------------------------------------------------------------
+libdlext_test_norelro_src_files := \
+    dlext_test_library.cpp \
+
+libdlext_test_norelro_ldflags := \
+    -Wl,-z,norelro \
+
+module := libdlext_test_norelro
+module_tag := optional
+build_type := target
+build_target := SHARED_LIBRARY
+include $(TEST_PATH)/Android.build.mk
+
+# -----------------------------------------------------------------------------
+# Library used by dlfcn tests
+# -----------------------------------------------------------------------------
+libtest_simple_src_files := \
+    dlopen_testlib_simple.cpp
+
+module := libtest_simple
+build_type := target
+build_target := SHARED_LIBRARY
+include $(TEST_PATH)/Android.build.mk
+
+
+# -----------------------------------------------------------------------------
+# Library used by atexit tests
+# -----------------------------------------------------------------------------
+
+libtest_atexit_src_files := \
+    atexit_testlib.cpp
+
+module := libtest_atexit
+build_target := SHARED_LIBRARY
+build_type := target
+include $(TEST_PATH)/Android.build.mk
+build_type := host
+include $(TEST_PATH)/Android.build.mk
+
+# -----------------------------------------------------------------------------
+# Library with weak function
+# -----------------------------------------------------------------------------
+libtest_dlsym_weak_func_src_files := \
+    dlsym_weak_function.cpp
+
+module := libtest_dlsym_weak_func
+build_target := SHARED_LIBRARY
+build_type := target
+include $(TEST_PATH)/Android.build.mk
+build_type := host
+include $(TEST_PATH)/Android.build.mk
diff --git a/tests/atexit_testlib.cpp b/tests/libs/atexit_testlib.cpp
similarity index 100%
rename from tests/atexit_testlib.cpp
rename to tests/libs/atexit_testlib.cpp
diff --git a/tests/dlext_test_library.cpp b/tests/libs/dlext_test_library.cpp
similarity index 100%
rename from tests/dlext_test_library.cpp
rename to tests/libs/dlext_test_library.cpp
diff --git a/tests/dlopen_testlib_simple.cpp b/tests/libs/dlopen_testlib_simple.cpp
similarity index 100%
rename from tests/dlopen_testlib_simple.cpp
rename to tests/libs/dlopen_testlib_simple.cpp
diff --git a/tests/libs/dlsym_weak_function.cpp b/tests/libs/dlsym_weak_function.cpp
new file mode 100644
index 0000000..e38f2b8
--- /dev/null
+++ b/tests/libs/dlsym_weak_function.cpp
@@ -0,0 +1,20 @@
+/*
+ * Copyright (C) 2014 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+extern "C" int __attribute__((weak)) weak_func() {
+  return 42;
+}
+
diff --git a/tests/empty.cpp b/tests/libs/empty.cpp
similarity index 100%
rename from tests/empty.cpp
rename to tests/libs/empty.cpp
diff --git a/tests/malloc_test.cpp b/tests/malloc_test.cpp
index 12a5ffa..6b7a28b 100644
--- a/tests/malloc_test.cpp
+++ b/tests/malloc_test.cpp
@@ -16,18 +16,28 @@
 
 #include <gtest/gtest.h>
 
+#include <limits.h>
+#include <stdint.h>
 #include <stdlib.h>
 #include <malloc.h>
+#include <unistd.h>
+
+#include "private/bionic_config.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 +47,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 +140,6 @@
     for (size_t i = 0; i < 250; i++) {
       ASSERT_EQ(0x67, ptr[i]);
     }
-
     free(ptr);
   }
 }
@@ -105,7 +157,6 @@
   for (size_t i = 0; i < 100; i++) {
     ASSERT_EQ(67, ptr[i]);
   }
-
   free(ptr);
 }
 
@@ -122,7 +173,6 @@
   for (size_t i = 0; i < 100; i++) {
     ASSERT_EQ(67, ptr[i]);
   }
-
   free(ptr);
 }
 
@@ -161,9 +211,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 +226,6 @@
   for (size_t i = 0; i < 100; i++) {
     ASSERT_EQ(0, ptr[i]);
   }
-
   free(ptr);
 }
 
@@ -192,7 +241,6 @@
   for (size_t i = 0; i < 100; i++) {
     ASSERT_EQ(0, ptr[i]);
   }
-
   free(ptr);
 }
 
@@ -230,21 +278,47 @@
   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);
-  }
+#if defined(HAVE_DEPRECATED_MALLOC_FUNCS)
+extern "C" void* pvalloc(size_t);
+extern "C" void* valloc(size_t);
+
+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));
+}
+#endif
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/string_test.cpp b/tests/string_test.cpp
index 67b3860..2ab60d7 100644
--- a/tests/string_test.cpp
+++ b/tests/string_test.cpp
@@ -17,6 +17,7 @@
 #include <gtest/gtest.h>
 
 #include <errno.h>
+#include <malloc.h>
 #include <math.h>
 #include <string.h>
 
@@ -143,9 +144,9 @@
     int max_alignment = 64;
 
     // TODO: fix the tests to not sometimes use twice their specified "MAX_LEN".
-    glob_ptr = reinterpret_cast<Character*>(valloc(2 * sizeof(Character) * MAX_LEN + max_alignment));
-    glob_ptr1 = reinterpret_cast<Character*>(valloc(2 * sizeof(Character) * MAX_LEN + max_alignment));
-    glob_ptr2 = reinterpret_cast<Character*>(valloc(2 * sizeof(Character) * MAX_LEN + max_alignment));
+    glob_ptr = reinterpret_cast<Character*>(memalign(sysconf(_SC_PAGESIZE), 2 * sizeof(Character) * MAX_LEN + max_alignment));
+    glob_ptr1 = reinterpret_cast<Character*>(memalign(sysconf(_SC_PAGESIZE), 2 * sizeof(Character) * MAX_LEN + max_alignment));
+    glob_ptr2 = reinterpret_cast<Character*>(memalign(sysconf(_SC_PAGESIZE), 2 * sizeof(Character) * MAX_LEN + max_alignment));
 
     InitLenArray();
 
@@ -789,37 +790,6 @@
   }
 }
 
-extern "C" int __memcmp16(const unsigned short *ptr1, const unsigned short *ptr2, size_t n);
-
-TEST(string, __memcmp16) {
-#if defined(__BIONIC__)
-  StringTestState<unsigned short> state(SMALL);
-
-  for (size_t i = 0; i < state.n; i++) {
-    for (size_t j = 0; j < POS_ITER; j++) {
-      state.NewIteration();
-
-      unsigned short mask = 0xffff;
-      unsigned short c1 = rand() & mask;
-      unsigned short c2 = rand() & mask;
-
-      std::fill(state.ptr1, state.ptr1 + state.MAX_LEN, c1);
-      std::fill(state.ptr2, state.ptr2 + state.MAX_LEN, c1);
-
-      int pos = (state.len[i] == 0) ? 0 : (random() % state.len[i]);
-      state.ptr2[pos] = c2;
-
-      int expected = (static_cast<unsigned short>(c1) - static_cast<unsigned short>(c2));
-      int actual = __memcmp16(state.ptr1, state.ptr2, (size_t) state.MAX_LEN);
-
-      ASSERT_EQ(signum(expected), signum(actual));
-    }
-  }
-#else // __BIONIC__
-  GTEST_LOG_(INFO) << "This test does nothing.\n";
-#endif // __BIONIC__
-}
-
 TEST(string, wmemcmp) {
   StringTestState<wchar_t> state(SMALL);
 
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));
 }