Stop daemon threads in runtime shutdown

Ensure that daemons are stopped and joins before bringing down the
runtime. This fixes bugs related to native code still running when
we shutdown the runtime.

Also changed the mutex destructor to allow contenders if we are
deleting a monitor lock level mutex.

Bug: 18577101
Change-Id: I6457b35fd69c6997b9003b5f15f39861749843a9
diff --git a/runtime/runtime.cc b/runtime/runtime.cc
index 078e7d2..32d787a 100644
--- a/runtime/runtime.cc
+++ b/runtime/runtime.cc
@@ -190,6 +190,13 @@
   }
 
   Thread* self = Thread::Current();
+  if (self == nullptr) {
+    CHECK(AttachCurrentThread("Shutdown thread", false, nullptr, false));
+    self = Thread::Current();
+  } else {
+    LOG(WARNING) << "Current thread not detached in Runtime shutdown";
+  }
+
   {
     MutexLock mu(self, *Locks::runtime_shutdown_lock_);
     shutting_down_started_ = true;
@@ -198,6 +205,16 @@
     }
     shutting_down_ = true;
   }
+  // Shutdown and wait for the daemons.
+  CHECK(self != nullptr);
+  if (IsFinishedStarting()) {
+    self->ClearException();
+    self->GetJniEnv()->CallStaticVoidMethod(WellKnownClasses::java_lang_Daemons,
+                                            WellKnownClasses::java_lang_Daemons_stop);
+  }
+  DetachCurrentThread();
+  self = nullptr;
+
   // Shut down background profiler before the runtime exits.
   if (profiler_started_) {
     BackgroundMethodSamplingProfiler::Shutdown();