Merge "Add si_timerid to <signal.h>."
diff --git a/libc/Android.mk b/libc/Android.mk
index 2046bea..0ad5af2 100644
--- a/libc/Android.mk
+++ b/libc/Android.mk
@@ -165,6 +165,7 @@
     bionic/pipe.cpp \
     bionic/poll.cpp \
     bionic/posix_fallocate.cpp \
+    bionic/posix_timers.cpp \
     bionic/pthread_atfork.cpp \
     bionic/pthread_attr.cpp \
     bionic/pthread_cond.cpp \
@@ -224,7 +225,6 @@
     bionic/sys_signame.c \
     bionic/tdestroy.cpp \
     bionic/thread_atexit.cpp \
-    bionic/timer.cpp \
     bionic/tmpfile.cpp \
     bionic/unlink.cpp \
     bionic/utimes.cpp \
@@ -514,7 +514,8 @@
     -DINET6 \
     -I$(LOCAL_PATH)/dns/include \
     -I$(LOCAL_PATH)/private \
-    -I$(LOCAL_PATH)/upstream-netbsd/lib/libc/include # for NetBSD private headers
+    -I$(LOCAL_PATH)/upstream-netbsd/lib/libc/include \
+    -include upstream-netbsd/netbsd-compat.h
 LOCAL_CONLYFLAGS := $(libc_common_conlyflags)
 LOCAL_CPPFLAGS := $(libc_common_cppflags)
 LOCAL_C_INCLUDES := $(libc_common_c_includes)
diff --git a/libc/SYSCALLS.TXT b/libc/SYSCALLS.TXT
index 1928168..8d4b258 100644
--- a/libc/SYSCALLS.TXT
+++ b/libc/SYSCALLS.TXT
@@ -213,11 +213,11 @@
 int           clock_nanosleep(clockid_t clock_id, int flags, const struct timespec* req, struct timespec* rem)  all
 int           getitimer(int, const struct itimerval*)   all
 int           setitimer(int, const struct itimerval*, struct itimerval*)  all
-int           __timer_create:timer_create(clockid_t clockid, struct sigevent* evp, timer_t* timerid)    all
-int           __timer_settime:timer_settime(timer_t, int, const struct itimerspec*, struct itimerspec*) all
-int           __timer_gettime:timer_gettime(timer_t, struct itimerspec*)                                all
-int           __timer_getoverrun:timer_getoverrun(timer_t)                                              all
-int           __timer_delete:timer_delete(timer_t)                                                      all
+int           __timer_create:timer_create(clockid_t clockid, struct sigevent* evp, __kernel_timer_t* timerid)    all
+int           __timer_settime:timer_settime(__kernel_timer_t, int, const struct itimerspec*, struct itimerspec*) all
+int           __timer_gettime:timer_gettime(__kernel_timer_t, struct itimerspec*)                                all
+int           __timer_getoverrun:timer_getoverrun(__kernel_timer_t)                                              all
+int           __timer_delete:timer_delete(__kernel_timer_t)                                                      all
 int           timerfd_create(clockid_t, int)   all
 int           timerfd_settime(int, int, const struct itimerspec*, struct itimerspec*)   all
 int           timerfd_gettime(int, struct itimerspec*)   all
diff --git a/libc/bionic/fork.cpp b/libc/bionic/fork.cpp
index 9fa5fcf..a0f98e4 100644
--- a/libc/bionic/fork.cpp
+++ b/libc/bionic/fork.cpp
@@ -29,15 +29,9 @@
 #include <unistd.h>
 #include <sys/syscall.h>
 
-#include "private/libc_logging.h"
 #include "pthread_internal.h"
 
 int fork() {
-  // POSIX mandates that the timers of a fork child process be
-  // disarmed, but not destroyed. To avoid a race condition, we're
-  // going to stop all timers now, and only re-start them in case
-  // of error, or in the parent process
-  __timer_table_start_stop(1);
   __bionic_atfork_run_prepare();
 
   pthread_internal_t* self = __get_thread();
@@ -50,7 +44,6 @@
   if (result == 0) {
     __bionic_atfork_run_child();
   } else {
-    __timer_table_start_stop(0);
     __bionic_atfork_run_parent();
   }
   return result;
diff --git a/libc/bionic/posix_timers.cpp b/libc/bionic/posix_timers.cpp
new file mode 100644
index 0000000..ffe213c
--- /dev/null
+++ b/libc/bionic/posix_timers.cpp
@@ -0,0 +1,221 @@
+/*
+ * 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 "pthread_internal.h"
+#include "private/bionic_futex.h"
+#include "private/bionic_pthread.h"
+#include "private/kernel_sigset_t.h"
+
+#include <errno.h>
+#include <stdio.h>
+#include <string.h>
+
+// System calls.
+extern "C" int __rt_sigtimedwait(const sigset_t*, siginfo_t*, const struct timespec*, size_t);
+extern "C" int __timer_create(clockid_t, sigevent*, __kernel_timer_t*);
+extern "C" int __timer_delete(__kernel_timer_t);
+extern "C" int __timer_getoverrun(__kernel_timer_t);
+extern "C" int __timer_gettime(__kernel_timer_t, itimerspec*);
+extern "C" int __timer_settime(__kernel_timer_t, int, const itimerspec*, itimerspec*);
+
+// Most POSIX timers are handled directly by the kernel. We translate SIGEV_THREAD timers
+// into SIGEV_THREAD_ID timers so the kernel handles all the time-related stuff and we just
+// need to worry about running user code on a thread.
+
+// We can't use SIGALRM because too many other C library functions throw that around, and since
+// they don't send to a specific thread, all threads are eligible to handle the signal and we can
+// end up with one of our POSIX timer threads handling it (meaning that the intended recipient
+// doesn't). glibc uses SIGRTMIN for its POSIX timer implementation, so in the absence of any
+// reason to use anything else, we use that too.
+static const int TIMER_SIGNAL = SIGRTMIN;
+
+struct PosixTimer {
+  __kernel_timer_t kernel_timer_id;
+
+  int sigev_notify;
+
+  // These fields are only needed for a SIGEV_THREAD timer.
+  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) {
+  return reinterpret_cast<PosixTimer*>(timer)->kernel_timer_id;
+}
+
+static void* __timer_thread_start(void* arg) {
+  PosixTimer* timer = reinterpret_cast<PosixTimer*>(arg);
+
+  kernel_sigset_t sigset;
+  sigaddset(sigset.get(), TIMER_SIGNAL);
+
+  while (true) {
+    // Wait for a signal...
+    siginfo_t si;
+    memset(&si, 0, sizeof(si));
+    int rc = __rt_sigtimedwait(sigset.get(), &si, NULL, sizeof(sigset));
+    if (rc == -1) {
+      continue;
+    }
+
+    if (si.si_code == SI_TIMER) {
+      // This signal was sent because a timer fired, so call the callback.
+      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);
+      return NULL;
+    }
+  }
+}
+
+static void __timer_thread_stop(PosixTimer* timer) {
+  pthread_kill(timer->callback_thread, TIMER_SIGNAL);
+
+  // 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) {
+    return -1;
+  }
+
+  new_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);
+      return -1;
+    }
+
+    *timer_id = new_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;
+
+  // Check arguments that the kernel doesn't care about but we do.
+  if (new_timer->callback == NULL) {
+    free(new_timer);
+    errno = EINVAL;
+    return -1;
+  }
+
+  // Create this timer's thread.
+  pthread_attr_t thread_attributes;
+  if (evp->sigev_notify_attributes == NULL) {
+    pthread_attr_init(&thread_attributes);
+  } else {
+    thread_attributes = *reinterpret_cast<pthread_attr_t*>(evp->sigev_notify_attributes);
+  }
+  pthread_attr_setdetachstate(&thread_attributes, PTHREAD_CREATE_DETACHED);
+
+  // We start the thread with TIMER_SIGNAL blocked by blocking the signal here and letting it
+  // inherit. If it tried to block the signal itself, there would be a race.
+  kernel_sigset_t sigset;
+  sigaddset(sigset.get(), TIMER_SIGNAL);
+  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);
+
+  pthread_sigmask(SIG_SETMASK, old_sigset.get(), NULL);
+
+  if (rc != 0) {
+    free(new_timer);
+    errno = rc;
+    return -1;
+  }
+
+  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);
+    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);
+
+  *timer_id = new_timer;
+  return 0;
+}
+
+// http://pubs.opengroup.org/onlinepubs/9699919799/functions/timer_delete.html
+int timer_delete(timer_t id) {
+  int rc = __timer_delete(to_kernel_timer_id(id));
+  if (rc == -1) {
+    return -1;
+  }
+
+  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) {
+    __timer_thread_stop(timer);
+  }
+
+  free(timer);
+
+  return 0;
+}
+
+// http://pubs.opengroup.org/onlinepubs/9699919799/functions/timer_getoverrun.html
+int timer_gettime(timer_t id, itimerspec* ts) {
+  return __timer_gettime(to_kernel_timer_id(id), ts);
+}
+
+// http://pubs.opengroup.org/onlinepubs/9699919799/functions/timer_getoverrun.html
+int timer_settime(timer_t id, int flags, const itimerspec* ts, itimerspec* ots) {
+  return __timer_settime(to_kernel_timer_id(id), flags, ts, ots);
+}
+
+// http://pubs.opengroup.org/onlinepubs/9699919799/functions/timer_getoverrun.html
+int timer_getoverrun(timer_t id) {
+  return __timer_getoverrun(to_kernel_timer_id(id));
+}
diff --git a/libc/bionic/pthread_atfork.cpp b/libc/bionic/pthread_atfork.cpp
index 5bf63fb..c0664a9 100644
--- a/libc/bionic/pthread_atfork.cpp
+++ b/libc/bionic/pthread_atfork.cpp
@@ -48,14 +48,12 @@
 static atfork_list_t gAtForkList = { NULL, NULL };
 
 void __bionic_atfork_run_prepare() {
-  // We will lock this here, and unlock it in the parent and child functions.
+  // We lock the atfork list here, unlock it in the parent, and reset it in the child.
   // This ensures that nobody can modify the handler array between the calls
   // to the prepare and parent/child handlers.
   //
-  // TODO: If a handler mucks with the list, it could cause problems.  Right
-  //       now it's ok because all they can do is add new items to the end
-  //       of the list, but if/when we implement cleanup in dlclose() things
-  //       will get more interesting...
+  // TODO: If a handler tries to mutate the list, they'll block. We should probably copy
+  // the list before forking, and have prepare, parent, and child all work on the consistent copy.
   pthread_mutex_lock(&gAtForkListMutex);
 
   // Call pthread_atfork() prepare handlers. POSIX states that the prepare
@@ -75,10 +73,7 @@
     }
   }
 
-  pthread_mutexattr_t attr;
-  pthread_mutexattr_init(&attr);
-  pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
-  pthread_mutex_init(&gAtForkListMutex, &attr);
+  gAtForkListMutex = PTHREAD_RECURSIVE_MUTEX_INITIALIZER;
 }
 
 void __bionic_atfork_run_parent() {
diff --git a/libc/bionic/pthread_internal.h b/libc/bionic/pthread_internal.h
index 3825a4c..41f4636 100644
--- a/libc/bionic/pthread_internal.h
+++ b/libc/bionic/pthread_internal.h
@@ -91,8 +91,7 @@
 
 __LIBC_HIDDEN__ int __timespec_from_absolute(timespec*, const timespec*, clockid_t);
 
-/* needed by fork.c */
-__LIBC_HIDDEN__ extern void __timer_table_start_stop(int);
+/* Needed by fork. */
 __LIBC_HIDDEN__ extern void __bionic_atfork_run_prepare();
 __LIBC_HIDDEN__ extern void __bionic_atfork_run_child();
 __LIBC_HIDDEN__ extern void __bionic_atfork_run_parent();
diff --git a/libc/bionic/timer.cpp b/libc/bionic/timer.cpp
deleted file mode 100644
index ed73821..0000000
--- a/libc/bionic/timer.cpp
+++ /dev/null
@@ -1,636 +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 "pthread_internal.h"
-
-#include <errno.h>
-#include <stdio.h>
-#include <string.h>
-
-extern int __pthread_cond_timedwait(pthread_cond_t*, pthread_mutex_t*, const timespec*, clockid_t);
-extern int __pthread_cond_timedwait_relative(pthread_cond_t*, pthread_mutex_t*, const timespec*);
-
-// Normal (i.e. non-SIGEV_THREAD) timers are created directly by the kernel
-// and are passed as is to/from the caller.
-//
-// This file also implements the support required for SIGEV_THREAD ("POSIX interval")
-// timers. See the following pages for additional details:
-//
-// www.opengroup.org/onlinepubs/000095399/functions/timer_create.html
-// www.opengroup.org/onlinepubs/000095399/functions/timer_settime.html
-// www.opengroup.org/onlinepubs/000095399/functions/xsh_chap02_04.html#tag_02_04_01
-//
-// The Linux kernel doesn't support these, so we need to implement them in the
-// C library. We use a very basic scheme where each timer is associated to a
-// thread that will loop, waiting for timeouts or messages from the program
-// corresponding to calls to timer_settime() and timer_delete().
-//
-// Note also an important thing: Posix mandates that in the case of fork(),
-// the timers of the child process should be disarmed, but not deleted.
-// this is implemented by providing a fork() wrapper (see bionic/fork.c) which
-// stops all timers before the fork, and only re-start them in case of error
-// or in the parent process.
-//
-// This stop/start is implemented by the __timer_table_start_stop() function
-// below.
-//
-// A SIGEV_THREAD timer ID will always have its TIMER_ID_WRAP_BIT
-// set to 1. In this implementation, this is always bit 31, which is
-// guaranteed to never be used by kernel-provided timer ids
-//
-// (See code in <kernel>/lib/idr.c, used to manage IDs, to see why.)
-
-#define  TIMER_ID_WRAP_BIT        0x80000000
-#define  TIMER_ID_WRAP(id)        ((timer_t)((id) |  TIMER_ID_WRAP_BIT))
-#define  TIMER_ID_UNWRAP(id)      ((timer_t)((id) & ~TIMER_ID_WRAP_BIT))
-#define  TIMER_ID_IS_WRAPPED(id)  (((id) & TIMER_ID_WRAP_BIT) != 0)
-
-/* this value is used internally to indicate a 'free' or 'zombie'
- * thr_timer structure. Here, 'zombie' means that timer_delete()
- * has been called, but that the corresponding thread hasn't
- * exited yet.
- */
-#define  TIMER_ID_NONE            ((timer_t)0xffffffff)
-
-/* True iff a timer id is valid */
-#define  TIMER_ID_IS_VALID(id)    ((id) != TIMER_ID_NONE)
-
-/* the maximum value of overrun counters */
-#define  DELAYTIMER_MAX    0x7fffffff
-
-typedef struct thr_timer          thr_timer_t;
-typedef struct thr_timer_table    thr_timer_table_t;
-
-/* The Posix spec says the function receives an unsigned parameter, but
- * it's really a 'union sigval' a.k.a. sigval_t */
-typedef void (*thr_timer_func_t)( sigval_t );
-
-struct thr_timer {
-    thr_timer_t*       next;     /* next in free list */
-    timer_t            id;       /* TIMER_ID_NONE iff free or dying */
-    clockid_t          clock;
-    pthread_t          thread;
-    pthread_attr_t     attributes;
-    thr_timer_func_t   callback;
-    sigval_t           value;
-
-    /* the following are used to communicate between
-     * the timer thread and the timer_XXX() functions
-     */
-    pthread_mutex_t           mutex;     /* lock */
-    pthread_cond_t            cond;      /* signal a state change to thread */
-    int volatile              done;      /* set by timer_delete */
-    int volatile              stopped;   /* set by _start_stop() */
-    timespec volatile  expires;   /* next expiration time, or 0 */
-    timespec volatile  period;    /* reload value, or 0 */
-    int volatile              overruns;  /* current number of overruns */
-};
-
-#define  MAX_THREAD_TIMERS  32
-
-struct thr_timer_table {
-    pthread_mutex_t  lock;
-    thr_timer_t*     free_timer;
-    thr_timer_t      timers[ MAX_THREAD_TIMERS ];
-};
-
-/** GLOBAL TABLE OF THREAD TIMERS
- **/
-
-static void
-thr_timer_table_init( thr_timer_table_t*  t )
-{
-    int  nn;
-
-    memset(t, 0, sizeof *t);
-    pthread_mutex_init( &t->lock, NULL );
-
-    for (nn = 0; nn < MAX_THREAD_TIMERS; nn++)
-        t->timers[nn].id = TIMER_ID_NONE;
-
-    t->free_timer = &t->timers[0];
-    for (nn = 1; nn < MAX_THREAD_TIMERS; nn++)
-        t->timers[nn-1].next = &t->timers[nn];
-}
-
-
-static thr_timer_t*
-thr_timer_table_alloc( thr_timer_table_t*  t )
-{
-    thr_timer_t*  timer;
-
-    if (t == NULL)
-        return NULL;
-
-    pthread_mutex_lock(&t->lock);
-    timer = t->free_timer;
-    if (timer != NULL) {
-        t->free_timer = timer->next;
-        timer->next   = NULL;
-        timer->id     = TIMER_ID_WRAP((timer - t->timers));
-    }
-    pthread_mutex_unlock(&t->lock);
-    return timer;
-}
-
-
-static void
-thr_timer_table_free( thr_timer_table_t*  t, thr_timer_t*  timer )
-{
-    pthread_mutex_lock( &t->lock );
-    timer->id     = TIMER_ID_NONE;
-    timer->thread = 0;
-    timer->next   = t->free_timer;
-    t->free_timer = timer;
-    pthread_mutex_unlock( &t->lock );
-}
-
-
-static void thr_timer_table_start_stop(thr_timer_table_t* t, int stop) {
-  if (t == NULL) {
-    return;
-  }
-
-  pthread_mutex_lock(&t->lock);
-  for (int nn = 0; nn < MAX_THREAD_TIMERS; ++nn) {
-    thr_timer_t*  timer  = &t->timers[nn];
-    if (TIMER_ID_IS_VALID(timer->id)) {
-      // Tell the thread to start/stop.
-      pthread_mutex_lock(&timer->mutex);
-      timer->stopped = stop;
-      pthread_cond_signal( &timer->cond );
-      pthread_mutex_unlock(&timer->mutex);
-    }
-  }
-  pthread_mutex_unlock(&t->lock);
-}
-
-
-/* convert a timer_id into the corresponding thr_timer_t* pointer
- * returns NULL if the id is not wrapped or is invalid/free
- */
-static thr_timer_t*
-thr_timer_table_from_id( thr_timer_table_t*  t,
-                         timer_t             id,
-                         int                 remove )
-{
-    unsigned      index;
-    thr_timer_t*  timer;
-
-    if (t == NULL || !TIMER_ID_IS_WRAPPED(id))
-        return NULL;
-
-    index = (unsigned) TIMER_ID_UNWRAP(id);
-    if (index >= MAX_THREAD_TIMERS)
-        return NULL;
-
-    pthread_mutex_lock(&t->lock);
-
-    timer = &t->timers[index];
-
-    if (!TIMER_ID_IS_VALID(timer->id)) {
-        timer = NULL;
-    } else {
-        /* if we're removing this timer, clear the id
-         * right now to prevent another thread to
-         * use the same id after the unlock */
-        if (remove)
-            timer->id = TIMER_ID_NONE;
-    }
-    pthread_mutex_unlock(&t->lock);
-
-    return timer;
-}
-
-/* the static timer table - we only create it if the process
- * really wants to use SIGEV_THREAD timers, which should be
- * pretty infrequent
- */
-
-static pthread_once_t __timer_table_once = PTHREAD_ONCE_INIT;
-static thr_timer_table_t* __timer_table;
-
-static void __timer_table_init(void) {
-  __timer_table = reinterpret_cast<thr_timer_table_t*>(calloc(1, sizeof(*__timer_table)));
-  if (__timer_table != NULL) {
-    thr_timer_table_init(__timer_table);
-  }
-}
-
-static thr_timer_table_t* __timer_table_get(void) {
-  pthread_once(&__timer_table_once, __timer_table_init);
-  return __timer_table;
-}
-
-/** POSIX THREAD TIMERS CLEANUP ON FORK
- **
- ** this should be called from the 'fork()' wrapper to stop/start
- ** all active thread timers. this is used to implement a Posix
- ** requirements: the timers of fork child processes must be
- ** disarmed but not deleted.
- **/
-void __timer_table_start_stop(int stop) {
-  // We access __timer_table directly so we don't create it if it doesn't yet exist.
-  thr_timer_table_start_stop(__timer_table, stop);
-}
-
-static thr_timer_t*
-thr_timer_from_id( timer_t   id )
-{
-    thr_timer_table_t*  table = __timer_table_get();
-    thr_timer_t*        timer = thr_timer_table_from_id( table, id, 0 );
-
-    return timer;
-}
-
-
-static __inline__ void
-thr_timer_lock( thr_timer_t*  t )
-{
-    pthread_mutex_lock(&t->mutex);
-}
-
-static __inline__ void
-thr_timer_unlock( thr_timer_t*  t )
-{
-    pthread_mutex_unlock(&t->mutex);
-}
-
-
-static __inline__ void timespec_add(timespec* a, const timespec* b) {
-  a->tv_sec  += b->tv_sec;
-  a->tv_nsec += b->tv_nsec;
-  if (a->tv_nsec >= 1000000000) {
-    a->tv_nsec -= 1000000000;
-    a->tv_sec  += 1;
-  }
-}
-
-static __inline__ void timespec_sub(timespec* a, const timespec* b) {
-  a->tv_sec  -= b->tv_sec;
-  a->tv_nsec -= b->tv_nsec;
-  if (a->tv_nsec < 0) {
-    a->tv_nsec += 1000000000;
-    a->tv_sec  -= 1;
-  }
-}
-
-static __inline__ void timespec_zero(timespec* a) {
-  a->tv_sec = a->tv_nsec = 0;
-}
-
-static __inline__ int timespec_is_zero(const timespec* a) {
-  return (a->tv_sec == 0 && a->tv_nsec == 0);
-}
-
-static __inline__ int timespec_cmp(const timespec* a, const timespec* b) {
-  if (a->tv_sec  < b->tv_sec)  return -1;
-  if (a->tv_sec  > b->tv_sec)  return +1;
-  if (a->tv_nsec < b->tv_nsec) return -1;
-  if (a->tv_nsec > b->tv_nsec) return +1;
-  return 0;
-}
-
-static __inline__ int timespec_cmp0(const timespec* a) {
-  if (a->tv_sec < 0) return -1;
-  if (a->tv_sec > 0) return +1;
-  if (a->tv_nsec < 0) return -1;
-  if (a->tv_nsec > 0) return +1;
-  return 0;
-}
-
-/** POSIX TIMERS APIs */
-
-extern "C" int __timer_create(clockid_t, sigevent*, timer_t*);
-extern "C" int __timer_delete(timer_t);
-extern "C" int __timer_gettime(timer_t, itimerspec*);
-extern "C" int __timer_settime(timer_t, int, const itimerspec*, itimerspec*);
-extern "C" int __timer_getoverrun(timer_t);
-
-static void* timer_thread_start(void*);
-
-int timer_create(clockid_t clock_id, sigevent* evp, timer_t* timer_id) {
-  // If not a SIGEV_THREAD timer, the kernel can handle it without our help.
-  if (__predict_true(evp == NULL || evp->sigev_notify != SIGEV_THREAD)) {
-    return __timer_create(clock_id, evp, timer_id);
-  }
-
-  // Check arguments.
-  if (evp->sigev_notify_function == NULL) {
-    errno = EINVAL;
-    return -1;
-  }
-
-  // Check that the clock id is supported by the kernel.
-  timespec dummy;
-  if (clock_gettime(clock_id, &dummy) < 0 && errno == EINVAL) {
-    return -1;
-  }
-
-  // Create a new timer and its thread.
-  // TODO: use a single global thread for all timers.
-  thr_timer_table_t* table = __timer_table_get();
-  thr_timer_t* timer = thr_timer_table_alloc(table);
-  if (timer == NULL) {
-    errno = ENOMEM;
-    return -1;
-  }
-
-  // Copy the thread attributes.
-  if (evp->sigev_notify_attributes == NULL) {
-    pthread_attr_init(&timer->attributes);
-  } else {
-    timer->attributes = ((pthread_attr_t*) evp->sigev_notify_attributes)[0];
-  }
-
-  // Posix says that the default is PTHREAD_CREATE_DETACHED and
-  // that PTHREAD_CREATE_JOINABLE has undefined behavior.
-  // So simply always use DETACHED :-)
-  pthread_attr_setdetachstate(&timer->attributes, PTHREAD_CREATE_DETACHED);
-
-  timer->callback = evp->sigev_notify_function;
-  timer->value = evp->sigev_value;
-  timer->clock = clock_id;
-
-  pthread_mutex_init(&timer->mutex, NULL);
-  pthread_cond_init(&timer->cond, NULL);
-
-  timer->done = 0;
-  timer->stopped = 0;
-  timer->expires.tv_sec = timer->expires.tv_nsec = 0;
-  timer->period.tv_sec = timer->period.tv_nsec  = 0;
-  timer->overruns = 0;
-
-  // Create the thread.
-  int rc = pthread_create(&timer->thread, &timer->attributes, timer_thread_start, timer);
-  if (rc != 0) {
-    thr_timer_table_free(table, timer);
-    errno = rc;
-    return -1;
-  }
-
-  *timer_id = timer->id;
-  return 0;
-}
-
-
-int
-timer_delete( timer_t  id )
-{
-    if ( __predict_true(!TIMER_ID_IS_WRAPPED(id)) )
-        return __timer_delete( id );
-    else
-    {
-        thr_timer_table_t*  table = __timer_table_get();
-        thr_timer_t*        timer = thr_timer_table_from_id(table, id, 1);
-
-        if (timer == NULL) {
-            errno = EINVAL;
-            return -1;
-        }
-
-        /* tell the timer's thread to stop */
-        thr_timer_lock(timer);
-        timer->done = 1;
-        pthread_cond_signal( &timer->cond );
-        thr_timer_unlock(timer);
-
-        /* NOTE: the thread will call __timer_table_free() to free the
-         * timer object. the '1' parameter to thr_timer_table_from_id
-         * above ensured that the object and its timer_id cannot be
-         * reused before that.
-         */
-        return 0;
-    }
-}
-
-/* return the relative time until the next expiration, or 0 if
- * the timer is disarmed */
-static void timer_gettime_internal(thr_timer_t* timer, itimerspec* spec) {
-  timespec diff = const_cast<timespec&>(timer->expires);
-  if (!timespec_is_zero(&diff)) {
-    timespec now;
-
-    clock_gettime(timer->clock, &now);
-    timespec_sub(&diff, &now);
-
-    /* in case of overrun, return 0 */
-    if (timespec_cmp0(&diff) < 0) {
-      timespec_zero(&diff);
-    }
-  }
-
-  spec->it_value = diff;
-  spec->it_interval = const_cast<timespec&>(timer->period);
-}
-
-
-int timer_gettime(timer_t id, itimerspec* ospec) {
-    if (ospec == NULL) {
-        errno = EINVAL;
-        return -1;
-    }
-
-    if ( __predict_true(!TIMER_ID_IS_WRAPPED(id)) ) {
-        return __timer_gettime( id, ospec );
-    } else {
-        thr_timer_t*  timer = thr_timer_from_id(id);
-
-        if (timer == NULL) {
-            errno = EINVAL;
-            return -1;
-        }
-        thr_timer_lock(timer);
-        timer_gettime_internal( timer, ospec );
-        thr_timer_unlock(timer);
-    }
-    return 0;
-}
-
-
-int
-timer_settime(timer_t id, int flags, const itimerspec* spec, itimerspec* ospec) {
-    if (spec == NULL) {
-        errno = EINVAL;
-        return -1;
-    }
-
-    if ( __predict_true(!TIMER_ID_IS_WRAPPED(id)) ) {
-        return __timer_settime( id, flags, spec, ospec );
-    } else {
-        thr_timer_t*        timer = thr_timer_from_id(id);
-        timespec     expires, now;
-
-        if (timer == NULL) {
-            errno = EINVAL;
-            return -1;
-        }
-        thr_timer_lock(timer);
-
-        /* return current timer value if ospec isn't NULL */
-        if (ospec != NULL) {
-            timer_gettime_internal(timer, ospec );
-        }
-
-        /* compute next expiration time. note that if the
-         * new it_interval is 0, we should disarm the timer
-         */
-        expires = spec->it_value;
-        if (!timespec_is_zero(&expires)) {
-            clock_gettime( timer->clock, &now );
-            if (!(flags & TIMER_ABSTIME)) {
-                timespec_add(&expires, &now);
-            } else {
-                if (timespec_cmp(&expires, &now) < 0)
-                    expires = now;
-            }
-        }
-        const_cast<timespec&>(timer->expires) = expires;
-        const_cast<timespec&>(timer->period) = spec->it_interval;
-        thr_timer_unlock( timer );
-
-        /* signal the change to the thread */
-        pthread_cond_signal( &timer->cond );
-    }
-    return 0;
-}
-
-
-int
-timer_getoverrun(timer_t  id)
-{
-    if ( __predict_true(!TIMER_ID_IS_WRAPPED(id)) ) {
-        return __timer_getoverrun( id );
-    } else {
-        thr_timer_t*  timer = thr_timer_from_id(id);
-        int           result;
-
-        if (timer == NULL) {
-            errno = EINVAL;
-            return -1;
-        }
-
-        thr_timer_lock(timer);
-        result = timer->overruns;
-        thr_timer_unlock(timer);
-
-        return result;
-    }
-}
-
-
-static void* timer_thread_start(void* arg) {
-  thr_timer_t* timer = reinterpret_cast<thr_timer_t*>(arg);
-
-  thr_timer_lock(timer);
-
-  // Give this thread a meaningful name.
-  char name[32];
-  snprintf(name, sizeof(name), "POSIX interval timer 0x%08x", timer->id);
-  pthread_setname_np(pthread_self(), name);
-
-  // We loop until timer->done is set in timer_delete().
-  while (!timer->done) {
-    timespec expires = const_cast<timespec&>(timer->expires);
-    timespec period = const_cast<timespec&>(timer->period);
-
-    // If the timer is stopped or disarmed, wait indefinitely
-    // for a state change from timer_settime/_delete/_start_stop.
-    if (timer->stopped || timespec_is_zero(&expires)) {
-      pthread_cond_wait(&timer->cond, &timer->mutex);
-      continue;
-    }
-
-    // Otherwise, we need to do a timed wait until either a
-    // state change of the timer expiration time.
-    timespec now;
-    clock_gettime(timer->clock, &now);
-
-    if (timespec_cmp(&expires, &now) > 0) {
-      // Cool, there was no overrun, so compute the
-      // relative timeout as 'expires - now', then wait.
-      timespec diff = expires;
-      timespec_sub(&diff, &now);
-
-      int ret = __pthread_cond_timedwait_relative(&timer->cond, &timer->mutex, &diff);
-
-      // If we didn't time out, it means that a state change
-      // occurred, so loop to take care of it.
-      if (ret != ETIMEDOUT) {
-        continue;
-      }
-    } else {
-      // Overrun was detected before we could wait!
-      if (!timespec_is_zero(&period)) {
-        // For periodic timers, compute total overrun count.
-        do {
-          timespec_add(&expires, &period);
-          if (timer->overruns < DELAYTIMER_MAX) {
-            timer->overruns += 1;
-          }
-        } while (timespec_cmp(&expires, &now) < 0);
-
-        // Backtrack the last one, because we're going to
-        // add the same value just a bit later.
-        timespec_sub(&expires, &period);
-      } else {
-        // For non-periodic timers, things are simple.
-        timer->overruns = 1;
-      }
-    }
-
-    // If we get here, a timeout was detected.
-    // First reload/disarm the timer as needed.
-    if (!timespec_is_zero(&period)) {
-      timespec_add(&expires, &period);
-    } else {
-      timespec_zero(&expires);
-    }
-    const_cast<timespec&>(timer->expires) = expires;
-
-    // Now call the timer callback function. Release the
-    // lock to allow the function to modify the timer setting
-    // or call timer_getoverrun().
-    // NOTE: at this point we trust the callback not to be a
-    //      total moron and pthread_kill() the timer thread
-    thr_timer_unlock(timer);
-    timer->callback(timer->value);
-    thr_timer_lock(timer);
-
-    // Now clear the overruns counter. it only makes sense
-    // within the callback.
-    timer->overruns = 0;
-  }
-
-  thr_timer_unlock(timer);
-
-  // Free the timer object.
-  thr_timer_table_free(__timer_table_get(), timer);
-
-  return NULL;
-}
diff --git a/libc/dns/nameser/ns_name.c b/libc/dns/nameser/ns_name.c
index da36425..e3759ab 100644
--- a/libc/dns/nameser/ns_name.c
+++ b/libc/dns/nameser/ns_name.c
@@ -1,4 +1,4 @@
-/*	$NetBSD: ns_name.c,v 1.3 2004/11/07 02:19:49 christos Exp $	*/
+/*	$NetBSD: ns_name.c,v 1.9 2012/03/13 21:13:39 christos Exp $	*/
 
 /*
  * Copyright (c) 2004 by Internet Systems Consortium, Inc. ("ISC")
@@ -20,9 +20,9 @@
 #include <sys/cdefs.h>
 #ifndef lint
 #ifdef notdef
-static const char rcsid[] = "Id: ns_name.c,v 1.3.2.4.4.2 2004/05/04 03:27:47 marka Exp";
+static const char rcsid[] = "Id: ns_name.c,v 1.11 2009/01/23 19:59:16 each Exp";
 #else
-__RCSID("$NetBSD: ns_name.c,v 1.3 2004/11/07 02:19:49 christos Exp $");
+__RCSID("$NetBSD: ns_name.c,v 1.9 2012/03/13 21:13:39 christos Exp $");
 #endif
 #endif
 
@@ -31,6 +31,7 @@
 #include <netinet/in.h>
 #include <arpa/nameser.h>
 
+#include <assert.h>
 #include <errno.h>
 #ifdef ANDROID_CHANGES
 #include "resolv_private.h"
@@ -43,9 +44,9 @@
 #include <limits.h>
 
 #ifdef SPRINTF_CHAR
-# define SPRINTF(x) strlen(sprintf/**/x)
+# define SPRINTF(x) ((int)strlen(sprintf/**/x))
 #else
-# define SPRINTF(x) ((size_t)sprintf x)
+# define SPRINTF(x) (sprintf x)
 #endif
 
 #define NS_TYPE_ELT			0x40 /* EDNS0 extended label type */
@@ -91,10 +92,10 @@
 /* Public. */
 
 /*
- * ns_name_ntop(src, dst, dstsiz)
  *	Convert an encoded domain name to printable ascii as per RFC1035.
  * return:
  *	Number of bytes written to buffer, or -1 (with errno set)
+ *
  * notes:
  *	The root is returned as "."
  *	All other domains are returned in non absolute form
@@ -188,23 +189,42 @@
 		return (-1);
 	}
 	*dn++ = '\0';
-	return (dn - dst);
+	_DIAGASSERT(__type_fit(int, dn - dst));
+	return (int)(dn - dst);
 }
 
 /*
- * ns_name_pton(src, dst, dstsiz)
+ *	Convert a ascii string into an encoded domain name as per RFC1035.
+ *
+ * return:
+ *
+ *	-1 if it fails
+ *	1 if string was fully qualified
+ *	0 is string was not fully qualified
+ *
+ * notes:
+ *	Enforces label and domain length limits.
+ */
+int
+ns_name_pton(const char *src, u_char *dst, size_t dstsiz) {
+	return (ns_name_pton2(src, dst, dstsiz, NULL));
+}
+
+/*
+ * ns_name_pton2(src, dst, dstsiz, *dstlen)
  *	Convert a ascii string into an encoded domain name as per RFC1035.
  * return:
  *	-1 if it fails
  *	1 if string was fully qualified
  *	0 is string was not fully qualified
+ * side effects:
+ *	fills in *dstlen (if non-NULL)
  * notes:
  *	Enforces label and domain length limits.
  */
 
 int
-ns_name_pton(const char *src, u_char *dst, size_t dstsiz)
-{
+ns_name_pton2(const char *src, u_char *dst, size_t dstsiz, size_t *dstlen) {
 	u_char *label, *bp, *eom;
 	int c, n, escaped, e = 0;
 	char *cp;
@@ -238,19 +258,19 @@
 				continue;
 			}
 			else if ((cp = strchr(digits, c)) != NULL) {
-				n = (cp - digits) * 100;
+				n = (int)(cp - digits) * 100;
 				if ((c = *src++) == 0 ||
 				    (cp = strchr(digits, c)) == NULL) {
 					errno = EMSGSIZE;
 					return (-1);
 				}
-				n += (cp - digits) * 10;
+				n += (int)(cp - digits) * 10;
 				if ((c = *src++) == 0 ||
 				    (cp = strchr(digits, c)) == NULL) {
 					errno = EMSGSIZE;
 					return (-1);
 				}
-				n += (cp - digits);
+				n += (int)(cp - digits);
 				if (n > 255) {
 					errno = EMSGSIZE;
 					return (-1);
@@ -262,7 +282,7 @@
 			escaped = 1;
 			continue;
 		} else if (c == '.') {
-			c = (bp - label - 1);
+			c = (int)(bp - label - 1);
 			if ((c & NS_CMPRSFLGS) != 0) {	/* Label too big. */
 				errno = EMSGSIZE;
 				return (-1);
@@ -285,6 +305,8 @@
 					errno = EMSGSIZE;
 					return (-1);
 				}
+				if (dstlen != NULL)
+					*dstlen = (bp - dst);
 				return (1);
 			}
 			if (c == 0 || *src == '.') {
@@ -300,7 +322,7 @@
 		}
 		*bp++ = (u_char)c;
 	}
-	c = (bp - label - 1);
+	c = (int)(bp - label - 1);
 	if ((c & NS_CMPRSFLGS) != 0) {		/* Label too big. */
 		errno = EMSGSIZE;
 		return (-1);
@@ -322,14 +344,17 @@
 		errno = EMSGSIZE;
 		return (-1);
 	}
+	if (dstlen != NULL)
+		*dstlen = (bp - dst);
 	return (0);
 }
 
 /*
- * ns_name_ntol(src, dst, dstsiz)
  *	Convert a network strings labels into all lowercase.
+ *
  * return:
  *	Number of bytes written to buffer, or -1 (with errno set)
+ *
  * notes:
  *	Enforces label and domain length limits.
  */
@@ -368,19 +393,20 @@
 		}
 		for (; l > 0; l--) {
 			c = *cp++;
-			if (isupper(c))
+			if (isascii(c) && isupper(c))
 				*dn++ = tolower(c);
 			else
 				*dn++ = c;
 		}
 	}
 	*dn++ = '\0';
-	return (dn - dst);
+	_DIAGASSERT(__type_fit(int, dn - dst));
+	return (int)(dn - dst);
 }
 
 /*
- * ns_name_unpack(msg, eom, src, dst, dstsiz)
  *	Unpack a domain name from a message, source may be compressed.
+ *
  * return:
  *	-1 if it fails, or consumed octets if it succeeds.
  */
@@ -388,6 +414,21 @@
 ns_name_unpack(const u_char *msg, const u_char *eom, const u_char *src,
 	       u_char *dst, size_t dstsiz)
 {
+	return (ns_name_unpack2(msg, eom, src, dst, dstsiz, NULL));
+}
+
+/*
+ * ns_name_unpack2(msg, eom, src, dst, dstsiz, *dstlen)
+ *	Unpack a domain name from a message, source may be compressed.
+ * return:
+ *	-1 if it fails, or consumed octets if it succeeds.
+ * side effect:
+ *	fills in *dstlen (if non-NULL).
+ */
+int
+ns_name_unpack2(const u_char *msg, const u_char *eom, const u_char *src,
+		u_char *dst, size_t dstsiz, size_t *dstlen)
+{
 	const u_char *srcp, *dstlim;
 	u_char *dstp;
 	int n, len, checked, l;
@@ -428,13 +469,18 @@
 				errno = EMSGSIZE;
 				return (-1);
 			}
-			if (len < 0)
-				len = srcp - src + 1;
-			srcp = msg + (((n & 0x3f) << 8) | (*srcp & 0xff));
-			if (srcp < msg || srcp >= eom) {  /* Out of range. */
+			if (len < 0) {
+				_DIAGASSERT(__type_fit(int, srcp - src + 1));
+				len = (int)(srcp - src + 1);
+			}
+			// BEGIN android-changed: safer pointer overflow check
+			l = (((n & 0x3f) << 8) | (*srcp & 0xff));
+			if (l >= eom - msg) {  /* Out of range. */
 				errno = EMSGSIZE;
 				return (-1);
 			}
+			srcp = msg + l;
+			// END android-changed
 			checked += 2;
 			/*
 			 * Check for loops in the compressed name;
@@ -452,23 +498,29 @@
 			return (-1);			/* flag error */
 		}
 	}
-	*dstp = '\0';
-	if (len < 0)
-		len = srcp - src;
-	return (len);
+	*dstp++ = 0;
+	if (dstlen != NULL)
+		*dstlen = dstp - dst;
+	if (len < 0) {
+		_DIAGASSERT(__type_fit(int, srcp - src));
+		len = (int)(srcp - src);
+	}
+	return len;
 }
 
 /*
- * ns_name_pack(src, dst, dstsiz, dnptrs, lastdnptr)
  *	Pack domain name 'domain' into 'comp_dn'.
+ *
  * return:
  *	Size of the compressed name, or -1.
+ *
  * notes:
  *	'dnptrs' is an array of pointers to previous compressed names.
  *	dnptrs[0] is a pointer to the beginning of the message. The array
  *	ends with NULL.
  *	'lastdnptr' is a pointer to the end of the array pointed to
  *	by 'dnptrs'.
+ *
  * Side effects:
  *	The list of pointers in dnptrs is updated for labels inserted into
  *	the message as we compress the name.  If 'dnptr' is NULL, we don't
@@ -491,7 +543,7 @@
 	if (dnptrs != NULL) {
 		if ((msg = *dnptrs++) != NULL) {
 			for (cpp = dnptrs; *cpp != NULL; cpp++)
-				;
+				continue;
 			lpp = cpp;	/* end of list to search */
 		}
 	} else
@@ -533,7 +585,8 @@
 				}
 				*dstp++ = ((u_int32_t)l >> 8) | NS_CMPRSFLGS;
 				*dstp++ = l % 256;
-				return (dstp - dst);
+				_DIAGASSERT(__type_fit(int, dstp - dst));
+				return (int)(dstp - dst);
 			}
 			/* Not found, save it. */
 			if (lastdnptr != NULL && cpp < lastdnptr - 1 &&
@@ -564,14 +617,16 @@
 		errno = EMSGSIZE;
 		return (-1);
 	}
-	return (dstp - dst);
+	_DIAGASSERT(__type_fit(int, dstp - dst));
+	return (int)(dstp - dst);
 }
 
 /*
- * ns_name_uncompress(msg, eom, src, dst, dstsiz)
  *	Expand compressed domain name to presentation format.
+ *
  * return:
  *	Number of bytes read out of `src', or -1 (with errno set).
+ *
  * note:
  *	Root domain returns as "." not "".
  */
@@ -590,10 +645,11 @@
 }
 
 /*
- * ns_name_compress(src, dst, dstsiz, dnptrs, lastdnptr)
  *	Compress a domain name into wire format, using compression pointers.
+ *
  * return:
  *	Number of bytes consumed in `dst' or -1 (with errno set).
+ *
  * notes:
  *	'dnptrs' is an array of pointers to previous compressed names.
  *	dnptrs[0] is a pointer to the beginning of the message.
@@ -632,8 +688,8 @@
 }
 
 /*
- * ns_name_skip(ptrptr, eom)
  *	Advance *ptrptr to skip over the compressed name it points at.
+ *
  * return:
  *	0 on success, -1 (with errno set) on failure.
  */
@@ -675,12 +731,156 @@
 	return (0);
 }
 
+/* Find the number of octets an nname takes up, including the root label.
+ * (This is basically ns_name_skip() without compression-pointer support.)
+ * ((NOTE: can only return zero if passed-in namesiz argument is zero.))
+ */
+ssize_t
+ns_name_length(ns_nname_ct nname, size_t namesiz) {
+	ns_nname_ct orig = nname;
+	u_int n;
+
+	while (namesiz-- > 0 && (n = *nname++) != 0) {
+		if ((n & NS_CMPRSFLGS) != 0) {
+			errno = EISDIR;
+			return (-1);
+		}
+		if (n > namesiz) {
+			errno = EMSGSIZE;
+			return (-1);
+		}
+		nname += n;
+		namesiz -= n;
+	}
+	return (nname - orig);
+}
+
+/* Compare two nname's for equality.  Return -1 on error (setting errno).
+ */
+int
+ns_name_eq(ns_nname_ct a, size_t as, ns_nname_ct b, size_t bs) {
+	ns_nname_ct ae = a + as, be = b + bs;
+	int ac, bc;
+
+	while (ac = *a, bc = *b, ac != 0 && bc != 0) {
+		if ((ac & NS_CMPRSFLGS) != 0 || (bc & NS_CMPRSFLGS) != 0) {
+			errno = EISDIR;
+			return (-1);
+		}
+		if (a + ac >= ae || b + bc >= be) {
+			errno = EMSGSIZE;
+			return (-1);
+		}
+		if (ac != bc || strncasecmp((const char *) ++a,
+					    (const char *) ++b,
+					    (size_t)ac) != 0)
+			return (0);
+		a += ac, b += bc;
+	}
+	return (ac == 0 && bc == 0);
+}
+
+/* Is domain "A" owned by (at or below) domain "B"?
+ */
+int
+ns_name_owned(ns_namemap_ct a, int an, ns_namemap_ct b, int bn) {
+	/* If A is shorter, it cannot be owned by B. */
+	if (an < bn)
+		return (0);
+
+	/* If they are unequal before the length of the shorter, A cannot... */
+	while (bn > 0) {
+		if (a->len != b->len ||
+		    strncasecmp((const char *) a->base,
+				(const char *) b->base, (size_t)a->len) != 0)
+			return (0);
+		a++, an--;
+		b++, bn--;
+	}
+
+	/* A might be longer or not, but either way, B owns it. */
+	return (1);
+}
+
+/* Build an array of <base,len> tuples from an nname, top-down order.
+ * Return the number of tuples (labels) thus discovered.
+ */
+int
+ns_name_map(ns_nname_ct nname, size_t namelen, ns_namemap_t map, int mapsize) {
+	u_int n;
+	int l;
+
+	n = *nname++;
+	namelen--;
+
+	/* Root zone? */
+	if (n == 0) {
+		/* Extra data follows name? */
+		if (namelen > 0) {
+			errno = EMSGSIZE;
+			return (-1);
+		}
+		return (0);
+	}
+
+	/* Compression pointer? */
+	if ((n & NS_CMPRSFLGS) != 0) {
+		errno = EISDIR;
+		return (-1);
+	}
+
+	/* Label too long? */
+	if (n > namelen) {
+		errno = EMSGSIZE;
+		return (-1);
+	}
+
+	/* Recurse to get rest of name done first. */
+	l = ns_name_map(nname + n, namelen - n, map, mapsize);
+	if (l < 0)
+		return (-1);
+
+	/* Too many labels? */
+	if (l >= mapsize) {
+		errno = ENAMETOOLONG;
+		return (-1);
+	}
+
+	/* We're on our way back up-stack, store current map data. */
+	map[l].base = nname;
+	map[l].len = n;
+	return (l + 1);
+}
+
+/* Count the labels in a domain name.  Root counts, so COM. has two.  This
+ * is to make the result comparable to the result of ns_name_map().
+ */
+int
+ns_name_labels(ns_nname_ct nname, size_t namesiz) {
+	int ret = 0;
+	u_int n;
+
+	while (namesiz-- > 0 && (n = *nname++) != 0) {
+		if ((n & NS_CMPRSFLGS) != 0) {
+			errno = EISDIR;
+			return (-1);
+		}
+		if (n > namesiz) {
+			errno = EMSGSIZE;
+			return (-1);
+		}
+		nname += n;
+		namesiz -= n;
+		ret++;
+	}
+	return (ret + 1);
+}
 /* Private. */
 
 /*
- * special(ch)
  *	Thinking in noninternationalized USASCII (per the DNS spec),
  *	is this characted special ("in need of quoting") ?
+ *
  * return:
  *	boolean.
  */
@@ -703,9 +903,9 @@
 }
 
 /*
- * printable(ch)
  *	Thinking in noninternationalized USASCII (per the DNS spec),
  *	is this character visible and not a space when printed ?
+ *
  * return:
  *	boolean.
  */
@@ -726,10 +926,11 @@
 }
 
 /*
- * dn_find(domain, msg, dnptrs, lastdnptr)
  *	Search for the counted-label name in an array of compressed names.
+ *
  * return:
  *	offset from msg if found, or -1.
+ *
  * notes:
  *	dnptrs is the pointer to the first name on the list,
  *	not the pointer to the start of the message.
@@ -771,8 +972,11 @@
 						    mklower(*cp++))
 							goto next;
 					/* Is next root for both ? */
-					if (*dn == '\0' && *cp == '\0')
-						return (sp - msg);
+					if (*dn == '\0' && *cp == '\0') {
+						_DIAGASSERT(__type_fit(int,
+						    sp - msg));
+						return (int)(sp - msg);
+					}
 					if (*dn)
 						continue;
 					goto next;
@@ -803,7 +1007,7 @@
 	if ((blen = (*cp & 0xff)) == 0)
 		blen = 256;
 	plen = (blen + 3) / 4;
-	plen += sizeof("\\[x/]") + (blen > 99 ? 3 : (blen > 9) ? 2 : 1);
+	plen += (int)sizeof("\\[x/]") + (blen > 99 ? 3 : (blen > 9) ? 2 : 1);
 	if (dn + plen >= eom)
 		return(-1);
 
@@ -838,7 +1042,8 @@
 	dn += i;
 
 	*cpp = cp;
-	return(dn - beg);
+	_DIAGASSERT(__type_fit(int, dn - beg));
+	return (int)(dn - beg);
 }
 
 static int
diff --git a/libc/dns/nameser/ns_netint.c b/libc/dns/nameser/ns_netint.c
index 33e6090..8b546f8 100644
--- a/libc/dns/nameser/ns_netint.c
+++ b/libc/dns/nameser/ns_netint.c
@@ -1,4 +1,4 @@
-/*	$NetBSD: ns_netint.c,v 1.2 2004/05/20 20:19:00 christos Exp $	*/
+/*	$NetBSD: ns_netint.c,v 1.7 2012/03/13 21:13:39 christos Exp $	*/
 
 /*
  * Copyright (c) 2004 by Internet Systems Consortium, Inc. ("ISC")
@@ -20,9 +20,9 @@
 #include <sys/cdefs.h>
 #ifndef lint
 #ifdef notdef
-static const char rcsid[] = "Id: ns_netint.c,v 1.1.206.1 2004/03/09 08:33:44 marka Exp";
+static const char rcsid[] = "Id: ns_netint.c,v 1.3 2005/04/27 04:56:40 sra Exp";
 #else
-__RCSID("$NetBSD: ns_netint.c,v 1.2 2004/05/20 20:19:00 christos Exp $");
+__RCSID("$NetBSD: ns_netint.c,v 1.7 2012/03/13 21:13:39 christos Exp $");
 #endif
 #endif
 
@@ -32,28 +32,28 @@
 
 /* Public. */
 
-u_int16_t
+uint16_t
 ns_get16(const u_char *src) {
-	u_int dst;
+	uint16_t dst;
 
 	NS_GET16(dst, src);
-	return (dst);
+	return dst;
 }
 
-u_int32_t
+uint32_t
 ns_get32(const u_char *src) {
-	u_long dst;
+	u_int32_t dst;
 
 	NS_GET32(dst, src);
-	return (dst);
+	return dst;
 }
 
 void
-ns_put16(u_int16_t src, u_char *dst) {
+ns_put16(uint16_t src, u_char *dst) {
 	NS_PUT16(src, dst);
 }
 
 void
-ns_put32(u_int32_t src, u_char *dst) {
+ns_put32(uint32_t src, u_char *dst) {
 	NS_PUT32(src, dst);
 }
diff --git a/libc/dns/nameser/ns_parse.c b/libc/dns/nameser/ns_parse.c
index 899ff81..2d6d530 100644
--- a/libc/dns/nameser/ns_parse.c
+++ b/libc/dns/nameser/ns_parse.c
@@ -1,4 +1,4 @@
-/*	$NetBSD: ns_parse.c,v 1.2 2004/05/20 20:35:05 christos Exp $	*/
+/*	$NetBSD: ns_parse.c,v 1.9 2012/03/13 21:13:39 christos Exp $	*/
 
 /*
  * Copyright (c) 2004 by Internet Systems Consortium, Inc. ("ISC")
@@ -20,9 +20,9 @@
 #include <sys/cdefs.h>
 #ifndef lint
 #ifdef notdef
-static const char rcsid[] = "Id: ns_parse.c,v 1.3.2.1.4.1 2004/03/09 08:33:44 marka Exp";
+static const char rcsid[] = "Id: ns_parse.c,v 1.10 2009/01/23 19:59:16 each Exp";
 #else
-__RCSID("$NetBSD: ns_parse.c,v 1.2 2004/05/20 20:35:05 christos Exp $");
+__RCSID("$NetBSD: ns_parse.c,v 1.9 2012/03/13 21:13:39 christos Exp $");
 #endif
 #endif
 
@@ -33,6 +33,7 @@
 #include <netinet/in.h>
 #include <arpa/nameser.h>
 
+#include <assert.h>
 #include <errno.h>
 #ifdef ANDROID_CHANGES
 #include "resolv_private.h"
@@ -96,7 +97,8 @@
 	}
 	if (ptr > eom)
 		RETERR(EMSGSIZE);
-	return (ptr - optr);
+	_DIAGASSERT(__type_fit(int, ptr - optr));
+	return (int)(ptr - optr);
 }
 
 int
@@ -104,7 +106,6 @@
 	const u_char *eom = msg + msglen;
 	int i;
 
-	memset(handle, 0x5e, sizeof *handle);
 	handle->_msg = msg;
 	handle->_eom = eom;
 	if (msg + NS_INT16SZ > eom)
@@ -139,9 +140,11 @@
 int
 ns_parserr(ns_msg *handle, ns_sect section, int rrnum, ns_rr *rr) {
 	int b;
+	int tmp;
 
 	/* Make section right. */
-	if ((unsigned)section >= (unsigned)ns_s_max)
+	tmp = section;
+	if (tmp < 0 || section >= ns_s_max)
 		RETERR(ENODEV);
 	if (section != handle->_sect)
 		setsection(handle, section);
@@ -194,6 +197,69 @@
 	return (0);
 }
 
+/*
+ * This is identical to the above but uses network-format (uncompressed) names.
+ */
+int
+ns_parserr2(ns_msg *handle, ns_sect section, int rrnum, ns_rr2 *rr) {
+	int b;
+	int tmp;
+
+	/* Make section right. */
+	tmp = section;
+	if (tmp < 0 || section >= ns_s_max)
+		RETERR(ENODEV);
+	if (section != handle->_sect)
+		setsection(handle, section);
+
+	/* Make rrnum right. */
+	if (rrnum == -1)
+		rrnum = handle->_rrnum;
+	if (rrnum < 0 || rrnum >= handle->_counts[(int)section])
+		RETERR(ENODEV);
+	if (rrnum < handle->_rrnum)
+		setsection(handle, section);
+	if (rrnum > handle->_rrnum) {
+		b = ns_skiprr(handle->_msg_ptr, handle->_eom, section,
+			      rrnum - handle->_rrnum);
+
+		if (b < 0)
+			return (-1);
+		handle->_msg_ptr += b;
+		handle->_rrnum = rrnum;
+	}
+
+	/* Do the parse. */
+	b = ns_name_unpack2(handle->_msg, handle->_eom, handle->_msg_ptr,
+			    rr->nname, NS_MAXNNAME, &rr->nnamel);
+	if (b < 0)
+		return (-1);
+	handle->_msg_ptr += b;
+	if (handle->_msg_ptr + NS_INT16SZ + NS_INT16SZ > handle->_eom)
+		RETERR(EMSGSIZE);
+	NS_GET16(rr->type, handle->_msg_ptr);
+	NS_GET16(rr->rr_class, handle->_msg_ptr);
+	if (section == ns_s_qd) {
+		rr->ttl = 0;
+		rr->rdlength = 0;
+		rr->rdata = NULL;
+	} else {
+		if (handle->_msg_ptr + NS_INT32SZ + NS_INT16SZ > handle->_eom)
+			RETERR(EMSGSIZE);
+		NS_GET32(rr->ttl, handle->_msg_ptr);
+		NS_GET16(rr->rdlength, handle->_msg_ptr);
+		if (handle->_msg_ptr + rr->rdlength > handle->_eom)
+			RETERR(EMSGSIZE);
+		rr->rdata = handle->_msg_ptr;
+		handle->_msg_ptr += rr->rdlength;
+	}
+	if (++handle->_rrnum > handle->_counts[(int)section])
+		setsection(handle, (ns_sect)((int)section + 1));
+
+	/* All done. */
+	return (0);
+}
+
 /* Private. */
 
 static void
diff --git a/libc/dns/nameser/ns_print.c b/libc/dns/nameser/ns_print.c
index 0b3c068..0a6a1d6 100644
--- a/libc/dns/nameser/ns_print.c
+++ b/libc/dns/nameser/ns_print.c
@@ -1,4 +1,4 @@
-/*	$NetBSD: ns_print.c,v 1.5 2004/11/07 02:19:49 christos Exp $	*/
+/*	$NetBSD: ns_print.c,v 1.11 2012/03/13 21:13:39 christos Exp $	*/
 
 /*
  * Copyright (c) 2004 by Internet Systems Consortium, Inc. ("ISC")
@@ -20,9 +20,9 @@
 #include <sys/cdefs.h>
 #ifndef lint
 #ifdef notdef
-static const char rcsid[] = "Id: ns_print.c,v 1.3.2.1.4.5 2004/07/28 20:16:45 marka Exp";
+static const char rcsid[] = "Id: ns_print.c,v 1.12 2009/03/03 05:29:58 each Exp";
 #else
-__RCSID("$NetBSD: ns_print.c,v 1.5 2004/11/07 02:19:49 christos Exp $");
+__RCSID("$NetBSD: ns_print.c,v 1.11 2012/03/13 21:13:39 christos Exp $");
 #endif
 #endif
 
@@ -37,20 +37,21 @@
 
 #include <isc/assertions.h>
 #include <isc/dst.h>
+#include <assert.h>
 #include <errno.h>
 #ifdef ANDROID_CHANGES
 #include "resolv_private.h"
 #else
 #include <resolv.h>
 #endif
+#include <stddef.h>
 #include <string.h>
 #include <ctype.h>
-#include <assert.h>
 
 #ifdef SPRINTF_CHAR
-# define SPRINTF(x) strlen(sprintf/**/x)
+# define SPRINTF(x) ((int)strlen(sprintf/**/x))
 #else
-# define SPRINTF(x) ((size_t)sprintf x)
+# define SPRINTF(x) (sprintf x)
 #endif
 
 #ifndef MIN
@@ -79,12 +80,13 @@
 			return (-1); \
 	} while (/*CONSTCOND*/0)
 
+static const char base32hex[] =
+        "0123456789ABCDEFGHIJKLMNOPQRSTUV=0123456789abcdefghijklmnopqrstuv";
 /* Public. */
 
 /*
- * int
- * ns_sprintrr(handle, rr, name_ctx, origin, buf, buflen)
  *	Convert an RR to presentation format.
+ *
  * return:
  *	Number of characters written to buf, or -1 (check errno).
  */
@@ -103,10 +105,8 @@
 }
 
 /*
- * int
- * ns_sprintrrf(msg, msglen, name, class, type, ttl, rdata, rdlen,
- *	       name_ctx, origin, buf, buflen)
  *	Convert the fields of an RR into presentation format.
+ *
  * return:
  *	Number of characters written to buf, or -1 (check errno).
  */
@@ -131,7 +131,7 @@
 	if (name_ctx != NULL && ns_samename(name_ctx, name) == 1) {
 		T(addstr("\t\t\t", (size_t)3, &buf, &buflen));
 	} else {
-		len = prune_origin(name, origin);
+		len = (int)prune_origin(name, origin);
 		if (*name == '\0') {
 			goto root;
 		} else if (len == 0) {
@@ -166,7 +166,7 @@
 	case ns_t_a:
 		if (rdlen != (size_t)NS_INADDRSZ)
 			goto formerr;
-		(void) inet_ntop(AF_INET, rdata, buf, buflen);
+		(void) inet_ntop(AF_INET, rdata, buf, (socklen_t)buflen);
 		addlen(strlen(buf), &buf, &buflen);
 		break;
 
@@ -265,7 +265,8 @@
 
 	case ns_t_mx:
 	case ns_t_afsdb:
-	case ns_t_rt: {
+	case ns_t_rt:
+	case ns_t_kx: {
 		u_int t;
 
 		if (rdlen < (size_t)NS_INT16SZ)
@@ -313,6 +314,7 @@
 		break;
 
 	case ns_t_txt:
+	case ns_t_spf:
 		while (rdata < edata) {
 			T(len = charstr(rdata, edata, &buf, &buflen));
 			if (len == 0)
@@ -334,7 +336,7 @@
 	case ns_t_aaaa:
 		if (rdlen != (size_t)NS_IN6ADDRSZ)
 			goto formerr;
-		(void) inet_ntop(AF_INET6, rdata, buf, buflen);
+		(void) inet_ntop(AF_INET6, rdata, buf, (socklen_t)buflen);
 		addlen(strlen(buf), &buf, &buflen);
 		break;
 
@@ -425,7 +427,7 @@
 			goto formerr;
 
 		/* Address. */
-		(void) inet_ntop(AF_INET, rdata, buf, buflen);
+		(void) inet_ntop(AF_INET, rdata, buf, (socklen_t)buflen);
 		addlen(strlen(buf), &buf, &buflen);
 		rdata += NS_INADDRSZ;
 
@@ -459,7 +461,8 @@
 		break;
 	    }
 
-	case ns_t_key: {
+	case ns_t_key:
+	case ns_t_dnskey: {
 		char base64_key[NS_MD5RSA_MAX_BASE64];
 		u_int keyflags, protocol, algorithm, key_id;
 		const char *leader;
@@ -505,7 +508,8 @@
 		break;
 	    }
 
-	case ns_t_sig: {
+	case ns_t_sig:
+	case ns_t_rrsig: {
 		char base64_key[NS_MD5RSA_MAX_BASE64];
 		u_int typ, algorithm, labels, footprint;
 		const char *leader;
@@ -566,7 +570,7 @@
 	    }
 
 	case ns_t_nxt: {
-		int n, c;
+		ptrdiff_t n, c;
 
 		/* Next domain name. */
 		T(addname(msg, msglen, &rdata, origin, &buf, &buflen));
@@ -575,7 +579,7 @@
 		n = edata - rdata;
 		for (c = 0; c < n*8; c++)
 			if (NS_NXT_BIT_ISSET(c, rdata)) {
-				len = SPRINTF((tmp, " %s", p_type(c)));
+				len = SPRINTF((tmp, " %s", p_type((int)c)));
 				T(addstr(tmp, (size_t)len, &buf, &buflen));
 			}
 		break;
@@ -584,7 +588,7 @@
 	case ns_t_cert: {
 		u_int c_type, key_tag, alg;
 		int n;
-		unsigned int siz;
+		size_t siz;
 		char base64_cert[8192], tmp1[40];
 		const char *leader;
 
@@ -690,7 +694,7 @@
 			if (rdata + pbyte >= edata) goto formerr;
 			memset(&a, 0, sizeof(a));
 			memcpy(&a.s6_addr[pbyte], rdata, sizeof(a) - pbyte);
-			(void) inet_ntop(AF_INET6, &a, buf, buflen);
+			(void) inet_ntop(AF_INET6, &a, buf, (socklen_t)buflen);
 			addlen(strlen(buf), &buf, &buflen);
 			rdata += sizeof(a) - pbyte;
 		}
@@ -711,25 +715,368 @@
 		break;
 	    }
 
+	case ns_t_ds:
+	case ns_t_dlv:
+	case ns_t_sshfp: {
+		u_int t;
+
+		if (type == ns_t_ds || type == ns_t_dlv) {
+			if (rdlen < 4U) goto formerr;
+			t = ns_get16(rdata);
+			rdata += NS_INT16SZ;
+			len = SPRINTF((tmp, "%u ", t));
+			T(addstr(tmp, (size_t)len, &buf, &buflen));
+		} else
+			if (rdlen < 2U) goto formerr;
+
+		len = SPRINTF((tmp, "%u ", *rdata));
+		T(addstr(tmp, (size_t)len, &buf, &buflen));
+		rdata++;
+
+		len = SPRINTF((tmp, "%u ", *rdata));
+		T(addstr(tmp, (size_t)len, &buf, &buflen));
+		rdata++;
+
+		while (rdata < edata) {
+			len = SPRINTF((tmp, "%02X", *rdata));
+			T(addstr(tmp, (size_t)len, &buf, &buflen));
+			rdata++;
+		}
+		break;
+	    }
+
+	case ns_t_nsec3:
+	case ns_t_nsec3param: {
+		u_int t, w, l, j, k, c;
+
+		len = SPRINTF((tmp, "%u ", *rdata));
+		T(addstr(tmp, (size_t)len, &buf, &buflen));
+		rdata++;
+
+		len = SPRINTF((tmp, "%u ", *rdata));
+		T(addstr(tmp, (size_t)len, &buf, &buflen));
+		rdata++;
+
+		t = ns_get16(rdata);
+		rdata += NS_INT16SZ;
+		len = SPRINTF((tmp, "%u ", t));
+		T(addstr(tmp, (size_t)len, &buf, &buflen));
+
+		t = *rdata++;
+		if (t == 0) {
+			T(addstr("-", 1, &buf, &buflen));
+		} else {
+			while (t-- > 0) {
+				len = SPRINTF((tmp, "%02X", *rdata));
+				T(addstr(tmp, (size_t)len, &buf, &buflen));
+				rdata++;
+			}
+		}
+		if (type == ns_t_nsec3param)
+			break;
+		T(addstr(" ", 1, &buf, &buflen));
+
+		t = *rdata++;
+		while (t > 0) {
+			switch (t) {
+			case 1:
+				tmp[0] = base32hex[(((uint32_t)rdata[0]>>3)&0x1f)];
+				tmp[1] = base32hex[(((uint32_t)rdata[0]<<2)&0x1c)];
+				tmp[2] = tmp[3] = tmp[4] = '=';
+				tmp[5] = tmp[6] = tmp[7] = '=';
+				break;
+			case 2:
+				tmp[0] = base32hex[(((uint32_t)rdata[0]>>3)&0x1f)];
+				tmp[1] = base32hex[(((uint32_t)rdata[0]<<2)&0x1c)|
+						   (((uint32_t)rdata[1]>>6)&0x03)];
+				tmp[2] = base32hex[(((uint32_t)rdata[1]>>1)&0x1f)];
+				tmp[3] = base32hex[(((uint32_t)rdata[1]<<4)&0x10)];
+				tmp[4] = tmp[5] = tmp[6] = tmp[7] = '=';
+				break;
+			case 3:
+				tmp[0] = base32hex[(((uint32_t)rdata[0]>>3)&0x1f)];
+				tmp[1] = base32hex[(((uint32_t)rdata[0]<<2)&0x1c)|
+						   (((uint32_t)rdata[1]>>6)&0x03)];
+				tmp[2] = base32hex[(((uint32_t)rdata[1]>>1)&0x1f)];
+				tmp[3] = base32hex[(((uint32_t)rdata[1]<<4)&0x10)|
+						   (((uint32_t)rdata[2]>>4)&0x0f)];
+				tmp[4] = base32hex[(((uint32_t)rdata[2]<<1)&0x1e)];
+				tmp[5] = tmp[6] = tmp[7] = '=';
+				break;
+			case 4:
+				tmp[0] = base32hex[(((uint32_t)rdata[0]>>3)&0x1f)];
+				tmp[1] = base32hex[(((uint32_t)rdata[0]<<2)&0x1c)|
+						   (((uint32_t)rdata[1]>>6)&0x03)];
+				tmp[2] = base32hex[(((uint32_t)rdata[1]>>1)&0x1f)];
+				tmp[3] = base32hex[(((uint32_t)rdata[1]<<4)&0x10)|
+						   (((uint32_t)rdata[2]>>4)&0x0f)];
+				tmp[4] = base32hex[(((uint32_t)rdata[2]<<1)&0x1e)|
+						   (((uint32_t)rdata[3]>>7)&0x01)];
+				tmp[5] = base32hex[(((uint32_t)rdata[3]>>2)&0x1f)];
+				tmp[6] = base32hex[((uint32_t)rdata[3]<<3)&0x18];
+				tmp[7] = '=';
+				break;
+			default:
+				tmp[0] = base32hex[(((uint32_t)rdata[0]>>3)&0x1f)];
+				tmp[1] = base32hex[(((uint32_t)rdata[0]<<2)&0x1c)|
+						   (((uint32_t)rdata[1]>>6)&0x03)];
+				tmp[2] = base32hex[(((uint32_t)rdata[1]>>1)&0x1f)];
+				tmp[3] = base32hex[(((uint32_t)rdata[1]<<4)&0x10)|
+						   (((uint32_t)rdata[2]>>4)&0x0f)];
+				tmp[4] = base32hex[(((uint32_t)rdata[2]<<1)&0x1e)|
+						   (((uint32_t)rdata[3]>>7)&0x01)];
+				tmp[5] = base32hex[(((uint32_t)rdata[3]>>2)&0x1f)];
+				tmp[6] = base32hex[(((uint32_t)rdata[3]<<3)&0x18)|
+						   (((uint32_t)rdata[4]>>5)&0x07)];
+				tmp[7] = base32hex[(rdata[4]&0x1f)];
+				break;
+			}
+			T(addstr(tmp, 8, &buf, &buflen));
+			if (t >= 5) {
+				rdata += 5;
+				t -= 5;
+			} else {
+				rdata += t;
+				t -= t;
+			}
+		}
+
+		while (rdata < edata) {
+			w = *rdata++;
+			l = *rdata++;
+			for (j = 0; j < l; j++) {
+				if (rdata[j] == 0)
+					continue;
+				for (k = 0; k < 8; k++) {
+					if ((rdata[j] & (0x80 >> k)) == 0)
+						continue;
+					c = w * 256 + j * 8 + k;
+					len = SPRINTF((tmp, " %s", p_type((ns_type)c)));
+					T(addstr(tmp, (size_t)len, &buf, &buflen));
+				}
+			}
+			rdata += l;
+		}
+		break;
+	    }
+
+	case ns_t_nsec: {
+		u_int w, l, j, k, c;
+
+		T(addname(msg, msglen, &rdata, origin, &buf, &buflen));
+
+		while (rdata < edata) {
+			w = *rdata++;
+			l = *rdata++;
+			for (j = 0; j < l; j++) {
+				if (rdata[j] == 0)
+					continue;
+				for (k = 0; k < 8; k++) {
+					if ((rdata[j] & (0x80 >> k)) == 0)
+						continue;
+					c = w * 256 + j * 8 + k;
+					len = SPRINTF((tmp, " %s", p_type((ns_type)c)));
+					T(addstr(tmp, (size_t)len, &buf, &buflen));
+				}
+			}
+			rdata += l;
+		}
+		break;
+	    }
+
+	case ns_t_dhcid: {
+		int n;
+		unsigned int siz;
+		char base64_dhcid[8192];
+		const char *leader;
+
+		siz = (int)(edata-rdata)*4/3 + 4; /* "+4" accounts for trailing \0 */
+		if (siz > sizeof(base64_dhcid) * 3/4) {
+			const char *str = "record too long to print";
+			T(addstr(str, strlen(str), &buf, &buflen));
+		} else {
+			len = b64_ntop(rdata, (size_t)(edata-rdata),
+			    base64_dhcid, siz);
+
+			if (len < 0)
+				goto formerr;
+
+			else if (len > 15) {
+				T(addstr(" (", 2, &buf, &buflen));
+				leader = "\n\t\t";
+				spaced = 0;
+			}
+			else
+				leader = " ";
+
+			for (n = 0; n < len; n += 48) {
+				T(addstr(leader, strlen(leader),
+					 &buf, &buflen));
+				T(addstr(base64_dhcid + n,
+				    (size_t)MIN(len - n, 48), &buf, &buflen));
+			}
+			if (len > 15)
+				T(addstr(" )", 2, &buf, &buflen));
+		}
+		break;
+	}
+
+	case ns_t_ipseckey: {
+		int n;
+		unsigned int siz;
+		char base64_key[8192];
+		const char *leader;
+
+		if (rdlen < 2)
+			goto formerr;
+
+		switch (rdata[1]) {
+		case 0:
+		case 3:
+			if (rdlen < 3)
+				goto formerr;
+			break;
+		case 1:
+			if (rdlen < 7)
+				goto formerr;
+			break;
+		case 2:
+			if (rdlen < 19)
+				goto formerr;
+			break;
+		default:
+			comment = "unknown IPSECKEY gateway type";
+			goto hexify;
+		}
+
+		len = SPRINTF((tmp, "%u ", *rdata));
+		T(addstr(tmp, (size_t)len, &buf, &buflen));
+		rdata++;
+
+		len = SPRINTF((tmp, "%u ", *rdata));
+		T(addstr(tmp, (size_t)len, &buf, &buflen));
+		rdata++;
+
+		len = SPRINTF((tmp, "%u ", *rdata));
+		T(addstr(tmp, (size_t)len, &buf, &buflen));
+		rdata++;
+
+		switch (rdata[-2]) {
+		case 0:
+			T(addstr(".", 1, &buf, &buflen));
+			break;
+		case 1:
+			(void) inet_ntop(AF_INET, rdata, buf, (socklen_t)buflen);
+			addlen(strlen(buf), &buf, &buflen);
+			rdata += 4;
+			break;
+		case 2:
+			(void) inet_ntop(AF_INET6, rdata, buf, (socklen_t)buflen);
+			addlen(strlen(buf), &buf, &buflen);
+			rdata += 16;
+			break;
+		case 3:
+			T(addname(msg, msglen, &rdata, origin, &buf, &buflen));
+			break;
+		}
+
+		if (rdata >= edata)
+			break;
+
+		siz = (int)(edata-rdata)*4/3 + 4; /* "+4" accounts for trailing \0 */
+		if (siz > sizeof(base64_key) * 3/4) {
+			const char *str = "record too long to print";
+			T(addstr(str, strlen(str), &buf, &buflen));
+		} else {
+			len = b64_ntop(rdata, (size_t)(edata-rdata),
+			    base64_key, siz);
+
+			if (len < 0)
+				goto formerr;
+
+			else if (len > 15) {
+				T(addstr(" (", 2, &buf, &buflen));
+				leader = "\n\t\t";
+				spaced = 0;
+			}
+			else
+				leader = " ";
+
+			for (n = 0; n < len; n += 48) {
+				T(addstr(leader, strlen(leader),
+					 &buf, &buflen));
+				T(addstr(base64_key + n,
+				    (size_t)MIN(len - n, 48), &buf, &buflen));
+			}
+			if (len > 15)
+				T(addstr(" )", 2, &buf, &buflen));
+		}
+		break;
+	}
+
+	case ns_t_hip: {
+		unsigned int i, hip_len, algorithm, key_len;
+		char base64_key[NS_MD5RSA_MAX_BASE64];
+		unsigned int siz;
+		const char *leader = "\n\t\t\t\t\t";
+
+		hip_len = *rdata++;
+		algorithm = *rdata++;
+		key_len = ns_get16(rdata);
+		rdata += NS_INT16SZ;
+
+		siz = key_len*4/3 + 4; /* "+4" accounts for trailing \0 */
+		if (siz > sizeof(base64_key) * 3/4) {
+			const char *str = "record too long to print";
+			T(addstr(str, strlen(str), &buf, &buflen));
+		} else {
+			len = sprintf(tmp, "( %u ", algorithm);
+			T(addstr(tmp, (size_t)len, &buf, &buflen));
+
+			for (i = 0; i < hip_len; i++) {
+				len = sprintf(tmp, "%02X", *rdata);
+				T(addstr(tmp, (size_t)len, &buf, &buflen));
+				rdata++;
+			}
+			T(addstr(leader, strlen(leader), &buf, &buflen));
+
+			len = b64_ntop(rdata, key_len, base64_key, siz);
+			if (len < 0)
+				goto formerr;
+
+			T(addstr(base64_key, (size_t)len, &buf, &buflen));
+
+			rdata += key_len;
+			while (rdata < edata) {
+				T(addstr(leader, strlen(leader), &buf, &buflen));
+				T(addname(msg, msglen, &rdata, origin,
+					  &buf, &buflen));
+			}
+			T(addstr(" )", 2, &buf, &buflen));
+		}
+		break;
+	    }
+
 	default:
 		comment = "unknown RR type";
 		goto hexify;
 	}
-	return (buf - obuf);
+	_DIAGASSERT(__type_fit(int, buf - obuf));
+	return (int)(buf - obuf);
  formerr:
 	comment = "RR format error";
  hexify: {
 	int n, m;
 	char *p;
 
-	len = SPRINTF((tmp, "\\# %tu%s\t; %s", edata - rdata,
-		       rdlen != 0 ? " (" : "", comment));
+	len = SPRINTF((tmp, "\\# %u%s\t; %s", (unsigned)(edata - rdata),
+		       rdlen != 0U ? " (" : "", comment));
 	T(addstr(tmp, (size_t)len, &buf, &buflen));
 	while (rdata < edata) {
 		p = tmp;
 		p += SPRINTF((p, "\n\t"));
 		spaced = 0;
-		n = MIN(16, edata - rdata);
+		n = MIN(16, (int)(edata - rdata));
 		for (m = 0; m < n; m++)
 			p += SPRINTF((p, "%02x ", rdata[m]));
 		T(addstr(tmp, (size_t)(p - tmp), &buf, &buflen));
@@ -746,7 +1093,8 @@
 		T(addstr(tmp, (size_t)(p - tmp), &buf, &buflen));
 		rdata += n;
 	}
-	return (buf - obuf);
+	_DIAGASSERT(__type_fit(int, buf - obuf));
+	return (int)(buf - obuf);
     }
 }
 
@@ -822,7 +1170,8 @@
 	}
 	if (addstr("\"", (size_t)1, buf, buflen) < 0)
 		goto enospc;
-	return (rdata - odata);
+	_DIAGASSERT(__type_fit(int, rdata - odata));
+	return (int)(rdata - odata);
  enospc:
 	errno = ENOSPC;
 	*buf = save_buf;
@@ -866,7 +1215,8 @@
 	*pp += n;
 	addlen(newlen, buf, buflen);
 	**buf = '\0';
-	return (newlen);
+	_DIAGASSERT(__type_fit(int, newlen));
+	return (int)newlen;
  enospc:
 	errno = ENOSPC;
 	*buf = save_buf;
@@ -897,7 +1247,7 @@
 addtab(size_t len, size_t target, int spaced, char **buf, size_t *buflen) {
 	size_t save_buflen = *buflen;
 	char *save_buf = *buf;
-	int t;
+	ptrdiff_t t;
 
 	if (spaced || len >= target - 1) {
 		T(addstr("  ", (size_t)2, buf, buflen));
diff --git a/libc/dns/nameser/ns_samedomain.c b/libc/dns/nameser/ns_samedomain.c
index d35dfe1..0be0c28 100644
--- a/libc/dns/nameser/ns_samedomain.c
+++ b/libc/dns/nameser/ns_samedomain.c
@@ -1,4 +1,4 @@
-/*	$NetBSD: ns_samedomain.c,v 1.2 2004/05/20 20:35:05 christos Exp $	*/
+/*	$NetBSD: ns_samedomain.c,v 1.8 2012/11/22 20:22:31 christos Exp $	*/
 
 /*
  * Copyright (c) 2004 by Internet Systems Consortium, Inc. ("ISC")
@@ -20,9 +20,9 @@
 #include <sys/cdefs.h>
 #ifndef lint
 #ifdef notdef
-static const char rcsid[] = "Id: ns_samedomain.c,v 1.1.2.2.4.2 2004/03/16 12:34:17 marka Exp";
+static const char rcsid[] = "Id: ns_samedomain.c,v 1.6 2005/04/27 04:56:40 sra Exp";
 #else
-__RCSID("$NetBSD: ns_samedomain.c,v 1.2 2004/05/20 20:35:05 christos Exp $");
+__RCSID("$NetBSD: ns_samedomain.c,v 1.8 2012/11/22 20:22:31 christos Exp $");
 #endif
 #endif
 
@@ -31,16 +31,17 @@
 #include <errno.h>
 #include <string.h>
 
-#ifndef _LIBC
+#ifdef _LIBRESOLV
 /*
- * int
- * ns_samedomain(a, b)
  *	Check whether a name belongs to a domain.
+ *
  * Inputs:
  *	a - the domain whose ancestory is being verified
  *	b - the potential ancestor we're checking against
+ *
  * Return:
  *	boolean - is a at or below b?
+ *
  * Notes:
  *	Trailing dots are first removed from name and domain.
  *	Always compare complete subdomains, not only whether the
@@ -52,8 +53,8 @@
 
 int
 ns_samedomain(const char *a, const char *b) {
-	size_t la, lb;
-	int diff, i, escaped;
+	size_t la, lb, i;
+	int diff, escaped;
 	const char *cp;
 
 	la = strlen(a);
@@ -63,8 +64,8 @@
 	if (la != 0U && a[la - 1] == '.') {
 		escaped = 0;
 		/* Note this loop doesn't get executed if la==1. */
-		for (i = la - 2; i >= 0; i--)
-			if (a[i] == '\\') {
+		for (i = la - 1; i > 0; i--)
+			if (a[i - 1] == '\\') {
 				if (escaped)
 					escaped = 0;
 				else
@@ -79,8 +80,8 @@
 	if (lb != 0U && b[lb - 1] == '.') {
 		escaped = 0;
 		/* note this loop doesn't get executed if lb==1 */
-		for (i = lb - 2; i >= 0; i--)
-			if (b[i] == '\\') {
+		for (i = lb - 1; i > 0; i--)
+			if (b[i - 1] == '\\') {
 				if (escaped)
 					escaped = 0;
 				else
@@ -105,7 +106,7 @@
 
 	/* Ok, we know la > lb. */
 
-	diff = la - lb;
+	diff = (int)(la - lb);
 
 	/*
 	 * If 'a' is only 1 character longer than 'b', then it can't be
@@ -128,8 +129,8 @@
          * and thus not a really a label separator.
 	 */
 	escaped = 0;
-	for (i = diff - 2; i >= 0; i--)
-		if (a[i] == '\\') {
+	for (i = diff - 1; i > 0; i--)
+		if (a[i - 1] == '\\') {
 			if (escaped)
 				escaped = 0;
 			else
@@ -145,8 +146,6 @@
 }
 
 /*
- * int
- * ns_subdomain(a, b)
  *	is "a" a subdomain of "b"?
  */
 int
@@ -155,10 +154,10 @@
 }
 #endif
 
+#ifdef _LIBC
 /*
- * int
- * ns_makecanon(src, dst, dstsize)
  *	make a canonical copy of domain name "src"
+ *
  * notes:
  *	foo -> foo.
  *	foo. -> foo.
@@ -188,9 +187,8 @@
 }
 
 /*
- * int
- * ns_samename(a, b)
  *	determine whether domain name "a" is the same as domain name "b"
+ *
  * return:
  *	-1 on error
  *	0 if names differ
@@ -209,3 +207,4 @@
 	else
 		return (0);
 }
+#endif
diff --git a/libc/dns/nameser/ns_ttl.c b/libc/dns/nameser/ns_ttl.c
index 1ad3b49..2395b99 100644
--- a/libc/dns/nameser/ns_ttl.c
+++ b/libc/dns/nameser/ns_ttl.c
@@ -1,4 +1,4 @@
-/*	$NetBSD: ns_ttl.c,v 1.2 2004/05/20 20:35:05 christos Exp $	*/
+/*	$NetBSD: ns_ttl.c,v 1.8 2012/03/13 21:13:39 christos Exp $	*/
 
 /*
  * Copyright (c) 2004 by Internet Systems Consortium, Inc. ("ISC")
@@ -20,9 +20,9 @@
 #include <sys/cdefs.h>
 #ifndef lint
 #ifdef notdef
-static const char rcsid[] = "Id: ns_ttl.c,v 1.1.206.1 2004/03/09 08:33:45 marka Exp";
+static const char rcsid[] = "Id: ns_ttl.c,v 1.4 2005/07/28 06:51:49 marka Exp";
 #else
-__RCSID("$NetBSD: ns_ttl.c,v 1.2 2004/05/20 20:35:05 christos Exp $");
+__RCSID("$NetBSD: ns_ttl.c,v 1.8 2012/03/13 21:13:39 christos Exp $");
 #endif
 #endif
 
@@ -30,6 +30,7 @@
 
 #include <arpa/nameser.h>
 
+#include <assert.h>
 #include <ctype.h>
 #include <errno.h>
 #include <stdio.h>
@@ -57,11 +58,11 @@
 	int secs, mins, hours, days, weeks, x;
 	char *p;
 
-	secs = src % 60;   src /= 60;
-	mins = src % 60;   src /= 60;
-	hours = src % 24;  src /= 24;
-	days = src % 7;    src /= 7;
-	weeks = src;       src = 0;
+	secs = (int)(src % 60);   src /= 60;
+	mins = (int)(src % 60);   src /= 60;
+	hours = (int)(src % 24);  src /= 24;
+	days = (int)(src % 7);    src /= 7;
+	weeks = (int)src;       src = 0;
 
 	x = 0;
 	if (weeks) {
@@ -93,7 +94,8 @@
 				*p = tolower(ch);
 	}
 
-	return (dst - odst);
+	_DIAGASSERT(__type_fit(int, dst - odst));
+	return (int)(dst - odst);
 }
 
 #ifndef _LIBC
@@ -137,7 +139,8 @@
 			goto einval;
 		else
 			ttl += tmp;
-	}
+	} else if (!dirty)
+		goto einval;
 	*dst = ttl;
 	return (0);
 
diff --git a/libc/include/arpa/nameser.h b/libc/include/arpa/nameser.h
index c339db3..a87ac91 100644
--- a/libc/include/arpa/nameser.h
+++ b/libc/include/arpa/nameser.h
@@ -1,4 +1,21 @@
-/*	$NetBSD: nameser.h,v 1.19 2005/12/26 19:01:47 perry Exp $	*/
+/*	$NetBSD: nameser.h,v 1.25 2009/04/12 17:07:34 christos Exp $	*/
+
+/*
+ * Portions Copyright (C) 2004, 2005, 2008, 2009  Internet Systems Consortium, Inc. ("ISC")
+ * Portions Copyright (C) 1996-2003  Internet Software Consortium.
+ *
+ * Permission to use, copy, modify, and/or distribute this software for any
+ * purpose with or without fee is hereby granted, provided that the above
+ * copyright notice and this permission notice appear in all copies.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
+ * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS.  IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
+ * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
+ * LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
+ * OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
+ * PERFORMANCE OF THIS SOFTWARE.
+ */
 
 /*
  * Copyright (c) 1983, 1989, 1993
@@ -30,24 +47,7 @@
  */
 
 /*
- * Copyright (c) 2004 by Internet Systems Consortium, Inc. ("ISC")
- * Copyright (c) 1996-1999 by Internet Software Consortium.
- *
- * Permission to use, copy, modify, and distribute this software for any
- * purpose with or without fee is hereby granted, provided that the above
- * copyright notice and this permission notice appear in all copies.
- *
- * THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES
- * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS.  IN NO EVENT SHALL ISC BE LIABLE FOR
- * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
- * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
- * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
- * OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
- */
-
-/*
- *	Id: nameser.h,v 1.2.2.4.4.1 2004/03/09 08:33:30 marka Exp
+ *	Id: nameser.h,v 1.16 2009/03/03 01:52:48 each Exp
  */
 
 #ifndef _ARPA_NAMESER_H_
@@ -66,16 +66,19 @@
  * contains a new enough lib/nameser/ to support the feature you need.
  */
 
-#define __NAMESER	19991006	/* New interface version stamp. */
+#define __NAMESER	20090302	/*%< New interface version stamp. */
 
 /*
- * Define constants based on RFC 883, RFC 1034, RFC 1035
+ * Define constants based on RFC0883, RFC1034, RFC 1035
  */
 #define NS_PACKETSZ	512	/* default UDP packet size */
-#define NS_MAXDNAME	1025	/* maximum domain name */
+#define NS_MAXDNAME	1025	/* maximum domain name (presentation format)*/
 #define NS_MAXMSG	65535	/* maximum message size */
 #define NS_MAXCDNAME	255	/* maximum compressed domain name */
 #define NS_MAXLABEL	63	/* maximum length of domain label */
+#define NS_MAXLABELS	128	/* theoretical max #/labels per domain name */
+#define NS_MAXNNAME	256	/* maximum uncompressed (binary) domain name*/
+#define	NS_MAXPADDR	(sizeof "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff")
 #define NS_HFIXEDSZ	12	/* #/bytes of fixed data in header */
 #define NS_QFIXEDSZ	4	/* #/bytes of fixed data in query */
 #define NS_RRFIXEDSZ	10	/* #/bytes of fixed data in r record */
@@ -103,6 +106,18 @@
 } ns_sect;
 
 /*
+ * Network name (compressed or not) type.  Equivilent to a pointer when used
+ * in a function prototype.  Can be const'd.
+ */
+typedef u_char ns_nname[NS_MAXNNAME];
+typedef const u_char *ns_nname_ct;
+typedef u_char *ns_nname_t;
+
+struct ns_namemap { ns_nname_ct base; int len; };
+typedef struct ns_namemap *ns_namemap_t;
+typedef const struct ns_namemap *ns_namemap_ct;
+
+/*
  * This is a message handle.  It is caller allocated and has no dynamic data.
  * This structure is intended to be opaque to all but ns_parse.c, thus the
  * leading _'s on the member names.  Use the accessor functions, not the _'s.
@@ -115,6 +130,16 @@
 	int		_rrnum;
 	const u_char	*_msg_ptr;
 } ns_msg;
+/*
+ * This is a newmsg handle, used when constructing new messages with
+ * ns_newmsg_init, et al.
+ */
+struct ns_newmsg {
+	ns_msg		msg;
+	const u_char	*dnptrs[25];
+	const u_char	**lastdnptr;
+};
+typedef struct ns_newmsg ns_newmsg;
 
 /* Private data structure - do not use from outside library. */
 struct _ns_flagdata {  int mask, shift;  };
@@ -140,8 +165,22 @@
 	const u_char *	rdata;
 } ns_rr;
 
+/*
+ * Same thing, but using uncompressed network binary names, and real C types.
+ */
+typedef	struct __ns_rr2 {
+	ns_nname	nname;
+	size_t		nnamel;
+	int		type;
+	int		rr_class;
+	u_int		ttl;
+	int		rdlength;
+	const u_char *	rdata;
+} ns_rr2;
 /* Accessor macros - this is part of the public interface. */
 #define ns_rr_name(rr)	(((rr).name[0] != '\0') ? (rr).name : ".")
+#define ns_rr_nname(rr)	((const ns_nname_t)(rr).nname)
+#define ns_rr_nnamel(rr) ((rr).nnamel + 0)
 #define ns_rr_type(rr)	((ns_type)((rr).type + 0))
 #define ns_rr_class(rr)	((ns_class)((rr).rr_class + 0))
 #define ns_rr_ttl(rr)	((u_long)(rr).ttl + 0)
@@ -274,7 +313,7 @@
 	ns_t_key = 25,		/* Security key. */
 	ns_t_px = 26,		/* X.400 mail mapping. */
 	ns_t_gpos = 27,		/* Geographical position (withdrawn). */
-	ns_t_aaaa = 28,		/* Ip6 Address. */
+	ns_t_aaaa = 28,		/* IPv6 Address. */
 	ns_t_loc = 29,		/* Location Information. */
 	ns_t_nxt = 30,		/* Next domain (security). */
 	ns_t_eid = 31,		/* Endpoint identifier. */
@@ -284,11 +323,22 @@
 	ns_t_naptr = 35,	/* Naming Authority PoinTeR */
 	ns_t_kx = 36,		/* Key Exchange */
 	ns_t_cert = 37,		/* Certification record */
-	ns_t_a6 = 38,		/* IPv6 address (deprecates AAAA) */
-	ns_t_dname = 39,	/* Non-terminal DNAME (for IPv6) */
+	ns_t_a6 = 38,		/* IPv6 address (experimental) */
+	ns_t_dname = 39,	/* Non-terminal DNAME */
 	ns_t_sink = 40,		/* Kitchen sink (experimentatl) */
 	ns_t_opt = 41,		/* EDNS0 option (meta-RR) */
 	ns_t_apl = 42,		/* Address prefix list (RFC 3123) */
+	ns_t_ds = 43,		/* Delegation Signer */
+	ns_t_sshfp = 44,	/* SSH Fingerprint */
+	ns_t_ipseckey = 45,	/* IPSEC Key */
+	ns_t_rrsig = 46,	/* RRset Signature */
+	ns_t_nsec = 47,		/* Negative security */
+	ns_t_dnskey = 48,	/* DNS Key */
+	ns_t_dhcid = 49,	/* Dynamic host configuratin identifier */
+	ns_t_nsec3 = 50,	/* Negative security type 3 */
+	ns_t_nsec3param = 51,	/* Negative security type 3 parameters */
+	ns_t_hip = 55,		/* Host Identity Protocol */
+	ns_t_spf = 99,		/* Sender Policy Framework */
 	ns_t_tkey = 249,	/* Transaction key */
 	ns_t_tsig = 250,	/* Transaction signature. */
 	ns_t_ixfr = 251,	/* Incremental zone transfer. */
@@ -297,6 +347,7 @@
 	ns_t_maila = 254,	/* Transfer mail agent records. */
 	ns_t_any = 255,		/* Wildcard match. */
 	ns_t_zxfr = 256,	/* BIND-specific, nonstandard. */
+	ns_t_dlv = 32769,	/* DNSSEC look-aside validatation. */
 	ns_t_max = 65536
 } ns_type;
 
@@ -423,9 +474,10 @@
 #define NS_NXT_MAX 127
 
 /*
- * EDNS0 extended flags, host order.
+ * EDNS0 extended flags and option codes, host order.
  */
 #define NS_OPT_DNSSEC_OK	0x8000U
+#define NS_OPT_NSID             3
 
 /*
  * Inline versions of get/put short/long.  Pointer is advanced.
@@ -477,6 +529,7 @@
 #define ns_initparse		__ns_initparse
 #define ns_skiprr		__ns_skiprr
 #define ns_parserr		__ns_parserr
+#define ns_parserr2		__ns_parserr2
 #define	ns_sprintrr		__ns_sprintrr
 #define	ns_sprintrrf		__ns_sprintrrf
 #define	ns_format_ttl		__ns_format_ttl
@@ -485,12 +538,19 @@
 #define	ns_name_ntol		__ns_name_ntol
 #define	ns_name_ntop		__ns_name_ntop
 #define	ns_name_pton		__ns_name_pton
+#define	ns_name_pton2		__ns_name_pton2
 #define	ns_name_unpack		__ns_name_unpack
+#define	ns_name_unpack2		__ns_name_unpack2
 #define	ns_name_pack		__ns_name_pack
 #define	ns_name_compress	__ns_name_compress
 #define	ns_name_uncompress	__ns_name_uncompress
 #define	ns_name_skip		__ns_name_skip
 #define	ns_name_rollback	__ns_name_rollback
+#define	ns_name_length		__ns_name_length
+#define	ns_name_eq		__ns_name_eq
+#define	ns_name_owned		__ns_name_owned
+#define	ns_name_map		__ns_name_map
+#define	ns_name_labels		__ns_name_labels
 #define	ns_sign			__ns_sign
 #define	ns_sign2		__ns_sign2
 #define	ns_sign_tcp		__ns_sign_tcp
@@ -504,6 +564,16 @@
 #define	ns_subdomain		__ns_subdomain
 #define	ns_makecanon		__ns_makecanon
 #define	ns_samename		__ns_samename
+#define	ns_newmsg_init		__ns_newmsg_init
+#define	ns_newmsg_copy		__ns_newmsg_copy
+#define	ns_newmsg_id		__ns_newmsg_id
+#define	ns_newmsg_flag		__ns_newmsg_flag
+#define	ns_newmsg_q		__ns_newmsg_q
+#define	ns_newmsg_rr		__ns_newmsg_rr
+#define	ns_newmsg_done		__ns_newmsg_done
+#define	ns_rdata_unpack		__ns_rdata_unpack
+#define	ns_rdata_equal		__ns_rdata_equal
+#define	ns_rdata_refers		__ns_rdata_refers
 
 __BEGIN_DECLS
 int		ns_msg_getflag(ns_msg, int);
@@ -514,6 +584,7 @@
 int		ns_initparse(const u_char *, int, ns_msg *);
 int		ns_skiprr(const u_char *, const u_char *, ns_sect, int);
 int		ns_parserr(ns_msg *, ns_sect, int, ns_rr *);
+int		ns_parserr2(ns_msg *, ns_sect, int, ns_rr2 *);
 int		ns_sprintrr(const ns_msg *, const ns_rr *,
 				 const char *, const char *, char *, size_t);
 int		ns_sprintrrf(const u_char *, size_t, const char *,
@@ -526,8 +597,12 @@
 int		ns_name_ntol(const u_char *, u_char *, size_t);
 int		ns_name_ntop(const u_char *, char *, size_t);
 int		ns_name_pton(const char *, u_char *, size_t);
+int		ns_name_pton2(const char *, u_char *, size_t, size_t *);
 int		ns_name_unpack(const u_char *, const u_char *,
 				    const u_char *, u_char *, size_t);
+int		ns_name_unpack2(const u_char *, const u_char *,
+				     const u_char *, u_char *, size_t,
+				     size_t *);
 int		ns_name_pack(const u_char *, u_char *, int,
 				  const u_char **, const u_char **);
 int		ns_name_uncompress(const u_char *, const u_char *,
@@ -542,6 +617,11 @@
 int		ns_sign2(u_char *, int *, int, int, void *,
 			      const u_char *, int, u_char *, int *, time_t,
 			      u_char **, u_char **);
+ssize_t		ns_name_length(ns_nname_ct, size_t);
+int		ns_name_eq(ns_nname_ct, size_t, ns_nname_ct, size_t);
+int		ns_name_owned(ns_namemap_ct, int, ns_namemap_ct, int);
+int		ns_name_map(ns_nname_ct, size_t, ns_namemap_t, int);
+int		ns_name_labels(ns_nname_ct, size_t);
 int		ns_sign_tcp(u_char *, int *, int, int,
 				 ns_tcp_tsig_state *, int);
 int		ns_sign_tcp2(u_char *, int *, int, int,
@@ -560,17 +640,29 @@
 int		ns_subdomain(const char *, const char *);
 int		ns_makecanon(const char *, char *, size_t);
 int		ns_samename(const char *, const char *);
+int		ns_newmsg_init(u_char *buffer, size_t bufsiz, ns_newmsg *);
+int		ns_newmsg_copy(ns_newmsg *, ns_msg *);
+void		ns_newmsg_id(ns_newmsg *handle, uint16_t id);
+void		ns_newmsg_flag(ns_newmsg *handle, ns_flag flag, u_int value);
+int		ns_newmsg_q(ns_newmsg *handle, ns_nname_ct qname,
+			    ns_type qtype, ns_class qclass);
+int		ns_newmsg_rr(ns_newmsg *handle, ns_sect sect,
+			     ns_nname_ct name, ns_type type,
+			     ns_class rr_class, uint32_t ttl,
+			     uint16_t rdlen, const u_char *rdata);
+size_t		ns_newmsg_done(ns_newmsg *handle);
+ssize_t		ns_rdata_unpack(const u_char *, const u_char *, ns_type,
+				const u_char *, size_t, u_char *, size_t);
+int		ns_rdata_equal(ns_type,
+			       const u_char *, size_t,
+			       const u_char *, size_t);
+int		ns_rdata_refers(ns_type,
+				const u_char *, size_t,
+				const u_char *);
 __END_DECLS
 
 #ifdef BIND_4_COMPAT
 #include <arpa/nameser_compat.h>
 #endif
 
-#if 0
-#  include "private/libc_logging.h"
-#  define XLOG(...)  __libc_format_log(ANDROID_LOG_DEBUG,"libc",__VA_ARGS__)
-#else
-#define  XLOG(...)   do {} while (0)
-#endif
-
 #endif /* !_ARPA_NAMESER_H_ */
diff --git a/libc/include/arpa/nameser_compat.h b/libc/include/arpa/nameser_compat.h
index 79bdfd0..e060f60 100644
--- a/libc/include/arpa/nameser_compat.h
+++ b/libc/include/arpa/nameser_compat.h
@@ -34,7 +34,7 @@
 
 /*
  *      from nameser.h	8.1 (Berkeley) 6/2/93
- *	Id: nameser_compat.h,v 1.1.2.3.4.2 2004/07/01 04:43:41 marka Exp
+ *	Id: nameser_compat.h,v 1.8 2006/05/19 02:33:40 marka Exp
  */
 
 #ifndef _ARPA_NAMESER_COMPAT_
@@ -48,7 +48,7 @@
 #if (BSD >= 199103)
 # include <machine/endian.h>
 #else
-#ifdef __linux
+#ifdef __linux__
 # include <endian.h>
 #else
 #define	LITTLE_ENDIAN	1234	/* least-significant byte first (vax, pc) */
@@ -57,7 +57,9 @@
 
 #if defined(vax) || defined(ns32000) || defined(sun386) || defined(i386) || \
     defined(MIPSEL) || defined(_MIPSEL) || defined(BIT_ZERO_ON_RIGHT) || \
-    defined(__alpha__) || defined(__alpha) || \
+    defined(__i386__) || defined(__i386) || defined(__amd64__) || \
+    defined(__x86_64__) || defined(MIPSEL) || defined(_MIPSEL) || \
+    defined(BIT_ZERO_ON_RIGHT) || defined(__alpha__) || defined(__alpha) || \
     (defined(__Lynx__) && defined(__x86__))
 #define BYTE_ORDER	LITTLE_ENDIAN
 #endif
diff --git a/libc/include/sys/types.h b/libc/include/sys/types.h
index 5340585..f8261f4 100644
--- a/libc/include/sys/types.h
+++ b/libc/include/sys/types.h
@@ -69,7 +69,7 @@
 typedef __uint32_t __nlink_t;
 typedef __nlink_t nlink_t;
 
-typedef int __timer_t;
+typedef void* __timer_t;
 typedef __timer_t timer_t;
 
 typedef __int32_t __suseconds_t;
diff --git a/tests/pthread_test.cpp b/tests/pthread_test.cpp
index 120bbc7..1e85a54 100644
--- a/tests/pthread_test.cpp
+++ b/tests/pthread_test.cpp
@@ -25,6 +25,8 @@
 #include <time.h>
 #include <unistd.h>
 
+#include "ScopedSignalHandler.h"
+
 TEST(pthread, pthread_key_create) {
   pthread_key_t key;
   ASSERT_EQ(0, pthread_key_create(&key, NULL));
@@ -337,14 +339,8 @@
 }
 
 TEST(pthread, pthread_kill__in_signal_handler) {
-  struct sigaction action;
-  struct sigaction original_action;
-  sigemptyset(&action.sa_mask);
-  action.sa_flags = 0;
-  action.sa_handler = pthread_kill__in_signal_handler_helper;
-  ASSERT_EQ(0, sigaction(SIGALRM, &action, &original_action));
+  ScopedSignalHandler ssh(SIGALRM, pthread_kill__in_signal_handler_helper);
   ASSERT_EQ(0, pthread_kill(pthread_self(), SIGALRM));
-  ASSERT_EQ(0, sigaction(SIGALRM, &original_action, NULL));
 }
 
 TEST(pthread, pthread_detach__no_such_thread) {
diff --git a/tests/time_test.cpp b/tests/time_test.cpp
index 869ee4b..9563c78 100644
--- a/tests/time_test.cpp
+++ b/tests/time_test.cpp
@@ -14,11 +14,14 @@
  * limitations under the License.
  */
 
-#include <sys/cdefs.h>
+#include <time.h>
+
+#include <errno.h>
 #include <features.h>
 #include <gtest/gtest.h>
+#include <signal.h>
 
-#include <time.h>
+#include "ScopedSignalHandler.h"
 
 #if defined(__BIONIC__) // mktime_tz is a bionic extension.
 #include <libc/private/bionic_time.h>
@@ -92,3 +95,208 @@
 #endif
 #endif
 }
+
+void SetTime(timer_t t, time_t value_s, time_t value_ns, time_t interval_s, time_t interval_ns) {
+  itimerspec ts;
+  ts.it_value.tv_sec = value_s;
+  ts.it_value.tv_nsec = value_ns;
+  ts.it_interval.tv_sec = interval_s;
+  ts.it_interval.tv_nsec = interval_ns;
+  ASSERT_EQ(0, timer_settime(t, TIMER_ABSTIME, &ts, NULL));
+}
+
+static void NoOpNotifyFunction(sigval_t) {
+}
+
+TEST(time, timer_create) {
+  sigevent_t se;
+  memset(&se, 0, sizeof(se));
+  se.sigev_notify = SIGEV_THREAD;
+  se.sigev_notify_function = NoOpNotifyFunction;
+  timer_t timer_id;
+  ASSERT_EQ(0, timer_create(CLOCK_MONOTONIC, &se, &timer_id));
+
+  int pid = fork();
+  ASSERT_NE(-1, pid) << strerror(errno);
+
+  if (pid == 0) {
+    // Timers are not inherited by the child.
+    ASSERT_EQ(-1, timer_delete(timer_id));
+    ASSERT_EQ(EINVAL, errno);
+    _exit(0);
+  }
+
+  int status;
+  ASSERT_EQ(pid, waitpid(pid, &status, 0));
+  ASSERT_TRUE(WIFEXITED(status));
+  ASSERT_EQ(0, WEXITSTATUS(status));
+
+  ASSERT_EQ(0, timer_delete(timer_id));
+}
+
+static int timer_create_SIGEV_SIGNAL_signal_handler_invocation_count = 0;
+static void timer_create_SIGEV_SIGNAL_signal_handler(int signal_number) {
+  ++timer_create_SIGEV_SIGNAL_signal_handler_invocation_count;
+  ASSERT_EQ(SIGUSR1, signal_number);
+}
+
+TEST(time, timer_create_SIGEV_SIGNAL) {
+  sigevent_t se;
+  memset(&se, 0, sizeof(se));
+  se.sigev_notify = SIGEV_SIGNAL;
+  se.sigev_signo = SIGUSR1;
+
+  timer_t timer_id;
+  ASSERT_EQ(0, timer_create(CLOCK_MONOTONIC, &se, &timer_id));
+
+  ScopedSignalHandler ssh(SIGUSR1, timer_create_SIGEV_SIGNAL_signal_handler);
+
+  ASSERT_EQ(0, timer_create_SIGEV_SIGNAL_signal_handler_invocation_count);
+
+  itimerspec ts;
+  ts.it_value.tv_sec =  0;
+  ts.it_value.tv_nsec = 1;
+  ts.it_interval.tv_sec = 0;
+  ts.it_interval.tv_nsec = 0;
+  ASSERT_EQ(0, timer_settime(timer_id, TIMER_ABSTIME, &ts, NULL));
+
+  usleep(500000);
+  ASSERT_EQ(1, timer_create_SIGEV_SIGNAL_signal_handler_invocation_count);
+}
+
+struct Counter {
+  volatile int value;
+  timer_t timer_id;
+  sigevent_t se;
+
+  Counter(void (*fn)(sigval_t)) : value(0) {
+    memset(&se, 0, sizeof(se));
+    se.sigev_notify = SIGEV_THREAD;
+    se.sigev_notify_function = fn;
+    se.sigev_value.sival_ptr = this;
+  }
+
+  void Create() {
+    ASSERT_EQ(0, timer_create(CLOCK_REALTIME, &se, &timer_id));
+  }
+
+  ~Counter() {
+    if (timer_delete(timer_id) != 0) {
+      abort();
+    }
+  }
+
+  static void CountNotifyFunction(sigval_t value) {
+    Counter* cd = reinterpret_cast<Counter*>(value.sival_ptr);
+    ++cd->value;
+  }
+
+  static void CountAndDisarmNotifyFunction(sigval_t value) {
+    Counter* cd = reinterpret_cast<Counter*>(value.sival_ptr);
+    ++cd->value;
+
+    // Setting the initial expiration time to 0 disarms the timer.
+    SetTime(cd->timer_id, 0, 0, 1, 0);
+  }
+};
+
+TEST(time, timer_settime_0) {
+  Counter counter(Counter::CountAndDisarmNotifyFunction);
+  counter.Create();
+
+  ASSERT_EQ(0, counter.value);
+
+  SetTime(counter.timer_id, 0, 1, 1, 0);
+  usleep(500000);
+
+  // The count should just be 1 because we disarmed the timer the first time it fired.
+  ASSERT_EQ(1, counter.value);
+}
+
+TEST(time, timer_settime_repeats) {
+  Counter counter(Counter::CountNotifyFunction);
+  counter.Create();
+
+  ASSERT_EQ(0, counter.value);
+
+  SetTime(counter.timer_id, 0, 1, 0, 10);
+  usleep(500000);
+
+  // The count should just be > 1 because we let the timer repeat.
+  ASSERT_GT(counter.value, 1);
+}
+
+static int timer_create_NULL_signal_handler_invocation_count = 0;
+static void timer_create_NULL_signal_handler(int signal_number) {
+  ++timer_create_NULL_signal_handler_invocation_count;
+  ASSERT_EQ(SIGALRM, signal_number);
+}
+
+TEST(time, timer_create_NULL) {
+  // A NULL sigevent* is equivalent to asking for SIGEV_SIGNAL for SIGALRM.
+  timer_t timer_id;
+  ASSERT_EQ(0, timer_create(CLOCK_MONOTONIC, NULL, &timer_id));
+
+  ScopedSignalHandler ssh(SIGALRM, timer_create_NULL_signal_handler);
+
+  ASSERT_EQ(0, timer_create_NULL_signal_handler_invocation_count);
+
+  SetTime(timer_id, 0, 1, 0, 0);
+  usleep(500000);
+
+  ASSERT_EQ(1, timer_create_NULL_signal_handler_invocation_count);
+}
+
+TEST(time, timer_create_EINVAL) {
+  clockid_t invalid_clock = 16;
+
+  // A SIGEV_SIGNAL timer is easy; the kernel does all that.
+  timer_t timer_id;
+  ASSERT_EQ(-1, timer_create(invalid_clock, NULL, &timer_id));
+  ASSERT_EQ(EINVAL, errno);
+
+  // A SIGEV_THREAD timer is more interesting because we have stuff to clean up.
+  sigevent_t se;
+  memset(&se, 0, sizeof(se));
+  se.sigev_notify = SIGEV_THREAD;
+  se.sigev_notify_function = NoOpNotifyFunction;
+  ASSERT_EQ(-1, timer_create(invalid_clock, &se, &timer_id));
+  ASSERT_EQ(EINVAL, errno);
+}
+
+TEST(time, timer_delete_multiple) {
+  timer_t timer_id;
+  ASSERT_EQ(0, timer_create(CLOCK_MONOTONIC, NULL, &timer_id));
+  ASSERT_EQ(0, timer_delete(timer_id));
+  ASSERT_EQ(-1, timer_delete(timer_id));
+  ASSERT_EQ(EINVAL, errno);
+
+  sigevent_t se;
+  memset(&se, 0, sizeof(se));
+  se.sigev_notify = SIGEV_THREAD;
+  se.sigev_notify_function = NoOpNotifyFunction;
+  ASSERT_EQ(0, timer_create(CLOCK_MONOTONIC, &se, &timer_id));
+  ASSERT_EQ(0, timer_delete(timer_id));
+  ASSERT_EQ(-1, timer_delete(timer_id));
+  ASSERT_EQ(EINVAL, errno);
+}
+
+TEST(time, timer_create_multiple) {
+  Counter counter1(Counter::CountNotifyFunction);
+  counter1.Create();
+  Counter counter2(Counter::CountNotifyFunction);
+  counter2.Create();
+  Counter counter3(Counter::CountNotifyFunction);
+  counter3.Create();
+
+  ASSERT_EQ(0, counter1.value);
+  ASSERT_EQ(0, counter2.value);
+  ASSERT_EQ(0, counter3.value);
+
+  SetTime(counter2.timer_id, 0, 1, 0, 0);
+  usleep(500000);
+
+  EXPECT_EQ(0, counter1.value);
+  EXPECT_EQ(1, counter2.value);
+  EXPECT_EQ(0, counter3.value);
+}