Merge "libc: ARM64: update memset/strlen/memcpy/memmove to newlib/cortex-strings"
diff --git a/README.md b/README.md
index 6f8edf4..61314b6 100644
--- a/README.md
+++ b/README.md
@@ -200,9 +200,8 @@
 
 ### Device tests
 
-    $ mma
-    $ adb remount
-    $ adb sync
+    $ mma # In $ANDROID_ROOT/bionic.
+    $ adb root && adb remount && adb sync
     $ adb shell /data/nativetest/bionic-unit-tests/bionic-unit-tests32
     $ adb shell \
         /data/nativetest/bionic-unit-tests-static/bionic-unit-tests-static32
@@ -216,9 +215,36 @@
 <https://github.com/google/googletest/blob/master/googletest/docs/AdvancedGuide.md#running-test-programs-advanced-options>,
 in particular for test isolation and parallelism (both on by default).
 
+### Device tests via CTS
+
+Most of the unit tests are executed by CTS. By default, CTS runs as
+a non-root user, so the unit tests must also pass when not run as root.
+Some tests cannot do any useful work unless run as root. In this case,
+the test should check `getuid() == 0` and do nothing otherwise (typically
+we log in this case to prevent accidents!). Obviously, if the test can be
+rewritten to not require root, that's an even better solution.
+
+Currently, the list of bionic CTS tests is generated at build time by
+running a host version of the test executable and dumping the list of
+all tests. In order for this to continue to work, all architectures must
+have the same number of tests, and the host version of the executable
+must also have the same number of tests.
+
+Running the gtests directly is orders of magnitude faster than using CTS,
+but in cases where you really have to run CTS:
+
+    $ make cts # In $ANDROID_ROOT.
+    $ adb unroot # Because real CTS doesn't run as root.
+    # This will sync any *test* changes, but not *code* changes:
+    $ cts-tradefed \
+        run singleCommand cts --skip-preconditions -m CtsBionicTestCases
+
 ### Host tests
 
 The host tests require that you have `lunch`ed either an x86 or x86_64 target.
+Note that due to ABI limitations (specifically, the size of pthread_mutex_t),
+32-bit bionic requires PIDs less than 65536. To enforce this, set /proc/sys/kernel/pid_max
+to 65536.
 
     $ ./tests/run-on-host.sh 32
     $ ./tests/run-on-host.sh 64   # For x86_64-bit *targets* only.
diff --git a/android-changes-for-ndk-developers.md b/android-changes-for-ndk-developers.md
index 8925926..5b0fe38 100644
--- a/android-changes-for-ndk-developers.md
+++ b/android-changes-for-ndk-developers.md
@@ -11,6 +11,92 @@
 and “pax-utils” for scanelf.
 
 
+## Changes to library search order
+
+We have made various fixes to library search order when resolving symbols.
+
+With API 22, load order switched from depth-first to breadth-first to
+fix dlsym(3).
+
+Before API 23, the default search order was to try the main executable,
+LD_PRELOAD libraries, the library itself, and its DT_NEEDED libraries
+in that order. For API 23 and later, for any given library, the dynamic
+linker divides other libraries into the global group and the local
+group. The global group is shared by all libraries and contains the main
+executable, LD_PRELOAD libraries, and any library with the DF_1_GLOBAL
+flag set (by passing “-z global” to ld(1)). The local group is
+the breadth-first transitive closure of the library and its DT_NEEDED
+libraries. The M dynamic linker searches the global group followed by
+the local group. This allows ASAN, for example, to ensure that it can
+intercept any symbol.
+
+
+## RTLD_LOCAL (Available in API level >= 23)
+
+The dlopen(3) RTLD_LOCAL flag used to be ignored but is implemented
+correctly in API 23 and later. Note that RTLD_LOCAL is the default,
+so even calls to dlopen(3) that didn’t explicitly use RTLD_LOCAL will
+be affected (unless they explicitly used RTLD_GLOBAL). With RTLD_LOCAL,
+symbols will not be made available to libraries loaded by later calls
+to dlopen(3) (as opposed to being referenced by DT_NEEDED entries).
+
+
+## GNU hashes (Availible in API level >= 23)
+
+The GNU hash style available with --hash-style=gnu allows faster
+symbol lookup and is now supported by the dynamic linker in API 23 and
+above. (Use --hash-style=both if you want to build code that uses this
+feature >= Android M but still works on older releases.)
+
+
+## Correct soname/path handling (Available in API level >= 23)
+
+The dynamic linker now understands the difference
+between a library’s soname and its path  (public bug
+https://code.google.com/p/android/issues/detail?id=6670). API level 23
+is the first release where search by soname is implemented. Earlier
+releases would assume that the basename of the library was the soname,
+and used that to search for already-loaded libraries. For example,
+`dlopen("/this/directory/does/not/exist/libc.so", RTLD_NOW)` would
+find `/system/lib/libc.so` because it’s already loaded. This also meant
+that it was impossible to have two libraries `"dir1/libx.so"` and
+`"dir2/libx.so"` --- the dynamic linker couldn’t tell the difference
+and would always use whichever was loaded first, even if you explicitly
+tried to load both. This also applied to DT_NEEDED entries.
+
+Some apps have bad DT_NEEDED entries (usually absolute paths on the build
+machine’s file system) that used to work because we ignored everything
+but the basename. These apps will fail to load on API level 23 and above.
+
+
+## Symbol versioning (Available in API level >= 23)
+
+Symbol versioning allows libraries to provide better backwards
+compatibility. For example, if a library author knowingly changes
+the behavior of a function, they can provide two versions in the same
+library so that old code gets the old version and new code gets the new
+version. This is supported in API level 23 and above.
+
+
+## Opening shared libraries directly from an APK
+
+In API level 23 and above, it’s possible to open a .so file directly from
+your APK. Just use `System.loadLibrary("foo")` exactly as normal but set
+`android:extractNativeLibs="false"` in your `AndroidManifest.xml`. In
+older releases, the .so files were extracted from the APK file
+at install time. This meant that they took up space in your APK and
+again in your installation directory (and this was counted against you
+and reported to the user as space taken up by your app). Any .so file
+that you want to load directly from your APK must be page aligned
+(on a 4096-byte boundary) in the zip file and stored uncompressed.
+Current versions of the zipalign tool take care of alignment.
+
+Note that in API level 23 and above dlopen(3) will open a library from
+any zip file, not just your APK. Just give dlopen(3) a path of the form
+"my_zip_file.zip!/libs/libstuff.so". As with APKs, the library must be
+page-aligned and stored uncompressed for this to work.
+
+
 ## Private API (Enforced for API level >= 24)
 
 Native libraries must use only public API, and must not link against
@@ -204,7 +290,7 @@
 the -soname linker option).
 
 
-## Writable and Executable Segments (AOSP master)
+## Writable and Executable Segments (Enforced for API level >= 26)
 
 Each segment in an ELF file has associated flags that tell the
 dynamic linker what permissions to give the corresponding page in
@@ -222,15 +308,16 @@
 into your app. The middleware vendor is aware of the problem and has a fix
 available.
 
-## Invalid ELF header/section headers (AOSP master)
+## Invalid ELF header/section headers (Enforced for API level >= 26)
 
-Android loader now checks for invalid values in ELF header and section headers and fails
-if they are invalid.
+In API level 26 and above the dynamic linker checks more values in
+the ELF header and section headers and fails if they are invalid.
 
 *Example error*
+```
 dlopen failed: "/data/data/com.example.bad/lib.so" has unsupported e_shentsize: 0x0 (expected 0x28)
+```
 
-*Resolution*
-Do not use tools that produce invalid/malformed elf-files. Note that using them puts application
-under high risk of being incompatible with future versions of Android.
-
+*Resolution*: don't use tools that produce invalid/malformed
+ELF files. Note that using them puts application under high risk of
+being incompatible with future versions of Android.
diff --git a/libc/Android.bp b/libc/Android.bp
index 2981e13..3f7e94c 100644
--- a/libc/Android.bp
+++ b/libc/Android.bp
@@ -4,7 +4,6 @@
     "bionic/ether_aton.c",
     "bionic/ether_ntoa.c",
     "bionic/fts.c",
-    "bionic/getpriority.c",
     "bionic/initgroups.c",
     "bionic/isatty.c",
     "bionic/pututline.c",
@@ -55,6 +54,7 @@
 // ========================================================
 cc_defaults {
     name: "libc_defaults",
+    defaults: ["linux_bionic_supported"],
     cflags: libc_common_flags,
     asflags: libc_common_flags,
     conlyflags: ["-std=gnu99"],
@@ -779,7 +779,6 @@
                 "arch-arm/generic/bionic/strcpy.S",
                 "arch-arm/generic/bionic/strlen.c",
 
-                "arch-arm/bionic/abort_arm.S",
                 "arch-arm/bionic/atomics_arm.c",
                 "arch-arm/bionic/__bionic_clone.S",
                 "arch-arm/bionic/_exit_with_stack_teardown.S",
@@ -796,14 +795,14 @@
             cortex_a7: {
                 srcs: [
                     "arch-arm/cortex-a7/bionic/memset.S",
+                    "arch-arm/cortex-a7/bionic/memcpy.S",
+                    "arch-arm/cortex-a7/bionic/__strcat_chk.S",
+                    "arch-arm/cortex-a7/bionic/__strcpy_chk.S",
 
-                    "arch-arm/cortex-a15/bionic/memcpy.S",
                     "arch-arm/cortex-a15/bionic/stpcpy.S",
                     "arch-arm/cortex-a15/bionic/strcat.S",
-                    "arch-arm/cortex-a15/bionic/__strcat_chk.S",
                     "arch-arm/cortex-a15/bionic/strcmp.S",
                     "arch-arm/cortex-a15/bionic/strcpy.S",
-                    "arch-arm/cortex-a15/bionic/__strcpy_chk.S",
                     "arch-arm/cortex-a15/bionic/strlen.S",
 
                     "arch-arm/denver/bionic/memmove.S",
@@ -1264,12 +1263,14 @@
         "bionic/getpagesize.cpp",
         "bionic/getpgrp.cpp",
         "bionic/getpid.cpp",
+        "bionic/getpriority.cpp",
         "bionic/gettid.cpp",
         "bionic/__gnu_basename.cpp",
         "bionic/grp_pwd.cpp",
         "bionic/ifaddrs.cpp",
         "bionic/inotify_init.cpp",
         "bionic/ioctl.cpp",
+        "bionic/langinfo.cpp",
         "bionic/lchown.cpp",
         "bionic/lfs64_support.cpp",
         "bionic/__libc_current_sigrtmax.cpp",
@@ -1585,10 +1586,9 @@
 // dynamic linker.
 
 cc_library_static {
+    name: "libc_nomalloc",
+
     defaults: ["libc_defaults"],
-    srcs: [
-        "bionic/dl_iterate_phdr_static.cpp",
-    ],
 
     arch: {
         arm: {
@@ -1598,8 +1598,6 @@
 
     cflags: ["-DLIBC_STATIC"],
 
-    name: "libc_nomalloc",
-
     whole_static_libs: [
         "libc_common",
         "libc_init_static",
@@ -1631,6 +1629,7 @@
     static: {
         srcs: [
             "bionic/dl_iterate_phdr_static.cpp",
+            "bionic/icu_static.cpp",
             "bionic/malloc_common.cpp",
             "bionic/libc_init_static.cpp",
         ],
@@ -1641,6 +1640,7 @@
         srcs: [
             "arch-common/bionic/crtbegin_so.c",
             "arch-common/bionic/crtbrand.S",
+            "bionic/icu.cpp",
             "bionic/malloc_common.cpp",
             "bionic/libc_init_dynamic.cpp",
             "bionic/NetdClient.cpp",
@@ -1778,6 +1778,7 @@
 
 cc_defaults {
     name: "crt_defaults",
+    defaults: ["linux_bionic_supported"],
 
     no_default_compiler_flags: true,
 
@@ -2012,10 +2013,21 @@
 // }
 
 ndk_headers {
-    name: "libc_linux",
-    from: "kernel/uapi/linux",
-    to: "linux",
-    srcs: ["kernel/uapi/linux/**/*.h"],
+    name: "libc_uapi",
+    from: "kernel/uapi",
+    to: "",
+    srcs: [
+        "kernel/uapi/asm-generic/**/*.h",
+        "kernel/uapi/drm/**/*.h",
+        "kernel/uapi/linux/**/*.h",
+        "kernel/uapi/misc/**/*.h",
+        "kernel/uapi/mtd/**/*.h",
+        "kernel/uapi/rdma/**/*.h",
+        "kernel/uapi/scsi/**/*.h",
+        "kernel/uapi/sound/**/*.h",
+        "kernel/uapi/video/**/*.h",
+        "kernel/uapi/xen/**/*.h",
+    ],
     license: "NOTICE",
 }
 
@@ -2028,14 +2040,6 @@
 }
 
 ndk_headers {
-    name: "libc_asm_generic",
-    from: "kernel/uapi/asm-generic",
-    to: "asm-generic",
-    srcs: ["kernel/uapi/asm-generic/**/*.h"],
-    license: "NOTICE",
-}
-
-ndk_headers {
     name: "libc_asm_arm",
     from: "kernel/uapi/asm-arm",
     to: "arm-linux-androideabi",
diff --git a/libc/NOTICE b/libc/NOTICE
index 266dda0..fd6cee6 100644
--- a/libc/NOTICE
+++ b/libc/NOTICE
@@ -3415,31 +3415,6 @@
 
 -------------------------------------------------------------------
 
-Copyright (c) 2002 Marc Espie.
-
-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.
-
-THIS SOFTWARE IS PROVIDED BY THE OPENBSD PROJECT 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 OPENBSD
-PROJECT 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.
-
--------------------------------------------------------------------
-
 Copyright (c) 2002 The NetBSD Foundation, Inc.
 All rights reserved.
 
diff --git a/libc/SYSCALLS.TXT b/libc/SYSCALLS.TXT
index 42c8f01..f98cc61 100644
--- a/libc/SYSCALLS.TXT
+++ b/libc/SYSCALLS.TXT
@@ -62,8 +62,8 @@
 
 # <sys/resource.h>
 int getrusage(int, struct rusage*)  all
-int __getpriority:getpriority(int, int)  all
-int setpriority(int, int, int)   all
+int __getpriority:getpriority(int, id_t)  all
+int setpriority(int, id_t, int)   all
 # On LP64, rlimit and rlimit64 are the same.
 # On 32-bit systems we use prlimit64 to implement the rlimit64 functions.
 int getrlimit:ugetrlimit(int, struct rlimit*)  arm,x86
@@ -117,8 +117,8 @@
 int         munlockall()   all
 int         mincore(void*  start, size_t  length, unsigned char*  vec)   all
 int         __ioctl:ioctl(int, int, void*)  all
-int         readv(int, const struct iovec*, int)   all
-int         writev(int, const struct iovec*, int)  all
+ssize_t     readv(int, const struct iovec*, int)   all
+ssize_t     writev(int, const struct iovec*, int)  all
 int         __fcntl64:fcntl64(int, int, void*)  arm,mips,x86
 int         fcntl(int, int, void*)  arm64,mips64,x86_64
 int         flock(int, int)   all
diff --git a/libc/arch-arm/bionic/abort_arm.S b/libc/arch-arm/bionic/abort_arm.S
deleted file mode 100644
index 1039502..0000000
--- a/libc/arch-arm/bionic/abort_arm.S
+++ /dev/null
@@ -1,44 +0,0 @@
-/*
- * Copyright (C) 2012 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>
-
-/*
- * Coding the abort function in assembly so that registers are guaranteed to
- * be preserved properly regardless of GCC's assumption on the "noreturn"
- * attribute. When the registers are not properly preserved we won't be able
- * to unwind the stack all the way to the bottom to fully reveal the call
- * sequence when the crash happens.
- */
-ENTRY(abort)
-    stmfd   sp!, {r3, r14}
-    .cfi_def_cfa_offset 8
-    .cfi_rel_offset r3, 0
-    .cfi_rel_offset r14, 4
-    bl      __libc_android_abort
-END(abort)
diff --git a/libc/arch-arm/cortex-a7/bionic/__strcat_chk.S b/libc/arch-arm/cortex-a7/bionic/__strcat_chk.S
new file mode 100644
index 0000000..da40f6c
--- /dev/null
+++ b/libc/arch-arm/cortex-a7/bionic/__strcat_chk.S
@@ -0,0 +1,199 @@
+/*
+ * Copyright (C) 2013 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>
+
+    .syntax unified
+
+    .thumb
+    .thumb_func
+
+// Get the length of src string, then get the source of the dst string.
+// Check that the two lengths together don't exceed the threshold, then
+// do a memcpy of the data.
+ENTRY(__strcat_chk)
+    pld     [r0, #0]
+    push    {r0, lr}
+    .cfi_def_cfa_offset 8
+    .cfi_rel_offset r0, 0
+    .cfi_rel_offset lr, 4
+    push    {r4, r5}
+    .cfi_adjust_cfa_offset 8
+    .cfi_rel_offset r4, 0
+    .cfi_rel_offset r5, 4
+
+    mov     lr, r2
+
+    // Save the dst register to r5
+    mov     r5, r0
+
+    // Zero out r4
+    eor     r4, r4, r4
+
+    // r1 contains the address of the string to count.
+.L_strlen_start:
+    mov     r0, r1
+    ands    r3, r1, #7
+    beq     .L_mainloop
+
+    // Align to a double word (64 bits).
+    rsb     r3, r3, #8
+    lsls    ip, r3, #31
+    beq     .L_align_to_32
+
+    ldrb    r2, [r1], #1
+    cbz     r2, .L_update_count_and_finish
+
+.L_align_to_32:
+    bcc     .L_align_to_64
+    ands    ip, r3, #2
+    beq     .L_align_to_64
+
+    ldrb    r2, [r1], #1
+    cbz     r2, .L_update_count_and_finish
+    ldrb    r2, [r1], #1
+    cbz     r2, .L_update_count_and_finish
+
+.L_align_to_64:
+    tst     r3, #4
+    beq     .L_mainloop
+    ldr     r3, [r1], #4
+
+    sub     ip, r3, #0x01010101
+    bic     ip, ip, r3
+    ands    ip, ip, #0x80808080
+    bne     .L_zero_in_second_register
+
+    .p2align 2
+.L_mainloop:
+    ldrd    r2, r3, [r1], #8
+
+    pld     [r1, #64]
+
+    sub     ip, r2, #0x01010101
+    bic     ip, ip, r2
+    ands    ip, ip, #0x80808080
+    bne     .L_zero_in_first_register
+
+    sub     ip, r3, #0x01010101
+    bic     ip, ip, r3
+    ands    ip, ip, #0x80808080
+    bne     .L_zero_in_second_register
+    b       .L_mainloop
+
+.L_update_count_and_finish:
+    sub     r3, r1, r0
+    sub     r3, r3, #1
+    b       .L_finish
+
+.L_zero_in_first_register:
+    sub     r3, r1, r0
+    lsls    r2, ip, #17
+    bne     .L_sub8_and_finish
+    bcs     .L_sub7_and_finish
+    lsls    ip, ip, #1
+    bne     .L_sub6_and_finish
+
+    sub     r3, r3, #5
+    b       .L_finish
+
+.L_sub8_and_finish:
+    sub     r3, r3, #8
+    b       .L_finish
+
+.L_sub7_and_finish:
+    sub     r3, r3, #7
+    b       .L_finish
+
+.L_sub6_and_finish:
+    sub     r3, r3, #6
+    b       .L_finish
+
+.L_zero_in_second_register:
+    sub     r3, r1, r0
+    lsls    r2, ip, #17
+    bne     .L_sub4_and_finish
+    bcs     .L_sub3_and_finish
+    lsls    ip, ip, #1
+    bne     .L_sub2_and_finish
+
+    sub     r3, r3, #1
+    b       .L_finish
+
+.L_sub4_and_finish:
+    sub     r3, r3, #4
+    b       .L_finish
+
+.L_sub3_and_finish:
+    sub     r3, r3, #3
+    b       .L_finish
+
+.L_sub2_and_finish:
+    sub     r3, r3, #2
+
+.L_finish:
+    cmp     r4, #0
+    bne     .L_strlen_done
+
+    // Time to get the dst string length.
+    mov     r1, r5
+
+    // Save the original source address to r5.
+    mov     r5, r0
+
+    // Save the current length (adding 1 for the terminator).
+    add     r4, r3, #1
+    b       .L_strlen_start
+
+    // r0 holds the pointer to the dst string.
+    // r3 holds the dst string length.
+    // r4 holds the src string length + 1.
+.L_strlen_done:
+    add     r2, r3, r4
+    cmp     r2, lr
+    itt     hi
+    movhi   r0, lr
+    bhi     __strcat_chk_fail
+
+    // Set up the registers for the memcpy code.
+    mov     r1, r5
+    pld     [r1, #64]
+    mov     r2, r4
+    add     r0, r0, r3
+    pop     {r4, r5}
+    .cfi_adjust_cfa_offset -8
+    .cfi_restore r4
+    .cfi_restore r5
+
+#include "memcpy_base.S"
+
+    // Undo the above cfi directives
+    .cfi_adjust_cfa_offset 8
+    .cfi_rel_offset r4, 0
+    .cfi_rel_offset r5, 4
+END(__strcat_chk)
diff --git a/libc/arch-arm/cortex-a7/bionic/__strcpy_chk.S b/libc/arch-arm/cortex-a7/bionic/__strcpy_chk.S
new file mode 100644
index 0000000..026adcc
--- /dev/null
+++ b/libc/arch-arm/cortex-a7/bionic/__strcpy_chk.S
@@ -0,0 +1,161 @@
+/*
+ * Copyright (C) 2013 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>
+
+    .syntax unified
+
+    .thumb
+    .thumb_func
+
+// Get the length of the source string first, then do a memcpy of the data
+// instead of a strcpy.
+ENTRY(__strcpy_chk)
+    pld     [r0, #0]
+    push    {r0, lr}
+    .cfi_def_cfa_offset 8
+    .cfi_rel_offset r0, 0
+    .cfi_rel_offset lr, 4
+
+    mov     lr, r2
+    mov     r0, r1
+
+    ands    r3, r1, #7
+    beq     .L_mainloop
+
+    // Align to a double word (64 bits).
+    rsb     r3, r3, #8
+    lsls    ip, r3, #31
+    beq     .L_align_to_32
+
+    ldrb    r2, [r0], #1
+    cbz     r2, .L_update_count_and_finish
+
+.L_align_to_32:
+    bcc     .L_align_to_64
+    ands    ip, r3, #2
+    beq     .L_align_to_64
+
+    ldrb    r2, [r0], #1
+    cbz     r2, .L_update_count_and_finish
+    ldrb    r2, [r0], #1
+    cbz     r2, .L_update_count_and_finish
+
+.L_align_to_64:
+    tst     r3, #4
+    beq     .L_mainloop
+    ldr     r3, [r0], #4
+
+    sub     ip, r3, #0x01010101
+    bic     ip, ip, r3
+    ands    ip, ip, #0x80808080
+    bne     .L_zero_in_second_register
+
+    .p2align 2
+.L_mainloop:
+    ldrd    r2, r3, [r0], #8
+
+    pld     [r0, #64]
+
+    sub     ip, r2, #0x01010101
+    bic     ip, ip, r2
+    ands    ip, ip, #0x80808080
+    bne     .L_zero_in_first_register
+
+    sub     ip, r3, #0x01010101
+    bic     ip, ip, r3
+    ands    ip, ip, #0x80808080
+    bne     .L_zero_in_second_register
+    b       .L_mainloop
+
+.L_update_count_and_finish:
+    sub     r3, r0, r1
+    sub     r3, r3, #1
+    b       .L_check_size
+
+.L_zero_in_first_register:
+    sub     r3, r0, r1
+    lsls    r2, ip, #17
+    bne     .L_sub8_and_finish
+    bcs     .L_sub7_and_finish
+    lsls    ip, ip, #1
+    bne     .L_sub6_and_finish
+
+    sub     r3, r3, #5
+    b       .L_check_size
+
+.L_sub8_and_finish:
+    sub     r3, r3, #8
+    b       .L_check_size
+
+.L_sub7_and_finish:
+    sub     r3, r3, #7
+    b       .L_check_size
+
+.L_sub6_and_finish:
+    sub     r3, r3, #6
+    b       .L_check_size
+
+.L_zero_in_second_register:
+    sub     r3, r0, r1
+    lsls    r2, ip, #17
+    bne     .L_sub4_and_finish
+    bcs     .L_sub3_and_finish
+    lsls    ip, ip, #1
+    bne     .L_sub2_and_finish
+
+    sub     r3, r3, #1
+    b       .L_check_size
+
+.L_sub4_and_finish:
+    sub     r3, r3, #4
+    b       .L_check_size
+
+.L_sub3_and_finish:
+    sub     r3, r3, #3
+    b       .L_check_size
+
+.L_sub2_and_finish:
+    sub     r3, r3, #2
+
+.L_check_size:
+    pld     [r1, #0]
+    pld     [r1, #64]
+    ldr     r0, [sp]
+
+    // Add 1 for copy length to get the string terminator.
+    add     r2, r3, #1
+
+    cmp     r2, lr
+    itt     hi
+    movhi   r0, r2
+    bhi     __strcpy_chk_fail
+
+#include "memcpy_base.S"
+
+END(__strcpy_chk)
diff --git a/libc/arch-arm/cortex-a7/bionic/memcpy.S b/libc/arch-arm/cortex-a7/bionic/memcpy.S
new file mode 100644
index 0000000..9407a08
--- /dev/null
+++ b/libc/arch-arm/cortex-a7/bionic/memcpy.S
@@ -0,0 +1,82 @@
+/*
+ * 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.
+ */
+/*
+ * Copyright (c) 2013 ARM Ltd
+ * 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. The name of the company may not be used to endorse or promote
+ *    products derived from this software without specific prior written
+ *    permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY ARM LTD ``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 ARM LTD 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>
+
+        .text
+        .syntax unified
+        .fpu    neon
+
+ENTRY(__memcpy_chk)
+        cmp r2, r3
+        bls memcpy
+
+        // Preserve lr for backtrace.
+        push        {lr}
+        .cfi_def_cfa_offset 4
+        .cfi_rel_offset lr, 0
+        bl          __memcpy_chk_fail
+END(__memcpy_chk)
+
+// Prototype: void *memcpy (void *dst, const void *src, size_t count).
+ENTRY(memcpy)
+        pld     [r1, #64]
+        push    {r0, lr}
+        .cfi_def_cfa_offset 8
+        .cfi_rel_offset r0, 0
+        .cfi_rel_offset lr, 4
+
+#include "memcpy_base.S"
+END(memcpy)
diff --git a/libc/arch-arm/cortex-a7/bionic/memcpy_base.S b/libc/arch-arm/cortex-a7/bionic/memcpy_base.S
new file mode 100644
index 0000000..1d152bb
--- /dev/null
+++ b/libc/arch-arm/cortex-a7/bionic/memcpy_base.S
@@ -0,0 +1,154 @@
+/*
+ * 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.
+ */
+/*
+ * Copyright (c) 2013 ARM Ltd
+ * 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. The name of the company may not be used to endorse or promote
+ *    products derived from this software without specific prior written
+ *    permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY ARM LTD ``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 ARM LTD 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.
+ */
+
+.L_memcpy_base:
+        // Assumes that n >= 0, and dst, src are valid pointers.
+        // For any sizes less than 832 use the neon code that doesn't
+        // care about the src alignment. This avoids any checks
+        // for src alignment, and offers the best improvement since
+        // smaller sized copies are dominated by the overhead of
+        // the pre and post main loop.
+        // For larger copies, if src and dst cannot both be aligned to
+        // word boundaries, use the neon code.
+        // For all other copies, align dst to a double word boundary
+        // and copy using LDRD/STRD instructions.
+
+        cmp     r2, #16
+        blo     .L_copy_less_than_16_unknown_align
+
+.L_copy_unknown_alignment:
+        // Unknown alignment of src and dst.
+        // Assumes that the first few bytes have already been prefetched.
+
+        // Align destination to 128 bits. The mainloop store instructions
+        // require this alignment or they will throw an exception.
+        rsb         r3, r0, #0
+        ands        r3, r3, #0xF
+        beq         2f
+
+        // Copy up to 15 bytes (count in r3).
+        sub         r2, r2, r3
+        movs        ip, r3, lsl #31
+
+        itt         mi
+        ldrbmi      lr, [r1], #1
+        strbmi      lr, [r0], #1
+        itttt       cs
+        ldrbcs      ip, [r1], #1
+        ldrbcs      lr, [r1], #1
+        strbcs      ip, [r0], #1
+        strbcs      lr, [r0], #1
+
+        movs        ip, r3, lsl #29
+        bge         1f
+        // Copies 4 bytes, dst 32 bits aligned before, at least 64 bits after.
+        vld4.8      {d0[0], d1[0], d2[0], d3[0]}, [r1]!
+        vst4.8      {d0[0], d1[0], d2[0], d3[0]}, [r0, :32]!
+1:      bcc         2f
+        // Copies 8 bytes, dst 64 bits aligned before, at least 128 bits after.
+        vld1.8      {d0}, [r1]!
+        vst1.8      {d0}, [r0, :64]!
+
+2:      // Make sure we have at least 64 bytes to copy.
+        subs        r2, r2, #64
+        blo         2f
+
+1:      // The main loop copies 64 bytes at a time.
+        vld1.8      {d0  - d3},   [r1]!
+        vld1.8      {d4  - d7},   [r1]!
+        pld         [r1, #(64*4)]
+        subs        r2, r2, #64
+        vst1.8      {d0  - d3},   [r0, :128]!
+        vst1.8      {d4  - d7},   [r0, :128]!
+        bhs         1b
+
+2:      // Fix-up the remaining count and make sure we have >= 32 bytes left.
+        adds        r2, r2, #32
+        blo         3f
+
+        // 32 bytes. These cache lines were already preloaded.
+        vld1.8      {d0 - d3},  [r1]!
+        sub         r2, r2, #32
+        vst1.8      {d0 - d3},  [r0, :128]!
+3:      // Less than 32 left.
+        add         r2, r2, #32
+        tst         r2, #0x10
+        beq         .L_copy_less_than_16_unknown_align
+        // Copies 16 bytes, destination 128 bits aligned.
+        vld1.8      {d0, d1}, [r1]!
+        vst1.8      {d0, d1}, [r0, :128]!
+
+.L_copy_less_than_16_unknown_align:
+        // Copy up to 15 bytes (count in r2).
+        movs        ip, r2, lsl #29
+        bcc         1f
+        vld1.8      {d0}, [r1]!
+        vst1.8      {d0}, [r0]!
+1:      bge         2f
+        vld4.8      {d0[0], d1[0], d2[0], d3[0]}, [r1]!
+        vst4.8      {d0[0], d1[0], d2[0], d3[0]}, [r0]!
+
+2:      // Copy 0 to 4 bytes.
+        lsls        r2, r2, #31
+        itt         ne
+        ldrbne      lr, [r1], #1
+        strbne      lr, [r0], #1
+        itttt       cs
+        ldrbcs      ip, [r1], #1
+        ldrbcs      lr, [r1]
+        strbcs      ip, [r0], #1
+        strbcs      lr, [r0]
+
+        pop         {r0, pc}
diff --git a/libc/bionic/abort.cpp b/libc/bionic/abort.cpp
index 75413c6..9aefd44 100644
--- a/libc/bionic/abort.cpp
+++ b/libc/bionic/abort.cpp
@@ -31,12 +31,9 @@
 #include <stdlib.h>
 #include <unistd.h>
 
-#ifdef __arm__
-extern "C" __LIBC_HIDDEN__ void __libc_android_abort()
-#else
-void abort()
-#endif
-{
+extern "C" int tgkill(int tgid, int tid, int sig);
+
+void abort() {
   // Don't block SIGABRT to give any signal handler a chance; we ignore
   // any errors -- X311J doesn't allow abort to return anyway.
   sigset_t mask;
@@ -44,7 +41,7 @@
   sigdelset(&mask, SIGABRT);
   sigprocmask(SIG_SETMASK, &mask, NULL);
 
-  raise(SIGABRT);
+  tgkill(getpid(), gettid(), SIGABRT);
 
   // If SIGABRT ignored, or caught and the handler returns,
   // remove the SIGABRT signal handler and raise SIGABRT again.
@@ -54,6 +51,9 @@
   sigemptyset(&sa.sa_mask);
   sigaction(SIGABRT, &sa, &sa);
   sigprocmask(SIG_SETMASK, &mask, NULL);
-  raise(SIGABRT);
-  _exit(1);
+
+  tgkill(getpid(), gettid(), SIGABRT);
+
+  // If we get this far, just exit.
+  _exit(127);
 }
diff --git a/libc/bionic/bionic_arc4random.cpp b/libc/bionic/bionic_arc4random.cpp
index 429ff7f..ba3b4e1 100644
--- a/libc/bionic/bionic_arc4random.cpp
+++ b/libc/bionic/bionic_arc4random.cpp
@@ -29,6 +29,7 @@
 #include "private/bionic_arc4random.h"
 
 #include <errno.h>
+#include <stdatomic.h>
 #include <stdlib.h>
 #include <sys/auxv.h>
 #include <syscall.h>
@@ -37,16 +38,20 @@
 #include "private/KernelArgumentBlock.h"
 #include "private/libc_logging.h"
 
-void __libc_safe_arc4random_buf(void* buf, size_t n, KernelArgumentBlock& args) {
-  static bool have_getrandom = syscall(SYS_getrandom, nullptr, 0, 0) != -1 || errno != ENOSYS;
+bool __libc_arc4random_has_unlimited_entropy() {
   static bool have_urandom = access("/dev/urandom", R_OK) == 0;
-  static size_t at_random_bytes_consumed = 0;
+  return have_urandom;
+}
 
-  if (have_getrandom || have_urandom) {
+void __libc_safe_arc4random_buf(void* buf, size_t n, KernelArgumentBlock& args) {
+  // Only call arc4random_buf once we `have_urandom', since in getentropy_getrandom we may fallback
+  // to use /dev/urandom, if the kernel entropy pool hasn't been initialized or not enough bytes
+  if (__libc_arc4random_has_unlimited_entropy()) {
     arc4random_buf(buf, n);
     return;
   }
 
+  static size_t at_random_bytes_consumed = 0;
   if (at_random_bytes_consumed + n > 16) {
     __libc_fatal("ran out of AT_RANDOM bytes, have %zu, requested %zu",
                  16 - at_random_bytes_consumed, n);
diff --git a/libc/bionic/getentropy_linux.c b/libc/bionic/getentropy_linux.c
index 98fb6fb..cf0aa45 100644
--- a/libc/bionic/getentropy_linux.c
+++ b/libc/bionic/getentropy_linux.c
@@ -102,7 +102,7 @@
 	ret = getentropy_getrandom(buf, len);
 	if (ret != -1)
 		return (ret);
-	if (errno != ENOSYS)
+	if (errno != ENOSYS && errno != EAGAIN)
 		return (-1);
 
 	/*
@@ -200,7 +200,11 @@
 	if (len > 256)
 		return (-1);
 	do {
-		ret = syscall(SYS_getrandom, buf, len, 0);
+		/*
+		 * Use GRND_NONBLOCK to avoid blocking before the
+		 * entropy pool has been initialized
+		 */
+		ret = syscall(SYS_getrandom, buf, len, GRND_NONBLOCK);
 	} while (ret == -1 && errno == EINTR);
 
 	if ((size_t)ret != len)
diff --git a/libc/bionic/getpriority.c b/libc/bionic/getpriority.cpp
similarity index 91%
rename from libc/bionic/getpriority.c
rename to libc/bionic/getpriority.cpp
index efc9d4e..7f0eb1c 100644
--- a/libc/bionic/getpriority.c
+++ b/libc/bionic/getpriority.cpp
@@ -25,13 +25,12 @@
  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  * SUCH DAMAGE.
  */
+
 #include <sys/resource.h>
 
-extern int __getpriority(int, int);
+extern "C" int __getpriority(int, id_t);
 
-int getpriority(int which, int who)
-{
+int getpriority(int which, id_t who) {
   int result = __getpriority(which, who);
-
-  return ( result < 0 ) ? result : 20-result;
+  return (result < 0) ? result : 20-result;
 }
diff --git a/libc/bionic/icu.cpp b/libc/bionic/icu.cpp
new file mode 100644
index 0000000..abc0eec
--- /dev/null
+++ b/libc/bionic/icu.cpp
@@ -0,0 +1,99 @@
+/*
+ * Copyright (C) 2016 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/icu.h"
+
+#include <dirent.h>
+#include <dlfcn.h>
+#include <pthread.h>
+#include <stdlib.h>
+
+#include "private/libc_logging.h"
+
+// Allowed icu4c version numbers are in the range [44, 999].
+// Gingerbread's icu4c 4.4 is the minimum supported ICU version.
+static constexpr auto ICUDATA_VERSION_MIN_LENGTH = 2;
+static constexpr auto ICUDATA_VERSION_MAX_LENGTH = 3;
+static constexpr auto ICUDATA_VERSION_MIN = 44;
+
+static char g_icudata_version[ICUDATA_VERSION_MAX_LENGTH + 1];
+
+static void* g_libicuuc_handle = nullptr;
+
+static int __icu_dat_file_filter(const dirent* dirp) {
+  const char* name = dirp->d_name;
+
+  // Is the name the right length to match 'icudt(\d\d\d)l.dat'?
+  const size_t len = strlen(name);
+  if (len < 10 + ICUDATA_VERSION_MIN_LENGTH || len > 10 + ICUDATA_VERSION_MAX_LENGTH) return 0;
+
+  return !strncmp(name, "icudt", 5) && !strncmp(&name[len - 5], "l.dat", 5);
+}
+
+static bool __find_icu() {
+  dirent** namelist = nullptr;
+  int n = scandir("/system/usr/icu", &namelist, &__icu_dat_file_filter, alphasort);
+  int max_version = -1;
+  while (n--) {
+    // We prefer the latest version available.
+    int version = atoi(&namelist[n]->d_name[strlen("icudt")]);
+    if (version != 0 && version > max_version) max_version = version;
+    free(namelist[n]);
+  }
+  free(namelist);
+
+  if (max_version == -1 || max_version < ICUDATA_VERSION_MIN) {
+    __libc_write_log(ANDROID_LOG_ERROR, "bionic-icu", "couldn't find an ICU .dat file");
+    return false;
+  }
+
+  snprintf(g_icudata_version, sizeof(g_icudata_version), "_%d", max_version);
+
+  g_libicuuc_handle = dlopen("libicuuc.so", RTLD_LOCAL);
+  if (g_libicuuc_handle == nullptr) {
+    __libc_format_log(ANDROID_LOG_ERROR, "bionic-icu", "couldn't open libicuuc.so: %s", dlerror());
+    return false;
+  }
+
+  return true;
+}
+
+void* __find_icu_symbol(const char* symbol_name) {
+  static bool found_icu = __find_icu();
+  if (!found_icu) return nullptr;
+
+  char versioned_symbol_name[strlen(symbol_name) + sizeof(g_icudata_version)];
+  snprintf(versioned_symbol_name, sizeof(versioned_symbol_name), "%s%s",
+           symbol_name, g_icudata_version);
+
+  void* symbol = dlsym(g_libicuuc_handle, versioned_symbol_name);
+  if (symbol == nullptr) {
+    __libc_format_log(ANDROID_LOG_ERROR, "bionic-icu", "couldn't find %s", versioned_symbol_name);
+  }
+  return symbol;
+}
diff --git a/libc/bionic/getpriority.c b/libc/bionic/icu_static.cpp
similarity index 84%
copy from libc/bionic/getpriority.c
copy to libc/bionic/icu_static.cpp
index efc9d4e..cf24a38 100644
--- a/libc/bionic/getpriority.c
+++ b/libc/bionic/icu_static.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2008 The Android Open Source Project
+ * Copyright (C) 2016 The Android Open Source Project
  * All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
@@ -25,13 +25,10 @@
  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  * SUCH DAMAGE.
  */
-#include <sys/resource.h>
 
-extern int __getpriority(int, int);
+#include "private/icu.h"
 
-int getpriority(int which, int who)
-{
-  int result = __getpriority(which, who);
-
-  return ( result < 0 ) ? result : 20-result;
+// We don't have dlopen/dlsym for static binaries yet.
+void* __find_icu_symbol(const char*) {
+  return nullptr;
 }
diff --git a/libc/bionic/langinfo.cpp b/libc/bionic/langinfo.cpp
new file mode 100644
index 0000000..6f5057c
--- /dev/null
+++ b/libc/bionic/langinfo.cpp
@@ -0,0 +1,103 @@
+/*
+ * Copyright (C) 2016 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 <langinfo.h>
+
+#include <stdlib.h>
+
+char* nl_langinfo(nl_item item) {
+  const char* result = "";
+  switch (item) {
+    case CODESET: result = (MB_CUR_MAX == 1) ? "ASCII" : "UTF-8"; break;
+
+    case D_T_FMT: result = "%F %T %z"; break;
+    case D_FMT: result = "%F"; break;
+    case T_FMT: result = "%T"; break;
+    case T_FMT_AMPM: result = "%I:%M:%S %p"; break;
+    case AM_STR: result = "AM"; break;
+    case PM_STR: result = "PM"; break;
+    case DAY_1: result = "Sunday"; break;
+    case DAY_2: result = "Monday"; break;
+    case DAY_3: result = "Tuesday"; break;
+    case DAY_4: result = "Wednesday"; break;
+    case DAY_5: result = "Thursday"; break;
+    case DAY_6: result = "Friday"; break;
+    case DAY_7: result = "Saturday"; break;
+    case ABDAY_1: result = "Sun"; break;
+    case ABDAY_2: result = "Mon"; break;
+    case ABDAY_3: result = "Tue"; break;
+    case ABDAY_4: result = "Wed"; break;
+    case ABDAY_5: result = "Thu"; break;
+    case ABDAY_6: result = "Fri"; break;
+    case ABDAY_7: result = "Sat"; break;
+    case MON_1: result = "January"; break;
+    case MON_2: result = "February"; break;
+    case MON_3: result = "March"; break;
+    case MON_4: result = "April"; break;
+    case MON_5: result = "May"; break;
+    case MON_6: result = "June"; break;
+    case MON_7: result = "July"; break;
+    case MON_8: result = "August"; break;
+    case MON_9: result = "September"; break;
+    case MON_10: result = "October"; break;
+    case MON_11: result = "November"; break;
+    case MON_12: result = "December"; break;
+    case ABMON_1: result = "Jan"; break;
+    case ABMON_2: result = "Feb"; break;
+    case ABMON_3: result = "Mar"; break;
+    case ABMON_4: result = "Apr"; break;
+    case ABMON_5: result = "May"; break;
+    case ABMON_6: result = "Jun"; break;
+    case ABMON_7: result = "Jul"; break;
+    case ABMON_8: result = "Aug"; break;
+    case ABMON_9: result = "Sep"; break;
+    case ABMON_10: result = "Oct"; break;
+    case ABMON_11: result = "Nov"; break;
+    case ABMON_12: result = "Dec"; break;
+    case ERA: result = ""; break;
+    case ERA_D_FMT: result = ""; break;
+    case ERA_D_T_FMT: result = ""; break;
+    case ERA_T_FMT: result = ""; break;
+    case ALT_DIGITS: result = ""; break;
+
+    case RADIXCHAR: result = "."; break;
+    case THOUSEP: result = ""; break;
+
+    case YESEXPR: result = "^[yY]"; break;
+    case NOEXPR: result = "^[nN]"; break;
+
+    case CRNCYSTR: result = ""; break;
+
+    default: break;
+  }
+  return const_cast<char*>(result);
+}
+
+char* nl_langinfo_l(nl_item item, locale_t) {
+  return nl_langinfo(item);
+}
diff --git a/libc/bionic/malloc_common.cpp b/libc/bionic/malloc_common.cpp
index e050619..3fceb71 100644
--- a/libc/bionic/malloc_common.cpp
+++ b/libc/bionic/malloc_common.cpp
@@ -175,8 +175,7 @@
 static const char* DEBUG_SHARED_LIB = "libc_malloc_debug.so";
 static const char* DEBUG_MALLOC_PROPERTY_OPTIONS = "libc.debug.malloc.options";
 static const char* DEBUG_MALLOC_PROPERTY_PROGRAM = "libc.debug.malloc.program";
-static const char* DEBUG_MALLOC_PROPERTY_ENV_ENABLED = "libc.debug.malloc.env_enabled";
-static const char* DEBUG_MALLOC_ENV_ENABLE = "LIBC_DEBUG_MALLOC_ENABLE";
+static const char* DEBUG_MALLOC_ENV_OPTIONS = "LIBC_DEBUG_MALLOC_OPTIONS";
 
 static void* libc_malloc_impl_handle = nullptr;
 
@@ -309,20 +308,21 @@
 // Initializes memory allocation framework once per process.
 static void malloc_init_impl(libc_globals* globals) {
   char value[PROP_VALUE_MAX];
-  if (__system_property_get(DEBUG_MALLOC_PROPERTY_OPTIONS, value) == 0 || value[0] == '\0') {
-    return;
-  }
 
-  // Check to see if only a specific program should have debug malloc enabled.
-  if (__system_property_get(DEBUG_MALLOC_PROPERTY_PROGRAM, value) != 0 &&
-      strstr(getprogname(), value) == nullptr) {
-    return;
-  }
+  // If DEBUG_MALLOC_ENV_OPTIONS is set then it overrides the system properties.
+  const char* options = getenv(DEBUG_MALLOC_ENV_OPTIONS);
+  if (options == nullptr || options[0] == '\0') {
+    if (__system_property_get(DEBUG_MALLOC_PROPERTY_OPTIONS, value) == 0 || value[0] == '\0') {
+      return;
+    }
+    options = value;
 
-  // Check for the special environment variable instead.
-  if (__system_property_get(DEBUG_MALLOC_PROPERTY_ENV_ENABLED, value) != 0
-      && value[0] != '\0' && getenv(DEBUG_MALLOC_ENV_ENABLE) == nullptr) {
-    return;
+    // Check to see if only a specific program should have debug malloc enabled.
+    char program[PROP_VALUE_MAX];
+    if (__system_property_get(DEBUG_MALLOC_PROPERTY_PROGRAM, program) != 0 &&
+        strstr(getprogname(), program) == nullptr) {
+      return;
+    }
   }
 
   // Load the debug malloc shared library.
@@ -334,7 +334,7 @@
   }
 
   // Initialize malloc debugging in the loaded module.
-  auto init_func = reinterpret_cast<bool (*)(const MallocDispatch*, int*)>(
+  auto init_func = reinterpret_cast<bool (*)(const MallocDispatch*, int*, const char*)>(
       dlsym(malloc_impl_handle, "debug_initialize"));
   if (init_func == nullptr) {
     error_log("%s: debug_initialize routine not found in %s", getprogname(), DEBUG_SHARED_LIB);
@@ -374,7 +374,7 @@
     return;
   }
 
-  if (!init_func(&__libc_malloc_default_dispatch, &gMallocLeakZygoteChild)) {
+  if (!init_func(&__libc_malloc_default_dispatch, &gMallocLeakZygoteChild, options)) {
     dlclose(malloc_impl_handle);
     return;
   }
diff --git a/libc/bionic/pathconf.cpp b/libc/bionic/pathconf.cpp
index e6f5742..9724f44 100644
--- a/libc/bionic/pathconf.cpp
+++ b/libc/bionic/pathconf.cpp
@@ -29,7 +29,7 @@
 #include <unistd.h>
 
 #include <errno.h>
-#include <sys/limits.h>
+#include <limits.h>
 #include <sys/vfs.h>
 
 static long __filesizebits(const struct statfs& s) {
diff --git a/libc/bionic/wcstod.cpp b/libc/bionic/wcstod.cpp
index eb66ba0..f7bd433 100644
--- a/libc/bionic/wcstod.cpp
+++ b/libc/bionic/wcstod.cpp
@@ -32,8 +32,14 @@
 
 #include "local.h"
 
-template <typename float_type> float_type wcstod(const wchar_t* str, wchar_t** end,
-                                                 float_type strtod_fn(const char*, char**)) {
+/// Performs wide-character string to floating point conversion.
+template <typename float_type>
+float_type wcstod(const wchar_t* str, wchar_t** end, float_type strtod_fn(const char*, char**)) {
+  const wchar_t* original_str = str;
+  while (iswspace(*str)) {
+    str++;
+  }
+
   // What's the longest span of the input that might be part of the float?
   size_t max_len = wcsspn(str, L"-+0123456789.xXeEpP()nNaAiIfFtTyY");
 
@@ -70,7 +76,15 @@
   float_type result = strtod_fn(ascii_str, &ascii_end);
   if (ascii_end != ascii_str + actual_len) abort();
 
-  if (end) *end = const_cast<wchar_t*>(str) + actual_len;
+  if (end) {
+    if (actual_len == 0) {
+      // There was an error. We need to set the end pointer back to the original string, not the
+      // one we advanced past the leading whitespace.
+      *end = const_cast<wchar_t*>(original_str);
+    } else {
+      *end = const_cast<wchar_t*>(str) + actual_len;
+    }
+  }
 
   delete[] ascii_str;
   return result;
diff --git a/libc/bionic/wctype.cpp b/libc/bionic/wctype.cpp
index cd8c39b..77f8dde 100644
--- a/libc/bionic/wctype.cpp
+++ b/libc/bionic/wctype.cpp
@@ -34,26 +34,41 @@
 #include <string.h>
 #include <wchar.h>
 
-// These functions are either defined to be the same as their ASCII cousins,
-// or defined in terms of other functions.
-int iswalnum(wint_t wc) { return iswdigit(wc) || iswalpha(wc); }
-int iswblank(wint_t wc) { return isblank(wc); }
-int iswdigit(wint_t wc) { return isdigit(wc); }
-int iswgraph(wint_t wc) { return !iswspace(wc) && iswprint(wc); }
-int iswlower(wint_t wc) {
-  return towlower(wc) == wc && !(iswcntrl(wc) || iswdigit(wc) || iswpunct(wc) || iswspace(wc));
-}
-int iswupper(wint_t wc) {
-  return towupper(wc) == wc && !(iswcntrl(wc) || iswdigit(wc) || iswpunct(wc) || iswspace(wc));
-}
-int iswxdigit(wint_t wc) { return isxdigit(wc); }
+#include "private/icu.h"
 
-// TODO: need proper implementations of these.
-int iswalpha(wint_t wc) { return isalpha(wc); }
-int iswcntrl(wint_t wc) { return iscntrl(wc); }
-int iswprint(wint_t wc) { return isprint(wc); }
-int iswpunct(wint_t wc) { return ispunct(wc); }
-int iswspace(wint_t wc) { return isspace(wc); }
+static bool __icu_hasBinaryProperty(wint_t wc, UProperty property, int (*fallback)(int)) {
+  typedef UBool (*FnT)(UChar32, UProperty);
+  static auto u_hasBinaryProperty = reinterpret_cast<FnT>(__find_icu_symbol("u_hasBinaryProperty"));
+  return u_hasBinaryProperty ? u_hasBinaryProperty(wc, property) : fallback(wc);
+}
+
+int iswalnum(wint_t wc) { return __icu_hasBinaryProperty(wc, UCHAR_POSIX_ALNUM, isalnum); }
+int iswalpha(wint_t wc) { return __icu_hasBinaryProperty(wc, UCHAR_ALPHABETIC, isalpha); }
+int iswblank(wint_t wc) { return __icu_hasBinaryProperty(wc, UCHAR_POSIX_BLANK, isblank); }
+int iswgraph(wint_t wc) { return __icu_hasBinaryProperty(wc, UCHAR_POSIX_GRAPH, isgraph); }
+int iswlower(wint_t wc) { return __icu_hasBinaryProperty(wc, UCHAR_LOWERCASE, islower); }
+int iswprint(wint_t wc) { return __icu_hasBinaryProperty(wc, UCHAR_POSIX_PRINT, isprint); }
+int iswspace(wint_t wc) { return __icu_hasBinaryProperty(wc, UCHAR_WHITE_SPACE, isspace); }
+int iswupper(wint_t wc) { return __icu_hasBinaryProperty(wc, UCHAR_UPPERCASE, isupper); }
+int iswxdigit(wint_t wc) { return __icu_hasBinaryProperty(wc, UCHAR_POSIX_XDIGIT, isxdigit); }
+
+int iswcntrl(wint_t wc) {
+  typedef int8_t (*FnT)(UChar32);
+  static auto u_charType = reinterpret_cast<FnT>(__find_icu_symbol("u_charType"));
+  return u_charType ? (u_charType(wc) == U_CONTROL_CHAR) : iscntrl(wc);
+}
+
+int iswdigit(wint_t wc) {
+  typedef UBool (*FnT)(UChar32);
+  static auto u_isdigit = reinterpret_cast<FnT>(__find_icu_symbol("u_isdigit"));
+  return u_isdigit ? u_isdigit(wc) : isdigit(wc);
+}
+
+int iswpunct(wint_t wc) {
+  typedef UBool (*FnT)(UChar32);
+  static auto u_ispunct = reinterpret_cast<FnT>(__find_icu_symbol("u_ispunct"));
+  return u_ispunct ? u_ispunct(wc) : ispunct(wc);
+}
 
 int iswalnum_l(wint_t c, locale_t) { return iswalnum(c); }
 int iswalpha_l(wint_t c, locale_t) { return iswalpha(c); }
@@ -90,12 +105,20 @@
   return iswctype(wc, char_class);
 }
 
-// TODO: need proper implementations of these.
-wint_t towlower(wint_t wc) { return tolower(wc); }
-wint_t towupper(wint_t wc) { return toupper(wc); }
+wint_t towlower(wint_t wc) {
+  typedef UChar32 (*FnT)(UChar32);
+  static auto u_tolower = reinterpret_cast<FnT>(__find_icu_symbol("u_tolower"));
+  return u_tolower ? u_tolower(wc) : tolower(wc);
+}
 
-wint_t towupper_l(int c, locale_t) { return towupper(c); }
-wint_t towlower_l(int c, locale_t) { return towlower(c); }
+wint_t towupper(wint_t wc) {
+  typedef UChar32 (*FnT)(UChar32);
+  static auto u_toupper = reinterpret_cast<FnT>(__find_icu_symbol("u_toupper"));
+  return u_toupper ? u_toupper(wc) : toupper(wc);
+}
+
+wint_t towupper_l(wint_t c, locale_t) { return towupper(c); }
+wint_t towlower_l(wint_t c, locale_t) { return towlower(c); }
 
 wctype_t wctype(const char* property) {
   static const char* const  properties[WC_TYPE_MAX] = {
diff --git a/libc/dns/net/getaddrinfo.c b/libc/dns/net/getaddrinfo.c
index 13000f7..6c26cd3 100644
--- a/libc/dns/net/getaddrinfo.c
+++ b/libc/dns/net/getaddrinfo.c
@@ -108,10 +108,6 @@
 #include <stdarg.h>
 #include "nsswitch.h"
 
-#if defined(__BIONIC__)
-#include <sys/system_properties.h>
-#endif
-
 typedef union sockaddr_union {
     struct sockaddr     generic;
     struct sockaddr_in  in;
@@ -134,8 +130,10 @@
 };
 #endif
 
+#if defined(__ANDROID__)
 // This should be synchronized to ResponseCode.h
 static const int DnsProxyQueryResult = 222;
+#endif
 
 static const struct afd {
 	int a_af;
@@ -399,6 +397,7 @@
   return true;
 }
 
+#if defined(__ANDROID__)
 // Returns 0 on success, else returns on error.
 static int
 android_getaddrinfo_proxy(
@@ -555,6 +554,7 @@
 	}
 	return EAI_NODATA;
 }
+#endif
 
 int
 getaddrinfo(const char *hostname, const char *servname,
diff --git a/libc/dns/net/getnameinfo.c b/libc/dns/net/getnameinfo.c
index 63a347e..236e7f2 100644
--- a/libc/dns/net/getnameinfo.c
+++ b/libc/dns/net/getnameinfo.c
@@ -62,7 +62,6 @@
 #include <arpa/nameser.h>
 #include "resolv_netid.h"
 #include "resolv_private.h"
-#include <sys/system_properties.h>
 #include <stdlib.h>
 #include <unistd.h>
 #include <errno.h>
diff --git a/libc/dns/resolv/res_cache.c b/libc/dns/resolv/res_cache.c
index ad2c5c0..8b3c76b 100644
--- a/libc/dns/resolv/res_cache.c
+++ b/libc/dns/resolv/res_cache.c
@@ -38,7 +38,6 @@
 
 #include <errno.h>
 #include <arpa/nameser.h>
-#include <sys/system_properties.h>
 #include <net/if.h>
 #include <netdb.h>
 #include <linux/if.h>
@@ -137,7 +136,6 @@
  * *****************************************
  */
 #define  CONFIG_MAX_ENTRIES    64 * 2 * 5
-/* name of the system property that can be used to set the cache size */
 
 /****************************************************************************/
 /****************************************************************************/
@@ -2010,8 +2008,8 @@
             }
             cache_info->nscount = numservers;
 
-            // Flush the cache and reset the stats.
-            _flush_cache_for_net_locked(netid);
+            // Clear the NS statistics because the mapping to nameservers might have changed.
+            _res_cache_clear_stats_locked(cache_info);
 
             // increment the revision id to ensure that sample state is not written back if the
             // servers change; in theory it would suffice to do so only if the servers or
@@ -2286,4 +2284,3 @@
 
     pthread_mutex_unlock(&_res_cache_list_lock);
 }
-
diff --git a/libc/dns/resolv/res_init.c b/libc/dns/resolv/res_init.c
index a5413dd..b9fc131 100644
--- a/libc/dns/resolv/res_init.c
+++ b/libc/dns/resolv/res_init.c
@@ -101,7 +101,6 @@
 #ifdef ANDROID_CHANGES
 #include <errno.h>
 #include <fcntl.h>
-#include <sys/system_properties.h>
 #endif /* ANDROID_CHANGES */
 
 /* ensure that sockaddr_in6 and IN6ADDR_ANY_INIT are declared / defined */
diff --git a/libc/dns/resolv/res_state.c b/libc/dns/resolv/res_state.c
index 0e02a8f..4ed168c 100644
--- a/libc/dns/resolv/res_state.c
+++ b/libc/dns/resolv/res_state.c
@@ -36,8 +36,6 @@
 #include <stdlib.h>
 #include <string.h>
 
-#define _REALLY_INCLUDE_SYS__SYSTEM_PROPERTIES_H_
-#include <sys/_system_properties.h>
 
 /* Set to 1 to enable debug traces */
 #define DEBUG 0
@@ -54,8 +52,6 @@
     int                  _h_errno;
     // TODO: Have one __res_state per network so we don't have to repopulate frequently.
     struct __res_state  _nres[1];
-    unsigned             _serial;
-    struct prop_info*   _pi;
     struct res_static   _rstatic[1];
 } _res_thread;
 
@@ -66,12 +62,6 @@
 
     if (rt) {
         rt->_h_errno = 0;
-        /* Special system property which tracks any changes to 'net.*'. */
-        rt->_serial = 0;
-        rt->_pi = (struct prop_info*) __system_property_find("net.change");
-        if (rt->_pi) {
-            rt->_serial = __system_property_serial(rt->_pi);
-        }
         memset(rt->_rstatic, 0, sizeof rt->_rstatic);
     }
     return rt;
@@ -116,32 +106,7 @@
     rt = pthread_getspecific( _res_key );
 
     if (rt != NULL) {
-        /* We already have one thread-specific DNS state object.
-         * Check the serial value for any changes to net.* properties */
-        D("%s: Called for tid=%d rt=%p rt->pi=%p rt->serial=%d",
-           __FUNCTION__, gettid(), rt, rt->_pi, rt->_serial);
-        if (rt->_pi == NULL) {
-            /* The property wasn't created when _res_thread_get() was
-             * called the last time. This should only happen very
-             * early during the boot sequence. First, let's try to see if it
-             * is here now. */
-            rt->_pi = (struct prop_info*) __system_property_find("net.change");
-            if (rt->_pi == NULL) {
-                /* Still nothing, return current state */
-                D("%s: exiting for tid=%d rt=%p since system property not found",
-                  __FUNCTION__, gettid(), rt);
-                return rt;
-            }
-        }
-        if (rt->_serial == __system_property_serial(rt->_pi)) {
-            /* Nothing changed, so return the current state */
-            D("%s: tid=%d rt=%p nothing changed, returning",
-              __FUNCTION__, gettid(), rt);
-            return rt;
-        }
-        /* Update the recorded serial number, and go reset the state */
-        rt->_serial = __system_property_serial(rt->_pi);
-        goto RESET_STATE;
+        return rt;
     }
 
     /* It is the first time this function is called in this thread,
@@ -154,11 +119,10 @@
     D("%s: tid=%d Created new DNS state rt=%p",
       __FUNCTION__, gettid(), rt);
 
-RESET_STATE:
     /* Reset the state, note that res_ninit() can now properly reset
      * an existing state without leaking memory.
      */
-    D("%s: tid=%d, rt=%p, resetting DNS state (options RES_INIT=%d)",
+    D("%s: tid=%d, rt=%p, setting DNS state (options RES_INIT=%d)",
       __FUNCTION__, gettid(), rt, (rt->_nres->options & RES_INIT) != 0);
     if ( res_ninit( rt->_nres ) < 0 ) {
         /* This should not happen */
diff --git a/libc/include/langinfo.h b/libc/include/langinfo.h
new file mode 100644
index 0000000..5c884ac
--- /dev/null
+++ b/libc/include/langinfo.h
@@ -0,0 +1,100 @@
+/*
+ * Copyright (C) 2016 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 _LANGINFO_H_
+#define _LANGINFO_H_
+
+#include <sys/cdefs.h>
+
+#include <nl_types.h>
+#include <xlocale.h>
+
+__BEGIN_DECLS
+
+#define CODESET 1
+#define D_T_FMT 2
+#define D_FMT 3
+#define T_FMT 4
+#define T_FMT_AMPM 5
+#define AM_STR 6
+#define PM_STR 7
+#define DAY_1 8
+#define DAY_2 9
+#define DAY_3 10
+#define DAY_4 11
+#define DAY_5 12
+#define DAY_6 13
+#define DAY_7 14
+#define ABDAY_1 15
+#define ABDAY_2 16
+#define ABDAY_3 17
+#define ABDAY_4 18
+#define ABDAY_5 19
+#define ABDAY_6 20
+#define ABDAY_7 21
+#define MON_1 22
+#define MON_2 23
+#define MON_3 24
+#define MON_4 25
+#define MON_5 26
+#define MON_6 27
+#define MON_7 28
+#define MON_8 29
+#define MON_9 30
+#define MON_10 31
+#define MON_11 32
+#define MON_12 33
+#define ABMON_1 34
+#define ABMON_2 35
+#define ABMON_3 36
+#define ABMON_4 37
+#define ABMON_5 38
+#define ABMON_6 39
+#define ABMON_7 40
+#define ABMON_8 41
+#define ABMON_9 42
+#define ABMON_10 43
+#define ABMON_11 44
+#define ABMON_12 45
+#define ERA 46
+#define ERA_D_FMT 47
+#define ERA_D_T_FMT 48
+#define ERA_T_FMT 49
+#define ALT_DIGITS 50
+#define RADIXCHAR 51
+#define THOUSEP 52
+#define YESEXPR 53
+#define NOEXPR 54
+#define CRNCYSTR 55
+
+char* nl_langinfo(nl_item) __INTRODUCED_IN_FUTURE;
+char* nl_langinfo_l(nl_item, locale_t) __INTRODUCED_IN_FUTURE;
+
+__END_DECLS
+
+#endif
diff --git a/libc/include/limits.h b/libc/include/limits.h
index a1124b3..a25eb65 100644
--- a/libc/include/limits.h
+++ b/libc/include/limits.h
@@ -33,10 +33,15 @@
  */
 
 #ifndef _LIMITS_H_
-#define	_LIMITS_H_
+#define _LIMITS_H_
 
 #include <sys/cdefs.h>
 
+/* Historically bionic exposed the content of <float.h> from <limits.h> and <sys/limits.h> too. */
+#include <float.h>
+
+#include <linux/limits.h>
+
 #define PASS_MAX		128	/* _PASSWORD_LEN from <pwd.h> */
 
 #define NL_ARGMAX		9
@@ -48,7 +53,48 @@
 
 #define TMP_MAX                 308915776
 
-#include <sys/limits.h>
+/* TODO: get all these from the compiler's <limits.h>? */
+
+#define CHAR_BIT 8
+#ifdef __LP64__
+# define LONG_BIT 64
+#else
+# define LONG_BIT 32
+#endif
+
+#define	SCHAR_MAX	0x7f		/* max value for a signed char */
+#define SCHAR_MIN	(-0x7f-1)	/* min value for a signed char */
+
+#define	UCHAR_MAX	0xffU		/* max value for an unsigned char */
+#ifdef __CHAR_UNSIGNED__
+# define CHAR_MIN	0		/* min value for a char */
+# define CHAR_MAX	0xff		/* max value for a char */
+#else
+# define CHAR_MAX	0x7f
+# define CHAR_MIN	(-0x7f-1)
+#endif
+
+#define	USHRT_MAX	0xffffU		/* max value for an unsigned short */
+#define	SHRT_MAX	0x7fff		/* max value for a short */
+#define SHRT_MIN        (-0x7fff-1)     /* min value for a short */
+
+#define	UINT_MAX	0xffffffffU	/* max value for an unsigned int */
+#define	INT_MAX		0x7fffffff	/* max value for an int */
+#define	INT_MIN		(-0x7fffffff-1)	/* min value for an int */
+
+#ifdef __LP64__
+# define ULONG_MAX	0xffffffffffffffffUL     /* max value for unsigned long */
+# define LONG_MAX	0x7fffffffffffffffL      /* max value for a signed long */
+# define LONG_MIN	(-0x7fffffffffffffffL-1) /* min value for a signed long */
+#else
+# define ULONG_MAX	0xffffffffUL	/* max value for an unsigned long */
+# define LONG_MAX	0x7fffffffL	/* max value for a long */
+# define LONG_MIN	(-0x7fffffffL-1)/* min value for a long */
+#endif
+
+# define ULLONG_MAX	0xffffffffffffffffULL     /* max value for unsigned long long */
+# define LLONG_MAX	0x7fffffffffffffffLL      /* max value for a signed long long */
+# define LLONG_MIN	(-0x7fffffffffffffffLL-1) /* min value for a signed long long */
 
 /* GLibc compatibility definitions.
    Note that these are defined by GCC's <limits.h>
@@ -67,6 +113,8 @@
 #endif
 
 #if defined(__USE_BSD) || defined(__BIONIC__) /* Historically bionic exposed these. */
+# define UID_MAX	UINT_MAX	/* max value for a uid_t */
+# define GID_MAX	UINT_MAX	/* max value for a gid_t */
 #if defined(__LP64__)
 #define SIZE_T_MAX ULONG_MAX
 #else
@@ -89,4 +137,16 @@
 #include <bits/posix_limits.h>
 
 #define HOST_NAME_MAX _POSIX_HOST_NAME_MAX
+
+#define  _POSIX_VERSION             200809L   /* Posix C language bindings version */
+#define  _POSIX2_VERSION            -1        /* we don't support Posix command-line tools */
+#define  _XOPEN_VERSION             700       /* by Posix definition */
+
+/* >= _POSIX_THREAD_DESTRUCTOR_ITERATIONS */
+#define PTHREAD_DESTRUCTOR_ITERATIONS 4
+/* >= _POSIX_THREAD_KEYS_MAX */
+#define PTHREAD_KEYS_MAX 128
+/* bionic has no specific limit */
+#undef PTHREAD_THREADS_MAX
+
 #endif /* !_LIMITS_H_ */
diff --git a/libc/include/pwd.h b/libc/include/pwd.h
index a686d05..223fc5a 100644
--- a/libc/include/pwd.h
+++ b/libc/include/pwd.h
@@ -65,39 +65,6 @@
 
 __BEGIN_DECLS
 
-#define _PATH_PASSWD        "/etc/passwd"
-#define _PATH_MASTERPASSWD  "/etc/master.passwd"
-#define _PATH_MASTERPASSWD_LOCK "/etc/ptmp"
-
-#define _PATH_PASSWD_CONF   "/etc/passwd.conf"
-#define _PATH_PASSWDCONF    _PATH_PASSWD_CONF   /* XXX: compat */
-#define _PATH_USERMGMT_CONF "/etc/usermgmt.conf"
-
-#define _PATH_MP_DB     "/etc/pwd.db"
-#define _PATH_SMP_DB        "/etc/spwd.db"
-
-#define _PATH_PWD_MKDB      "/usr/sbin/pwd_mkdb"
-
-#define _PW_KEYBYNAME       '1' /* stored by name */
-#define _PW_KEYBYNUM        '2' /* stored by entry in the "file" */
-#define _PW_KEYBYUID        '3' /* stored by uid */
-
-#define _PASSWORD_EFMT1     '_' /* extended DES encryption format */
-#define _PASSWORD_NONDES    '$' /* non-DES encryption formats */
-
-#define _PASSWORD_LEN       128 /* max length, not counting NUL */
-
-#define _PASSWORD_NOUID     0x01    /* flag for no specified uid. */
-#define _PASSWORD_NOGID     0x02    /* flag for no specified gid. */
-#define _PASSWORD_NOCHG     0x04    /* flag for no specified change. */
-#define _PASSWORD_NOEXP     0x08    /* flag for no specified expire. */
-
-#define _PASSWORD_OLDFMT    0x10    /* flag to expect an old style entry */
-#define _PASSWORD_NOWARN    0x20    /* no warnings for bad entries */
-
-#define _PASSWORD_WARNDAYS  14  /* days to warn about expiry */
-#define _PASSWORD_CHGNOW    -1  /* special day to force password change at next login */
-
 struct passwd {
   char* pw_name;
   char* pw_passwd;
diff --git a/libc/include/sys/limits.h b/libc/include/sys/limits.h
index 60cc7f7..1e189a1 100644
--- a/libc/include/sys/limits.h
+++ b/libc/include/sys/limits.h
@@ -1,122 +1 @@
-/* $OpenBSD: limits.h,v 1.6 2005/12/13 00:35:23 millert Exp $ */
-/*
- * Copyright (c) 2002 Marc Espie.
- *
- * 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.
- *
- * THIS SOFTWARE IS PROVIDED BY THE OPENBSD PROJECT 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 OPENBSD
- * PROJECT 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_LIMITS_H_
-#define _SYS_LIMITS_H_
-
-#include <sys/cdefs.h>
-#include <linux/limits.h>
-
-/* Common definitions for limits.h. */
-
-#define	CHAR_BIT	8		/* number of bits in a char */
-
-#define	SCHAR_MAX	0x7f		/* max value for a signed char */
-#define SCHAR_MIN	(-0x7f-1)	/* min value for a signed char */
-
-#define	UCHAR_MAX	0xffU		/* max value for an unsigned char */
-#ifdef __CHAR_UNSIGNED__
-# define CHAR_MIN	0		/* min value for a char */
-# define CHAR_MAX	0xff		/* max value for a char */
-#else
-# define CHAR_MAX	0x7f
-# define CHAR_MIN	(-0x7f-1)
-#endif
-
-#define	USHRT_MAX	0xffffU		/* max value for an unsigned short */
-#define	SHRT_MAX	0x7fff		/* max value for a short */
-#define SHRT_MIN        (-0x7fff-1)     /* min value for a short */
-
-#define	UINT_MAX	0xffffffffU	/* max value for an unsigned int */
-#define	INT_MAX		0x7fffffff	/* max value for an int */
-#define	INT_MIN		(-0x7fffffff-1)	/* min value for an int */
-
-#ifdef __LP64__
-# define ULONG_MAX	0xffffffffffffffffUL
-					/* max value for unsigned long */
-# define LONG_MAX	0x7fffffffffffffffL
-					/* max value for a signed long */
-# define LONG_MIN	(-0x7fffffffffffffffL-1)
-					/* min value for a signed long */
-#else
-# define ULONG_MAX	0xffffffffUL	/* max value for an unsigned long */
-# define LONG_MAX	0x7fffffffL	/* max value for a long */
-# define LONG_MIN	(-0x7fffffffL-1)/* min value for a long */
-#endif
-
-# define ULLONG_MAX	0xffffffffffffffffULL
-					/* max value for unsigned long long */
-# define LLONG_MAX	0x7fffffffffffffffLL
-					/* max value for a signed long long */
-# define LLONG_MIN	(-0x7fffffffffffffffLL-1)
-					/* min value for a signed long long */
-
-#if defined(__USE_BSD) || defined(__BIONIC__) /* Historically bionic exposed these. */
-# define UID_MAX	UINT_MAX	/* max value for a uid_t */
-# define GID_MAX	UINT_MAX	/* max value for a gid_t */
-#endif
-
-
-#ifdef __LP64__
-# define LONG_BIT	64
-#else
-# define LONG_BIT	32
-#endif
-
-/* float.h defines these as well */
-# if !defined(DBL_DIG)
-#  if defined(__DBL_DIG)
-#   define DBL_DIG	__DBL_DIG
-#   define DBL_MAX	__DBL_MAX
-#   define DBL_MIN	__DBL_MIN
-
-#   define FLT_DIG	__FLT_DIG
-#   define FLT_MAX	__FLT_MAX
-#   define FLT_MIN	__FLT_MIN
-#  else
-#   define DBL_DIG	15
-#   define DBL_MAX	1.7976931348623157E+308
-#   define DBL_MIN	2.2250738585072014E-308
-
-#   define FLT_DIG	6
-#   define FLT_MAX	3.40282347E+38F
-#   define FLT_MIN	1.17549435E-38F
-#  endif
-# endif
-
-/* Bionic-specific definitions */
-
-#define  _POSIX_VERSION             200809L   /* Posix C language bindings version */
-#define  _POSIX2_VERSION            -1        /* we don't support Posix command-line tools */
-#define  _XOPEN_VERSION             700       /* by Posix definition */
-
-/* >= _POSIX_THREAD_DESTRUCTOR_ITERATIONS */
-#define PTHREAD_DESTRUCTOR_ITERATIONS 4
-/* >= _POSIX_THREAD_KEYS_MAX */
-#define PTHREAD_KEYS_MAX 128
-/* bionic has no specific limit */
-#undef PTHREAD_THREADS_MAX
-
-#endif
+#include <limits.h>
diff --git a/libc/include/sys/resource.h b/libc/include/sys/resource.h
index 248310e..7c43ca3 100644
--- a/libc/include/sys/resource.h
+++ b/libc/include/sys/resource.h
@@ -48,8 +48,8 @@
 int getrlimit64(int, struct rlimit64*) __INTRODUCED_IN(21);
 int setrlimit64(int, const struct rlimit64*) __INTRODUCED_IN(21);
 
-int getpriority(int, int);
-int setpriority(int, int, int);
+int getpriority(int, id_t);
+int setpriority(int, id_t, int);
 
 int getrusage(int, struct rusage*);
 
diff --git a/libc/include/sys/uio.h b/libc/include/sys/uio.h
index 7a009b4..0e56d7d 100644
--- a/libc/include/sys/uio.h
+++ b/libc/include/sys/uio.h
@@ -34,8 +34,8 @@
 
 __BEGIN_DECLS
 
-int readv(int, const struct iovec*, int);
-int writev(int, const struct iovec*, int);
+ssize_t readv(int, const struct iovec*, int);
+ssize_t writev(int, const struct iovec*, int);
 
 #if defined(__USE_GNU)
 #if defined(__USE_FILE_OFFSET64)
diff --git a/libc/include/unistd.h b/libc/include/unistd.h
index 1e239cd..cbdb438 100644
--- a/libc/include/unistd.h
+++ b/libc/include/unistd.h
@@ -148,7 +148,7 @@
 int lchown(const char* __path, uid_t __owner, gid_t __group);
 char* getcwd(char* __buf, size_t __size);
 
-int sync(void);
+void sync(void);
 
 int close(int __fd);
 
diff --git a/libc/include/wctype.h b/libc/include/wctype.h
index a0ed09a..9e22a8f 100644
--- a/libc/include/wctype.h
+++ b/libc/include/wctype.h
@@ -49,8 +49,8 @@
 int iswupper_l(wint_t, locale_t) __INTRODUCED_IN(21);
 int iswxdigit_l(wint_t, locale_t) __INTRODUCED_IN(21);
 
-wint_t towlower_l(int, locale_t) __INTRODUCED_IN(21);
-wint_t towupper_l(int, locale_t) __INTRODUCED_IN(21);
+wint_t towlower_l(wint_t, locale_t) __INTRODUCED_IN(21);
+wint_t towupper_l(wint_t, locale_t) __INTRODUCED_IN(21);
 #else
 // Implemented as static inlines before 21.
 #endif
diff --git a/libc/libc.arm.map b/libc/libc.arm.map
index eb75e8f..f9c5ede 100644
--- a/libc/libc.arm.map
+++ b/libc/libc.arm.map
@@ -1288,6 +1288,8 @@
     msgget; # future
     msgrcv; # future
     msgsnd; # future
+    nl_langinfo; # future
+    nl_langinfo_l; # future
     pthread_getname_np; # future
     quotactl; # future
     semctl; # future
diff --git a/libc/libc.arm64.map b/libc/libc.arm64.map
index 28755d4..179d8bf 100644
--- a/libc/libc.arm64.map
+++ b/libc/libc.arm64.map
@@ -1210,6 +1210,8 @@
     msgget; # future
     msgrcv; # future
     msgsnd; # future
+    nl_langinfo; # future
+    nl_langinfo_l; # future
     pthread_getname_np; # future
     quotactl; # future
     semctl; # future
diff --git a/libc/libc.map.txt b/libc/libc.map.txt
index 1fba8ee..f122937 100644
--- a/libc/libc.map.txt
+++ b/libc/libc.map.txt
@@ -1313,6 +1313,8 @@
     msgget; # future
     msgrcv; # future
     msgsnd; # future
+    nl_langinfo; # future
+    nl_langinfo_l; # future
     pthread_getname_np; # future
     quotactl; # future
     semctl; # future
diff --git a/libc/libc.mips.map b/libc/libc.mips.map
index f61f615..a969703 100644
--- a/libc/libc.mips.map
+++ b/libc/libc.mips.map
@@ -1272,6 +1272,8 @@
     msgget; # future
     msgrcv; # future
     msgsnd; # future
+    nl_langinfo; # future
+    nl_langinfo_l; # future
     pthread_getname_np; # future
     quotactl; # future
     semctl; # future
diff --git a/libc/libc.mips64.map b/libc/libc.mips64.map
index 28755d4..179d8bf 100644
--- a/libc/libc.mips64.map
+++ b/libc/libc.mips64.map
@@ -1210,6 +1210,8 @@
     msgget; # future
     msgrcv; # future
     msgsnd; # future
+    nl_langinfo; # future
+    nl_langinfo_l; # future
     pthread_getname_np; # future
     quotactl; # future
     semctl; # future
diff --git a/libc/libc.x86.map b/libc/libc.x86.map
index a166361..dfa839e 100644
--- a/libc/libc.x86.map
+++ b/libc/libc.x86.map
@@ -1270,6 +1270,8 @@
     msgget; # future
     msgrcv; # future
     msgsnd; # future
+    nl_langinfo; # future
+    nl_langinfo_l; # future
     pthread_getname_np; # future
     quotactl; # future
     semctl; # future
diff --git a/libc/libc.x86_64.map b/libc/libc.x86_64.map
index 28755d4..179d8bf 100644
--- a/libc/libc.x86_64.map
+++ b/libc/libc.x86_64.map
@@ -1210,6 +1210,8 @@
     msgget; # future
     msgrcv; # future
     msgsnd; # future
+    nl_langinfo; # future
+    nl_langinfo_l; # future
     pthread_getname_np; # future
     quotactl; # future
     semctl; # future
diff --git a/libc/malloc_debug/Android.bp b/libc/malloc_debug/Android.bp
index 8ce3ff3..708c101 100644
--- a/libc/malloc_debug/Android.bp
+++ b/libc/malloc_debug/Android.bp
@@ -111,7 +111,6 @@
         "tests/backtrace_fake.cpp",
         "tests/log_fake.cpp",
         "tests/libc_fake.cpp",
-        "tests/property_fake.cpp",
         "tests/malloc_debug_config_tests.cpp",
         "tests/malloc_debug_unit_tests.cpp",
     ],
diff --git a/libc/malloc_debug/Config.cpp b/libc/malloc_debug/Config.cpp
index c9fb850..cb75bd6 100644
--- a/libc/malloc_debug/Config.cpp
+++ b/libc/malloc_debug/Config.cpp
@@ -37,8 +37,6 @@
 #include <string>
 #include <vector>
 
-#include <sys/system_properties.h>
-
 #include <private/bionic_macros.h>
 
 #include "Config.h"
@@ -329,13 +327,7 @@
 
 // This function is designed to be called once. A second call will not
 // reset all variables.
-bool Config::SetFromProperties() {
-  char property_str[PROP_VALUE_MAX];
-  memset(property_str, 0, sizeof(property_str));
-  if (!__system_property_get("libc.debug.malloc.options", property_str)) {
-    return false;
-  }
-
+bool Config::Set(const char* options_str) {
   // Initialize a few default values.
   fill_alloc_value = DEFAULT_FILL_ALLOC_VALUE;
   fill_free_value = DEFAULT_FILL_FREE_VALUE;
@@ -426,7 +418,7 @@
   }
 
   // Process each property name we can find.
-  PropertyParser parser(property_str);
+  PropertyParser parser(options_str);
   bool valid = true;
   std::string property;
   std::string value;
diff --git a/libc/malloc_debug/Config.h b/libc/malloc_debug/Config.h
index ac620ad..ca56dc8 100644
--- a/libc/malloc_debug/Config.h
+++ b/libc/malloc_debug/Config.h
@@ -56,7 +56,7 @@
 constexpr uint64_t HEADER_OPTIONS = FRONT_GUARD | REAR_GUARD | BACKTRACE | FREE_TRACK | LEAK_TRACK;
 
 struct Config {
-  bool SetFromProperties();
+  bool Set(const char* str);
 
   size_t front_guard_bytes = 0;
   size_t rear_guard_bytes = 0;
diff --git a/libc/malloc_debug/DebugData.cpp b/libc/malloc_debug/DebugData.cpp
index fdc2810..339efdf 100644
--- a/libc/malloc_debug/DebugData.cpp
+++ b/libc/malloc_debug/DebugData.cpp
@@ -37,8 +37,8 @@
 #include "malloc_debug.h"
 #include "TrackData.h"
 
-bool DebugData::Initialize() {
-  if (!config_.SetFromProperties()) {
+bool DebugData::Initialize(const char* options) {
+  if (!config_.Set(options)) {
     return false;
   }
 
diff --git a/libc/malloc_debug/DebugData.h b/libc/malloc_debug/DebugData.h
index 7e2df0c..7228a72 100644
--- a/libc/malloc_debug/DebugData.h
+++ b/libc/malloc_debug/DebugData.h
@@ -49,7 +49,7 @@
   DebugData() = default;
   ~DebugData() = default;
 
-  bool Initialize();
+  bool Initialize(const char* options);
 
   static bool Disabled();
 
diff --git a/libc/malloc_debug/malloc_debug.cpp b/libc/malloc_debug/malloc_debug.cpp
index d2bcf99..bb16faa 100644
--- a/libc/malloc_debug/malloc_debug.cpp
+++ b/libc/malloc_debug/malloc_debug.cpp
@@ -62,7 +62,8 @@
 // ------------------------------------------------------------------------
 __BEGIN_DECLS
 
-bool debug_initialize(const MallocDispatch* malloc_dispatch, int* malloc_zygote_child);
+bool debug_initialize(const MallocDispatch* malloc_dispatch, int* malloc_zygote_child,
+    const char* options);
 void debug_finalize();
 void debug_get_malloc_leak_info(
     uint8_t** info, size_t* overall_size, size_t* info_size, size_t* total_memory,
@@ -178,8 +179,9 @@
   return g_debug->GetPointer(header);
 }
 
-bool debug_initialize(const MallocDispatch* malloc_dispatch, int* malloc_zygote_child) {
-  if (malloc_zygote_child == nullptr) {
+bool debug_initialize(const MallocDispatch* malloc_dispatch, int* malloc_zygote_child,
+    const char* options) {
+  if (malloc_zygote_child == nullptr || options == nullptr) {
     return false;
   }
 
@@ -194,7 +196,7 @@
   }
 
   DebugData* debug = new DebugData();
-  if (!debug->Initialize()) {
+  if (!debug->Initialize(options)) {
     delete debug;
     DebugDisableFinalize();
     return false;
diff --git a/libc/malloc_debug/tests/malloc_debug_config_tests.cpp b/libc/malloc_debug/tests/malloc_debug_config_tests.cpp
index 49edaba..f988124 100644
--- a/libc/malloc_debug/tests/malloc_debug_config_tests.cpp
+++ b/libc/malloc_debug/tests/malloc_debug_config_tests.cpp
@@ -25,8 +25,6 @@
 
 #include "log_fake.h"
 
-extern "C" int property_set(const char*, const char*);
-
 class MallocDebugConfigTest : public ::testing::Test {
  protected:
   void SetUp() override {
@@ -38,10 +36,9 @@
 
   std::unique_ptr<Config> config;
 
-  bool InitConfig(const char* property_value) {
+  bool InitConfig(const char* options) {
     config.reset(new Config);
-    property_set("libc.debug.malloc.options", property_value);
-    return config->SetFromProperties();
+    return config->Set(options);
   }
 };
 
diff --git a/libc/malloc_debug/tests/malloc_debug_unit_tests.cpp b/libc/malloc_debug/tests/malloc_debug_unit_tests.cpp
index edb03f6..1b08a39 100644
--- a/libc/malloc_debug/tests/malloc_debug_unit_tests.cpp
+++ b/libc/malloc_debug/tests/malloc_debug_unit_tests.cpp
@@ -44,8 +44,7 @@
 
 __BEGIN_DECLS
 
-int property_set(const char*, const char*);
-bool debug_initialize(const MallocDispatch*, int*);
+bool debug_initialize(const MallocDispatch*, int*, const char*);
 void debug_finalize();
 
 void* debug_malloc(size_t);
@@ -98,10 +97,9 @@
     }
   }
 
-  void Init(const char* property_value) {
-    property_set("libc.debug.malloc.options", property_value);
+  void Init(const char* options) {
     zygote = 0;
-    ASSERT_TRUE(debug_initialize(&dispatch, &zygote));
+    ASSERT_TRUE(debug_initialize(&dispatch, &zygote, options));
     initialized = true;
   }
 
diff --git a/libc/malloc_debug/tests/property_fake.cpp b/libc/malloc_debug/tests/property_fake.cpp
deleted file mode 100644
index d9f0ad8..0000000
--- a/libc/malloc_debug/tests/property_fake.cpp
+++ /dev/null
@@ -1,55 +0,0 @@
-/*
- * Copyright (C) 2015 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include <string.h>
-
-#include <string>
-#include <unordered_map>
-
-#include <sys/system_properties.h>
-
-std::unordered_map<std::string, std::string> g_properties;
-
-extern "C" int property_set(const char* name, const char* value) {
-  if (g_properties.count(name) != 0) {
-    g_properties.erase(name);
-  }
-  g_properties[name] = value;
-  return 0;
-}
-
-extern "C" int property_get(const char* key, char* value, const char* default_value) {
-  if (g_properties.count(key) == 0) {
-    if (default_value == nullptr) {
-      return 0;
-    }
-    strncpy(value, default_value, PROP_VALUE_MAX-1);
-  } else {
-    strncpy(value, g_properties[key].c_str(), PROP_VALUE_MAX-1);
-  }
-  value[PROP_VALUE_MAX-1] = '\0';
-  return strlen(value);
-}
-
-extern "C" int __system_property_get(const char* key, char* value) {
-  if (g_properties.count(key) == 0) {
-    return 0;
-  } else {
-    strncpy(value, g_properties[key].c_str(), PROP_VALUE_MAX-1);
-  }
-  value[PROP_VALUE_MAX-1] = '\0';
-  return strlen(value);
-}
diff --git a/libc/private/bionic_arc4random.h b/libc/private/bionic_arc4random.h
index d26a4e7..b51f818 100644
--- a/libc/private/bionic_arc4random.h
+++ b/libc/private/bionic_arc4random.h
@@ -39,7 +39,12 @@
  * created yet. Provide a wrapper function that falls back to AT_RANDOM if
  * we don't have getrandom and /dev/urandom is missing.
  */
-
 void __libc_safe_arc4random_buf(void* buf, size_t n, KernelArgumentBlock& args);
 
+/*
+ * Return true if libc has an unlimited entropy source (something other than
+ * AT_RANDOM), and arc4random* calls will always succeed.
+ */
+bool __libc_arc4random_has_unlimited_entropy();
+
 #endif
diff --git a/libc/bionic/getpriority.c b/libc/private/icu.h
similarity index 70%
copy from libc/bionic/getpriority.c
copy to libc/private/icu.h
index efc9d4e..03fdf66 100644
--- a/libc/bionic/getpriority.c
+++ b/libc/private/icu.h
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2008 The Android Open Source Project
+ * Copyright (C) 2016 The Android Open Source Project
  * All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
@@ -25,13 +25,31 @@
  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  * SUCH DAMAGE.
  */
-#include <sys/resource.h>
 
-extern int __getpriority(int, int);
+#ifndef _PRIVATE_ICU_H
+#define _PRIVATE_ICU_H
 
-int getpriority(int which, int who)
-{
-  int result = __getpriority(which, who);
+#include <stdint.h>
 
-  return ( result < 0 ) ? result : 20-result;
-}
+typedef int8_t UBool;
+typedef int32_t UChar32;
+
+enum UProperty {
+  UCHAR_ALPHABETIC = 0,
+  UCHAR_LOWERCASE = 22,
+  UCHAR_POSIX_ALNUM = 44,
+  UCHAR_POSIX_BLANK = 45,
+  UCHAR_POSIX_GRAPH = 46,
+  UCHAR_POSIX_PRINT = 47,
+  UCHAR_POSIX_XDIGIT = 48,
+  UCHAR_UPPERCASE = 30,
+  UCHAR_WHITE_SPACE = 31,
+};
+
+enum UCharCategory {
+  U_CONTROL_CHAR = 15,
+};
+
+void* __find_icu_symbol(const char* symbol_name);
+
+#endif  // _PRIVATE_ICU_H
diff --git a/libc/upstream-openbsd/lib/libc/include/langinfo.h b/libc/upstream-openbsd/lib/libc/include/langinfo.h
deleted file mode 100644
index a871ab8..0000000
--- a/libc/upstream-openbsd/lib/libc/include/langinfo.h
+++ /dev/null
@@ -1,3 +0,0 @@
-/* Hack to build "vfprintf.c". */
-#define RADIXCHAR 1
-#define nl_langinfo(i) ((i == RADIXCHAR) ? (char*) "." : NULL)
diff --git a/libc/zoneinfo/tzdata b/libc/zoneinfo/tzdata
index ce00600..577ede6 100644
--- a/libc/zoneinfo/tzdata
+++ b/libc/zoneinfo/tzdata
Binary files differ
diff --git a/libdl/Android.bp b/libdl/Android.bp
index 273a887..e9b79d7 100644
--- a/libdl/Android.bp
+++ b/libdl/Android.bp
@@ -2,6 +2,9 @@
 // libdl
 //
 cc_library {
+    name: "libdl",
+
+    defaults: ["linux_bionic_supported"],
 
     // NOTE: --exclude-libs=libgcc.a makes sure that any symbols libdl.so pulls from
     // libgcc.a are made static to libdl.so.  This in turn ensures that libraries that
@@ -46,7 +49,54 @@
     ],
     stl: "none",
 
-    name: "libdl",
+    // NOTE: libdl needs __aeabi_unwind_cpp_pr0 from libgcc.a but libgcc.a needs a
+    // few symbols from libc. Using --no-undefined here results in having to link
+    // against libc creating a circular dependency which is removed and we end up
+    // with missing symbols. Since this library is just a bunch of stubs, we set
+    // LOCAL_ALLOW_UNDEFINED_SYMBOLS to remove --no-undefined from the linker flags.
+    allow_undefined_symbols: true,
+    system_shared_libs: [],
+
+    // This is placeholder library the actual implementation is (currently)
+    // provided by the linker.
+    shared_libs: [ "ld-android" ],
+
+    sanitize: {
+        never: true,
+    },
+}
+
+cc_library {
+    // NOTE: --exclude-libs=libgcc.a makes sure that any symbols libdl.so pulls from
+    // libgcc.a are made static to ld-android.so.  This in turn ensures that libraries that
+    // a) pull symbols from libgcc.a and b) depend on ld-android.so will not rely on ld-android.so
+    // to provide those symbols, but will instead pull them from libgcc.a.  Specifically,
+    // we use this property to make sure libc.so has its own copy of the code from
+    // libgcc.a it uses.
+    //
+    // DO NOT REMOVE --exclude-libs!
+
+    ldflags: ["-Wl,--exclude-libs=libgcc.a"],
+
+    // for x86, exclude libgcc_eh.a for the same reasons as above
+    arch: {
+        x86: {
+            ldflags: ["-Wl,--exclude-libs=libgcc_eh.a"],
+        },
+        x86_64: {
+            ldflags: ["-Wl,--exclude-libs=libgcc_eh.a"],
+        },
+    },
+    srcs: ["ld_android.c"],
+    cflags: [
+        "-Wall",
+        "-Wextra",
+        "-Wunused",
+        "-Werror",
+    ],
+    stl: "none",
+
+    name: "ld-android",
 
     // NOTE: libdl needs __aeabi_unwind_cpp_pr0 from libgcc.a but libgcc.a needs a
     // few symbols from libc. Using --no-undefined here results in having to link
diff --git a/libdl/ld_android.c b/libdl/ld_android.c
new file mode 100644
index 0000000..8b13789
--- /dev/null
+++ b/libdl/ld_android.c
@@ -0,0 +1 @@
+
diff --git a/libdl/libdl.c b/libdl/libdl.c
index 4cc4dea..3fbd7e5 100644
--- a/libdl/libdl.c
+++ b/libdl/libdl.c
@@ -20,54 +20,153 @@
 #include <stdbool.h>
 #include <android/dlext.h>
 
-// These are stubs for functions that are actually defined
-// in the dynamic linker and hijacked at runtime.
+// These functions are exported by the loader
+// TODO(dimitry): replace these with reference to libc.so
 
-void* dlopen(const char* filename __unused, int flag __unused) { return 0; }
+__attribute__((__weak__, visibility("default")))
+void* __loader_dlopen(const char* filename, int flags, const void* caller_addr);
 
-char* dlerror(void) { return 0; }
+__attribute__((__weak__, visibility("default")))
+void* __loader_dlerror();
 
-void* dlsym(void* handle __unused, const char* symbol __unused) { return 0; }
+__attribute__((__weak__, visibility("default")))
+void* __loader_dlsym(void* handle, const char* symbol, const void* caller_addr);
 
-void* dlvsym(void* handle __unused, const char* symbol __unused, const char* version __unused) {
-  return 0;
-}
+__attribute__((__weak__, visibility("default")))
+void* __loader_dlvsym(void* handle,
+                      const char* symbol,
+                      const char* version,
+                      const void* caller_addr);
 
-int dladdr(const void* addr __unused, Dl_info* info __unused) { return 0; }
+__attribute__((__weak__, visibility("default")))
+int __loader_dladdr(const void* addr, Dl_info* info);
 
-int dlclose(void* handle __unused) { return 0; }
+__attribute__((__weak__, visibility("default")))
+int __loader_dlclose(void* handle);
 
 #if defined(__arm__)
-_Unwind_Ptr dl_unwind_find_exidx(_Unwind_Ptr pc __unused, int* pcount __unused) { return 0; }
+__attribute__((__weak__, visibility("default")))
+_Unwind_Ptr __loader_dl_unwind_find_exidx(_Unwind_Ptr pc, int* pcount);
 #endif
 
-int dl_iterate_phdr(int (*cb)(struct dl_phdr_info* info, size_t size, void* data) __unused,
-                    void* data __unused) {
-  return 0;
+__attribute__((__weak__, visibility("default")))
+int __loader_dl_iterate_phdr(int (*cb)(struct dl_phdr_info* info, size_t size, void* data),
+                             void* data);
+
+__attribute__((__weak__, visibility("default")))
+void __loader_android_get_LD_LIBRARY_PATH(char* buffer, size_t buffer_size);
+
+__attribute__((__weak__, visibility("default")))
+void __loader_android_update_LD_LIBRARY_PATH(const char* ld_library_path);
+
+__attribute__((__weak__, visibility("default")))
+void* __loader_android_dlopen_ext(const char* filename,
+                                  int flag,
+                                  const android_dlextinfo* extinfo,
+                                  const void* caller_addr);
+
+__attribute__((__weak__, visibility("default")))
+void __loader_android_set_application_target_sdk_version(uint32_t target);
+
+__attribute__((__weak__, visibility("default")))
+uint32_t __loader_android_get_application_target_sdk_version();
+
+__attribute__((__weak__, visibility("default")))
+bool __loader_android_init_namespaces(const char* public_ns_sonames,
+                                      const char* anon_ns_library_path);
+
+__attribute__((__weak__, visibility("default")))
+struct android_namespace_t* __loader_android_create_namespace(
+                                const char* name,
+                                const char* ld_library_path,
+                                const char* default_library_path,
+                                uint64_t type,
+                                const char* permitted_when_isolated_path,
+                                struct android_namespace_t* parent,
+                                const void* caller_addr);
+
+__attribute__((__weak__, visibility("default")))
+void __loader_android_dlwarning(void* obj, void (*f)(void*, const char*));
+
+// Proxy calls to bionic loader
+void* dlopen(const char* filename, int flag) {
+  const void* caller_addr = __builtin_return_address(0);
+  return __loader_dlopen(filename, flag, caller_addr);
 }
 
-void android_get_LD_LIBRARY_PATH(char* buffer __unused, size_t buffer_size __unused) { }
-void android_update_LD_LIBRARY_PATH(const char* ld_library_path __unused) { }
-
-void* android_dlopen_ext(const char* filename __unused, int flag __unused,
-                         const android_dlextinfo* extinfo __unused) {
-  return 0;
+char* dlerror() {
+  return __loader_dlerror();
 }
 
-void android_set_application_target_sdk_version(uint32_t target __unused) { }
-uint32_t android_get_application_target_sdk_version() { return 0; }
-
-bool android_init_namespaces(const char* public_ns_sonames __unused,
-                             const char* anon_ns_library_path __unused) {
-  return false;
+void* dlsym(void* handle, const char* symbol) {
+  const void* caller_addr = __builtin_return_address(0);
+  return __loader_dlsym(handle, symbol, caller_addr);
 }
 
-struct android_namespace_t* android_create_namespace(const char* name __unused,
-                                                     const char* ld_library_path __unused,
-                                                     const char* default_library_path __unused,
-                                                     uint64_t type __unused,
-                                                     const char* permitted_when_isolated_path __unused) {
-  return 0;
+void* dlvsym(void* handle, const char* symbol, const char* version) {
+  const void* caller_addr = __builtin_return_address(0);
+  return __loader_dlvsym(handle, symbol, version, caller_addr);
 }
 
-void android_dlwarning(void* obj, void (*f)(void*, const char*)) { f(obj, 0); }
+int dladdr(const void* addr, Dl_info* info) {
+  return __loader_dladdr(addr, info);
+}
+
+int dlclose(void* handle) {
+  return __loader_dlclose(handle);
+}
+
+#if defined(__arm__)
+_Unwind_Ptr dl_unwind_find_exidx(_Unwind_Ptr pc, int* pcount) {
+  return __loader_dl_unwind_find_exidx(pc, pcount);
+}
+#endif
+
+int dl_iterate_phdr(int (*cb)(struct dl_phdr_info* info, size_t size, void* data), void* data) {
+  return __loader_dl_iterate_phdr(cb, data);
+}
+
+void android_get_LD_LIBRARY_PATH(char* buffer, size_t buffer_size) {
+  __loader_android_get_LD_LIBRARY_PATH(buffer, buffer_size);
+}
+
+void android_update_LD_LIBRARY_PATH(const char* ld_library_path) {
+  __loader_android_update_LD_LIBRARY_PATH(ld_library_path);
+}
+
+void* android_dlopen_ext(const char* filename, int flag, const android_dlextinfo* extinfo) {
+  const void* caller_addr = __builtin_return_address(0);
+  return __loader_android_dlopen_ext(filename, flag, extinfo, caller_addr);
+}
+
+void android_set_application_target_sdk_version(uint32_t target) {
+  __loader_android_set_application_target_sdk_version(target);
+}
+uint32_t android_get_application_target_sdk_version() {
+  return __loader_android_get_application_target_sdk_version();
+}
+
+bool android_init_namespaces(const char* public_ns_sonames,
+                             const char* anon_ns_library_path) {
+  return __loader_android_init_namespaces(public_ns_sonames, anon_ns_library_path);
+}
+
+struct android_namespace_t* android_create_namespace(const char* name,
+                                                     const char* ld_library_path,
+                                                     const char* default_library_path,
+                                                     uint64_t type,
+                                                     const char* permitted_when_isolated_path,
+                                                     struct android_namespace_t* parent) {
+  const void* caller_addr = __builtin_return_address(0);
+  return __loader_android_create_namespace(name,
+                                           ld_library_path,
+                                           default_library_path,
+                                           type,
+                                           permitted_when_isolated_path,
+                                           parent,
+                                           caller_addr);
+}
+
+void android_dlwarning(void* obj, void (*f)(void*, const char*)) {
+  __loader_android_dlwarning(obj, f);
+}
diff --git a/libm/Android.bp b/libm/Android.bp
index 11017f6..7489bfe 100644
--- a/libm/Android.bp
+++ b/libm/Android.bp
@@ -5,6 +5,7 @@
 //
 cc_library {
     name: "libm",
+    defaults: ["linux_bionic_supported"],
 
     srcs: [
         "upstream-freebsd/lib/msun/bsdsrc/b_exp.c",
@@ -526,7 +527,8 @@
 
     native_coverage: bionic_coverage,
     sanitize: {
-        never: true,
+        address: false,
+        coverage: false,
     },
     stl: "none",
 }
diff --git a/linker/Android.bp b/linker/Android.bp
index 4d770ac..a3b9cb2 100644
--- a/linker/Android.bp
+++ b/linker/Android.bp
@@ -1,6 +1,6 @@
 cc_library_static {
     name: "liblinker_malloc",
-    clang: true,
+    defaults: ["linux_bionic_supported"],
 
     srcs: [
         "linker_allocator.cpp",
@@ -12,8 +12,7 @@
 }
 
 cc_binary {
-    clang: true,
-
+    defaults: ["linux_bionic_supported"],
     srcs: [
         "dlfcn.cpp",
         "linker.cpp",
@@ -97,10 +96,14 @@
         "-Werror",
     ],
 
-    conlyflags: ["-std=gnu99"],
-
     cppflags: ["-Wold-style-cast"],
 
+    // we are going to link libc++_static manually because
+    // when stl is not set to "none" build system adds libdl
+    // to the list of static libraries which needs to be
+    // avoided in the case of building loader.
+    stl: "none",
+
     // we don't want crtbegin.o (because we have begin.o), so unset it
     // just for this module
     nocrt: true,
@@ -112,7 +115,7 @@
         "libbase",
         "libz",
         "liblog",
-        "libdebuggerd_client",
+        "libc++_static",
 
         // Important: The liblinker_malloc should be the last library in the list
         // to overwrite any other malloc implementations by other static libraries.
@@ -121,19 +124,22 @@
     static_executable: true,
 
     name: "linker",
+    symlinks: ["linker_asan"],
     multilib: {
-        lib32: {
-            symlinks: ["linker_asan"],
-        },
         lib64: {
             suffix: "64",
-            symlinks: ["linker_asan64"],
-       },
+        },
     },
     target: {
+        android: {
+            static_libs: ["libdebuggerd_client"],
+        },
         android64: {
             cflags: ["-DTARGET_IS_64_BIT"],
         },
+        linux_bionic: {
+            cflags: ["-DTARGET_IS_64_BIT"],
+        },
     },
     compile_multilib: "both",
 
diff --git a/linker/dlfcn.cpp b/linker/dlfcn.cpp
index 3ac61d7..bb7b1ca 100644
--- a/linker/dlfcn.cpp
+++ b/linker/dlfcn.cpp
@@ -52,23 +52,25 @@
   __bionic_set_dlerror(buffer);
 }
 
-char* dlerror() {
+char* __dlerror() {
   char* old_value = __bionic_set_dlerror(nullptr);
   return old_value;
 }
 
-void android_get_LD_LIBRARY_PATH(char* buffer, size_t buffer_size) {
+void __android_get_LD_LIBRARY_PATH(char* buffer, size_t buffer_size) {
   ScopedPthreadMutexLocker locker(&g_dl_mutex);
   do_android_get_LD_LIBRARY_PATH(buffer, buffer_size);
 }
 
-void android_update_LD_LIBRARY_PATH(const char* ld_library_path) {
+void __android_update_LD_LIBRARY_PATH(const char* ld_library_path) {
   ScopedPthreadMutexLocker locker(&g_dl_mutex);
   do_android_update_LD_LIBRARY_PATH(ld_library_path);
 }
 
-static void* dlopen_ext(const char* filename, int flags,
-                        const android_dlextinfo* extinfo, void* caller_addr) {
+static void* dlopen_ext(const char* filename,
+                        int flags,
+                        const android_dlextinfo* extinfo,
+                        const void* caller_addr) {
   ScopedPthreadMutexLocker locker(&g_dl_mutex);
   g_linker_logger.ResetState();
   void* result = do_dlopen(filename, flags, extinfo, caller_addr);
@@ -79,17 +81,18 @@
   return result;
 }
 
-void* android_dlopen_ext(const char* filename, int flags, const android_dlextinfo* extinfo) {
-  void* caller_addr = __builtin_return_address(0);
+void* __android_dlopen_ext(const char* filename,
+                           int flags,
+                           const android_dlextinfo* extinfo,
+                           const void* caller_addr) {
   return dlopen_ext(filename, flags, extinfo, caller_addr);
 }
 
-void* dlopen(const char* filename, int flags) {
-  void* caller_addr = __builtin_return_address(0);
+void* __dlopen(const char* filename, int flags, const void* caller_addr) {
   return dlopen_ext(filename, flags, nullptr, caller_addr);
 }
 
-void* dlsym_impl(void* handle, const char* symbol, const char* version, void* caller_addr) {
+void* dlsym_impl(void* handle, const char* symbol, const char* version, const void* caller_addr) {
   ScopedPthreadMutexLocker locker(&g_dl_mutex);
   g_linker_logger.ResetState();
   void* result;
@@ -101,22 +104,20 @@
   return result;
 }
 
-void* dlsym(void* handle, const char* symbol) {
-  void* caller_addr = __builtin_return_address(0);
+void* __dlsym(void* handle, const char* symbol, const void* caller_addr) {
   return dlsym_impl(handle, symbol, nullptr, caller_addr);
 }
 
-void* dlvsym(void* handle, const char* symbol, const char* version) {
-  void* caller_addr = __builtin_return_address(0);
+void* __dlvsym(void* handle, const char* symbol, const char* version, const void* caller_addr) {
   return dlsym_impl(handle, symbol, version, caller_addr);
 }
 
-int dladdr(const void* addr, Dl_info* info) {
+int __dladdr(const void* addr, Dl_info* info) {
   ScopedPthreadMutexLocker locker(&g_dl_mutex);
   return do_dladdr(addr, info);
 }
 
-int dlclose(void* handle) {
+int __dlclose(void* handle) {
   ScopedPthreadMutexLocker locker(&g_dl_mutex);
   int result = do_dlclose(handle);
   if (result != 0) {
@@ -125,27 +126,35 @@
   return result;
 }
 
+// This function is needed by libgcc.a (this is why there is no prefix for this one)
 int dl_iterate_phdr(int (*cb)(dl_phdr_info* info, size_t size, void* data), void* data) {
   ScopedPthreadMutexLocker locker(&g_dl_mutex);
   return do_dl_iterate_phdr(cb, data);
 }
 
-void android_set_application_target_sdk_version(uint32_t target) {
+#if defined(__arm__)
+_Unwind_Ptr __dl_unwind_find_exidx(_Unwind_Ptr pc, int* pcount) {
+  ScopedPthreadMutexLocker locker(&g_dl_mutex);
+  return do_dl_unwind_find_exidx(pc, pcount);
+}
+#endif
+
+void __android_set_application_target_sdk_version(uint32_t target) {
   // lock to avoid modification in the middle of dlopen.
   ScopedPthreadMutexLocker locker(&g_dl_mutex);
   set_application_target_sdk_version(target);
 }
 
-uint32_t android_get_application_target_sdk_version() {
+uint32_t __android_get_application_target_sdk_version() {
   return get_application_target_sdk_version();
 }
 
-void android_dlwarning(void* obj, void (*f)(void*, const char*)) {
+void __android_dlwarning(void* obj, void (*f)(void*, const char*)) {
   ScopedPthreadMutexLocker locker(&g_dl_mutex);
   get_dlwarning(obj, f);
 }
 
-bool android_init_namespaces(const char* public_ns_sonames,
+bool __android_init_namespaces(const char* public_ns_sonames,
                              const char* anon_ns_library_path) {
   ScopedPthreadMutexLocker locker(&g_dl_mutex);
   bool success = init_namespaces(public_ns_sonames, anon_ns_library_path);
@@ -156,13 +165,13 @@
   return success;
 }
 
-android_namespace_t* android_create_namespace(const char* name,
-                                              const char* ld_library_path,
-                                              const char* default_library_path,
-                                              uint64_t type,
-                                              const char* permitted_when_isolated_path,
-                                              android_namespace_t* parent_namespace) {
-  void* caller_addr = __builtin_return_address(0);
+android_namespace_t* __android_create_namespace(const char* name,
+                                                const char* ld_library_path,
+                                                const char* default_library_path,
+                                                uint64_t type,
+                                                const char* permitted_when_isolated_path,
+                                                android_namespace_t* parent_namespace,
+                                                const void* caller_addr) {
   ScopedPthreadMutexLocker locker(&g_dl_mutex);
 
   android_namespace_t* result = create_namespace(caller_addr,
@@ -200,18 +209,28 @@
     }
 
 static const char ANDROID_LIBDL_STRTAB[] =
-  // 0000000 00011111 111112 22222222 2333333 3333444444444455555555556666666 6667777777777888888888899999 99999
-  // 0123456 78901234 567890 12345678 9012345 6789012345678901234567890123456 7890123456789012345678901234 56789
-    "dlopen\0dlclose\0dlsym\0dlerror\0dladdr\0android_update_LD_LIBRARY_PATH\0android_get_LD_LIBRARY_PATH\0dl_it"
-  // 00000000001 1111111112222222222 3333333333444444444455555555556666666666777 777777788888888889999999999
-  // 01234567890 1234567890123456789 0123456789012345678901234567890123456789012 345678901234567890123456789
-    "erate_phdr\0android_dlopen_ext\0android_set_application_target_sdk_version\0android_get_application_tar"
-  // 0000000000111111 111122222222223333333333 4444444444555555555566666 6666677 777777778888888888
-  // 0123456789012345 678901234567890123456789 0123456789012345678901234 5678901 234567890123456789
-    "get_sdk_version\0android_init_namespaces\0android_create_namespace\0dlvsym\0android_dlwarning\0"
+  // 0000000000111111 11112222222222333 333333344444444 44555555555566666 6666677777777778 8888888889999999999
+  // 0123456789012345 67890123456789012 345678901234567 89012345678901234 5678901234567890 1234567890123456789
+    "__loader_dlopen\0__loader_dlclose\0__loader_dlsym\0__loader_dlerror\0__loader_dladdr\0__loader_android_up"
+  // 1*
+  // 000000000011111111112 2222222223333333333444444444455555555 5566666666667777777777888 88888889999999999
+  // 012345678901234567890 1234567890123456789012345678901234567 8901234567890123456789012 34567890123456789
+    "date_LD_LIBRARY_PATH\0__loader_android_get_LD_LIBRARY_PATH\0__loader_dl_iterate_phdr\0__loader_android_"
+  // 2*
+  // 00000000001 1111111112222222222333333333344444444445555555555666 6666666777777777788888888889999999999
+  // 01234567890 1234567890123456789012345678901234567890123456789012 3456789012345678901234567890123456789
+    "dlopen_ext\0__loader_android_set_application_target_sdk_version\0__loader_android_get_application_targ"
+  // 3*
+  // 000000000011111 111112222222222333333333344444444 4455555555556666666666777777777788 8888888899999999 99
+  // 012345678901234 567890123456789012345678901234567 8901234567890123456789012345678901 2345678901234567 89
+    "et_sdk_version\0__loader_android_init_namespaces\0__loader_android_create_namespace\0__loader_dlvsym\0__"
+  // 4*
+  // 0000000000111111111122222 2222233333333334444444 4445555555555666666666677777777778 8888888889999999 999
+  // 0123456789012345678901234 5678901234567890123456 7890123456789012345678901234567890 1234567890123456 789
+    "loader_android_dlwarning\0"
 #if defined(__arm__)
-  // 290
-    "dl_unwind_find_exidx\0"
+  // 425
+    "__loader_dl_unwind_find_exidx\0"
 #endif
     ;
 
@@ -221,23 +240,23 @@
   // supposed to have st_name == 0, but instead, it points to an index
   // in the strtab with a \0 to make iterating through the symtab easier.
   ELFW(SYM_INITIALIZER)(sizeof(ANDROID_LIBDL_STRTAB) - 1, nullptr, 0),
-  ELFW(SYM_INITIALIZER)(  0, &dlopen, 1),
-  ELFW(SYM_INITIALIZER)(  7, &dlclose, 1),
-  ELFW(SYM_INITIALIZER)( 15, &dlsym, 1),
-  ELFW(SYM_INITIALIZER)( 21, &dlerror, 1),
-  ELFW(SYM_INITIALIZER)( 29, &dladdr, 1),
-  ELFW(SYM_INITIALIZER)( 36, &android_update_LD_LIBRARY_PATH, 1),
-  ELFW(SYM_INITIALIZER)( 67, &android_get_LD_LIBRARY_PATH, 1),
-  ELFW(SYM_INITIALIZER)( 95, &dl_iterate_phdr, 1),
-  ELFW(SYM_INITIALIZER)(111, &android_dlopen_ext, 1),
-  ELFW(SYM_INITIALIZER)(130, &android_set_application_target_sdk_version, 1),
-  ELFW(SYM_INITIALIZER)(173, &android_get_application_target_sdk_version, 1),
-  ELFW(SYM_INITIALIZER)(216, &android_init_namespaces, 1),
-  ELFW(SYM_INITIALIZER)(240, &android_create_namespace, 1),
-  ELFW(SYM_INITIALIZER)(265, &dlvsym, 1),
-  ELFW(SYM_INITIALIZER)(272, &android_dlwarning, 1),
+  ELFW(SYM_INITIALIZER)(  0, &__dlopen, 1),
+  ELFW(SYM_INITIALIZER)( 16, &__dlclose, 1),
+  ELFW(SYM_INITIALIZER)( 33, &__dlsym, 1),
+  ELFW(SYM_INITIALIZER)( 48, &__dlerror, 1),
+  ELFW(SYM_INITIALIZER)( 65, &__dladdr, 1),
+  ELFW(SYM_INITIALIZER)( 81, &__android_update_LD_LIBRARY_PATH, 1),
+  ELFW(SYM_INITIALIZER)(121, &__android_get_LD_LIBRARY_PATH, 1),
+  ELFW(SYM_INITIALIZER)(158, &dl_iterate_phdr, 1),
+  ELFW(SYM_INITIALIZER)(183, &__android_dlopen_ext, 1),
+  ELFW(SYM_INITIALIZER)(211, &__android_set_application_target_sdk_version, 1),
+  ELFW(SYM_INITIALIZER)(263, &__android_get_application_target_sdk_version, 1),
+  ELFW(SYM_INITIALIZER)(315, &__android_init_namespaces, 1),
+  ELFW(SYM_INITIALIZER)(348, &__android_create_namespace, 1),
+  ELFW(SYM_INITIALIZER)(382, &__dlvsym, 1),
+  ELFW(SYM_INITIALIZER)(398, &__android_dlwarning, 1),
 #if defined(__arm__)
-  ELFW(SYM_INITIALIZER)(290, &dl_unwind_find_exidx, 1),
+  ELFW(SYM_INITIALIZER)(425, &__dl_unwind_find_exidx, 1),
 #endif
 };
 
@@ -263,9 +282,9 @@
 static soinfo* __libdl_info = nullptr;
 
 // This is used by the dynamic linker. Every process gets these symbols for free.
-soinfo* get_libdl_info() {
+soinfo* get_libdl_info(const char* linker_path) {
   if (__libdl_info == nullptr) {
-    __libdl_info = new (__libdl_info_buf) soinfo(&g_default_namespace, "libdl.so", nullptr, 0, RTLD_GLOBAL);
+    __libdl_info = new (__libdl_info_buf) soinfo(&g_default_namespace, linker_path, nullptr, 0, 0);
     __libdl_info->flags_ |= FLAG_LINKED;
     __libdl_info->strtab_ = ANDROID_LIBDL_STRTAB;
     __libdl_info->symtab_ = g_libdl_symtab;
@@ -276,7 +295,7 @@
     __libdl_info->ref_count_ = 1;
     __libdl_info->strtab_size_ = sizeof(ANDROID_LIBDL_STRTAB);
     __libdl_info->local_group_root_ = __libdl_info;
-    __libdl_info->soname_ = "libdl.so";
+    __libdl_info->soname_ = "ld-android.so";
     __libdl_info->target_sdk_version_ = __ANDROID_API__;
     __libdl_info->generate_handle();
 #if defined(__work_around_b_24465209__)
diff --git a/linker/linker.cpp b/linker/linker.cpp
index 266ca6e..fc8d1ef 100644
--- a/linker/linker.cpp
+++ b/linker/linker.cpp
@@ -324,9 +324,7 @@
 // in that section (via *pcount).
 //
 // Intended to be called by libc's __gnu_Unwind_Find_exidx().
-//
-// This function is exposed via dlfcn.cpp and libdl.so.
-_Unwind_Ptr dl_unwind_find_exidx(_Unwind_Ptr pc, int* pcount) {
+_Unwind_Ptr do_dl_unwind_find_exidx(_Unwind_Ptr pc, int* pcount) {
   uintptr_t addr = reinterpret_cast<uintptr_t>(pc);
 
   for (soinfo* si = solist_get_head(); si != 0; si = si->next) {
@@ -1730,8 +1728,9 @@
                                         info->library_namespace : nullptr);
 }
 
-void* do_dlopen(const char* name, int flags, const android_dlextinfo* extinfo,
-                  void* caller_addr) {
+void* do_dlopen(const char* name, int flags,
+                const android_dlextinfo* extinfo,
+                const void* caller_addr) {
   soinfo* const caller = find_containing_library(caller_addr);
   android_namespace_t* ns = get_caller_namespace(caller);
 
@@ -1785,18 +1784,21 @@
   std::string asan_name_holder;
 
   const char* translated_name = name;
-  if (g_is_asan) {
-    if (file_is_in_dir(name, kSystemLibDir)) {
-      asan_name_holder = std::string(kAsanSystemLibDir) + "/" + basename(name);
-      if (file_exists(asan_name_holder.c_str())) {
-        translated_name = asan_name_holder.c_str();
-        PRINT("linker_asan dlopen translating \"%s\" -> \"%s\"", name, translated_name);
-      }
-    } else if (file_is_in_dir(name, kVendorLibDir)) {
-      asan_name_holder = std::string(kAsanVendorLibDir) + "/" + basename(name);
-      if (file_exists(asan_name_holder.c_str())) {
-        translated_name = asan_name_holder.c_str();
-        PRINT("linker_asan dlopen translating \"%s\" -> \"%s\"", name, translated_name);
+  if (g_is_asan && translated_name != nullptr && translated_name[0] == '/') {
+    char translated_path[PATH_MAX];
+    if (realpath(translated_name, translated_path) != nullptr) {
+      if (file_is_in_dir(translated_path, kSystemLibDir)) {
+        asan_name_holder = std::string(kAsanSystemLibDir) + "/" + basename(translated_path);
+        if (file_exists(asan_name_holder.c_str())) {
+          translated_name = asan_name_holder.c_str();
+          PRINT("linker_asan dlopen translating \"%s\" -> \"%s\"", name, translated_name);
+        }
+      } else if (file_is_in_dir(translated_path, kVendorLibDir)) {
+        asan_name_holder = std::string(kAsanVendorLibDir) + "/" + basename(translated_path);
+        if (file_exists(asan_name_holder.c_str())) {
+          translated_name = asan_name_holder.c_str();
+          PRINT("linker_asan dlopen translating \"%s\" -> \"%s\"", name, translated_name);
+        }
       }
     }
   }
@@ -1804,10 +1806,13 @@
   ProtectedDataGuard guard;
   soinfo* si = find_library(ns, translated_name, flags, extinfo, caller);
   if (si != nullptr) {
-    failure_guard.disable();
-    si->call_constructors();
     void* handle = si->to_handle();
     LD_LOG(kLogDlopen,
+           "... dlopen calling constructors: realpath=\"%s\", soname=\"%s\", handle=%p",
+           si->get_realpath(), si->get_soname(), handle);
+    si->call_constructors();
+    failure_guard.disable();
+    LD_LOG(kLogDlopen,
            "... dlopen successful: realpath=\"%s\", soname=\"%s\", handle=%p",
            si->get_realpath(), si->get_soname(), handle);
     return handle;
@@ -1852,8 +1857,11 @@
   return static_cast<soinfo*>(handle);
 }
 
-bool do_dlsym(void* handle, const char* sym_name, const char* sym_ver,
-              void* caller_addr, void** symbol) {
+bool do_dlsym(void* handle,
+              const char* sym_name,
+              const char* sym_ver,
+              const void* caller_addr,
+              void** symbol) {
 #if !defined(__LP64__)
   if (handle == nullptr) {
     DL_ERR("dlsym failed: library handle is null");
@@ -1861,15 +1869,33 @@
   }
 #endif
 
-  if (sym_name == nullptr) {
-    DL_ERR("dlsym failed: symbol name is null");
-    return false;
-  }
-
   soinfo* found = nullptr;
   const ElfW(Sym)* sym = nullptr;
   soinfo* caller = find_containing_library(caller_addr);
   android_namespace_t* ns = get_caller_namespace(caller);
+  soinfo* si = nullptr;
+  if (handle != RTLD_DEFAULT && handle != RTLD_NEXT) {
+    si = soinfo_from_handle(handle);
+  }
+
+  LD_LOG(kLogDlsym,
+         "dlsym(handle=%p(\"%s\"), sym_name=\"%s\", sym_ver=\"%s\", caller=\"%s\", caller_ns=%s@%p) ...",
+         handle,
+         si != nullptr ? si->get_realpath() : "n/a",
+         sym_name,
+         sym_ver,
+         caller == nullptr ? "(null)" : caller->get_realpath(),
+         ns == nullptr ? "(null)" : ns->get_name(),
+         ns);
+
+  auto failure_guard = make_scope_guard([&]() {
+    LD_LOG(kLogDlsym, "... dlsym failed: %s", linker_get_error_buffer());
+  });
+
+  if (sym_name == nullptr) {
+    DL_ERR("dlsym failed: symbol name is null");
+    return false;
+  }
 
   version_info vi_instance;
   version_info* vi = nullptr;
@@ -1883,7 +1909,6 @@
   if (handle == RTLD_DEFAULT || handle == RTLD_NEXT) {
     sym = dlsym_linear_lookup(ns, sym_name, vi, &found, caller, handle);
   } else {
-    soinfo* si = soinfo_from_handle(handle);
     if (si == nullptr) {
       DL_ERR("dlsym failed: invalid handle: %p", handle);
       return false;
@@ -1896,6 +1921,10 @@
 
     if ((bind == STB_GLOBAL || bind == STB_WEAK) && sym->st_shndx != 0) {
       *symbol = reinterpret_cast<void*>(found->resolve_symbol_address(sym));
+      failure_guard.disable();
+      LD_LOG(kLogDlsym,
+             "... dlsym successful: sym_name=\"%s\", sym_ver=\"%s\", found in=\"%s\", address=%p",
+             sym_name, sym_ver, found->get_soname(), *symbol);
       return true;
     }
 
diff --git a/linker/linker.h b/linker/linker.h
index 4787471..c65d503 100644
--- a/linker/linker.h
+++ b/linker/linker.h
@@ -101,17 +101,27 @@
 
 void count_relocation(RelocationKind kind);
 
-soinfo* get_libdl_info();
+soinfo* get_libdl_info(const char* linker_path);
 
 void do_android_get_LD_LIBRARY_PATH(char*, size_t);
 void do_android_update_LD_LIBRARY_PATH(const char* ld_library_path);
-void* do_dlopen(const char* name, int flags, const android_dlextinfo* extinfo, void* caller_addr);
+void* do_dlopen(const char* name,
+                int flags,
+                const android_dlextinfo* extinfo,
+                const void* caller_addr);
+
 int do_dlclose(void* handle);
 
 int do_dl_iterate_phdr(int (*cb)(dl_phdr_info* info, size_t size, void* data), void* data);
 
-bool do_dlsym(void* handle, const char* sym_name, const char* sym_ver,
-              void* caller_addr, void** symbol);
+#if defined(__arm__)
+_Unwind_Ptr do_dl_unwind_find_exidx(_Unwind_Ptr pc, int* pcount);
+#endif
+
+bool do_dlsym(void* handle, const char* sym_name,
+              const char* sym_ver,
+              const void* caller_addr,
+              void** symbol);
 
 int do_dladdr(const void* addr, Dl_info* info);
 
diff --git a/linker/linker_logger.h b/linker/linker_logger.h
index 0932471..502f872 100644
--- a/linker/linker_logger.h
+++ b/linker/linker_logger.h
@@ -40,6 +40,7 @@
 
 constexpr const uint32_t kLogErrors = 1 << 0;
 constexpr const uint32_t kLogDlopen = 1 << 1;
+constexpr const uint32_t kLogDlsym  = 1 << 2;
 
 class LinkerLogger {
  public:
diff --git a/linker/linker_main.cpp b/linker/linker_main.cpp
index 2e98bf0..13edfe1 100644
--- a/linker/linker_main.cpp
+++ b/linker/linker_main.cpp
@@ -40,7 +40,9 @@
 
 #include "android-base/strings.h"
 #include "android-base/stringprintf.h"
+#ifdef __ANDROID__
 #include "debuggerd/client.h"
+#endif
 
 #include <vector>
 
@@ -158,16 +160,11 @@
  * relocate the offset of our exported 'rtld_db_dlactivity' symbol.
  * Note that the linker shouldn't be on the soinfo list.
  */
-static void init_linker_info_for_gdb(ElfW(Addr) linker_base) {
+static void init_linker_info_for_gdb(ElfW(Addr) linker_base, char* linker_path) {
   static link_map linker_link_map_for_gdb;
-#if defined(__LP64__)
-  static char kLinkerPath[] = "/system/bin/linker64";
-#else
-  static char kLinkerPath[] = "/system/bin/linker";
-#endif
 
   linker_link_map_for_gdb.l_addr = linker_base;
-  linker_link_map_for_gdb.l_name = kLinkerPath;
+  linker_link_map_for_gdb.l_name = linker_path;
 
   /*
    * Set the dynamic field in the link map otherwise gdb will complain with
@@ -199,6 +196,12 @@
   return executable_path.c_str();
 }
 
+#if defined(__LP64__)
+static char kLinkerPath[] = "/system/bin/linker64";
+#else
+static char kLinkerPath[] = "/system/bin/linker";
+#endif
+
 /*
  * This code is called after the linker has linked itself and
  * fixed it's own GOT. It is safe to make references to externs
@@ -217,6 +220,7 @@
   __system_properties_init(); // may use 'environ'
 
   // Register the debuggerd signal handler.
+#ifdef __ANDROID__
   debuggerd_callbacks_t callbacks = {
     .get_abort_message = []() {
       return g_abort_message;
@@ -224,6 +228,7 @@
     .post_dump = &notify_gdb_of_libraries,
   };
   debuggerd_init(&callbacks);
+#endif
 
   g_linker_logger.ResetState();
 
@@ -278,7 +283,7 @@
   map->l_addr = 0;
   map->l_name = const_cast<char*>(executable_path);
   insert_link_map_into_debug_map(map);
-  init_linker_info_for_gdb(linker_base);
+  init_linker_info_for_gdb(linker_base, kLinkerPath);
 
   // Extract information passed from the kernel.
   si->phdr = reinterpret_cast<ElfW(Phdr)*>(args.getauxval(AT_PHDR));
@@ -520,9 +525,8 @@
   // Initialize static variables. Note that in order to
   // get correct libdl_info we need to call constructors
   // before get_libdl_info().
-  solist = get_libdl_info();
-  sonext = get_libdl_info();
-  g_default_namespace.add_soinfo(get_libdl_info());
+  sonext = solist = get_libdl_info(kLinkerPath);
+  g_default_namespace.add_soinfo(solist);
 
   // We have successfully fixed our own relocations. It's safe to run
   // the main part of the linker now.
diff --git a/linker/linker_soinfo.h b/linker/linker_soinfo.h
index a0fe9e2..7ef5da2 100644
--- a/linker/linker_soinfo.h
+++ b/linker/linker_soinfo.h
@@ -336,7 +336,7 @@
   android_namespace_list_t secondary_namespaces_;
   uintptr_t handle_;
 
-  friend soinfo* get_libdl_info();
+  friend soinfo* get_libdl_info(const char* linker_path);
 };
 
 // This function is used by dlvsym() to calculate hash of sym_ver
diff --git a/tests/Android.bp b/tests/Android.bp
index 3e1e13b..a9d302a 100644
--- a/tests/Android.bp
+++ b/tests/Android.bp
@@ -68,6 +68,7 @@
         "grp_pwd_test.cpp",
         "ifaddrs_test.cpp",
         "inttypes_test.cpp",
+        "langinfo_test.cpp",
         "libc_logging_test.cpp",
         "libgen_basename_test.cpp",
         "libgen_test.cpp",
@@ -385,6 +386,12 @@
     name: "bionic-unit-tests",
     defaults: ["bionic_unit_tests_defaults", "bionic_tests_defaults"],
     clang: true,
+
+    target: {
+        android: {
+            shared_libs: ["libicuuc"],
+        },
+    },
 }
 
 cc_test {
@@ -476,7 +483,10 @@
 
     include_dirs: ["bionic/libc"],
 
-    ldflags: ["-Wl,--export-dynamic"],
+    ldflags: [
+        "-Wl,--rpath,${ORIGIN}/../bionic-loader-test-libs",
+        "-Wl,--export-dynamic",
+    ],
 
     sanitize: {
         never: false,
diff --git a/tests/Android.build.mk b/tests/Android.build.mk
index cce4344..9236558 100644
--- a/tests/Android.build.mk
+++ b/tests/Android.build.mk
@@ -20,24 +20,30 @@
 LOCAL_MODULE := $(module)
 LOCAL_MODULE_TAGS := $(module_tag)
 ifeq ($(build_type),host)
-# Always make host multilib
-LOCAL_MULTILIB := both
+  # Always make host multilib
+  LOCAL_MULTILIB := both
 endif
 
 ifneq ($(findstring LIBRARY, $(build_target)),LIBRARY)
-    LOCAL_MODULE_STEM_32 := $(module)32
-    LOCAL_MODULE_STEM_64 := $(module)64
+  LOCAL_MODULE_STEM_32 := $(module)32
+  LOCAL_MODULE_STEM_64 := $(module)64
 else
-ifneq ($($(module)_install_to_out_data_dir),)
-    LOCAL_MODULE_PATH_32 := $($(TARGET_2ND_ARCH_VAR_PREFIX)TARGET_OUT_DATA_NATIVE_TESTS)/$($(module)_install_to_out_data_dir)
-    LOCAL_MODULE_PATH_64 := $(TARGET_OUT_DATA_NATIVE_TESTS)/$($(module)_install_to_out_data_dir)
+ifneq ($($(module)_install_to_native_tests_dir),)
+  ifeq ($(build_type),host)
+    native_tests_var := HOST_OUT_NATIVE_TESTS
+  else
+    native_tests_var := TARGET_OUT_DATA_NATIVE_TESTS
+  endif
+
+  LOCAL_MODULE_PATH_32 := $($(TARGET_2ND_ARCH_VAR_PREFIX)$(native_tests_var))/$($(module)_install_to_native_tests_dir)
+  LOCAL_MODULE_PATH_64 := $($(native_tests_var))/$($(module)_install_to_native_tests_dir)
 endif
 endif
 
 LOCAL_CLANG := $($(module)_clang_$(build_type))
 
 ifneq ($($(module)_allow_asan),true)
-LOCAL_SANITIZE := never
+  LOCAL_SANITIZE := never
 endif
 
 LOCAL_FORCE_STATIC_EXECUTABLE := $($(module)_force_static_executable)
@@ -45,11 +51,11 @@
 LOCAL_ALLOW_UNDEFINED_SYMBOLS := $($(module)_allow_undefined_symbols)
 
 ifneq ($($(module)_multilib),)
-    LOCAL_MULTILIB := $($(module)_multilib)
+  LOCAL_MULTILIB := $($(module)_multilib)
 endif
 
 ifneq ($($(module)_relative_path),)
-    LOCAL_MODULE_RELATIVE_PATH := $($(module)_relative_path)
+  LOCAL_MODULE_RELATIVE_PATH := $($(module)_relative_path)
 endif
 
 LOCAL_CFLAGS := \
@@ -97,9 +103,9 @@
     $($(module)_ldlibs_$(build_type)) \
 
 ifeq ($(LOCAL_FORCE_STATIC_EXECUTABLE),true)
-LOCAL_CXX_STL := libc++_static
+  LOCAL_CXX_STL := libc++_static
 else
-LOCAL_CXX_STL := libc++
+  LOCAL_CXX_STL := libc++
 endif
 
 ifeq ($(build_type),target)
diff --git a/tests/dlext_test.cpp b/tests/dlext_test.cpp
index ed50ea5..e629e41 100644
--- a/tests/dlext_test.cpp
+++ b/tests/dlext_test.cpp
@@ -98,7 +98,7 @@
 }
 
 TEST_F(DlExtTest, ExtInfoUseFd) {
-  const std::string lib_path = g_testlib_root + "/libdlext_test_fd/libdlext_test_fd.so";
+  const std::string lib_path = get_testlib_root() + "/libdlext_test_fd/libdlext_test_fd.so";
 
   android_dlextinfo extinfo;
   extinfo.flags = ANDROID_DLEXT_USE_LIBRARY_FD;
@@ -116,7 +116,7 @@
 }
 
 TEST_F(DlExtTest, ExtInfoUseFdWithOffset) {
-  const std::string lib_path = g_testlib_root + "/libdlext_test_zip/libdlext_test_zip_zipaligned.zip";
+  const std::string lib_path = get_testlib_root() + "/libdlext_test_zip/libdlext_test_zip_zipaligned.zip";
 
   android_dlextinfo extinfo;
   extinfo.flags = ANDROID_DLEXT_USE_LIBRARY_FD | ANDROID_DLEXT_USE_LIBRARY_FD_OFFSET;
@@ -142,7 +142,7 @@
 }
 
 TEST_F(DlExtTest, ExtInfoUseFdWithInvalidOffset) {
-  const std::string lib_path = g_testlib_root + "/libdlext_test_zip/libdlext_test_zip_zipaligned.zip";
+  const std::string lib_path = get_testlib_root() + "/libdlext_test_zip/libdlext_test_zip_zipaligned.zip";
 
   android_dlextinfo extinfo;
   extinfo.flags = ANDROID_DLEXT_USE_LIBRARY_FD | ANDROID_DLEXT_USE_LIBRARY_FD_OFFSET;
@@ -228,7 +228,7 @@
 
 TEST(dlfcn, dlopen_from_zip_absolute_path) {
   const std::string lib_zip_path = "/libdlext_test_zip/libdlext_test_zip_zipaligned.zip";
-  const std::string lib_path = g_testlib_root + lib_zip_path;
+  const std::string lib_path = get_testlib_root() + lib_zip_path;
 
   void* handle = dlopen((lib_path + "!/libdir/libatest_simple_zip.so").c_str(), RTLD_NOW);
   ASSERT_TRUE(handle != nullptr) << dlerror();
@@ -242,7 +242,7 @@
 
 TEST(dlfcn, dlopen_from_zip_with_dt_runpath) {
   const std::string lib_zip_path = "/libdlext_test_runpath_zip/libdlext_test_runpath_zip_zipaligned.zip";
-  const std::string lib_path = g_testlib_root + lib_zip_path;
+  const std::string lib_path = get_testlib_root() + lib_zip_path;
 
   void* handle = dlopen((lib_path + "!/libdir/libtest_dt_runpath_d_zip.so").c_str(), RTLD_NOW);
 
@@ -261,7 +261,7 @@
 
 TEST(dlfcn, dlopen_from_zip_ld_library_path) {
   const std::string lib_zip_path = "/libdlext_test_zip/libdlext_test_zip_zipaligned.zip";
-  const std::string lib_path = g_testlib_root + lib_zip_path + "!/libdir";
+  const std::string lib_path = get_testlib_root() + lib_zip_path + "!/libdir";
 
   typedef void (*fn_t)(const char*);
   fn_t android_update_LD_LIBRARY_PATH =
@@ -631,7 +631,7 @@
   ASSERT_STREQ("android_init_namespaces failed: error initializing public namespace: "
                "the list of public libraries is empty.", dlerror());
 
-  const std::string lib_public_path = g_testlib_root + "/public_namespace_libs/" + g_public_lib;
+  const std::string lib_public_path = get_testlib_root() + "/public_namespace_libs/" + g_public_lib;
   void* handle_public = dlopen(lib_public_path.c_str(), RTLD_NOW);
   ASSERT_TRUE(handle_public != nullptr) << dlerror();
 
@@ -639,20 +639,20 @@
 
   // Check that libraries added to public namespace are NODELETE
   dlclose(handle_public);
-  handle_public = dlopen((g_testlib_root + "/public_namespace_libs/" + g_public_lib).c_str(),
+  handle_public = dlopen((get_testlib_root() + "/public_namespace_libs/" + g_public_lib).c_str(),
                          RTLD_NOW | RTLD_NOLOAD);
 
   ASSERT_TRUE(handle_public != nullptr) << dlerror();
 
   android_namespace_t* ns1 =
           android_create_namespace("private", nullptr,
-                                   (g_testlib_root + "/private_namespace_libs").c_str(),
+                                   (get_testlib_root() + "/private_namespace_libs").c_str(),
                                    ANDROID_NAMESPACE_TYPE_REGULAR, nullptr, nullptr);
   ASSERT_TRUE(ns1 != nullptr) << dlerror();
 
   android_namespace_t* ns2 =
           android_create_namespace("private_isolated", nullptr,
-                                   (g_testlib_root + "/private_namespace_libs").c_str(),
+                                   (get_testlib_root() + "/private_namespace_libs").c_str(),
                                    ANDROID_NAMESPACE_TYPE_ISOLATED, nullptr, nullptr);
   ASSERT_TRUE(ns2 != nullptr) << dlerror();
 
@@ -743,7 +743,7 @@
   static const char* root_lib = "libnstest_root_not_isolated.so";
   std::string path = std::string("libc.so:libc++.so:libdl.so:libm.so:") + g_public_lib;
 
-  const std::string lib_public_path = g_testlib_root + "/public_namespace_libs/" + g_public_lib;
+  const std::string lib_public_path = get_testlib_root() + "/public_namespace_libs/" + g_public_lib;
   void* handle_public = dlopen(lib_public_path.c_str(), RTLD_NOW);
   ASSERT_TRUE(handle_public != nullptr) << dlerror();
 
@@ -753,14 +753,14 @@
 
   android_namespace_t* ns_not_isolated =
           android_create_namespace("private", nullptr,
-                                   (g_testlib_root + "/private_namespace_libs").c_str(),
+                                   (get_testlib_root() + "/private_namespace_libs").c_str(),
                                    ANDROID_NAMESPACE_TYPE_REGULAR, nullptr, nullptr);
   ASSERT_TRUE(ns_not_isolated != nullptr) << dlerror();
 
   android_namespace_t* ns_isolated =
           android_create_namespace("private_isolated1",
                                    nullptr,
-                                   (g_testlib_root + "/private_namespace_libs").c_str(),
+                                   (get_testlib_root() + "/private_namespace_libs").c_str(),
                                    ANDROID_NAMESPACE_TYPE_ISOLATED,
                                    nullptr,
                                    nullptr);
@@ -768,10 +768,10 @@
 
   android_namespace_t* ns_isolated2 =
           android_create_namespace("private_isolated2",
-                                   (g_testlib_root + "/private_namespace_libs").c_str(),
+                                   (get_testlib_root() + "/private_namespace_libs").c_str(),
                                    nullptr,
                                    ANDROID_NAMESPACE_TYPE_ISOLATED,
-                                   g_testlib_root.c_str(),
+                                   get_testlib_root().c_str(),
                                    nullptr);
   ASSERT_TRUE(ns_isolated2 != nullptr) << dlerror();
 
@@ -779,7 +779,7 @@
   ASSERT_STREQ("dlopen failed: library \"libnstest_root_not_isolated.so\" not found", dlerror());
 
   std::string lib_private_external_path =
-      g_testlib_root + "/private_namespace_libs_external/libnstest_private_external.so";
+      get_testlib_root() + "/private_namespace_libs_external/libnstest_private_external.so";
 
   // Load lib_private_external_path to default namespace
   // (it should remain invisible for the isolated namespaces after this)
@@ -808,7 +808,7 @@
 
   extinfo.library_namespace = ns_isolated2;
 
-  // this should work because isolation_path for private_isolated2 includes g_testlib_root
+  // this should work because isolation_path for private_isolated2 includes get_testlib_root()
   handle2 = android_dlopen_ext(root_lib, RTLD_NOW, &extinfo);
   ASSERT_TRUE(handle2 != nullptr) << dlerror();
   dlclose(handle2);
@@ -849,7 +849,7 @@
   static const char* root_lib_isolated = "libnstest_root.so";
   std::string path = std::string("libc.so:libc++.so:libdl.so:libm.so:") + g_public_lib;
 
-  const std::string lib_public_path = g_testlib_root + "/public_namespace_libs/" + g_public_lib;
+  const std::string lib_public_path = get_testlib_root() + "/public_namespace_libs/" + g_public_lib;
   void* handle_public = dlopen(lib_public_path.c_str(), RTLD_NOW);
   ASSERT_TRUE(handle_public != nullptr) << dlerror();
 
@@ -860,18 +860,18 @@
   // preload this library to the default namespace to check if it
   // is shared later on.
   void* handle_dlopened =
-          dlopen((g_testlib_root + "/private_namespace_libs/libnstest_dlopened.so").c_str(), RTLD_NOW);
+          dlopen((get_testlib_root() + "/private_namespace_libs/libnstest_dlopened.so").c_str(), RTLD_NOW);
   ASSERT_TRUE(handle_dlopened != nullptr) << dlerror();
 
   android_namespace_t* ns_not_isolated =
           android_create_namespace("private", nullptr,
-                                   (g_testlib_root + "/private_namespace_libs").c_str(),
+                                   (get_testlib_root() + "/private_namespace_libs").c_str(),
                                    ANDROID_NAMESPACE_TYPE_REGULAR, nullptr, nullptr);
   ASSERT_TRUE(ns_not_isolated != nullptr) << dlerror();
 
   android_namespace_t* ns_isolated_shared =
           android_create_namespace("private_isolated_shared", nullptr,
-                                   (g_testlib_root + "/private_namespace_libs").c_str(),
+                                   (get_testlib_root() + "/private_namespace_libs").c_str(),
                                    ANDROID_NAMESPACE_TYPE_ISOLATED | ANDROID_NAMESPACE_TYPE_SHARED,
                                    nullptr, nullptr);
   ASSERT_TRUE(ns_isolated_shared != nullptr) << dlerror();
@@ -880,7 +880,7 @@
   ASSERT_STREQ("dlopen failed: library \"libnstest_root_not_isolated.so\" not found", dlerror());
 
   std::string lib_private_external_path =
-      g_testlib_root + "/private_namespace_libs_external/libnstest_private_external.so";
+      get_testlib_root() + "/private_namespace_libs_external/libnstest_private_external.so";
 
   // Load lib_private_external_path to default namespace
   // (it should remain invisible for the isolated namespaces after this)
@@ -971,12 +971,12 @@
   // preload this library to the default namespace to check if it
   // is shared later on.
   void* handle_dlopened =
-          dlopen((g_testlib_root + "/private_namespace_libs/libnstest_dlopened.so").c_str(), RTLD_NOW);
+          dlopen((get_testlib_root() + "/private_namespace_libs/libnstest_dlopened.so").c_str(), RTLD_NOW);
   ASSERT_TRUE(handle_dlopened != nullptr) << dlerror();
 
   android_namespace_t* ns_isolated_shared =
           android_create_namespace("private_isolated_shared", nullptr,
-                                   (g_testlib_root + "/private_namespace_libs").c_str(),
+                                   (get_testlib_root() + "/private_namespace_libs").c_str(),
                                    ANDROID_NAMESPACE_TYPE_ISOLATED | ANDROID_NAMESPACE_TYPE_SHARED,
                                    nullptr, nullptr);
   ASSERT_TRUE(ns_isolated_shared != nullptr) << dlerror();
@@ -997,7 +997,7 @@
   ASSERT_TRUE(handle == nullptr)
       << "Error: libnstest_dlopened.so is still accessible in shared namespace";
 
-  handle = android_dlopen_ext((g_testlib_root + "/private_namespace_libs/libnstest_dlopened.so").c_str(),
+  handle = android_dlopen_ext((get_testlib_root() + "/private_namespace_libs/libnstest_dlopened.so").c_str(),
                               RTLD_NOW | RTLD_NOLOAD, &extinfo);
   ASSERT_TRUE(handle == nullptr)
       << "Error: libnstest_dlopened.so is still accessible in shared namespace";
@@ -1006,14 +1006,14 @@
   ASSERT_TRUE(handle == nullptr)
       << "Error: libnstest_dlopened.so is still accessible in default namespace";
 
-  handle = dlopen((g_testlib_root + "/private_namespace_libs/libnstest_dlopened.so").c_str(),
+  handle = dlopen((get_testlib_root() + "/private_namespace_libs/libnstest_dlopened.so").c_str(),
                   RTLD_NOW | RTLD_NOLOAD);
   ASSERT_TRUE(handle == nullptr)
       << "Error: libnstest_dlopened.so is still accessible in default namespace";
 
   // Now lets see if the soinfo area gets reused in the wrong way:
   // load a library to default namespace.
-  const std::string lib_public_path = g_testlib_root + "/public_namespace_libs/" + g_public_lib;
+  const std::string lib_public_path = get_testlib_root() + "/public_namespace_libs/" + g_public_lib;
   void* handle_public = dlopen(lib_public_path.c_str(), RTLD_NOW);
   ASSERT_TRUE(handle_public != nullptr) << dlerror();
 
@@ -1029,12 +1029,12 @@
 
   ASSERT_TRUE(android_init_namespaces(path.c_str(), nullptr));
 
-  const std::string lib_public_path = g_testlib_root + "/public_namespace_libs";
+  const std::string lib_public_path = get_testlib_root() + "/public_namespace_libs";
 
   android_namespace_t* ns1 =
           android_create_namespace("isolated1",
                                    nullptr,
-                                   (g_testlib_root + "/private_namespace_libs").c_str(),
+                                   (get_testlib_root() + "/private_namespace_libs").c_str(),
                                    ANDROID_NAMESPACE_TYPE_ISOLATED,
                                    lib_public_path.c_str(),
                                    nullptr);
@@ -1043,7 +1043,7 @@
   android_namespace_t* ns2 =
           android_create_namespace("isolated2",
                                    nullptr,
-                                   (g_testlib_root + "/private_namespace_libs").c_str(),
+                                   (get_testlib_root() + "/private_namespace_libs").c_str(),
                                    ANDROID_NAMESPACE_TYPE_ISOLATED,
                                    lib_public_path.c_str(),
                                    nullptr);
@@ -1062,7 +1062,7 @@
   android_namespace_t* ns1_child =
         android_create_namespace("isolated1_child",
                                  nullptr,
-                                 (g_testlib_root + "/private_namespace_libs").c_str(),
+                                 (get_testlib_root() + "/private_namespace_libs").c_str(),
                                  ANDROID_NAMESPACE_TYPE_ISOLATED,
                                  nullptr,
                                  ns1);
@@ -1097,22 +1097,22 @@
   static const char* root_lib = "libnstest_root.so";
   std::string path = std::string("libc.so:libc++.so:libdl.so:libm.so:") + g_public_lib;
 
-  const std::string lib_public_path = g_testlib_root + "/public_namespace_libs/" + g_public_lib;
+  const std::string lib_public_path = get_testlib_root() + "/public_namespace_libs/" + g_public_lib;
   void* handle_public = dlopen(lib_public_path.c_str(), RTLD_NOW);
 
   ASSERT_TRUE(handle_public != nullptr) << dlerror();
 
-  ASSERT_TRUE(android_init_namespaces(path.c_str(), (g_testlib_root + "/private_namespace_libs").c_str()))
+  ASSERT_TRUE(android_init_namespaces(path.c_str(), (get_testlib_root() + "/private_namespace_libs").c_str()))
       << dlerror();
 
   android_namespace_t* ns = android_create_namespace(
                                 "private", nullptr,
-                                (g_testlib_root + "/private_namespace_libs").c_str(),
+                                (get_testlib_root() + "/private_namespace_libs").c_str(),
                                 ANDROID_NAMESPACE_TYPE_REGULAR, nullptr, nullptr);
 
   ASSERT_TRUE(ns != nullptr) << dlerror();
 
-  std::string private_library_absolute_path = g_testlib_root + "/private_namespace_libs/" + root_lib;
+  std::string private_library_absolute_path = get_testlib_root() + "/private_namespace_libs/" + root_lib;
 
   android_dlextinfo extinfo;
   extinfo.flags = ANDROID_DLEXT_USE_NAMESPACE;
diff --git a/tests/dlfcn_test.cpp b/tests/dlfcn_test.cpp
index 5908fc3..46f6ec0 100644
--- a/tests/dlfcn_test.cpp
+++ b/tests/dlfcn_test.cpp
@@ -25,6 +25,7 @@
 #include "private/ScopeGuard.h"
 
 #include <string>
+#include <thread>
 
 #include "gtest_globals.h"
 #include "dlfcn_symlink_support.h"
@@ -754,24 +755,45 @@
 #endif
 }
 
-static void* ConcurrentDlErrorFn(void*) {
-  dlopen("/child/thread", RTLD_NOW);
-  return reinterpret_cast<void*>(strdup(dlerror()));
+static void ConcurrentDlErrorFn(std::string& error) {
+  ASSERT_TRUE(dlerror() == nullptr);
+
+  void* handle = dlopen("/child/thread", RTLD_NOW);
+  ASSERT_TRUE(handle == nullptr);
+
+  const char* err = dlerror();
+  ASSERT_TRUE(err != nullptr);
+
+  error = err;
+}
+
+TEST(dlfcn, dlerror_concurrent_buffer) {
+  void* handle = dlopen("/main/thread", RTLD_NOW);
+  ASSERT_TRUE(handle == nullptr);
+  const char* main_thread_error = dlerror();
+  ASSERT_TRUE(main_thread_error != nullptr);
+  ASSERT_SUBSTR("/main/thread", main_thread_error);
+
+  std::string child_thread_error;
+  std::thread t(ConcurrentDlErrorFn, std::ref(child_thread_error));
+  t.join();
+  ASSERT_SUBSTR("/child/thread", child_thread_error.c_str());
+
+  // Check that main thread local buffer was not modified.
+  ASSERT_SUBSTR("/main/thread", main_thread_error);
 }
 
 TEST(dlfcn, dlerror_concurrent) {
-  dlopen("/main/thread", RTLD_NOW);
+  void* handle = dlopen("/main/thread", RTLD_NOW);
+  ASSERT_TRUE(handle == nullptr);
+
+  std::string child_thread_error;
+  std::thread t(ConcurrentDlErrorFn, std::ref(child_thread_error));
+  t.join();
+  ASSERT_SUBSTR("/child/thread", child_thread_error.c_str());
+
   const char* main_thread_error = dlerror();
-  ASSERT_SUBSTR("/main/thread", main_thread_error);
-
-  pthread_t t;
-  ASSERT_EQ(0, pthread_create(&t, nullptr, ConcurrentDlErrorFn, nullptr));
-  void* result;
-  ASSERT_EQ(0, pthread_join(t, &result));
-  char* child_thread_error = static_cast<char*>(result);
-  ASSERT_SUBSTR("/child/thread", child_thread_error);
-  free(child_thread_error);
-
+  ASSERT_TRUE(main_thread_error != nullptr);
   ASSERT_SUBSTR("/main/thread", main_thread_error);
 }
 
@@ -991,6 +1013,22 @@
   ASSERT_TRUE(addr != nullptr);
 }
 
+// Check that RTLD_NEXT of a libc symbol works in dlopened library
+TEST(dlfcn, rtld_next_from_library) {
+  void* library_with_close = dlopen("libtest_check_rtld_next_from_library.so", RTLD_NOW);
+  ASSERT_TRUE(library_with_close != nullptr) << dlerror();
+  void* expected_addr = dlsym(RTLD_DEFAULT, "close");
+  ASSERT_TRUE(expected_addr != nullptr) << dlerror();
+  typedef void* (*get_libc_close_ptr_fn_t)();
+  get_libc_close_ptr_fn_t get_libc_close_ptr =
+      reinterpret_cast<get_libc_close_ptr_fn_t>(dlsym(library_with_close, "get_libc_close_ptr"));
+  ASSERT_TRUE(get_libc_close_ptr != nullptr) << dlerror();
+  ASSERT_EQ(expected_addr, get_libc_close_ptr());
+
+  dlclose(library_with_close);
+}
+
+
 TEST(dlfcn, dlsym_weak_func) {
   dlerror();
   void* handle = dlopen("libtest_dlsym_weak_func.so", RTLD_NOW);
@@ -1137,7 +1175,7 @@
 #if defined(__BIONIC__)
 
 TEST(dlfcn, dt_runpath_absolute_path) {
-  std::string libpath = g_testlib_root + "/libtest_dt_runpath_d.so";
+  std::string libpath = get_testlib_root() + "/libtest_dt_runpath_d.so";
   void* handle = dlopen(libpath.c_str(), RTLD_NOW);
   ASSERT_TRUE(handle != nullptr) << dlerror();
 
@@ -1152,7 +1190,7 @@
 }
 
 TEST(dlfcn, dlopen_invalid_rw_load_segment) {
-  const std::string libpath = g_testlib_root +
+  const std::string libpath = get_testlib_root() +
                               "/" + kPrebuiltElfDir +
                               "/libtest_invalid-rw_load_segment.so";
   void* handle = dlopen(libpath.c_str(), RTLD_NOW);
@@ -1162,7 +1200,7 @@
 }
 
 TEST(dlfcn, dlopen_invalid_unaligned_shdr_offset) {
-  const std::string libpath = g_testlib_root +
+  const std::string libpath = get_testlib_root() +
                               "/" + kPrebuiltElfDir +
                               "/libtest_invalid-unaligned_shdr_offset.so";
 
@@ -1173,7 +1211,7 @@
 }
 
 TEST(dlfcn, dlopen_invalid_zero_shentsize) {
-  const std::string libpath = g_testlib_root +
+  const std::string libpath = get_testlib_root() +
                               "/" + kPrebuiltElfDir +
                               "/libtest_invalid-zero_shentsize.so";
 
@@ -1184,7 +1222,7 @@
 }
 
 TEST(dlfcn, dlopen_invalid_zero_shstrndx) {
-  const std::string libpath = g_testlib_root +
+  const std::string libpath = get_testlib_root() +
                               "/" + kPrebuiltElfDir +
                               "/libtest_invalid-zero_shstrndx.so";
 
@@ -1195,7 +1233,7 @@
 }
 
 TEST(dlfcn, dlopen_invalid_empty_shdr_table) {
-  const std::string libpath = g_testlib_root +
+  const std::string libpath = get_testlib_root() +
                               "/" + kPrebuiltElfDir +
                               "/libtest_invalid-empty_shdr_table.so";
 
@@ -1206,7 +1244,7 @@
 }
 
 TEST(dlfcn, dlopen_invalid_zero_shdr_table_offset) {
-  const std::string libpath = g_testlib_root +
+  const std::string libpath = get_testlib_root() +
                               "/" + kPrebuiltElfDir +
                               "/libtest_invalid-zero_shdr_table_offset.so";
 
@@ -1217,7 +1255,7 @@
 }
 
 TEST(dlfcn, dlopen_invalid_zero_shdr_table_content) {
-  const std::string libpath = g_testlib_root +
+  const std::string libpath = get_testlib_root() +
                               "/" + kPrebuiltElfDir +
                               "/libtest_invalid-zero_shdr_table_content.so";
 
@@ -1228,7 +1266,7 @@
 }
 
 TEST(dlfcn, dlopen_invalid_textrels) {
-  const std::string libpath = g_testlib_root +
+  const std::string libpath = get_testlib_root() +
                               "/" + kPrebuiltElfDir +
                               "/libtest_invalid-textrels.so";
 
@@ -1239,7 +1277,7 @@
 }
 
 TEST(dlfcn, dlopen_invalid_textrels2) {
-  const std::string libpath = g_testlib_root +
+  const std::string libpath = get_testlib_root() +
                               "/" + kPrebuiltElfDir +
                               "/libtest_invalid-textrels2.so";
 
diff --git a/tests/grp_pwd_test.cpp b/tests/grp_pwd_test.cpp
index a684780..54729b1 100644
--- a/tests/grp_pwd_test.cpp
+++ b/tests/grp_pwd_test.cpp
@@ -114,76 +114,76 @@
 
 #endif
 
-TEST(getpwnam, system_id_root) {
+TEST(pwd, getpwnam_system_id_root) {
   check_get_passwd("root", 0, TYPE_SYSTEM);
 }
 
-TEST(getpwnam, system_id_system) {
+TEST(pwd, getpwnam_system_id_system) {
   check_get_passwd("system", 1000, TYPE_SYSTEM);
 }
 
-TEST(getpwnam, app_id_radio) {
+TEST(pwd, getpwnam_app_id_radio) {
   check_get_passwd("radio", 1001, TYPE_SYSTEM);
 }
 
-TEST(getpwnam, oem_id_5000) {
+TEST(pwd, getpwnam_oem_id_5000) {
   check_get_passwd("oem_5000", 5000, TYPE_SYSTEM);
 }
 
-TEST(getpwnam, oem_id_5999) {
+TEST(pwd, getpwnam_oem_id_5999) {
   check_get_passwd("oem_5999", 5999, TYPE_SYSTEM);
 }
 
-TEST(getpwnam, oem_id_2900) {
+TEST(pwd, getpwnam_oem_id_2900) {
   check_get_passwd("oem_2900", 2900, TYPE_SYSTEM);
 }
 
-TEST(getpwnam, oem_id_2999) {
+TEST(pwd, getpwnam_oem_id_2999) {
   check_get_passwd("oem_2999", 2999, TYPE_SYSTEM);
 }
 
-TEST(getpwnam, app_id_nobody) {
+TEST(pwd, getpwnam_app_id_nobody) {
   check_get_passwd("nobody", 9999, TYPE_SYSTEM);
 }
 
-TEST(getpwnam, app_id_u0_a0) {
+TEST(pwd, getpwnam_app_id_u0_a0) {
   check_get_passwd("u0_a0", 10000, TYPE_APP);
 }
 
-TEST(getpwnam, app_id_u0_a1234) {
+TEST(pwd, getpwnam_app_id_u0_a1234) {
   check_get_passwd("u0_a1234", 11234, TYPE_APP);
 }
 
 // Test the difference between uid and shared gid.
-TEST(getpwnam, app_id_u0_a49999) {
+TEST(pwd, getpwnam_app_id_u0_a49999) {
   check_get_passwd("u0_a49999", 59999, TYPE_APP);
 }
 
-TEST(getpwnam, app_id_u0_i1) {
+TEST(pwd, getpwnam_app_id_u0_i1) {
   check_get_passwd("u0_i1", 99001, TYPE_APP);
 }
 
-TEST(getpwnam, app_id_u1_root) {
+TEST(pwd, getpwnam_app_id_u1_root) {
   check_get_passwd("u1_root", 100000, TYPE_SYSTEM);
 }
 
-TEST(getpwnam, app_id_u1_radio) {
+TEST(pwd, getpwnam_app_id_u1_radio) {
   check_get_passwd("u1_radio", 101001, TYPE_SYSTEM);
 }
 
-TEST(getpwnam, app_id_u1_a0) {
+TEST(pwd, getpwnam_app_id_u1_a0) {
   check_get_passwd("u1_a0", 110000, TYPE_APP);
 }
 
-TEST(getpwnam, app_id_u1_a40000) {
+TEST(pwd, getpwnam_app_id_u1_a40000) {
   check_get_passwd("u1_a40000", 150000, TYPE_APP);
 }
 
-TEST(getpwnam, app_id_u1_i0) {
+TEST(pwd, getpwnam_app_id_u1_i0) {
   check_get_passwd("u1_i0", 199000, TYPE_APP);
 }
 
-TEST(getpwent, iterate) {
+TEST(pwd, getpwent_iterate) {
   passwd* pwd;
   std::bitset<10000> exist;
   bool application = false;
@@ -295,80 +295,80 @@
 
 #endif
 
-TEST(getgrnam, system_id_root) {
+TEST(grp, getgrnam_system_id_root) {
   check_get_group("root", 0);
 }
 
-TEST(getgrnam, system_id_system) {
+TEST(grp, getgrnam_system_id_system) {
   check_get_group("system", 1000);
 }
 
-TEST(getgrnam, app_id_radio) {
+TEST(grp, getgrnam_app_id_radio) {
   check_get_group("radio", 1001);
 }
 
-TEST(getgrnam, oem_id_5000) {
+TEST(grp, getgrnam_oem_id_5000) {
   check_get_group("oem_5000", 5000);
 }
 
-TEST(getgrnam, oem_id_5999) {
+TEST(grp, getgrnam_oem_id_5999) {
   check_get_group("oem_5999", 5999);
 }
 
-TEST(getgrnam, oem_id_2900) {
+TEST(grp, getgrnam_oem_id_2900) {
   check_get_group("oem_2900", 2900);
 }
 
-TEST(getgrnam, oem_id_2999) {
+TEST(grp, getgrnam_oem_id_2999) {
   check_get_group("oem_2999", 2999);
 }
 
-TEST(getgrnam, app_id_nobody) {
+TEST(grp, getgrnam_app_id_nobody) {
   check_get_group("nobody", 9999);
 }
 
-TEST(getgrnam, app_id_u0_a0) {
+TEST(grp, getgrnam_app_id_u0_a0) {
   check_get_group("u0_a0", 10000);
 }
 
-TEST(getgrnam, app_id_u0_a1234) {
+TEST(grp, getgrnam_app_id_u0_a1234) {
   check_get_group("u0_a1234", 11234);
 }
 
-TEST(getgrnam, app_id_u0_a9999) {
+TEST(grp, getgrnam_app_id_u0_a9999) {
   check_get_group("u0_a9999", 19999);
 }
 
 // Test the difference between uid and shared gid.
-TEST(getgrnam, app_id_all_a9999) {
+TEST(grp, getgrnam_app_id_all_a9999) {
   check_get_group("all_a9999", 59999);
 }
 
-TEST(getgrnam, app_id_u0_i1) {
+TEST(grp, getgrnam_app_id_u0_i1) {
   check_get_group("u0_i1", 99001);
 }
 
-TEST(getgrnam, app_id_u1_root) {
+TEST(grp, getgrnam_app_id_u1_root) {
   check_get_group("u1_root", 100000);
 }
 
-TEST(getgrnam, app_id_u1_radio) {
+TEST(grp, getgrnam_app_id_u1_radio) {
   check_get_group("u1_radio", 101001);
 }
 
-TEST(getgrnam, app_id_u1_a0) {
+TEST(grp, getgrnam_app_id_u1_a0) {
   check_get_group("u1_a0", 110000);
 }
 
-TEST(getgrnam, app_id_u1_a40000) {
+TEST(grp, getgrnam_app_id_u1_a40000) {
   check_get_group("u1_a40000", 150000);
 }
 
-TEST(getgrnam, app_id_u1_i0) {
+TEST(grp, getgrnam_app_id_u1_i0) {
   check_get_group("u1_i0", 199000);
 }
 
-TEST(getgrnam_r, reentrancy) {
+TEST(grp, getgrnam_r_reentrancy) {
 #if defined(__BIONIC__)
   group grp_storage[2];
   char buf[2][512];
@@ -388,7 +388,7 @@
 #endif
 }
 
-TEST(getgrgid_r, reentrancy) {
+TEST(grp, getgrgid_r_reentrancy) {
 #if defined(__BIONIC__)
   group grp_storage[2];
   char buf[2][512];
@@ -408,7 +408,7 @@
 #endif
 }
 
-TEST(getgrnam_r, large_enough_suggested_buffer_size) {
+TEST(grp, getgrnam_r_large_enough_suggested_buffer_size) {
   long size = sysconf(_SC_GETGR_R_SIZE_MAX);
   ASSERT_GT(size, 0);
   char buf[size];
@@ -418,7 +418,7 @@
   check_group(grp, "root", 0);
 }
 
-TEST(getgrent, iterate) {
+TEST(grp, getgrent_iterate) {
   group* grp;
   std::bitset<10000> exist;
   bool application = false;
diff --git a/tests/gtest_globals.cpp b/tests/gtest_globals.cpp
index 4f2c82e..bb99dd6 100644
--- a/tests/gtest_globals.cpp
+++ b/tests/gtest_globals.cpp
@@ -21,11 +21,20 @@
 
 #include <string>
 
-static std::string get_testlib_root() {
+static std::string init_testlib_root() {
   std::string out_path;
   const char* data_dir = getenv("ANDROID_DATA");
   if (data_dir == nullptr) {
-    out_path = "/data";
+    // Calculate ANDROID_DATA assuming the binary is in "$ANDROID_DATA/somedir/binary-dir/binary"
+    std::string path = get_executable_path();
+
+    path = get_dirname(path.c_str());
+    path += "/../..";
+
+    if (!get_realpath(path.c_str(), &out_path)) {
+      printf("Failed to get realpath for \"%s\"", path.c_str());
+      abort();
+    }
   } else {
     out_path = data_dir;
   }
@@ -35,12 +44,18 @@
   out_path += "64";
 #endif
   out_path += "/bionic-loader-test-libs";
+
   std::string real_path;
   if (!get_realpath(out_path, &real_path)) {
+    printf("\"%s\": does not exists", out_path.c_str());
     abort();
   }
 
   return real_path;
 }
 
-const std::string g_testlib_root = get_testlib_root();
+const std::string& get_testlib_root() {
+  static const std::string testlib_root = init_testlib_root();
+  return testlib_root;
+}
+
diff --git a/tests/gtest_globals.h b/tests/gtest_globals.h
index fab2a39..019849d 100644
--- a/tests/gtest_globals.h
+++ b/tests/gtest_globals.h
@@ -21,6 +21,6 @@
 
 constexpr const char* kPrebuiltElfDir = "prebuilt-elf-files";
 
-extern const std::string g_testlib_root;
+const std::string& get_testlib_root();
 
 #endif  // _BIONIC_TESTS_GTEST_GLOBALS_H
diff --git a/tests/gtest_globals_cts.cpp b/tests/gtest_globals_cts.cpp
index bf891a1..2532ef1 100644
--- a/tests/gtest_globals_cts.cpp
+++ b/tests/gtest_globals_cts.cpp
@@ -18,4 +18,8 @@
 
 #include <string>
 
-const std::string g_testlib_root = "/data/local/tmp/lib/bionic-loader-test-libs";
+static const std::string g_testlib_root = "/data/local/tmp/lib/bionic-loader-test-libs";
+
+const std::string& get_testlib_root() {
+  return g_testlib_root;
+}
diff --git a/tests/gtest_main.cpp b/tests/gtest_main.cpp
index aacf9ae..f0dac7c 100644
--- a/tests/gtest_main.cpp
+++ b/tests/gtest_main.cpp
@@ -20,6 +20,7 @@
 #include <errno.h>
 #include <fcntl.h>
 #include <inttypes.h>
+#include <libgen.h>
 #include <limits.h>
 #include <signal.h>
 #include <stdarg.h>
@@ -65,6 +66,15 @@
   return true;
 }
 
+std::string get_dirname(const char* path) {
+#if defined(__BIONIC__)
+  return dirname(path);
+#else
+  // GLIBC does not have const char* dirname
+  return dirname(const_cast<char*>(path));
+#endif
+}
+
 int get_argc() {
   return g_argc;
 }
@@ -1010,26 +1020,27 @@
   std::string gtest_filter_str;
   for (size_t i = args.size() - 1; i >= 1; --i) {
     if (strncmp(args[i], "--gtest_filter=", strlen("--gtest_filter=")) == 0) {
-      gtest_filter_str = std::string(args[i]);
+      gtest_filter_str = args[i] + strlen("--gtest_filter=");
       args.erase(args.begin() + i);
       break;
     }
   }
   if (enable_selftest == true) {
-    args.push_back(strdup("--gtest_filter=bionic_selftest*"));
+    gtest_filter_str = "bionic_selftest*";
   } else {
-    if (gtest_filter_str == "") {
-      gtest_filter_str = "--gtest_filter=-bionic_selftest*";
+    if (gtest_filter_str.empty()) {
+      gtest_filter_str = "-bionic_selftest*";
     } else {
       // Find if '-' for NEGATIVE_PATTERNS exists.
-      if (gtest_filter_str.find(":-") != std::string::npos) {
+      if (gtest_filter_str.find("-") != std::string::npos) {
         gtest_filter_str += ":bionic_selftest*";
       } else {
         gtest_filter_str += ":-bionic_selftest*";
       }
     }
-    args.push_back(strdup(gtest_filter_str.c_str()));
   }
+  gtest_filter_str = "--gtest_filter=" + gtest_filter_str;
+  args.push_back(strdup(gtest_filter_str.c_str()));
 
   options.isolate = true;
   // Parse arguments that make us can't run in isolation mode.
diff --git a/tests/inttypes_test.cpp b/tests/inttypes_test.cpp
index 80580a4..01d6b82 100644
--- a/tests/inttypes_test.cpp
+++ b/tests/inttypes_test.cpp
@@ -98,11 +98,15 @@
 }
 
 TEST(inttypes, wcstoimax) {
-  ASSERT_EQ(123, wcstoimax(L"123", NULL, 10));
+  wchar_t* end = nullptr;
+  EXPECT_EQ(123, wcstoimax(L"  +123x", &end, 10));
+  EXPECT_EQ(L'x', *end);
 }
 
 TEST(inttypes, wcstoumax) {
-  ASSERT_EQ(123U, wcstoumax(L"123", NULL, 10));
+  wchar_t* end = nullptr;
+  EXPECT_EQ(123U, wcstoumax(L"  +123x", &end, 10));
+  EXPECT_EQ(L'x', *end);
 }
 
 TEST(inttypes, strtoimax_EINVAL) {
diff --git a/tests/langinfo_test.cpp b/tests/langinfo_test.cpp
new file mode 100644
index 0000000..6eae8bc
--- /dev/null
+++ b/tests/langinfo_test.cpp
@@ -0,0 +1,146 @@
+/*
+ * Copyright (C) 2016 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 <gtest/gtest.h>
+
+#include <langinfo.h>
+
+TEST(langinfo, category_CTYPE) {
+  ASSERT_STREQ("C.UTF-8", setlocale(LC_ALL, "C.UTF-8"));
+
+  EXPECT_STREQ("UTF-8", nl_langinfo(CODESET));
+}
+
+TEST(langinfo, category_TIME) {
+  ASSERT_STREQ("C.UTF-8", setlocale(LC_ALL, "C.UTF-8"));
+
+#if defined(__BIONIC__)
+  // bionic's C locale is ISO rather than en_US.
+  EXPECT_STREQ("%F %T %z", nl_langinfo(D_T_FMT));
+  EXPECT_STREQ("%F", nl_langinfo(D_FMT));
+#else
+  EXPECT_STREQ("%a %d %b %Y %r %Z", nl_langinfo(D_T_FMT));
+  EXPECT_STREQ("%m/%d/%Y", nl_langinfo(D_FMT));
+#endif
+  EXPECT_STREQ("%T", nl_langinfo(T_FMT));
+  EXPECT_STREQ("%I:%M:%S %p", nl_langinfo(T_FMT_AMPM));
+  EXPECT_STREQ("AM", nl_langinfo(AM_STR));
+  EXPECT_STREQ("PM", nl_langinfo(PM_STR));
+  EXPECT_STREQ("Sunday", nl_langinfo(DAY_1));
+  EXPECT_STREQ("Monday", nl_langinfo(DAY_2));
+  EXPECT_STREQ("Tuesday", nl_langinfo(DAY_3));
+  EXPECT_STREQ("Wednesday", nl_langinfo(DAY_4));
+  EXPECT_STREQ("Thursday", nl_langinfo(DAY_5));
+  EXPECT_STREQ("Friday", nl_langinfo(DAY_6));
+  EXPECT_STREQ("Saturday", nl_langinfo(DAY_7));
+  EXPECT_STREQ("Sun", nl_langinfo(ABDAY_1));
+  EXPECT_STREQ("Mon", nl_langinfo(ABDAY_2));
+  EXPECT_STREQ("Tue", nl_langinfo(ABDAY_3));
+  EXPECT_STREQ("Wed", nl_langinfo(ABDAY_4));
+  EXPECT_STREQ("Thu", nl_langinfo(ABDAY_5));
+  EXPECT_STREQ("Fri", nl_langinfo(ABDAY_6));
+  EXPECT_STREQ("Sat", nl_langinfo(ABDAY_7));
+  EXPECT_STREQ("January", nl_langinfo(MON_1));
+  EXPECT_STREQ("February", nl_langinfo(MON_2));
+  EXPECT_STREQ("March", nl_langinfo(MON_3));
+  EXPECT_STREQ("April", nl_langinfo(MON_4));
+  EXPECT_STREQ("May", nl_langinfo(MON_5));
+  EXPECT_STREQ("June", nl_langinfo(MON_6));
+  EXPECT_STREQ("July", nl_langinfo(MON_7));
+  EXPECT_STREQ("August", nl_langinfo(MON_8));
+  EXPECT_STREQ("September", nl_langinfo(MON_9));
+  EXPECT_STREQ("October", nl_langinfo(MON_10));
+  EXPECT_STREQ("November", nl_langinfo(MON_11));
+  EXPECT_STREQ("December", nl_langinfo(MON_12));
+  EXPECT_STREQ("Jan", nl_langinfo(ABMON_1));
+  EXPECT_STREQ("Feb", nl_langinfo(ABMON_2));
+  EXPECT_STREQ("Mar", nl_langinfo(ABMON_3));
+  EXPECT_STREQ("Apr", nl_langinfo(ABMON_4));
+  EXPECT_STREQ("May", nl_langinfo(ABMON_5));
+  EXPECT_STREQ("Jun", nl_langinfo(ABMON_6));
+  EXPECT_STREQ("Jul", nl_langinfo(ABMON_7));
+  EXPECT_STREQ("Aug", nl_langinfo(ABMON_8));
+  EXPECT_STREQ("Sep", nl_langinfo(ABMON_9));
+  EXPECT_STREQ("Oct", nl_langinfo(ABMON_10));
+  EXPECT_STREQ("Nov", nl_langinfo(ABMON_11));
+  EXPECT_STREQ("Dec", nl_langinfo(ABMON_12));
+  EXPECT_STREQ("", nl_langinfo(ERA));
+  EXPECT_STREQ("", nl_langinfo(ERA_D_FMT));
+  EXPECT_STREQ("", nl_langinfo(ERA_D_T_FMT));
+  EXPECT_STREQ("", nl_langinfo(ERA_T_FMT));
+  EXPECT_STREQ("", nl_langinfo(ALT_DIGITS));
+}
+
+TEST(langinfo, category_NUMERIC) {
+  ASSERT_STREQ("C.UTF-8", setlocale(LC_ALL, "C.UTF-8"));
+
+  EXPECT_STREQ(".", nl_langinfo(RADIXCHAR));
+  EXPECT_STREQ("", nl_langinfo(THOUSEP));
+}
+
+TEST(langinfo, category_MESSAGES) {
+  ASSERT_STREQ("C.UTF-8", setlocale(LC_ALL, "C.UTF-8"));
+
+  EXPECT_STREQ("^[yY]", nl_langinfo(YESEXPR));
+  EXPECT_STREQ("^[nN]", nl_langinfo(NOEXPR));
+}
+
+TEST(langinfo, category_MONETARY) {
+  ASSERT_STREQ("C.UTF-8", setlocale(LC_ALL, "C.UTF-8"));
+
+  // POSIX says that if the currency symbol is the empty string (as it is for
+  // the C locale), an implementation can return the empty string and not
+  // include the leading [+-.] that signifies where the currency symbol should
+  // appear. For consistency with localeconv (which POSIX says to prefer for
+  // RADIXCHAR, THOUSEP, and CRNCYSTR) we return the empty string. glibc
+  // disagrees.
+#if defined(__BIONIC__)
+  EXPECT_STREQ("", nl_langinfo(CRNCYSTR));
+#else
+  EXPECT_STREQ("-", nl_langinfo(CRNCYSTR));
+#endif
+}
+
+TEST(langinfo, invalid) {
+  ASSERT_STREQ("C.UTF-8", setlocale(LC_ALL, "C.UTF-8"));
+
+  EXPECT_STREQ("", nl_langinfo(-1));
+  EXPECT_STREQ("", nl_langinfo(0));
+  EXPECT_STREQ("", nl_langinfo(666));
+}
+
+TEST(langinfo, matches_localeconv) {
+  ASSERT_STREQ("C.UTF-8", setlocale(LC_ALL, "C.UTF-8"));
+
+  EXPECT_STREQ(localeconv()->decimal_point, nl_langinfo(RADIXCHAR));
+  EXPECT_STREQ(localeconv()->thousands_sep, nl_langinfo(THOUSEP));
+#if defined(__BIONIC__)
+  // (See comment in category_MONETARY test.)
+  EXPECT_STREQ(localeconv()->currency_symbol, nl_langinfo(CRNCYSTR));
+#endif
+}
diff --git a/tests/libs/Android.bp b/tests/libs/Android.bp
index fe0d6ab..4cd991a 100644
--- a/tests/libs/Android.bp
+++ b/tests/libs/Android.bp
@@ -411,6 +411,24 @@
 }
 
 // -----------------------------------------------------------------------------
+// Check that RTLD_NEXT of a libc symbol works in dlopened library
+// -----------------------------------------------------------------------------
+cc_test_library {
+    name: "libtest_check_rtld_next_from_library",
+    defaults: ["bionic_testlib_defaults"],
+    srcs: ["check_rtld_next_from_library.cpp"],
+
+    target: {
+        android: {
+            shared_libs: ["libdl"],
+        },
+        host: {
+            host_ldlibs: ["-ldl"],
+        },
+    },
+}
+
+// -----------------------------------------------------------------------------
 // Library with constructor that calls dlopen() b/7941716
 // -----------------------------------------------------------------------------
 cc_test_library {
diff --git a/tests/libs/Android.build.dt_runpath.mk b/tests/libs/Android.build.dt_runpath.mk
index 60844e5..a3fcac5 100644
--- a/tests/libs/Android.build.dt_runpath.mk
+++ b/tests/libs/Android.build.dt_runpath.mk
@@ -80,7 +80,7 @@
 libtest_dt_runpath_d_zip_shared_libraries := libtest_dt_runpath_b libtest_dt_runpath_c
 libtest_dt_runpath_d_zip_ldflags := -Wl,--rpath,\$${ORIGIN}/dt_runpath_b_c_x -Wl,--enable-new-dtags
 libtest_dt_runpath_d_zip_ldlibs := -ldl
-libtest_dt_runpath_d_zip_install_to_out_data_dir := $(module)
+libtest_dt_runpath_d_zip_install_to_native_tests_dir := $(module)
 
 module_tag := optional
 build_type := target
diff --git a/tests/libs/Android.build.target.testlib.mk b/tests/libs/Android.build.testlib.host.mk
similarity index 81%
rename from tests/libs/Android.build.target.testlib.mk
rename to tests/libs/Android.build.testlib.host.mk
index 1e767c2..38970dc 100644
--- a/tests/libs/Android.build.target.testlib.mk
+++ b/tests/libs/Android.build.testlib.host.mk
@@ -1,5 +1,5 @@
 #
-# Copyright (C) 2015 The Android Open Source Project
+# Copyright (C) 2016 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.
@@ -15,6 +15,5 @@
 #
 
 build_target := SHARED_LIBRARY
-build_type := target
-include $(TEST_PATH)/Android.build.mk
-
+build_type := host
+include $(LOCAL_PATH)/Android.build.testlib.internal.mk
diff --git a/tests/libs/Android.build.testlib.internal.mk b/tests/libs/Android.build.testlib.internal.mk
new file mode 100644
index 0000000..e1fec2b
--- /dev/null
+++ b/tests/libs/Android.build.testlib.internal.mk
@@ -0,0 +1,27 @@
+#
+# Copyright (C) 2016 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.
+#
+
+# 1. Install test libraries to $ANDROID_DATA/nativetests../bionic-loader-test-libs/
+#    by default.
+ifeq ($($(module)_relative_install_path),)
+  $(module)_install_to_native_tests_dir := bionic-loader-test-libs
+else
+  $(module)_install_to_native_tests_dir := bionic-loader-test-libs/$($(module)_relative_install_path)
+endif
+# 2. Set dt_runpath to origin to resolve dependencies
+$(module)_ldflags += -Wl,--rpath,\$${ORIGIN} -Wl,--enable-new-dtags
+
+include $(TEST_PATH)/Android.build.mk
diff --git a/tests/libs/Android.build.testlib.mk b/tests/libs/Android.build.testlib.mk
index 833caf6..a46c457 100644
--- a/tests/libs/Android.build.testlib.mk
+++ b/tests/libs/Android.build.testlib.mk
@@ -14,9 +14,6 @@
 # limitations under the License.
 #
 
-build_target := SHARED_LIBRARY
-build_type := host
-include $(TEST_PATH)/Android.build.mk
+include $(LOCAL_PATH)/Android.build.testlib.host.mk
 
 include $(LOCAL_PATH)/Android.build.testlib.target.mk
-
diff --git a/tests/libs/Android.build.testlib.target.mk b/tests/libs/Android.build.testlib.target.mk
index b79dbfc..5ec0d71 100644
--- a/tests/libs/Android.build.testlib.target.mk
+++ b/tests/libs/Android.build.testlib.target.mk
@@ -14,14 +14,6 @@
 # limitations under the License.
 #
 
+build_target := SHARED_LIBRARY
 build_type := target
-# 1. Install test libraries to /data/nativetests../bionic-loader-test-libs/
-#    by default.
-ifeq ($($(module)_relative_install_path),)
-  $(module)_install_to_out_data_dir := bionic-loader-test-libs
-else
-  $(module)_install_to_out_data_dir := bionic-loader-test-libs/$($(module)_relative_install_path)
-endif
-# 2. Set dt_runpath to origin to resolve dependencies
-$(module)_ldflags += -Wl,--rpath,\$${ORIGIN} -Wl,--enable-new-dtags
-include $(TEST_PATH)/Android.build.mk
+include $(LOCAL_PATH)/Android.build.testlib.internal.mk
diff --git a/tests/libs/check_rtld_next_from_library.cpp b/tests/libs/check_rtld_next_from_library.cpp
new file mode 100644
index 0000000..45d8eea
--- /dev/null
+++ b/tests/libs/check_rtld_next_from_library.cpp
@@ -0,0 +1,36 @@
+/*
+ * Copyright (C) 2016 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <dlfcn.h>
+#include <stdlib.h>
+
+static void* g_libc_close_ptr;
+
+static void __attribute__((constructor)) __libc_close_lookup() {
+  g_libc_close_ptr = dlsym(RTLD_NEXT, "close");
+}
+
+// A libc function used for RTLD_NEXT
+// This function in not supposed to be called
+extern "C" int __attribute__((weak)) close(int) {
+  abort();
+}
+
+extern "C" void* get_libc_close_ptr() {
+  return g_libc_close_ptr;
+}
+
+
diff --git a/tests/pty_test.cpp b/tests/pty_test.cpp
index 9b5785a..74415d5 100644
--- a/tests/pty_test.cpp
+++ b/tests/pty_test.cpp
@@ -14,11 +14,17 @@
  * limitations under the License.
  */
 
+#include <pty.h>
+
 #include <gtest/gtest.h>
 
-#include <pty.h>
+#include <pthread.h>
 #include <sys/ioctl.h>
 
+#include <atomic>
+
+#include <android-base/file.h>
+
 #include "utils.h"
 
 TEST(pty, openpty) {
diff --git a/tests/stdlib_test.cpp b/tests/stdlib_test.cpp
index 5b9442f..fc17cde 100644
--- a/tests/stdlib_test.cpp
+++ b/tests/stdlib_test.cpp
@@ -298,6 +298,11 @@
   EXPECT_PRED_FORMAT2(pred, 9.0, fn("0.9e1", nullptr));
   EXPECT_PRED_FORMAT2(pred, 9.0, fn("0x1.2p3", nullptr));
 
+  const char* s = " \t\v\f\r\n9.0";
+  char* p;
+  EXPECT_PRED_FORMAT2(pred, 9.0, fn(s, &p));
+  EXPECT_EQ(s + strlen(s), p);
+
   EXPECT_TRUE(isnan(fn("+nan", nullptr)));
   EXPECT_TRUE(isnan(fn("nan", nullptr)));
   EXPECT_TRUE(isnan(fn("-nan", nullptr)));
@@ -306,7 +311,6 @@
   EXPECT_TRUE(isnan(fn("nan(0xff)", nullptr)));
   EXPECT_TRUE(isnan(fn("-nan(0xff)", nullptr)));
 
-  char* p;
   EXPECT_TRUE(isnan(fn("+nanny", &p)));
   EXPECT_STREQ("ny", p);
   EXPECT_TRUE(isnan(fn("nanny", &p)));
diff --git a/tests/sys_prctl_test.cpp b/tests/sys_prctl_test.cpp
index 205db86..1d80dbc 100644
--- a/tests/sys_prctl_test.cpp
+++ b/tests/sys_prctl_test.cpp
@@ -15,7 +15,9 @@
  */
 
 #include <inttypes.h>
+#include <limits.h>
 #include <stdio.h>
+#include <sys/capability.h>
 #include <sys/mman.h>
 #include <sys/prctl.h>
 #include <unistd.h>
@@ -64,3 +66,51 @@
   GTEST_LOG_(INFO) << "This test does nothing as it tests an Android specific kernel feature.";
 #endif
 }
+
+TEST(sys_prctl, pr_cap_ambient) {
+// PR_CAP_AMBIENT was introduced in v4.3.  Android devices should always
+// have a backport, but we can't guarantee it's available on the host.
+#if defined(__ANDROID__) || defined(PR_CAP_AMBIENT)
+  const std::string caps_sha =
+      "https://git.kernel.org/cgit/linux/kernel/git/torvalds/linux.git/commit/"
+      "?id=58319057b7847667f0c9585b9de0e8932b0fdb08";
+  const std::string caps_typo_sha =
+      "https://git.kernel.org/cgit/linux/kernel/git/torvalds/linux.git/commit/"
+      "?id=b7f76ea2ef6739ee484a165ffbac98deb855d3d3";
+
+  auto err = prctl(PR_CAP_AMBIENT, PR_CAP_AMBIENT_CLEAR_ALL, 0, 0, 0);
+  EXPECT_EQ(0, err);
+  // EINVAL -> unrecognized prctl option
+  ASSERT_NE(EINVAL, errno) << "kernel missing required commits:\n"
+                           << caps_sha << "\n"
+                           << caps_typo_sha << "\n";
+
+  // Unprivileged processes shouldn't be able to raise CAP_SYS_ADMIN,
+  // but they can check or lower it
+  err = prctl(PR_CAP_AMBIENT, PR_CAP_AMBIENT_RAISE, CAP_SYS_ADMIN, 0, 0);
+  EXPECT_EQ(-1, err);
+  EXPECT_EQ(EPERM, errno);
+
+  err = prctl(PR_CAP_AMBIENT, PR_CAP_AMBIENT_IS_SET, CAP_SYS_ADMIN, 0, 0);
+  EXPECT_EQ(0, err);
+
+  err = prctl(PR_CAP_AMBIENT, PR_CAP_AMBIENT_LOWER, CAP_SYS_ADMIN, 0, 0);
+  EXPECT_EQ(0, err);
+
+  // ULONG_MAX isn't a legal cap
+  err = prctl(PR_CAP_AMBIENT, PR_CAP_AMBIENT_RAISE, ULONG_MAX, 0, 0);
+  EXPECT_EQ(-1, err);
+  EXPECT_EQ(EINVAL, errno);
+
+  err = prctl(PR_CAP_AMBIENT, PR_CAP_AMBIENT_IS_SET, ULONG_MAX, 0, 0);
+  EXPECT_EQ(-1, err);
+  EXPECT_EQ(EINVAL, errno);
+
+  err = prctl(PR_CAP_AMBIENT, PR_CAP_AMBIENT_LOWER, ULONG_MAX, 0, 0);
+  EXPECT_EQ(-1, err);
+  EXPECT_EQ(EINVAL, errno);
+#else
+  GTEST_LOG_(INFO)
+      << "Skipping test that requires host support for PR_CAP_AMBIENT.";
+#endif
+}
diff --git a/tests/unistd_test.cpp b/tests/unistd_test.cpp
index b488e82..9d809f0 100644
--- a/tests/unistd_test.cpp
+++ b/tests/unistd_test.cpp
@@ -530,12 +530,7 @@
 
 static int CloneStartRoutine(int (*start_routine)(void*)) {
   void* child_stack[1024];
-  int clone_result = clone(start_routine, &child_stack[1024], CLONE_NEWNS | SIGCHLD, NULL);
-  if (clone_result == -1 && errno == EPERM && getuid() != 0) {
-    GTEST_LOG_(INFO) << "This test only works if you have permission to CLONE_NEWNS; try running as root.\n";
-    return clone_result;
-  }
-  return clone_result;
+  return clone(start_routine, &child_stack[1024], SIGCHLD, NULL);
 }
 
 static int GetPidCachingCloneStartRoutine(void*) {
@@ -1352,7 +1347,8 @@
   ExecTestHelper eth;
   errno = 0;
   ASSERT_EQ(-1, execvpe("this-does-not-exist", eth.GetArgs(), eth.GetEnv()));
-  ASSERT_EQ(ENOENT, errno);
+  // Running in CTS we might not even be able to search all directories in $PATH.
+  ASSERT_TRUE(errno == ENOENT || errno == EACCES);
 }
 
 TEST(UNISTD_TEST, execvpe) {
@@ -1385,8 +1381,8 @@
   ASSERT_EQ(-1, execvpe(basename(tf.filename), eth.GetArgs(), eth.GetEnv()));
   ASSERT_EQ(EACCES, errno);
 
-  // Make it executable.
-  ASSERT_EQ(0, chmod(tf.filename, 0555));
+  // Make it executable (and keep it writable because we're going to rewrite it below).
+  ASSERT_EQ(0, chmod(tf.filename, 0777));
 
   // TemporaryFile will have a writable fd, so we can test ETXTBSY while we're here...
   errno = 0;
diff --git a/tests/utils.h b/tests/utils.h
index c62da75..4c3aef4 100644
--- a/tests/utils.h
+++ b/tests/utils.h
@@ -128,6 +128,8 @@
 
 // Get realpath
 bool get_realpath(const std::string& path, std::string* realpath);
+// Get dirname
+std::string get_dirname(const char* path);
 
 // Access to argc/argv/envp
 int get_argc();
diff --git a/tests/wchar_test.cpp b/tests/wchar_test.cpp
index 34ed5a7..830eb70 100644
--- a/tests/wchar_test.cpp
+++ b/tests/wchar_test.cpp
@@ -686,6 +686,11 @@
   EXPECT_PRED_FORMAT2(pred, 9.0, fn(L"0.9e1", nullptr));
   EXPECT_PRED_FORMAT2(pred, 9.0, fn(L"0x1.2p3", nullptr));
 
+  const wchar_t* s = L" \t\v\f\r\n9.0";
+  wchar_t* p;
+  EXPECT_PRED_FORMAT2(pred, 9.0, fn(s, &p));
+  EXPECT_EQ(s + wcslen(s), p);
+
   EXPECT_TRUE(isnan(fn(L"+nan", nullptr)));
   EXPECT_TRUE(isnan(fn(L"nan", nullptr)));
   EXPECT_TRUE(isnan(fn(L"-nan", nullptr)));
@@ -694,7 +699,6 @@
   EXPECT_TRUE(isnan(fn(L"nan(0xff)", nullptr)));
   EXPECT_TRUE(isnan(fn(L"-nan(0xff)", nullptr)));
 
-  wchar_t* p;
   EXPECT_TRUE(isnan(fn(L"+nanny", &p)));
   EXPECT_STREQ(L"ny", p);
   EXPECT_TRUE(isnan(fn(L"nanny", &p)));
diff --git a/tests/wctype_test.cpp b/tests/wctype_test.cpp
index fe2e374..84a0e65 100644
--- a/tests/wctype_test.cpp
+++ b/tests/wctype_test.cpp
@@ -16,6 +16,8 @@
 
 #include <wctype.h>
 
+#include <dlfcn.h>
+
 #include <gtest/gtest.h>
 
 class UtfLocale {
@@ -25,63 +27,75 @@
   locale_t l;
 };
 
+// bionic's dlsym doesn't work in static binaries, so we can't access icu,
+// so any unicode test case will fail.
+static bool have_dl = (dlopen("libc.so", 0) != nullptr);
+
 static void TestIsWideFn(int fn(wint_t),
                          int fn_l(wint_t, locale_t),
                          const wchar_t* trues,
                          const wchar_t* falses) {
   UtfLocale l;
   for (const wchar_t* p = trues; *p; ++p) {
+    if (!have_dl && *p > 0x7f) {
+      GTEST_LOG_(INFO) << "skipping unicode test " << *p;
+      continue;
+    }
     EXPECT_TRUE(fn(*p)) << *p;
     EXPECT_TRUE(fn_l(*p, l.l)) << *p;
   }
   for (const wchar_t* p = falses; *p; ++p) {
+    if (!have_dl && *p > 0x7f) {
+      GTEST_LOG_(INFO) << "skipping unicode test " << *p;
+      continue;
+    }
     EXPECT_FALSE(fn(*p)) << *p;
     EXPECT_FALSE(fn_l(*p, l.l)) << *p;
   }
 }
 
 TEST(wctype, iswalnum) {
-  TestIsWideFn(iswalnum, iswalnum_l, L"1aA", L"! \b");
+  TestIsWideFn(iswalnum, iswalnum_l, L"1aAÇçΔδ", L"! \b");
 }
 
 TEST(wctype, iswalpha) {
-  TestIsWideFn(iswalpha, iswalpha_l, L"aA", L"1! \b");
+  TestIsWideFn(iswalpha, iswalpha_l, L"aAÇçΔδ", L"1! \b");
 }
 
 TEST(wctype, iswblank) {
-  TestIsWideFn(iswblank, iswblank_l, L" \t", L"1aA!\b");
+  TestIsWideFn(iswblank, iswblank_l, L" \t", L"1aA!\bÇçΔδ");
 }
 
 TEST(wctype, iswcntrl) {
-  TestIsWideFn(iswcntrl, iswcntrl_l, L"\b", L"1aA! ");
+  TestIsWideFn(iswcntrl, iswcntrl_l, L"\b\u009f", L"1aA! ÇçΔδ");
 }
 
 TEST(wctype, iswdigit) {
-  TestIsWideFn(iswdigit, iswdigit_l, L"1", L"aA! \b");
+  TestIsWideFn(iswdigit, iswdigit_l, L"1", L"aA! \bÇçΔδ");
 }
 
 TEST(wctype, iswgraph) {
-  TestIsWideFn(iswgraph, iswgraph_l, L"1aA!", L" \b");
+  TestIsWideFn(iswgraph, iswgraph_l, L"1aA!ÇçΔδ", L" \b");
 }
 
 TEST(wctype, iswlower) {
-  TestIsWideFn(iswlower, iswlower_l, L"a", L"1A! \b");
+  TestIsWideFn(iswlower, iswlower_l, L"açδ", L"1A! \bÇΔ");
 }
 
 TEST(wctype, iswprint) {
-  TestIsWideFn(iswprint, iswprint_l, L"1aA! ", L"\b");
+  TestIsWideFn(iswprint, iswprint_l, L"1aA! ÇçΔδ", L"\b");
 }
 
 TEST(wctype, iswpunct) {
-  TestIsWideFn(iswpunct, iswpunct_l, L"!", L"1aA \b");
+  TestIsWideFn(iswpunct, iswpunct_l, L"!", L"1aA \bÇçΔδ");
 }
 
 TEST(wctype, iswspace) {
-  TestIsWideFn(iswspace, iswspace_l, L" \f\t", L"1aA!\b");
+  TestIsWideFn(iswspace, iswspace_l, L" \f\t", L"1aA!\bÇçΔδ");
 }
 
 TEST(wctype, iswupper) {
-  TestIsWideFn(iswupper, iswupper_l, L"A", L"1a! \b");
+  TestIsWideFn(iswupper, iswupper_l, L"AÇΔ", L"1a! \bçδ");
 }
 
 TEST(wctype, iswxdigit) {
@@ -89,29 +103,65 @@
 }
 
 TEST(wctype, towlower) {
+  EXPECT_EQ(WEOF, towlower(WEOF));
   EXPECT_EQ(wint_t('!'), towlower(L'!'));
   EXPECT_EQ(wint_t('a'), towlower(L'a'));
   EXPECT_EQ(wint_t('a'), towlower(L'A'));
+  if (have_dl) {
+    EXPECT_EQ(wint_t(L'ç'), towlower(L'ç'));
+    EXPECT_EQ(wint_t(L'ç'), towlower(L'Ç'));
+    EXPECT_EQ(wint_t(L'δ'), towlower(L'δ'));
+    EXPECT_EQ(wint_t(L'δ'), towlower(L'Δ'));
+  } else {
+    GTEST_LOG_(INFO) << "skipping unicode towlower tests";
+  }
 }
 
 TEST(wctype, towlower_l) {
   UtfLocale l;
+  EXPECT_EQ(WEOF, towlower(WEOF));
   EXPECT_EQ(wint_t('!'), towlower_l(L'!', l.l));
   EXPECT_EQ(wint_t('a'), towlower_l(L'a', l.l));
   EXPECT_EQ(wint_t('a'), towlower_l(L'A', l.l));
+  if (have_dl) {
+    EXPECT_EQ(wint_t(L'ç'), towlower_l(L'ç', l.l));
+    EXPECT_EQ(wint_t(L'ç'), towlower_l(L'Ç', l.l));
+    EXPECT_EQ(wint_t(L'δ'), towlower_l(L'δ', l.l));
+    EXPECT_EQ(wint_t(L'δ'), towlower_l(L'Δ', l.l));
+  } else {
+    GTEST_LOG_(INFO) << "skipping unicode towlower_l tests";
+  }
 }
 
 TEST(wctype, towupper) {
+  EXPECT_EQ(WEOF, towupper(WEOF));
   EXPECT_EQ(wint_t('!'), towupper(L'!'));
   EXPECT_EQ(wint_t('A'), towupper(L'a'));
   EXPECT_EQ(wint_t('A'), towupper(L'A'));
+  if (have_dl) {
+    EXPECT_EQ(wint_t(L'Ç'), towupper(L'ç'));
+    EXPECT_EQ(wint_t(L'Ç'), towupper(L'Ç'));
+    EXPECT_EQ(wint_t(L'Δ'), towupper(L'δ'));
+    EXPECT_EQ(wint_t(L'Δ'), towupper(L'Δ'));
+  } else {
+    GTEST_LOG_(INFO) << "skipping unicode towupper tests";
+  }
 }
 
 TEST(wctype, towupper_l) {
   UtfLocale l;
+  EXPECT_EQ(WEOF, towupper_l(WEOF, l.l));
   EXPECT_EQ(wint_t('!'), towupper_l(L'!', l.l));
   EXPECT_EQ(wint_t('A'), towupper_l(L'a', l.l));
   EXPECT_EQ(wint_t('A'), towupper_l(L'A', l.l));
+  if (have_dl) {
+    EXPECT_EQ(wint_t(L'Ç'), towupper_l(L'ç', l.l));
+    EXPECT_EQ(wint_t(L'Ç'), towupper_l(L'Ç', l.l));
+    EXPECT_EQ(wint_t(L'Δ'), towupper_l(L'δ', l.l));
+    EXPECT_EQ(wint_t(L'Δ'), towupper_l(L'Δ', l.l));
+  } else {
+    GTEST_LOG_(INFO) << "skipping unicode towupper_l tests";
+  }
 }
 
 TEST(wctype, wctype) {
diff --git a/tools/versioner/src/Preprocessor.cpp b/tools/versioner/src/Preprocessor.cpp
index c863e6c..86bb225 100644
--- a/tools/versioner/src/Preprocessor.cpp
+++ b/tools/versioner/src/Preprocessor.cpp
@@ -439,8 +439,13 @@
 
   // Copy over the original headers before preprocessing.
   char* fts_paths[2] = { const_cast<char*>(src_dir.c_str()), nullptr };
-  FTS* fts = fts_open(fts_paths, FTS_LOGICAL, nullptr);
-  while (FTSENT* ent = fts_read(fts)) {
+  std::unique_ptr<FTS, decltype(&fts_close)> fts(fts_open(fts_paths, FTS_LOGICAL, nullptr),
+                                                 fts_close);
+  if (!fts) {
+    err(1, "failed to open directory %s", src_dir.c_str());
+  }
+
+  while (FTSENT* ent = fts_read(fts.get())) {
     llvm::StringRef path = ent->fts_path;
     if (!path.startswith(src_dir)) {
       err(1, "path '%s' doesn't start with source dir '%s'", ent->fts_path, src_dir.c_str());
@@ -461,7 +466,6 @@
            dst_path.c_str());
     }
   }
-  fts_close(fts);
 
   for (const auto& file_it : guards) {
     file_lines[file_it.first] = readFileLines(file_it.first);
diff --git a/tools/versioner/src/SymbolDatabase.cpp b/tools/versioner/src/SymbolDatabase.cpp
index 90c0c9f..bd4b99d 100644
--- a/tools/versioner/src/SymbolDatabase.cpp
+++ b/tools/versioner/src/SymbolDatabase.cpp
@@ -130,7 +130,7 @@
       }
 
       if (result.count(symbol_name) != 0) {
-        if (verbose) {
+        if (strict) {
           printf("duplicated symbol '%s' in '%s'\n", symbol_name.str().c_str(), file.str().c_str());
         }
       }
diff --git a/tools/versioner/src/Utils.cpp b/tools/versioner/src/Utils.cpp
index dd087a5..ef7facc 100644
--- a/tools/versioner/src/Utils.cpp
+++ b/tools/versioner/src/Utils.cpp
@@ -25,6 +25,8 @@
 #include <string>
 #include <vector>
 
+#include <android-base/strings.h>
+
 #include "DeclarationDatabase.h"
 
 std::string getWorkingDir() {
@@ -35,27 +37,30 @@
   return buf;
 }
 
-std::vector<std::string> collectFiles(const std::string& directory) {
-  std::vector<std::string> files;
+std::vector<std::string> collectHeaders(const std::string& directory) {
+  std::vector<std::string> headers;
 
   char* dir_argv[2] = { const_cast<char*>(directory.c_str()), nullptr };
-  FTS* fts = fts_open(dir_argv, FTS_LOGICAL | FTS_NOCHDIR, nullptr);
+  std::unique_ptr<FTS, decltype(&fts_close)> fts(
+      fts_open(dir_argv, FTS_LOGICAL | FTS_NOCHDIR, nullptr), fts_close);
 
   if (!fts) {
     err(1, "failed to open directory '%s'", directory.c_str());
   }
 
-  FTSENT* ent;
-  while ((ent = fts_read(fts))) {
+  while (FTSENT* ent = fts_read(fts.get())) {
     if (ent->fts_info & (FTS_D | FTS_DP)) {
       continue;
     }
 
-    files.push_back(ent->fts_path);
+    if (!android::base::EndsWith(ent->fts_path, ".h")) {
+      continue;
+    }
+
+    headers.push_back(ent->fts_path);
   }
 
-  fts_close(fts);
-  return files;
+  return headers;
 }
 
 llvm::StringRef StripPrefix(llvm::StringRef string, llvm::StringRef prefix) {
diff --git a/tools/versioner/src/Utils.h b/tools/versioner/src/Utils.h
index 7876f23..44a34f8 100644
--- a/tools/versioner/src/Utils.h
+++ b/tools/versioner/src/Utils.h
@@ -27,7 +27,7 @@
 #include <llvm/ADT/StringRef.h>
 
 std::string getWorkingDir();
-std::vector<std::string> collectFiles(const std::string& directory);
+std::vector<std::string> collectHeaders(const std::string& directory);
 
 static inline std::string dirname(const std::string& path) {
   std::unique_ptr<char, decltype(&free)> path_copy(strdup(path.c_str()), free);
diff --git a/tools/versioner/src/VFS.cpp b/tools/versioner/src/VFS.cpp
index cd6d367..1aa7229 100644
--- a/tools/versioner/src/VFS.cpp
+++ b/tools/versioner/src/VFS.cpp
@@ -36,12 +36,14 @@
 
 static void addDirectoryToVFS(InMemoryFileSystem* vfs, const std::string& path) {
   char* paths[] = { const_cast<char*>(path.c_str()), nullptr };
-  FTS* fts = fts_open(paths, FTS_COMFOLLOW | FTS_LOGICAL | FTS_NOCHDIR, nullptr);
+  std::unique_ptr<FTS, decltype(&fts_close)> fts(
+      fts_open(paths, FTS_COMFOLLOW | FTS_LOGICAL | FTS_NOCHDIR, nullptr), fts_close);
+
   if (!fts) {
     err(1, "failed to open directory %s", path.c_str());
   }
 
-  while (FTSENT* ent = fts_read(fts)) {
+  while (FTSENT* ent = fts_read(fts.get())) {
     if ((ent->fts_info & FTS_F) == 0) {
       continue;
     }
@@ -61,8 +63,6 @@
       errx(1, "failed to add file '%s'", file_path);
     }
   }
-
-  fts_close(fts);
 }
 
 llvm::IntrusiveRefCntPtr<FileSystem> createCommonVFS(const std::string& header_dir,
diff --git a/tools/versioner/src/versioner.cpp b/tools/versioner/src/versioner.cpp
index 86349e1..6c287d9 100644
--- a/tools/versioner/src/versioner.cpp
+++ b/tools/versioner/src/versioner.cpp
@@ -22,7 +22,12 @@
 #include <sys/types.h>
 #include <unistd.h>
 
+#if defined(__linux__)
+#include <sched.h>
+#endif
+
 #include <atomic>
+#include <chrono>
 #include <functional>
 #include <iostream>
 #include <map>
@@ -36,6 +41,7 @@
 
 #include <llvm/ADT/StringRef.h>
 
+#include <android-base/macros.h>
 #include <android-base/parseint.h>
 
 #include "Arch.h"
@@ -48,15 +54,32 @@
 
 #include "versioner.h"
 
+using namespace std::chrono_literals;
 using namespace std::string_literals;
 
-bool add_include;
+bool strict;
 bool verbose;
-static int max_thread_count = 48;
+bool add_include;
+
+static int getCpuCount();
+static int max_thread_count = getCpuCount();
+
+static int getCpuCount() {
+#if defined(__linux__)
+  cpu_set_t cpu_set;
+  int rc = sched_getaffinity(getpid(), sizeof(cpu_set), &cpu_set);
+  if (rc != 0) {
+    err(1, "sched_getaffinity failed");
+  }
+  return CPU_COUNT(&cpu_set);
+#else
+  return 1;
+#endif
+}
 
 static CompilationRequirements collectRequirements(const Arch& arch, const std::string& header_dir,
                                                    const std::string& dependency_dir) {
-  std::vector<std::string> headers = collectFiles(header_dir);
+  std::vector<std::string> headers = collectHeaders(header_dir);
   std::vector<std::string> dependencies = { header_dir };
   if (!dependency_dir.empty()) {
     auto collect_children = [&dependencies, &dependency_dir](const std::string& dir_path) {
@@ -158,6 +181,7 @@
   initializeTargetCC1FlagCache(vfs, types, requirements);
 
   std::vector<std::pair<CompilationType, const std::string&>> jobs;
+  std::atomic<size_t> job_index(0);
   for (CompilationType type : types) {
     CompilationRequirements& req = requirements[type.arch];
     for (const std::string& header : req.headers) {
@@ -173,13 +197,17 @@
     }
   } else {
     // Spawn threads.
+    size_t cpu_count = getCpuCount();
     for (size_t i = 0; i < thread_count; ++i) {
-      threads.emplace_back([&jobs, &result, &header_dir, vfs, thread_count, i]() {
-        size_t index = i;
-        while (index < jobs.size()) {
-          const auto& job = jobs[index];
+      threads.emplace_back([&jobs, &job_index, &result, &header_dir, vfs, cpu_count, i]() {
+        while (true) {
+          size_t idx = job_index++;
+          if (idx >= jobs.size()) {
+            return;
+          }
+
+          const auto& job = jobs[idx];
           compileHeader(vfs, result.get(), job.first, job.second);
-          index += thread_count;
         }
       });
     }
@@ -362,7 +390,7 @@
       failed = true;
     }
 
-    if (verbose) {
+    if (strict) {
       auto extra_it = extra_availability.find(symbol_name);
       if (extra_it != extra_availability.end()) {
         printf("%s: declaration marked unavailable but symbol available in [%s]\n",
@@ -402,7 +430,7 @@
     fprintf(stderr, "\n");
     fprintf(stderr, "Validation:\n");
     fprintf(stderr, "  -p PATH\tcompare against NDK platform at PATH\n");
-    fprintf(stderr, "  -v\t\tenable verbose warnings\n");
+    fprintf(stderr, "  -s\t\tenable strict warnings\n");
     fprintf(stderr, "\n");
     fprintf(stderr, "Preprocessing:\n");
     fprintf(stderr, "  -o PATH\tpreprocess header files and emit them at PATH\n");
@@ -411,6 +439,7 @@
     fprintf(stderr, "Miscellaneous:\n");
     fprintf(stderr, "  -d\t\tdump function availability\n");
     fprintf(stderr, "  -j THREADS\tmaximum number of threads to use\n");
+    fprintf(stderr, "  -v\t\tenable verbose logging\n");
     fprintf(stderr, "  -h\t\tdisplay this message\n");
     exit(0);
   }
@@ -427,7 +456,7 @@
   bool dump = false;
 
   int c;
-  while ((c = getopt(argc, argv, "a:r:p:vo:fdj:hi")) != -1) {
+  while ((c = getopt(argc, argv, "a:r:p:so:fdj:vhi")) != -1) {
     default_args = false;
     switch (c) {
       case 'a': {
@@ -472,8 +501,8 @@
         break;
       }
 
-      case 'v':
-        verbose = true;
+      case 's':
+        strict = true;
         break;
 
       case 'o':
@@ -500,6 +529,10 @@
         }
         break;
 
+      case 'v':
+        verbose = true;
+        break;
+
       case 'h':
         usage(true);
         break;
@@ -572,8 +605,15 @@
     symbol_database = parsePlatforms(compilation_types, platform_dir);
   }
 
+  auto start = std::chrono::high_resolution_clock::now();
   std::unique_ptr<HeaderDatabase> declaration_database =
       compileHeaders(compilation_types, header_dir, dependency_dir);
+  auto end = std::chrono::high_resolution_clock::now();
+
+  if (verbose) {
+    auto diff = (end - start) / 1.0ms;
+    printf("Compiled headers for %zu targets in %0.2LFms\n", compilation_types.size(), diff);
+  }
 
   bool failed = false;
   if (dump) {
diff --git a/tools/versioner/src/versioner.h b/tools/versioner/src/versioner.h
index 97b1509..a5f2c7d 100644
--- a/tools/versioner/src/versioner.h
+++ b/tools/versioner/src/versioner.h
@@ -22,6 +22,7 @@
 #include <unordered_map>
 #include <unordered_set>
 
+extern bool strict;
 extern bool verbose;
 extern bool add_include;