perfetto_hprof: do not wait for listener

waiting for the listener thread added significant time to app startup.

Test: flash flame-userdebug
      functional: take heap profile
      performance: trace chrome startup. perfetto_hprof init < 500us.
      art/tools/run-gtests.sh: https://gist.github.com/segfaulthunter/27f6c7d794b511b4a14bf14166a84b85
      art/test/testrunner/testrunner.py: PASS
      art/tools/run-libcore-tests.sh: PASS
      art/tools/run-libjdwp-tests.sh: PASS

Bug: 147667830
Change-Id: Ic5f74aba653aee2012b7335487774aafe00a655d
diff --git a/perfetto_hprof/perfetto_hprof.cc b/perfetto_hprof/perfetto_hprof.cc
index 33fc73e..6ba3bb4 100644
--- a/perfetto_hprof/perfetto_hprof.cc
+++ b/perfetto_hprof/perfetto_hprof.cc
@@ -699,6 +699,12 @@
     if (!runtime->AttachCurrentThread("perfetto_hprof_listener", /*as_daemon=*/ true,
                                       runtime->GetSystemThreadGroup(), /*create_peer=*/ false)) {
       LOG(ERROR) << "failed to attach thread.";
+      {
+        art::MutexLock lk(nullptr, GetStateMutex());
+        g_state = State::kUninitialized;
+        GetStateCV().Broadcast(nullptr);
+      }
+
       return;
     }
     art::Thread* self = art::Thread::Current();
@@ -733,10 +739,6 @@
   });
   th.detach();
 
-  art::MutexLock lk(art::Thread::Current(), GetStateMutex());
-  while (g_state == State::kWaitForListener) {
-    GetStateCV().Wait(art::Thread::Current());
-  }
   return true;
 }
 
@@ -751,10 +753,14 @@
 
   art::Thread* self = art::Thread::Current();
   art::MutexLock lk(self, GetStateMutex());
-  if (g_state != State::kWaitForListener) {
-    g_state = State::kUninitialized;
-    GetStateCV().Broadcast(self);
+  // Wait until after the thread was registered to the runtime. This is so
+  // we do not attempt to register it with the runtime after it had been torn
+  // down (ArtPlugin_Deinitialize gets called in the Runtime dtor).
+  while (g_state == State::kWaitForListener) {
+    GetStateCV().Wait(art::Thread::Current());
   }
+  g_state = State::kUninitialized;
+  GetStateCV().Broadcast(self);
   return true;
 }