Merge "Revert "arm64: Use builtin for nearbyintf/nearbyint""
diff --git a/README.md b/README.md
index a6cf467..12c5235 100644
--- a/README.md
+++ b/README.md
@@ -1,13 +1,17 @@
-Using bionic
-============
+# bionic
 
-See the [additional documentation](docs/).
+[bionic](https://en.wikipedia.org/wiki/Bionic_(software)) is Android's
+C library, math library, and dynamic linker.
 
-Working on bionic
-=================
+# Using bionic as an app developer
 
-What are the big pieces of bionic?
-----------------------------------
+See the [user documentation](docs/).
+
+# Working on bionic itself
+
+This documentation is about making changes to bionic itself.
+
+## What are the big pieces of bionic?
 
 #### libc/ --- libc.so, libc.a
 
@@ -51,10 +55,9 @@
 The `benchmarks/` directory contains benchmarks, with its own [documentation](benchmarks/README.md).
 
 
-What's in libc/?
-----------------
+## What's in libc/?
 
-<pre>
+```
 libc/
   arch-arm/
   arch-arm64/
@@ -69,12 +72,6 @@
     bionic/
       # Every architecture needs a handful of machine-specific assembler files.
       # They live here.
-    include/
-      machine/
-        # The majority of header files are actually in libc/include/, but many
-        # of them pull in a <machine/something.h> for things like limits,
-        # endianness, and how floating point numbers are represented. Those
-        # headers live here.
     string/
       # Most architectures have a handful of optional assembler files
       # implementing optimized versions of various routines. The <string.h>
@@ -141,11 +138,10 @@
   zoneinfo/
     # Android-format time zone data.
     # See 'Updating tzdata' later.
-</pre>
+```
 
 
-Adding libc wrappers for system calls
--------------------------------------
+## Adding libc wrappers for system calls
 
 The first question you should ask is "should I add a libc wrapper for
 this system call?". The answer is usually "no".
@@ -183,8 +179,7 @@
      correct system call is being made.)
 
 
-Updating kernel header files
-----------------------------
+## Updating kernel header files
 
 As mentioned above, this is currently a two-step process:
 
@@ -197,8 +192,7 @@
 `TARGET_DEVICE_KERNEL_HEADERS` and friends described in [config.mk](https://android.googlesource.com/platform/build/+/master/core/config.mk#186).
 
 
-Updating tzdata
----------------
+## Updating tzdata
 
 This is fully automated (and these days handled by the libcore team, because
 they own icu, and that needs to be updated in sync with bionic):
@@ -206,8 +200,7 @@
   1. Run update-tzdata.py in external/icu/tools/.
 
 
-Verifying changes
------------------
+## Verifying changes
 
 If you make a change that is likely to have a wide effect on the tree (such as a
 libc header change), you should run `make checkbuild`. A regular `make` will
@@ -218,8 +211,7 @@
 `make checkbuild` is enough.
 
 
-Running the tests
------------------
+## Running the tests
 
 The tests are all built from the tests/ directory.
 
@@ -285,8 +277,7 @@
     $ ./tests/run-on-host.sh glibc
 
 
-Gathering test coverage
------------------------
+## Gathering test coverage
 
 For either host or target coverage, you must first:
 
@@ -319,8 +310,7 @@
 The coverage report is now available at `covreport/index.html`.
 
 
-Attaching GDB to the tests
---------------------------
+## Attaching GDB to the tests
 
 Bionic's test runner will run each test in its own process by default to prevent
 tests failures from impacting other tests. This also has the added benefit of
@@ -330,7 +320,6 @@
 each test from being forked, run the tests with the flag `--no-isolate`.
 
 
-32-bit ABI bugs
----------------
+## 32-bit ABI bugs
 
 See [32-bit ABI bugs](docs/32-bit-abi.md).
diff --git a/docs/status.md b/docs/status.md
index e41baa6..c8c06c6 100644
--- a/docs/status.md
+++ b/docs/status.md
@@ -40,6 +40,12 @@
 New libc functions in Q (API level 29):
   * `timespec_get` (C11 `<time.h>` addition)
   * `res_randomid` (in `<resolv.h>`)
+  * `pthread_sigqueue` (GNU extension)
+
+New libc behavior in Q (API level 29):
+  * Whole printf family now supports the GNU `%m` extension, rather than a special-case hack in `syslog`
+  * `popen` now always uses `O_CLOEXEC`, not just with the `e` extension
+  * Bug fixes to handling of UTF-8 U+fffe/U+ffff and code points above U+10ffff
 
 New libc functions in P (API level 28):
   * `__freading`/`__fwriting` (completing <stdio_ext.h>)
diff --git a/libc/arch-arm64/generic/bionic/__memcpy_chk.S b/libc/arch-arm64/generic/bionic/__memcpy_chk.S
index 4217775..a6eeca4 100644
--- a/libc/arch-arm64/generic/bionic/__memcpy_chk.S
+++ b/libc/arch-arm64/generic/bionic/__memcpy_chk.S
@@ -30,8 +30,11 @@
 
 ENTRY(__memcpy_chk)
   cmp x2, x3
-  bls memcpy
+  // Direct b.ls memcpy may not have enough range
+  b.hi .L_memcpy_chk_fail
+  b memcpy
 
+.L_memcpy_chk_fail:
   // Preserve for accurate backtrace.
   stp x29, x30, [sp, -16]!
   .cfi_def_cfa_offset 16
diff --git a/libc/bionic/NetdClient.cpp b/libc/bionic/NetdClient.cpp
index a1071d2..966cbcc 100644
--- a/libc/bionic/NetdClient.cpp
+++ b/libc/bionic/NetdClient.cpp
@@ -24,6 +24,8 @@
 
 #include <dlfcn.h>
 #include <pthread.h>
+#include <string.h>
+#include <unistd.h>
 
 template <typename FunctionType>
 static void netdClientInitFunction(void* handle, const char* symbol, FunctionType* function) {
@@ -35,6 +37,14 @@
 }
 
 static void netdClientInitImpl() {
+    // Prevent netd from looping back fwmarkd connections to itself. It would work, but it's
+    // a deadlock hazard and unnecessary overhead for the resolver.
+    if (getuid() == 0 && strcmp(getprogname(), "netd") == 0) {
+        async_safe_format_log(ANDROID_LOG_INFO, "netdClient",
+                              "Skipping libnetd_client init since *we* are netd");
+        return;
+    }
+
     void* netdClientHandle = dlopen("libnetd_client.so", RTLD_NOW);
     if (netdClientHandle == NULL) {
         // If the library is not available, it's not an error. We'll just use
@@ -54,6 +64,6 @@
 
 extern "C" __LIBC_HIDDEN__ void netdClientInit() {
     if (pthread_once(&netdClientInitOnce, netdClientInitImpl)) {
-        async_safe_format_log(ANDROID_LOG_ERROR, "netdClient", "Failed to initialize netd_client");
+        async_safe_format_log(ANDROID_LOG_ERROR, "netdClient", "Failed to initialize libnetd_client");
     }
 }
diff --git a/libc/bionic/abort.cpp b/libc/bionic/abort.cpp
index d2c99a5..c8bba01 100644
--- a/libc/bionic/abort.cpp
+++ b/libc/bionic/abort.cpp
@@ -32,32 +32,9 @@
 #include <sys/syscall.h>
 #include <unistd.h>
 
-// We call tgkill(2) directly instead of raise (or even the libc tgkill wrapper), to reduce the
-// number of uninteresting stack frames at the top of a crash.
-static inline __always_inline void inline_tgkill(pid_t pid, pid_t tid, int sig) {
-#if defined(__arm__)
-  register int r0 __asm__("r0") = pid;
-  register int r1 __asm__("r1") = tid;
-  register int r2 __asm__("r2") = sig;
-  register int r7 __asm__("r7") = __NR_tgkill;
-  __asm__("swi #0" : "=r"(r0) : "r"(r0), "r"(r1), "r"(r2), "r"(r7) : "memory");
-#elif defined(__aarch64__)
-  register long x0 __asm__("x0") = pid;
-  register long x1 __asm__("x1") = tid;
-  register long x2 __asm__("x2") = sig;
-  register long x8 __asm__("x8") = __NR_tgkill;
-  __asm__("svc #0" : "=r"(x0) : "r"(x0), "r"(x1), "r"(x2), "r"(x8) : "memory");
-#else
-  syscall(__NR_tgkill, pid, tid, sig);
-#endif
-}
+#include "private/bionic_inline_raise.h"
 
 void abort() {
-  // Protect ourselves against stale cached PID/TID values by fetching them via syscall.
-  // http://b/37769298
-  pid_t pid = syscall(__NR_getpid);
-  pid_t tid = syscall(__NR_gettid);
-
   // Don't block SIGABRT to give any signal handler a chance; we ignore
   // any errors -- X311J doesn't allow abort to return anyway.
   sigset64_t mask;
@@ -65,7 +42,7 @@
   sigdelset64(&mask, SIGABRT);
 
   sigprocmask64(SIG_SETMASK, &mask, nullptr);
-  inline_tgkill(pid, tid, SIGABRT);
+  inline_raise(SIGABRT);
 
   // If SIGABRT is ignored or it's caught and the handler returns,
   // remove the SIGABRT signal handler and raise SIGABRT again.
@@ -73,7 +50,7 @@
   sigaction64(SIGABRT, &sa, nullptr);
 
   sigprocmask64(SIG_SETMASK, &mask, nullptr);
-  inline_tgkill(pid, tid, SIGABRT);
+  inline_raise(SIGABRT);
 
   // If we get this far, just exit.
   _exit(127);
diff --git a/libc/bionic/fdsan.cpp b/libc/bionic/fdsan.cpp
index b5e141a..31ffa96 100644
--- a/libc/bionic/fdsan.cpp
+++ b/libc/bionic/fdsan.cpp
@@ -43,6 +43,7 @@
 #include <sys/system_properties.h>
 
 #include "private/bionic_globals.h"
+#include "private/bionic_inline_raise.h"
 #include "pthread_internal.h"
 
 extern "C" int ___close(int fd);
@@ -200,12 +201,11 @@
       __BIONIC_FALLTHROUGH;
     case ANDROID_FDSAN_ERROR_LEVEL_WARN_ALWAYS:
       // DEBUGGER_SIGNAL
-      sigval abort_msg;
-      abort_msg.sival_ptr = &abort_message;
-      pthread_sigqueue(pthread_self(), __SIGRTMIN + 3, abort_msg);
+      inline_raise(__SIGRTMIN + 3, &abort_message);
       break;
 
     case ANDROID_FDSAN_ERROR_LEVEL_FATAL:
+      inline_raise(SIGABRT);
       abort();
 
     case ANDROID_FDSAN_ERROR_LEVEL_DISABLED:
diff --git a/libc/bionic/syslog.cpp b/libc/bionic/syslog.cpp
index d1a0c5b..6b17d26 100644
--- a/libc/bionic/syslog.cpp
+++ b/libc/bionic/syslog.cpp
@@ -49,8 +49,6 @@
 }
 
 void vsyslog(int priority, const char* fmt, va_list args) {
-  int caller_errno = errno;
-
   // Check whether we're supposed to be logging messages of this priority.
   if ((syslog_priority_mask & LOG_MASK(LOG_PRI(priority))) == 0) {
     return;
@@ -75,48 +73,10 @@
     android_log_priority = ANDROID_LOG_DEBUG;
   }
 
-  // glibc's printf family support %m directly, but our BSD-based one doesn't.
-  // If the format string seems to contain "%m", rewrite it.
-  const char* log_fmt = fmt;
-  if (strstr(fmt, "%m") != nullptr) {
-    size_t dst_len = 1024;
-    char* dst = reinterpret_cast<char*>(malloc(dst_len));
-    log_fmt = dst;
-
-    const char* src = fmt;
-    for (; dst_len > 0 && *src != '\0'; ++src) {
-      if (*src == '%' && *(src + 1) == 'm') {
-        // Expand %m.
-        size_t n = strlcpy(dst, strerror(caller_errno), dst_len);
-        if (n >= dst_len) {
-          n = dst_len;
-        }
-        dst += n;
-        dst_len -= n;
-        ++src;
-      } else if (*src == '%' && *(src + 1) == '%') {
-        // We need to copy pairs of '%'s so the %m test works.
-        if (dst_len <= 2) {
-          break;
-        }
-        *dst++ = '%'; --dst_len;
-        *dst++ = '%'; --dst_len;
-        ++src;
-      } else {
-        *dst++ = *src; --dst_len;
-      }
-    }
-    *dst = '\0';
-  }
-
   // We can't let async_safe_format_log do the formatting because it doesn't support
   // all the printf functionality.
   char log_line[1024];
-  vsnprintf(log_line, sizeof(log_line), log_fmt, args);
-
-  if (log_fmt != fmt) {
-    free(const_cast<char*>(log_fmt));
-  }
+  vsnprintf(log_line, sizeof(log_line), fmt, args);
 
   async_safe_format_log(android_log_priority, log_tag, "%s", log_line);
 }
diff --git a/libc/private/bionic_inline_raise.h b/libc/private/bionic_inline_raise.h
new file mode 100644
index 0000000..7223b4e
--- /dev/null
+++ b/libc/private/bionic_inline_raise.h
@@ -0,0 +1,67 @@
+/*
+ * Copyright (C) 2018 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.
+ */
+
+#pragma once
+
+#include <sys/cdefs.h>
+#include <sys/syscall.h>
+#include <sys/types.h>
+#include <unistd.h>
+
+// An inline version of pthread_sigqueue(pthread_self(), ...), to reduce the number of
+// uninteresting stack frames at the top of a crash.
+static inline __always_inline void inline_raise(int sig, void* value = nullptr) {
+  // Protect ourselves against stale cached PID/TID values by fetching them via syscall.
+  // http://b/37769298
+  pid_t pid = syscall(__NR_getpid);
+  pid_t tid = syscall(__NR_gettid);
+  siginfo_t info = {};
+  info.si_code = SI_QUEUE;
+  info.si_pid = pid;
+  info.si_uid = getuid();
+  info.si_value.sival_ptr = value;
+
+#if defined(__arm__)
+  register long r0 __asm__("r0") = pid;
+  register long r1 __asm__("r1") = tid;
+  register long r2 __asm__("r2") = sig;
+  register long r3 __asm__("r3") = reinterpret_cast<long>(&info);
+  register long r7 __asm__("r7") = __NR_rt_tgsigqueueinfo;
+  __asm__("swi #0" : "=r"(r0) : "r"(r0), "r"(r1), "r"(r2), "r"(r3), "r"(r7) : "memory");
+#elif defined(__aarch64__)
+  register long x0 __asm__("x0") = pid;
+  register long x1 __asm__("x1") = tid;
+  register long x2 __asm__("x2") = sig;
+  register long x3 __asm__("x3") = reinterpret_cast<long>(&info);
+  register long x8 __asm__("x8") = __NR_rt_tgsigqueueinfo;
+  __asm__("svc #0" : "=r"(x0) : "r"(x0), "r"(x1), "r"(x2), "r"(x3), "r"(x8) : "memory");
+#else
+  syscall(__NR_rt_tgsigqueueinfo, pid, tid, sig, &info);
+#endif
+}
+
diff --git a/libc/stdio/vfprintf.cpp b/libc/stdio/vfprintf.cpp
index a14963e..8b247e9 100644
--- a/libc/stdio/vfprintf.cpp
+++ b/libc/stdio/vfprintf.cpp
@@ -43,6 +43,7 @@
 #include "printf_common.h"
 
 int FUNCTION_NAME(FILE* fp, const CHAR_TYPE* fmt0, va_list ap) {
+  int caller_errno = errno;
   int n, n2;
   CHAR_TYPE* cp;            /* handy char pointer (short term usage) */
   CHAR_TYPE sign;           /* sign prefix (' ', '+', '-', or \0) */
@@ -451,6 +452,9 @@
         break;
       case 'n':
         __fortify_fatal("%%n not allowed on Android");
+      case 'm':
+        cp = strerror(caller_errno);
+        goto string;
       case 'O':
         flags |= LONGINT;
         __BIONIC_FALLTHROUGH;
@@ -493,6 +497,7 @@
         } else if ((cp = GETARG(char*)) == nullptr) {
           cp = const_cast<char*>("(null)");
         }
+  string:
         if (prec >= 0) {
           size = CHAR_TYPE_STRNLEN(cp, prec);
         } else {
diff --git a/libc/stdio/vfwprintf.cpp b/libc/stdio/vfwprintf.cpp
index 1c3b80d..19cce17 100644
--- a/libc/stdio/vfwprintf.cpp
+++ b/libc/stdio/vfwprintf.cpp
@@ -43,6 +43,7 @@
 #include "printf_common.h"
 
 int FUNCTION_NAME(FILE* fp, const CHAR_TYPE* fmt0, va_list ap) {
+  int caller_errno = errno;
   int n, n2;
   CHAR_TYPE* cp;   /* handy char pointer (short term usage) */
   CHAR_TYPE sign;  /* sign prefix (' ', '+', '-', or \0) */
@@ -436,6 +437,16 @@
         break;
       case 'n':
         __fortify_fatal("%%n not allowed on Android");
+      case 'm':
+        free(convbuf);
+        convbuf = helpers::mbsconv(strerror(caller_errno), prec);
+        if (convbuf == nullptr) {
+            fp->_flags |= __SERR;
+            goto error;
+        } else {
+            cp = convbuf;
+        }
+        goto string;
       case 'O':
         flags |= LONGINT;
         __BIONIC_FALLTHROUGH;
@@ -474,6 +485,7 @@
             cp = convbuf;
           }
         }
+  string:
         if (prec >= 0) {
           size = CHAR_TYPE_STRNLEN(cp, prec);
         } else {
diff --git a/tests/stdio_test.cpp b/tests/stdio_test.cpp
index d96da02..4107a74 100644
--- a/tests/stdio_test.cpp
+++ b/tests/stdio_test.cpp
@@ -2356,6 +2356,32 @@
   ASSERT_EQ(buf, "hello");
 }
 
+TEST(STDIO_TEST, printf_m) {
+  char buf[BUFSIZ];
+  errno = 0;
+  snprintf(buf, sizeof(buf), "<%m>");
+  ASSERT_STREQ("<Success>", buf);
+  errno = -1;
+  snprintf(buf, sizeof(buf), "<%m>");
+  ASSERT_STREQ("<Unknown error -1>", buf);
+  errno = EINVAL;
+  snprintf(buf, sizeof(buf), "<%m>");
+  ASSERT_STREQ("<Invalid argument>", buf);
+}
+
+TEST(STDIO_TEST, wprintf_m) {
+  wchar_t buf[BUFSIZ];
+  errno = 0;
+  swprintf(buf, sizeof(buf), L"<%m>");
+  ASSERT_EQ(std::wstring(L"<Success>"), buf);
+  errno = -1;
+  swprintf(buf, sizeof(buf), L"<%m>");
+  ASSERT_EQ(std::wstring(L"<Unknown error -1>"), buf);
+  errno = EINVAL;
+  swprintf(buf, sizeof(buf), L"<%m>");
+  ASSERT_EQ(std::wstring(L"<Invalid argument>"), buf);
+}
+
 TEST(STDIO_TEST, fopen_append_mode_and_ftell) {
   TemporaryFile tf;
   SetFileTo(tf.filename, "0123456789");