Improve stack overflow diagnostics (take 2).

This reverts commits eb1b07469f2b5a392dc1bfd8adc211aea8c72bc5 and
d14dc3b87fbf80553f1cafa453816b7f11366627, and fixes the bug where
we were calling mmap (which might cause errno to be set) before
__set_tls (which is required to implement errno).

Bug: 8557703
Change-Id: I2c36d00240c56e156e1bb430d8c22a73a068b70c
diff --git a/libc/bionic/pthread.c b/libc/bionic/pthread.c
index 8589cd6..92e2c27 100644
--- a/libc/bionic/pthread.c
+++ b/libc/bionic/pthread.c
@@ -31,6 +31,7 @@
 #include <errno.h>
 #include <limits.h>
 #include <sys/atomics.h>
+#include <sys/mman.h>
 #include <unistd.h>
 
 #include "bionic_atomic_inline.h"
@@ -102,6 +103,18 @@
     // space (see pthread_key_delete)
     pthread_key_clean_all();
 
+    if (thread->alternate_signal_stack != NULL) {
+      // Tell the kernel to stop using the alternate signal stack.
+      stack_t ss;
+      ss.ss_sp = NULL;
+      ss.ss_flags = SS_DISABLE;
+      sigaltstack(&ss, NULL);
+
+      // Free it.
+      munmap(thread->alternate_signal_stack, SIGSTKSZ);
+      thread->alternate_signal_stack = NULL;
+    }
+
     // if the thread is detached, destroy the pthread_internal_t
     // otherwise, keep it in memory and signal any joiners.
     pthread_mutex_lock(&gThreadListLock);