Merge "Fix shutdown when the current thread has been manually detached." into ics-mr1-plus-art
diff --git a/src/oatexec.cc b/src/oatexec.cc
index 4f7228b..4f068db 100644
--- a/src/oatexec.cc
+++ b/src/oatexec.cc
@@ -172,10 +172,14 @@
 
   int rc = InvokeMain(env, &argv[arg_idx]);
 
+#if defined(NDEBUG)
+  // The DestroyJavaVM call will detach this thread for us. In debug builds, we don't want to
+  // detach because detaching disables the CheckSafeToLockOrUnlock checking.
   if (vm->DetachCurrentThread() != JNI_OK) {
     fprintf(stderr, "Warning: unable to detach main thread\n");
     rc = EXIT_FAILURE;
   }
+#endif
 
   if (vm->DestroyJavaVM() != 0) {
     fprintf(stderr, "Warning: runtime did not shut down cleanly\n");
diff --git a/src/thread.cc b/src/thread.cc
index 37d366d..10b099d 100644
--- a/src/thread.cc
+++ b/src/thread.cc
@@ -1753,6 +1753,10 @@
 }
 
 void Thread::CheckSafeToLockOrUnlock(MutexRank rank, bool is_locking) {
+  if (this == NULL) {
+    CHECK(Runtime::Current()->IsShuttingDown());
+    return;
+  }
   if (is_locking) {
     if (held_mutexes_[rank] == 0) {
       bool bad_mutexes_held = false;
@@ -1772,6 +1776,10 @@
 }
 
 void Thread::CheckSafeToWait(MutexRank rank) {
+  if (this == NULL) {
+    CHECK(Runtime::Current()->IsShuttingDown());
+    return;
+  }
   bool bad_mutexes_held = false;
   for (int i = kMaxMutexRank; i >= 0; --i) {
     if (i != rank && held_mutexes_[i] != 0) {