Merge "Fixes for __cxa_finalize"
diff --git a/benchmarks/Android.mk b/benchmarks/Android.mk
index 25e2ed9..cf3d692 100644
--- a/benchmarks/Android.mk
+++ b/benchmarks/Android.mk
@@ -54,4 +54,27 @@
 LOCAL_SRC_FILES := $(benchmark_src_files)
 include $(BUILD_EXECUTABLE)
 
+ifeq ($(HOST_OS)-$(HOST_ARCH),linux-x86)
+ifeq ($(TARGET_ARCH),x86)
+LINKER = linker
+NATIVE_SUFFIX=32
+else
+LINKER = linker64
+NATIVE_SUFFIX=64
+endif
+
+bionic-benchmarks-run-on-host: bionic-benchmarks $(TARGET_OUT_EXECUTABLES)/$(LINKER) $(TARGET_OUT_EXECUTABLES)/sh
+	if [ ! -d /system -o ! -d /system/bin ]; then \
+	  echo "Attempting to create /system/bin"; \
+	  sudo mkdir -p -m 0777 /system/bin; \
+	fi
+	mkdir -p $(TARGET_OUT_DATA)/local/tmp
+	cp $(TARGET_OUT_EXECUTABLES)/$(LINKER) /system/bin
+	cp $(TARGET_OUT_EXECUTABLES)/sh /system/bin
+	ANDROID_DATA=$(TARGET_OUT_DATA) \
+	ANDROID_ROOT=$(TARGET_OUT) \
+	LD_LIBRARY_PATH=$(TARGET_OUT_SHARED_LIBRARIES) \
+		$(TARGET_OUT_EXECUTABLES)/bionic-benchmarks$(NATIVE_SUFFIX) $(BIONIC_BENCHMARKS_FLAGS)
+endif # linux-x86
+
 endif # !BUILD_TINY_ANDROID
diff --git a/benchmarks/property_benchmark.cpp b/benchmarks/property_benchmark.cpp
index 4311a1d..6d17ec7 100644
--- a/benchmarks/property_benchmark.cpp
+++ b/benchmarks/property_benchmark.cpp
@@ -15,6 +15,9 @@
  */
 
 #include "benchmark.h"
+#include <errno.h>
+#include <stdio.h>
+#include <stdlib.h>
 #include <unistd.h>
 
 #define _REALLY_INCLUDE_SYS__SYSTEM_PROPERTIES_H_
@@ -32,10 +35,17 @@
     LocalPropertyTestState(int nprops) : nprops(nprops), valid(false) {
         static const char prop_name_chars[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ.-_";
 
-        char dir_template[] = "/data/local/tmp/prop-XXXXXX";
+        const char* android_data = getenv("ANDROID_DATA");
+        if (android_data == NULL) {
+          printf("ANDROID_DATA environment variable not set\n");
+          return;
+        }
+        char dir_template[PATH_MAX];
+        snprintf(dir_template, sizeof(dir_template), "%s/local/tmp/prop-XXXXXX", android_data);
         char *dirname = mkdtemp(dir_template);
         if (!dirname) {
-            perror("making temp file for test state failed (is /data/local/tmp writable?)");
+            printf("making temp file for test state failed (is %s/local/tmp writable?): %s\n",
+                   android_data, strerror(errno));
             return;
         }
 
diff --git a/libc/Android.mk b/libc/Android.mk
index a0eb612..9b71f6a 100644
--- a/libc/Android.mk
+++ b/libc/Android.mk
@@ -214,6 +214,7 @@
     bionic/utimes.cpp \
     bionic/wait.cpp \
     bionic/wchar.cpp \
+    bionic/wctype.cpp \
 
 libc_upstream_freebsd_src_files := \
     upstream-freebsd/lib/libc/gen/ldexp.c \
@@ -222,7 +223,6 @@
     upstream-freebsd/lib/libc/stdio/fclose.c \
     upstream-freebsd/lib/libc/stdio/flags.c \
     upstream-freebsd/lib/libc/stdio/fopen.c \
-    upstream-freebsd/lib/libc/stdio/fwrite.c \
     upstream-freebsd/lib/libc/stdio/makebuf.c \
     upstream-freebsd/lib/libc/stdio/mktemp.c \
     upstream-freebsd/lib/libc/stdio/setvbuf.c \
@@ -356,6 +356,7 @@
     upstream-openbsd/lib/libc/locale/wcstoumax.c \
     upstream-openbsd/lib/libc/locale/wcsxfrm.c \
     upstream-openbsd/lib/libc/locale/wctob.c \
+    upstream-openbsd/lib/libc/locale/wctomb.c \
     upstream-openbsd/lib/libc/stdio/asprintf.c \
     upstream-openbsd/lib/libc/stdio/clrerr.c \
     upstream-openbsd/lib/libc/stdio/fdopen.c \
@@ -386,6 +387,7 @@
     upstream-openbsd/lib/libc/stdio/fwalk.c \
     upstream-openbsd/lib/libc/stdio/fwide.c \
     upstream-openbsd/lib/libc/stdio/fwprintf.c \
+    upstream-openbsd/lib/libc/stdio/fwrite.c \
     upstream-openbsd/lib/libc/stdio/fwscanf.c \
     upstream-openbsd/lib/libc/stdio/getc.c \
     upstream-openbsd/lib/libc/stdio/getchar.c \
@@ -552,6 +554,8 @@
 include $(CLEAR_VARS)
 
 LOCAL_SRC_FILES := $(call all-c-files-under,tzcode)
+# tzcode doesn't include wcsftime, so we use the OpenBSD one.
+LOCAL_SRC_FILES += upstream-openbsd/lib/libc/time/wcsftime.c
 
 LOCAL_CFLAGS := $(libc_common_cflags)
 # Don't use ridiculous amounts of stack.
@@ -567,7 +571,7 @@
 
 LOCAL_CONLYFLAGS := $(libc_common_conlyflags)
 LOCAL_CPPFLAGS := $(libc_common_cppflags)
-LOCAL_C_INCLUDES := $(libc_common_c_includes)
+LOCAL_C_INCLUDES := $(libc_common_c_includes) $(LOCAL_PATH)/tzcode/
 LOCAL_MODULE := libc_tzcode
 LOCAL_ADDITIONAL_DEPENDENCIES := $(libc_common_additional_dependencies)
 LOCAL_SYSTEM_SHARED_LIBRARIES :=
@@ -669,6 +673,7 @@
     $(libc_common_cflags) \
     -I$(LOCAL_PATH)/upstream-openbsd/android/include \
     -I$(LOCAL_PATH)/upstream-openbsd/lib/libc/include \
+    -I$(LOCAL_PATH)/upstream-openbsd/lib/libc/gdtoa/ \
     -include openbsd-compat.h
 LOCAL_CONLYFLAGS := $(libc_common_conlyflags)
 LOCAL_CPPFLAGS := $(libc_common_cppflags)
diff --git a/libc/bionic/locale.cpp b/libc/bionic/locale.cpp
index 5ab834d..3752fa4 100644
--- a/libc/bionic/locale.cpp
+++ b/libc/bionic/locale.cpp
@@ -75,8 +75,12 @@
   gLocale.int_n_sign_posn = CHAR_MAX;
 }
 
+static bool __bionic_current_locale_is_utf8 = false;
+
 static bool __is_supported_locale(const char* locale) {
-  return (strcmp(locale, "") == 0 || strcmp(locale, "C") == 0 || strcmp(locale, "POSIX") == 0);
+  return (strcmp(locale, "") == 0 ||
+          strcmp(locale, "C") == 0 || strcmp(locale, "C.UTF-8") == 0 ||
+          strcmp(locale, "POSIX") == 0);
 }
 
 static locale_t __new_locale() {
@@ -115,26 +119,24 @@
   return __new_locale();
 }
 
-char* setlocale(int category, char const* locale_name) {
+char* setlocale(int category, const char* locale_name) {
   // Is 'category' valid?
   if (category < LC_CTYPE || category > LC_IDENTIFICATION) {
     errno = EINVAL;
     return NULL;
   }
 
-  // Caller just wants to query the current locale?
-  if (locale_name == NULL) {
-    return const_cast<char*>("C");
+  // Caller wants to set the locale rather than just query?
+  if (locale_name != NULL) {
+    if (!__is_supported_locale(locale_name)) {
+      // We don't support this locale.
+      errno = ENOENT;
+      return NULL;
+    }
+    __bionic_current_locale_is_utf8 = (strstr(locale_name, "UTF-8") != NULL);
   }
 
-  // Caller wants one of the mandatory POSIX locales?
-  if (__is_supported_locale(locale_name)) {
-    return const_cast<char*>("C");
-  }
-
-  // We don't support any other locales.
-  errno = ENOENT;
-  return NULL;
+  return const_cast<char*>(__bionic_current_locale_is_utf8 ? "C.UTF-8" : "C");
 }
 
 locale_t uselocale(locale_t new_locale) {
diff --git a/libc/bionic/wchar.cpp b/libc/bionic/wchar.cpp
index badd256..b46ad49 100644
--- a/libc/bionic/wchar.cpp
+++ b/libc/bionic/wchar.cpp
@@ -1,215 +1,306 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
+/*	$OpenBSD: citrus_utf8.c,v 1.6 2012/12/05 23:19:59 deraadt Exp $ */
+
+/*-
+ * Copyright (c) 2002-2004 Tim J. Robbins
  * 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
+ * 1. 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.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * THIS SOFTWARE IS PROVIDED BY THE 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
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  * SUCH DAMAGE.
  */
 
-#include <ctype.h>
 #include <errno.h>
-#include <limits.h>
-#include <stdint.h>
-#include <stdlib.h>
 #include <string.h>
+#include <sys/param.h>
 #include <wchar.h>
 
-/* stubs for wide-char functions */
+//
+// This file is basically OpenBSD's citrus_utf8.c but rewritten to not require a 12-byte mbstate_t
+// so we're backwards-compatible with our LP32 ABI where mbstate_t was only 4 bytes. An additional
+// advantage of this is that callers who don't supply their own mbstate_t won't be accessing shared
+// state.
+//
+// We also implement the POSIX interface directly rather than being accessed via function pointers.
+//
 
-int iswalnum(wint_t wc) { return isalnum(wc); }
-int iswalpha(wint_t wc) { return isalpha(wc); }
-int iswblank(wint_t wc) { return isblank(wc); }
-int iswcntrl(wint_t wc) { return iscntrl(wc); }
-int iswdigit(wint_t wc) { return isdigit(wc); }
-int iswgraph(wint_t wc) { return isgraph(wc); }
-int iswlower(wint_t wc) { return islower(wc); }
-int iswprint(wint_t wc) { return isprint(wc); }
-int iswpunct(wint_t wc) { return ispunct(wc); }
-int iswspace(wint_t wc) { return isspace(wc); }
-int iswupper(wint_t wc) { return isupper(wc); }
-int iswxdigit(wint_t wc) { return isxdigit(wc); }
+#define ERR_ILLEGAL_SEQUENCE static_cast<size_t>(-1)
+#define ERR_INCOMPLETE_SEQUENCE static_cast<size_t>(-2)
 
-int iswctype(wint_t wc, wctype_t char_class) {
-  switch (char_class) {
-    case WC_TYPE_ALNUM: return isalnum(wc);
-    case WC_TYPE_ALPHA: return isalpha(wc);
-    case WC_TYPE_BLANK: return isblank(wc);
-    case WC_TYPE_CNTRL: return iscntrl(wc);
-    case WC_TYPE_DIGIT: return isdigit(wc);
-    case WC_TYPE_GRAPH: return isgraph(wc);
-    case WC_TYPE_LOWER: return islower(wc);
-    case WC_TYPE_PRINT: return isprint(wc);
-    case WC_TYPE_PUNCT: return ispunct(wc);
-    case WC_TYPE_SPACE: return isspace(wc);
-    case WC_TYPE_UPPER: return isupper(wc);
-    case WC_TYPE_XDIGIT: return isxdigit(wc);
-    default: return 0;
-  }
-}
-
-int mbsinit(const mbstate_t* /*ps*/) {
+int mbsinit(const mbstate_t*) {
+  // We have no state, so we're always in the initial state.
   return 1;
 }
 
-size_t mbrtowc(wchar_t* pwc, const char* s, size_t n, mbstate_t* /*ps*/) {
+size_t mbrtowc(wchar_t* pwc, const char* s, size_t n, mbstate_t*) {
   if (s == NULL) {
-    return 0;
+    s = "";
+    n = 1;
+    pwc = NULL;
   }
+
   if (n == 0) {
     return 0;
   }
-  if (pwc != NULL) {
-    *pwc = *s;
-  }
-  return (*s != 0);
-}
 
-size_t mbsnrtowcs(wchar_t* dst, const char** src, size_t n, size_t dst_size, mbstate_t* /*ps*/) {
-  size_t i = 0; // Number of input bytes read.
-  size_t o = 0; // Number of output characters written.
-  for (; i < n && (*src)[i] != 0; ++i) {
-    // TODO: UTF-8 support.
-    if (static_cast<uint8_t>((*src)[i]) > 0x7f) {
-      errno = EILSEQ;
-      if (dst != NULL) {
-        *src = &(*src)[i];
-      }
-      return static_cast<size_t>(-1);
+  int ch;
+  if (((ch = static_cast<uint8_t>(*s)) & ~0x7f) == 0) {
+    // Fast path for plain ASCII characters.
+    if (pwc != NULL) {
+      *pwc = ch;
     }
-    if (dst != NULL) {
-      if (o + 1 > dst_size) {
-        break;
-      }
-      dst[o++] = static_cast<wchar_t>((*src)[i]);
-    } else {
-      ++o;
-    }
+    return (ch != '\0' ? 1 : 0);
   }
-  // If we consumed all the input, terminate the output.
-  if (dst != NULL && o < dst_size) {
-    dst[o] = 0;
-  }
-  // If we were actually consuming input, record how far we got.
-  if (dst != NULL) {
-    if ((*src)[i] != 0) {
-      *src = &(*src)[i]; // This is where the next call should pick up.
-    } else {
-      *src = NULL; // We consumed everything.
-    }
-  }
-  return o;
-}
 
-size_t mbsrtowcs(wchar_t* dst, const char** src, size_t dst_size, mbstate_t* ps) {
-  return mbsnrtowcs(dst, src, SIZE_MAX, dst_size, ps);
-}
+  // Determine the number of octets that make up this character
+  // from the first octet, and a mask that extracts the
+  // interesting bits of the first octet. We already know
+  // the character is at least two bytes long.
+  size_t length;
+  int mask;
 
-wint_t towlower(wint_t wc) {
-  return tolower(wc);
-}
+  // We also specify a lower bound for the character code to
+  // detect redundant, non-"shortest form" encodings. For
+  // example, the sequence C0 80 is _not_ a legal representation
+  // of the null character. This enforces a 1-to-1 mapping
+  // between character codes and their multibyte representations.
+  wchar_t lower_bound;
 
-wint_t towupper(wint_t wc) {
-  return toupper(wc);
-}
-
-int wctomb(char* s, wchar_t wc) {
-  if (s == NULL) {
-    return 0;
-  }
-  if (wc <= 0xff) {
-    *s = static_cast<char>(wc);
+  ch = static_cast<uint8_t>(*s);
+  if ((ch & 0x80) == 0) {
+    mask = 0x7f;
+    length = 1;
+    lower_bound = 0;
+  } else if ((ch & 0xe0) == 0xc0) {
+    mask = 0x1f;
+    length = 2;
+    lower_bound = 0x80;
+  } else if ((ch & 0xf0) == 0xe0) {
+    mask = 0x0f;
+    length = 3;
+    lower_bound = 0x800;
+  } else if ((ch & 0xf8) == 0xf0) {
+    mask = 0x07;
+    length = 4;
+    lower_bound = 0x10000;
   } else {
-    *s = '?';
+    // Malformed input; input is not UTF-8. See RFC 3629.
+    errno = EILSEQ;
+    return ERR_ILLEGAL_SEQUENCE;
   }
-  return 1;
-}
 
-size_t wcrtomb(char* s, wchar_t wc, mbstate_t* /*ps*/) {
-  if (s == NULL) {
-    char buf[MB_LEN_MAX];
-    return wctomb(buf, L'\0');
-  }
-  return wctomb(s, wc);
-}
-
-size_t wcsftime(wchar_t* wcs, size_t maxsize, const wchar_t* format,  const struct tm* timptr) {
-  return strftime(reinterpret_cast<char*>(wcs), maxsize, reinterpret_cast<const char*>(format), timptr);
-}
-
-size_t wcsnrtombs(char* dst, const wchar_t** src, size_t n, size_t dst_size, mbstate_t* /*ps*/) {
-  size_t i = 0; // Number of input characters read.
-  size_t o = 0; // Number of output bytes written.
-  for (; i < n && (*src)[i] != 0; ++i) {
-    // TODO: UTF-8 support.
-    if ((*src)[i] > 0x7f) {
+  // Decode the octet sequence representing the character in chunks
+  // of 6 bits, most significant first.
+  wchar_t wch = static_cast<uint8_t>(*s++) & mask;
+  size_t i;
+  for (i = 1; i < MIN(length, n); i++) {
+    if ((*s & 0xc0) != 0x80) {
+      // Malformed input; bad characters in the middle of a character.
       errno = EILSEQ;
-      if (dst != NULL) {
-        *src = &(*src)[i];
+      return ERR_ILLEGAL_SEQUENCE;
+    }
+    wch <<= 6;
+    wch |= *s++ & 0x3f;
+  }
+  if (i < length) {
+    return ERR_INCOMPLETE_SEQUENCE;
+  }
+  if (wch < lower_bound) {
+    // Malformed input; redundant encoding.
+    errno = EILSEQ;
+    return ERR_ILLEGAL_SEQUENCE;
+  }
+  if ((wch >= 0xd800 && wch <= 0xdfff) || wch == 0xfffe || wch == 0xffff) {
+    // Malformed input; invalid code points.
+    errno = EILSEQ;
+    return ERR_ILLEGAL_SEQUENCE;
+  }
+  if (pwc != NULL) {
+    *pwc = wch;
+  }
+  return (wch == L'\0' ? 0 : length);
+}
+
+size_t mbsnrtowcs(wchar_t* dst, const char** src, size_t nmc, size_t len, mbstate_t* ps) {
+  size_t i, o, r;
+
+  if (dst == NULL) {
+    for (i = o = 0; i < nmc; i += r, o++) {
+      if (static_cast<uint8_t>((*src)[i]) < 0x80) {
+        // Fast path for plain ASCII characters.
+        if ((*src)[i] == '\0') {
+          return o;
+        }
+        r = 1;
+      } else {
+        r = mbrtowc(NULL, *src + i, nmc - i, ps);
+        if (r == ERR_ILLEGAL_SEQUENCE) {
+          return r;
+        }
+        if (r == ERR_INCOMPLETE_SEQUENCE) {
+          return o;
+        }
+        if (r == 0) {
+          return o;
+        }
       }
-      return static_cast<size_t>(-1);
     }
-    if (dst != NULL) {
-      if (o + 1 > dst_size) {
-        break;
+    return o;
+  }
+
+  for (i = o = 0; i < nmc && o < len; i += r, o++) {
+    if (static_cast<uint8_t>((*src)[i]) < 0x80) {
+      // Fast path for plain ASCII characters.
+      dst[o] = (*src)[i];
+      if ((*src)[i] == '\0') {
+        *src = NULL;
+        return o;
       }
-      dst[o++] = static_cast<char>((*src)[i]);
+      r = 1;
     } else {
-      ++o;
+      r = mbrtowc(dst + o, *src + i, nmc - i, ps);
+      if (r == ERR_ILLEGAL_SEQUENCE) {
+        *src += i;
+        return r;
+      }
+      if (r == ERR_INCOMPLETE_SEQUENCE) {
+        *src += nmc;
+        return o;
+      }
+      if (r == 0) {
+        *src = NULL;
+        return o;
+      }
     }
   }
-  // If we consumed all the input, terminate the output.
-  if (dst != NULL && o < dst_size) {
-    dst[o] = 0;
-  }
-  // If we were actually consuming input, record how far we got.
-  if (dst != NULL) {
-    if ((*src)[i] != 0) {
-      *src = &(*src)[i]; // This is where the next call should pick up.
-    } else {
-      *src = NULL; // We consumed everything.
-    }
-  }
+  *src += i;
   return o;
 }
 
-size_t wcsrtombs(char* dst, const wchar_t** src, size_t dst_size, mbstate_t* ps) {
-  return wcsnrtombs(dst, src, SIZE_MAX, dst_size, ps);
+size_t mbsrtowcs(wchar_t* dst, const char** src, size_t len, mbstate_t* ps) {
+  return mbsnrtowcs(dst, src, SIZE_MAX, len, ps);
 }
 
-wctype_t wctype(const char* property) {
-  static const char* const  properties[WC_TYPE_MAX] = {
-    "<invalid>",
-    "alnum", "alpha", "blank", "cntrl", "digit", "graph",
-    "lower", "print", "punct", "space", "upper", "xdigit"
-  };
-  for (size_t i = 0; i < WC_TYPE_MAX; ++i) {
-    if (!strcmp(properties[i], property)) {
-      return static_cast<wctype_t>(i);
+size_t wcrtomb(char* s, wchar_t wc, mbstate_t*) {
+  if (s == NULL) {
+    // Reset to initial shift state (no-op).
+    return 1;
+  }
+
+  if ((wc & ~0x7f) == 0) {
+    // Fast path for plain ASCII characters.
+    *s = wc;
+    return 1;
+  }
+
+  // Determine the number of octets needed to represent this character.
+  // We always output the shortest sequence possible. Also specify the
+  // first few bits of the first octet, which contains the information
+  // about the sequence length.
+  uint8_t lead;
+  size_t length;
+  if ((wc & ~0x7f) == 0) {
+    lead = 0;
+    length = 1;
+  } else if ((wc & ~0x7ff) == 0) {
+    lead = 0xc0;
+    length = 2;
+  } else if ((wc & ~0xffff) == 0) {
+    lead = 0xe0;
+    length = 3;
+  } else if ((wc & ~0x1fffff) == 0) {
+    lead = 0xf0;
+    length = 4;
+  } else {
+    errno = EILSEQ;
+    return ERR_ILLEGAL_SEQUENCE;
+  }
+
+  // Output the octets representing the character in chunks
+  // of 6 bits, least significant last. The first octet is
+  // a special case because it contains the sequence length
+  // information.
+  for (size_t i = length - 1; i > 0; i--) {
+    s[i] = (wc & 0x3f) | 0x80;
+    wc >>= 6;
+  }
+  *s = (wc & 0xff) | lead;
+
+  return length;
+}
+
+size_t wcsnrtombs(char* dst, const wchar_t** src, size_t nwc, size_t len, mbstate_t* ps) {
+  char buf[MB_LEN_MAX];
+  size_t i, o, r;
+  if (dst == NULL) {
+    for (i = o = 0; i < nwc; i++, o += r) {
+      wchar_t wc = (*src)[i];
+      if (static_cast<uint32_t>(wc) < 0x80) {
+        // Fast path for plain ASCII characters.
+        if (wc == 0) {
+          return o;
+        }
+        r = 1;
+      } else {
+        r = wcrtomb(buf, wc, ps);
+        if (r == ERR_ILLEGAL_SEQUENCE) {
+          return r;
+        }
+      }
+    }
+    return o;
+  }
+
+  for (i = o = 0; i < nwc && o < len; i++, o += r) {
+    wchar_t wc = (*src)[i];
+    if (static_cast<uint32_t>(wc) < 0x80) {
+      // Fast path for plain ASCII characters.
+      dst[o] = wc;
+      if (wc == 0) {
+        *src = NULL;
+        return o;
+      }
+      r = 1;
+    } else if (len - o >= sizeof(buf)) {
+      // Enough space to translate in-place.
+      r = wcrtomb(dst + o, wc, ps);
+      if (r == ERR_ILLEGAL_SEQUENCE) {
+        *src += i;
+        return r;
+      }
+    } else {
+      // May not be enough space; use temp buffer.
+      r = wcrtomb(buf, wc, ps);
+      if (r == ERR_ILLEGAL_SEQUENCE) {
+        *src += i;
+        return r;
+      }
+      if (r > len - o) {
+        break;
+      }
+      memcpy(dst + o, buf, r);
     }
   }
-  return static_cast<wctype_t>(0);
+  *src += i;
+  return o;
 }
 
-int wcwidth(wchar_t wc) {
-  return (wc > 0);
+size_t wcsrtombs(char* dst, const wchar_t** src, size_t len, mbstate_t* ps) {
+  return wcsnrtombs(dst, src, SIZE_MAX, len, ps);
 }
diff --git a/libc/bionic/wctype.cpp b/libc/bionic/wctype.cpp
new file mode 100644
index 0000000..673402d
--- /dev/null
+++ b/libc/bionic/wctype.cpp
@@ -0,0 +1,86 @@
+/*
+ * Copyright (C) 2008 The Android Open Source Project
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *  * Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in
+ *    the documentation and/or other materials provided with the
+ *    distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
+ * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
+ * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
+ * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
+ * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <ctype.h>
+#include <stdlib.h>
+#include <string.h>
+#include <wchar.h>
+
+// TODO: these only work for the ASCII range; rewrite to dlsym icu4c? http://b/14499654
+
+int iswalnum(wint_t wc) { return isalnum(wc); }
+int iswalpha(wint_t wc) { return isalpha(wc); }
+int iswblank(wint_t wc) { return isblank(wc); }
+int iswcntrl(wint_t wc) { return iscntrl(wc); }
+int iswdigit(wint_t wc) { return isdigit(wc); }
+int iswgraph(wint_t wc) { return isgraph(wc); }
+int iswlower(wint_t wc) { return islower(wc); }
+int iswprint(wint_t wc) { return isprint(wc); }
+int iswpunct(wint_t wc) { return ispunct(wc); }
+int iswspace(wint_t wc) { return isspace(wc); }
+int iswupper(wint_t wc) { return isupper(wc); }
+int iswxdigit(wint_t wc) { return isxdigit(wc); }
+
+int iswctype(wint_t wc, wctype_t char_class) {
+  switch (char_class) {
+    case WC_TYPE_ALNUM: return iswalnum(wc);
+    case WC_TYPE_ALPHA: return iswalpha(wc);
+    case WC_TYPE_BLANK: return iswblank(wc);
+    case WC_TYPE_CNTRL: return iswcntrl(wc);
+    case WC_TYPE_DIGIT: return iswdigit(wc);
+    case WC_TYPE_GRAPH: return iswgraph(wc);
+    case WC_TYPE_LOWER: return iswlower(wc);
+    case WC_TYPE_PRINT: return iswprint(wc);
+    case WC_TYPE_PUNCT: return iswpunct(wc);
+    case WC_TYPE_SPACE: return iswspace(wc);
+    case WC_TYPE_UPPER: return iswupper(wc);
+    case WC_TYPE_XDIGIT: return iswxdigit(wc);
+    default: return 0;
+  }
+}
+
+wint_t towlower(wint_t wc) { return tolower(wc); }
+wint_t towupper(wint_t wc) { return toupper(wc); }
+
+wctype_t wctype(const char* property) {
+  static const char* const  properties[WC_TYPE_MAX] = {
+    "<invalid>",
+    "alnum", "alpha", "blank", "cntrl", "digit", "graph",
+    "lower", "print", "punct", "space", "upper", "xdigit"
+  };
+  for (size_t i = 0; i < WC_TYPE_MAX; ++i) {
+    if (!strcmp(properties[i], property)) {
+      return static_cast<wctype_t>(i);
+    }
+  }
+  return static_cast<wctype_t>(0);
+}
+
+int wcwidth(wchar_t wc) {
+  return (wc > 0);
+}
diff --git a/libc/kernel/tools/clean_header.py b/libc/kernel/tools/clean_header.py
index e825ae0..238087b 100755
--- a/libc/kernel/tools/clean_header.py
+++ b/libc/kernel/tools/clean_header.py
@@ -7,7 +7,7 @@
 
 noUpdate = 1
 
-def  cleanupFile( path, original_path):
+def cleanupFile(path, original_path):
     """reads an original header and perform the cleanup operation on it
        this functions returns the destination path and the clean header
        as a single string"""
diff --git a/libc/kernel/tools/cpp.py b/libc/kernel/tools/cpp.py
index 2c40d7c..2be9532 100644
--- a/libc/kernel/tools/cpp.py
+++ b/libc/kernel/tools/cpp.py
@@ -685,9 +685,9 @@
         # we have the defined keyword, check the rest
         self.i += 1
         self.skip_spaces()
-        use_parens = 0
+        used_parens = 0
         if self.i < self.n and self.tok[self.i].id == tokLPAREN:
-            use_parens = 1
+            used_parens = 1
             self.i += 1
             self.skip_spaces()
 
@@ -699,7 +699,7 @@
             self.throw(CppConstantExpected,i,"### 'defined' must be followed by macro name")
 
         self.i += 1
-        if use_parens:
+        if used_parens:
             self.expectId(tokRPAREN)
 
         return ("defined", t.value)
@@ -1162,7 +1162,7 @@
         return self.directive in ["if","ifdef","ifndef","elif"]
 
     def isInclude(self):
-        """checks wether this is a #include directive. if true, then returns the
+        """checks whether this is a #include directive. if true, then returns the
            corresponding file name (with brackets or double-qoutes). None otherwise"""
         if self.directive != "include":
             return None
@@ -1517,15 +1517,20 @@
         tokens = tokens[:-1]  # remove trailing tokLN
         self.blocks = [ Block(tokens) ] + self.blocks
 
-    def replaceTokens(self,replacements=dict()):
-        """replace tokens according to the given dict
-           """
+    def replaceTokens(self,replacements):
+        """replace tokens according to the given dict"""
         for b in self.blocks:
-            if (not b.isDirective()) or b.isDefine():
+            made_change = False
+            if b.isInclude() == None:
                 for tok in b.tokens:
                     if tok.id == tokIDENT:
                         if tok.value in replacements:
                             tok.value = replacements[tok.value]
+                            made_change = True
+
+            if made_change and b.isIf():
+                # Keep 'expr' in sync with 'tokens'.
+                b.expr = CppExpr(b.tokens)
 
 class BlockParser:
     """a class used to convert an input source file into a BlockList object"""
@@ -1798,6 +1803,10 @@
 #define X
 #endif
 
+#ifndef SIGRTMAX
+#define SIGRTMAX 123
+#endif /* SIGRTMAX */
+
 #if 0
 #if 1
 #define  BAD_6
@@ -1817,12 +1826,17 @@
 #define X
 #endif
 
+#ifndef __SIGRTMAX
+#define __SIGRTMAX 123
+#endif
+
 """
 
     out = StringOutput()
     lines = string.split(text, '\n')
     list = BlockParser().parse( CppLinesTokenizer(lines) )
     #D_setlevel(2)
+    list.replaceTokens( kernel_token_replacements )
     list.optimizeAll( {"__KERNEL__":kCppUndefinedMacro} )
     list.write(out)
     if out.get() != expected:
diff --git a/libc/kernel/uapi/asm-generic/signal.h b/libc/kernel/uapi/asm-generic/signal.h
index a16622a..e103240 100644
--- a/libc/kernel/uapi/asm-generic/signal.h
+++ b/libc/kernel/uapi/asm-generic/signal.h
@@ -67,7 +67,7 @@
 #define SIGUNUSED 31
 /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
 #define __SIGRTMIN 32
-#ifndef SIGRTMAX
+#ifndef __SIGRTMAX
 #define __SIGRTMAX _KERNEL__NSIG
 #endif
 /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
diff --git a/libc/upstream-openbsd/lib/libc/locale/wctomb.c b/libc/upstream-openbsd/lib/libc/locale/wctomb.c
new file mode 100644
index 0000000..39f7a7c
--- /dev/null
+++ b/libc/upstream-openbsd/lib/libc/locale/wctomb.c
@@ -0,0 +1,47 @@
+/*	$OpenBSD: wctomb.c,v 1.2 2012/12/05 23:20:00 deraadt Exp $ */
+
+/*-
+ * Copyright (c) 2002-2004 Tim J. Robbins.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <stdlib.h>
+#include <string.h>
+#include <wchar.h>
+
+int
+wctomb(char *s, wchar_t wchar)
+{
+	static mbstate_t mbs;
+	size_t rval;
+
+	if (s == NULL) {
+		/* No support for state dependent encodings. */
+		memset(&mbs, 0, sizeof(mbs));
+		return (0);
+	}
+	if ((rval = wcrtomb(s, wchar, &mbs)) == (size_t)-1)
+		return (-1);
+	return ((int)rval);
+}
diff --git a/libc/upstream-openbsd/lib/libc/stdio/fgetln.c b/libc/upstream-openbsd/lib/libc/stdio/fgetln.c
index 539b3c0..d0c0809 100644
--- a/libc/upstream-openbsd/lib/libc/stdio/fgetln.c
+++ b/libc/upstream-openbsd/lib/libc/stdio/fgetln.c
@@ -1,4 +1,4 @@
-/*	$OpenBSD: fgetln.c,v 1.11 2009/11/21 09:53:44 guenther Exp $ */
+/*	$OpenBSD: fgetln.c,v 1.12 2013/11/12 07:04:06 deraadt Exp $ */
 /*-
  * Copyright (c) 1990, 1993
  *	The Regents of the University of California.  All rights reserved.
@@ -43,7 +43,7 @@
  * so we add 1 here.
 #endif
  */
-int
+static int
 __slbexpand(FILE *fp, size_t newsize)
 {
 	void *p;
diff --git a/libc/upstream-openbsd/lib/libc/stdio/fputws.c b/libc/upstream-openbsd/lib/libc/stdio/fputws.c
index c4c2d8e..108846e 100644
--- a/libc/upstream-openbsd/lib/libc/stdio/fputws.c
+++ b/libc/upstream-openbsd/lib/libc/stdio/fputws.c
@@ -1,4 +1,4 @@
-/*	$OpenBSD: fputws.c,v 1.6 2013/04/17 17:40:35 tedu Exp $	*/
+/*	$OpenBSD: fputws.c,v 1.7 2013/11/12 07:04:35 deraadt Exp $	*/
 /* $NetBSD: fputws.c,v 1.1 2003/03/07 07:11:37 tshiozak Exp $ */
 
 /*-
@@ -34,8 +34,7 @@
 #include <stdio.h>
 #include <wchar.h>
 #include "local.h"
-
-wint_t __fputwc_unlock(wchar_t wc, FILE *fp);
+#include "fvwrite.h"
 
 int
 fputws(ws, fp)
diff --git a/libc/upstream-openbsd/lib/libc/stdio/fread.c b/libc/upstream-openbsd/lib/libc/stdio/fread.c
index 430865d..8a592f6 100644
--- a/libc/upstream-openbsd/lib/libc/stdio/fread.c
+++ b/libc/upstream-openbsd/lib/libc/stdio/fread.c
@@ -1,4 +1,4 @@
-/*	$OpenBSD: fread.c,v 1.11 2009/11/21 09:53:44 guenther Exp $ */
+/*	$OpenBSD: fread.c,v 1.12 2014/05/01 16:40:36 deraadt Exp $ */
 /*-
  * Copyright (c) 1990, 1993
  *	The Regents of the University of California.  All rights reserved.
@@ -33,8 +33,12 @@
 
 #include <stdio.h>
 #include <string.h>
+#include <stdint.h>
+#include <errno.h>
 #include "local.h"
 
+#define MUL_NO_OVERFLOW	(1UL << (sizeof(size_t) * 4))
+
 size_t
 fread(void *buf, size_t size, size_t count, FILE *fp)
 {
@@ -44,6 +48,16 @@
 	size_t total;
 
 	/*
+	 * Extension:  Catch integer overflow
+	 */
+	if ((size >= MUL_NO_OVERFLOW || count >= MUL_NO_OVERFLOW) &&
+	    size > 0 && SIZE_MAX / size < count) {
+		errno = EOVERFLOW;
+		fp->_flags |= __SERR;
+		return (0);
+	}
+
+	/*
 	 * ANSI and SUSv2 require a return value of 0 if size or count are 0.
 	 */
 	if ((resid = count * size) == 0)
diff --git a/libc/stdio/fvwrite.h b/libc/upstream-openbsd/lib/libc/stdio/fvwrite.h
similarity index 93%
rename from libc/stdio/fvwrite.h
rename to libc/upstream-openbsd/lib/libc/stdio/fvwrite.h
index 96f65de..d3a309b 100644
--- a/libc/stdio/fvwrite.h
+++ b/libc/upstream-openbsd/lib/libc/stdio/fvwrite.h
@@ -1,4 +1,4 @@
-/*	$OpenBSD: fvwrite.h,v 1.5 2003/06/02 20:18:37 millert Exp $	*/
+/*	$OpenBSD: fvwrite.h,v 1.6 2013/11/12 07:04:35 deraadt Exp $	*/
 
 /*-
  * Copyright (c) 1990, 1993
@@ -36,7 +36,7 @@
  * I/O descriptors for __sfvwrite().
  */
 struct __siov {
-	const void	*iov_base;
+	void	*iov_base;
 	size_t	iov_len;
 };
 struct __suio {
@@ -46,3 +46,4 @@
 };
 
 extern int __sfvwrite(FILE *, struct __suio *);
+wint_t __fputwc_unlock(wchar_t wc, FILE *fp);
diff --git a/libc/upstream-freebsd/lib/libc/stdio/fwrite.c b/libc/upstream-openbsd/lib/libc/stdio/fwrite.c
similarity index 74%
rename from libc/upstream-freebsd/lib/libc/stdio/fwrite.c
rename to libc/upstream-openbsd/lib/libc/stdio/fwrite.c
index 707d362..f0a17bf 100644
--- a/libc/upstream-freebsd/lib/libc/stdio/fwrite.c
+++ b/libc/upstream-openbsd/lib/libc/stdio/fwrite.c
@@ -1,3 +1,4 @@
+/*	$OpenBSD: fwrite.c,v 1.11 2014/05/01 16:40:36 deraadt Exp $ */
 /*-
  * Copyright (c) 1990, 1993
  *	The Regents of the University of California.  All rights reserved.
@@ -30,67 +31,58 @@
  * SUCH DAMAGE.
  */
 
-#if defined(LIBC_SCCS) && !defined(lint)
-static char sccsid[] = "@(#)fwrite.c	8.1 (Berkeley) 6/4/93";
-#endif /* LIBC_SCCS and not lint */
-#include <sys/cdefs.h>
-__FBSDID("$FreeBSD$");
-
-#include "namespace.h"
-#include <errno.h>
-#include <stdint.h>
 #include <stdio.h>
-#include "un-namespace.h"
+#include <stdlib.h>
+#include <stdint.h>
+#include <errno.h>
 #include "local.h"
 #include "fvwrite.h"
-#include "libc_private.h"
+
+#define MUL_NO_OVERFLOW	(1UL << (sizeof(size_t) * 4))
 
 /*
  * Write `count' objects (each size `size') from memory to the given file.
  * Return the number of whole objects written.
  */
 size_t
-fwrite(const void * __restrict buf, size_t size, size_t count, FILE * __restrict fp)
+fwrite(const void *buf, size_t size, size_t count, FILE *fp)
 {
 	size_t n;
 	struct __suio uio;
 	struct __siov iov;
+	int ret;
 
 	/*
-	 * ANSI and SUSv2 require a return value of 0 if size or count are 0.
+	 * Extension:  Catch integer overflow
 	 */
-	if ((count == 0) || (size == 0))
-		return (0);
-
-	/*
-	 * Check for integer overflow.  As an optimization, first check that
-	 * at least one of {count, size} is at least 2^16, since if both
-	 * values are less than that, their product can't possible overflow
-	 * (size_t is always at least 32 bits on FreeBSD).
-	 */
-	if (((count | size) > 0xFFFF) &&
-	    (count > SIZE_MAX / size)) {
-		errno = EINVAL;
+	if ((size >= MUL_NO_OVERFLOW || count >= MUL_NO_OVERFLOW) &&
+	    size > 0 && SIZE_MAX / size < count) {
+		errno = EOVERFLOW;
 		fp->_flags |= __SERR;
 		return (0);
 	}
 
-	n = count * size;
+	/*
+	 * ANSI and SUSv2 require a return value of 0 if size or count are 0.
+	 */
+	if ((n = count * size) == 0)
+		return (0);
 
 	iov.iov_base = (void *)buf;
 	uio.uio_resid = iov.iov_len = n;
 	uio.uio_iov = &iov;
 	uio.uio_iovcnt = 1;
 
-	FLOCKFILE(fp);
-	ORIENT(fp, -1);
 	/*
 	 * The usual case is success (__sfvwrite returns 0);
 	 * skip the divide if this happens, since divides are
 	 * generally slow and since this occurs whenever size==0.
 	 */
-	if (__sfvwrite(fp, &uio) != 0)
-	    count = (n - uio.uio_resid) / size;
+	FLOCKFILE(fp);
+	_SET_ORIENTATION(fp, -1);
+	ret = __sfvwrite(fp, &uio);
 	FUNLOCKFILE(fp);
-	return (count);
+	if (ret == 0)
+		return (count);
+	return ((n - uio.uio_resid) / size);
 }
diff --git a/libc/upstream-openbsd/lib/libc/stdio/vfprintf.c b/libc/upstream-openbsd/lib/libc/stdio/vfprintf.c
index b4f8f29..86b540e 100644
--- a/libc/upstream-openbsd/lib/libc/stdio/vfprintf.c
+++ b/libc/upstream-openbsd/lib/libc/stdio/vfprintf.c
@@ -1,4 +1,4 @@
-/*	$OpenBSD: vfprintf.c,v 1.63 2013/03/02 19:40:08 guenther Exp $	*/
+/*	$OpenBSD: vfprintf.c,v 1.65 2014/03/19 05:17:01 guenther Exp $	*/
 /*-
  * Copyright (c) 1990 The Regents of the University of California.
  * All rights reserved.
@@ -216,11 +216,10 @@
 #include <locale.h>
 #include <math.h>
 #include "floatio.h"
+#include "gdtoa.h"
 
 #define	DEFPREC		6
 
-extern char *__dtoa(double, int, int, int *, int *, char **);
-extern void  __freedtoa(char *);
 static int exponent(char *, int, int);
 #endif /* FLOATING_POINT */
 
@@ -399,7 +398,7 @@
 	    flags&PTRINT ? GETARG(ptrdiff_t) : \
 	    flags&SIZEINT ? GETARG(ssize_t) : \
 	    flags&SHORTINT ? (short)GETARG(int) : \
-	    flags&CHARINT ? (__signed char)GETARG(int) : \
+	    flags&CHARINT ? (signed char)GETARG(int) : \
 	    GETARG(int)))
 #define	UARG() \
 	((uintmax_t)(flags&MAXINT ? GETARG(uintmax_t) : \
@@ -810,7 +809,7 @@
 			else if (flags & SHORTINT)
 				*GETARG(short *) = ret;
 			else if (flags & CHARINT)
-				*GETARG(__signed char *) = ret;
+				*GETARG(signed char *) = ret;
 			else if (flags & PTRINT)
 				*GETARG(ptrdiff_t *) = ret;
 			else if (flags & SIZEINT)
diff --git a/libc/upstream-openbsd/lib/libc/stdio/vfscanf.c b/libc/upstream-openbsd/lib/libc/stdio/vfscanf.c
index c2996a9..abefe32 100644
--- a/libc/upstream-openbsd/lib/libc/stdio/vfscanf.c
+++ b/libc/upstream-openbsd/lib/libc/stdio/vfscanf.c
@@ -1,4 +1,4 @@
-/*	$OpenBSD: vfscanf.c,v 1.30 2013/04/17 17:40:35 tedu Exp $ */
+/*	$OpenBSD: vfscanf.c,v 1.31 2014/03/19 05:17:01 guenther Exp $ */
 /*-
  * Copyright (c) 1990, 1993
  *	The Regents of the University of California.  All rights reserved.
@@ -273,7 +273,7 @@
 			if (flags & SUPPRESS)
 				continue;
 			if (flags & SHORTSHORT)
-				*va_arg(ap, __signed char *) = nread;
+				*va_arg(ap, signed char *) = nread;
 			else if (flags & SHORT)
 				*va_arg(ap, short *) = nread;
 			else if (flags & LONG)
@@ -749,7 +749,7 @@
 				else if (flags & SHORT)
 					*va_arg(ap, short *) = res;
 				else if (flags & SHORTSHORT)
-					*va_arg(ap, __signed char *) = res;
+					*va_arg(ap, signed char *) = res;
 				else
 					*va_arg(ap, int *) = res;
 				nassigned++;
diff --git a/libc/upstream-openbsd/lib/libc/stdio/vfwprintf.c b/libc/upstream-openbsd/lib/libc/stdio/vfwprintf.c
index f76eed3..7cb08ea 100644
--- a/libc/upstream-openbsd/lib/libc/stdio/vfwprintf.c
+++ b/libc/upstream-openbsd/lib/libc/stdio/vfwprintf.c
@@ -1,4 +1,4 @@
-/*	$OpenBSD: vfwprintf.c,v 1.6 2013/04/17 17:40:35 tedu Exp $ */
+/*	$OpenBSD: vfwprintf.c,v 1.9 2014/03/19 05:17:01 guenther Exp $ */
 /*-
  * Copyright (c) 1990 The Regents of the University of California.
  * All rights reserved.
@@ -54,8 +54,6 @@
 #include "local.h"
 #include "fvwrite.h"
 
-wint_t __fputwc_unlock(wchar_t wc, FILE *fp);
-
 union arg {
 	int			intarg;
 	unsigned int		uintarg;
@@ -235,11 +233,10 @@
 #include <locale.h>
 #include <math.h>
 #include "floatio.h"
+#include "gdtoa.h"
 
 #define	DEFPREC		6
 
-extern char *__dtoa(double, int, int, int *, int *, char **);
-extern void  __freedtoa(char *);
 static int exponent(wchar_t *, int, int);
 #endif /* FLOATING_POINT */
 
@@ -392,7 +389,7 @@
 	    flags&PTRINT ? GETARG(ptrdiff_t) : \
 	    flags&SIZEINT ? GETARG(ssize_t) : \
 	    flags&SHORTINT ? (short)GETARG(int) : \
-	    flags&CHARINT ? (__signed char)GETARG(int) : \
+	    flags&CHARINT ? (signed char)GETARG(int) : \
 	    GETARG(int)))
 #define	UARG() \
 	((uintmax_t)(flags&MAXINT ? GETARG(uintmax_t) : \
@@ -795,7 +792,7 @@
 			else if (flags & SHORTINT)
 				*GETARG(short *) = ret;
 			else if (flags & CHARINT)
-				*GETARG(__signed char *) = ret;
+				*GETARG(signed char *) = ret;
 			else if (flags & PTRINT)
 				*GETARG(ptrdiff_t *) = ret;
 			else if (flags & SIZEINT)
diff --git a/libc/upstream-openbsd/lib/libc/stdio/vfwscanf.c b/libc/upstream-openbsd/lib/libc/stdio/vfwscanf.c
index e5cf5e1..cbb36be 100644
--- a/libc/upstream-openbsd/lib/libc/stdio/vfwscanf.c
+++ b/libc/upstream-openbsd/lib/libc/stdio/vfwscanf.c
@@ -1,4 +1,4 @@
-/*	$OpenBSD: vfwscanf.c,v 1.2 2012/01/18 17:23:11 chl Exp $ */
+/*	$OpenBSD: vfwscanf.c,v 1.4 2014/03/19 05:17:01 guenther Exp $ */
 /*-
  * Copyright (c) 1990, 1993
  *	The Regents of the University of California.  All rights reserved.
@@ -31,7 +31,6 @@
  * SUCH DAMAGE.
  */
 
-#include <ctype.h>
 #include <inttypes.h>
 #include <limits.h>
 #include <locale.h>
@@ -300,7 +299,7 @@
 			if (flags & SUPPRESS)
 				continue;
 			if (flags & SHORTSHORT)
-				*va_arg(ap, __signed char *) = nread;
+				*va_arg(ap, signed char *) = nread;
 			else if (flags & SHORT)
 				*va_arg(ap, short *) = nread;
 			else if (flags & LONG)
@@ -324,7 +323,7 @@
 			return (EOF);
 
 		default:	/* compat */
-			if (isupper(c))
+			if (iswupper(c))
 				flags |= LONG;
 			c = CT_INT;
 			base = 10;
@@ -672,7 +671,7 @@
 				else if (flags & SHORT)
 					*va_arg(ap, short *) = res;
 				else if (flags & SHORTSHORT)
-					*va_arg(ap, __signed char *) = res;
+					*va_arg(ap, signed char *) = res;
 				else
 					*va_arg(ap, int *) = res;
 				nassigned++;
diff --git a/libc/upstream-openbsd/lib/libc/time/wcsftime.c b/libc/upstream-openbsd/lib/libc/time/wcsftime.c
new file mode 100644
index 0000000..5760493
--- /dev/null
+++ b/libc/upstream-openbsd/lib/libc/time/wcsftime.c
@@ -0,0 +1,575 @@
+/*	$OpenBSD: wcsftime.c,v 1.2 2013/01/20 20:29:02 millert Exp $ */
+#include "private.h"
+
+/*
+** Based on the UCB version with the ID appearing below.
+** This is ANSIish only when "multibyte character == plain character".
+**
+** Copyright (c) 1989, 1993
+**	The Regents of the University of California.  All rights reserved.
+**
+** Redistribution and use in source and binary forms, with or without
+** modification, are permitted provided that the following conditions
+** are met:
+** 1. Redistributions of source code must retain the above copyright
+**    notice, this list of conditions and the following disclaimer.
+** 2. Redistributions in binary form must reproduce the above copyright
+**    notice, this list of conditions and the following disclaimer in the
+**    documentation and/or other materials provided with the distribution.
+** 3. Neither the name of the University nor the names of its contributors
+**    may be used to endorse or promote products derived from this software
+**    without specific prior written permission.
+**
+** THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
+** ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+** IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+** ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
+** FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+** DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+** OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+** HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+** LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+** OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+** SUCH DAMAGE.
+*/
+
+#include "tzfile.h"
+#include "fcntl.h"
+#include <locale.h>
+#include <wchar.h>
+
+struct lc_time_T {
+	const wchar_t *	mon[MONSPERYEAR];
+	const wchar_t *	month[MONSPERYEAR];
+	const wchar_t *	wday[DAYSPERWEEK];
+	const wchar_t *	weekday[DAYSPERWEEK];
+	const wchar_t *	X_fmt;
+	const wchar_t *	x_fmt;
+	const wchar_t *	c_fmt;
+	const wchar_t *	am;
+	const wchar_t *	pm;
+	const wchar_t *	date_fmt;
+};
+
+#define Locale	(&C_time_locale)
+
+static const struct lc_time_T	C_time_locale = {
+	{
+		L"Jan", L"Feb", L"Mar", L"Apr", L"May", L"Jun",
+		L"Jul", L"Aug", L"Sep", L"Oct", L"Nov", L"Dec"
+	}, {
+		L"January", L"February", L"March", L"April", L"May", L"June",
+		L"July", L"August", L"September", L"October", L"November", 
+		L"December"
+	}, {
+		L"Sun", L"Mon", L"Tue", L"Wed",
+		L"Thu", L"Fri", L"Sat"
+	}, {
+		L"Sunday", L"Monday", L"Tuesday", L"Wednesday",
+		L"Thursday", L"Friday", L"Saturday"
+	},
+
+	/* X_fmt */
+	L"%H:%M:%S",
+
+	/*
+	** x_fmt
+	** C99 requires this format.
+	** Using just numbers (as here) makes Quakers happier;
+	** it's also compatible with SVR4.
+	*/
+	L"%m/%d/%y",
+
+	/*
+	** c_fmt
+	** C99 requires this format.
+	** Previously this code used "%D %X", but we now conform to C99.
+	** Note that
+	**	"%a %b %d %H:%M:%S %Y"
+	** is used by Solaris 2.3.
+	*/
+	L"%a %b %e %T %Y",
+
+	/* am */
+	L"AM",
+
+	/* pm */
+	L"PM",
+
+	/* date_fmt */
+	L"%a %b %e %H:%M:%S %Z %Y"
+};
+
+#define UNKNOWN L"?"
+static wchar_t *	_add(const wchar_t *, wchar_t *, const wchar_t *);
+static wchar_t *	_sadd(const char *, wchar_t *, const wchar_t *);
+static wchar_t *	_conv(int, const wchar_t *, wchar_t *, const wchar_t *);
+static wchar_t *	_fmt(const wchar_t *, const struct tm *, wchar_t *, const wchar_t *,
+			int *);
+static wchar_t *	_yconv(int, int, int, int, wchar_t *, const wchar_t *);
+
+extern char *	tzname[];
+
+#ifndef YEAR_2000_NAME
+#define YEAR_2000_NAME	"CHECK_STRFTIME_FORMATS_FOR_TWO_DIGIT_YEARS"
+#endif /* !defined YEAR_2000_NAME */
+
+#define IN_NONE	0
+#define IN_SOME	1
+#define IN_THIS	2
+#define IN_ALL	3
+
+size_t
+wcsftime(wchar_t *__restrict s, size_t maxsize, 
+    const wchar_t *__restrict format, const struct tm *__restrict t)
+{
+	wchar_t *p;
+	int	warn;
+
+	tzset();
+	warn = IN_NONE;
+	p = _fmt(((format == NULL) ? L"%c" : format), t, s, s + maxsize, &warn);
+#ifndef NO_RUN_TIME_WARNINGS_ABOUT_YEAR_2000_PROBLEMS_THANK_YOU
+	if (warn != IN_NONE && getenv(YEAR_2000_NAME) != NULL) {
+		(void) fprintf(stderr, "\n");
+		if (format == NULL)
+			(void) fprintf(stderr, "NULL strftime format ");
+		else	(void) fwprintf(stderr, "strftime format \"%ls\" ",
+				format);
+		(void) fprintf(stderr, "yields only two digits of years in ");
+		if (warn == IN_SOME)
+			(void) fprintf(stderr, "some locales");
+		else if (warn == IN_THIS)
+			(void) fprintf(stderr, "the current locale");
+		else	(void) fprintf(stderr, "all locales");
+		(void) fprintf(stderr, "\n");
+	}
+#endif /* !defined NO_RUN_TIME_WARNINGS_ABOUT_YEAR_2000_PROBLEMS_THANK_YOU */
+	if (p == s + maxsize) {
+		if (maxsize > 0)
+			s[maxsize - 1] = '\0';
+		return 0;
+	}
+	*p = L'\0';
+	return p - s;
+}
+
+static wchar_t *
+_fmt(const wchar_t *format, const struct tm *t, wchar_t *pt, 
+    const wchar_t *ptlim, int *warnp)
+{
+	for ( ; *format; ++format) {
+		if (*format != L'%') {
+			if (pt == ptlim)
+				break;
+			*pt++ = *format;
+			continue;
+		}
+label:
+		switch (*++format) {
+		case '\0':
+			--format;
+			break;
+		case 'A':
+			pt = _add((t->tm_wday < 0 ||
+				t->tm_wday >= DAYSPERWEEK) ?
+				UNKNOWN : Locale->weekday[t->tm_wday],
+				pt, ptlim);
+			continue;
+		case 'a':
+			pt = _add((t->tm_wday < 0 ||
+				t->tm_wday >= DAYSPERWEEK) ?
+				UNKNOWN : Locale->wday[t->tm_wday],
+				pt, ptlim);
+			continue;
+		case 'B':
+			pt = _add((t->tm_mon < 0 ||
+				t->tm_mon >= MONSPERYEAR) ?
+				UNKNOWN : Locale->month[t->tm_mon],
+				pt, ptlim);
+			continue;
+		case 'b':
+		case 'h':
+			pt = _add((t->tm_mon < 0 ||
+				t->tm_mon >= MONSPERYEAR) ?
+				UNKNOWN : Locale->mon[t->tm_mon],
+				pt, ptlim);
+			continue;
+		case 'C':
+			/*
+			** %C used to do a...
+			**	_fmt("%a %b %e %X %Y", t);
+			** ...whereas now POSIX 1003.2 calls for
+			** something completely different.
+			** (ado, 1993-05-24)
+			*/
+			pt = _yconv(t->tm_year, TM_YEAR_BASE, 1, 0,
+				pt, ptlim);
+			continue;
+		case 'c':
+			{
+			int warn2 = IN_SOME;
+
+			pt = _fmt(Locale->c_fmt, t, pt, ptlim, &warn2);
+			if (warn2 == IN_ALL)
+				warn2 = IN_THIS;
+			if (warn2 > *warnp)
+				*warnp = warn2;
+			}
+			continue;
+		case 'D':
+			pt = _fmt(L"%m/%d/%y", t, pt, ptlim, warnp);
+			continue;
+		case 'd':
+			pt = _conv(t->tm_mday, L"%02d", pt, ptlim);
+			continue;
+		case 'E':
+		case 'O':
+			/*
+			** C99 locale modifiers.
+			** The sequences
+			**	%Ec %EC %Ex %EX %Ey %EY
+			**	%Od %oe %OH %OI %Om %OM
+			**	%OS %Ou %OU %OV %Ow %OW %Oy
+			** are supposed to provide alternate
+			** representations.
+			*/
+			goto label;
+		case 'e':
+			pt = _conv(t->tm_mday, L"%2d", pt, ptlim);
+			continue;
+		case 'F':
+			pt = _fmt(L"%Y-%m-%d", t, pt, ptlim, warnp);
+			continue;
+		case 'H':
+			pt = _conv(t->tm_hour, L"%02d", pt, ptlim);
+			continue;
+		case 'I':
+			pt = _conv((t->tm_hour % 12) ?
+				(t->tm_hour % 12) : 12,
+				L"%02d", pt, ptlim);
+			continue;
+		case 'j':
+			pt = _conv(t->tm_yday + 1, L"%03d", pt, ptlim);
+			continue;
+		case 'k':
+			/*
+			** This used to be...
+			**	_conv(t->tm_hour % 12 ?
+			**		t->tm_hour % 12 : 12, 2, ' ');
+			** ...and has been changed to the below to
+			** match SunOS 4.1.1 and Arnold Robbins'
+			** strftime version 3.0. That is, "%k" and
+			** "%l" have been swapped.
+			** (ado, 1993-05-24)
+			*/
+			pt = _conv(t->tm_hour, L"%2d", pt, ptlim);
+			continue;
+		case 'l':
+			/*
+			** This used to be...
+			**	_conv(t->tm_hour, 2, ' ');
+			** ...and has been changed to the below to
+			** match SunOS 4.1.1 and Arnold Robbin's
+			** strftime version 3.0. That is, "%k" and
+			** "%l" have been swapped.
+			** (ado, 1993-05-24)
+			*/
+			pt = _conv((t->tm_hour % 12) ?
+				(t->tm_hour % 12) : 12,
+				L"%2d", pt, ptlim);
+			continue;
+		case 'M':
+			pt = _conv(t->tm_min, L"%02d", pt, ptlim);
+			continue;
+		case 'm':
+			pt = _conv(t->tm_mon + 1, L"%02d", pt, ptlim);
+			continue;
+		case 'n':
+			pt = _add(L"\n", pt, ptlim);
+			continue;
+		case 'p':
+			pt = _add((t->tm_hour >= (HOURSPERDAY / 2)) ?
+				Locale->pm :
+				Locale->am,
+				pt, ptlim);
+			continue;
+		case 'R':
+			pt = _fmt(L"%H:%M", t, pt, ptlim, warnp);
+			continue;
+		case 'r':
+			pt = _fmt(L"%I:%M:%S %p", t, pt, ptlim, warnp);
+			continue;
+		case 'S':
+			pt = _conv(t->tm_sec, L"%02d", pt, ptlim);
+			continue;
+		case 's':
+			{
+				struct tm	tm;
+				wchar_t		buf[INT_STRLEN_MAXIMUM(
+							time_t) + 1];
+				time_t		mkt;
+
+				tm = *t;
+				mkt = mktime(&tm);
+				if (TYPE_SIGNED(time_t))
+					(void) swprintf(buf, 
+					    sizeof buf/sizeof buf[0],
+					    L"%ld", (long) mkt);
+				else	
+					(void) swprintf(buf, 
+					    sizeof buf/sizeof buf[0],
+					    L"%lu", (unsigned long) mkt);
+				pt = _add(buf, pt, ptlim);
+			}
+			continue;
+		case 'T':
+			pt = _fmt(L"%H:%M:%S", t, pt, ptlim, warnp);
+			continue;
+		case 't':
+			pt = _add(L"\t", pt, ptlim);
+			continue;
+		case 'U':
+			pt = _conv((t->tm_yday + DAYSPERWEEK -
+				t->tm_wday) / DAYSPERWEEK,
+				L"%02d", pt, ptlim);
+			continue;
+		case 'u':
+			/*
+			** From Arnold Robbins' strftime version 3.0:
+			** "ISO 8601: Weekday as a decimal number
+			** [1 (Monday) - 7]"
+			** (ado, 1993-05-24)
+			*/
+			pt = _conv((t->tm_wday == 0) ?
+				DAYSPERWEEK : t->tm_wday,
+				L"%d", pt, ptlim);
+			continue;
+		case 'V':	/* ISO 8601 week number */
+		case 'G':	/* ISO 8601 year (four digits) */
+		case 'g':	/* ISO 8601 year (two digits) */
+/*
+** From Arnold Robbins' strftime version 3.0: "the week number of the
+** year (the first Monday as the first day of week 1) as a decimal number
+** (01-53)."
+** (ado, 1993-05-24)
+**
+** From "http://www.ft.uni-erlangen.de/~mskuhn/iso-time.html" by Markus Kuhn:
+** "Week 01 of a year is per definition the first week which has the
+** Thursday in this year, which is equivalent to the week which contains
+** the fourth day of January. In other words, the first week of a new year
+** is the week which has the majority of its days in the new year. Week 01
+** might also contain days from the previous year and the week before week
+** 01 of a year is the last week (52 or 53) of the previous year even if
+** it contains days from the new year. A week starts with Monday (day 1)
+** and ends with Sunday (day 7). For example, the first week of the year
+** 1997 lasts from 1996-12-30 to 1997-01-05..."
+** (ado, 1996-01-02)
+*/
+			{
+			int	year;
+			int	base;
+			int	yday;
+			int	wday;
+			int	w;
+
+			year = t->tm_year;
+			base = TM_YEAR_BASE;
+			yday = t->tm_yday;
+			wday = t->tm_wday;
+			for ( ; ; ) {
+				int	len;
+				int	bot;
+				int	top;
+
+				len = isleap_sum(year, base) ?
+					DAYSPERLYEAR :
+					DAYSPERNYEAR;
+				/*
+				** What yday (-3 ... 3) does the ISO year 
+				** begin on?
+				*/
+				bot = ((yday + 11 - wday) % DAYSPERWEEK) - 3;
+				/*
+				** What yday does the NEXT ISO year begin on?
+				*/
+				top = bot - (len % DAYSPERWEEK);
+				if (top < -3)
+					top += DAYSPERWEEK;
+				top += len;
+				if (yday >= top) {
+					++base;
+					w = 1;
+					break;
+				}
+				if (yday >= bot) {
+					w = 1 + ((yday - bot) / DAYSPERWEEK);
+					break;
+				}
+				--base;
+				yday += isleap_sum(year, base) ?
+					DAYSPERLYEAR :
+					DAYSPERNYEAR;
+			}
+			if ((w == 52 && t->tm_mon == TM_JANUARY) ||
+				(w == 1 && t->tm_mon == TM_DECEMBER))
+					w = 53;
+			if (*format == 'V')
+				pt = _conv(w, L"%02d", pt, ptlim);
+			else if (*format == 'g') {
+				*warnp = IN_ALL;
+				pt = _yconv(year, base, 0, 1, pt, ptlim);
+			} else	
+				pt = _yconv(year, base, 1, 1, pt, ptlim);
+			}
+			continue;
+		case 'v':
+			/*
+			** From Arnold Robbins' strftime version 3.0:
+			** "date as dd-bbb-YYYY"
+			** (ado, 1993-05-24)
+			*/
+			pt = _fmt(L"%e-%b-%Y", t, pt, ptlim, warnp);
+			continue;
+		case 'W':
+			pt = _conv((t->tm_yday + DAYSPERWEEK -
+				(t->tm_wday ?
+				(t->tm_wday - 1) :
+				(DAYSPERWEEK - 1))) / DAYSPERWEEK,
+				L"%02d", pt, ptlim);
+			continue;
+		case 'w':
+			pt = _conv(t->tm_wday, L"%d", pt, ptlim);
+			continue;
+		case 'X':
+			pt = _fmt(Locale->X_fmt, t, pt, ptlim, warnp);
+			continue;
+		case 'x':
+			{
+			int	warn2 = IN_SOME;
+
+			pt = _fmt(Locale->x_fmt, t, pt, ptlim, &warn2);
+			if (warn2 == IN_ALL)
+				warn2 = IN_THIS;
+			if (warn2 > *warnp)
+				*warnp = warn2;
+			}
+			continue;
+		case 'y':
+			*warnp = IN_ALL;
+			pt = _yconv(t->tm_year, TM_YEAR_BASE, 0, 1, pt, ptlim);
+			continue;
+		case 'Y':
+			pt = _yconv(t->tm_year, TM_YEAR_BASE, 1, 1, pt, ptlim);
+			continue;
+		case 'Z':
+			if (t->tm_zone != NULL)
+				pt = _sadd(t->TM_ZONE, pt, ptlim);
+			else
+				if (t->tm_isdst >= 0)
+					pt = _sadd(tzname[t->tm_isdst != 0], 
+					    pt, ptlim);
+			/*
+			** C99 says that %Z must be replaced by the
+			** empty string if the time zone is not
+			** determinable.
+			*/
+			continue;
+		case 'z':
+			{
+			int		diff;
+			wchar_t const *	sign;
+
+			if (t->tm_isdst < 0)
+				continue;
+			diff = t->tm_gmtoff;
+			if (diff < 0) {
+				sign = L"-";
+				diff = -diff;
+			} else	
+				sign = L"+";
+			pt = _add(sign, pt, ptlim);
+			diff /= SECSPERMIN;
+			diff = (diff / MINSPERHOUR) * 100 +
+				(diff % MINSPERHOUR);
+			pt = _conv(diff, L"%04d", pt, ptlim);
+			}
+			continue;
+		case '+':
+			pt = _fmt(Locale->date_fmt, t, pt, ptlim, warnp);
+			continue;
+		case '%':
+		/*
+		** X311J/88-090 (4.12.3.5): if conversion wchar_t is
+		** undefined, behavior is undefined. Print out the
+		** character itself as printf(3) also does.
+		*/
+		default:
+			if (pt != ptlim)
+				*pt++ = *format;
+			break;
+		}
+	}
+	return pt;
+}
+
+static wchar_t *
+_conv(int n, const wchar_t *format, wchar_t *pt, const wchar_t *ptlim)
+{
+	wchar_t	buf[INT_STRLEN_MAXIMUM(int) + 1];
+
+	(void) swprintf(buf, sizeof buf/sizeof buf[0], format, n);
+	return _add(buf, pt, ptlim);
+}
+
+static wchar_t *
+_add(const wchar_t *str, wchar_t *pt, const wchar_t *ptlim)
+{
+	while (pt < ptlim && (*pt = *str++) != L'\0')
+		++pt;
+	return pt;
+}
+
+static wchar_t *
+_sadd(const char *str, wchar_t *pt, const wchar_t *ptlim)
+{
+	while (pt < ptlim && (*pt = btowc(*str++)) != L'\0')
+		++pt;
+	return pt;
+}
+/*
+** POSIX and the C Standard are unclear or inconsistent about
+** what %C and %y do if the year is negative or exceeds 9999.
+** Use the convention that %C concatenated with %y yields the
+** same output as %Y, and that %Y contains at least 4 bytes,
+** with more only if necessary.
+*/
+
+static wchar_t *
+_yconv(int a, int b, int convert_top, int convert_yy, wchar_t *pt, 
+    const wchar_t *ptlim)
+{
+	register int	lead;
+	register int	trail;
+
+#define DIVISOR	100
+	trail = a % DIVISOR + b % DIVISOR;
+	lead = a / DIVISOR + b / DIVISOR + trail / DIVISOR;
+	trail %= DIVISOR;
+	if (trail < 0 && lead > 0) {
+		trail += DIVISOR;
+		--lead;
+	} else if (lead < 0 && trail > 0) {
+		trail -= DIVISOR;
+		++lead;
+	}
+	if (convert_top) {
+		if (lead == 0 && trail < 0)
+			pt = _add(L"-0", pt, ptlim);
+		else	pt = _conv(lead, L"%02d", pt, ptlim);
+	}
+	if (convert_yy)
+		pt = _conv(((trail < 0) ? -trail : trail), L"%02d", pt, ptlim);
+	return pt;
+}
+
diff --git a/linker/linker.cpp b/linker/linker.cpp
index 4d8563e..08231ea 100755
--- a/linker/linker.cpp
+++ b/linker/linker.cpp
@@ -680,6 +680,9 @@
       return fd;
     }
     // ...but nvidia binary blobs (at least) rely on this behavior, so fall through for now.
+#if defined(__LP64__)
+    return -1;
+#endif
   }
 
   // Otherwise we try LD_LIBRARY_PATH first, and fall back to the built-in well known paths.
diff --git a/tests/wchar_test.cpp b/tests/wchar_test.cpp
index f6c2683..a92ac9d 100644
--- a/tests/wchar_test.cpp
+++ b/tests/wchar_test.cpp
@@ -18,6 +18,7 @@
 
 #include <errno.h>
 #include <limits.h>
+#include <locale.h>
 #include <stdint.h>
 #include <wchar.h>
 
@@ -49,18 +50,46 @@
   EXPECT_EQ(1U, wcrtomb(bytes, L'\0', NULL));
 
   // ...and for regular characters.
-  bytes[0] = 'x';
+  memset(bytes, 0, sizeof(bytes));
   EXPECT_EQ(1, wctomb(bytes, L'h'));
   EXPECT_EQ('h', bytes[0]);
-
-  bytes[0] = 'x';
+  memset(bytes, 0, sizeof(bytes));
   EXPECT_EQ(1U, wcrtomb(bytes, L'h', NULL));
   EXPECT_EQ('h', bytes[0]);
+
+  ASSERT_STREQ("C.UTF-8", setlocale(LC_CTYPE, "C.UTF-8"));
+  uselocale(LC_GLOBAL_LOCALE);
+
+  // 1-byte UTF-8.
+  memset(bytes, 0, sizeof(bytes));
+  EXPECT_EQ(1U, wcrtomb(bytes, L'h', NULL));
+  EXPECT_EQ('h', bytes[0]);
+  // 2-byte UTF-8.
+  memset(bytes, 0, sizeof(bytes));
+  EXPECT_EQ(2U, wcrtomb(bytes, 0x00a2, NULL));
+  EXPECT_EQ('\xc2', bytes[0]);
+  EXPECT_EQ('\xa2', bytes[1]);
+  // 3-byte UTF-8.
+  memset(bytes, 0, sizeof(bytes));
+  EXPECT_EQ(3U, wcrtomb(bytes, 0x20ac, NULL));
+  EXPECT_EQ('\xe2', bytes[0]);
+  EXPECT_EQ('\x82', bytes[1]);
+  EXPECT_EQ('\xac', bytes[2]);
+  // 4-byte UTF-8.
+  memset(bytes, 0, sizeof(bytes));
+  EXPECT_EQ(4U, wcrtomb(bytes, 0x24b62, NULL));
+  EXPECT_EQ('\xf0', bytes[0]);
+  EXPECT_EQ('\xa4', bytes[1]);
+  EXPECT_EQ('\xad', bytes[2]);
+  EXPECT_EQ('\xa2', bytes[3]);
+  // Invalid code point.
+  EXPECT_EQ(static_cast<size_t>(-1), wcrtomb(bytes, 0xffffffff, NULL));
+  EXPECT_EQ(EILSEQ, errno);
 }
 
 TEST(wchar, wcstombs_wcrtombs) {
   const wchar_t chars[] = { L'h', L'e', L'l', L'l', L'o', 0 };
-  const wchar_t bad_chars[] = { L'h', L'i', 666, 0 };
+  const wchar_t bad_chars[] = { L'h', L'i', static_cast<wchar_t>(0xffffffff), 0 };
   const wchar_t* src;
   char bytes[BUFSIZ];
 
@@ -212,6 +241,30 @@
   ASSERT_EQ(1U, mbrtowc(NULL, "hello", 1, NULL));
 
   ASSERT_EQ(0U, mbrtowc(NULL, NULL, 0, NULL));
+
+  ASSERT_STREQ("C.UTF-8", setlocale(LC_CTYPE, "C.UTF-8"));
+  uselocale(LC_GLOBAL_LOCALE);
+
+  // 1-byte UTF-8.
+  ASSERT_EQ(1U, mbrtowc(out, "abcdef", 6, NULL));
+  ASSERT_EQ(L'a', out[0]);
+  // 2-byte UTF-8.
+  ASSERT_EQ(2U, mbrtowc(out, "\xc2\xa2" "cdef", 6, NULL));
+  ASSERT_EQ(0x00a2, out[0]);
+  // 3-byte UTF-8.
+  ASSERT_EQ(3U, mbrtowc(out, "\xe2\x82\xac" "def", 6, NULL));
+  ASSERT_EQ(0x20ac, out[0]);
+  // 4-byte UTF-8.
+  ASSERT_EQ(4U, mbrtowc(out, "\xf0\xa4\xad\xa2" "ef", 6, NULL));
+  ASSERT_EQ(0x24b62, out[0]);
+#if __BIONIC__ // glibc allows this.
+  // Illegal 5-byte UTF-8.
+  ASSERT_EQ(static_cast<size_t>(-1), mbrtowc(out, "\xf8\xa1\xa2\xa3\xa4" "f", 6, NULL));
+  ASSERT_EQ(EILSEQ, errno);
+#endif
+  // Illegal over-long sequence.
+  ASSERT_EQ(static_cast<size_t>(-1), mbrtowc(out, "\xf0\x82\x82\xac" "ef", 6, NULL));
+  ASSERT_EQ(EILSEQ, errno);
 }
 
 TEST(wchar, wcstod) {
@@ -266,3 +319,18 @@
   ASSERT_EQ(L'l', dst[2]);
   ASSERT_EQ(&s[3], src);
 }
+
+TEST(wchar, wcsftime) {
+  setenv("TZ", "UTC", 1);
+
+  struct tm t;
+  memset(&t, 0, sizeof(tm));
+  t.tm_year = 200;
+  t.tm_mon = 2;
+  t.tm_mday = 10;
+
+  wchar_t buf[64];
+
+  EXPECT_EQ(24U, wcsftime(buf, sizeof(buf), L"%c", &t));
+  EXPECT_STREQ(L"Sun Mar 10 00:00:00 2100", buf);
+}