Don't corrupt the thread list if the main thread exits.

...and don't pass a non-heap pointer to free(3), either.

This patch replaces the "node** prev" with the clearer "node* prev"
style and fixes the null pointer dereference in the old code. That's
not sufficient to fix the reporter's bug, though. The pthread_internal_t*
for the main thread isn't heap-allocated --- __libc_init_tls causes a
pointer to a statically-allocated pthread_internal_t to be added to
the thread list.

Bug: http://code.google.com/p/android/issues/detail?id=37410
Change-Id: I112b7f22782fc789d58f9c783f7b323bda8fb8b7
diff --git a/tests/pthread_test.cpp b/tests/pthread_test.cpp
index e400b84..da945b4 100644
--- a/tests/pthread_test.cpp
+++ b/tests/pthread_test.cpp
@@ -109,3 +109,20 @@
   void* result;
   ASSERT_EQ(EDEADLK, pthread_join(pthread_self(), &result));
 }
+
+#if __BIONIC__ // For some reason, gtest on bionic can cope with this but gtest on glibc can't.
+
+static void TestBug37410() {
+  pthread_t t1;
+  ASSERT_EQ(0, pthread_create(&t1, NULL, JoinFn, reinterpret_cast<void*>(pthread_self())));
+  pthread_exit(NULL);
+}
+
+// We have to say "DeathTest" here so gtest knows to run this test (which exits)
+// in its own process.
+TEST(pthread_DeathTest, pthread_bug_37410) {
+  // http://code.google.com/p/android/issues/detail?id=37410
+  ::testing::FLAGS_gtest_death_test_style = "threadsafe";
+  EXPECT_EXIT(TestBug37410(), ::testing::ExitedWithCode(0), "");
+}
+#endif