Revert some flaky unloading

Revert "Revert "Revert "Remove double unloading hack"""

This reverts commit c0f2e678e45ff191f90651117f4e238caa521b80.

Revert "Revert "Revert "Revert "Revert "(dl)Close native libraries on unload"""""

This reverts commit 33bae7d52debe898879fc034a5524b1b165dbd88.

Still flaky.

Bug: 28406866

Change-Id: I31a9ace17c676ac615ed04a9f4ac51582fca55d9
diff --git a/runtime/common_runtime_test.cc b/runtime/common_runtime_test.cc
index 5bdb36c..f58af5a 100644
--- a/runtime/common_runtime_test.cc
+++ b/runtime/common_runtime_test.cc
@@ -418,6 +418,26 @@
   (*icu_cleanup_fn)();
 
   Runtime::Current()->GetHeap()->VerifyHeap();  // Check for heap corruption after the test
+
+  // Manually closing the JNI libraries.
+  // Runtime does not support repeatedly doing JNI->CreateVM, thus we need to manually clean up the
+  // dynamic linking loader so that gtests would not fail.
+  // Bug: 25785594
+  if (runtime_->IsStarted()) {
+    {
+      // We retrieve the handle by calling dlopen on the library. To close it, we need to call
+      // dlclose twice, the first time to undo our dlopen and the second time to actually unload it.
+      // See man dlopen.
+      void* handle = dlopen("libjavacore.so", RTLD_LAZY);
+      dlclose(handle);
+      CHECK_EQ(0, dlclose(handle));
+    }
+    {
+      void* handle = dlopen("libopenjdkd.so", RTLD_LAZY);
+      dlclose(handle);
+      CHECK_EQ(0, dlclose(handle));
+    }
+  }
 }
 
 static std::string GetDexFileName(const std::string& jar_prefix, bool host) {