From 0778f0119083ae33aea5ce9b5a1b44f565f45397 Mon Sep 17 00:00:00 2001
Date: Thu, 19 Oct 2023 15:25:43 +0800
Subject: [PATCH 4/5] Add metaspace memory allocation failure validation

---
 hotspot/src/share/vm/memory/metaspace.cpp | 10 +++++++++-
 1 file changed, 9 insertions(+), 1 deletion(-)

diff --git a/hotspot/src/share/vm/memory/metaspace.cpp b/hotspot/src/share/vm/memory/metaspace.cpp
index 0569500c1..f39ae41f3 100644
--- a/hotspot/src/share/vm/memory/metaspace.cpp
+++ b/hotspot/src/share/vm/memory/metaspace.cpp
@@ -571,7 +571,7 @@ class OccupancyMap : public CHeapObj<mtInternal> {
     assert(_map_size * 8 >= num_bits, "sanity");
     _map[0] = (uint8_t*) os::malloc(_map_size, mtInternal);
     _map[1] = (uint8_t*) os::malloc(_map_size, mtInternal);
-    assert(_map[0] != NULL && _map[1] != NULL, "Occupancy Map: allocation failed.");
+    guarantee(_map[0] != NULL && _map[1] != NULL, "Metaspace Occupancy Map: allocation failed.");
     memset(_map[1], 0, _map_size);
     memset(_map[0], 0, _map_size);
     // Sanity test: the first respectively last possible chunk start address in
@@ -918,6 +918,14 @@ void VirtualSpaceNode::print_map(outputStream* st, bool is_class) const {
   char* lines[NUM_LINES];
   for (int i = 0; i < NUM_LINES; i ++) {
     lines[i] = (char*)os::malloc(line_len, mtInternal);
+    // Only print the VirtualSpaceNode memory layout during metaspace OOM.
+    // If it fails,we should return instead of hanging the VM.
+    if (lines[i] == NULL) {
+      for (int j = 0; j < i; j ++) {
+        os::free(lines[j]);
+      }
+      return;
+    }
   }
   int pos = 0;
   const MetaWord* p = bottom();
-- 
2.19.1

