Merge "Use glibc structure for __cmsg_nxthdr."
diff --git a/libc/Android.mk b/libc/Android.mk
index 1008082..beb2cb1 100644
--- a/libc/Android.mk
+++ b/libc/Android.mk
@@ -71,7 +71,6 @@
     bionic/sigsetmask.c \
     bionic/strntoimax.c \
     bionic/strntoumax.c \
-    bionic/strtotimeval.c \
     bionic/system_properties_compat.c \
     bionic/time64.c \
     bionic/unlockpt.c \
@@ -96,6 +95,8 @@
     bionic/__memmove_chk.cpp \
     bionic/__read_chk.cpp \
     bionic/__recvfrom_chk.cpp \
+    bionic/__stpcpy_chk.cpp \
+    bionic/__stpncpy_chk.cpp \
     bionic/__strchr_chk.cpp \
     bionic/__strlcat_chk.cpp \
     bionic/__strlcpy_chk.cpp \
@@ -142,6 +143,7 @@
     bionic/libc_logging.cpp \
     bionic/libgen.cpp \
     bionic/link.cpp \
+    bionic/locale.cpp \
     bionic/lstat.cpp \
     bionic/mkdir.cpp \
     bionic/mkfifo.cpp \
@@ -187,7 +189,6 @@
     bionic/setegid.cpp \
     bionic/__set_errno.cpp \
     bionic/seteuid.cpp \
-    bionic/setlocale.cpp \
     bionic/setpgrp.cpp \
     bionic/sigaction.cpp \
     bionic/sigaddset.cpp \
@@ -384,6 +385,8 @@
     upstream-openbsd/lib/libc/stdlib/strtoull.c \
     upstream-openbsd/lib/libc/stdlib/strtoumax.c \
     upstream-openbsd/lib/libc/stdlib/system.c \
+    upstream-openbsd/lib/libc/string/stpcpy.c \
+    upstream-openbsd/lib/libc/string/stpncpy.c \
     upstream-openbsd/lib/libc/string/strcasecmp.c \
     upstream-openbsd/lib/libc/string/strcspn.c \
     upstream-openbsd/lib/libc/string/strdup.c \
diff --git a/libc/SYSCALLS.TXT b/libc/SYSCALLS.TXT
index e597b2f..220c713 100644
--- a/libc/SYSCALLS.TXT
+++ b/libc/SYSCALLS.TXT
@@ -308,7 +308,7 @@
 
 int eventfd:eventfd2(unsigned int, int)  all
 
-void _exit:exit_group(int)  all
+void _exit|_Exit:exit_group(int)  all
 void __exit:exit(int)  all
 
 int futex(void*, int, int, void*, void*, int)  all
diff --git a/libc/arch-arm/syscalls/_exit.S b/libc/arch-arm/syscalls/_exit.S
index 1a6b35d..581b340 100644
--- a/libc/arch-arm/syscalls/_exit.S
+++ b/libc/arch-arm/syscalls/_exit.S
@@ -12,3 +12,6 @@
     neg     r0, r0
     b       __set_errno
 END(_exit)
+
+    .globl _Exit
+    .equ _Exit, _exit
diff --git a/libc/arch-arm64/arm64.mk b/libc/arch-arm64/arm64.mk
index 7b6b1c3..88da1f3 100644
--- a/libc/arch-arm64/arm64.mk
+++ b/libc/arch-arm64/arm64.mk
@@ -14,11 +14,6 @@
     upstream-freebsd/lib/libc/string/wcslen.c \
     upstream-freebsd/lib/libc/string/wcsrchr.c \
     upstream-freebsd/lib/libc/string/wmemcmp.c \
-    upstream-openbsd/lib/libc/locale/_def_numeric.c \
-    upstream-openbsd/lib/libc/locale/_def_messages.c \
-    upstream-openbsd/lib/libc/locale/_def_monetary.c \
-    upstream-openbsd/lib/libc/locale/_def_time.c \
-    upstream-openbsd/lib/libc/locale/localeconv.c \
     upstream-openbsd/lib/libc/string/bcopy.c \
     upstream-openbsd/lib/libc/string/strcat.c \
     upstream-openbsd/lib/libc/string/strcpy.c \
diff --git a/libc/arch-arm64/syscalls/_exit.S b/libc/arch-arm64/syscalls/_exit.S
index 24b7b17..40ada48 100644
--- a/libc/arch-arm64/syscalls/_exit.S
+++ b/libc/arch-arm64/syscalls/_exit.S
@@ -19,3 +19,6 @@
 
     ret
 END(_exit)
+
+    .globl _Exit
+    .equ _Exit, _exit
diff --git a/libc/arch-mips/syscalls/_exit.S b/libc/arch-mips/syscalls/_exit.S
index 5a0877d..f546b66 100644
--- a/libc/arch-mips/syscalls/_exit.S
+++ b/libc/arch-mips/syscalls/_exit.S
@@ -17,3 +17,6 @@
     nop
     .set reorder
 END(_exit)
+
+    .globl _Exit
+    .equ _Exit, _exit
diff --git a/libc/arch-mips64/mips64.mk b/libc/arch-mips64/mips64.mk
index 9b29f0d..75620d8 100644
--- a/libc/arch-mips64/mips64.mk
+++ b/libc/arch-mips64/mips64.mk
@@ -16,11 +16,6 @@
     upstream-freebsd/lib/libc/string/wcslen.c \
     upstream-freebsd/lib/libc/string/wcsrchr.c \
     upstream-freebsd/lib/libc/string/wmemcmp.c \
-    upstream-openbsd/lib/libc/locale/_def_numeric.c \
-    upstream-openbsd/lib/libc/locale/_def_messages.c \
-    upstream-openbsd/lib/libc/locale/_def_monetary.c \
-    upstream-openbsd/lib/libc/locale/_def_time.c \
-    upstream-openbsd/lib/libc/locale/localeconv.c \
     upstream-openbsd/lib/libc/string/bcopy.c \
     upstream-openbsd/lib/libc/string/strcat.c \
     upstream-openbsd/lib/libc/string/strcmp.c \
@@ -60,7 +55,7 @@
 # FIXME TODO
 ## libc_bionic_src_files_mips64 += arch-mips64/string/memcpy.S
 ## libc_bionic_src_files_mips64 += arch-mips64/string/memset.S
-libc_bionic_src_files_mips64 += bionic/memcpy.c
+libc_bionic_src_files_mips64 += bionic/memcpy.cpp
 libc_bionic_src_files_mips64 += bionic/memset.c
 
 
diff --git a/libc/arch-mips64/syscalls/_exit.S b/libc/arch-mips64/syscalls/_exit.S
index 9b108a6..eb84def 100644
--- a/libc/arch-mips64/syscalls/_exit.S
+++ b/libc/arch-mips64/syscalls/_exit.S
@@ -23,3 +23,6 @@
     move ra, t0
     .set pop
 END(_exit)
+
+    .globl _Exit
+    .equ _Exit, _exit
diff --git a/libc/arch-x86/syscalls/_exit.S b/libc/arch-x86/syscalls/_exit.S
index 2ff5faf..793c9d5 100644
--- a/libc/arch-x86/syscalls/_exit.S
+++ b/libc/arch-x86/syscalls/_exit.S
@@ -20,3 +20,6 @@
     popl    %ebx
     ret
 END(_exit)
+
+    .globl _Exit
+    .equ _Exit, _exit
diff --git a/libc/arch-x86_64/syscalls/_exit.S b/libc/arch-x86_64/syscalls/_exit.S
index f40cfe3..3c15897 100644
--- a/libc/arch-x86_64/syscalls/_exit.S
+++ b/libc/arch-x86_64/syscalls/_exit.S
@@ -14,3 +14,6 @@
 1:
     ret
 END(_exit)
+
+    .globl _Exit
+    .equ _Exit, _exit
diff --git a/libc/arch-x86_64/x86_64.mk b/libc/arch-x86_64/x86_64.mk
index a3adaa4..9bce065 100644
--- a/libc/arch-x86_64/x86_64.mk
+++ b/libc/arch-x86_64/x86_64.mk
@@ -18,11 +18,6 @@
     upstream-freebsd/lib/libc/string/wcslen.c \
     upstream-freebsd/lib/libc/string/wcsrchr.c \
     upstream-freebsd/lib/libc/string/wmemcmp.c \
-    upstream-openbsd/lib/libc/locale/_def_numeric.c \
-    upstream-openbsd/lib/libc/locale/_def_messages.c \
-    upstream-openbsd/lib/libc/locale/_def_monetary.c \
-    upstream-openbsd/lib/libc/locale/_def_time.c \
-    upstream-openbsd/lib/libc/locale/localeconv.c \
     upstream-openbsd/lib/libc/string/bcopy.c \
     upstream-openbsd/lib/libc/string/strcat.c \
     upstream-openbsd/lib/libc/string/strcmp.c \
diff --git a/libc/bionic/setlocale.cpp b/libc/bionic/__stpcpy_chk.cpp
similarity index 63%
copy from libc/bionic/setlocale.cpp
copy to libc/bionic/__stpcpy_chk.cpp
index e8fdc9e..3ce81ee 100644
--- a/libc/bionic/setlocale.cpp
+++ b/libc/bionic/__stpcpy_chk.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2008 The Android Open Source Project
+ * Copyright (C) 2014 The Android Open Source Project
  * All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
@@ -26,10 +26,30 @@
  * SUCH DAMAGE.
  */
 
-#include <locale.h>
-#include <stdlib.h>
+#undef _FORTIFY_SOURCE
 
-// setlocale(3) always fails on bionic.
-char* setlocale(int /*category*/, char const* /*locale*/) {
-    return NULL;
+#include <string.h>
+#include <stdlib.h>
+#include "private/libc_logging.h"
+
+/*
+ * Runtime implementation of __builtin____stpcpy_chk.
+ *
+ * See
+ *   http://gcc.gnu.org/onlinedocs/gcc/Object-Size-Checking.html
+ *   http://gcc.gnu.org/ml/gcc-patches/2004-09/msg02055.html
+ * for details.
+ *
+ * This stpcpy check is called if _FORTIFY_SOURCE is defined and
+ * greater than 0.
+ */
+extern "C" char* __stpcpy_chk(char* dest, const char* src, size_t dest_len) {
+  // TODO: optimize so we don't scan src twice.
+  size_t src_len = strlen(src) + 1;
+  if (__predict_false(src_len > dest_len)) {
+    __fortify_chk_fail("stpcpy: prevented write past end of buffer",
+                       BIONIC_EVENT_STPCPY_BUFFER_OVERFLOW);
+  }
+
+  return stpcpy(dest, src);
 }
diff --git a/libc/bionic/__stpncpy_chk.cpp b/libc/bionic/__stpncpy_chk.cpp
new file mode 100644
index 0000000..6c9215c
--- /dev/null
+++ b/libc/bionic/__stpncpy_chk.cpp
@@ -0,0 +1,92 @@
+/*
+ * Copyright (C) 2014 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.
+ */
+
+#undef _FORTIFY_SOURCE
+
+#include <string.h>
+#include <stdlib.h>
+#include "private/libc_logging.h"
+
+/*
+ * Runtime implementation of __builtin____stpncpy_chk.
+ *
+ * See
+ *   http://gcc.gnu.org/onlinedocs/gcc/Object-Size-Checking.html
+ *   http://gcc.gnu.org/ml/gcc-patches/2004-09/msg02055.html
+ * for details.
+ *
+ * This stpncpy check is called if _FORTIFY_SOURCE is defined and
+ * greater than 0.
+ */
+extern "C" char* __stpncpy_chk(char* __restrict dest, const char* __restrict src,
+                               size_t len, size_t dest_len) {
+  if (__predict_false(len > dest_len)) {
+    __fortify_chk_fail("stpncpy: prevented write past end of buffer",
+                       BIONIC_EVENT_STPNCPY_BUFFER_OVERFLOW);
+  }
+
+  return stpncpy(dest, src, len);
+}
+
+/*
+ * __stpncpy_chk2
+ *
+ * This is a variant of __stpncpy_chk, but it also checks to make
+ * sure we don't read beyond the end of "src". The code for this is
+ * based on the original version of stpncpy, but modified to check
+ * how much we read from "src" at the end of the copy operation.
+ */
+extern "C" char* __stpncpy_chk2(char* __restrict dst, const char* __restrict src,
+              size_t n, size_t dest_len, size_t src_len)
+{
+  if (__predict_false(n > dest_len)) {
+    __fortify_chk_fail("stpncpy: prevented write past end of buffer",
+                       BIONIC_EVENT_STPNCPY_BUFFER_OVERFLOW);
+  }
+  if (n != 0) {
+    char* d = dst;
+    const char* s = src;
+
+    do {
+      if ((*d++ = *s++) == 0) {
+        /* NUL pad the remaining n-1 bytes */
+        while (--n != 0) {
+          *d++ = 0;
+        }
+        break;
+      }
+    } while (--n != 0);
+
+    size_t s_copy_len = static_cast<size_t>(s - src);
+    if (__predict_false(s_copy_len > src_len)) {
+      __fortify_chk_fail("stpncpy: prevented read past end of buffer", 0);
+    }
+  }
+
+  return dst;
+}
diff --git a/libc/bionic/__strcpy_chk.cpp b/libc/bionic/__strcpy_chk.cpp
index 1f6bc80..ad3ef50 100644
--- a/libc/bionic/__strcpy_chk.cpp
+++ b/libc/bionic/__strcpy_chk.cpp
@@ -26,6 +26,8 @@
  * SUCH DAMAGE.
  */
 
+#undef _FORTIFY_SOURCE
+
 #include <string.h>
 #include <stdlib.h>
 #include "private/libc_logging.h"
@@ -41,7 +43,7 @@
  * This strcpy check is called if _FORTIFY_SOURCE is defined and
  * greater than 0.
  */
-extern "C" char* __strcpy_chk (char* dest, const char* src, size_t dest_len) {
+extern "C" char* __strcpy_chk(char* dest, const char* src, size_t dest_len) {
   // TODO: optimize so we don't scan src twice.
   size_t src_len = strlen(src) + 1;
   if (__predict_false(src_len > dest_len)) {
diff --git a/libc/bionic/locale.cpp b/libc/bionic/locale.cpp
new file mode 100644
index 0000000..4fade84
--- /dev/null
+++ b/libc/bionic/locale.cpp
@@ -0,0 +1,156 @@
+/*
+ * Copyright (C) 2008 The Android Open Source Project
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *  * Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in
+ *    the documentation and/or other materials provided with the
+ *    distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
+ * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
+ * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
+ * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
+ * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <locale.h>
+#include <pthread.h>
+#include <stdlib.h>
+
+// We currently support a single locale, the "C" locale (also known as "POSIX").
+
+struct __locale_t {
+  // Because we only support one locale, these are just tokens with no data.
+};
+
+static pthread_once_t gLocaleOnce = PTHREAD_ONCE_INIT;
+static lconv gLocale;
+
+static pthread_once_t gUselocaleKeyOnce = PTHREAD_ONCE_INIT;
+static pthread_key_t gUselocaleKey;
+
+static void __locale_init() {
+  gLocale.decimal_point = const_cast<char*>(".");
+
+  char* not_available = const_cast<char*>("");
+  gLocale.thousands_sep = not_available;
+  gLocale.grouping = not_available;
+  gLocale.int_curr_symbol = not_available;
+  gLocale.currency_symbol = not_available;
+  gLocale.mon_decimal_point = not_available;
+  gLocale.mon_thousands_sep = not_available;
+  gLocale.mon_grouping = not_available;
+  gLocale.positive_sign = not_available;
+  gLocale.negative_sign = not_available;
+
+  gLocale.int_frac_digits = CHAR_MAX;
+  gLocale.frac_digits = CHAR_MAX;
+  gLocale.p_cs_precedes = CHAR_MAX;
+  gLocale.p_sep_by_space = CHAR_MAX;
+  gLocale.n_cs_precedes = CHAR_MAX;
+  gLocale.n_sep_by_space = CHAR_MAX;
+  gLocale.p_sign_posn = CHAR_MAX;
+  gLocale.n_sign_posn = CHAR_MAX;
+  gLocale.int_p_cs_precedes = CHAR_MAX;
+  gLocale.int_p_sep_by_space = CHAR_MAX;
+  gLocale.int_n_cs_precedes = CHAR_MAX;
+  gLocale.int_n_sep_by_space = CHAR_MAX;
+  gLocale.int_p_sign_posn = CHAR_MAX;
+  gLocale.int_n_sign_posn = CHAR_MAX;
+}
+
+static void __uselocale_key_init() {
+  pthread_key_create(&gUselocaleKey, NULL);
+}
+
+static bool __is_supported_locale(const char* locale) {
+  return (strcmp(locale, "") == 0 || strcmp(locale, "C") == 0 || strcmp(locale, "POSIX") == 0);
+}
+
+static locale_t __new_locale() {
+  return reinterpret_cast<locale_t>(malloc(sizeof(__locale_t)));
+}
+
+lconv* localeconv() {
+  pthread_once(&gLocaleOnce, __locale_init);
+  return &gLocale;
+}
+
+locale_t duplocale(locale_t l) {
+  locale_t clone = __new_locale();
+  if (clone != NULL && l != LC_GLOBAL_LOCALE) {
+    *clone = *l;
+  }
+  return clone;
+}
+
+void freelocale(locale_t l) {
+  free(l);
+}
+
+locale_t newlocale(int category_mask, const char* locale_name, locale_t /*base*/) {
+  // Is 'category_mask' valid?
+  if ((category_mask & ~LC_ALL_MASK) != 0) {
+    errno = EINVAL;
+    return NULL;
+  }
+
+  if (!__is_supported_locale(locale_name)) {
+    errno = ENOENT;
+    return NULL;
+  }
+
+  return __new_locale();
+}
+
+char* setlocale(int category, char const* locale_name) {
+  // Is 'category' valid?
+  if (category < LC_CTYPE || category > LC_IDENTIFICATION) {
+    errno = EINVAL;
+    return NULL;
+  }
+
+  // Caller just wants to query the current locale?
+  if (locale_name == NULL) {
+    return const_cast<char*>("C");
+  }
+
+  // Caller wants one of the mandatory POSIX locales?
+  if (__is_supported_locale(locale_name)) {
+    return const_cast<char*>("C");
+  }
+
+  // We don't support any other locales.
+  errno = ENOENT;
+  return NULL;
+}
+
+locale_t uselocale(locale_t new_locale) {
+  pthread_once(&gUselocaleKeyOnce, __uselocale_key_init);
+
+  locale_t old_locale = static_cast<locale_t>(pthread_getspecific(gUselocaleKey));
+
+  // If this is the first call to uselocale(3) on this thread, we return LC_GLOBAL_LOCALE.
+  if (old_locale == NULL) {
+    old_locale = LC_GLOBAL_LOCALE;
+  }
+
+  if (new_locale != NULL) {
+    pthread_setspecific(gUselocaleKey, new_locale);
+  }
+
+  return old_locale;
+}
diff --git a/libc/bionic/ndk_cruft.cpp b/libc/bionic/ndk_cruft.cpp
index b0346d4..7826651 100644
--- a/libc/bionic/ndk_cruft.cpp
+++ b/libc/bionic/ndk_cruft.cpp
@@ -29,6 +29,8 @@
 // This file perpetuates the mistakes of the past, but only for 32-bit targets.
 #if !defined(__LP64__)
 
+#include <ctype.h>
+#include <inttypes.h>
 #include <pthread.h>
 #include <stdlib.h>
 #include <sys/resource.h>
@@ -87,4 +89,31 @@
   return 0;
 }
 
+// Non-standard cruft that should only ever have been in system/core/toolbox.
+extern "C" char* strtotimeval(const char* str, struct timeval* ts) {
+  char* s;
+  ts->tv_sec = strtoumax(str, &s, 10);
+
+  long fractional_seconds = 0;
+  if (*s == '.') {
+    s++;
+    int count = 0;
+
+    // Read up to 6 digits (microseconds).
+    while (*s && isdigit(*s)) {
+      if (++count < 7) {
+        fractional_seconds = fractional_seconds*10 + (*s - '0');
+      }
+      s++;
+    }
+
+    for (; count < 6; count++) {
+      fractional_seconds *= 10;
+    }
+  }
+
+  ts->tv_usec = fractional_seconds;
+  return s;
+}
+
 #endif
diff --git a/libc/bionic/strtotimeval.c b/libc/bionic/strtotimeval.c
deleted file mode 100644
index 195381b..0000000
--- a/libc/bionic/strtotimeval.c
+++ /dev/null
@@ -1,58 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *  * Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- *  * Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in
- *    the documentation and/or other materials provided with the
- *    distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
- * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
- * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
- * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
- * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
- * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
- * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- */
-#include <ctype.h>
-#include <inttypes.h>
-#include <stdlib.h>
-#include <sys/time.h>
-
-char * strtotimeval(const char *str, struct timeval *ts) {
-  char *s;
-  long fs = 0; /* fractional seconds */
-
-  ts->tv_sec = strtoumax(str, &s, 10);
-
-  if (*s == '.') {
-    s++;
-    int count = 0;
-
-    /* read up to 6 digits (microseconds) */
-    while (*s && isdigit(*s)) {
-      if (++count < 7) {
-        fs = fs*10 + (*s - '0');
-      }
-      s++;
-    }
-
-    for (; count < 6; count++) {
-      fs *= 10;
-    }
-  }
-
-  ts->tv_usec = fs;
-  return s;
-}
diff --git a/libc/bionic/wchar.cpp b/libc/bionic/wchar.cpp
index 50a3875..8d56458 100644
--- a/libc/bionic/wchar.cpp
+++ b/libc/bionic/wchar.cpp
@@ -28,6 +28,7 @@
 
 #include <ctype.h>
 #include <errno.h>
+#include <limits.h>
 #include <stdlib.h>
 #include <string.h>
 #include <wchar.h>
@@ -156,8 +157,8 @@
   return 1;
 }
 
-size_t mbrlen(const char* /*s*/, size_t n, mbstate_t* /*ps*/) {
-  return (n != 0);
+size_t mbrlen(const char* s, size_t n, mbstate_t* /*ps*/) {
+  return (n == 0 || s[0] == 0) ? 0 : 1;
 }
 
 size_t mbrtowc(wchar_t* pwc, const char* s, size_t n, mbstate_t* /*ps*/) {
@@ -217,13 +218,26 @@
   return ungetc(static_cast<char>(wc), stream);
 }
 
-size_t wcrtomb(char* s, wchar_t /*wc*/, mbstate_t* /*ps*/) {
-  if (s != NULL) {
-    *s = 1;
+int wctomb(char* s, wchar_t wc) {
+  if (s == NULL) {
+    return 0;
+  }
+  if (wc <= 0xff) {
+    *s = static_cast<char>(wc);
+  } else {
+    *s = '?';
   }
   return 1;
 }
 
+size_t wcrtomb(char* s, wchar_t wc, mbstate_t* /*ps*/) {
+  if (s == NULL) {
+    char buf[MB_LEN_MAX];
+    return wctomb(buf, L'\0');
+  }
+  return wctomb(s, wc);
+}
+
 size_t wcsftime(wchar_t* wcs, size_t maxsize, const wchar_t* format,  const struct tm* timptr) {
   return strftime(reinterpret_cast<char*>(wcs), maxsize, reinterpret_cast<const char*>(format), timptr);
 }
diff --git a/libc/dns/gethnamaddr.c b/libc/dns/gethnamaddr.c
index 2234c7c..dbcadee 100644
--- a/libc/dns/gethnamaddr.c
+++ b/libc/dns/gethnamaddr.c
@@ -60,6 +60,7 @@
 #include <netinet/in.h>
 #include <arpa/inet.h>
 #include <arpa/nameser.h>
+#include "resolv_netid.h"
 #include "resolv_private.h"
 #include "resolv_cache.h"
 #include <assert.h>
@@ -129,7 +130,7 @@
 static int _dns_gethtbyaddr(void *, void *, va_list);
 static int _dns_gethtbyname(void *, void *, va_list);
 
-static struct hostent *gethostbyname_internal(const char *, int, res_state, const char *, int);
+static struct hostent *gethostbyname_internal(const char *, int, res_state, unsigned, unsigned);
 
 static const ns_src default_dns_files[] = {
 	{ NSSRC_FILES, 	NS_SUCCESS },
@@ -500,13 +501,13 @@
 
 	/* try IPv6 first - if that fails do IPv4 */
 	if (res->options & RES_USE_INET6) {
-		hp = gethostbyname_internal(name, AF_INET6, res, NULL, 0);
+		hp = gethostbyname_internal(name, AF_INET6, res, NETID_UNSET, MARK_UNSET);
 		if (hp) {
 			__res_put_state(res);
 			return hp;
 		}
 	}
-	hp = gethostbyname_internal(name, AF_INET, res, NULL, 0);
+	hp = gethostbyname_internal(name, AF_INET, res, NETID_UNSET, MARK_UNSET);
 	__res_put_state(res);
 	return hp;
 }
@@ -514,18 +515,18 @@
 struct hostent *
 gethostbyname2(const char *name, int af)
 {
-	return android_gethostbynameforiface(name, af, NULL, 0);
+	return android_gethostbynamefornet(name, af, NETID_UNSET, MARK_UNSET);
 }
 
 struct hostent *
-android_gethostbynameforiface(const char *name, int af, const char *iface, int mark)
+android_gethostbynamefornet(const char *name, int af, unsigned netid, unsigned mark)
 {
 	struct hostent *hp;
 	res_state res = __res_get_state();
 
 	if (res == NULL)
 		return NULL;
-	hp = gethostbyname_internal(name, af, res, iface, mark);
+	hp = gethostbyname_internal(name, af, res, netid, mark);
 	__res_put_state(res);
 	return hp;
 }
@@ -744,14 +745,14 @@
 
 // very similar in proxy-ness to android_getaddrinfo_proxy
 static struct hostent *
-gethostbyname_internal(const char *name, int af, res_state res, const char *iface, int mark)
+gethostbyname_internal(const char *name, int af, res_state res, unsigned netid, unsigned mark)
 {
 	const char *cache_mode = getenv("ANDROID_DNS_MODE");
 	FILE* proxy = NULL;
 	struct hostent *result = NULL;
 
 	if (cache_mode != NULL && strcmp(cache_mode, "local") == 0) {
-		res_setiface(res, iface);
+		res_setnetid(res, netid);
 		res_setmark(res, mark);
 		return gethostbyname_internal_real(name, af, res);
 	}
@@ -761,8 +762,8 @@
 
 	/* This is writing to system/netd/DnsProxyListener.cpp and changes
 	 * here need to be matched there */
-	if (fprintf(proxy, "gethostbyname %s %s %d",
-			iface == NULL ? "^" : iface,
+	if (fprintf(proxy, "gethostbyname %u %s %d",
+			netid,
 			name == NULL ? "^" : name,
 			af) < 0) {
 		goto exit;
@@ -783,8 +784,8 @@
 
 
 struct hostent *
-android_gethostbyaddrforiface_proxy(const void *addr,
-    socklen_t len, int af, const char* iface, int mark)
+android_gethostbyaddrfornet_proxy(const void *addr,
+    socklen_t len, int af, unsigned netid)
 {
 	struct hostent *result = NULL;
 	FILE* proxy = android_open_proxy();
@@ -795,8 +796,8 @@
 	const char * addrStr = inet_ntop(af, addr, buf, sizeof(buf));
 	if (addrStr == NULL) goto exit;
 
-	if (fprintf(proxy, "gethostbyaddr %s %d %d %s",
-			addrStr, len, af, iface == NULL ? "^" : iface) < 0) {
+	if (fprintf(proxy, "gethostbyaddr %s %d %d %u",
+			addrStr, len, af, netid) < 0) {
 		goto exit;
 	}
 
@@ -813,8 +814,8 @@
 }
 
 struct hostent *
-android_gethostbyaddrforiface_real(const void *addr,
-    socklen_t len, int af, const char* iface, int mark)
+android_gethostbyaddrfornet_real(const void *addr,
+    socklen_t len, int af, unsigned netid, unsigned mark)
 {
 	const u_char *uaddr = (const u_char *)addr;
 	socklen_t size;
@@ -862,28 +863,28 @@
 	hp = NULL;
 	h_errno = NETDB_INTERNAL;
 	if (nsdispatch(&hp, dtab, NSDB_HOSTS, "gethostbyaddr",
-		default_dns_files, uaddr, len, af, iface, mark) != NS_SUCCESS)
+		default_dns_files, uaddr, len, af, netid, mark) != NS_SUCCESS)
 		return NULL;
 	h_errno = NETDB_SUCCESS;
 	return hp;
 }
 
 struct hostent *
-android_gethostbyaddrforiface(const void *addr, socklen_t len, int af, const char* iface, int mark)
+android_gethostbyaddrfornet(const void *addr, socklen_t len, int af, unsigned netid, unsigned mark)
 {
 	const char *cache_mode = getenv("ANDROID_DNS_MODE");
 
 	if (cache_mode == NULL || strcmp(cache_mode, "local") != 0) {
-		return android_gethostbyaddrforiface_proxy(addr, len, af, iface, mark);
+		return android_gethostbyaddrfornet_proxy(addr, len, af, netid);
 	} else {
-		return android_gethostbyaddrforiface_real(addr,len, af, iface, mark);
+		return android_gethostbyaddrfornet_real(addr,len, af, netid, mark);
 	}
 }
 
 struct hostent *
 gethostbyaddr(const void *addr, socklen_t len, int af)
 {
-	return android_gethostbyaddrforiface(addr, len, af, NULL, 0);
+	return android_gethostbyaddrfornet(addr, len, af, NETID_UNSET, MARK_UNSET);
 }
 
 
@@ -1318,8 +1319,7 @@
 	const unsigned char *uaddr;
 	int len, af, advance;
 	res_state res;
-	const char* iface;
-	int mark;
+	unsigned netid, mark;
 	res_static rs = __res_get_static();
 
 	assert(rv != NULL);
@@ -1327,8 +1327,8 @@
 	uaddr = va_arg(ap, unsigned char *);
 	len = va_arg(ap, int);
 	af = va_arg(ap, int);
-	iface = va_arg(ap, char *);
-	mark = va_arg(ap, int);
+	netid = va_arg(ap, unsigned);
+	mark = va_arg(ap, unsigned);
 
 	switch (af) {
 	case AF_INET:
@@ -1370,7 +1370,7 @@
 		free(buf);
 		return NS_NOTFOUND;
 	}
-	res_setiface(res, iface);
+	res_setnetid(res, netid);
 	res_setmark(res, mark);
 	n = res_nquery(res, qbuf, C_IN, T_PTR, buf->buf, sizeof(buf->buf));
 	if (n < 0) {
diff --git a/libc/dns/include/resolv_cache.h b/libc/dns/include/resolv_cache.h
index 68a1180..16f3e43 100644
--- a/libc/dns/include/resolv_cache.h
+++ b/libc/dns/include/resolv_cache.h
@@ -34,61 +34,15 @@
 struct __res_state;
 struct resolv_cache;  /* forward */
 
-/* gets the cache for an interface. Set ifname argument to NULL or
- * empty buffer ('\0') to get cache for default interface.
- * returned cache might be NULL*/
+/* Gets the cache for a network. Returned cache might be NULL. */
 __LIBC_HIDDEN__
-extern struct resolv_cache*  __get_res_cache(const char* ifname);
-
-/* this gets called everytime we detect some changes in the DNS configuration
- * and will flush the cache */
-__LIBC_HIDDEN__
-extern void  _resolv_cache_reset( unsigned  generation );
-
-/* Gets the address of the n:th name server for the default interface
- * Return length of address on success else 0.
- * Note: The first name server is at n = 1 */
-__LIBC_HIDDEN__
-extern int _resolv_cache_get_nameserver(int n, char* addr, int addrLen);
-
-/* Gets the address of the n:th name server for a certain interface
- * Return length of address on success else 0.
- * Note: The first name server is at n = 1 */
-__LIBC_HIDDEN__
-extern int _resolv_cache_get_nameserver_for_iface(const char* ifname, int n,
-        char* addr, int addrLen);
-
-/* Gets addrinfo of the n:th name server associated with an interface.
- * NULL is returned if no address if found.
- * Note: The first name server is at n = 1. */
-__LIBC_HIDDEN__
-extern struct addrinfo* _resolv_cache_get_nameserver_addr_for_iface(const char* ifname, int n);
-
-/* Gets addrinfo of the n:th name server associated with the default interface
- * NULL is returned if no address if found.
- * Note: The first name server is at n = 1. */
-__LIBC_HIDDEN__
-extern struct addrinfo* _resolv_cache_get_nameserver_addr(int n);
-
-/* gets the address associated with the default interface */
-__LIBC_HIDDEN__
-extern struct in_addr* _resolv_get_addr_of_default_iface();
-
-/* gets the address associated with the specified interface */
-__LIBC_HIDDEN__
-extern struct in_addr* _resolv_get_addr_of_iface(const char* ifname);
-
-/* Copy the name of the default interface to the provided buffer.
- * Returns the string length of the default interface,
- * be that less or more than the buffLen, or 0 if nothing had been written */
-__LIBC_HIDDEN__
- extern size_t _resolv_get_default_iface(char* buff, size_t buffLen);
+extern struct resolv_cache* __get_res_cache(unsigned netid);
 
 /* sets the name server addresses to the provided res_state structure. The
  * name servers are retrieved from the cache which is associated
- * with the interface to which the res_state structure is associated */
+ * with the network to which the res_state structure is associated */
 __LIBC_HIDDEN__
-extern void _resolv_populate_res_for_iface(struct __res_state* statp);
+extern void _resolv_populate_res_for_net(struct __res_state* statp);
 
 typedef enum {
     RESOLV_CACHE_UNSUPPORTED,  /* the cache can't handle that kind of queries */
diff --git a/libc/dns/include/resolv_iface.h b/libc/dns/include/resolv_iface.h
deleted file mode 100644
index ad42793..0000000
--- a/libc/dns/include/resolv_iface.h
+++ /dev/null
@@ -1,106 +0,0 @@
-/*
- * Copyright (C) 2011 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 _RESOLV_IFACE_H
-#define _RESOLV_IFACE_H
-
-/* This header contains declarations related to per-interface DNS
- * server selection. They are used by system/netd/ and should not be
- * exposed by the C library's public NDK headers.
- *
- * NOTE: <resolv.h> contains the same declarations, this will be removed
- *        when we change system/netd to use this header instead.
- */
-#include <sys/cdefs.h>
-#include <netinet/in.h>
-
-__BEGIN_DECLS
-
-/* Use a guard macro until we remove the same definitions from <resolv.h> */
-#ifndef _BIONIC_RESOLV_IFACE_FUNCTIONS_DECLARED
-#define _BIONIC_RESOLV_IFACE_FUNCTIONS_DECLARED
-
-/* Set name of default interface */
-extern void _resolv_set_default_iface(const char* ifname);
-
-/* set name servers for an interface */
-extern void _resolv_set_nameservers_for_iface(const char* ifname, const char** servers, int numservers,
-        const char *domains);
-
-/* tell resolver of the address of an interface */
-extern void _resolv_set_addr_of_iface(const char* ifname, struct in_addr* addr);
-
-/* flush the cache associated with the default interface */
-extern void _resolv_flush_cache_for_default_iface();
-
-/* flush the cache associated with a certain interface */
-extern void _resolv_flush_cache_for_iface(const char* ifname);
-
-/* set a pid to use the name servers of the specified interface */
-extern void _resolv_set_iface_for_pid(const char* ifname, int pid);
-
-/* clear pid from being associated with an interface */
-extern void _resolv_clear_iface_for_pid(int pid);
-
-/* clear the entire mapping of pids to interfaces. */
-extern void _resolv_clear_iface_pid_mapping();
-
-/** Gets the name of the interface to which the pid is attached.
- *  On error, -1 is returned.
- *  If no interface is found, 0 is returned and buff is set to empty ('\0').
- *  If an interface is found, the name is copied to buff and the length of the name is returned.
- *  Arguments:   pid The pid to find an interface for
- *               buff A buffer to copy the result to
- *               buffLen Length of buff. An interface is at most IF_NAMESIZE in length */
-extern int _resolv_get_pids_associated_interface(int pid, char* buff, int buffLen);
-
-
-/** set a uid range to use the name servers of the specified interface
- *  If [low,high] overlaps with an already existing rule -1 is returned */
-extern int _resolv_set_iface_for_uid_range(const char* ifname, int uid_start, int uid_end);
-
-/* clear a uid range from being associated with an interface
- * If the range given is not mapped -1 is returned. */
-extern int _resolv_clear_iface_for_uid_range(int uid_start, int uid_end);
-
-/* clear the entire mapping of uid ranges to interfaces. */
-extern void _resolv_clear_iface_uid_range_mapping();
-
-/** Gets the name of the interface to which the uid is attached.
- *  On error, -1 is returned.
- *  If no interface is found, 0 is returned and buff is set to empty ('\0').
- *  If an interface is found, the name is copied to buff and the length of the name is returned.
- *  Arguments:   uid The uid to find an interface for
- *               buff A buffer to copy the result to
- *               buffLen Length of buff. An interface is at most IF_NAMESIZE in length */
-extern int _resolv_get_uids_associated_interface(int uid, char* buff, int buffLen);
-
-#endif /* _BIONIC_RESOLV_IFACE_FUNCTIONS_DECLARED */
-
-__END_DECLS
-
-#endif /* _RESOLV_IFACE_H */
diff --git a/libc/dns/include/resolv_netid.h b/libc/dns/include/resolv_netid.h
new file mode 100644
index 0000000..991a0bf
--- /dev/null
+++ b/libc/dns/include/resolv_netid.h
@@ -0,0 +1,70 @@
+/*
+ * Copyright (C) 2014 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 _RESOLV_NETID_H
+#define _RESOLV_NETID_H
+
+/* This header contains declarations related to per-network DNS
+ * server selection. They are used by system/netd/ and should not be
+ * exposed by the C library's public NDK headers.
+ */
+#include <sys/cdefs.h>
+#include <netinet/in.h>
+
+/*
+ * Passing NETID_UNSET as the netId causes system/netd/DnsProxyListener.cpp to
+ * fill in the appropriate default netId for the query.
+ */
+#define NETID_UNSET 0u
+
+/*
+ * MARK_UNSET represents the default (i.e. unset) value for a socket mark.
+ */
+#define MARK_UNSET 0u
+
+__BEGIN_DECLS
+
+struct addrinfo;
+
+struct hostent *android_gethostbyaddrfornet(const void *, socklen_t, int, unsigned, unsigned);
+struct hostent *android_gethostbyaddrfornet_proxy(const void *, socklen_t, int , unsigned);
+struct hostent *android_gethostbynamefornet(const char *, int, unsigned, unsigned);
+int android_getaddrinfofornet(const char *, const char *, const struct addrinfo *, unsigned,
+		unsigned, struct addrinfo **);
+int android_getnameinfofornet(const struct sockaddr *, socklen_t, char *, size_t, char *, size_t,
+		 int, unsigned, unsigned);
+
+/* set name servers for a network */
+extern void _resolv_set_nameservers_for_net(unsigned netid,
+    const char** servers, int numservers, const char *domains);
+
+/* flush the cache associated with a certain network */
+extern void _resolv_flush_cache_for_net(unsigned netid);
+
+__END_DECLS
+
+#endif /* _RESOLV_NETID_H */
diff --git a/libc/dns/include/resolv_private.h b/libc/dns/include/resolv_private.h
index c7bcb89..8914fae 100644
--- a/libc/dns/include/resolv_private.h
+++ b/libc/dns/include/resolv_private.h
@@ -142,7 +142,7 @@
 struct __res_state_ext;
 
 struct __res_state {
-	char	iface[IF_NAMESIZE+1];
+	unsigned	netid;			/* NetId: cache key and socket mark */
 	int	retrans;	 	/* retransmission time interval */
 	int	retry;			/* number of times to retransmit */
 #ifdef sun
@@ -175,7 +175,7 @@
 	res_send_qhook qhook;		/* query hook */
 	res_send_rhook rhook;		/* response hook */
 	int	res_h_errno;		/* last one set for this context */
-	int _mark;          /* If non-0 SET_MARK to _mark on all request sockets */
+	unsigned _mark;			/* If non-0 SET_MARK to _mark on all request sockets */
 	int	_vcsock;		/* PRIVATE: for res_send VC i/o */
 	u_int	_flags;			/* PRIVATE: see below */
 	u_int	_pad;			/* make _u 64 bit aligned */
@@ -490,8 +490,8 @@
 int		res_getservers(res_state,
 				    union res_sockaddr_union *, int);
 
-void res_setiface();
-void res_setmark();
+void res_setnetid(res_state, unsigned);
+void res_setmark(res_state, unsigned);
 u_int  res_randomid(void);
 
 __END_DECLS
diff --git a/libc/dns/net/getaddrinfo.c b/libc/dns/net/getaddrinfo.c
index 7da69f9..4c120d9 100644
--- a/libc/dns/net/getaddrinfo.c
+++ b/libc/dns/net/getaddrinfo.c
@@ -92,6 +92,8 @@
 #include <ctype.h>
 #include <errno.h>
 #include <netdb.h>
+#include "resolv_cache.h"
+#include "resolv_netid.h"
 #include "resolv_private.h"
 #include <stdbool.h>
 #include <stddef.h>
@@ -215,7 +217,7 @@
 
 static int str2number(const char *);
 static int explore_fqdn(const struct addrinfo *, const char *,
-	const char *, struct addrinfo **, const char *iface, int mark);
+	const char *, struct addrinfo **, unsigned netid, unsigned mark);
 static int explore_null(const struct addrinfo *,
 	const char *, struct addrinfo **);
 static int explore_numeric(const struct addrinfo *, const char *,
@@ -358,10 +360,12 @@
  * the destination (e.g., no IPv4 address, no IPv6 default route, ...).
  */
 static int
-_test_connect(int pf, struct sockaddr *addr, size_t addrlen) {
+_test_connect(int pf, struct sockaddr *addr, size_t addrlen, unsigned mark) {
 	int s = socket(pf, SOCK_DGRAM, IPPROTO_UDP);
 	if (s < 0)
 		return 0;
+	if (mark != MARK_UNSET && setsockopt(s, SOL_SOCKET, SO_MARK, &mark, sizeof(mark)) < 0)
+		return 0;
 	int ret;
 	do {
 		ret = connect(s, addr, addrlen);
@@ -383,31 +387,31 @@
  * so checking for connectivity is the next best thing.
  */
 static int
-_have_ipv6() {
+_have_ipv6(unsigned mark) {
 	static const struct sockaddr_in6 sin6_test = {
 		.sin6_family = AF_INET6,
 		.sin6_addr.s6_addr = {  // 2000::
 			0x20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
 		};
-        sockaddr_union addr = { .in6 = sin6_test };
-	return _test_connect(PF_INET6, &addr.generic, sizeof(addr.in6));
+	sockaddr_union addr = { .in6 = sin6_test };
+	return _test_connect(PF_INET6, &addr.generic, sizeof(addr.in6), mark);
 }
 
 static int
-_have_ipv4() {
+_have_ipv4(unsigned mark) {
 	static const struct sockaddr_in sin_test = {
 		.sin_family = AF_INET,
 		.sin_addr.s_addr = __constant_htonl(0x08080808L)  // 8.8.8.8
 	};
-        sockaddr_union addr = { .in = sin_test };
-        return _test_connect(PF_INET, &addr.generic, sizeof(addr.in));
+	sockaddr_union addr = { .in = sin_test };
+	return _test_connect(PF_INET, &addr.generic, sizeof(addr.in), mark);
 }
 
 // Returns 0 on success, else returns on error.
 static int
 android_getaddrinfo_proxy(
     const char *hostname, const char *servname,
-    const struct addrinfo *hints, struct addrinfo **res, const char *iface)
+    const struct addrinfo *hints, struct addrinfo **res, unsigned netid)
 {
 	int sock;
 	const int one = 1;
@@ -447,14 +451,14 @@
 
 	// Send the request.
 	proxy = fdopen(sock, "r+");
-	if (fprintf(proxy, "getaddrinfo %s %s %d %d %d %d %s",
+	if (fprintf(proxy, "getaddrinfo %s %s %d %d %d %d %u",
 		    hostname == NULL ? "^" : hostname,
 		    servname == NULL ? "^" : servname,
 		    hints == NULL ? -1 : hints->ai_flags,
 		    hints == NULL ? -1 : hints->ai_family,
 		    hints == NULL ? -1 : hints->ai_socktype,
 		    hints == NULL ? -1 : hints->ai_protocol,
-		    iface == NULL ? "^" : iface) < 0) {
+		    netid) < 0) {
 		goto exit;
 	}
 	// literal NULL byte at end, required by FrameworkListener
@@ -578,12 +582,12 @@
 getaddrinfo(const char *hostname, const char *servname,
     const struct addrinfo *hints, struct addrinfo **res)
 {
-	return android_getaddrinfoforiface(hostname, servname, hints, NULL, 0, res);
+	return android_getaddrinfofornet(hostname, servname, hints, NETID_UNSET, MARK_UNSET, res);
 }
 
 int
-android_getaddrinfoforiface(const char *hostname, const char *servname,
-    const struct addrinfo *hints, const char *iface, int mark, struct addrinfo **res)
+android_getaddrinfofornet(const char *hostname, const char *servname,
+    const struct addrinfo *hints, unsigned netid, unsigned mark, struct addrinfo **res)
 {
 	struct addrinfo sentinel;
 	struct addrinfo *cur;
@@ -732,7 +736,7 @@
          */
 	if (cache_mode == NULL || strcmp(cache_mode, "local") != 0) {
 		// we're not the proxy - pass the request to them
-		return android_getaddrinfo_proxy(hostname, servname, hints, res, iface);
+		return android_getaddrinfo_proxy(hostname, servname, hints, res, netid);
 	}
 
 	/*
@@ -762,7 +766,7 @@
 			pai->ai_protocol = ex->e_protocol;
 
 		error = explore_fqdn(pai, hostname, servname,
-			&cur->ai_next, iface, mark);
+			&cur->ai_next, netid, mark);
 
 		while (cur && cur->ai_next)
 			cur = cur->ai_next;
@@ -795,7 +799,7 @@
  */
 static int
 explore_fqdn(const struct addrinfo *pai, const char *hostname,
-    const char *servname, struct addrinfo **res, const char *iface, int mark)
+    const char *servname, struct addrinfo **res, unsigned netid, unsigned mark)
 {
 	struct addrinfo *result;
 	struct addrinfo *cur;
@@ -821,7 +825,7 @@
 		return 0;
 
 	switch (nsdispatch(&result, dtab, NSDB_HOSTS, "getaddrinfo",
-			default_dns_files, hostname, pai, iface, mark)) {
+			default_dns_files, hostname, pai, netid, mark)) {
 	case NS_TRYAGAIN:
 		error = EAI_AGAIN;
 		goto free;
@@ -1767,7 +1771,7 @@
 
 /*ARGSUSED*/
 static int
-_find_src_addr(const struct sockaddr *addr, struct sockaddr *src_addr)
+_find_src_addr(const struct sockaddr *addr, struct sockaddr *src_addr, unsigned mark)
 {
 	int sock;
 	int ret;
@@ -1793,7 +1797,8 @@
 			return -1;
 		}
 	}
-
+	if (mark != MARK_UNSET && setsockopt(sock, SOL_SOCKET, SO_MARK, &mark, sizeof(mark)) < 0)
+		return 0;
 	do {
 		ret = connect(sock, addr, len);
 	} while (ret == -1 && errno == EINTR);
@@ -1818,7 +1823,7 @@
 
 /*ARGSUSED*/
 static void
-_rfc6724_sort(struct addrinfo *list_sentinel)
+_rfc6724_sort(struct addrinfo *list_sentinel, unsigned mark)
 {
 	struct addrinfo *cur;
 	int nelem = 0, i;
@@ -1845,7 +1850,7 @@
 		elems[i].ai = cur;
 		elems[i].original_order = i;
 
-		has_src_addr = _find_src_addr(cur->ai_addr, &elems[i].src_addr.generic);
+		has_src_addr = _find_src_addr(cur->ai_addr, &elems[i].src_addr.generic, mark);
 		if (has_src_addr == -1) {
 			goto error;
 		}
@@ -1865,21 +1870,6 @@
 	free(elems);
 }
 
-static bool _using_default_dns(const char *iface)
-{
-	char buf[IF_NAMESIZE+1];
-	size_t if_len;
-
-	// common case
-	if (iface == NULL || *iface == '\0') return true;
-
-	if_len = _resolv_get_default_iface(buf, sizeof(buf));
-	if (if_len != 0 && if_len + 1 <= sizeof(buf)) {
-		if (strcmp(buf, iface) == 0) return true;
-	}
-	return false;
-}
-
 /*ARGSUSED*/
 static int
 _dns_getaddrinfo(void *rv, void	*cb_data, va_list ap)
@@ -1891,13 +1881,12 @@
 	struct addrinfo sentinel, *cur;
 	struct res_target q, q2;
 	res_state res;
-	const char* iface;
-	int mark;
+	unsigned netid, mark;
 
 	name = va_arg(ap, char *);
 	pai = va_arg(ap, const struct addrinfo *);
-	iface = va_arg(ap, char *);
-	mark = va_arg(ap, int);
+	netid = va_arg(ap, unsigned);
+	mark = va_arg(ap, unsigned);
 	//fprintf(stderr, "_dns_getaddrinfo() name = '%s'\n", name);
 
 	memset(&q, 0, sizeof(q));
@@ -1926,13 +1915,8 @@
 		q.anslen = sizeof(buf->buf);
 		int query_ipv6 = 1, query_ipv4 = 1;
 		if (pai->ai_flags & AI_ADDRCONFIG) {
-			// Only implement AI_ADDRCONFIG if the application is not
-			// using its own DNS servers, since our implementation
-			// only works on the default connection.
-			if (_using_default_dns(iface)) {
-				query_ipv6 = _have_ipv6();
-				query_ipv4 = _have_ipv4();
-			}
+			query_ipv6 = _have_ipv6(mark);
+			query_ipv4 = _have_ipv4(mark);
 		}
 		if (query_ipv6) {
 			q.qtype = T_AAAA;
@@ -1979,12 +1963,12 @@
 		return NS_NOTFOUND;
 	}
 
-	/* this just sets our iface val in the thread private data so we don't have to
+	/* this just sets our netid val in the thread private data so we don't have to
 	 * modify the api's all the way down to res_send.c's res_nsend.  We could
 	 * fully populate the thread private data here, but if we get down there
 	 * and have a cache hit that would be wasted, so we do the rest there on miss
 	 */
-	res_setiface(res, iface);
+	res_setnetid(res, netid);
 	res_setmark(res, mark);
 	if (res_searchN(name, &q, res) < 0) {
 		__res_put_state(res);
@@ -2017,7 +2001,7 @@
 		}
 	}
 
-	_rfc6724_sort(&sentinel);
+	_rfc6724_sort(&sentinel, netid);
 
 	__res_put_state(res);
 
@@ -2320,7 +2304,7 @@
 		 * the domain stuff is tried.  Will have a better
 		 * fix after thread pools are used.
 		 */
-		_resolv_populate_res_for_iface(res);
+		_resolv_populate_res_for_net(res);
 
 		for (domain = (const char * const *)res->dnsrch;
 		   *domain && !done;
diff --git a/libc/dns/net/getnameinfo.c b/libc/dns/net/getnameinfo.c
index f940109..b9c0280 100644
--- a/libc/dns/net/getnameinfo.c
+++ b/libc/dns/net/getnameinfo.c
@@ -62,6 +62,7 @@
 #include <limits.h>
 #include <netdb.h>
 #include <arpa/nameser.h>
+#include "resolv_netid.h"
 #include "resolv_private.h"
 #include <sys/system_properties.h>
 #include <stdlib.h>
@@ -92,7 +93,7 @@
 };
 
 static int getnameinfo_inet(const struct sockaddr *, socklen_t, char *,
-    socklen_t, char *, socklen_t, int, const char*, int);
+    socklen_t, char *, socklen_t, int, unsigned, unsigned);
 #ifdef INET6
 static int ip6_parsenumeric(const struct sockaddr *, const char *, char *,
 				 socklen_t, int);
@@ -105,18 +106,22 @@
  * Top-level getnameinfo() code.  Look at the address family, and pick an
  * appropriate function to call.
  */
-int getnameinfo(const struct sockaddr* sa, socklen_t salen, char* host, size_t hostlen, char* serv, size_t servlen, int flags)
+int getnameinfo(const struct sockaddr* sa, socklen_t salen, char* host, size_t hostlen,
+		char* serv, size_t servlen, int flags)
 {
-	return android_getnameinfoforiface(sa, salen, host, hostlen, serv, servlen, flags, NULL, 0);
+	return android_getnameinfofornet(sa, salen, host, hostlen, serv, servlen, flags,
+			NETID_UNSET, MARK_UNSET);
 }
 
-int android_getnameinfoforiface(const struct sockaddr* sa, socklen_t salen, char* host, size_t hostlen, char* serv, size_t servlen, int flags, const char* iface, int mark)
+int android_getnameinfofornet(const struct sockaddr* sa, socklen_t salen, char* host,
+		size_t hostlen, char* serv, size_t servlen, int flags, unsigned netid,
+		unsigned mark)
 {
 	switch (sa->sa_family) {
 	case AF_INET:
 	case AF_INET6:
 		return getnameinfo_inet(sa, salen, host, hostlen,
-				serv, servlen, flags, iface, mark);
+				serv, servlen, flags, netid, mark);
 	case AF_LOCAL:
 		return getnameinfo_local(sa, salen, host, hostlen,
 		    serv, servlen, flags);
@@ -152,24 +157,6 @@
        return 0;
 }
 
-/* On success length of the host name is returned. A return
- * value of 0 means there's no host name associated with
- * the address. On failure -1 is returned in which case
- * normal execution flow shall continue. */
-static int
-android_gethostbyaddr_proxy(char* nameBuf, size_t nameBufLen, const void *addr, socklen_t addrLen, int addrFamily, const char* iface, int mark)
-{
-	struct hostent *hostResult =
-			android_gethostbyaddrforiface_proxy(addr, addrLen, addrFamily, iface, mark);
-
-	if (hostResult == NULL) return 0;
-
-	int lengthResult = strlen(hostResult->h_name);
-
-	if (nameBuf) strncpy(nameBuf, hostResult->h_name, nameBufLen);
-	return lengthResult;
-}
-
 /*
  * getnameinfo_inet():
  * Format an IPv4 or IPv6 sockaddr into a printable string.
@@ -178,7 +165,7 @@
 getnameinfo_inet(const struct sockaddr* sa, socklen_t salen,
        char *host, socklen_t hostlen,
        char *serv, socklen_t servlen,
-       int flags, const char* iface, int mark)
+       int flags, unsigned netid, unsigned mark)
 {
 	const struct afd *afd;
 	struct servent *sp;
@@ -316,21 +303,7 @@
 			break;
 		}
 	} else {
-		struct hostent android_proxy_hostent;
-		char android_proxy_buf[MAXDNAME];
-
-		int hostnamelen = android_gethostbyaddr_proxy(android_proxy_buf,
-				MAXDNAME, addr, afd->a_addrlen, afd->a_af, iface, mark);
-		if (hostnamelen > 0) {
-			hp = &android_proxy_hostent;
-			hp->h_name = android_proxy_buf;
-		} else if (!hostnamelen) {
-			hp = NULL;
-		} else {
-			hp = android_gethostbyaddrforiface(addr, afd->a_addrlen, afd->a_af,
-					iface, mark);
-		}
-
+		hp = android_gethostbyaddrfornet_proxy(addr, afd->a_addrlen, afd->a_af, netid);
 		if (hp) {
 #if 0
 			/*
@@ -341,6 +314,7 @@
 				char *p;
 				p = strchr(hp->h_name, '.');
 				if (p)
+					TODO: Before uncommenting rewrite to avoid modifying hp.
 					*p = '\0';
 			}
 #endif
diff --git a/libc/dns/resolv/res_cache.c b/libc/dns/resolv/res_cache.c
index fa7345c..9df97cd 100644
--- a/libc/dns/resolv/res_cache.c
+++ b/libc/dns/resolv/res_cache.c
@@ -42,7 +42,7 @@
 
 #include <arpa/inet.h>
 #include "resolv_private.h"
-#include "resolv_iface.h"
+#include "resolv_netid.h"
 #include "res_private.h"
 
 /* This code implements a small and *simple* DNS resolver cache.
@@ -92,18 +92,6 @@
  *
  *     note that RESOLV_CACHE_UNSUPPORTED is also returned if the answer buffer
  *     is too short to accomodate the cached result.
- *
- *  - when network settings change, the cache must be flushed since the list
- *    of DNS servers probably changed. this is done by calling
- *    _resolv_cache_reset()
- *
- *    the parameter to this function must be an ever-increasing generation
- *    number corresponding to the current network settings state.
- *
- *    This is done because several threads could detect the same network
- *    settings change (but at different times) and will all end up calling the
- *    same function. Comparing with the last used generation number ensures
- *    that the cache is only flushed once per network change.
  */
 
 /* the name of an environment variable that will be checked the first time
@@ -1231,34 +1219,20 @@
     int              num_entries;
     Entry            mru_list;
     pthread_mutex_t  lock;
-    unsigned         generation;
     int              last_id;
     Entry*           entries;
     PendingReqInfo   pending_requests;
 } Cache;
 
-typedef struct resolv_cache_info {
-    char                        ifname[IF_NAMESIZE + 1];
-    struct in_addr              ifaddr;
+struct resolv_cache_info {
+    unsigned                    netid;
     Cache*                      cache;
     struct resolv_cache_info*   next;
     char*                       nameservers[MAXNS +1];
     struct addrinfo*            nsaddrinfo[MAXNS + 1];
     char                        defdname[256];
     int                         dnsrch_offset[MAXDNSRCH+1];  // offsets into defdname
-} CacheInfo;
-
-typedef struct resolv_pidiface_info {
-    int                             pid;
-    char                            ifname[IF_NAMESIZE + 1];
-    struct resolv_pidiface_info*    next;
-} PidIfaceInfo;
-typedef struct resolv_uidiface_info {
-    int                             uid_start;
-    int                             uid_end;
-    char                            ifname[IF_NAMESIZE + 1];
-    struct resolv_uidiface_info*    next;
-} UidIfaceInfo;
+};
 
 #define  HTABLE_VALID(x)  ((x) != NULL && (x) != HTABLE_DELETED)
 
@@ -1417,7 +1391,6 @@
         cache->max_entries = _res_cache_get_max_entries();
         cache->entries = calloc(sizeof(*cache->entries), cache->max_entries);
         if (cache->entries) {
-            cache->generation = ~0U;
             pthread_mutex_init( &cache->lock, NULL );
             cache->mru_list.mru_prev = cache->mru_list.mru_next = &cache->mru_list;
             XLOG("%s: cache created\n", __FUNCTION__);
@@ -1485,7 +1458,7 @@
     }
     else {
         errno = 0; // else debug is introducing error signals
-        XLOG("_dump_answer: can't open file\n");
+        XLOG("%s: can't open file\n", __FUNCTION__);
     }
 }
 #endif
@@ -1776,64 +1749,27 @@
 // Head of the list of caches.  Protected by _res_cache_list_lock.
 static struct resolv_cache_info _res_cache_list;
 
-// List of pid iface pairs
-static struct resolv_pidiface_info _res_pidiface_list;
-
-// List of uid iface pairs
-static struct resolv_uidiface_info _res_uidiface_list;
-
-// name of the current default inteface
-static char            _res_default_ifname[IF_NAMESIZE + 1];
-
 // lock protecting everything in the _resolve_cache_info structs (next ptr, etc)
 static pthread_mutex_t _res_cache_list_lock;
 
-// lock protecting the _res_pid_iface_list
-static pthread_mutex_t _res_pidiface_list_lock;
-
-// lock protecting the _res_uidiface_list
-static pthread_mutex_t _res_uidiface_list_lock;
-
-/* lookup the default interface name */
-static char *_get_default_iface_locked();
-/* find the first cache that has an associated interface and return the name of the interface */
-static char* _find_any_iface_name_locked( void );
-
 /* insert resolv_cache_info into the list of resolv_cache_infos */
 static void _insert_cache_info_locked(struct resolv_cache_info* cache_info);
 /* creates a resolv_cache_info */
 static struct resolv_cache_info* _create_cache_info( void );
-/* gets cache associated with an interface name, or NULL if none exists */
-static struct resolv_cache* _find_named_cache_locked(const char* ifname);
-/* gets a resolv_cache_info associated with an interface name, or NULL if not found */
-static struct resolv_cache_info* _find_cache_info_locked(const char* ifname);
+/* gets cache associated with a network, or NULL if none exists */
+static struct resolv_cache* _find_named_cache_locked(unsigned netid);
+/* gets a resolv_cache_info associated with a network, or NULL if not found */
+static struct resolv_cache_info* _find_cache_info_locked(unsigned netid);
 /* look up the named cache, and creates one if needed */
-static struct resolv_cache* _get_res_cache_for_iface_locked(const char* ifname);
+static struct resolv_cache* _get_res_cache_for_net_locked(unsigned netid);
 /* empty the named cache */
-static void _flush_cache_for_iface_locked(const char* ifname);
+static void _flush_cache_for_net_locked(unsigned netid);
 /* empty the nameservers set for the named cache */
 static void _free_nameservers_locked(struct resolv_cache_info* cache_info);
-/* lookup the namserver for the name interface */
-static int _get_nameserver_locked(const char* ifname, int n, char* addr, int addrLen);
-/* lookup the addr of the nameserver for the named interface */
-static struct addrinfo* _get_nameserver_addr_locked(const char* ifname, int n);
-/* lookup the inteface's address */
-static struct in_addr* _get_addr_locked(const char * ifname);
 /* return 1 if the provided list of name servers differs from the list of name servers
  * currently attached to the provided cache_info */
 static int _resolv_is_nameservers_equal_locked(struct resolv_cache_info* cache_info,
         const char** servers, int numservers);
-/* remove a resolv_pidiface_info structure from _res_pidiface_list */
-static void _remove_pidiface_info_locked(int pid);
-/* get a resolv_pidiface_info structure from _res_pidiface_list with a certain pid */
-static struct resolv_pidiface_info* _get_pid_iface_info_locked(int pid);
-
-/* remove a resolv_pidiface_info structure from _res_uidiface_list */
-static int _remove_uidiface_info_locked(int uid_start, int uid_end);
-/* check if a range [low,high] overlaps with any already existing ranges in the uid=>iface map*/
-static int  _resolv_check_uid_range_overlap_locked(int uid_start, int uid_end);
-/* get a resolv_uidiface_info structure from _res_uidiface_list with a certain uid */
-static struct resolv_uidiface_info* _get_uid_iface_info_locked(int uid);
 
 static void
 _res_cache_init(void)
@@ -1845,60 +1781,37 @@
         return;
     }
 
-    memset(&_res_default_ifname, 0, sizeof(_res_default_ifname));
     memset(&_res_cache_list, 0, sizeof(_res_cache_list));
-    memset(&_res_pidiface_list, 0, sizeof(_res_pidiface_list));
-    memset(&_res_uidiface_list, 0, sizeof(_res_uidiface_list));
     pthread_mutex_init(&_res_cache_list_lock, NULL);
-    pthread_mutex_init(&_res_pidiface_list_lock, NULL);
-    pthread_mutex_init(&_res_uidiface_list_lock, NULL);
 }
 
 struct resolv_cache*
-__get_res_cache(const char* ifname)
+__get_res_cache(unsigned netid)
 {
     struct resolv_cache *cache;
 
     pthread_once(&_res_cache_once, _res_cache_init);
     pthread_mutex_lock(&_res_cache_list_lock);
 
-    char* iface;
-    if (ifname == NULL || ifname[0] == '\0') {
-        iface = _get_default_iface_locked();
-        if (iface[0] == '\0') {
-            char* tmp = _find_any_iface_name_locked();
-            if (tmp) {
-                iface = tmp;
-            }
-        }
-    } else {
-        iface = (char *) ifname;
-    }
-
-    cache = _get_res_cache_for_iface_locked(iface);
+    /* Does NOT create a cache if it does not exist. */
+    cache = _find_named_cache_locked(netid);
 
     pthread_mutex_unlock(&_res_cache_list_lock);
-    XLOG("_get_res_cache: iface = %s, cache=%p\n", iface, cache);
+    XLOG("%s: netid=%u, cache=%p\n", __FUNCTION__, netid, cache);
     return cache;
 }
 
 static struct resolv_cache*
-_get_res_cache_for_iface_locked(const char* ifname)
+_get_res_cache_for_net_locked(unsigned netid)
 {
-    if (ifname == NULL)
-        return NULL;
-
-    struct resolv_cache* cache = _find_named_cache_locked(ifname);
+    struct resolv_cache* cache = _find_named_cache_locked(netid);
     if (!cache) {
         struct resolv_cache_info* cache_info = _create_cache_info();
         if (cache_info) {
             cache = _resolv_cache_create();
             if (cache) {
-                int len = sizeof(cache_info->ifname);
                 cache_info->cache = cache;
-                strncpy(cache_info->ifname, ifname, len - 1);
-                cache_info->ifname[len - 1] = '\0';
-
+                cache_info->netid = netid;
                 _insert_cache_info_locked(cache_info);
             } else {
                 free(cache_info);
@@ -1909,73 +1822,20 @@
 }
 
 void
-_resolv_cache_reset(unsigned  generation)
-{
-    XLOG("%s: generation=%d", __FUNCTION__, generation);
-
-    pthread_once(&_res_cache_once, _res_cache_init);
-    pthread_mutex_lock(&_res_cache_list_lock);
-
-    char* ifname = _get_default_iface_locked();
-    // if default interface not set then use the first cache
-    // associated with an interface as the default one.
-    // Note: Copied the code from __get_res_cache since this
-    // method will be deleted/obsolete when cache per interface
-    // implemented all over
-    if (ifname[0] == '\0') {
-        struct resolv_cache_info* cache_info = _res_cache_list.next;
-        while (cache_info) {
-            if (cache_info->ifname[0] != '\0') {
-                ifname = cache_info->ifname;
-                break;
-            }
-
-            cache_info = cache_info->next;
-        }
-    }
-    struct resolv_cache* cache = _get_res_cache_for_iface_locked(ifname);
-
-    if (cache != NULL) {
-        pthread_mutex_lock( &cache->lock );
-        if (cache->generation != generation) {
-            _cache_flush_locked(cache);
-            cache->generation = generation;
-        }
-        pthread_mutex_unlock( &cache->lock );
-    }
-
-    pthread_mutex_unlock(&_res_cache_list_lock);
-}
-
-void
-_resolv_flush_cache_for_default_iface(void)
-{
-    char* ifname;
-
-    pthread_once(&_res_cache_once, _res_cache_init);
-    pthread_mutex_lock(&_res_cache_list_lock);
-
-    ifname = _get_default_iface_locked();
-    _flush_cache_for_iface_locked(ifname);
-
-    pthread_mutex_unlock(&_res_cache_list_lock);
-}
-
-void
-_resolv_flush_cache_for_iface(const char* ifname)
+_resolv_flush_cache_for_net(unsigned netid)
 {
     pthread_once(&_res_cache_once, _res_cache_init);
     pthread_mutex_lock(&_res_cache_list_lock);
 
-    _flush_cache_for_iface_locked(ifname);
+    _flush_cache_for_net_locked(netid);
 
     pthread_mutex_unlock(&_res_cache_list_lock);
 }
 
 static void
-_flush_cache_for_iface_locked(const char* ifname)
+_flush_cache_for_net_locked(unsigned netid)
 {
-    struct resolv_cache* cache = _find_named_cache_locked(ifname);
+    struct resolv_cache* cache = _find_named_cache_locked(netid);
     if (cache) {
         pthread_mutex_lock(&cache->lock);
         _cache_flush_locked(cache);
@@ -1986,7 +1846,7 @@
 static struct resolv_cache_info*
 _create_cache_info(void)
 {
-    struct resolv_cache_info*  cache_info;
+    struct resolv_cache_info* cache_info;
 
     cache_info = calloc(sizeof(*cache_info), 1);
     return cache_info;
@@ -2004,9 +1864,9 @@
 }
 
 static struct resolv_cache*
-_find_named_cache_locked(const char* ifname) {
+_find_named_cache_locked(unsigned netid) {
 
-    struct resolv_cache_info* info = _find_cache_info_locked(ifname);
+    struct resolv_cache_info* info = _find_cache_info_locked(netid);
 
     if (info != NULL) return info->cache;
 
@@ -2014,15 +1874,12 @@
 }
 
 static struct resolv_cache_info*
-_find_cache_info_locked(const char* ifname)
+_find_cache_info_locked(unsigned netid)
 {
-    if (ifname == NULL)
-        return NULL;
-
     struct resolv_cache_info* cache_info = _res_cache_list.next;
 
     while (cache_info) {
-        if (strcmp(cache_info->ifname, ifname) == 0) {
+        if (cache_info->netid == netid) {
             break;
         }
 
@@ -2031,50 +1888,8 @@
     return cache_info;
 }
 
-static char*
-_get_default_iface_locked(void)
-{
-
-    char* iface = _res_default_ifname;
-
-    return iface;
-}
-
-static char*
-_find_any_iface_name_locked( void ) {
-    char* ifname = NULL;
-
-    struct resolv_cache_info* cache_info = _res_cache_list.next;
-    while (cache_info) {
-        if (cache_info->ifname[0] != '\0') {
-            ifname = cache_info->ifname;
-            break;
-        }
-
-        cache_info = cache_info->next;
-    }
-
-    return ifname;
-}
-
 void
-_resolv_set_default_iface(const char* ifname)
-{
-    XLOG("_resolv_set_default_if ifname %s\n",ifname);
-
-    pthread_once(&_res_cache_once, _res_cache_init);
-    pthread_mutex_lock(&_res_cache_list_lock);
-
-    int size = sizeof(_res_default_ifname);
-    memset(_res_default_ifname, 0, size);
-    strncpy(_res_default_ifname, ifname, size - 1);
-    _res_default_ifname[size - 1] = '\0';
-
-    pthread_mutex_unlock(&_res_cache_list_lock);
-}
-
-void
-_resolv_set_nameservers_for_iface(const char* ifname, const char** servers, int numservers,
+_resolv_set_nameservers_for_net(unsigned netid, const char** servers, int numservers,
         const char *domains)
 {
     int i, rt, index;
@@ -2087,9 +1902,9 @@
     pthread_mutex_lock(&_res_cache_list_lock);
 
     // creates the cache if not created
-    _get_res_cache_for_iface_locked(ifname);
+    _get_res_cache_for_net_locked(netid);
 
-    struct resolv_cache_info* cache_info = _find_cache_info_locked(ifname);
+    struct resolv_cache_info* cache_info = _find_cache_info_locked(netid);
 
     if (cache_info != NULL &&
             !_resolv_is_nameservers_equal_locked(cache_info, servers, numservers)) {
@@ -2108,8 +1923,7 @@
             if (rt == 0) {
                 cache_info->nameservers[index] = strdup(servers[i]);
                 index++;
-                XLOG("_resolv_set_nameservers_for_iface: iface = %s, addr = %s\n",
-                        ifname, servers[i]);
+                XLOG("%s: netid = %u, addr = %s\n", __FUNCTION__, netid, servers[i]);
             } else {
                 cache_info->nsaddrinfo[index] = NULL;
             }
@@ -2138,7 +1952,7 @@
         *offset = -1; /* cache_info->dnsrch_offset has MAXDNSRCH+1 items */
 
         // flush cache since new settings
-        _flush_cache_for_iface_locked(ifname);
+        _flush_cache_for_net_locked(netid);
 
     }
 
@@ -2184,449 +1998,21 @@
     }
 }
 
-int
-_resolv_cache_get_nameserver(int n, char* addr, int addrLen)
-{
-    char *ifname;
-    int result = 0;
-
-    pthread_once(&_res_cache_once, _res_cache_init);
-    pthread_mutex_lock(&_res_cache_list_lock);
-
-    ifname = _get_default_iface_locked();
-    result = _get_nameserver_locked(ifname, n, addr, addrLen);
-
-    pthread_mutex_unlock(&_res_cache_list_lock);
-    return result;
-}
-
-static int
-_get_nameserver_locked(const char* ifname, int n, char* addr, int addrLen)
-{
-    int len = 0;
-    char* ns;
-    struct resolv_cache_info* cache_info;
-
-    if (n < 1 || n > MAXNS || !addr)
-        return 0;
-
-    cache_info = _find_cache_info_locked(ifname);
-    if (cache_info) {
-        ns = cache_info->nameservers[n - 1];
-        if (ns) {
-            len = strlen(ns);
-            if (len < addrLen) {
-                strncpy(addr, ns, len);
-                addr[len] = '\0';
-            } else {
-                len = 0;
-            }
-        }
-    }
-
-    return len;
-}
-
-struct addrinfo*
-_cache_get_nameserver_addr(int n)
-{
-    struct addrinfo *result;
-    char* ifname;
-
-    pthread_once(&_res_cache_once, _res_cache_init);
-    pthread_mutex_lock(&_res_cache_list_lock);
-
-    ifname = _get_default_iface_locked();
-
-    result = _get_nameserver_addr_locked(ifname, n);
-    pthread_mutex_unlock(&_res_cache_list_lock);
-    return result;
-}
-
-static struct addrinfo*
-_get_nameserver_addr_locked(const char* ifname, int n)
-{
-    struct addrinfo* ai = NULL;
-    struct resolv_cache_info* cache_info;
-
-    if (n < 1 || n > MAXNS)
-        return NULL;
-
-    cache_info = _find_cache_info_locked(ifname);
-    if (cache_info) {
-        ai = cache_info->nsaddrinfo[n - 1];
-    }
-    return ai;
-}
-
 void
-_resolv_set_addr_of_iface(const char* ifname, struct in_addr* addr)
-{
-    pthread_once(&_res_cache_once, _res_cache_init);
-    pthread_mutex_lock(&_res_cache_list_lock);
-    struct resolv_cache_info* cache_info = _find_cache_info_locked(ifname);
-    if (cache_info) {
-        memcpy(&cache_info->ifaddr, addr, sizeof(*addr));
-
-        if (DEBUG) {
-            XLOG("address of interface %s is %s\n",
-                    ifname, inet_ntoa(cache_info->ifaddr));
-        }
-    }
-    pthread_mutex_unlock(&_res_cache_list_lock);
-}
-
-struct in_addr*
-_resolv_get_addr_of_default_iface(void)
-{
-    struct in_addr* ai = NULL;
-    char* ifname;
-
-    pthread_once(&_res_cache_once, _res_cache_init);
-    pthread_mutex_lock(&_res_cache_list_lock);
-    ifname = _get_default_iface_locked();
-    ai = _get_addr_locked(ifname);
-    pthread_mutex_unlock(&_res_cache_list_lock);
-
-    return ai;
-}
-
-struct in_addr*
-_resolv_get_addr_of_iface(const char* ifname)
-{
-    struct in_addr* ai = NULL;
-
-    pthread_once(&_res_cache_once, _res_cache_init);
-    pthread_mutex_lock(&_res_cache_list_lock);
-    ai =_get_addr_locked(ifname);
-    pthread_mutex_unlock(&_res_cache_list_lock);
-    return ai;
-}
-
-static struct in_addr*
-_get_addr_locked(const char * ifname)
-{
-    struct resolv_cache_info* cache_info = _find_cache_info_locked(ifname);
-    if (cache_info) {
-        return &cache_info->ifaddr;
-    }
-    return NULL;
-}
-
-static void
-_remove_pidiface_info_locked(int pid) {
-    struct resolv_pidiface_info* result = &_res_pidiface_list;
-    struct resolv_pidiface_info* prev = NULL;
-
-    while (result != NULL && result->pid != pid) {
-        prev = result;
-        result = result->next;
-    }
-    if (prev != NULL && result != NULL) {
-        prev->next = result->next;
-        free(result);
-    }
-}
-
-static struct resolv_pidiface_info*
-_get_pid_iface_info_locked(int pid)
-{
-    struct resolv_pidiface_info* result = &_res_pidiface_list;
-    while (result != NULL && result->pid != pid) {
-        result = result->next;
-    }
-
-    return result;
-}
-
-void
-_resolv_set_iface_for_pid(const char* ifname, int pid)
-{
-    // make sure the pid iface list is created
-    pthread_once(&_res_cache_once, _res_cache_init);
-    pthread_mutex_lock(&_res_pidiface_list_lock);
-
-    struct resolv_pidiface_info* pidiface_info = _get_pid_iface_info_locked(pid);
-    if (!pidiface_info) {
-        pidiface_info = calloc(sizeof(*pidiface_info), 1);
-        if (pidiface_info) {
-            pidiface_info->pid = pid;
-            int len = sizeof(pidiface_info->ifname);
-            strncpy(pidiface_info->ifname, ifname, len - 1);
-            pidiface_info->ifname[len - 1] = '\0';
-
-            pidiface_info->next = _res_pidiface_list.next;
-            _res_pidiface_list.next = pidiface_info;
-
-            XLOG("_resolv_set_iface_for_pid: pid %d , iface %s\n", pid, ifname);
-        } else {
-            XLOG("_resolv_set_iface_for_pid failing calloc");
-        }
-    }
-
-    pthread_mutex_unlock(&_res_pidiface_list_lock);
-}
-
-void
-_resolv_clear_iface_for_pid(int pid)
-{
-    pthread_once(&_res_cache_once, _res_cache_init);
-    pthread_mutex_lock(&_res_pidiface_list_lock);
-
-    _remove_pidiface_info_locked(pid);
-
-    XLOG("_resolv_clear_iface_for_pid: pid %d\n", pid);
-
-    pthread_mutex_unlock(&_res_pidiface_list_lock);
-}
-
-int
-_resolv_get_pids_associated_interface(int pid, char* buff, int buffLen)
-{
-    int len = 0;
-
-    if (!buff) {
-        return -1;
-    }
-
-    pthread_once(&_res_cache_once, _res_cache_init);
-    pthread_mutex_lock(&_res_pidiface_list_lock);
-
-    struct resolv_pidiface_info* pidiface_info = _get_pid_iface_info_locked(pid);
-    buff[0] = '\0';
-    if (pidiface_info) {
-        len = strlen(pidiface_info->ifname);
-        if (len < buffLen) {
-            strncpy(buff, pidiface_info->ifname, len);
-            buff[len] = '\0';
-        }
-    }
-
-    XLOG("_resolv_get_pids_associated_interface buff: %s\n", buff);
-
-    pthread_mutex_unlock(&_res_pidiface_list_lock);
-
-    return len;
-}
-
-static int
-_remove_uidiface_info_locked(int uid_start, int uid_end) {
-    struct resolv_uidiface_info* result = _res_uidiface_list.next;
-    struct resolv_uidiface_info* prev = &_res_uidiface_list;
-
-    while (result != NULL && result->uid_start != uid_start && result->uid_end != uid_end) {
-        prev = result;
-        result = result->next;
-    }
-    if (prev != NULL && result != NULL) {
-        prev->next = result->next;
-        free(result);
-        return 0;
-    }
-    errno = EINVAL;
-    return -1;
-}
-
-static struct resolv_uidiface_info*
-_get_uid_iface_info_locked(int uid)
-{
-    struct resolv_uidiface_info* result = _res_uidiface_list.next;
-    while (result != NULL && !(result->uid_start <= uid && result->uid_end >= uid)) {
-        result = result->next;
-    }
-
-    return result;
-}
-
-static int
-_resolv_check_uid_range_overlap_locked(int uid_start, int uid_end)
-{
-    struct resolv_uidiface_info* cur = _res_uidiface_list.next;
-    while (cur != NULL) {
-        if (cur->uid_start <= uid_end && cur->uid_end >= uid_start) {
-            return -1;
-        }
-        cur = cur->next;
-    }
-    return 0;
-}
-
-void
-_resolv_clear_iface_uid_range_mapping()
-{
-    pthread_once(&_res_cache_once, _res_cache_init);
-    pthread_mutex_lock(&_res_uidiface_list_lock);
-    struct resolv_uidiface_info *current = _res_uidiface_list.next;
-    struct resolv_uidiface_info *next;
-    while (current != NULL) {
-        next = current->next;
-        free(current);
-        current = next;
-    }
-    _res_uidiface_list.next = NULL;
-    pthread_mutex_unlock(&_res_uidiface_list_lock);
-}
-
-void
-_resolv_clear_iface_pid_mapping()
-{
-    pthread_once(&_res_cache_once, _res_cache_init);
-    pthread_mutex_lock(&_res_pidiface_list_lock);
-    struct resolv_pidiface_info *current = _res_pidiface_list.next;
-    struct resolv_pidiface_info *next;
-    while (current != NULL) {
-        next = current->next;
-        free(current);
-        current = next;
-    }
-    _res_pidiface_list.next = NULL;
-    pthread_mutex_unlock(&_res_pidiface_list_lock);
-}
-
-int
-_resolv_set_iface_for_uid_range(const char* ifname, int uid_start, int uid_end)
-{
-    int rv = 0;
-    struct resolv_uidiface_info* uidiface_info;
-    // make sure the uid iface list is created
-    pthread_once(&_res_cache_once, _res_cache_init);
-    if (uid_start > uid_end) {
-        errno = EINVAL;
-        return -1;
-    }
-    pthread_mutex_lock(&_res_uidiface_list_lock);
-    //check that we aren't adding an overlapping range
-    if (!_resolv_check_uid_range_overlap_locked(uid_start, uid_end)) {
-        uidiface_info = calloc(sizeof(*uidiface_info), 1);
-        if (uidiface_info) {
-            uidiface_info->uid_start = uid_start;
-            uidiface_info->uid_end = uid_end;
-            int len = sizeof(uidiface_info->ifname);
-            strncpy(uidiface_info->ifname, ifname, len - 1);
-            uidiface_info->ifname[len - 1] = '\0';
-
-            uidiface_info->next = _res_uidiface_list.next;
-            _res_uidiface_list.next = uidiface_info;
-
-            XLOG("_resolv_set_iface_for_uid_range: [%d,%d], iface %s\n", uid_start, uid_end,
-                    ifname);
-        } else {
-            XLOG("_resolv_set_iface_for_uid_range failing calloc\n");
-            rv = -1;
-            errno = EINVAL;
-        }
-    } else {
-        XLOG("_resolv_set_iface_for_uid_range range [%d,%d] overlaps\n", uid_start, uid_end);
-        rv = -1;
-        errno = EINVAL;
-    }
-
-    pthread_mutex_unlock(&_res_uidiface_list_lock);
-    return rv;
-}
-
-int
-_resolv_clear_iface_for_uid_range(int uid_start, int uid_end)
-{
-    pthread_once(&_res_cache_once, _res_cache_init);
-    pthread_mutex_lock(&_res_uidiface_list_lock);
-
-    int rv = _remove_uidiface_info_locked(uid_start, uid_end);
-
-    XLOG("_resolv_clear_iface_for_uid_range: [%d,%d]\n", uid_start, uid_end);
-
-    pthread_mutex_unlock(&_res_uidiface_list_lock);
-
-    return rv;
-}
-
-int
-_resolv_get_uids_associated_interface(int uid, char* buff, int buffLen)
-{
-    int len = 0;
-
-    if (!buff) {
-        return -1;
-    }
-
-    pthread_once(&_res_cache_once, _res_cache_init);
-    pthread_mutex_lock(&_res_uidiface_list_lock);
-
-    struct resolv_uidiface_info* uidiface_info = _get_uid_iface_info_locked(uid);
-    buff[0] = '\0';
-    if (uidiface_info) {
-        len = strlen(uidiface_info->ifname);
-        if (len < buffLen) {
-            strncpy(buff, uidiface_info->ifname, len);
-            buff[len] = '\0';
-        }
-    }
-
-    XLOG("_resolv_get_uids_associated_interface buff: %s\n", buff);
-
-    pthread_mutex_unlock(&_res_uidiface_list_lock);
-
-    return len;
-}
-
-size_t
-_resolv_get_default_iface(char* buff, size_t buffLen)
-{
-    if (!buff || buffLen == 0) {
-        return 0;
-    }
-
-    pthread_once(&_res_cache_once, _res_cache_init);
-    pthread_mutex_lock(&_res_cache_list_lock);
-
-    char* ifname = _get_default_iface_locked(); // never null, but may be empty
-
-    // if default interface not set give up.
-    if (ifname[0] == '\0') {
-        pthread_mutex_unlock(&_res_cache_list_lock);
-        return 0;
-    }
-
-    size_t len = strlen(ifname);
-    if (len < buffLen) {
-        strncpy(buff, ifname, len);
-        buff[len] = '\0';
-    } else {
-        buff[0] = '\0';
-    }
-
-    pthread_mutex_unlock(&_res_cache_list_lock);
-
-    return len;
-}
-
-void
-_resolv_populate_res_for_iface(res_state statp)
+_resolv_populate_res_for_net(res_state statp)
 {
     if (statp == NULL) {
         return;
     }
 
-    if (statp->iface[0] == '\0') { // no interface set assign default
-        size_t if_len = _resolv_get_default_iface(statp->iface, sizeof(statp->iface));
-        if (if_len + 1 > sizeof(statp->iface)) {
-            XLOG("%s: INTERNAL_ERROR: can't fit interface name into statp->iface.\n", __FUNCTION__);
-            return;
-        }
-        if (if_len == 0) {
-            XLOG("%s: INTERNAL_ERROR: can't find any suitable interfaces.\n", __FUNCTION__);
-            return;
-        }
-    }
-
     pthread_once(&_res_cache_once, _res_cache_init);
     pthread_mutex_lock(&_res_cache_list_lock);
 
-    struct resolv_cache_info* info = _find_cache_info_locked(statp->iface);
+    struct resolv_cache_info* info = _find_cache_info_locked(statp->netid);
     if (info != NULL) {
         int nserv;
         struct addrinfo* ai;
-        XLOG("_resolv_populate_res_for_iface: %s\n", statp->iface);
+        XLOG("%s: %u\n", __FUNCTION__, statp->netid);
         for (nserv = 0; nserv < MAXNS; nserv++) {
             ai = info->nsaddrinfo[nserv];
             if (ai == NULL) {
@@ -2647,7 +2033,7 @@
                     }
                 }
             } else {
-                XLOG("_resolv_populate_res_for_iface found too long addrlen");
+                XLOG("%s: found too long addrlen", __FUNCTION__);
             }
         }
         statp->nscount = nserv;
diff --git a/libc/dns/resolv/res_init.c b/libc/dns/resolv/res_init.c
index 973226a..9f3a9da 100644
--- a/libc/dns/resolv/res_init.c
+++ b/libc/dns/resolv/res_init.c
@@ -110,6 +110,7 @@
 
 /* ensure that sockaddr_in6 and IN6ADDR_ANY_INIT are declared / defined */
 #ifdef ANDROID_CHANGES
+#include "resolv_netid.h"
 #include "resolv_private.h"
 #else
 #include <resolv.h>
@@ -183,10 +184,12 @@
                 res_ndestroy(statp);
 
 	if (!preinit) {
+		statp->netid = NETID_UNSET;
 		statp->retrans = RES_TIMEOUT;
 		statp->retry = RES_DFLRETRY;
 		statp->options = RES_DEFAULT;
 		statp->id = res_randomid();
+		statp->_mark = MARK_UNSET;
 	}
 
 	memset(u, 0, sizeof(u));
@@ -793,24 +796,18 @@
 }
 
 #ifdef ANDROID_CHANGES
-void res_setiface(res_state statp, const char* iface)
+void res_setnetid(res_state statp, unsigned netid)
 {
 	if (statp != NULL) {
-		// set interface
-		if (iface && iface[0] != '\0') {
-			int len = sizeof(statp->iface);
-			strncpy(statp->iface, iface, len - 1);
-			statp->iface[len - 1] = '\0';
-		} else {
-			statp->iface[0] = '\0';
-		}
+		statp->netid = netid;
 	}
 }
 
-void res_setmark(res_state statp, int mark)
+void res_setmark(res_state statp, unsigned mark)
 {
 	if (statp != NULL) {
 		statp->_mark = mark;
 	}
 }
+
 #endif /* ANDROID_CHANGES */
diff --git a/libc/dns/resolv/res_query.c b/libc/dns/resolv/res_query.c
index fa50631..6cd9b15 100644
--- a/libc/dns/resolv/res_query.c
+++ b/libc/dns/resolv/res_query.c
@@ -91,6 +91,7 @@
 #include <errno.h>
 #include <netdb.h>
 #ifdef ANDROID_CHANGES
+#include "resolv_cache.h"
 #include "resolv_private.h"
 #else
 #include <resolv.h>
@@ -272,14 +273,14 @@
 	    (dots && !trailing_dot && (statp->options & RES_DNSRCH) != 0U)) {
 		int done = 0;
 
-		/* Unfortunately we need to load interface info
+		/* Unfortunately we need to load network-specific info
 		 * (dns servers, search domains) before
 		 * the domain stuff is tried.  Will have a better
 		 * fix after thread pools are used as this will
 		 * be loaded once for the thread instead of each
 		 * time a query is tried.
 		 */
-		_resolv_populate_res_for_iface(statp);
+		_resolv_populate_res_for_net(statp);
 
 		for (domain = (const char * const *)statp->dnsrch;
 		     *domain && !done;
diff --git a/libc/dns/resolv/res_send.c b/libc/dns/resolv/res_send.c
index 8e1f318..9b36f55 100644
--- a/libc/dns/resolv/res_send.c
+++ b/libc/dns/resolv/res_send.c
@@ -102,6 +102,7 @@
 #include <fcntl.h>
 #include <netdb.h>
 #ifdef ANDROID_CHANGES
+#include "resolv_netid.h"
 #include "resolv_private.h"
 #else
 #include <resolv.h>
@@ -388,8 +389,8 @@
 	terrno = ETIMEDOUT;
 
 #if USE_RESOLV_CACHE
-	// get the cache associated with the interface
-	cache = __get_res_cache(statp->iface);
+	// get the cache associated with the network
+	cache = __get_res_cache(statp->netid);
 	if (cache != NULL) {
 		int  anslen = 0;
 		cache_status = _resolv_cache_lookup(
@@ -399,9 +400,9 @@
 		if (cache_status == RESOLV_CACHE_FOUND) {
 			return anslen;
 		} else {
-			// had a cache miss for a known interface, so populate the thread private
+			// had a cache miss for a known network, so populate the thread private
 			// data so the normal resolve path can do its thing
-			_resolv_populate_res_for_iface(statp);
+			_resolv_populate_res_for_net(statp);
 		}
 	}
 
@@ -762,7 +763,7 @@
 	if (statp->_vcsock >= 0 && (statp->_flags & RES_F_VC) != 0) {
 		struct sockaddr_storage peer;
 		socklen_t size = sizeof peer;
-		int old_mark;
+		unsigned old_mark;
 		int mark_size = sizeof(old_mark);
 		if (getpeername(statp->_vcsock,
 				(struct sockaddr *)(void *)&peer, &size) < 0 ||
@@ -798,7 +799,7 @@
 				return (-1);
 			}
 		}
-		if (statp->_mark != 0) {
+		if (statp->_mark != MARK_UNSET) {
 			if (setsockopt(statp->_vcsock, SOL_SOCKET,
 				        SO_MARK, &statp->_mark, sizeof(statp->_mark)) < 0) {
 				*terrno = errno;
@@ -1082,7 +1083,7 @@
 			}
 		}
 
-		if (statp->_mark != 0) {
+		if (statp->_mark != MARK_UNSET) {
 			if (setsockopt(EXT(statp).nssocks[ns], SOL_SOCKET,
 					SO_MARK, &(statp->_mark), sizeof(statp->_mark)) < 0) {
 				res_nclose(statp);
diff --git a/libc/dns/resolv/res_state.c b/libc/dns/resolv/res_state.c
index 087a5e6..01f68e9 100644
--- a/libc/dns/resolv/res_state.c
+++ b/libc/dns/resolv/res_state.c
@@ -54,6 +54,7 @@
 
 typedef struct {
     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;
diff --git a/libc/include/fcntl.h b/libc/include/fcntl.h
index 779a089..cd68154 100644
--- a/libc/include/fcntl.h
+++ b/libc/include/fcntl.h
@@ -37,6 +37,20 @@
 
 __BEGIN_DECLS
 
+#ifdef __LP64__
+/* LP64 kernels don't have flock64 because their flock is 64-bit. */
+struct flock64 {
+  short l_type;
+  short l_whence;
+  off64_t l_start;
+  off64_t l_len;
+  pid_t l_pid;
+};
+#define F_GETLK64  F_GETLK
+#define F_SETLK64  F_SETLK
+#define F_SETLKW64 F_SETLKW
+#endif
+
 #ifndef O_ASYNC
 #define O_ASYNC  FASYNC
 #endif
diff --git a/libc/include/locale.h b/libc/include/locale.h
index 4efc564..6989851 100644
--- a/libc/include/locale.h
+++ b/libc/include/locale.h
@@ -29,6 +29,7 @@
 #define _LOCALE_H_
 
 #include <sys/cdefs.h>
+#include <xlocale.h>
 
 __BEGIN_DECLS
 
@@ -43,15 +44,29 @@
     LC_PAPER     = 7,
     LC_NAME      = 8,
     LC_ADDRESS   = 9,
-
     LC_TELEPHONE      = 10,
     LC_MEASUREMENT    = 11,
     LC_IDENTIFICATION = 12
 };
 
-extern char* setlocale(int, const char*);
+#define LC_CTYPE_MASK          (1 << LC_CTYPE)
+#define LC_NUMERIC_MASK        (1 << LC_NUMERIC)
+#define LC_TIME_MASK           (1 << LC_TIME)
+#define LC_COLLATE_MASK        (1 << LC_COLLATE)
+#define LC_MONETARY_MASK       (1 << LC_MONETARY)
+#define LC_MESSAGES_MASK       (1 << LC_MESSAGES)
+#define LC_PAPER_MASK          (1 << LC_PAPER)
+#define LC_NAME_MASK           (1 << LC_NAME)
+#define LC_ADDRESS_MASK        (1 << LC_ADDRESS)
+#define LC_TELEPHONE_MASK      (1 << LC_TELEPHONE)
+#define LC_MEASUREMENT_MASK    (1 << LC_MEASUREMENT)
+#define LC_IDENTIFICATION_MASK (1 << LC_IDENTIFICATION)
 
-#if defined(__LP64__)
+#define LC_ALL_MASK (LC_CTYPE_MASK | LC_NUMERIC_MASK | LC_TIME_MASK | LC_COLLATE_MASK | \
+                     LC_MONETARY_MASK | LC_MESSAGES_MASK | LC_PAPER_MASK | LC_NAME_MASK | \
+                     LC_ADDRESS_MASK | LC_TELEPHONE_MASK | LC_MEASUREMENT_MASK | \
+                     LC_IDENTIFICATION_MASK)
+
 struct lconv {
     char* decimal_point;
     char* thousands_sep;
@@ -71,7 +86,6 @@
     char  n_sep_by_space;
     char  p_sign_posn;
     char  n_sign_posn;
-    /* ISO-C99 */
     char  int_p_cs_precedes;
     char  int_p_sep_by_space;
     char  int_n_cs_precedes;
@@ -79,13 +93,17 @@
     char  int_p_sign_posn;
     char  int_n_sign_posn;
 };
-#else
-// Keep old declaration for ILP32 for compatibility
-struct lconv { };
-#endif
 
 struct lconv* localeconv(void);
 
+locale_t duplocale(locale_t);
+void freelocale(locale_t);
+locale_t newlocale(int, const char*, locale_t);
+char* setlocale(int, const char*);
+locale_t uselocale(locale_t);
+
+#define LC_GLOBAL_LOCALE ((locale_t) -1L)
+
 __END_DECLS
 
 #endif /* _LOCALE_H_ */
diff --git a/libc/include/netdb.h b/libc/include/netdb.h
index 62a7a3c..ead5954 100644
--- a/libc/include/netdb.h
+++ b/libc/include/netdb.h
@@ -207,13 +207,11 @@
 void endservent(void);
 void freehostent(struct hostent *);
 struct hostent	*gethostbyaddr(const void *, socklen_t, int);
-struct hostent	*android_gethostbyaddrforiface(const void *, socklen_t, int, const char*, int);
 int gethostbyaddr_r(const void *, int, int, struct hostent *, char *, size_t, struct hostent **, int *);
 struct hostent	*gethostbyname(const char *);
 int gethostbyname_r(const char *, struct hostent *, char *, size_t, struct hostent **, int *);
 struct hostent	*gethostbyname2(const char *, int);
 int gethostbyname2_r(const char *, int, struct hostent *, char *, size_t, struct hostent **, int *);
-struct hostent	*android_gethostbynameforiface(const char *, int, const char *, int);
 struct hostent	*gethostent(void);
 int gethostent_r(struct hostent *, char *, size_t, struct hostent **, int *);
 struct hostent	*getipnodebyaddr(const void *, size_t, int, int *);
@@ -241,9 +239,7 @@
 void setnetent(int);
 void setprotoent(int);
 int getaddrinfo(const char *, const char *, const struct addrinfo *, struct addrinfo **);
-int android_getaddrinfoforiface(const char *, const char *, const struct addrinfo *, const char *, int, struct addrinfo **);
 int getnameinfo(const struct sockaddr *, socklen_t, char *, size_t, char *, size_t, int);
-int android_getnameinfoforiface(const struct sockaddr *, socklen_t, char *, size_t, char *, size_t, int, const char *, int);
 void freeaddrinfo(struct addrinfo *);
 const char	*gai_strerror(int);
 void setnetgrent(const char *);
diff --git a/libc/include/stdlib.h b/libc/include/stdlib.h
index 9b7e6d1..2c797c5 100644
--- a/libc/include/stdlib.h
+++ b/libc/include/stdlib.h
@@ -41,8 +41,9 @@
 #define EXIT_FAILURE 1
 #define EXIT_SUCCESS 0
 
-extern __noreturn void exit(int);
 extern __noreturn void abort(void);
+extern __noreturn void exit(int);
+extern __noreturn void _Exit(int);
 extern int atexit(void (*)(void));
 
 extern char *getenv(const char *);
@@ -151,7 +152,6 @@
 extern const char* getprogname(void);
 extern void setprogname(const char*);
 
-#if 1 /* MISSING FROM BIONIC - ENABLED FOR STLPort and libstdc++-v3 */
 /* make STLPort happy */
 extern int      mblen(const char *, size_t);
 extern size_t   mbstowcs(wchar_t *, const char *, size_t);
@@ -160,7 +160,6 @@
 /* Likewise, make libstdc++-v3 happy.  */
 extern int	wctomb(char *, wchar_t);
 extern size_t	wcstombs(char *, const wchar_t *, size_t);
-#endif /* MISSING */
 
 #define MB_CUR_MAX 1
 
diff --git a/libc/include/string.h b/libc/include/string.h
index ec998ed..c9ae03b 100644
--- a/libc/include/string.h
+++ b/libc/include/string.h
@@ -53,6 +53,7 @@
 extern size_t strlen(const char *) __purefunc;
 extern size_t __strlen_chk(const char *, size_t);
 extern int    strcmp(const char *, const char *) __purefunc;
+extern char*  stpcpy(char* __restrict, const char* __restrict);
 extern char*  strcpy(char* __restrict, const char* __restrict);
 extern char*  strcat(char* __restrict, const char* __restrict);
 
@@ -72,6 +73,7 @@
 extern char*  strncat(char* __restrict, const char* __restrict, size_t);
 extern char*  strndup(const char *, size_t);
 extern int    strncmp(const char *, const char *, size_t) __purefunc;
+extern char*  stpncpy(char* __restrict, const char* __restrict, size_t);
 extern char*  strncpy(char* __restrict, const char* __restrict, size_t);
 
 extern size_t strlcat(char* __restrict, const char* __restrict, size_t);
@@ -89,8 +91,8 @@
 
 #if defined(__BIONIC_FORTIFY)
 
-__errordecl(__memcpy_dest_size_error, "memcpy called with size bigger than destination");
-__errordecl(__memcpy_src_size_error, "memcpy called with size bigger than source");
+__errordecl(__memcpy_dest_size_error, "memcpy: prevented write past end of buffer");
+__errordecl(__memcpy_src_size_error, "memcpy: prevented read past end of buffer");
 
 __BIONIC_FORTIFY_INLINE
 void* memcpy(void* __restrict dest, const void* __restrict src, size_t copy_amount) {
@@ -116,11 +118,43 @@
 }
 
 __BIONIC_FORTIFY_INLINE
+char* stpcpy(char* __restrict dest, const char* __restrict src) {
+    return __builtin___stpcpy_chk(dest, src, __bos(dest));
+}
+
+__BIONIC_FORTIFY_INLINE
 char* strcpy(char* __restrict dest, const char* __restrict src) {
     return __builtin___strcpy_chk(dest, src, __bos(dest));
 }
 
-__errordecl(__strncpy_error, "strncpy called with size bigger than buffer");
+__errordecl(__stpncpy_error, "stpncpy: prevented write past end of buffer");
+extern char* __stpncpy_chk2(char* __restrict, const char* __restrict, size_t, size_t, size_t);
+
+__BIONIC_FORTIFY_INLINE
+char* stpncpy(char* __restrict dest, const char* __restrict src, size_t n) {
+    size_t bos_dest = __bos(dest);
+    size_t bos_src = __bos(src);
+    if (__builtin_constant_p(n) && (n > bos_dest)) {
+        __stpncpy_error();
+    }
+
+    if (bos_src == __BIONIC_FORTIFY_UNKNOWN_SIZE) {
+        return __builtin___stpncpy_chk(dest, src, n, bos_dest);
+    }
+
+    if (__builtin_constant_p(n) && (n <= bos_src)) {
+        return __builtin___stpncpy_chk(dest, src, n, bos_dest);
+    }
+
+    size_t slen = __builtin_strlen(src);
+    if (__builtin_constant_p(slen)) {
+        return __builtin___stpncpy_chk(dest, src, n, bos_dest);
+    }
+
+    return __stpncpy_chk2(dest, src, n, bos_dest, bos_src);
+}
+
+__errordecl(__strncpy_error, "strncpy: prevented write past end of buffer");
 extern char* __strncpy_chk2(char* __restrict, const char* __restrict, size_t, size_t, size_t);
 
 __BIONIC_FORTIFY_INLINE
@@ -164,7 +198,7 @@
 
 extern size_t __strlcpy_real(char* __restrict, const char* __restrict, size_t)
     __asm__(__USER_LABEL_PREFIX__ "strlcpy");
-__errordecl(__strlcpy_error, "strlcpy called with size bigger than buffer");
+__errordecl(__strlcpy_error, "strlcpy: prevented write past end of buffer");
 extern size_t __strlcpy_chk(char *, const char *, size_t, size_t);
 
 __BIONIC_FORTIFY_INLINE
@@ -195,7 +229,7 @@
 
 extern size_t __strlcat_real(char* __restrict, const char* __restrict, size_t)
     __asm__(__USER_LABEL_PREFIX__ "strlcat");
-__errordecl(__strlcat_error, "strlcat called with size bigger than buffer");
+__errordecl(__strlcat_error, "strlcat: prevented write past end of buffer");
 extern size_t __strlcat_chk(char* __restrict, const char* __restrict, size_t, size_t);
 
 
diff --git a/libc/include/sys/cdefs.h b/libc/include/sys/cdefs.h
index 9fa62df..685de32 100644
--- a/libc/include/sys/cdefs.h
+++ b/libc/include/sys/cdefs.h
@@ -528,6 +528,13 @@
 #define  __BIONIC__   1
 #include <android/api-level.h>
 
+/* glibc compatibility. */
+#if __LP64__
+#define __WORDSIZE 64
+#else
+#define __WORDSIZE 32
+#endif
+
 /*
  * When _FORTIFY_SOURCE is defined, automatic bounds checking is
  * added to commonly used libc functions. If a buffer overrun is
diff --git a/libc/include/sys/localedef.h b/libc/include/sys/localedef.h
deleted file mode 100644
index b6b5eb1..0000000
--- a/libc/include/sys/localedef.h
+++ /dev/null
@@ -1,101 +0,0 @@
-/*	$OpenBSD: localedef.h,v 1.3 1996/04/21 22:31:47 deraadt Exp $	*/
-/*	$NetBSD: localedef.h,v 1.4 1996/04/09 20:55:31 cgd Exp $	*/
-
-/*
- * Copyright (c) 1994 Winning Strategies, Inc.
- * 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. All advertising materials mentioning features or use of this software
- *    must display the following acknowledgement:
- *      This product includes software developed by Winning Strategies, Inc.
- * 4. The name of the author may not be used to endorse or promote products
- *    derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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_LOCALEDEF_H_
-#define _SYS_LOCALEDEF_H_
-
-#include <sys/param.h>
-#include <sys/types.h>
-
-typedef struct
-{
-	char *yesexpr;
-	char *noexpr;
-	char *yesstr;
-	char *nostr;
-} _MessagesLocale;
-
-extern const _MessagesLocale *_CurrentMessagesLocale;
-extern const _MessagesLocale  _DefaultMessagesLocale;
-
-
-typedef struct
-{
-	char *int_curr_symbol;
-	char *currency_symbol;
-	char *mon_decimal_point;
-	char *mon_thousands_sep;
-	char *mon_grouping;
-	char *positive_sign;
-	char *negative_sign;
-	char int_frac_digits;
-	char frac_digits;
-	char p_cs_precedes;
-	char p_sep_by_space;
-	char n_cs_precedes;
-	char n_sep_by_space;
-	char p_sign_posn;
-	char n_sign_posn;
-} _MonetaryLocale;
-
-extern const _MonetaryLocale *_CurrentMonetaryLocale;
-extern const _MonetaryLocale  _DefaultMonetaryLocale;
-
-
-typedef struct
-{
-	const char *decimal_point;
-	const char *thousands_sep;
-	const char *grouping;
-} _NumericLocale;
-
-extern const _NumericLocale *_CurrentNumericLocale;
-extern const _NumericLocale  _DefaultNumericLocale;
-
-
-typedef struct {
-	const char *abday[7];
-	const char *day[7];
-	const char *abmon[12];
-	const char *mon[12];
-	const char *am_pm[2];
-	const char *d_t_fmt;
-	const char *d_fmt;
-	const char *t_fmt;
-	const char *t_fmt_ampm;
-} _TimeLocale;
-
-extern const _TimeLocale *_CurrentTimeLocale;
-extern const _TimeLocale  _DefaultTimeLocale;
-
-#endif /* !_SYS_LOCALEDEF_H_ */
diff --git a/libc/include/sys/ucontext.h b/libc/include/sys/ucontext.h
index 94b7a68..f29381b 100644
--- a/libc/include/sys/ucontext.h
+++ b/libc/include/sys/ucontext.h
@@ -86,6 +86,7 @@
   struct ucontext *uc_link;
   stack_t uc_stack;
   sigset_t uc_sigmask;
+  char __padding[128 - sizeof(sigset_t)];
   mcontext_t uc_mcontext;
 } ucontext_t;
 
diff --git a/libc/include/time.h b/libc/include/time.h
index 3f2047c..0f86fd3 100644
--- a/libc/include/time.h
+++ b/libc/include/time.h
@@ -61,8 +61,6 @@
 extern time_t time(time_t*);
 extern int nanosleep(const struct timespec*, struct timespec*);
 
-extern char* strtotimeval(const char*, struct timeval*);
-
 extern char* asctime(const struct tm*);
 extern char* asctime_r(const struct tm*, char*);
 
diff --git a/libc/include/wchar.h b/libc/include/wchar.h
index 32cf127..89c6fb6 100644
--- a/libc/include/wchar.h
+++ b/libc/include/wchar.h
@@ -36,13 +36,6 @@
 #include <time.h>
 #include <malloc.h>
 
-/* IMPORTANT: Any code that relies on wide character support is essentially
- *            non-portable and/or broken. the only reason this header exist
- *            is because I'm really a nice guy. However, I'm not nice enough
- *            to provide you with a real implementation. instead wchar_t == char
- *            and all wc functions are stubs to their "normal" equivalent...
- */
-
 __BEGIN_DECLS
 
 typedef __WINT_TYPE__           wint_t;
@@ -150,12 +143,11 @@
 extern size_t wcslcat(wchar_t*, const wchar_t*, size_t);
 extern size_t wcslcpy(wchar_t*, const wchar_t*, size_t);
 
-/* No really supported.  These are just for making libstdc++-v3 happy.  */
 typedef void *wctrans_t;
-extern wint_t		 towctrans(wint_t, wctrans_t);
-extern wctrans_t	 wctrans (const char *);
+extern wint_t towctrans(wint_t, wctrans_t);
+extern wctrans_t wctrans(const char*);
 
-#if _XOPEN_SOURCE >= 700 || _POSIX_C_SOURCE >= 200809L
+#if __POSIX_VISIBLE >= 200809
 wchar_t* wcsdup(const wchar_t*);
 size_t wcsnlen(const wchar_t*, size_t);
 #endif
diff --git a/libc/bionic/setlocale.cpp b/libc/include/xlocale.h
similarity index 83%
rename from libc/bionic/setlocale.cpp
rename to libc/include/xlocale.h
index e8fdc9e..f7eb8f4 100644
--- a/libc/bionic/setlocale.cpp
+++ b/libc/include/xlocale.h
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2008 The Android Open Source Project
+ * Copyright (C) 2014 The Android Open Source Project
  * All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
@@ -26,10 +26,11 @@
  * SUCH DAMAGE.
  */
 
-#include <locale.h>
-#include <stdlib.h>
+#ifndef _XLOCALE_H_
+#define _XLOCALE_H_
 
-// setlocale(3) always fails on bionic.
-char* setlocale(int /*category*/, char const* /*locale*/) {
-    return NULL;
-}
+/* If we just use void* here, GCC exposes that in error messages. */
+struct __locale_t;
+typedef struct __locale_t* locale_t;
+
+#endif /* _XLOCALE_H_ */
diff --git a/libc/kernel/tools/defaults.py b/libc/kernel/tools/defaults.py
index 09556c9..b4d823e 100644
--- a/libc/kernel/tools/defaults.py
+++ b/libc/kernel/tools/defaults.py
@@ -6,20 +6,16 @@
 from utils import *
 
 # the list of supported architectures
-#
 kernel_archs = [ 'arm', 'arm64', 'mips', 'x86' ]
 
 # the list of include directories that belong to the kernel
 # tree. used when looking for sources...
-#
 kernel_dirs = [ "linux", "asm", "asm-generic", "mtd" ]
 
 # path to the directory containing the original kernel headers
-#
 kernel_original_path = os.path.normpath( find_program_dir() + '/../../../../external/kernel-headers/original' )
 
 # path to the default location of the cleaned-up headers
-#
 kernel_cleaned_path = os.path.normpath( find_program_dir() + '/..' )
 
 # a special value that is used to indicate that a given macro is known to be
@@ -33,6 +29,7 @@
     "__KERNEL_STRICT_NAMES":"1",
     "__CHECKER__": kCppUndefinedMacro,
     "__CHECK_ENDIAN__": kCppUndefinedMacro,
+    "CONFIG_64BIT": "__LP64__",
     "CONFIG_X86_32": "__i386__",
     "__EXPORTED_HEADERS__": "1",
     }
@@ -71,6 +68,7 @@
 # this is the set of known static inline functions that we want to keep
 # in the final ARM headers. this is only used to keep optimized byteswapping
 # static functions and stuff like that.
+# TODO: this isn't working!
 kernel_known_arm_statics = set(
         [ "___arch__swab32",    # asm-arm/byteorder.h
         ]
@@ -93,11 +91,9 @@
     )
 
 kernel_known_generic_statics = set(
-        [ "__invalid_size_argument_for_IOC",  # asm-generic/ioctl.h
-          "__cmsg_nxthdr",                    # linux/socket.h
-          "cmsg_nxthdr",                      # linux/socket.h
-          "ipt_get_target",
-          "ip6t_get_target",
+        [
+          "ipt_get_target",  # uapi/linux/netfilter_ipv4/ip_tables.h
+          "ip6t_get_target", # uapi/linux/netfilter_ipv6/ip6_tables.h
         ]
     )
 
diff --git a/libc/kernel/uapi/asm-generic/fcntl.h b/libc/kernel/uapi/asm-generic/fcntl.h
index f7b24a5..207734f 100644
--- a/libc/kernel/uapi/asm-generic/fcntl.h
+++ b/libc/kernel/uapi/asm-generic/fcntl.h
@@ -112,84 +112,89 @@
 #define F_GETSIG 11
 /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
 #endif
+#ifndef __LP64__
 #ifndef F_GETLK64
 #define F_GETLK64 12
-#define F_SETLK64 13
 /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
+#define F_SETLK64 13
 #define F_SETLKW64 14
 #endif
+#endif
+/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
 #ifndef F_SETOWN_EX
 #define F_SETOWN_EX 15
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
 #define F_GETOWN_EX 16
 #endif
+/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
 #ifndef F_GETOWNER_UIDS
 #define F_GETOWNER_UIDS 17
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
 #endif
 #define F_OWNER_TID 0
+/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
 #define F_OWNER_PID 1
 #define F_OWNER_PGRP 2
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
 struct f_owner_ex {
  int type;
+/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
  __kernel_pid_t pid;
 };
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
 #define FD_CLOEXEC 1
 #ifndef F_RDLCK
+/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
 #define F_RDLCK 0
 #define F_WRLCK 1
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
 #define F_UNLCK 2
 #endif
+/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
 #ifndef F_EXLCK
 #define F_EXLCK 4
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
 #define F_SHLCK 8
 #endif
+/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
 #define LOCK_SH 1
 #define LOCK_EX 2
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
 #define LOCK_NB 4
 #define LOCK_UN 8
+/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
 #define LOCK_MAND 32
 #define LOCK_READ 64
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
 #define LOCK_WRITE 128
 #define LOCK_RW 192
+/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
 #define F_LINUX_SPECIFIC_BASE 1024
 #ifndef HAVE_ARCH_STRUCT_FLOCK
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
 #ifndef __ARCH_FLOCK_PAD
 #define __ARCH_FLOCK_PAD
+/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
 #endif
 struct flock {
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
  short l_type;
  short l_whence;
+/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
  __kernel_off_t l_start;
  __kernel_off_t l_len;
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
  __kernel_pid_t l_pid;
  __ARCH_FLOCK_PAD
+/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
 };
 #endif
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
+#ifndef __LP64__
 #ifndef HAVE_ARCH_STRUCT_FLOCK64
+/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
 #ifndef __ARCH_FLOCK64_PAD
 #define __ARCH_FLOCK64_PAD
 #endif
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
 struct flock64 {
+/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
  short l_type;
  short l_whence;
  __kernel_loff_t l_start;
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
  __kernel_loff_t l_len;
+/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
  __kernel_pid_t l_pid;
  __ARCH_FLOCK64_PAD
 };
+#endif
 /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
 #endif
 #endif
diff --git a/libc/kernel/uapi/asm-mips/asm/siginfo.h b/libc/kernel/uapi/asm-mips/asm/siginfo.h
index 4a085f8..45b418a 100644
--- a/libc/kernel/uapi/asm-mips/asm/siginfo.h
+++ b/libc/kernel/uapi/asm-mips/asm/siginfo.h
@@ -26,74 +26,78 @@
 struct siginfo;
 #define __ARCH_SI_PREAMBLE_SIZE (3 * sizeof(int))
 /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
+#ifdef __LP64__
+#define __ARCH_SI_PREAMBLE_SIZE (4 * sizeof(int))
+#endif
 #include <asm-generic/siginfo.h>
+/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
 typedef struct siginfo {
  int si_signo;
  int si_code;
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
  int si_errno;
+/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
  int __pad0[SI_MAX_SIZE / sizeof(int) - SI_PAD_SIZE - 3];
  union {
  int _pad[SI_PAD_SIZE];
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
  struct {
+/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
  pid_t _pid;
  __ARCH_SI_UID_T _uid;
  } _kill;
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
  struct {
+/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
  timer_t _tid;
  int _overrun;
  char _pad[sizeof( __ARCH_SI_UID_T) - sizeof(int)];
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
  sigval_t _sigval;
+/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
  int _sys_private;
  } _timer;
  struct {
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
  pid_t _pid;
+/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
  __ARCH_SI_UID_T _uid;
  sigval_t _sigval;
  } _rt;
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
  struct {
+/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
  pid_t _pid;
  __ARCH_SI_UID_T _uid;
  int _status;
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
  clock_t _utime;
+/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
  clock_t _stime;
  } _sigchld;
  struct {
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
  pid_t _pid;
+/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
  clock_t _utime;
  int _status;
  clock_t _stime;
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
  } _irix_sigchld;
+/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
  struct {
  void __user *_addr;
 #ifdef __ARCH_SI_TRAPNO
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
  int _trapno;
+/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
 #endif
  short _addr_lsb;
  } _sigfault;
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
  struct {
+/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
  __ARCH_SI_BAND_T _band;
  int _fd;
  } _sigpoll;
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
  } _sifields;
+/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
 } siginfo_t;
 #undef SI_ASYNCIO
 #undef SI_TIMER
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
 #undef SI_MESGQ
+/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
 #define SI_ASYNCIO -2
 #define SI_TIMER __SI_CODE(__SI_TIMER, -3)
 #define SI_MESGQ __SI_CODE(__SI_MESGQ, -4)
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
 #endif
+/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
diff --git a/libc/private/libc_events.h b/libc/private/libc_events.h
index 5d20f4b..f2b973d 100644
--- a/libc/private/libc_events.h
+++ b/libc/private/libc_events.h
@@ -40,6 +40,8 @@
 #define BIONIC_EVENT_STRNCPY_BUFFER_OVERFLOW  80120
 #define BIONIC_EVENT_MEMSET_BUFFER_OVERFLOW   80125
 #define BIONIC_EVENT_STRCPY_BUFFER_OVERFLOW   80130
+#define BIONIC_EVENT_STPCPY_BUFFER_OVERFLOW   80135
+#define BIONIC_EVENT_STPNCPY_BUFFER_OVERFLOW  80140
 
 #define BIONIC_EVENT_RESOLVER_OLD_RESPONSE    80300
 #define BIONIC_EVENT_RESOLVER_WRONG_SERVER    80305
diff --git a/libc/stdio/vfprintf.c b/libc/stdio/vfprintf.c
index b101145..efc8fd0 100644
--- a/libc/stdio/vfprintf.c
+++ b/libc/stdio/vfprintf.c
@@ -51,7 +51,35 @@
 #include "local.h"
 #include "fvwrite.h"
 
-static void __find_arguments(const char *fmt0, va_list ap, va_list **argtable,
+union arg {
+	int			intarg;
+	unsigned int		uintarg;
+	long			longarg;
+	unsigned long		ulongarg;
+	long long		longlongarg;
+	unsigned long long	ulonglongarg;
+	ptrdiff_t		ptrdiffarg;
+	size_t			sizearg;
+	size_t			ssizearg;
+	intmax_t		intmaxarg;
+	uintmax_t		uintmaxarg;
+	void			*pvoidarg;
+	char			*pchararg;
+	signed char		*pschararg;
+	short			*pshortarg;
+	int			*pintarg;
+	long			*plongarg;
+	long long		*plonglongarg;
+	ptrdiff_t		*pptrdiffarg;
+	size_t			*pssizearg;
+	intmax_t		*pintmaxarg;
+#ifdef FLOATING_POINT
+	double			doublearg;
+	long double		longdoublearg;
+#endif
+};
+
+static int __find_arguments(const char *fmt0, va_list ap, union arg **argtable,
     size_t *argtablesiz);
 static int __grow_type_table(unsigned char **typetable, int *tablesize);
 
@@ -169,13 +197,13 @@
 int
 __vfprintf(FILE *fp, const char *fmt0, __va_list ap)
 {
-	char *fmt;	/* format string */
-	int ch;	/* character from fmt */
-	int n, m, n2;	/* handy integers (short term usage) */
-	char *cp;	/* handy char pointer (short term usage) */
-	char *cp_free = NULL;  /* BIONIC: copy of cp to be freed after usage */
-	struct __siov *iovp;/* for PRINT macro */
-	int flags;	/* flags as above */
+	char *fmt;		/* format string */
+	int ch;			/* character from fmt */
+	int n, m, n2;		/* handy integers (short term usage) */
+	char *cp;		/* handy char pointer (short term usage) */
+	char *cp_free = NULL;	/* BIONIC: copy of cp to be freed after usage */
+	struct __siov *iovp;	/* for PRINT macro */
+	int flags;		/* flags as above */
 	int ret;		/* return value accumulator */
 	int width;		/* width from format (%8d), or 0 */
 	int prec;		/* precision from format (%.3d), or -1 */
@@ -203,8 +231,8 @@
 	struct __siov iov[NIOV];/* ... and individual io vectors */
 	char buf[BUF];		/* space for %c, %[diouxX], %[eEfgG] */
 	char ox[2];		/* space for 0x hex-prefix */
-	va_list *argtable;	/* args, built due to positional arg */
-	va_list statargtable[STATIC_ARG_TBL_SIZE];
+	union arg *argtable;	/* args, built due to positional arg */
+	union arg statargtable[STATIC_ARG_TBL_SIZE];
 	size_t argtablesiz;
 	int nextarg;		/* 1-based argument index */
 	va_list orgap;		/* original argument pointer */
@@ -303,8 +331,8 @@
 * argument (and arguments must be gotten sequentially).
 */
 #define GETARG(type) \
-	(((argtable != NULL) ? (void)(ap = argtable[nextarg]) : (void)0), \
-	 nextarg++, va_arg(ap, type))
+	((argtable != NULL) ? *((type*)(&argtable[nextarg++])) : \
+		(nextarg++, va_arg(ap, type)))
 
 	_SET_ORIENTATION(fp, -1);
 	/* sorry, fprintf(read_only_file, "") returns EOF, not 0 */
@@ -548,15 +576,16 @@
 					size = expt;
 					if (prec || flags & ALT)
 						size += prec + 1;
-				} else	/* "0.X" */
+				} else { /* "0.X" */
 					size = prec + 2;
+				}
 			} else if (expt >= ndig) {	/* fixed g fmt */
 				size = expt;
 				if (flags & ALT)
 					++size;
-			} else
-				size = ndig + (expt > 0 ?
-					1 : 2 - expt);
+			} else {
+				size = ndig + (expt > 0 ?  1 : 2 - expt);
+			}
 
 			if (softsign)
 				sign = '-';
@@ -624,10 +653,12 @@
 					size = p - cp;
 					if (size > prec)
 						size = prec;
-				} else
+				} else {
 					size = prec;
-			} else
+				}
+			} else {
 				size = strlen(cp);
+			}
 			sign = '\0';
 			break;
 		case 'U':
@@ -793,11 +824,13 @@
 					PRINT(ox, 2);
 					if (_double) {
 						PRINT(cp, ndig-1);
-					} else	/* 0.[0..] */
+					} else {/* 0.[0..] */
 						/* __dtoa irregularity */
 						PAD(ndig - 1, zeroes);
-				} else	/* XeYYY */
+					}
+				} else { /* XeYYY */
 					PRINT(cp, 1);
+				}
 				PRINT(expstr, expsize);
 			}
 		}
@@ -874,15 +907,15 @@
  * used since we are attempting to make snprintf thread safe, and alloca is
  * problematic since we have nested functions..)
  */
-static void
-__find_arguments(const char *fmt0, va_list ap, va_list **argtable,
+static int
+__find_arguments(const char *fmt0, va_list ap, union arg **argtable,
     size_t *argtablesiz)
 {
-	char *fmt;	/* format string */
-	int ch;	/* character from fmt */
-	int n, n2;	/* handy integer (short term usage) */
-	char *cp;	/* handy char pointer (short term usage) */
-	int flags;	/* flags as above */
+	char *fmt;		/* format string */
+	int ch;			/* character from fmt */
+	int n, n2;		/* handy integer (short term usage) */
+	char *cp;		/* handy char pointer (short term usage) */
+	int flags;		/* flags as above */
 	unsigned char *typetable; /* table of types */
 	unsigned char stattypetable[STATIC_ARG_TBL_SIZE];
 	int tablesize;		/* current size of type table */
@@ -1105,86 +1138,89 @@
 	 * Build the argument table.
 	 */
 	if (tablemax >= STATIC_ARG_TBL_SIZE) {
-		*argtablesiz = sizeof (va_list) * (tablemax + 1);
-		*argtable = (va_list *)mmap(NULL, *argtablesiz,
+		*argtablesiz = sizeof(union arg) * (tablemax + 1);
+		*argtable = mmap(NULL, *argtablesiz,
 		    PROT_WRITE|PROT_READ, MAP_ANON|MAP_PRIVATE, -1, 0);
+		if (*argtable == MAP_FAILED)
+			return (-1);
 	}
 
 #if 0
 	/* XXX is this required? */
-	(*argtable) [0] = NULL;
+	(*argtable)[0].intarg = 0;
 #endif
 	for (n = 1; n <= tablemax; n++) {
-		va_copy((*argtable)[n], ap);
 		switch (typetable[n]) {
 		case T_UNUSED:
-			(void) va_arg(ap, int);
+			(*argtable)[n].intarg = va_arg(ap, int);
 			break;
 		case T_SHORT:
-			(void) va_arg(ap, int);
+			(*argtable)[n].intarg = va_arg(ap, int);
 			break;
 		case T_U_SHORT:
-			(void) va_arg(ap, int);
+			(*argtable)[n].intarg = va_arg(ap, int);
 			break;
 		case TP_SHORT:
-			(void) va_arg(ap, short *);
+			(*argtable)[n].pshortarg = va_arg(ap, short *);
 			break;
 		case T_INT:
-			(void) va_arg(ap, int);
+			(*argtable)[n].intarg = va_arg(ap, int);
 			break;
 		case T_U_INT:
-			(void) va_arg(ap, unsigned int);
+			(*argtable)[n].uintarg = va_arg(ap, unsigned int);
 			break;
 		case TP_INT:
-			(void) va_arg(ap, int *);
+			(*argtable)[n].pintarg = va_arg(ap, int *);
 			break;
 		case T_LONG:
-			(void) va_arg(ap, long);
+			(*argtable)[n].longarg = va_arg(ap, long);
 			break;
 		case T_U_LONG:
-			(void) va_arg(ap, unsigned long);
+			(*argtable)[n].ulongarg = va_arg(ap, unsigned long);
 			break;
 		case TP_LONG:
-			(void) va_arg(ap, long *);
+			(*argtable)[n].plongarg = va_arg(ap, long *);
 			break;
 		case T_LLONG:
-			(void) va_arg(ap, long long);
+			(*argtable)[n].longlongarg = va_arg(ap, long long);
 			break;
 		case T_U_LLONG:
-			(void) va_arg(ap, unsigned long long);
+			(*argtable)[n].ulonglongarg = va_arg(ap, unsigned long long);
 			break;
 		case TP_LLONG:
-			(void) va_arg(ap, long long *);
+			(*argtable)[n].plonglongarg = va_arg(ap, long long *);
 			break;
+#ifdef FLOATING_POINT
 		case T_DOUBLE:
-			(void) va_arg(ap, double);
+			(*argtable)[n].doublearg = va_arg(ap, double);
 			break;
 		case T_LONG_DOUBLE:
-			(void) va_arg(ap, long double);
+			(*argtable)[n].longdoublearg = va_arg(ap, long double);
 			break;
+#endif
 		case TP_CHAR:
-			(void) va_arg(ap, char *);
+			(*argtable)[n].pchararg = va_arg(ap, char *);
 			break;
 		case TP_VOID:
-			(void) va_arg(ap, void *);
+			(*argtable)[n].pvoidarg = va_arg(ap, void *);
 			break;
 		case T_PTRINT:
-			(void) va_arg(ap, ptrdiff_t);
+			(*argtable)[n].ptrdiffarg = va_arg(ap, ptrdiff_t);
 			break;
 		case TP_PTRINT:
-			(void) va_arg(ap, ptrdiff_t *);
+			(*argtable)[n].pptrdiffarg = va_arg(ap, ptrdiff_t *);
 			break;
 		case T_SIZEINT:
-			(void) va_arg(ap, size_t);
+			(*argtable)[n].sizearg = va_arg(ap, size_t);
 			break;
 		case T_SSIZEINT:
-			(void) va_arg(ap, ssize_t);
+			(*argtable)[n].ssizearg = va_arg(ap, ssize_t);
 			break;
 		case TP_SSIZEINT:
-			(void) va_arg(ap, ssize_t *);
+			(*argtable)[n].pssizearg = va_arg(ap, ssize_t *);
 			break;
 		case TP_MAXINT:
-			(void) va_arg(ap, intmax_t *);
+			(*argtable)[n].intmaxarg = va_arg(ap, intmax_t);
 			break;
 		}
 	}
@@ -1193,6 +1229,7 @@
 		munmap(typetable, *argtablesiz);
 		typetable = NULL;
 	}
+	return (0);
 }
 
 /*
@@ -1205,24 +1242,24 @@
 	int newsize = *tablesize * 2;
 
 	if (*tablesize == STATIC_ARG_TBL_SIZE) {
-		*typetable = (unsigned char *)mmap(NULL,
-		    sizeof (unsigned char) * newsize, PROT_WRITE|PROT_READ,
+		*typetable = mmap(NULL, newsize, PROT_WRITE|PROT_READ,
 		    MAP_ANON|MAP_PRIVATE, -1, 0);
-		/* XXX unchecked */
+		if (*typetable == MAP_FAILED)
+			return (-1);
 		memcpy( *typetable, oldtable, *tablesize);
 	} else {
-		unsigned char *new = (unsigned char *)mmap(NULL,
-		    sizeof (unsigned char) * newsize, PROT_WRITE|PROT_READ,
+		unsigned char *new = mmap(NULL, newsize, PROT_WRITE|PROT_READ,
 		    MAP_ANON|MAP_PRIVATE, -1, 0);
+		if (new == MAP_FAILED)
+			return (-1);
 		memmove(new, *typetable, *tablesize);
 		munmap(*typetable, *tablesize);
 		*typetable = new;
-		/* XXX unchecked */
 	}
 	memset(*typetable + *tablesize, T_UNUSED, (newsize - *tablesize));
 
 	*tablesize = newsize;
-	return(0);
+	return (0);
 }
 
 
@@ -1256,7 +1293,7 @@
 	} else
 		*sign = '\000';
 	digits = __dtoa(value, mode, ndigits, decpt, &dsgn, &rve);
-	if ((ch != 'g' && ch != 'G') || flags & ALT) {	/* Print trailing zeros */
+	if ((ch != 'g' && ch != 'G') || flags & ALT) {/* Print trailing zeros */
 		bp = digits + ndigits;
 		if (ch == 'f') {
 			if (*digits == '0' && value)
@@ -1283,8 +1320,7 @@
 	if (exp < 0) {
 		exp = -exp;
 		*p++ = '-';
-	}
-	else
+	} else
 		*p++ = '+';
 	t = expbuf + MAXEXP;
 	if (exp > 9) {
@@ -1292,9 +1328,9 @@
 			*--t = to_char(exp % 10);
 		} while ((exp /= 10) > 9);
 		*--t = to_char(exp);
-		for (; t < expbuf + MAXEXP; *p++ = *t++);
-	}
-	else {
+		for (; t < expbuf + MAXEXP; *p++ = *t++)
+			/* nothing */;
+	} else {
 		*p++ = '0';
 		*p++ = to_char(exp);
 	}
diff --git a/libc/stdlib/strtod.c b/libc/stdlib/strtod.c
index b39c90e..95d0e19 100644
--- a/libc/stdlib/strtod.c
+++ b/libc/stdlib/strtod.c
@@ -1332,15 +1332,11 @@
 	Bigint *bb1, *bd0;
 	Bigint *bb = NULL, *bd = NULL, *bs = NULL, *delta = NULL;/* pacify gcc */
 
-#if defined(__LP64__) /* BEGIN android-changed: no localeconv for ILP32. */
 #ifndef KR_headers
 	CONST char decimal_point = localeconv()->decimal_point[0];
 #else
 	CONST char decimal_point = '.';
 #endif
-#else
-	CONST char decimal_point = '.';
-#endif /* END android-changed */
 
 	sign = nz0 = nz = 0;
 	value(rv) = 0.;
diff --git a/libc/upstream-openbsd/lib/libc/locale/_def_messages.c b/libc/upstream-openbsd/lib/libc/locale/_def_messages.c
deleted file mode 100644
index 1ed653a..0000000
--- a/libc/upstream-openbsd/lib/libc/locale/_def_messages.c
+++ /dev/null
@@ -1,18 +0,0 @@
-/*	$OpenBSD: _def_messages.c,v 1.5 2005/08/08 08:05:35 espie Exp $ */
-/*
- * Written by J.T. Conklin <jtc@netbsd.org>.
- * Public domain.
- */
-
-#include <sys/localedef.h>
-#include <locale.h>
-
-const _MessagesLocale _DefaultMessagesLocale =
-{
-	"^[Yy]",
-	"^[Nn]",
-	"yes",
-	"no"
-} ;
-
-const _MessagesLocale *_CurrentMessagesLocale = &_DefaultMessagesLocale;
diff --git a/libc/upstream-openbsd/lib/libc/locale/_def_monetary.c b/libc/upstream-openbsd/lib/libc/locale/_def_monetary.c
deleted file mode 100644
index aa92c75..0000000
--- a/libc/upstream-openbsd/lib/libc/locale/_def_monetary.c
+++ /dev/null
@@ -1,30 +0,0 @@
-/*	$OpenBSD: _def_monetary.c,v 1.4 2005/08/08 08:05:35 espie Exp $ */
-/*
- * Written by J.T. Conklin <jtc@netbsd.org>.
- * Public domain.
- */
-
-#include <sys/localedef.h>
-#include <limits.h>
-#include <locale.h>
-
-const _MonetaryLocale _DefaultMonetaryLocale =
-{
-	"",
-	"",
-	"",
-	"",
-	"",
-	"",
-	"",
-	CHAR_MAX,
-	CHAR_MAX,
-	CHAR_MAX,
-	CHAR_MAX,
-	CHAR_MAX,
-	CHAR_MAX,
-	CHAR_MAX,
-	CHAR_MAX
-};
-
-const _MonetaryLocale *_CurrentMonetaryLocale = &_DefaultMonetaryLocale;
diff --git a/libc/upstream-openbsd/lib/libc/locale/_def_numeric.c b/libc/upstream-openbsd/lib/libc/locale/_def_numeric.c
deleted file mode 100644
index 6511254..0000000
--- a/libc/upstream-openbsd/lib/libc/locale/_def_numeric.c
+++ /dev/null
@@ -1,17 +0,0 @@
-/*	$OpenBSD: _def_numeric.c,v 1.4 2005/08/08 08:05:35 espie Exp $ */
-/*
- * Written by J.T. Conklin <jtc@netbsd.org>.
- * Public domain.
- */
-
-#include <sys/localedef.h>
-#include <locale.h>
-
-const _NumericLocale _DefaultNumericLocale =
-{
-	".",
-	"",
-	""
-};
-
-const _NumericLocale *_CurrentNumericLocale = &_DefaultNumericLocale;
diff --git a/libc/upstream-openbsd/lib/libc/locale/_def_time.c b/libc/upstream-openbsd/lib/libc/locale/_def_time.c
deleted file mode 100644
index 75179a6..0000000
--- a/libc/upstream-openbsd/lib/libc/locale/_def_time.c
+++ /dev/null
@@ -1,36 +0,0 @@
-/*	$OpenBSD: _def_time.c,v 1.5 2011/10/09 06:39:53 ajacoutot Exp $ */
-/*
- * Written by J.T. Conklin <jtc@netbsd.org>.
- * Public domain.
- */
-
-#include <sys/localedef.h>
-#include <locale.h>
-
-const _TimeLocale _DefaultTimeLocale =
-{
-	{
-		"Sun","Mon","Tue","Wed","Thu","Fri","Sat",
-	},
-	{
-		"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday",
-		"Friday", "Saturday"
-	},
-	{
-		"Jan", "Feb", "Mar", "Apr", "May", "Jun",
-		"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
-	},
-	{
-		"January", "February", "March", "April", "May", "June", "July",
-		"August", "September", "October", "November", "December"
-	},
-	{
-		"AM", "PM"
-	},
-	"%a %b %e %H:%M:%S %Y",
-	"%m/%d/%y",
-	"%H:%M:%S",
-	"%I:%M:%S %p"
-};
-
-const _TimeLocale *_CurrentTimeLocale = &_DefaultTimeLocale;
diff --git a/libc/upstream-openbsd/lib/libc/locale/localeconv.c b/libc/upstream-openbsd/lib/libc/locale/localeconv.c
deleted file mode 100644
index 989eb4b..0000000
--- a/libc/upstream-openbsd/lib/libc/locale/localeconv.c
+++ /dev/null
@@ -1,59 +0,0 @@
-/*	$OpenBSD: localeconv.c,v 1.5 2005/08/08 08:05:35 espie Exp $ */
-/*
- * Written by J.T. Conklin <jtc@netbsd.org>.
- * Public domain.
- */
-
-#include <sys/localedef.h>
-#include <locale.h>
-
-/*
- * The localeconv() function constructs a struct lconv from the current
- * monetary and numeric locales.
- *
- * Because localeconv() may be called many times (especially by library
- * routines like printf() & strtod()), the approprate members of the
- * lconv structure are computed only when the monetary or numeric
- * locale has been changed.
- */
-int __mlocale_changed = 1;
-int __nlocale_changed = 1;
-
-/*
- * Return the current locale conversion.
- */
-struct lconv *
-localeconv(void)
-{
-    static struct lconv ret;
-
-    if (__mlocale_changed) {
-	/* LC_MONETARY */
-	ret.int_curr_symbol	= _CurrentMonetaryLocale->int_curr_symbol;
-	ret.currency_symbol	= _CurrentMonetaryLocale->currency_symbol;
-	ret.mon_decimal_point	= _CurrentMonetaryLocale->mon_decimal_point;
-	ret.mon_thousands_sep	= _CurrentMonetaryLocale->mon_thousands_sep;
-	ret.mon_grouping	= _CurrentMonetaryLocale->mon_grouping;
-	ret.positive_sign	= _CurrentMonetaryLocale->positive_sign;
-	ret.negative_sign	= _CurrentMonetaryLocale->negative_sign;
-	ret.int_frac_digits	= _CurrentMonetaryLocale->int_frac_digits;
-	ret.frac_digits		= _CurrentMonetaryLocale->frac_digits;
-	ret.p_cs_precedes	= _CurrentMonetaryLocale->p_cs_precedes;
-	ret.p_sep_by_space	= _CurrentMonetaryLocale->p_sep_by_space;
-	ret.n_cs_precedes	= _CurrentMonetaryLocale->n_cs_precedes;
-	ret.n_sep_by_space	= _CurrentMonetaryLocale->n_sep_by_space;
-	ret.p_sign_posn		= _CurrentMonetaryLocale->p_sign_posn;
-	ret.n_sign_posn		= _CurrentMonetaryLocale->n_sign_posn;
-	__mlocale_changed = 0;
-    }
-
-    if (__nlocale_changed) {
-	/* LC_NUMERIC */
-	ret.decimal_point	= (char *) _CurrentNumericLocale->decimal_point;
-	ret.thousands_sep	= (char *) _CurrentNumericLocale->thousands_sep;
-	ret.grouping		= (char *) _CurrentNumericLocale->grouping;
-	__nlocale_changed = 0;
-    }
-
-    return (&ret);
-}
diff --git a/libc/upstream-openbsd/lib/libc/string/stpcpy.c b/libc/upstream-openbsd/lib/libc/string/stpcpy.c
new file mode 100644
index 0000000..d3d61e0
--- /dev/null
+++ b/libc/upstream-openbsd/lib/libc/string/stpcpy.c
@@ -0,0 +1,44 @@
+/*	$OpenBSD: stpcpy.c,v 1.1 2012/01/17 02:48:01 guenther Exp $	*/
+
+/*
+ * Copyright (c) 1988 Regents of the University of California.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of the University nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <string.h>
+
+#if defined(APIWARN)
+__warn_references(stpcpy,
+    "warning: stpcpy() is dangerous GNU crap; don't use it");
+#endif
+
+char *
+stpcpy(char *to, const char *from)
+{
+	for (; (*to = *from) != '\0'; ++from, ++to);
+	return(to);
+}
diff --git a/libc/upstream-openbsd/lib/libc/string/stpncpy.c b/libc/upstream-openbsd/lib/libc/string/stpncpy.c
new file mode 100644
index 0000000..c7c2a57
--- /dev/null
+++ b/libc/upstream-openbsd/lib/libc/string/stpncpy.c
@@ -0,0 +1,56 @@
+/*	$OpenBSD: stpncpy.c,v 1.2 2012/07/11 10:44:59 naddy Exp $	*/
+
+/*-
+ * Copyright (c) 1990 The Regents of the University of California.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Chris Torek.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of the University nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <string.h>
+
+char *
+stpncpy(char *dst, const char *src, size_t n)
+{
+	if (n != 0) {
+		char *d = dst;
+		const char *s = src;
+
+		dst = &dst[n];
+		do {
+			if ((*d++ = *s++) == 0) {
+				dst = d - 1;
+				/* NUL pad the remaining n-1 bytes */
+				while (--n != 0)
+					*d++ = 0;
+				break;
+			}
+		} while (--n != 0);
+	}
+	return (dst);
+}
diff --git a/tests/Android.mk b/tests/Android.mk
index 7482ebc..e8ee687 100644
--- a/tests/Android.mk
+++ b/tests/Android.mk
@@ -82,6 +82,7 @@
     system_properties_test.cpp \
     time_test.cpp \
     unistd_test.cpp \
+    wchar_test.cpp \
 
 libBionicStandardTests_cflags := \
     $(test_cflags) \
diff --git a/tests/fcntl_test.cpp b/tests/fcntl_test.cpp
index 4aac468..725ac4a 100644
--- a/tests/fcntl_test.cpp
+++ b/tests/fcntl_test.cpp
@@ -116,3 +116,19 @@
   ASSERT_EQ(0, fstat(tf.fd, &sb));
   ASSERT_EQ(4, sb.st_size);
 }
+
+TEST(fcntl, f_getlk64) {
+  int fd = open64("/proc/version", O_RDONLY);
+  ASSERT_TRUE(fd != -1);
+
+  struct flock64 check_lock;
+  check_lock.l_type = F_WRLCK;
+  check_lock.l_start = 0;
+  check_lock.l_whence = SEEK_SET;
+  check_lock.l_len = 0;
+
+  int rc = fcntl(fd, F_GETLK64, &check_lock);
+  ASSERT_EQ(0, rc);
+
+  close(fd);
+}
diff --git a/tests/fortify_test.cpp b/tests/fortify_test.cpp
index 67e197e..d80b2f7 100644
--- a/tests/fortify_test.cpp
+++ b/tests/fortify_test.cpp
@@ -43,6 +43,31 @@
 #ifndef __clang__
 // This test is disabled in clang because clang doesn't properly detect
 // this buffer overflow. TODO: Fix clang.
+TEST(DEATHTEST, stpncpy_fortified2) {
+  ::testing::FLAGS_gtest_death_test_style = "threadsafe";
+  foo myfoo;
+  int copy_amt = atoi("11");
+  ASSERT_EXIT(stpncpy(myfoo.a, "01234567890", copy_amt),
+              testing::KilledBySignal(SIGABRT), "");
+}
+#endif
+
+#ifndef __clang__
+// This test is disabled in clang because clang doesn't properly detect
+// this buffer overflow. TODO: Fix clang.
+TEST(DEATHTEST, stpncpy2_fortified2) {
+  ::testing::FLAGS_gtest_death_test_style = "threadsafe";
+  foo myfoo;
+  memset(&myfoo, 0, sizeof(myfoo));
+  myfoo.one[0] = 'A'; // not null terminated string
+  ASSERT_EXIT(stpncpy(myfoo.b, myfoo.one, sizeof(myfoo.b)),
+              testing::KilledBySignal(SIGABRT), "");
+}
+#endif
+
+#ifndef __clang__
+// This test is disabled in clang because clang doesn't properly detect
+// this buffer overflow. TODO: Fix clang.
 TEST(DEATHTEST, strncpy_fortified2) {
   ::testing::FLAGS_gtest_death_test_style = "threadsafe";
   foo myfoo;
@@ -144,6 +169,24 @@
 // zero sized target with "\0" source (should fail)
 // This test is disabled in clang because clang doesn't properly detect
 // this buffer overflow. TODO: Fix clang.
+TEST(DEATHTEST, stpcpy_fortified2) {
+#if defined(__BIONIC__)
+  ::testing::FLAGS_gtest_death_test_style = "threadsafe";
+  foo myfoo;
+  char* src = strdup("");
+  ASSERT_EXIT(stpcpy(myfoo.empty, src),
+              testing::KilledBySignal(SIGABRT), "");
+  free(src);
+#else // __BIONIC__
+  GTEST_LOG_(INFO) << "This test does nothing.\n";
+#endif // __BIONIC__
+}
+#endif
+
+#ifndef __clang__
+// zero sized target with "\0" source (should fail)
+// This test is disabled in clang because clang doesn't properly detect
+// this buffer overflow. TODO: Fix clang.
 TEST(DEATHTEST, strcpy_fortified2) {
 #if defined(__BIONIC__)
   ::testing::FLAGS_gtest_death_test_style = "threadsafe";
@@ -559,6 +602,23 @@
   ASSERT_EXIT(memcpy(bufb, bufa, n), testing::KilledBySignal(SIGABRT), "");
 }
 
+TEST(DEATHTEST, stpncpy_fortified) {
+  ::testing::FLAGS_gtest_death_test_style = "threadsafe";
+  char bufa[15];
+  char bufb[10];
+  strcpy(bufa, "01234567890123");
+  size_t n = strlen(bufa);
+  ASSERT_EXIT(stpncpy(bufb, bufa, n), testing::KilledBySignal(SIGABRT), "");
+}
+
+TEST(DEATHTEST, stpncpy2_fortified) {
+  ::testing::FLAGS_gtest_death_test_style = "threadsafe";
+  char dest[11];
+  char src[10];
+  memcpy(src, "0123456789", sizeof(src)); // src is not null terminated
+  ASSERT_EXIT(stpncpy(dest, src, sizeof(dest)), testing::KilledBySignal(SIGABRT), "");
+}
+
 TEST(DEATHTEST, strncpy_fortified) {
   ::testing::FLAGS_gtest_death_test_style = "threadsafe";
   char bufa[15];
@@ -568,6 +628,7 @@
   ASSERT_EXIT(strncpy(bufb, bufa, n), testing::KilledBySignal(SIGABRT), "");
 }
 
+
 TEST(DEATHTEST, strncpy2_fortified) {
   ::testing::FLAGS_gtest_death_test_style = "threadsafe";
   char dest[11];
@@ -790,6 +851,45 @@
   ASSERT_EQ('\0',  buf[9]);
 }
 
+TEST(TEST_NAME, stpncpy) {
+  char src[10];
+  char dst[10];
+  memcpy(src, "0123456789", sizeof(src)); // non null terminated string
+  stpncpy(dst, src, sizeof(dst));
+  ASSERT_EQ('0', dst[0]);
+  ASSERT_EQ('1', dst[1]);
+  ASSERT_EQ('2', dst[2]);
+  ASSERT_EQ('3', dst[3]);
+  ASSERT_EQ('4', dst[4]);
+  ASSERT_EQ('5', dst[5]);
+  ASSERT_EQ('6', dst[6]);
+  ASSERT_EQ('7', dst[7]);
+  ASSERT_EQ('8', dst[8]);
+  ASSERT_EQ('9', dst[9]);
+}
+
+TEST(TEST_NAME, stpncpy2) {
+  char src[10];
+  char dst[15];
+  memcpy(src, "012345678\0", sizeof(src));
+  stpncpy(dst, src, sizeof(dst));
+  ASSERT_EQ('0',  dst[0]);
+  ASSERT_EQ('1',  dst[1]);
+  ASSERT_EQ('2',  dst[2]);
+  ASSERT_EQ('3',  dst[3]);
+  ASSERT_EQ('4',  dst[4]);
+  ASSERT_EQ('5',  dst[5]);
+  ASSERT_EQ('6',  dst[6]);
+  ASSERT_EQ('7',  dst[7]);
+  ASSERT_EQ('8',  dst[8]);
+  ASSERT_EQ('\0', dst[9]);
+  ASSERT_EQ('\0', dst[10]);
+  ASSERT_EQ('\0', dst[11]);
+  ASSERT_EQ('\0', dst[12]);
+  ASSERT_EQ('\0', dst[13]);
+  ASSERT_EQ('\0', dst[14]);
+}
+
 TEST(TEST_NAME, strncpy) {
   char src[10];
   char dst[10];
@@ -848,22 +948,22 @@
   ASSERT_EQ('\0', buf[9]);
 }
 
+extern "C" char* __stpcpy_chk(char*, const char*, size_t);
+
+TEST(TEST_NAME, stpcpy_chk_max_int_size) {
+  char buf[10];
+  char* res = __stpcpy_chk(buf, "012345678", (size_t)-1);
+  ASSERT_EQ(buf + strlen("012345678"), res);
+  ASSERT_STREQ("012345678", buf);
+}
+
 extern "C" char* __strcpy_chk(char*, const char*, size_t);
 
 TEST(TEST_NAME, strcpy_chk_max_int_size) {
   char buf[10];
   char* res = __strcpy_chk(buf, "012345678", (size_t)-1);
   ASSERT_EQ(buf, res);
-  ASSERT_EQ('0',  buf[0]);
-  ASSERT_EQ('1',  buf[1]);
-  ASSERT_EQ('2',  buf[2]);
-  ASSERT_EQ('3',  buf[3]);
-  ASSERT_EQ('4',  buf[4]);
-  ASSERT_EQ('5',  buf[5]);
-  ASSERT_EQ('6',  buf[6]);
-  ASSERT_EQ('7',  buf[7]);
-  ASSERT_EQ('8',  buf[8]);
-  ASSERT_EQ('\0', buf[9]);
+  ASSERT_STREQ("012345678", buf);
 }
 
 extern "C" void* __memcpy_chk(void*, const void*, size_t, size_t);
diff --git a/tests/locale_test.cpp b/tests/locale_test.cpp
index df58a70..347b5b1 100644
--- a/tests/locale_test.cpp
+++ b/tests/locale_test.cpp
@@ -16,13 +16,92 @@
 
 #include <gtest/gtest.h>
 
+#include <errno.h>
+#include <limits.h>
 #include <locale.h>
 
 TEST(locale, localeconv) {
-#ifdef __LP64__
-  ASSERT_STREQ(".", localeconv()->decimal_point);
-  ASSERT_STREQ("", localeconv()->currency_symbol);
-#else
-  GTEST_LOG_(INFO) << "This test does nothing.\n";
+  EXPECT_STREQ(".", localeconv()->decimal_point);
+  EXPECT_STREQ("", localeconv()->thousands_sep);
+  EXPECT_STREQ("", localeconv()->grouping);
+  EXPECT_STREQ("", localeconv()->int_curr_symbol);
+  EXPECT_STREQ("", localeconv()->currency_symbol);
+  EXPECT_STREQ("", localeconv()->mon_decimal_point);
+  EXPECT_STREQ("", localeconv()->mon_thousands_sep);
+  EXPECT_STREQ("", localeconv()->mon_grouping);
+  EXPECT_STREQ("", localeconv()->positive_sign);
+  EXPECT_STREQ("", localeconv()->negative_sign);
+  EXPECT_EQ(CHAR_MAX, localeconv()->int_frac_digits);
+  EXPECT_EQ(CHAR_MAX, localeconv()->frac_digits);
+  EXPECT_EQ(CHAR_MAX, localeconv()->p_cs_precedes);
+  EXPECT_EQ(CHAR_MAX, localeconv()->p_sep_by_space);
+  EXPECT_EQ(CHAR_MAX, localeconv()->n_cs_precedes);
+  EXPECT_EQ(CHAR_MAX, localeconv()->n_sep_by_space);
+  EXPECT_EQ(CHAR_MAX, localeconv()->p_sign_posn);
+  EXPECT_EQ(CHAR_MAX, localeconv()->n_sign_posn);
+  EXPECT_EQ(CHAR_MAX, localeconv()->int_p_cs_precedes);
+  EXPECT_EQ(CHAR_MAX, localeconv()->int_p_sep_by_space);
+  EXPECT_EQ(CHAR_MAX, localeconv()->int_n_cs_precedes);
+  EXPECT_EQ(CHAR_MAX, localeconv()->int_n_sep_by_space);
+  EXPECT_EQ(CHAR_MAX, localeconv()->int_p_sign_posn);
+  EXPECT_EQ(CHAR_MAX, localeconv()->int_n_sign_posn);
+}
+
+TEST(locale, setlocale) {
+  EXPECT_STREQ("C", setlocale(LC_ALL, NULL));
+  EXPECT_STREQ("C", setlocale(LC_CTYPE, NULL));
+
+  errno = 0;
+  EXPECT_EQ(NULL, setlocale(-1, NULL));
+  EXPECT_EQ(EINVAL, errno);
+  errno = 0;
+  EXPECT_EQ(NULL, setlocale(13, NULL));
+  EXPECT_EQ(EINVAL, errno);
+
+#if __BIONIC__
+  // The "" locale is implementation-defined. For bionic, it's the C locale.
+  // glibc will give us something like "en_US.UTF-8", depending on the user's configuration.
+  EXPECT_STREQ("C", setlocale(LC_ALL, ""));
 #endif
+  EXPECT_STREQ("C", setlocale(LC_ALL, "C"));
+  EXPECT_STREQ("C", setlocale(LC_ALL, "POSIX"));
+
+  errno = 0;
+  EXPECT_EQ(NULL, setlocale(LC_ALL, "this-is-not-a-locale"));
+  EXPECT_EQ(ENOENT, errno); // POSIX specified, not an implementation detail!
+}
+
+TEST(locale, newlocale) {
+  errno = 0;
+  EXPECT_EQ(0, newlocale(1 << 20, "C", 0));
+  EXPECT_EQ(EINVAL, errno);
+
+  locale_t l = newlocale(LC_ALL, "C", 0);
+  ASSERT_TRUE(l != NULL);
+  freelocale(l);
+
+  errno = 0;
+  EXPECT_EQ(0, newlocale(LC_ALL, "this-is-not-a-locale", 0));
+  EXPECT_EQ(ENOENT, errno); // POSIX specified, not an implementation detail!
+}
+
+TEST(locale, duplocale) {
+  locale_t cloned_global = duplocale(LC_GLOBAL_LOCALE);
+  ASSERT_TRUE(cloned_global != NULL);
+  freelocale(cloned_global);
+}
+
+TEST(locale, uselocale) {
+  locale_t original = uselocale(NULL);
+  EXPECT_FALSE(original == 0);
+  EXPECT_EQ(LC_GLOBAL_LOCALE, original);
+
+  locale_t n = newlocale(LC_ALL, "C", 0);
+  EXPECT_FALSE(n == 0);
+  EXPECT_FALSE(n == original);
+
+  locale_t old = uselocale(n);
+  EXPECT_TRUE(old == original);
+
+  EXPECT_EQ(n, uselocale(NULL));
 }
diff --git a/tests/stdio_test.cpp b/tests/stdio_test.cpp
index 8c1cef9..cc1fd85 100644
--- a/tests/stdio_test.cpp
+++ b/tests/stdio_test.cpp
@@ -297,6 +297,9 @@
 
   snprintf(buf, sizeof(buf), "a_%g_b", 3.14);
   EXPECT_STREQ("a_3.14_b", buf);
+
+  snprintf(buf, sizeof(buf), "%1$s %1$s", "print_me_twice");
+  EXPECT_STREQ("print_me_twice print_me_twice", buf);
 }
 
 TEST(stdio, snprintf_d_INT_MAX) {
diff --git a/tests/stdlib_test.cpp b/tests/stdlib_test.cpp
index 3a3fe28..bb395f0 100644
--- a/tests/stdlib_test.cpp
+++ b/tests/stdlib_test.cpp
@@ -202,3 +202,17 @@
 TEST(stdlib, strtold) {
   ASSERT_DOUBLE_EQ(1.23, strtold("1.23", NULL));
 }
+
+TEST(unistd, _Exit) {
+  int pid = fork();
+  ASSERT_NE(-1, pid) << strerror(errno);
+
+  if (pid == 0) {
+    _Exit(99);
+  }
+
+  int status;
+  ASSERT_EQ(pid, waitpid(pid, &status, 0));
+  ASSERT_TRUE(WIFEXITED(status));
+  ASSERT_EQ(99, WEXITSTATUS(status));
+}
diff --git a/tests/string_test.cpp b/tests/string_test.cpp
index c35976a..14b284e 100644
--- a/tests/string_test.cpp
+++ b/tests/string_test.cpp
@@ -222,7 +222,7 @@
 TEST(string, strcpy2) {
   char buf[1];
   char* orig = strdup("");
-  strcpy(buf, orig);
+  ASSERT_EQ(buf, strcpy(buf, orig));
   ASSERT_EQ('\0', buf[0]);
   free(orig);
 }
@@ -232,13 +232,8 @@
   char buf[10];
   char* orig = strdup("12345");
   memset(buf, 'A', sizeof(buf));
-  strcpy(buf, orig);
-  ASSERT_EQ('1',  buf[0]);
-  ASSERT_EQ('2',  buf[1]);
-  ASSERT_EQ('3',  buf[2]);
-  ASSERT_EQ('4',  buf[3]);
-  ASSERT_EQ('5',  buf[4]);
-  ASSERT_EQ('\0', buf[5]);
+  ASSERT_EQ(buf, strcpy(buf, orig));
+  ASSERT_STREQ("12345", buf);
   ASSERT_EQ('A',  buf[6]);
   ASSERT_EQ('A',  buf[7]);
   ASSERT_EQ('A',  buf[8]);
@@ -251,17 +246,41 @@
   char buf[10];
   char* orig = strdup("123456789");
   memset(buf, 'A', sizeof(buf));
-  strcpy(buf, orig);
-  ASSERT_EQ('1',  buf[0]);
-  ASSERT_EQ('2',  buf[1]);
-  ASSERT_EQ('3',  buf[2]);
-  ASSERT_EQ('4',  buf[3]);
-  ASSERT_EQ('5',  buf[4]);
-  ASSERT_EQ('6',  buf[5]);
-  ASSERT_EQ('7',  buf[6]);
-  ASSERT_EQ('8',  buf[7]);
-  ASSERT_EQ('9',  buf[8]);
-  ASSERT_EQ('\0', buf[9]);
+  ASSERT_EQ(buf, strcpy(buf, orig));
+  ASSERT_STREQ("123456789", buf);
+  free(orig);
+}
+
+// one byte target with "\0" source
+TEST(string, stpcpy2) {
+  char buf[1];
+  char* orig = strdup("");
+  ASSERT_EQ(buf, stpcpy(buf, orig));
+  ASSERT_EQ('\0', buf[0]);
+  free(orig);
+}
+
+// multibyte target where we under fill target
+TEST(string, stpcpy3) {
+  char buf[10];
+  char* orig = strdup("12345");
+  memset(buf, 'A', sizeof(buf));
+  ASSERT_EQ(buf+strlen(orig), stpcpy(buf, orig));
+  ASSERT_STREQ("12345", buf);
+  ASSERT_EQ('A',  buf[6]);
+  ASSERT_EQ('A',  buf[7]);
+  ASSERT_EQ('A',  buf[8]);
+  ASSERT_EQ('A',  buf[9]);
+  free(orig);
+}
+
+// multibyte target where we fill target exactly
+TEST(string, stpcpy4) {
+  char buf[10];
+  char* orig = strdup("123456789");
+  memset(buf, 'A', sizeof(buf));
+  ASSERT_EQ(buf+strlen(orig), stpcpy(buf, orig));
+  ASSERT_STREQ("123456789", buf);
   free(orig);
 }
 
@@ -272,13 +291,7 @@
   buf[1] = '\0';
   char* res = strcat(buf, "01234");
   ASSERT_EQ(buf, res);
-  ASSERT_EQ('a',  buf[0]);
-  ASSERT_EQ('0',  buf[1]);
-  ASSERT_EQ('1',  buf[2]);
-  ASSERT_EQ('2',  buf[3]);
-  ASSERT_EQ('3',  buf[4]);
-  ASSERT_EQ('4',  buf[5]);
-  ASSERT_EQ('\0', buf[6]);
+  ASSERT_STREQ("a01234", buf);
   ASSERT_EQ('A',  buf[7]);
   ASSERT_EQ('A',  buf[8]);
   ASSERT_EQ('A',  buf[9]);
@@ -291,16 +304,7 @@
   buf[1] = '\0';
   char* res = strcat(buf, "01234567");
   ASSERT_EQ(buf, res);
-  ASSERT_EQ('a',  buf[0]);
-  ASSERT_EQ('0',  buf[1]);
-  ASSERT_EQ('1',  buf[2]);
-  ASSERT_EQ('2',  buf[3]);
-  ASSERT_EQ('3',  buf[4]);
-  ASSERT_EQ('4',  buf[5]);
-  ASSERT_EQ('5', buf[6]);
-  ASSERT_EQ('6',  buf[7]);
-  ASSERT_EQ('7',  buf[8]);
-  ASSERT_EQ('\0',  buf[9]);
+  ASSERT_STREQ("a01234567", buf);
 }
 
 TEST(string, strncat2) {
@@ -310,13 +314,7 @@
   buf[1] = '\0';
   char* res = strncat(buf, "01234", sizeof(buf) - strlen(buf) - 1);
   ASSERT_EQ(buf, res);
-  ASSERT_EQ('a',  buf[0]);
-  ASSERT_EQ('0',  buf[1]);
-  ASSERT_EQ('1',  buf[2]);
-  ASSERT_EQ('2',  buf[3]);
-  ASSERT_EQ('3',  buf[4]);
-  ASSERT_EQ('4',  buf[5]);
-  ASSERT_EQ('\0', buf[6]);
+  ASSERT_STREQ("a01234", buf);
   ASSERT_EQ('A',  buf[7]);
   ASSERT_EQ('A',  buf[8]);
   ASSERT_EQ('A',  buf[9]);
@@ -329,13 +327,7 @@
   buf[1] = '\0';
   char* res = strncat(buf, "0123456789", 5);
   ASSERT_EQ(buf, res);
-  ASSERT_EQ('a',  buf[0]);
-  ASSERT_EQ('0',  buf[1]);
-  ASSERT_EQ('1',  buf[2]);
-  ASSERT_EQ('2',  buf[3]);
-  ASSERT_EQ('3',  buf[4]);
-  ASSERT_EQ('4',  buf[5]);
-  ASSERT_EQ('\0', buf[6]);
+  ASSERT_STREQ("a01234", buf);
   ASSERT_EQ('A',  buf[7]);
   ASSERT_EQ('A',  buf[8]);
   ASSERT_EQ('A',  buf[9]);
@@ -348,16 +340,7 @@
   buf[1] = '\0';
   char* res = strncat(buf, "01234567", 8);
   ASSERT_EQ(buf, res);
-  ASSERT_EQ('a',  buf[0]);
-  ASSERT_EQ('0',  buf[1]);
-  ASSERT_EQ('1',  buf[2]);
-  ASSERT_EQ('2',  buf[3]);
-  ASSERT_EQ('3',  buf[4]);
-  ASSERT_EQ('4',  buf[5]);
-  ASSERT_EQ('5', buf[6]);
-  ASSERT_EQ('6',  buf[7]);
-  ASSERT_EQ('7',  buf[8]);
-  ASSERT_EQ('\0',  buf[9]);
+  ASSERT_STREQ("a01234567", buf);
 }
 
 TEST(string, strncat5) {
@@ -367,16 +350,7 @@
   buf[1] = '\0';
   char* res = strncat(buf, "01234567", 9);
   ASSERT_EQ(buf, res);
-  ASSERT_EQ('a',  buf[0]);
-  ASSERT_EQ('0',  buf[1]);
-  ASSERT_EQ('1',  buf[2]);
-  ASSERT_EQ('2',  buf[3]);
-  ASSERT_EQ('3',  buf[4]);
-  ASSERT_EQ('4',  buf[5]);
-  ASSERT_EQ('5', buf[6]);
-  ASSERT_EQ('6',  buf[7]);
-  ASSERT_EQ('7',  buf[8]);
-  ASSERT_EQ('\0',  buf[9]);
+  ASSERT_STREQ("a01234567", buf);
 }
 
 TEST(string, strchr_with_0) {
@@ -456,6 +430,32 @@
   }
 }
 
+TEST(string, stpcpy) {
+  StringTestState<char> state(SMALL);
+  for (size_t j = 0; j < POS_ITER; j++) {
+    state.NewIteration();
+
+    size_t pos = random() % state.MAX_LEN;
+
+    memset(state.ptr1, '\2', pos);
+    state.ptr1[pos] = '\0';
+    state.ptr1[state.MAX_LEN - 1] = '\0';
+
+    memcpy(state.ptr, state.ptr1, state.MAX_LEN);
+
+    memset(state.ptr2, '\1', state.MAX_LEN);
+    state.ptr2[state.MAX_LEN - 1] = '\0';
+
+    memset(state.ptr + state.MAX_LEN, '\1', state.MAX_LEN);
+    memcpy(state.ptr + state.MAX_LEN, state.ptr1, pos + 1);
+    state.ptr[2 * state.MAX_LEN - 1] = '\0';
+
+    ASSERT_TRUE(stpcpy(state.ptr2, state.ptr1) == state.ptr2 + strlen(state.ptr1));
+    ASSERT_FALSE((memcmp(state.ptr1, state.ptr, state.MAX_LEN)) != 0 ||
+                 (memcmp(state.ptr2, state.ptr + state.MAX_LEN, state.MAX_LEN) != 0));
+  }
+}
+
 TEST(string, strcpy) {
   StringTestState<char> state(SMALL);
   for (size_t j = 0; j < POS_ITER; j++) {
@@ -482,7 +482,6 @@
   }
 }
 
-
 TEST(string, strlcat) {
 #if defined(__BIONIC__)
   StringTestState<char> state(SMALL);
@@ -614,30 +613,81 @@
   }
 }
 
+TEST(string, stpncpy) {
+  StringTestState<char> state(SMALL);
+  for (size_t j = 0; j < ITER; j++) {
+    state.NewIteration();
+
+    // Choose a random value to fill the string, except \0 (string terminator),
+    // or \1 (guarantees it's different from anything in ptr2).
+    memset(state.ptr1, (random() % 254) + 2, state.MAX_LEN);
+    // Choose a random size for our src buffer.
+    size_t ptr1_len = random() % state.MAX_LEN;
+    state.ptr1[ptr1_len] = '\0';
+    // Copy ptr1 into ptr, used to verify that ptr1 does not get modified.
+    memcpy(state.ptr, state.ptr1, state.MAX_LEN);
+    // Init ptr2 to a set value.
+    memset(state.ptr2, '\1', state.MAX_LEN);
+
+    // Choose a random amount of data to copy.
+    size_t copy_len = random() % state.MAX_LEN;
+
+    // Set the second half of ptr to the expected pattern in ptr2.
+    memset(state.ptr + state.MAX_LEN, '\1', state.MAX_LEN);
+    memcpy(state.ptr + state.MAX_LEN, state.ptr1, copy_len);
+    size_t expected_end;
+    if (copy_len > ptr1_len) {
+      memset(state.ptr + state.MAX_LEN + ptr1_len, '\0', copy_len - ptr1_len);
+      expected_end = ptr1_len;
+    } else {
+      expected_end = copy_len;
+    }
+
+    ASSERT_EQ(state.ptr2 + expected_end, stpncpy(state.ptr2, state.ptr1, copy_len));
+
+    // Verify ptr1 was not modified.
+    ASSERT_EQ(0, memcmp(state.ptr1, state.ptr, state.MAX_LEN));
+    // Verify ptr2 contains the expected data.
+    ASSERT_EQ(0, memcmp(state.ptr2, state.ptr + state.MAX_LEN, state.MAX_LEN));
+  }
+}
+
 TEST(string, strncpy) {
   StringTestState<char> state(SMALL);
   for (size_t j = 0; j < ITER; j++) {
     state.NewIteration();
 
-    memset(state.ptr1, random() & 255, state.MAX_LEN);
-    state.ptr1[random () % state.MAX_LEN] = '\0';
+    // Choose a random value to fill the string, except \0 (string terminator),
+    // or \1 (guarantees it's different from anything in ptr2).
+    memset(state.ptr1, (random() % 254) + 2, state.MAX_LEN);
+    // Choose a random size for our src buffer.
+    size_t ptr1_len = random() % state.MAX_LEN;
+    state.ptr1[ptr1_len] = '\0';
+    // Copy ptr1 into ptr, used to verify that ptr1 does not get modified.
     memcpy(state.ptr, state.ptr1, state.MAX_LEN);
-
+    // Init ptr2 to a set value.
     memset(state.ptr2, '\1', state.MAX_LEN);
 
-    size_t pos;
-    if (memchr(state.ptr1, 0, state.MAX_LEN)) {
-      pos = strlen(state.ptr1);
+    // Choose a random amount of data to copy.
+    size_t copy_len = random() % state.MAX_LEN;
+
+    // Set the second half of ptr to the expected pattern in ptr2.
+    memset(state.ptr + state.MAX_LEN, '\1', state.MAX_LEN);
+    memcpy(state.ptr + state.MAX_LEN, state.ptr1, copy_len);
+    size_t expected_end;
+    if (copy_len > ptr1_len) {
+      memset(state.ptr + state.MAX_LEN + ptr1_len, '\0', copy_len - ptr1_len);
+      expected_end = ptr1_len;
     } else {
-      pos = state.MAX_LEN - 1;
+      expected_end = copy_len;
     }
 
-    memset(state.ptr + state.MAX_LEN, '\0', state.MAX_LEN);
-    memcpy(state.ptr + state.MAX_LEN, state.ptr1, pos + 1);
+    ASSERT_EQ(state.ptr2 + expected_end, stpncpy(state.ptr2, state.ptr1, copy_len));
 
-    ASSERT_TRUE(strncpy(state.ptr2, state.ptr1, state.MAX_LEN) == state.ptr2);
-    ASSERT_FALSE(memcmp(state.ptr1, state.ptr, state.MAX_LEN) != 0 ||
-                 memcmp(state.ptr2, state.ptr + state.MAX_LEN, state.MAX_LEN) != 0);
+    // Verify ptr1 was not modified.
+    ASSERT_EQ(0, memcmp(state.ptr1, state.ptr, state.MAX_LEN));
+    // Verify ptr2 contains the expected data.
+    ASSERT_EQ(0, memcmp(state.ptr2, state.ptr + state.MAX_LEN, state.MAX_LEN));
   }
 }
 
@@ -966,6 +1016,25 @@
   RunSrcDstBufferOverreadTest(DoStrcpyTest);
 }
 
+static void DoStpcpyTest(uint8_t* src, uint8_t* dst, size_t len) {
+  if (len >= 1) {
+    memset(src, (32 + (len % 96)), len - 1);
+    src[len-1] = '\0';
+    memset(dst, 0, len);
+    ASSERT_EQ(dst+len-1, reinterpret_cast<uint8_t*>(stpcpy(reinterpret_cast<char*>(dst),
+                                                           reinterpret_cast<char*>(src))));
+    ASSERT_TRUE(memcmp(src, dst, len) == 0);
+  }
+}
+
+TEST(string, stpcpy_align) {
+  RunSrcDstBufferAlignTest(LARGE, DoStpcpyTest);
+}
+
+TEST(string, stpcpy_overread) {
+  RunSrcDstBufferOverreadTest(DoStpcpyTest);
+}
+
 // Use our own incrementer to cut down on the total number of calls.
 static size_t LargeSetIncrement(size_t len) {
   if (len >= 4096) {
diff --git a/tests/time_test.cpp b/tests/time_test.cpp
index c055769..26b7775 100644
--- a/tests/time_test.cpp
+++ b/tests/time_test.cpp
@@ -387,51 +387,3 @@
   ASSERT_EQ(ESRCH, pthread_detach(tdd.thread_id));
 #endif
 }
-
-TEST(time, strtotimeval) {
-#if defined(__BIONIC__)
-  struct timeval tv1;
-  char* rest1 = strtotimeval("10.123456", &tv1);
-  ASSERT_EQ(10, tv1.tv_sec);
-  ASSERT_EQ(123456, tv1.tv_usec);
-  ASSERT_EQ('\0', *rest1);
-
-  // strtotimeval interprets the fractional part as microseconds and thus will
-  // only consider its first 6 digits. Even so it should consume all valid
-  // digits.
-  struct timeval tv2;
-  char* rest2 = strtotimeval(".1234567", &tv2);
-  ASSERT_EQ(0, tv2.tv_sec);
-  ASSERT_EQ(123456, tv2.tv_usec);
-  ASSERT_EQ('\0', *rest2);
-
-  struct timeval tv3;
-  char* rest3 = strtotimeval("1.1a", &tv3);
-  ASSERT_EQ(1, tv3.tv_sec);
-  ASSERT_EQ(100000, tv3.tv_usec);
-  ASSERT_EQ('a', *rest3);
-
-  struct timeval tv4;
-  char* rest4 = strtotimeval("a", &tv4);
-  ASSERT_EQ(0, tv4.tv_sec);
-  ASSERT_EQ(0, tv4.tv_usec);
-  ASSERT_EQ('a', *rest4);
-
-  struct timeval tv5;
-  char* rest5 = strtotimeval("0", &tv5);
-  ASSERT_EQ(0, tv5.tv_sec);
-  ASSERT_EQ(0, tv5.tv_usec);
-  ASSERT_EQ('\0', *rest5);
-
-  // TODO: should we reject this case and just return '.'?
-  struct timeval tv6;
-  char* rest6 = strtotimeval(".", &tv6);
-  ASSERT_EQ(0, tv6.tv_sec);
-  ASSERT_EQ(0, tv6.tv_usec);
-  ASSERT_EQ('\0', *rest6);
-
-#else // __BIONIC__
-  GTEST_LOG_(INFO) << "This test does nothing.\n";
-#endif // __BIONIC__
-}
-
diff --git a/tests/unistd_test.cpp b/tests/unistd_test.cpp
index f50c102..f56c5da 100644
--- a/tests/unistd_test.cpp
+++ b/tests/unistd_test.cpp
@@ -22,6 +22,8 @@
 #include <fcntl.h>
 #include <stdint.h>
 #include <unistd.h>
+#include <sys/types.h>
+#include <sys/wait.h>
 
 TEST(unistd, sysconf_SC_MONOTONIC_CLOCK) {
   ASSERT_GT(sysconf(_SC_MONOTONIC_CLOCK), 0);
@@ -116,3 +118,17 @@
 TEST(unistd, alarm) {
   ASSERT_EQ(0U, alarm(0));
 }
+
+TEST(unistd, _exit) {
+  int pid = fork();
+  ASSERT_NE(-1, pid) << strerror(errno);
+
+  if (pid == 0) {
+    _exit(99);
+  }
+
+  int status;
+  ASSERT_EQ(pid, waitpid(pid, &status, 0));
+  ASSERT_TRUE(WIFEXITED(status));
+  ASSERT_EQ(99, WEXITSTATUS(status));
+}
diff --git a/tests/wchar_test.cpp b/tests/wchar_test.cpp
new file mode 100644
index 0000000..20566f2
--- /dev/null
+++ b/tests/wchar_test.cpp
@@ -0,0 +1,57 @@
+/*
+ * Copyright (C) 2014 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <gtest/gtest.h>
+
+#include <limits.h>
+#include <wchar.h>
+
+TEST(wchar, sizeof_wchar_t) {
+  EXPECT_EQ(4U, sizeof(wchar_t));
+  EXPECT_EQ(4U, sizeof(wint_t));
+}
+
+TEST(wchar, mbrlen) {
+  char bytes[] = { 'h', 'e', 'l', 'l', 'o', '\0' };
+  EXPECT_EQ(0U, mbrlen(&bytes[0], 0, NULL));
+  EXPECT_EQ(1U, mbrlen(&bytes[0], 1, NULL));
+
+  EXPECT_EQ(1U, mbrlen(&bytes[4], 1, NULL));
+  EXPECT_EQ(0U, mbrlen(&bytes[5], 1, NULL));
+}
+
+TEST(wchar, wctomb_wcrtomb) {
+  // wctomb and wcrtomb behave differently when s == NULL.
+  EXPECT_EQ(0, wctomb(NULL, L'h'));
+  EXPECT_EQ(0, wctomb(NULL, L'\0'));
+  EXPECT_EQ(1U, wcrtomb(NULL, L'\0', NULL));
+  EXPECT_EQ(1U, wcrtomb(NULL, L'h', NULL));
+
+  char bytes[MB_LEN_MAX];
+
+  // wctomb and wcrtomb behave similarly for the null wide character.
+  EXPECT_EQ(1, wctomb(bytes, L'\0'));
+  EXPECT_EQ(1U, wcrtomb(bytes, L'\0', NULL));
+
+  // ...and for regular characters.
+  bytes[0] = 'x';
+  EXPECT_EQ(1, wctomb(bytes, L'h'));
+  EXPECT_EQ('h', bytes[0]);
+
+  bytes[0] = 'x';
+  EXPECT_EQ(1U, wcrtomb(bytes, L'h', NULL));
+  EXPECT_EQ('h', bytes[0]);
+}