Call ReferenceQueue add outside of active GC block

We were calling ReferenceQueue.add within the runtime GC active block.
This caused java code to be run and could (potentially) cause
deadlocks with JVMTI and debuggers.

To fix this we collect the cleared references during the GC and only
enqueue them after FinishGC.

Test: ./test.py --host
Test: atest CtsJdwpTunnelHostTestCases # with goldfish emulator
Test: ./art/tools/run-libjdwp-tests.sh --mode=host
Bug: 132460313

Change-Id: I276870096fb60a06afba7f850325d06709227b8e
diff --git a/runtime/gc/heap.cc b/runtime/gc/heap.cc
index 9755016..532b3ef 100644
--- a/runtime/gc/heap.cc
+++ b/runtime/gc/heap.cc
@@ -2014,10 +2014,14 @@
                static_cast<double>(space_size_before_compaction);
   }
   // Finish GC.
-  reference_processor_->EnqueueClearedReferences(self);
+  // Get the references we need to enqueue.
+  SelfDeletingTask* clear = reference_processor_->CollectClearedReferences(self);
   GrowForUtilization(semi_space_collector_);
   LogGC(kGcCauseHomogeneousSpaceCompact, collector);
   FinishGC(self, collector::kGcTypeFull);
+  // Enqueue any references after losing the GC locks.
+  clear->Run(self);
+  clear->Finalize();
   {
     ScopedObjectAccess soa(self);
     soa.Vm()->UnloadNativeLibraries();
@@ -2545,12 +2549,16 @@
   total_bytes_freed_ever_ += GetCurrentGcIteration()->GetFreedBytes() +
       GetCurrentGcIteration()->GetFreedLargeObjectBytes();
   RequestTrim(self);
-  // Enqueue cleared references.
-  reference_processor_->EnqueueClearedReferences(self);
+  // Collect cleared references.
+  SelfDeletingTask* clear = reference_processor_->CollectClearedReferences(self);
   // Grow the heap so that we know when to perform the next GC.
   GrowForUtilization(collector, bytes_allocated_before_gc);
   LogGC(gc_cause, collector);
   FinishGC(self, gc_type);
+  // Actually enqueue all cleared references. Do this after the GC has officially finished since
+  // otherwise we can deadlock.
+  clear->Run(self);
+  clear->Finalize();
   // Inform DDMS that a GC completed.
   Dbg::GcDidFinish();