Make sure the thread is dead before re-using its stack!

llvm-svn: 120169
diff --git a/vmkit/include/mvm/Threads/Thread.h b/vmkit/include/mvm/Threads/Thread.h
index f6c8434..2a203d4 100644
--- a/vmkit/include/mvm/Threads/Thread.h
+++ b/vmkit/include/mvm/Threads/Thread.h
@@ -14,6 +14,7 @@
 #include <cstdio>
 #include <stdlib.h>
 
+#include "debug.h"
 #include "types.h"
 
 #ifdef RUNTIME_DWARF_EXCEPTIONS
@@ -292,11 +293,11 @@
   /// Thread. The thread object is inlined in the stack.
   ///
   void* operator new(size_t sz);
-  void operator delete(void* th) {}
+  void operator delete(void* th) { UNREACHABLE(); }
   
   /// releaseThread - Free the stack so that another thread can use it.
   ///
-  static void releaseThread(void* th);
+  static void releaseThread(mvm::Thread* th);
 
   /// routine - The function to invoke when the thread starts.
   ///
diff --git a/vmkit/lib/J3/Classpath/ClasspathReflect.h b/vmkit/lib/J3/Classpath/ClasspathReflect.h
index c34852fe..1bb6240 100644
--- a/vmkit/lib/J3/Classpath/ClasspathReflect.h
+++ b/vmkit/lib/J3/Classpath/ClasspathReflect.h
@@ -14,6 +14,7 @@
 
 #include <JavaClass.h>
 #include <JavaObject.h>
+#include <JavaThread.h>
 
 extern "C" j3::JavaObject* internalFillInStackTrace(j3::JavaObject*);
 
diff --git a/vmkit/lib/Mvm/CommonThread/ctthread.cpp b/vmkit/lib/Mvm/CommonThread/ctthread.cpp
index 1c76f2f..76f6375 100644
--- a/vmkit/lib/Mvm/CommonThread/ctthread.cpp
+++ b/vmkit/lib/Mvm/CommonThread/ctthread.cpp
@@ -417,7 +417,6 @@
   th->MyVM->rendezvous.addThread(th);
   th->routine(th);
   th->MyVM->removeThread(th);
-  delete th;
 }
 
 
@@ -456,12 +455,22 @@
       res = (void*)TheStackManager.allocate();
     }
   }
+  // Make sure the thread information is cleared.
+  memset(res, 0, sz);
   return res;
 }
 
 /// releaseThread - Remove the stack of the thread from the list of stacks
 /// in use.
-void Thread::releaseThread(void* th) {
+void Thread::releaseThread(mvm::Thread* th) {
+  // It seems like the pthread implementation in Linux is clearing with NULL
+  // the stack of the thread. So we have to get the thread id before
+  // calling pthread_join.
+  void* thread_id = th->internalThreadID;
+  if (thread_id != NULL) {
+    // Wait for the thread to die.
+    pthread_join((pthread_t)thread_id, NULL);
+  }
   uintptr_t index = ((uintptr_t)th & Thread::IDMask);
   index = (index & ~TheStackManager.baseAddr) >> 20;
   TheStackManager.used[index] = 0;