Merge "Fix the printf issue for 64 bits. The following case:"
diff --git a/libc/Android.mk b/libc/Android.mk
index 44bf388..76425c1 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 \
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/posix_timers.cpp b/libc/bionic/posix_timers.cpp
index e9190b2..59933ec 100644
--- a/libc/bionic/posix_timers.cpp
+++ b/libc/bionic/posix_timers.cpp
@@ -63,7 +63,6 @@
   pthread_t callback_thread;
   void (*callback)(sigval_t);
   sigval_t callback_argument;
-  volatile int exiting;
 };
 
 static __kernel_timer_t to_kernel_timer_id(timer_t timer) {
@@ -90,8 +89,7 @@
       timer->callback(timer->callback_argument);
     } else if (si.si_code == SI_TKILL) {
       // This signal was sent because someone wants us to exit.
-      timer->exiting = 1;
-      __futex_wake(&timer->exiting, INT32_MAX);
+      free(timer);
       return NULL;
     }
   }
@@ -99,46 +97,35 @@
 
 static void __timer_thread_stop(PosixTimer* timer) {
   pthread_kill(timer->callback_thread, TIMER_SIGNAL);
-
-  // If this is being called from within the callback thread, do nothing else.
-  if (pthread_self() != timer->callback_thread) {
-    // We can't pthread_join because POSIX says "the threads created in response to a timer
-    // expiration are created detached, or in an unspecified way if the thread attribute's
-    // detachstate is PTHREAD_CREATE_JOINABLE".
-    while (timer->exiting == 0) {
-      __futex_wait(&timer->exiting, 0, NULL);
-    }
-  }
 }
 
 // http://pubs.opengroup.org/onlinepubs/9699919799/functions/timer_create.html
 int timer_create(clockid_t clock_id, sigevent* evp, timer_t* timer_id) {
-  PosixTimer* new_timer = reinterpret_cast<PosixTimer*>(malloc(sizeof(PosixTimer)));
-  if (new_timer == NULL) {
+  PosixTimer* timer = reinterpret_cast<PosixTimer*>(malloc(sizeof(PosixTimer)));
+  if (timer == NULL) {
     return -1;
   }
 
-  new_timer->sigev_notify = (evp == NULL) ? SIGEV_SIGNAL : evp->sigev_notify;
+  timer->sigev_notify = (evp == NULL) ? SIGEV_SIGNAL : evp->sigev_notify;
 
   // If not a SIGEV_THREAD timer, the kernel can handle it without our help.
-  if (new_timer->sigev_notify != SIGEV_THREAD) {
-    if (__timer_create(clock_id, evp, &new_timer->kernel_timer_id) == -1) {
-      free(new_timer);
+  if (timer->sigev_notify != SIGEV_THREAD) {
+    if (__timer_create(clock_id, evp, &timer->kernel_timer_id) == -1) {
+      free(timer);
       return -1;
     }
 
-    *timer_id = new_timer;
+    *timer_id = timer;
     return 0;
   }
 
   // Otherwise, this must be SIGEV_THREAD timer...
-  new_timer->callback = evp->sigev_notify_function;
-  new_timer->callback_argument = evp->sigev_value;
-  new_timer->exiting = 0;
+  timer->callback = evp->sigev_notify_function;
+  timer->callback_argument = evp->sigev_value;
 
   // Check arguments that the kernel doesn't care about but we do.
-  if (new_timer->callback == NULL) {
-    free(new_timer);
+  if (timer->callback == NULL) {
+    free(timer);
     errno = EINVAL;
     return -1;
   }
@@ -159,12 +146,12 @@
   kernel_sigset_t old_sigset;
   pthread_sigmask(SIG_BLOCK, sigset.get(), old_sigset.get());
 
-  int rc = pthread_create(&new_timer->callback_thread, &thread_attributes, __timer_thread_start, new_timer);
+  int rc = pthread_create(&timer->callback_thread, &thread_attributes, __timer_thread_start, timer);
 
   pthread_sigmask(SIG_SETMASK, old_sigset.get(), NULL);
 
   if (rc != 0) {
-    free(new_timer);
+    free(timer);
     errno = rc;
     return -1;
   }
@@ -172,20 +159,19 @@
   sigevent se = *evp;
   se.sigev_signo = TIMER_SIGNAL;
   se.sigev_notify = SIGEV_THREAD_ID;
-  se.sigev_notify_thread_id = __pthread_gettid(new_timer->callback_thread);
-  if (__timer_create(clock_id, &se, &new_timer->kernel_timer_id) == -1) {
-    __timer_thread_stop(new_timer);
-    free(new_timer);
+  se.sigev_notify_thread_id = __pthread_gettid(timer->callback_thread);
+  if (__timer_create(clock_id, &se, &timer->kernel_timer_id) == -1) {
+    __timer_thread_stop(timer);
     return -1;
   }
 
   // Give the thread a meaningful name.
   // It can't do this itself because the kernel timer isn't created until after it's running.
   char name[32];
-  snprintf(name, sizeof(name), "POSIX interval timer %d", to_kernel_timer_id(new_timer));
-  pthread_setname_np(new_timer->callback_thread, name);
+  snprintf(name, sizeof(name), "POSIX interval timer %d", to_kernel_timer_id(timer));
+  pthread_setname_np(timer->callback_thread, name);
 
-  *timer_id = new_timer;
+  *timer_id = timer;
   return 0;
 }
 
@@ -197,14 +183,14 @@
   }
 
   PosixTimer* timer = reinterpret_cast<PosixTimer*>(id);
-
-  // Make sure the timer's thread has exited before we free the timer data.
   if (timer->sigev_notify == SIGEV_THREAD) {
+    // Stopping the timer's thread frees the timer data when it's safe.
     __timer_thread_stop(timer);
+  } else {
+    // For timers without threads, we can just free right away.
+    free(timer);
   }
 
-  free(timer);
-
   return 0;
 }
 
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/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..5dbcb3d 100644
--- a/libc/include/stdlib.h
+++ b/libc/include/stdlib.h
@@ -151,7 +151,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 +159,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/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/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/kernel/uapi/video/adf.h b/libc/kernel/uapi/video/adf.h
index 057ec46..fe23e01 100644
--- a/libc/kernel/uapi/video/adf.h
+++ b/libc/kernel/uapi/video/adf.h
@@ -62,7 +62,7 @@
 struct adf_vsync_event {
 /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
  struct adf_event base;
- __u64 timestamp;
+ __aligned_u64 timestamp;
 };
 struct adf_hotplug_event {
 /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
@@ -77,12 +77,12 @@
  __u32 h;
 /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
  __u32 format;
- __s64 fd[ADF_MAX_PLANES];
+ __s32 fd[ADF_MAX_PLANES];
  __u32 offset[ADF_MAX_PLANES];
  __u32 pitch[ADF_MAX_PLANES];
 /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
  __u8 n_planes;
- __s64 acquire_fence;
+ __s32 acquire_fence;
 };
 #define ADF_MAX_BUFFERS (4096 / sizeof(struct adf_buffer_config))
 /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
@@ -94,7 +94,7 @@
  struct adf_buffer_config __user *bufs;
  size_t custom_data_size;
  void __user *custom_data;
- __s64 complete_fence;
+ __s32 complete_fence;
 /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
 };
 #define ADF_MAX_INTERFACES (4096 / sizeof(__u32))
@@ -103,7 +103,7 @@
 /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
  __u16 h;
  __u32 format;
- __s64 fd;
+ __s32 fd;
  __u32 offset;
 /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
  __u32 pitch;
@@ -111,7 +111,7 @@
 struct adf_simple_post_config {
  struct adf_buffer_config buf;
 /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
- __s64 complete_fence;
+ __s32 complete_fence;
 };
 struct adf_attachment_config {
  __u32 overlay_engine;
@@ -161,18 +161,20 @@
 };
 #define ADF_MAX_SUPPORTED_FORMATS (4096 / sizeof(__u32))
 /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define ADF_SET_EVENT _IOW('D', 0, struct adf_set_event)
-#define ADF_BLANK _IOW('D', 1, __u8)
-#define ADF_POST_CONFIG _IOW('D', 2, struct adf_post_config)
-#define ADF_SET_MODE _IOW('D', 3, struct drm_mode_modeinfo)
+#define ADF_IOCTL_TYPE 'D'
+#define ADF_IOCTL_NR_CUSTOM 128
+#define ADF_SET_EVENT _IOW(ADF_IOCTL_TYPE, 0, struct adf_set_event)
+#define ADF_BLANK _IOW(ADF_IOCTL_TYPE, 1, __u8)
 /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define ADF_GET_DEVICE_DATA _IOR('D', 4, struct adf_device_data)
-#define ADF_GET_INTERFACE_DATA _IOR('D', 5, struct adf_interface_data)
-#define ADF_GET_OVERLAY_ENGINE_DATA   _IOR('D', 6, struct adf_overlay_engine_data)
-#define ADF_SIMPLE_POST_CONFIG _IOW('D', 7, struct adf_simple_post_config)
+#define ADF_POST_CONFIG _IOW(ADF_IOCTL_TYPE, 2, struct adf_post_config)
+#define ADF_SET_MODE _IOW(ADF_IOCTL_TYPE, 3,   struct drm_mode_modeinfo)
+#define ADF_GET_DEVICE_DATA _IOR(ADF_IOCTL_TYPE, 4, struct adf_device_data)
+#define ADF_GET_INTERFACE_DATA _IOR(ADF_IOCTL_TYPE, 5,   struct adf_interface_data)
 /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define ADF_SIMPLE_BUFFER_ALLOC _IOW('D', 8, struct adf_simple_buffer_alloc)
-#define ADF_ATTACH _IOW('D', 9, struct adf_attachment_config)
-#define ADF_DETACH _IOW('D', 10, struct adf_attachment_config)
+#define ADF_GET_OVERLAY_ENGINE_DATA   _IOR(ADF_IOCTL_TYPE, 6,   struct adf_overlay_engine_data)
+#define ADF_SIMPLE_POST_CONFIG _IOW(ADF_IOCTL_TYPE, 7,   struct adf_simple_post_config)
+#define ADF_SIMPLE_BUFFER_ALLOC _IOW(ADF_IOCTL_TYPE, 8,   struct adf_simple_buffer_alloc)
+#define ADF_ATTACH _IOW(ADF_IOCTL_TYPE, 9,   struct adf_attachment_config)
+/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
+#define ADF_DETACH _IOW(ADF_IOCTL_TYPE, 10,   struct adf_attachment_config)
 #endif
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
diff --git a/libc/zoneinfo/tzdata b/libc/zoneinfo/tzdata
index 8468e83..2178298 100644
--- a/libc/zoneinfo/tzdata
+++ b/libc/zoneinfo/tzdata
Binary files differ
diff --git a/libm/Android.mk b/libm/Android.mk
index 4a826eb..aea4662 100644
--- a/libm/Android.mk
+++ b/libm/Android.mk
@@ -261,7 +261,6 @@
 LOCAL_C_INCLUDES_x86 := $(LOCAL_PATH)/i386 $(LOCAL_PATH)/i387
 LOCAL_SRC_FILES_x86 := i387/fenv.c
 
-LOCAL_CFLAGS_x86_64 := -include $(LOCAL_PATH)/fpmath.h
 LOCAL_C_INCLUDES_x86_64 := $(LOCAL_PATH)/amd64 $(libm_ld_includes)
 LOCAL_SRC_FILES_x86_64 := amd64/fenv.c $(libm_ld_src_files)
 
diff --git a/libm/fake_long_double.c b/libm/fake_long_double.c
index 13adf2f..b5b264b 100644
--- a/libm/fake_long_double.c
+++ b/libm/fake_long_double.c
@@ -22,16 +22,34 @@
 
 int (isnanf)(float a1) { return __isnanf(a1); }
 
-// FreeBSD falls back to the double variants of these functions as well.
-long double coshl(long double a1) { return cosh(a1); }
-long double erfcl(long double a1) { return erfc(a1); }
-long double erfl(long double a1) { return erf(a1); }
-long double lgammal(long double a1) { return lgamma(a1); }
+/*
+ * On LP64 sizeof(long double) > sizeof(double) so functions which fall back
+ * to their double variants lose precision. Emit a warning whenever something
+ * links against such functions.
+ * On LP32 sizeof(long double) == sizeof(double) so we don't need to warn.
+ */
+#ifdef __LP64__
+#define WARN_IMPRECISE(x) \
+  __warn_references(x, # x " has lower than advertised precision");
+#else
+#define WARN_IMPRECISE(x)
+#endif //__LP64__
+
+#define DECLARE_IMPRECISE(f) \
+  long double f ## l(long double v) { return f(v); } \
+  WARN_IMPRECISE(x)
+
+DECLARE_IMPRECISE(cosh);
+DECLARE_IMPRECISE(erfc);
+DECLARE_IMPRECISE(erf);
+DECLARE_IMPRECISE(lgamma);
+DECLARE_IMPRECISE(sinh);
+DECLARE_IMPRECISE(tanh);
+DECLARE_IMPRECISE(tgamma);
+DECLARE_IMPRECISE(significand);
+
 long double powl(long double a1, long double a2) { return pow(a1, a2); }
-long double sinhl(long double a1) { return sinh(a1); }
-long double tanhl(long double a1) { return tanh(a1); }
-long double tgammal(long double a1) { return tgamma(a1); }
-long double significandl(long double a1) { return significand(a1); }
+WARN_IMPRECISE(powl)
 
 #ifndef __LP64__
 /*
diff --git a/libm/upstream-freebsd/lib/msun/src/imprecise.c b/libm/upstream-freebsd/lib/msun/src/imprecise.c
deleted file mode 100644
index a7503bf..0000000
--- a/libm/upstream-freebsd/lib/msun/src/imprecise.c
+++ /dev/null
@@ -1,69 +0,0 @@
-/*-
- * Copyright (c) 2013 David Chisnall
- * 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.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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.
- *
- * $FreeBSD$
- */
-
-#include <float.h>
-#include <math.h>
-
-/*
- * If long double is not the same size as double, then these will lose
- * precision and we should emit a warning whenever something links against
- * them.
- */
-#if (LDBL_MANT_DIG > 53)
-#define WARN_IMPRECISE(x) \
-	__warn_references(x, # x " has lower than advertised precision");
-#else
-#define WARN_IMPRECISE(x)
-#endif
-/*
- * Declare the functions as weak variants so that other libraries providing
- * real versions can override them.
- */
-#define	DECLARE_WEAK(x)\
-	__weak_reference(imprecise_## x, x);\
-	WARN_IMPRECISE(x)
-
-long double
-imprecise_powl(long double x, long double y)
-{
-
-	return pow(x, y);
-}
-DECLARE_WEAK(powl);
-
-#define DECLARE_IMPRECISE(f) \
-	long double imprecise_ ## f ## l(long double v) { return f(v); }\
-	DECLARE_WEAK(f ## l)
-
-DECLARE_IMPRECISE(cosh);
-DECLARE_IMPRECISE(erfc);
-DECLARE_IMPRECISE(erf);
-DECLARE_IMPRECISE(lgamma);
-DECLARE_IMPRECISE(sinh);
-DECLARE_IMPRECISE(tanh);
-DECLARE_IMPRECISE(tgamma);
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/math_test.cpp b/tests/math_test.cpp
index 084ea0c..7734018 100644
--- a/tests/math_test.cpp
+++ b/tests/math_test.cpp
@@ -1224,36 +1224,23 @@
 
 TEST(math, modf) {
   double di;
-  double df = modf(123.456, &di);
+  double df = modf(123.75, &di);
   ASSERT_DOUBLE_EQ(123.0, di);
-  // ASSERT_DOUBLE uses more decimals than the double precision when performing
-  // the comparison which can result in false failures. And it seems that modf
-  // results are not 100% precise as expected but within the acceptable delta.
-  // Work around this by tweaking the expected value (taken) from the result of
-  // glibc modf).
-  ASSERT_DOUBLE_EQ(0.45600000000000307, df);
+  ASSERT_DOUBLE_EQ(0.75, df);
 }
 
 TEST(math, modff) {
   float fi;
-  float ff = modff(123.456f, &fi);
+  float ff = modff(123.75f, &fi);
   ASSERT_FLOAT_EQ(123.0f, fi);
-  // See modf comment on why we don't use 0.456f as an excepted value.
-  ASSERT_FLOAT_EQ(0.45600128f, ff);
+  ASSERT_FLOAT_EQ(0.75f, ff);
 }
 
 TEST(math, modfl) {
   long double ldi;
-  long double ldf = modfl(123.456l, &ldi);
-  ASSERT_DOUBLE_EQ(123.0l, ldi);
-  // See modf comment on why we don't use 0.456l as an excepted value when the
-  // modf == modfl. For LP64, where long double != double, modfl algorithm
-  // gives precise results and thus we don't need to tweak the expected value.
-#if defined(__LP64__) || !defined(__BIONIC__)
-  ASSERT_DOUBLE_EQ(0.456l, ldf);
-#else
-  ASSERT_DOUBLE_EQ(0.45600000000000307, ldf);
-#endif // __LP64__ || !__BIONIC__
+  long double ldf = modfl(123.75L, &ldi);
+  ASSERT_DOUBLE_EQ(123.0L, ldi);
+  ASSERT_DOUBLE_EQ(0.75L, ldf);
 }
 
 TEST(math, remquo) {
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/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]);
+}