Do not abort if we fail to allocate a thread-peer on shutdown

We were aborting if we failed to allocate the "Shutdown thread" a
java-peer. This can sometimes happen if there is very constrained
memory during shutdown for some reason. Since the thread-peer is only
observable in very rare situations (and the runtime is shutting down
anyway) we will instead simply continue without it.

We also change a test that was hitting this situation to handle not
having a thread peer.

Bug: 71623806

Test: while ./test/run-test --host \
                            --prebuild \
                            --compact-dex-level none \
                            --optimizing \
                            --no-relocate \
                            --runtime-option -Xcheck:jni \
                            --pic-test \
                            --64 \
                            --build-with-javac-dx \
                            004-ThreadStress;
      do; done
Test: ./test.py --host -j50
Change-Id: Ib159d03e9f4b0e4d5b1b071d4b85e94620679bb0
diff --git a/runtime/runtime.cc b/runtime/runtime.cc
index 2f45b10..38c2bfd 100644
--- a/runtime/runtime.cc
+++ b/runtime/runtime.cc
@@ -291,11 +291,21 @@
   const bool attach_shutdown_thread = self == nullptr;
   if (attach_shutdown_thread) {
     // We can only create a peer if the runtime is actually started. This is only not true during
-    // some tests.
-    CHECK(AttachCurrentThread("Shutdown thread",
-                              false,
-                              GetSystemThreadGroup(),
-                              /* Create peer */IsStarted()));
+    // some tests. If there is extreme memory pressure the allocation of the thread peer can fail.
+    // In this case we will just try again without allocating a peer so that shutdown can continue.
+    // Very few things are actually capable of distinguishing between the peer & peerless states so
+    // this should be fine.
+    bool thread_attached = AttachCurrentThread("Shutdown thread",
+                                               /* as_daemon */ false,
+                                               GetSystemThreadGroup(),
+                                               /* Create peer */ IsStarted());
+    if (UNLIKELY(!thread_attached)) {
+      LOG(WARNING) << "Failed to attach shutdown thread. Trying again without a peer.";
+      CHECK(AttachCurrentThread("Shutdown thread (no java peer)",
+                                /* as_daemon */   false,
+                                /* thread_group*/ nullptr,
+                                /* Create peer */ false));
+    }
     self = Thread::Current();
   } else {
     LOG(WARNING) << "Current thread not detached in Runtime shutdown";