threads.h: Add C11 thread support.

FreeBSD, glibc, and musl have all implemented C11 threads at this
point. POSIX is looking at how to align with it. Probably time to jump
on the bandwagon ourselves...

Implemented in the same style as <termios.h> so we can provide this
functionality even on older API levels. This does mean that this is
strictly more expensive than calling pthread functions directly.

Although this isn't in POSIX yet, assume that it's going to be basically
the same as C11 and add the header test anyway. We should revisit this
when POSIX actually adds <threads.h>.

Test: new tests
Change-Id: I8602d67ce71ca7f8ed1529daa0a8ea1feb083dd6
diff --git a/libc/Android.bp b/libc/Android.bp
index d8a1d70..e91038f 100644
--- a/libc/Android.bp
+++ b/libc/Android.bp
@@ -1153,6 +1153,7 @@
         "bionic/tdestroy.cpp",
         "bionic/termios.cpp",
         "bionic/thread_private.cpp",
+        "bionic/threads.cpp",
         "bionic/timespec_get.cpp",
         "bionic/tmpfile.cpp",
         "bionic/umount.cpp",
diff --git a/libc/bionic/threads.cpp b/libc/bionic/threads.cpp
new file mode 100644
index 0000000..f597580
--- /dev/null
+++ b/libc/bionic/threads.cpp
@@ -0,0 +1,32 @@
+/*
+ * Copyright (C) 2019 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 <threads.h>
+
+#define __BIONIC_THREADS_INLINE /* Out of line. */
+#include <bits/threads_inlines.h>
diff --git a/libc/include/android/api-level.h b/libc/include/android/api-level.h
index a175857..af7cde1 100644
--- a/libc/include/android/api-level.h
+++ b/libc/include/android/api-level.h
@@ -100,6 +100,9 @@
 /** Names the "Q" API level (29), for comparisons against __ANDROID_API__. */
 #define __ANDROID_API_Q__ 29
 
+/** Names the "R" API level (30), for comparisons against __ANDROID_API__. */
+#define __ANDROID_API_R__ 30
+
 /**
  * Returns the `targetSdkVersion` of the caller, or `__ANDROID_API_FUTURE__`
  * if there is no known target SDK version (for code not running in the
diff --git a/libc/include/android/legacy_threads_inlines.h b/libc/include/android/legacy_threads_inlines.h
new file mode 100644
index 0000000..e73ef37
--- /dev/null
+++ b/libc/include/android/legacy_threads_inlines.h
@@ -0,0 +1,38 @@
+/*
+ * Copyright (C) 2019 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>
+
+#if __ANDROID_API__ < __ANDROID_API_R__
+
+#define __BIONIC_THREADS_INLINE static __inline
+#include <bits/threads_inlines.h>
+
+#endif
diff --git a/libc/include/bits/threads_inlines.h b/libc/include/bits/threads_inlines.h
new file mode 100644
index 0000000..1130b3a
--- /dev/null
+++ b/libc/include/bits/threads_inlines.h
@@ -0,0 +1,207 @@
+/*
+ * Copyright (C) 2019 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 <threads.h>
+
+#include <errno.h>
+#include <sched.h>
+#include <stdlib.h>
+
+#if !defined(__BIONIC_THREADS_INLINE)
+#define __BIONIC_THREADS_INLINE static __inline
+#endif
+
+__BEGIN_DECLS
+
+static __inline int __bionic_thrd_error(int __pthread_code) {
+  switch (__pthread_code) {
+    case 0: return 0;
+    case ENOMEM: return thrd_nomem;
+    case ETIMEDOUT: return thrd_timedout;
+    case EBUSY: return thrd_busy;
+    default: return thrd_error;
+  }
+}
+
+__BIONIC_THREADS_INLINE void call_once(once_flag* __flag,
+                                       void (*__function)(void)) {
+  pthread_once(__flag, __function);
+}
+
+
+
+__BIONIC_THREADS_INLINE int cnd_broadcast(cnd_t* __cnd) {
+  return __bionic_thrd_error(pthread_cond_broadcast(__cnd));
+}
+
+__BIONIC_THREADS_INLINE void cnd_destroy(cnd_t* __cnd) {
+  pthread_cond_destroy(__cnd);
+}
+
+__BIONIC_THREADS_INLINE int cnd_init(cnd_t* __cnd) {
+  return __bionic_thrd_error(pthread_cond_init(__cnd, NULL));
+}
+
+__BIONIC_THREADS_INLINE int cnd_signal(cnd_t* __cnd) {
+  return __bionic_thrd_error(pthread_cond_signal(__cnd));
+}
+
+__BIONIC_THREADS_INLINE int cnd_timedwait(cnd_t* __cnd,
+                                          mtx_t* __mtx,
+                                          const struct timespec* __timeout) {
+  return __bionic_thrd_error(pthread_cond_timedwait(__cnd, __mtx, __timeout));
+}
+
+__BIONIC_THREADS_INLINE int cnd_wait(cnd_t* __cnd, mtx_t* __mtx) {
+  return __bionic_thrd_error(pthread_cond_wait(__cnd, __mtx));
+}
+
+
+
+__BIONIC_THREADS_INLINE void mtx_destroy(mtx_t* __mtx) {
+  pthread_mutex_destroy(__mtx);
+}
+
+__BIONIC_THREADS_INLINE int mtx_init(mtx_t* __mtx, int __type) {
+  int __pthread_type = (__type & mtx_recursive) ? PTHREAD_MUTEX_RECURSIVE
+                                                : PTHREAD_MUTEX_NORMAL;
+  __type &= ~mtx_recursive;
+  if (__type != mtx_plain && __type != mtx_timed) return thrd_error;
+
+  pthread_mutexattr_t __attr;
+  pthread_mutexattr_init(&__attr);
+  pthread_mutexattr_settype(&__attr, __pthread_type);
+  return __bionic_thrd_error(pthread_mutex_init(__mtx, &__attr));
+}
+
+__BIONIC_THREADS_INLINE int mtx_lock(mtx_t* __mtx) {
+  return __bionic_thrd_error(pthread_mutex_lock(__mtx));
+}
+
+__BIONIC_THREADS_INLINE int mtx_timedlock(mtx_t* __mtx,
+                                          const struct timespec* __timeout) {
+  return __bionic_thrd_error(pthread_mutex_timedlock(__mtx, __timeout));
+}
+
+__BIONIC_THREADS_INLINE int mtx_trylock(mtx_t* __mtx) {
+  return __bionic_thrd_error(pthread_mutex_trylock(__mtx));
+}
+
+__BIONIC_THREADS_INLINE int mtx_unlock(mtx_t* __mtx) {
+  return __bionic_thrd_error(pthread_mutex_unlock(__mtx));
+}
+
+
+
+struct __bionic_thrd_data {
+  thrd_start_t __func;
+  void* __arg;
+};
+
+static inline void* __bionic_thrd_trampoline(void* __arg) {
+  struct __bionic_thrd_data __data =
+      *__BIONIC_CAST(static_cast, struct __bionic_thrd_data*, __arg);
+  free(__arg);
+  int __result = __data.__func(__data.__arg);
+  return __BIONIC_CAST(reinterpret_cast, void*,
+                       __BIONIC_CAST(static_cast, uintptr_t, __result));
+}
+
+__BIONIC_THREADS_INLINE int thrd_create(thrd_t* __thrd,
+                                        thrd_start_t __func,
+                                        void* __arg) {
+  struct __bionic_thrd_data* __pthread_arg =
+      __BIONIC_CAST(static_cast, struct __bionic_thrd_data*,
+                    malloc(sizeof(struct __bionic_thrd_data)));
+  __pthread_arg->__func = __func;
+  __pthread_arg->__arg = __arg;
+  int __result = __bionic_thrd_error(pthread_create(__thrd, NULL,
+                                                    __bionic_thrd_trampoline,
+                                                    __pthread_arg));
+  if (__result != thrd_success) free(__pthread_arg);
+  return __result;
+}
+
+__BIONIC_THREADS_INLINE thrd_t thrd_current(void) {
+  return pthread_self();
+}
+
+__BIONIC_THREADS_INLINE int thrd_detach(thrd_t __thrd) {
+  return __bionic_thrd_error(pthread_detach(__thrd));
+}
+
+__BIONIC_THREADS_INLINE int thrd_equal(thrd_t __lhs, thrd_t __rhs) {
+  return pthread_equal(__lhs, __rhs);
+}
+
+__BIONIC_THREADS_INLINE void thrd_exit(int __result) {
+  pthread_exit(__BIONIC_CAST(reinterpret_cast, void*,
+                             __BIONIC_CAST(static_cast, uintptr_t, __result)));
+}
+
+__BIONIC_THREADS_INLINE int thrd_join(thrd_t __thrd, int* __result) {
+  void* __pthread_result;
+  if (pthread_join(__thrd, &__pthread_result) != 0) return thrd_error;
+  if (__result) {
+    *__result = __BIONIC_CAST(reinterpret_cast, intptr_t, __pthread_result);
+  }
+  return thrd_success;
+}
+
+__BIONIC_THREADS_INLINE int thrd_sleep(const struct timespec* __duration,
+                                       struct timespec* __remaining) {
+  int __rc = nanosleep(__duration, __remaining);
+  if (__rc == 0) return 0;
+  return (errno == EINTR) ? -1 : -2;
+}
+
+__BIONIC_THREADS_INLINE void thrd_yield(void) {
+  sched_yield();
+}
+
+
+
+__BIONIC_THREADS_INLINE int tss_create(tss_t* __key, tss_dtor_t __dtor) {
+  return __bionic_thrd_error(pthread_key_create(__key, __dtor));
+}
+
+__BIONIC_THREADS_INLINE void tss_delete(tss_t __key) {
+  pthread_key_delete(__key);
+}
+
+__BIONIC_THREADS_INLINE void* tss_get(tss_t __key) {
+  return pthread_getspecific(__key);
+}
+
+__BIONIC_THREADS_INLINE int tss_set(tss_t __key, void* __value) {
+  return __bionic_thrd_error(pthread_setspecific(__key, __value));
+}
+
+__END_DECLS
diff --git a/libc/include/threads.h b/libc/include/threads.h
new file mode 100644
index 0000000..2c43b0b
--- /dev/null
+++ b/libc/include/threads.h
@@ -0,0 +1,228 @@
+/*
+ * Copyright (C) 2019 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
+
+/**
+ * @file threads.h
+ * @brief C11 threads.
+ */
+
+#include <sys/cdefs.h>
+
+#include <pthread.h>
+#include <time.h>
+
+#define ONCE_FLAG_INIT PTHREAD_ONCE_INIT
+#define TSS_DTOR_ITERATIONS PTHREAD_DESTRUCTOR_ITERATIONS
+
+/** The type for a condition variable. */
+typedef pthread_cond_t cnd_t;
+/** The type for a thread. */
+typedef pthread_t thrd_t;
+/** The type for a thread-specific storage key. */
+typedef pthread_key_t tss_t;
+/** The type for a mutex. */
+typedef pthread_mutex_t mtx_t;
+
+/** The type for a thread-specific storage destructor. */
+typedef void (*tss_dtor_t)(void*);
+/** The type of the function passed to thrd_create() to create a new thread. */
+typedef int (*thrd_start_t)(void*);
+
+/** The type used by call_once(). */
+typedef pthread_once_t once_flag;
+
+enum {
+  mtx_plain = 0x1,
+  mtx_recursive = 0x2,
+  mtx_timed = 0x4,
+};
+
+enum {
+  thrd_success = 0,
+  thrd_busy = 1,
+  thrd_error = 2,
+  thrd_nomem = 3,
+  thrd_timedout = 4,
+};
+
+#if !defined(__cplusplus)
+#define thread_local _Thread_local
+#endif
+
+__BEGIN_DECLS
+
+#if __ANDROID_API__ >= __ANDROID_API_R__
+// This file is implemented as static inlines before API level 30.
+
+/** Uses `__flag` to ensure that `__function` is called exactly once. */
+void call_once(once_flag* __flag, void (*__function)(void));
+
+
+
+/**
+ * Unblocks all threads blocked on `__cond`.
+ */
+int cnd_broadcast(cnd_t* __cond);
+
+/**
+ * Destroys a condition variable.
+ */
+void cnd_destroy(cnd_t* __cond);
+
+/**
+ * Creates a condition variable.
+ */
+int cnd_init(cnd_t* __cond);
+
+/**
+ * Unblocks one thread blocked on `__cond`.
+ */
+int cnd_signal(cnd_t* __cond);
+
+/**
+ * Unlocks `__mutex` and blocks until `__cond` is signaled or `__timeout` occurs.
+ */
+int cnd_timedwait(cnd_t* __cond, mtx_t* __mutex, const struct timespec* __timeout);
+
+/**
+ * Unlocks `__mutex` and blocks until `__cond` is signaled.
+ */
+int cnd_wait(cnd_t* __cond, mtx_t* __mutex);
+
+
+
+/**
+ * Destroys a mutex.
+ */
+void mtx_destroy(mtx_t* __mutex);
+
+/**
+ * Creates a mutex.
+ */
+int mtx_init(mtx_t* __mutex, int __type);
+
+/**
+ * Blocks until `__mutex` is acquired.
+ */
+int mtx_lock(mtx_t* __mutex);
+
+/**
+ * Blocks until `__mutex` is acquired or `__timeout` expires.
+ */
+int mtx_timedlock(mtx_t* __mutex, const struct timespec* __timeout);
+
+/**
+ * Acquires `__mutex` or returns `thrd_busy`.
+ */
+int mtx_trylock(mtx_t* __mutex);
+
+/**
+ * Unlocks `__mutex`.
+ */
+int mtx_unlock(mtx_t* __mutex);
+
+
+
+/**
+ * Creates a new thread running `__function(__arg)`, and sets `*__thrd` to
+ * the new thread.
+ */
+int thrd_create(thrd_t* __thrd, thrd_start_t __function, void* __arg);
+
+/**
+ * Returns the `thrd_t` corresponding to the caller.
+ */
+thrd_t thrd_current(void);
+
+/**
+ * Tells the OS to automatically dispose of `__thrd` when it exits.
+ */
+int thrd_detach(thrd_t __thrd);
+
+/**
+ * Tests whether two threads are the same thread.
+ */
+int thrd_equal(thrd_t __lhs, thrd_t __rhs);
+
+/**
+ * Terminates the calling thread, setting its result to `__result`.
+ */
+void thrd_exit(int __result) __noreturn;
+
+/**
+ * Blocks until `__thrd` terminates. If `__result` is not null, `*__result`
+ * is set to the exiting thread's result.
+ */
+int thrd_join(thrd_t __thrd, int* __result);
+
+/**
+ * Blocks the caller for at least `__duration` unless a signal is delivered.
+ * If a signal causes the sleep to end early and `__remaining` is not null,
+ * `*__remaining` is set to the time remaining.
+ *
+ * Returns 0 on success, or -1 if a signal was delivered.
+ */
+int thrd_sleep(const struct timespec* __duration, struct timespec* __remaining);
+
+/**
+ * Request that other threads should be scheduled.
+ */
+void thrd_yield(void);
+
+
+
+/**
+ * Creates a thread-specific storage key with the associated destructor (which
+ * may be null).
+ */
+int tss_create(tss_t* __key, tss_dtor_t __dtor);
+
+/**
+ * Destroys a thread-specific storage key.
+ */
+void tss_delete(tss_t __key);
+
+/**
+ * Returns the value for the current thread held in the thread-specific storage
+ * identified by `__key`.
+ */
+void* tss_get(tss_t __key);
+
+/**
+ * Sets the current thread's value for the thread-specific storage identified
+ * by `__key` to `__value`.
+ */
+int tss_set(tss_t __key, void* __value);
+
+#endif
+
+__END_DECLS
+
+#include <android/legacy_threads_inlines.h>
diff --git a/libc/libc.map.txt b/libc/libc.map.txt
index 55ca9dc..5e49d3a 100644
--- a/libc/libc.map.txt
+++ b/libc/libc.map.txt
@@ -1485,6 +1485,35 @@
     android_mallopt; # apex
 } LIBC_P;
 
+LIBC_R { # introduced=R
+  global:
+    call_once;
+    cnd_broadcast;
+    cnd_destroy;
+    cnd_init;
+    cnd_signal;
+    cnd_timedwait;
+    cnd_wait;
+    mtx_destroy;
+    mtx_init;
+    mtx_lock;
+    mtx_timedlock;
+    mtx_trylock;
+    mtx_unlock;
+    thrd_create;
+    thrd_current;
+    thrd_detach;
+    thrd_equal;
+    thrd_exit;
+    thrd_join;
+    thrd_sleep;
+    thrd_yield;
+    tss_create;
+    tss_delete;
+    tss_get;
+    tss_set;
+} LIBC_Q;
+
 LIBC_PRIVATE {
   global:
     ___Unwind_Backtrace; # arm