Revert "Revert "More pthreads cleanup.""

This reverts commit 6f94de3ca49e4ea147b1c59e5818fa175846518f

(Doesn't try to increase the number of TLS slots; that leads to
an inability to boot. Adds more tests.)

Change-Id: Ia7d25ba3995219ed6e686463dbba80c95cc831ca
diff --git a/tests/pthread_test.cpp b/tests/pthread_test.cpp
index 0ccd948..00aa4b1 100644
--- a/tests/pthread_test.cpp
+++ b/tests/pthread_test.cpp
@@ -28,12 +28,14 @@
   ASSERT_EQ(EINVAL, pthread_key_delete(key));
 }
 
+#if !defined(__GLIBC__) // glibc uses keys internally that its sysconf value doesn't account for.
 TEST(pthread, pthread_key_create_lots) {
   // We can allocate _SC_THREAD_KEYS_MAX keys.
   std::vector<pthread_key_t> keys;
   for (int i = 0; i < sysconf(_SC_THREAD_KEYS_MAX); ++i) {
     pthread_key_t key;
-    ASSERT_EQ(0, pthread_key_create(&key, NULL));
+    // If this fails, it's likely that GLOBAL_INIT_THREAD_LOCAL_BUFFER_COUNT is wrong.
+    ASSERT_EQ(0, pthread_key_create(&key, NULL)) << i << " of " << sysconf(_SC_THREAD_KEYS_MAX);
     keys.push_back(key);
   }
 
@@ -46,6 +48,7 @@
     ASSERT_EQ(0, pthread_key_delete(keys[i]));
   }
 }
+#endif
 
 static void* IdFn(void* arg) {
   return arg;
@@ -87,6 +90,15 @@
   ASSERT_EQ(expected_result, result);
 }
 
+TEST(pthread, pthread_create_EAGAIN) {
+  pthread_attr_t attributes;
+  ASSERT_EQ(0, pthread_attr_init(&attributes));
+  ASSERT_EQ(0, pthread_attr_setstacksize(&attributes, static_cast<size_t>(-1) & ~(getpagesize() - 1)));
+
+  pthread_t t;
+  ASSERT_EQ(EAGAIN, pthread_create(&t, &attributes, IdFn, NULL));
+}
+
 TEST(pthread, pthread_no_join_after_detach) {
   pthread_t t1;
   ASSERT_EQ(0, pthread_create(&t1, NULL, SleepFn, reinterpret_cast<void*>(5)));
@@ -174,7 +186,7 @@
   ASSERT_EQ(0, reinterpret_cast<int>(join_result));
 }
 
-#if !defined(__GLIBC__)
+#if __BIONIC__
 extern "C" int  __pthread_clone(int (*fn)(void*), void* child_stack, int flags, void* arg);
 TEST(pthread, __pthread_clone) {
   uintptr_t fake_child_stack[16];
@@ -183,3 +195,27 @@
   ASSERT_EQ(EINVAL, errno);
 }
 #endif
+
+TEST(pthread, pthread_setname_np__too_long) {
+  ASSERT_EQ(ERANGE, pthread_setname_np(pthread_self(), "this name is far too long for linux"));
+}
+
+TEST(pthread, pthread_setname_np__self) {
+  ASSERT_EQ(0, pthread_setname_np(pthread_self(), "short 1"));
+}
+
+TEST(pthread, pthread_setname_np__other) {
+  pthread_t t1;
+  ASSERT_EQ(0, pthread_create(&t1, NULL, SleepFn, reinterpret_cast<void*>(5)));
+  ASSERT_EQ(0, pthread_setname_np(t1, "short 2"));
+}
+
+TEST(pthread, pthread_setname_np__no_such_thread) {
+  pthread_t t1;
+  ASSERT_EQ(0, pthread_create(&t1, NULL, IdFn, NULL));
+  void* result;
+  ASSERT_EQ(0, pthread_join(t1, &result));
+
+  // Call pthread_setname_np after thread has already exited.
+  ASSERT_EQ(ENOENT, pthread_setname_np(t1, "short 3"));
+}