1 /*
   2  * Copyright (c) 2018, 2022, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "precompiled.hpp"
  26 #include "cds/archiveBuilder.hpp"
  27 #include "cds/archiveUtils.hpp"
  28 #include "cds/cdsHeapVerifier.hpp"
  29 #include "cds/filemap.hpp"
  30 #include "cds/heapShared.inline.hpp"
  31 #include "cds/metaspaceShared.hpp"
  32 #include "classfile/classLoaderData.hpp"
  33 #include "classfile/classLoaderDataShared.hpp"
  34 #include "classfile/javaClasses.inline.hpp"
  35 #include "classfile/moduleEntry.hpp"
  36 #include "classfile/stringTable.hpp"
  37 #include "classfile/symbolTable.hpp"
  38 #include "classfile/systemDictionary.hpp"
  39 #include "classfile/systemDictionaryShared.hpp"
  40 #include "classfile/vmClasses.hpp"
  41 #include "classfile/vmSymbols.hpp"
  42 #include "gc/shared/collectedHeap.hpp"
  43 #include "gc/shared/gcLocker.hpp"
  44 #include "gc/shared/gcVMOperations.hpp"
  45 #include "logging/log.hpp"
  46 #include "logging/logStream.hpp"
  47 #include "memory/iterator.inline.hpp"
  48 #include "memory/metadataFactory.hpp"
  49 #include "memory/metaspaceClosure.hpp"
  50 #include "memory/resourceArea.hpp"
  51 #include "memory/universe.hpp"
  52 #include "oops/compressedOops.inline.hpp"
  53 #include "oops/fieldStreams.inline.hpp"
  54 #include "oops/objArrayOop.inline.hpp"
  55 #include "oops/oop.inline.hpp"
  56 #include "oops/typeArrayOop.inline.hpp"
  57 #include "prims/jvmtiExport.hpp"
  58 #include "runtime/fieldDescriptor.inline.hpp"
  59 #include "runtime/globals_extension.hpp"
  60 #include "runtime/init.hpp"
  61 #include "runtime/java.hpp"
  62 #include "runtime/javaCalls.hpp"
  63 #include "runtime/safepoint.hpp"
  64 #include "runtime/safepointVerifiers.hpp"
  65 #include "utilities/bitMap.inline.hpp"
  66 #include "utilities/copy.hpp"
  67 #if INCLUDE_G1GC
  68 #include "gc/g1/g1CollectedHeap.hpp"
  69 #endif
  70 
  71 #if INCLUDE_CDS_JAVA_HEAP
  72 
  73 bool HeapShared::_closed_regions_mapped = false;
  74 bool HeapShared::_open_regions_mapped = false;
  75 bool HeapShared::_is_loaded = false;
  76 bool HeapShared::_disable_writing = false;
  77 address   HeapShared::_narrow_oop_base;
  78 int       HeapShared::_narrow_oop_shift;
  79 DumpedInternedStrings *HeapShared::_dumped_interned_strings = NULL;
  80 
  81 // Support for loaded heap.
  82 uintptr_t HeapShared::_loaded_heap_bottom = 0;
  83 uintptr_t HeapShared::_loaded_heap_top = 0;
  84 uintptr_t HeapShared::_dumptime_base_0 = UINTPTR_MAX;
  85 uintptr_t HeapShared::_dumptime_base_1 = UINTPTR_MAX;
  86 uintptr_t HeapShared::_dumptime_base_2 = UINTPTR_MAX;
  87 uintptr_t HeapShared::_dumptime_base_3 = UINTPTR_MAX;
  88 uintptr_t HeapShared::_dumptime_top    = 0;
  89 intx HeapShared::_runtime_offset_0 = 0;
  90 intx HeapShared::_runtime_offset_1 = 0;
  91 intx HeapShared::_runtime_offset_2 = 0;
  92 intx HeapShared::_runtime_offset_3 = 0;
  93 bool HeapShared::_loading_failed = false;
  94 
  95 // Support for mapped heap (!UseCompressedOops only)
  96 ptrdiff_t HeapShared::_runtime_delta = 0;
  97 
  98 //
  99 // If you add new entries to the following tables, you should know what you're doing!
 100 //
 101 
 102 // Entry fields for shareable subgraphs archived in the closed archive heap
 103 // region. Warning: Objects in the subgraphs should not have reference fields
 104 // assigned at runtime.
 105 static ArchivableStaticFieldInfo closed_archive_subgraph_entry_fields[] = {
 106   {"java/lang/Integer$IntegerCache",              "archivedCache"},
 107   {"java/lang/Long$LongCache",                    "archivedCache"},
 108   {"java/lang/Byte$ByteCache",                    "archivedCache"},
 109   {"java/lang/Short$ShortCache",                  "archivedCache"},
 110   {"java/lang/Character$CharacterCache",          "archivedCache"},
 111   {"java/util/jar/Attributes$Name",               "KNOWN_NAMES"},
 112   {"sun/util/locale/BaseLocale",                  "constantBaseLocales"},
 113 };
 114 // Entry fields for subgraphs archived in the open archive heap region.
 115 static ArchivableStaticFieldInfo open_archive_subgraph_entry_fields[] = {
 116   {"jdk/internal/module/ArchivedModuleGraph",     "archivedModuleGraph"},
 117   {"java/util/ImmutableCollections",              "archivedObjects"},
 118   {"java/lang/ModuleLayer",                       "EMPTY_LAYER"},
 119   {"java/lang/module/Configuration",              "EMPTY_CONFIGURATION"},
 120   {"jdk/internal/math/FDBigInteger",              "archivedCaches"},
 121 };
 122 
 123 // Entry fields for subgraphs archived in the open archive heap region (full module graph).
 124 static ArchivableStaticFieldInfo fmg_open_archive_subgraph_entry_fields[] = {
 125   {"jdk/internal/loader/ArchivedClassLoaders",    "archivedClassLoaders"},
 126   {"jdk/internal/module/ArchivedBootLayer",       "archivedBootLayer"},
 127   {"java/lang/Module$ArchivedData",               "archivedData"},
 128 };
 129 
 130 const static int num_closed_archive_subgraph_entry_fields =
 131   sizeof(closed_archive_subgraph_entry_fields) / sizeof(ArchivableStaticFieldInfo);
 132 const static int num_open_archive_subgraph_entry_fields =
 133   sizeof(open_archive_subgraph_entry_fields) / sizeof(ArchivableStaticFieldInfo);
 134 const static int num_fmg_open_archive_subgraph_entry_fields =
 135   sizeof(fmg_open_archive_subgraph_entry_fields) / sizeof(ArchivableStaticFieldInfo);
 136 
 137 GrowableArrayCHeap<oop, mtClassShared>* HeapShared::_pending_roots = NULL;
 138 OopHandle HeapShared::_roots;
 139 
 140 #ifdef ASSERT
 141 bool HeapShared::is_archived_object_during_dumptime(oop p) {
 142   assert(HeapShared::can_write(), "must be");
 143   assert(DumpSharedSpaces, "this function is only used with -Xshare:dump");
 144   return Universe::heap()->is_archived_object(p);
 145 }
 146 #endif
 147 
 148 static bool is_subgraph_root_class_of(ArchivableStaticFieldInfo fields[], int num, InstanceKlass* ik) {
 149   for (int i = 0; i < num; i++) {
 150     if (fields[i].klass == ik) {
 151       return true;
 152     }
 153   }
 154   return false;
 155 }
 156 
 157 bool HeapShared::is_subgraph_root_class(InstanceKlass* ik) {
 158   return is_subgraph_root_class_of(closed_archive_subgraph_entry_fields,
 159                                    num_closed_archive_subgraph_entry_fields, ik) ||
 160          is_subgraph_root_class_of(open_archive_subgraph_entry_fields,
 161                                    num_open_archive_subgraph_entry_fields, ik) ||
 162          is_subgraph_root_class_of(fmg_open_archive_subgraph_entry_fields,
 163                                    num_fmg_open_archive_subgraph_entry_fields, ik);
 164 }
 165 
 166 void HeapShared::fixup_regions() {
 167   FileMapInfo* mapinfo = FileMapInfo::current_info();
 168   if (is_mapped()) {
 169     mapinfo->fixup_mapped_heap_regions();
 170   } else if (_loading_failed) {
 171     fill_failed_loaded_region();
 172   }
 173   if (is_fully_available()) {
 174     if (!MetaspaceShared::use_full_module_graph()) {
 175       // Need to remove all the archived java.lang.Module objects from HeapShared::roots().
 176       ClassLoaderDataShared::clear_archived_oops();
 177     }
 178   }
 179   SystemDictionaryShared::update_archived_mirror_native_pointers();
 180 }
 181 
 182 unsigned HeapShared::oop_hash(oop const& p) {
 183   unsigned hash = (unsigned)p->identity_hash();
 184   return hash;
 185 }
 186 
 187 static void reset_states(oop obj, TRAPS) {
 188   Handle h_obj(THREAD, obj);
 189   InstanceKlass* klass = InstanceKlass::cast(obj->klass());
 190   TempNewSymbol method_name = SymbolTable::new_symbol("resetArchivedStates");
 191   Symbol* method_sig = vmSymbols::void_method_signature();
 192 
 193   while (klass != NULL) {
 194     Method* method = klass->find_method(method_name, method_sig);
 195     if (method != NULL) {
 196       assert(method->is_private(), "must be");
 197       if (log_is_enabled(Debug, cds)) {
 198         ResourceMark rm(THREAD);
 199         log_debug(cds)("  calling %s", method->name_and_sig_as_C_string());
 200       }
 201       JavaValue result(T_VOID);
 202       JavaCalls::call_special(&result, h_obj, klass,
 203                               method_name, method_sig, CHECK);
 204     }
 205     klass = klass->java_super();
 206   }
 207 }
 208 
 209 void HeapShared::reset_archived_object_states(TRAPS) {
 210   assert(DumpSharedSpaces, "dump-time only");
 211   log_debug(cds)("Resetting platform loader");
 212   reset_states(SystemDictionary::java_platform_loader(), CHECK);
 213   log_debug(cds)("Resetting system loader");
 214   reset_states(SystemDictionary::java_system_loader(), CHECK);
 215 
 216   // Clean up jdk.internal.loader.ClassLoaders::bootLoader(), which is not
 217   // directly used for class loading, but rather is used by the core library
 218   // to keep track of resources, etc, loaded by the null class loader.
 219   //
 220   // Note, this object is non-null, and is not the same as
 221   // ClassLoaderData::the_null_class_loader_data()->class_loader(),
 222   // which is null.
 223   log_debug(cds)("Resetting boot loader");
 224   JavaValue result(T_OBJECT);
 225   JavaCalls::call_static(&result,
 226                          vmClasses::jdk_internal_loader_ClassLoaders_klass(),
 227                          vmSymbols::bootLoader_name(),
 228                          vmSymbols::void_BuiltinClassLoader_signature(),
 229                          CHECK);
 230   Handle boot_loader(THREAD, result.get_oop());
 231   reset_states(boot_loader(), CHECK);
 232 }
 233 
 234 HeapShared::ArchivedObjectCache* HeapShared::_archived_object_cache = NULL;
 235 HeapShared::OriginalObjectTable* HeapShared::_original_object_table = NULL;
 236 oop HeapShared::find_archived_heap_object(oop obj) {
 237   assert(DumpSharedSpaces, "dump-time only");
 238   ArchivedObjectCache* cache = archived_object_cache();
 239   CachedOopInfo* p = cache->get(obj);
 240   if (p != NULL) {
 241     return p->_obj;
 242   } else {
 243     return NULL;
 244   }
 245 }
 246 
 247 int HeapShared::append_root(oop obj) {
 248   assert(DumpSharedSpaces, "dump-time only");
 249 
 250   // No GC should happen since we aren't scanning _pending_roots.
 251   assert(Thread::current() == (Thread*)VMThread::vm_thread(), "should be in vm thread");
 252 
 253   if (_pending_roots == NULL) {
 254     _pending_roots = new GrowableArrayCHeap<oop, mtClassShared>(500);
 255   }
 256 
 257   return _pending_roots->append(obj);
 258 }
 259 
 260 objArrayOop HeapShared::roots() {
 261   if (DumpSharedSpaces) {
 262     assert(Thread::current() == (Thread*)VMThread::vm_thread(), "should be in vm thread");
 263     if (!HeapShared::can_write()) {
 264       return NULL;
 265     }
 266   } else {
 267     assert(UseSharedSpaces, "must be");
 268   }
 269 
 270   objArrayOop roots = (objArrayOop)_roots.resolve();
 271   assert(roots != NULL, "should have been initialized");
 272   return roots;
 273 }
 274 
 275 // Returns an objArray that contains all the roots of the archived objects
 276 oop HeapShared::get_root(int index, bool clear) {
 277   assert(index >= 0, "sanity");
 278   if (DumpSharedSpaces) {
 279     assert(Thread::current() == (Thread*)VMThread::vm_thread(), "should be in vm thread");
 280     assert(_pending_roots != NULL, "sanity");
 281     return _pending_roots->at(index);
 282   } else {
 283     assert(UseSharedSpaces, "must be");
 284     assert(!_roots.is_empty(), "must have loaded shared heap");
 285     oop result = roots()->obj_at(index);
 286     if (clear) {
 287       clear_root(index);
 288     }
 289     return result;
 290   }
 291 }
 292 
 293 void HeapShared::clear_root(int index) {
 294   assert(index >= 0, "sanity");
 295   assert(UseSharedSpaces, "must be");
 296   if (is_fully_available()) {
 297     if (log_is_enabled(Debug, cds, heap)) {
 298       oop old = roots()->obj_at(index);
 299       log_debug(cds, heap)("Clearing root %d: was " PTR_FORMAT, index, p2i(old));
 300     }
 301     roots()->obj_at_put(index, NULL);
 302   }
 303 }
 304 
 305 oop HeapShared::archive_object(oop obj) {
 306   assert(DumpSharedSpaces, "dump-time only");
 307 
 308   oop ao = find_archived_heap_object(obj);
 309   if (ao != NULL) {
 310     // already archived
 311     return ao;
 312   }
 313 
 314   int len = obj->size();
 315   if (G1CollectedHeap::heap()->is_archive_alloc_too_large(len)) {
 316     log_debug(cds, heap)("Cannot archive, object (" PTR_FORMAT ") is too large: " SIZE_FORMAT,
 317                          p2i(obj), (size_t)obj->size());
 318     return NULL;
 319   }
 320 
 321   oop archived_oop = cast_to_oop(G1CollectedHeap::heap()->archive_mem_allocate(len));
 322   if (archived_oop != NULL) {
 323     Copy::aligned_disjoint_words(cast_from_oop<HeapWord*>(obj), cast_from_oop<HeapWord*>(archived_oop), len);
 324     // Reinitialize markword to remove age/marking/locking/etc.
 325     //
 326     // We need to retain the identity_hash, because it may have been used by some hashtables
 327     // in the shared heap. This also has the side effect of pre-initializing the
 328     // identity_hash for all shared objects, so they are less likely to be written
 329     // into during run time, increasing the potential of memory sharing.
 330     int hash_original = obj->identity_hash();
 331 
 332     assert(SafepointSynchronize::is_at_safepoint(), "resolving displaced headers only at safepoint");
 333     markWord mark = obj->mark();
 334     if (mark.has_displaced_mark_helper()) {
 335       mark = mark.displaced_mark_helper();
 336     }
 337     narrowKlass nklass = mark.narrow_klass();
 338     archived_oop->set_mark(markWord::prototype().copy_set_hash(hash_original) LP64_ONLY(.set_narrow_klass(nklass)));
 339     assert(archived_oop->mark().is_unlocked(), "sanity");
 340 
 341     DEBUG_ONLY(int hash_archived = archived_oop->identity_hash());
 342     assert(hash_original == hash_archived, "Different hash codes: original %x, archived %x", hash_original, hash_archived);
 343 
 344     ArchivedObjectCache* cache = archived_object_cache();
 345     CachedOopInfo info = make_cached_oop_info(archived_oop);
 346     cache->put(obj, info);
 347     if (_original_object_table != NULL) {
 348       _original_object_table->put(archived_oop, obj);
 349     }
 350     if (log_is_enabled(Debug, cds, heap)) {
 351       ResourceMark rm;
 352       log_debug(cds, heap)("Archived heap object " PTR_FORMAT " ==> " PTR_FORMAT " : %s",
 353                            p2i(obj), p2i(archived_oop), obj->klass()->external_name());
 354     }
 355   } else {
 356     log_error(cds, heap)(
 357       "Cannot allocate space for object " PTR_FORMAT " in archived heap region",
 358       p2i(obj));
 359     vm_direct_exit(-1,
 360       err_msg("Out of memory. Please run with a larger Java heap, current MaxHeapSize = "
 361               SIZE_FORMAT "M", MaxHeapSize/M));
 362   }
 363   return archived_oop;
 364 }
 365 
 366 void HeapShared::archive_klass_objects() {
 367   GrowableArray<Klass*>* klasses = ArchiveBuilder::current()->klasses();
 368   assert(klasses != NULL, "sanity");
 369   for (int i = 0; i < klasses->length(); i++) {
 370     Klass* k = ArchiveBuilder::get_relocated_klass(klasses->at(i));
 371 
 372     // archive mirror object
 373     java_lang_Class::archive_mirror(k);
 374 
 375     // archive the resolved_referenes array
 376     if (k->is_instance_klass()) {
 377       InstanceKlass* ik = InstanceKlass::cast(k);
 378       ik->constants()->archive_resolved_references();
 379     }
 380   }
 381 }
 382 
 383 // -- Handling of Enum objects
 384 // Java Enum classes have synthetic <clinit> methods that look like this
 385 //     enum MyEnum {FOO, BAR}
 386 //     MyEnum::<clinint> {
 387 //        /*static final MyEnum*/ MyEnum::FOO = new MyEnum("FOO");
 388 //        /*static final MyEnum*/ MyEnum::BAR = new MyEnum("BAR");
 389 //     }
 390 //
 391 // If MyEnum::FOO object is referenced by any of the archived subgraphs, we must
 392 // ensure the archived value equals (in object address) to the runtime value of
 393 // MyEnum::FOO.
 394 //
 395 // However, since MyEnum::<clinint> is synthetically generated by javac, there's
 396 // no way of programmatically handling this inside the Java code (as you would handle
 397 // ModuleLayer::EMPTY_LAYER, for example).
 398 //
 399 // Instead, we archive all static field of such Enum classes. At runtime,
 400 // HeapShared::initialize_enum_klass() will skip the <clinit> method and pull
 401 // the static fields out of the archived heap.
 402 void HeapShared::check_enum_obj(int level,
 403                                 KlassSubGraphInfo* subgraph_info,
 404                                 oop orig_obj,
 405                                 bool is_closed_archive) {
 406   Klass* k = orig_obj->klass();
 407   Klass* relocated_k = ArchiveBuilder::get_relocated_klass(k);
 408   if (!k->is_instance_klass()) {
 409     return;
 410   }
 411   InstanceKlass* ik = InstanceKlass::cast(k);
 412   if (ik->java_super() == vmClasses::Enum_klass() && !ik->has_archived_enum_objs()) {
 413     ResourceMark rm;
 414     ik->set_has_archived_enum_objs();
 415     relocated_k->set_has_archived_enum_objs();
 416     oop mirror = ik->java_mirror();
 417 
 418     for (JavaFieldStream fs(ik); !fs.done(); fs.next()) {
 419       if (fs.access_flags().is_static()) {
 420         fieldDescriptor& fd = fs.field_descriptor();
 421         if (fd.field_type() != T_OBJECT && fd.field_type() != T_ARRAY) {
 422           guarantee(false, "static field %s::%s must be T_OBJECT or T_ARRAY",
 423                     ik->external_name(), fd.name()->as_C_string());
 424         }
 425         oop oop_field = mirror->obj_field(fd.offset());
 426         if (oop_field == NULL) {
 427           guarantee(false, "static field %s::%s must not be null",
 428                     ik->external_name(), fd.name()->as_C_string());
 429         } else if (oop_field->klass() != ik && oop_field->klass() != ik->array_klass_or_null()) {
 430           guarantee(false, "static field %s::%s is of the wrong type",
 431                     ik->external_name(), fd.name()->as_C_string());
 432         }
 433         oop archived_oop_field = archive_reachable_objects_from(level, subgraph_info, oop_field, is_closed_archive);
 434         int root_index = append_root(archived_oop_field);
 435         log_info(cds, heap)("Archived enum obj @%d %s::%s (" INTPTR_FORMAT " -> " INTPTR_FORMAT ")",
 436                             root_index, ik->external_name(), fd.name()->as_C_string(),
 437                             p2i((oopDesc*)oop_field), p2i((oopDesc*)archived_oop_field));
 438         SystemDictionaryShared::add_enum_klass_static_field(ik, root_index);
 439       }
 440     }
 441   }
 442 }
 443 
 444 // See comments in HeapShared::check_enum_obj()
 445 bool HeapShared::initialize_enum_klass(InstanceKlass* k, TRAPS) {
 446   if (!is_fully_available()) {
 447     return false;
 448   }
 449 
 450   RunTimeClassInfo* info = RunTimeClassInfo::get_for(k);
 451   assert(info != NULL, "sanity");
 452 
 453   if (log_is_enabled(Info, cds, heap)) {
 454     ResourceMark rm;
 455     log_info(cds, heap)("Initializing Enum class: %s", k->external_name());
 456   }
 457 
 458   oop mirror = k->java_mirror();
 459   int i = 0;
 460   for (JavaFieldStream fs(k); !fs.done(); fs.next()) {
 461     if (fs.access_flags().is_static()) {
 462       int root_index = info->enum_klass_static_field_root_index_at(i++);
 463       fieldDescriptor& fd = fs.field_descriptor();
 464       assert(fd.field_type() == T_OBJECT || fd.field_type() == T_ARRAY, "must be");
 465       mirror->obj_field_put(fd.offset(), get_root(root_index, /*clear=*/true));
 466     }
 467   }
 468   return true;
 469 }
 470 
 471 void HeapShared::run_full_gc_in_vm_thread() {
 472   if (HeapShared::can_write()) {
 473     // Avoid fragmentation while archiving heap objects.
 474     // We do this inside a safepoint, so that no further allocation can happen after GC
 475     // has finished.
 476     if (GCLocker::is_active()) {
 477       // Just checking for safety ...
 478       // This should not happen during -Xshare:dump. If you see this, probably the Java core lib
 479       // has been modified such that JNI code is executed in some clean up threads after
 480       // we have finished class loading.
 481       log_warning(cds)("GC locker is held, unable to start extra compacting GC. This may produce suboptimal results.");
 482     } else {
 483       log_info(cds)("Run GC ...");
 484       Universe::heap()->collect_as_vm_thread(GCCause::_archive_time_gc);
 485       log_info(cds)("Run GC done");
 486     }
 487   }
 488 }
 489 
 490 void HeapShared::archive_objects(GrowableArray<MemRegion>* closed_regions,
 491                                  GrowableArray<MemRegion>* open_regions) {
 492 
 493   G1HeapVerifier::verify_ready_for_archiving();
 494 
 495   {
 496     NoSafepointVerifier nsv;
 497 
 498     // Cache for recording where the archived objects are copied to
 499     create_archived_object_cache(log_is_enabled(Info, cds, map));
 500 
 501     log_info(cds)("Heap range = [" PTR_FORMAT " - "  PTR_FORMAT "]",
 502                    UseCompressedOops ? p2i(CompressedOops::begin()) :
 503                                        p2i((address)G1CollectedHeap::heap()->reserved().start()),
 504                    UseCompressedOops ? p2i(CompressedOops::end()) :
 505                                        p2i((address)G1CollectedHeap::heap()->reserved().end()));
 506     log_info(cds)("Dumping objects to closed archive heap region ...");
 507     copy_closed_objects(closed_regions);
 508 
 509     log_info(cds)("Dumping objects to open archive heap region ...");
 510     copy_open_objects(open_regions);
 511 
 512     CDSHeapVerifier::verify();
 513   }
 514 
 515   G1HeapVerifier::verify_archive_regions();
 516 }
 517 
 518 void HeapShared::copy_closed_objects(GrowableArray<MemRegion>* closed_regions) {
 519   assert(HeapShared::can_write(), "must be");
 520 
 521   G1CollectedHeap::heap()->begin_archive_alloc_range();
 522 
 523   // Archive interned string objects
 524   StringTable::write_to_archive(_dumped_interned_strings);
 525 
 526   archive_object_subgraphs(closed_archive_subgraph_entry_fields,
 527                            num_closed_archive_subgraph_entry_fields,
 528                            true /* is_closed_archive */,
 529                            false /* is_full_module_graph */);
 530 
 531   G1CollectedHeap::heap()->end_archive_alloc_range(closed_regions,
 532                                                    os::vm_allocation_granularity());
 533 }
 534 
 535 void HeapShared::copy_open_objects(GrowableArray<MemRegion>* open_regions) {
 536   assert(HeapShared::can_write(), "must be");
 537 
 538   G1CollectedHeap::heap()->begin_archive_alloc_range(true /* open */);
 539 
 540   java_lang_Class::archive_basic_type_mirrors();
 541 
 542   archive_klass_objects();
 543 
 544   archive_object_subgraphs(open_archive_subgraph_entry_fields,
 545                            num_open_archive_subgraph_entry_fields,
 546                            false /* is_closed_archive */,
 547                            false /* is_full_module_graph */);
 548   if (MetaspaceShared::use_full_module_graph()) {
 549     archive_object_subgraphs(fmg_open_archive_subgraph_entry_fields,
 550                              num_fmg_open_archive_subgraph_entry_fields,
 551                              false /* is_closed_archive */,
 552                              true /* is_full_module_graph */);
 553     ClassLoaderDataShared::init_archived_oops();
 554   }
 555 
 556   copy_roots();
 557 
 558   G1CollectedHeap::heap()->end_archive_alloc_range(open_regions,
 559                                                    os::vm_allocation_granularity());
 560 }
 561 
 562 // Copy _pending_archive_roots into an objArray
 563 void HeapShared::copy_roots() {
 564   // HeapShared::roots() points into an ObjArray in the open archive region. A portion of the
 565   // objects in this array are discovered during HeapShared::archive_objects(). For example,
 566   // in HeapShared::archive_reachable_objects_from() ->  HeapShared::check_enum_obj().
 567   // However, HeapShared::archive_objects() happens inside a safepoint, so we can't
 568   // allocate a "regular" ObjArray and pass the result to HeapShared::archive_object().
 569   // Instead, we have to roll our own alloc/copy routine here.
 570   int length = _pending_roots != NULL ? _pending_roots->length() : 0;
 571   size_t size = objArrayOopDesc::object_size(length);
 572   Klass* k = Universe::objectArrayKlassObj(); // already relocated to point to archived klass
 573   HeapWord* mem = G1CollectedHeap::heap()->archive_mem_allocate(size);
 574 
 575   memset(mem, 0, size * BytesPerWord);
 576   {
 577     // This is copied from MemAllocator::finish
 578     oopDesc::set_mark(mem, k->prototype_header());
 579 #ifndef _LP64
 580     oopDesc::release_set_klass(mem, k);
 581 #endif
 582   }
 583   {
 584     // This is copied from ObjArrayAllocator::initialize
 585     arrayOopDesc::set_length(mem, length);
 586   }
 587 
 588   _roots = OopHandle(Universe::vm_global(), cast_to_oop(mem));
 589   for (int i = 0; i < length; i++) {
 590     roots()->obj_at_put(i, _pending_roots->at(i));
 591   }
 592   log_info(cds)("archived obj roots[%d] = " SIZE_FORMAT " words, klass = %p, obj = %p", length, size, k, mem);
 593 }
 594 
 595 void HeapShared::init_narrow_oop_decoding(address base, int shift) {
 596   _narrow_oop_base = base;
 597   _narrow_oop_shift = shift;
 598 }
 599 
 600 //
 601 // Subgraph archiving support
 602 //
 603 HeapShared::DumpTimeKlassSubGraphInfoTable* HeapShared::_dump_time_subgraph_info_table = NULL;
 604 HeapShared::RunTimeKlassSubGraphInfoTable   HeapShared::_run_time_subgraph_info_table;
 605 
 606 // Get the subgraph_info for Klass k. A new subgraph_info is created if
 607 // there is no existing one for k. The subgraph_info records the relocated
 608 // Klass* of the original k.
 609 KlassSubGraphInfo* HeapShared::init_subgraph_info(Klass* k, bool is_full_module_graph) {
 610   assert(DumpSharedSpaces, "dump time only");
 611   bool created;
 612   Klass* relocated_k = ArchiveBuilder::get_relocated_klass(k);
 613   KlassSubGraphInfo* info =
 614     _dump_time_subgraph_info_table->put_if_absent(k, KlassSubGraphInfo(relocated_k, is_full_module_graph),
 615                                                   &created);
 616   assert(created, "must not initialize twice");
 617   return info;
 618 }
 619 
 620 KlassSubGraphInfo* HeapShared::get_subgraph_info(Klass* k) {
 621   assert(DumpSharedSpaces, "dump time only");
 622   KlassSubGraphInfo* info = _dump_time_subgraph_info_table->get(k);
 623   assert(info != NULL, "must have been initialized");
 624   return info;
 625 }
 626 
 627 // Add an entry field to the current KlassSubGraphInfo.
 628 void KlassSubGraphInfo::add_subgraph_entry_field(
 629       int static_field_offset, oop v, bool is_closed_archive) {
 630   assert(DumpSharedSpaces, "dump time only");
 631   if (_subgraph_entry_fields == NULL) {
 632     _subgraph_entry_fields =
 633       new(ResourceObj::C_HEAP, mtClass) GrowableArray<int>(10, mtClass);
 634   }
 635   _subgraph_entry_fields->append(static_field_offset);
 636   _subgraph_entry_fields->append(HeapShared::append_root(v));
 637 }
 638 
 639 // Add the Klass* for an object in the current KlassSubGraphInfo's subgraphs.
 640 // Only objects of boot classes can be included in sub-graph.
 641 void KlassSubGraphInfo::add_subgraph_object_klass(Klass* orig_k) {
 642   assert(DumpSharedSpaces, "dump time only");
 643   Klass* relocated_k = ArchiveBuilder::get_relocated_klass(orig_k);
 644 
 645   if (_subgraph_object_klasses == NULL) {
 646     _subgraph_object_klasses =
 647       new(ResourceObj::C_HEAP, mtClass) GrowableArray<Klass*>(50, mtClass);
 648   }
 649 
 650   assert(ArchiveBuilder::current()->is_in_buffer_space(relocated_k), "must be a shared class");
 651 
 652   if (_k == relocated_k) {
 653     // Don't add the Klass containing the sub-graph to it's own klass
 654     // initialization list.
 655     return;
 656   }
 657 
 658   if (relocated_k->is_instance_klass()) {
 659     assert(InstanceKlass::cast(relocated_k)->is_shared_boot_class(),
 660           "must be boot class");
 661     // vmClasses::xxx_klass() are not updated, need to check
 662     // the original Klass*
 663     if (orig_k == vmClasses::String_klass() ||
 664         orig_k == vmClasses::Object_klass()) {
 665       // Initialized early during VM initialization. No need to be added
 666       // to the sub-graph object class list.
 667       return;
 668     }
 669   } else if (relocated_k->is_objArray_klass()) {
 670     Klass* abk = ObjArrayKlass::cast(relocated_k)->bottom_klass();
 671     if (abk->is_instance_klass()) {
 672       assert(InstanceKlass::cast(abk)->is_shared_boot_class(),
 673             "must be boot class");
 674     }
 675     if (relocated_k == Universe::objectArrayKlassObj()) {
 676       // Initialized early during Universe::genesis. No need to be added
 677       // to the list.
 678       return;
 679     }
 680   } else {
 681     assert(relocated_k->is_typeArray_klass(), "must be");
 682     // Primitive type arrays are created early during Universe::genesis.
 683     return;
 684   }
 685 
 686   if (log_is_enabled(Debug, cds, heap)) {
 687     if (!_subgraph_object_klasses->contains(relocated_k)) {
 688       ResourceMark rm;
 689       log_debug(cds, heap)("Adding klass %s", orig_k->external_name());
 690     }
 691   }
 692 
 693   _subgraph_object_klasses->append_if_missing(relocated_k);
 694   _has_non_early_klasses |= is_non_early_klass(orig_k);
 695 }
 696 
 697 bool KlassSubGraphInfo::is_non_early_klass(Klass* k) {
 698   if (k->is_objArray_klass()) {
 699     k = ObjArrayKlass::cast(k)->bottom_klass();
 700   }
 701   if (k->is_instance_klass()) {
 702     if (!SystemDictionaryShared::is_early_klass(InstanceKlass::cast(k))) {
 703       ResourceMark rm;
 704       log_info(cds, heap)("non-early: %s", k->external_name());
 705       return true;
 706     } else {
 707       return false;
 708     }
 709   } else {
 710     return false;
 711   }
 712 }
 713 
 714 // Initialize an archived subgraph_info_record from the given KlassSubGraphInfo.
 715 void ArchivedKlassSubGraphInfoRecord::init(KlassSubGraphInfo* info) {
 716   _k = info->klass();
 717   _entry_field_records = NULL;
 718   _subgraph_object_klasses = NULL;
 719   _is_full_module_graph = info->is_full_module_graph();
 720 
 721   if (_is_full_module_graph) {
 722     // Consider all classes referenced by the full module graph as early -- we will be
 723     // allocating objects of these classes during JVMTI early phase, so they cannot
 724     // be processed by (non-early) JVMTI ClassFileLoadHook
 725     _has_non_early_klasses = false;
 726   } else {
 727     _has_non_early_klasses = info->has_non_early_klasses();
 728   }
 729 
 730   if (_has_non_early_klasses) {
 731     ResourceMark rm;
 732     log_info(cds, heap)(
 733           "Subgraph of klass %s has non-early klasses and cannot be used when JVMTI ClassFileLoadHook is enabled",
 734           _k->external_name());
 735   }
 736 
 737   // populate the entry fields
 738   GrowableArray<int>* entry_fields = info->subgraph_entry_fields();
 739   if (entry_fields != NULL) {
 740     int num_entry_fields = entry_fields->length();
 741     assert(num_entry_fields % 2 == 0, "sanity");
 742     _entry_field_records =
 743       ArchiveBuilder::new_ro_array<int>(num_entry_fields);
 744     for (int i = 0 ; i < num_entry_fields; i++) {
 745       _entry_field_records->at_put(i, entry_fields->at(i));
 746     }
 747   }
 748 
 749   // the Klasses of the objects in the sub-graphs
 750   GrowableArray<Klass*>* subgraph_object_klasses = info->subgraph_object_klasses();
 751   if (subgraph_object_klasses != NULL) {
 752     int num_subgraphs_klasses = subgraph_object_klasses->length();
 753     _subgraph_object_klasses =
 754       ArchiveBuilder::new_ro_array<Klass*>(num_subgraphs_klasses);
 755     for (int i = 0; i < num_subgraphs_klasses; i++) {
 756       Klass* subgraph_k = subgraph_object_klasses->at(i);
 757       if (log_is_enabled(Info, cds, heap)) {
 758         ResourceMark rm;
 759         log_info(cds, heap)(
 760           "Archived object klass %s (%2d) => %s",
 761           _k->external_name(), i, subgraph_k->external_name());
 762       }
 763       _subgraph_object_klasses->at_put(i, subgraph_k);
 764       ArchivePtrMarker::mark_pointer(_subgraph_object_klasses->adr_at(i));
 765     }
 766   }
 767 
 768   ArchivePtrMarker::mark_pointer(&_k);
 769   ArchivePtrMarker::mark_pointer(&_entry_field_records);
 770   ArchivePtrMarker::mark_pointer(&_subgraph_object_klasses);
 771 }
 772 
 773 struct CopyKlassSubGraphInfoToArchive : StackObj {
 774   CompactHashtableWriter* _writer;
 775   CopyKlassSubGraphInfoToArchive(CompactHashtableWriter* writer) : _writer(writer) {}
 776 
 777   bool do_entry(Klass* klass, KlassSubGraphInfo& info) {
 778     if (info.subgraph_object_klasses() != NULL || info.subgraph_entry_fields() != NULL) {
 779       ArchivedKlassSubGraphInfoRecord* record =
 780         (ArchivedKlassSubGraphInfoRecord*)ArchiveBuilder::ro_region_alloc(sizeof(ArchivedKlassSubGraphInfoRecord));
 781       record->init(&info);
 782 
 783       Klass* relocated_k = ArchiveBuilder::get_relocated_klass(klass);
 784       unsigned int hash = SystemDictionaryShared::hash_for_shared_dictionary((address)relocated_k);
 785       u4 delta = ArchiveBuilder::current()->any_to_offset_u4(record);
 786       _writer->add(hash, delta);
 787     }
 788     return true; // keep on iterating
 789   }
 790 };
 791 
 792 // Build the records of archived subgraph infos, which include:
 793 // - Entry points to all subgraphs from the containing class mirror. The entry
 794 //   points are static fields in the mirror. For each entry point, the field
 795 //   offset, value and is_closed_archive flag are recorded in the sub-graph
 796 //   info. The value is stored back to the corresponding field at runtime.
 797 // - A list of klasses that need to be loaded/initialized before archived
 798 //   java object sub-graph can be accessed at runtime.
 799 void HeapShared::write_subgraph_info_table() {
 800   // Allocate the contents of the hashtable(s) inside the RO region of the CDS archive.
 801   DumpTimeKlassSubGraphInfoTable* d_table = _dump_time_subgraph_info_table;
 802   CompactHashtableStats stats;
 803 
 804   _run_time_subgraph_info_table.reset();
 805 
 806   CompactHashtableWriter writer(d_table->_count, &stats);
 807   CopyKlassSubGraphInfoToArchive copy(&writer);
 808   d_table->iterate(&copy);
 809   writer.dump(&_run_time_subgraph_info_table, "subgraphs");
 810 }
 811 
 812 void HeapShared::serialize(SerializeClosure* soc) {
 813   oop roots_oop = NULL;
 814 
 815   if (soc->reading()) {
 816     soc->do_oop(&roots_oop); // read from archive
 817     assert(oopDesc::is_oop_or_null(roots_oop), "is oop");
 818     // Create an OopHandle only if we have actually mapped or loaded the roots
 819     if (roots_oop != NULL) {
 820       assert(HeapShared::is_fully_available(), "must be");
 821       _roots = OopHandle(Universe::vm_global(), roots_oop);
 822     }
 823   } else {
 824     // writing
 825     roots_oop = roots();
 826     soc->do_oop(&roots_oop); // write to archive
 827   }
 828 
 829   _run_time_subgraph_info_table.serialize_header(soc);
 830 }
 831 
 832 static void verify_the_heap(Klass* k, const char* which) {
 833   if (VerifyArchivedFields > 0) {
 834     ResourceMark rm;
 835     log_info(cds, heap)("Verify heap %s initializing static field(s) in %s",
 836                         which, k->external_name());
 837 
 838     VM_Verify verify_op;
 839     VMThread::execute(&verify_op);
 840 
 841     if (VerifyArchivedFields > 1 && is_init_completed()) {
 842       // At this time, the oop->klass() of some archived objects in the heap may not
 843       // have been loaded into the system dictionary yet. Nevertheless, oop->klass() should
 844       // have enough information (object size, oop maps, etc) so that a GC can be safely
 845       // performed.
 846       //
 847       // -XX:VerifyArchivedFields=2 force a GC to happen in such an early stage
 848       // to check for GC safety.
 849       log_info(cds, heap)("Trigger GC %s initializing static field(s) in %s",
 850                           which, k->external_name());
 851       FlagSetting fs1(VerifyBeforeGC, true);
 852       FlagSetting fs2(VerifyDuringGC, true);
 853       FlagSetting fs3(VerifyAfterGC,  true);
 854       Universe::heap()->collect(GCCause::_java_lang_system_gc);
 855     }
 856   }
 857 }
 858 
 859 // Before GC can execute, we must ensure that all oops reachable from HeapShared::roots()
 860 // have a valid klass. I.e., oopDesc::klass() must have already been resolved.
 861 //
 862 // Note: if a ArchivedKlassSubGraphInfoRecord contains non-early classes, and JVMTI
 863 // ClassFileLoadHook is enabled, it's possible for this class to be dynamically replaced. In
 864 // this case, we will not load the ArchivedKlassSubGraphInfoRecord and will clear its roots.
 865 void HeapShared::resolve_classes(JavaThread* THREAD) {
 866   if (!is_fully_available()) {
 867     return; // nothing to do
 868   }
 869   resolve_classes_for_subgraphs(closed_archive_subgraph_entry_fields,
 870                                 num_closed_archive_subgraph_entry_fields,
 871                                 THREAD);
 872   resolve_classes_for_subgraphs(open_archive_subgraph_entry_fields,
 873                                 num_open_archive_subgraph_entry_fields,
 874                                 THREAD);
 875   resolve_classes_for_subgraphs(fmg_open_archive_subgraph_entry_fields,
 876                                 num_fmg_open_archive_subgraph_entry_fields,
 877                                 THREAD);
 878 }
 879 
 880 void HeapShared::resolve_classes_for_subgraphs(ArchivableStaticFieldInfo fields[],
 881                                                int num, JavaThread* THREAD) {
 882   for (int i = 0; i < num; i++) {
 883     ArchivableStaticFieldInfo* info = &fields[i];
 884     TempNewSymbol klass_name = SymbolTable::new_symbol(info->klass_name);
 885     InstanceKlass* k = SystemDictionaryShared::find_builtin_class(klass_name);
 886     assert(k != NULL && k->is_shared_boot_class(), "sanity");
 887     resolve_classes_for_subgraph_of(k, THREAD);
 888   }
 889 }
 890 
 891 void HeapShared::resolve_classes_for_subgraph_of(Klass* k, JavaThread* THREAD) {
 892   ExceptionMark em(THREAD);
 893   const ArchivedKlassSubGraphInfoRecord* record =
 894    resolve_or_init_classes_for_subgraph_of(k, /*do_init=*/false, THREAD);
 895   if (HAS_PENDING_EXCEPTION) {
 896    CLEAR_PENDING_EXCEPTION;
 897   }
 898   if (record == NULL) {
 899    clear_archived_roots_of(k);
 900   }
 901 }
 902 
 903 void HeapShared::initialize_from_archived_subgraph(Klass* k, JavaThread* THREAD) {
 904   if (!is_fully_available()) {
 905     return; // nothing to do
 906   }
 907 
 908   ExceptionMark em(THREAD);
 909   const ArchivedKlassSubGraphInfoRecord* record =
 910     resolve_or_init_classes_for_subgraph_of(k, /*do_init=*/true, THREAD);
 911 
 912   if (HAS_PENDING_EXCEPTION) {
 913     CLEAR_PENDING_EXCEPTION;
 914     // None of the field value will be set if there was an exception when initializing the classes.
 915     // The java code will not see any of the archived objects in the
 916     // subgraphs referenced from k in this case.
 917     return;
 918   }
 919 
 920   if (record != NULL) {
 921     init_archived_fields_for(k, record);
 922   }
 923 }
 924 
 925 const ArchivedKlassSubGraphInfoRecord*
 926 HeapShared::resolve_or_init_classes_for_subgraph_of(Klass* k, bool do_init, TRAPS) {
 927   assert(!DumpSharedSpaces, "Should not be called with DumpSharedSpaces");
 928 
 929   if (!k->is_shared()) {
 930     return NULL;
 931   }
 932   unsigned int hash = SystemDictionaryShared::hash_for_shared_dictionary_quick(k);
 933   const ArchivedKlassSubGraphInfoRecord* record = _run_time_subgraph_info_table.lookup(k, hash, 0);
 934 
 935   // Initialize from archived data. Currently this is done only
 936   // during VM initialization time. No lock is needed.
 937   if (record != NULL) {
 938     if (record->is_full_module_graph() && !MetaspaceShared::use_full_module_graph()) {
 939       if (log_is_enabled(Info, cds, heap)) {
 940         ResourceMark rm(THREAD);
 941         log_info(cds, heap)("subgraph %s cannot be used because full module graph is disabled",
 942                             k->external_name());
 943       }
 944       return NULL;
 945     }
 946 
 947     if (record->has_non_early_klasses() && JvmtiExport::should_post_class_file_load_hook()) {
 948       if (log_is_enabled(Info, cds, heap)) {
 949         ResourceMark rm(THREAD);
 950         log_info(cds, heap)("subgraph %s cannot be used because JVMTI ClassFileLoadHook is enabled",
 951                             k->external_name());
 952       }
 953       return NULL;
 954     }
 955 
 956     resolve_or_init(k, do_init, CHECK_NULL);
 957 
 958     // Load/link/initialize the klasses of the objects in the subgraph.
 959     // NULL class loader is used.
 960     Array<Klass*>* klasses = record->subgraph_object_klasses();
 961     if (klasses != NULL) {
 962       for (int i = 0; i < klasses->length(); i++) {
 963         Klass* klass = klasses->at(i);
 964         if (!klass->is_shared()) {
 965           return NULL;
 966         }
 967         resolve_or_init(klass, do_init, CHECK_NULL);
 968       }
 969     }
 970   }
 971 
 972   return record;
 973 }
 974 
 975 void HeapShared::resolve_or_init(Klass* k, bool do_init, TRAPS) {
 976   if (!do_init) {
 977     if (k->class_loader_data() == NULL) {
 978       Klass* resolved_k = SystemDictionary::resolve_or_null(k->name(), CHECK);
 979       assert(resolved_k == k, "classes used by archived heap must not be replaced by JVMTI ClassFileLoadHook");
 980     }
 981   } else {
 982     assert(k->class_loader_data() != NULL, "must have been resolved by HeapShared::resolve_classes");
 983     if (k->is_instance_klass()) {
 984       InstanceKlass* ik = InstanceKlass::cast(k);
 985       ik->initialize(CHECK);
 986     } else if (k->is_objArray_klass()) {
 987       ObjArrayKlass* oak = ObjArrayKlass::cast(k);
 988       oak->initialize(CHECK);
 989     }
 990   }
 991 }
 992 
 993 void HeapShared::init_archived_fields_for(Klass* k, const ArchivedKlassSubGraphInfoRecord* record) {
 994   verify_the_heap(k, "before");
 995 
 996   // Load the subgraph entry fields from the record and store them back to
 997   // the corresponding fields within the mirror.
 998   oop m = k->java_mirror();
 999   Array<int>* entry_field_records = record->entry_field_records();
1000   if (entry_field_records != NULL) {
1001     int efr_len = entry_field_records->length();
1002     assert(efr_len % 2 == 0, "sanity");
1003     for (int i = 0; i < efr_len; i += 2) {
1004       int field_offset = entry_field_records->at(i);
1005       int root_index = entry_field_records->at(i+1);
1006       oop v = get_root(root_index, /*clear=*/true);
1007       m->obj_field_put(field_offset, v);
1008       log_debug(cds, heap)("  " PTR_FORMAT " init field @ %2d = " PTR_FORMAT, p2i(k), field_offset, p2i(v));
1009     }
1010 
1011     // Done. Java code can see the archived sub-graphs referenced from k's
1012     // mirror after this point.
1013     if (log_is_enabled(Info, cds, heap)) {
1014       ResourceMark rm;
1015       log_info(cds, heap)("initialize_from_archived_subgraph %s " PTR_FORMAT "%s",
1016                           k->external_name(), p2i(k), JvmtiExport::is_early_phase() ? " (early)" : "");
1017     }
1018   }
1019 
1020   verify_the_heap(k, "after ");
1021 }
1022 
1023 void HeapShared::clear_archived_roots_of(Klass* k) {
1024   unsigned int hash = SystemDictionaryShared::hash_for_shared_dictionary_quick(k);
1025   const ArchivedKlassSubGraphInfoRecord* record = _run_time_subgraph_info_table.lookup(k, hash, 0);
1026   if (record != NULL) {
1027     Array<int>* entry_field_records = record->entry_field_records();
1028     if (entry_field_records != NULL) {
1029       int efr_len = entry_field_records->length();
1030       assert(efr_len % 2 == 0, "sanity");
1031       for (int i = 0; i < efr_len; i += 2) {
1032         int root_index = entry_field_records->at(i+1);
1033         clear_root(root_index);
1034       }
1035     }
1036   }
1037 }
1038 
1039 class WalkOopAndArchiveClosure: public BasicOopIterateClosure {
1040   int _level;
1041   bool _is_closed_archive;
1042   bool _record_klasses_only;
1043   KlassSubGraphInfo* _subgraph_info;
1044   oop _orig_referencing_obj;
1045   oop _archived_referencing_obj;
1046 
1047   // The following are for maintaining a stack for determining
1048   // CachedOopInfo::_referrer
1049   static WalkOopAndArchiveClosure* _current;
1050   WalkOopAndArchiveClosure* _last;
1051  public:
1052   WalkOopAndArchiveClosure(int level,
1053                            bool is_closed_archive,
1054                            bool record_klasses_only,
1055                            KlassSubGraphInfo* subgraph_info,
1056                            oop orig, oop archived) :
1057     _level(level), _is_closed_archive(is_closed_archive),
1058     _record_klasses_only(record_klasses_only),
1059     _subgraph_info(subgraph_info),
1060     _orig_referencing_obj(orig), _archived_referencing_obj(archived) {
1061     _last = _current;
1062     _current = this;
1063   }
1064   ~WalkOopAndArchiveClosure() {
1065     _current = _last;
1066   }
1067   void do_oop(narrowOop *p) { WalkOopAndArchiveClosure::do_oop_work(p); }
1068   void do_oop(      oop *p) { WalkOopAndArchiveClosure::do_oop_work(p); }
1069 
1070  protected:
1071   template <class T> void do_oop_work(T *p) {
1072     oop obj = RawAccess<>::oop_load(p);
1073     if (!CompressedOops::is_null(obj)) {
1074       assert(!HeapShared::is_archived_object_during_dumptime(obj),
1075              "original objects must not point to archived objects");
1076 
1077       size_t field_delta = pointer_delta(p, _orig_referencing_obj, sizeof(char));
1078       T* new_p = (T*)(cast_from_oop<address>(_archived_referencing_obj) + field_delta);
1079 
1080       if (!_record_klasses_only && log_is_enabled(Debug, cds, heap)) {
1081         ResourceMark rm;
1082         log_debug(cds, heap)("(%d) %s[" SIZE_FORMAT "] ==> " PTR_FORMAT " size " SIZE_FORMAT " %s", _level,
1083                              _orig_referencing_obj->klass()->external_name(), field_delta,
1084                              p2i(obj), obj->size() * HeapWordSize, obj->klass()->external_name());
1085         LogTarget(Trace, cds, heap) log;
1086         LogStream out(log);
1087         obj->print_on(&out);
1088       }
1089 
1090       oop archived = HeapShared::archive_reachable_objects_from(
1091           _level + 1, _subgraph_info, obj, _is_closed_archive);
1092       assert(archived != NULL, "VM should have exited with unarchivable objects for _level > 1");
1093       assert(HeapShared::is_archived_object_during_dumptime(archived), "must be");
1094 
1095       if (!_record_klasses_only) {
1096         // Update the reference in the archived copy of the referencing object.
1097         log_debug(cds, heap)("(%d) updating oop @[" PTR_FORMAT "] " PTR_FORMAT " ==> " PTR_FORMAT,
1098                              _level, p2i(new_p), p2i(obj), p2i(archived));
1099         RawAccess<IS_NOT_NULL>::oop_store(new_p, archived);
1100       }
1101     }
1102   }
1103 
1104  public:
1105   static WalkOopAndArchiveClosure* current()  { return _current;              }
1106   oop orig_referencing_obj()                  { return _orig_referencing_obj; }
1107   KlassSubGraphInfo* subgraph_info()          { return _subgraph_info;        }
1108 };
1109 
1110 WalkOopAndArchiveClosure* WalkOopAndArchiveClosure::_current = NULL;
1111 
1112 HeapShared::CachedOopInfo HeapShared::make_cached_oop_info(oop orig_obj) {
1113   CachedOopInfo info;
1114   WalkOopAndArchiveClosure* walker = WalkOopAndArchiveClosure::current();
1115 
1116   info._subgraph_info = (walker == NULL) ? NULL : walker->subgraph_info();
1117   info._referrer = (walker == NULL) ? NULL : walker->orig_referencing_obj();
1118   info._obj = orig_obj;
1119 
1120   return info;
1121 }
1122 
1123 void HeapShared::check_closed_region_object(InstanceKlass* k) {
1124   // Check fields in the object
1125   for (JavaFieldStream fs(k); !fs.done(); fs.next()) {
1126     if (!fs.access_flags().is_static()) {
1127       BasicType ft = fs.field_descriptor().field_type();
1128       if (!fs.access_flags().is_final() && is_reference_type(ft)) {
1129         ResourceMark rm;
1130         log_warning(cds, heap)(
1131           "Please check reference field in %s instance in closed archive heap region: %s %s",
1132           k->external_name(), (fs.name())->as_C_string(),
1133           (fs.signature())->as_C_string());
1134       }
1135     }
1136   }
1137 }
1138 
1139 void HeapShared::check_module_oop(oop orig_module_obj) {
1140   assert(DumpSharedSpaces, "must be");
1141   assert(java_lang_Module::is_instance(orig_module_obj), "must be");
1142   ModuleEntry* orig_module_ent = java_lang_Module::module_entry_raw(orig_module_obj);
1143   if (orig_module_ent == NULL) {
1144     // These special Module objects are created in Java code. They are not
1145     // defined via Modules::define_module(), so they don't have a ModuleEntry:
1146     //     java.lang.Module::ALL_UNNAMED_MODULE
1147     //     java.lang.Module::EVERYONE_MODULE
1148     //     jdk.internal.loader.ClassLoaders$BootClassLoader::unnamedModule
1149     assert(java_lang_Module::name(orig_module_obj) == NULL, "must be unnamed");
1150     log_info(cds, heap)("Module oop with No ModuleEntry* @[" PTR_FORMAT "]", p2i(orig_module_obj));
1151   } else {
1152     ClassLoaderData* loader_data = orig_module_ent->loader_data();
1153     assert(loader_data->is_builtin_class_loader_data(), "must be");
1154   }
1155 }
1156 
1157 
1158 // (1) If orig_obj has not been archived yet, archive it.
1159 // (2) If orig_obj has not been seen yet (since start_recording_subgraph() was called),
1160 //     trace all  objects that are reachable from it, and make sure these objects are archived.
1161 // (3) Record the klasses of all orig_obj and all reachable objects.
1162 oop HeapShared::archive_reachable_objects_from(int level,
1163                                                KlassSubGraphInfo* subgraph_info,
1164                                                oop orig_obj,
1165                                                bool is_closed_archive) {
1166   assert(orig_obj != NULL, "must be");
1167   assert(!is_archived_object_during_dumptime(orig_obj), "sanity");
1168 
1169   if (!JavaClasses::is_supported_for_archiving(orig_obj)) {
1170     // This object has injected fields that cannot be supported easily, so we disallow them for now.
1171     // If you get an error here, you probably made a change in the JDK library that has added
1172     // these objects that are referenced (directly or indirectly) by static fields.
1173     ResourceMark rm;
1174     log_error(cds, heap)("Cannot archive object of class %s", orig_obj->klass()->external_name());
1175     vm_direct_exit(1);
1176   }
1177 
1178   // java.lang.Class instances cannot be included in an archived object sub-graph. We only support
1179   // them as Klass::_archived_mirror because they need to be specially restored at run time.
1180   //
1181   // If you get an error here, you probably made a change in the JDK library that has added a Class
1182   // object that is referenced (directly or indirectly) by static fields.
1183   if (java_lang_Class::is_instance(orig_obj)) {
1184     log_error(cds, heap)("(%d) Unknown java.lang.Class object is in the archived sub-graph", level);
1185     vm_direct_exit(1);
1186   }
1187 
1188   oop archived_obj = find_archived_heap_object(orig_obj);
1189   if (java_lang_String::is_instance(orig_obj) && archived_obj != NULL) {
1190     // To save time, don't walk strings that are already archived. They just contain
1191     // pointers to a type array, whose klass doesn't need to be recorded.
1192     return archived_obj;
1193   }
1194 
1195   if (has_been_seen_during_subgraph_recording(orig_obj)) {
1196     // orig_obj has already been archived and traced. Nothing more to do.
1197     return archived_obj;
1198   } else {
1199     set_has_been_seen_during_subgraph_recording(orig_obj);
1200   }
1201 
1202   bool record_klasses_only = (archived_obj != NULL);
1203   if (archived_obj == NULL) {
1204     ++_num_new_archived_objs;
1205     archived_obj = archive_object(orig_obj);
1206     if (archived_obj == NULL) {
1207       // Skip archiving the sub-graph referenced from the current entry field.
1208       ResourceMark rm;
1209       log_error(cds, heap)(
1210         "Cannot archive the sub-graph referenced from %s object ("
1211         PTR_FORMAT ") size " SIZE_FORMAT ", skipped.",
1212         orig_obj->klass()->external_name(), p2i(orig_obj), orig_obj->size() * HeapWordSize);
1213       if (level == 1) {
1214         // Don't archive a subgraph root that's too big. For archives static fields, that's OK
1215         // as the Java code will take care of initializing this field dynamically.
1216         return NULL;
1217       } else {
1218         // We don't know how to handle an object that has been archived, but some of its reachable
1219         // objects cannot be archived. Bail out for now. We might need to fix this in the future if
1220         // we have a real use case.
1221         vm_direct_exit(1);
1222       }
1223     }
1224 
1225     if (java_lang_Module::is_instance(orig_obj)) {
1226       check_module_oop(orig_obj);
1227       java_lang_Module::set_module_entry(archived_obj, NULL);
1228       java_lang_Module::set_loader(archived_obj, NULL);
1229     } else if (java_lang_ClassLoader::is_instance(orig_obj)) {
1230       // class_data will be restored explicitly at run time.
1231       guarantee(orig_obj == SystemDictionary::java_platform_loader() ||
1232                 orig_obj == SystemDictionary::java_system_loader() ||
1233                 java_lang_ClassLoader::loader_data(orig_obj) == NULL, "must be");
1234       java_lang_ClassLoader::release_set_loader_data(archived_obj, NULL);
1235     }
1236   }
1237 
1238   assert(archived_obj != NULL, "must be");
1239   Klass *orig_k = orig_obj->klass();
1240   subgraph_info->add_subgraph_object_klass(orig_k);
1241 
1242   WalkOopAndArchiveClosure walker(level, is_closed_archive, record_klasses_only,
1243                                   subgraph_info, orig_obj, archived_obj);
1244   orig_obj->oop_iterate(&walker);
1245   if (is_closed_archive && orig_k->is_instance_klass()) {
1246     check_closed_region_object(InstanceKlass::cast(orig_k));
1247   }
1248 
1249   check_enum_obj(level + 1, subgraph_info, orig_obj, is_closed_archive);
1250   return archived_obj;
1251 }
1252 
1253 //
1254 // Start from the given static field in a java mirror and archive the
1255 // complete sub-graph of java heap objects that are reached directly
1256 // or indirectly from the starting object by following references.
1257 // Sub-graph archiving restrictions (current):
1258 //
1259 // - All classes of objects in the archived sub-graph (including the
1260 //   entry class) must be boot class only.
1261 // - No java.lang.Class instance (java mirror) can be included inside
1262 //   an archived sub-graph. Mirror can only be the sub-graph entry object.
1263 //
1264 // The Java heap object sub-graph archiving process (see
1265 // WalkOopAndArchiveClosure):
1266 //
1267 // 1) Java object sub-graph archiving starts from a given static field
1268 // within a Class instance (java mirror). If the static field is a
1269 // reference field and points to a non-null java object, proceed to
1270 // the next step.
1271 //
1272 // 2) Archives the referenced java object. If an archived copy of the
1273 // current object already exists, updates the pointer in the archived
1274 // copy of the referencing object to point to the current archived object.
1275 // Otherwise, proceed to the next step.
1276 //
1277 // 3) Follows all references within the current java object and recursively
1278 // archive the sub-graph of objects starting from each reference.
1279 //
1280 // 4) Updates the pointer in the archived copy of referencing object to
1281 // point to the current archived object.
1282 //
1283 // 5) The Klass of the current java object is added to the list of Klasses
1284 // for loading and initializing before any object in the archived graph can
1285 // be accessed at runtime.
1286 //
1287 void HeapShared::archive_reachable_objects_from_static_field(InstanceKlass *k,
1288                                                              const char* klass_name,
1289                                                              int field_offset,
1290                                                              const char* field_name,
1291                                                              bool is_closed_archive) {
1292   assert(DumpSharedSpaces, "dump time only");
1293   assert(k->is_shared_boot_class(), "must be boot class");
1294 
1295   oop m = k->java_mirror();
1296 
1297   KlassSubGraphInfo* subgraph_info = get_subgraph_info(k);
1298   oop f = m->obj_field(field_offset);
1299 
1300   log_debug(cds, heap)("Start archiving from: %s::%s (" PTR_FORMAT ")", klass_name, field_name, p2i(f));
1301 
1302   if (!CompressedOops::is_null(f)) {
1303     if (log_is_enabled(Trace, cds, heap)) {
1304       LogTarget(Trace, cds, heap) log;
1305       LogStream out(log);
1306       f->print_on(&out);
1307     }
1308 
1309     oop af = archive_reachable_objects_from(1, subgraph_info, f, is_closed_archive);
1310 
1311     if (af == NULL) {
1312       log_error(cds, heap)("Archiving failed %s::%s (some reachable objects cannot be archived)",
1313                            klass_name, field_name);
1314     } else {
1315       // Note: the field value is not preserved in the archived mirror.
1316       // Record the field as a new subGraph entry point. The recorded
1317       // information is restored from the archive at runtime.
1318       subgraph_info->add_subgraph_entry_field(field_offset, af, is_closed_archive);
1319       log_info(cds, heap)("Archived field %s::%s => " PTR_FORMAT, klass_name, field_name, p2i(af));
1320     }
1321   } else {
1322     // The field contains null, we still need to record the entry point,
1323     // so it can be restored at runtime.
1324     subgraph_info->add_subgraph_entry_field(field_offset, NULL, false);
1325   }
1326 }
1327 
1328 #ifndef PRODUCT
1329 class VerifySharedOopClosure: public BasicOopIterateClosure {
1330  private:
1331   bool _is_archived;
1332 
1333  public:
1334   VerifySharedOopClosure(bool is_archived) : _is_archived(is_archived) {}
1335 
1336   void do_oop(narrowOop *p) { VerifySharedOopClosure::do_oop_work(p); }
1337   void do_oop(      oop *p) { VerifySharedOopClosure::do_oop_work(p); }
1338 
1339  protected:
1340   template <class T> void do_oop_work(T *p) {
1341     oop obj = RawAccess<>::oop_load(p);
1342     if (!CompressedOops::is_null(obj)) {
1343       HeapShared::verify_reachable_objects_from(obj, _is_archived);
1344     }
1345   }
1346 };
1347 
1348 void HeapShared::verify_subgraph_from_static_field(InstanceKlass* k, int field_offset) {
1349   assert(DumpSharedSpaces, "dump time only");
1350   assert(k->is_shared_boot_class(), "must be boot class");
1351 
1352   oop m = k->java_mirror();
1353   oop f = m->obj_field(field_offset);
1354   if (!CompressedOops::is_null(f)) {
1355     verify_subgraph_from(f);
1356   }
1357 }
1358 
1359 void HeapShared::verify_subgraph_from(oop orig_obj) {
1360   oop archived_obj = find_archived_heap_object(orig_obj);
1361   if (archived_obj == NULL) {
1362     // It's OK for the root of a subgraph to be not archived. See comments in
1363     // archive_reachable_objects_from().
1364     return;
1365   }
1366 
1367   // Verify that all objects reachable from orig_obj are archived.
1368   init_seen_objects_table();
1369   verify_reachable_objects_from(orig_obj, false);
1370   delete_seen_objects_table();
1371 
1372   // Note: we could also verify that all objects reachable from the archived
1373   // copy of orig_obj can only point to archived objects, with:
1374   //      init_seen_objects_table();
1375   //      verify_reachable_objects_from(archived_obj, true);
1376   //      init_seen_objects_table();
1377   // but that's already done in G1HeapVerifier::verify_archive_regions so we
1378   // won't do it here.
1379 }
1380 
1381 void HeapShared::verify_reachable_objects_from(oop obj, bool is_archived) {
1382   _num_total_verifications ++;
1383   if (!has_been_seen_during_subgraph_recording(obj)) {
1384     set_has_been_seen_during_subgraph_recording(obj);
1385 
1386     if (is_archived) {
1387       assert(is_archived_object_during_dumptime(obj), "must be");
1388       assert(find_archived_heap_object(obj) == NULL, "must be");
1389     } else {
1390       assert(!is_archived_object_during_dumptime(obj), "must be");
1391       assert(find_archived_heap_object(obj) != NULL, "must be");
1392     }
1393 
1394     VerifySharedOopClosure walker(is_archived);
1395     obj->oop_iterate(&walker);
1396   }
1397 }
1398 #endif
1399 
1400 HeapShared::SeenObjectsTable* HeapShared::_seen_objects_table = NULL;
1401 int HeapShared::_num_new_walked_objs;
1402 int HeapShared::_num_new_archived_objs;
1403 int HeapShared::_num_old_recorded_klasses;
1404 
1405 int HeapShared::_num_total_subgraph_recordings = 0;
1406 int HeapShared::_num_total_walked_objs = 0;
1407 int HeapShared::_num_total_archived_objs = 0;
1408 int HeapShared::_num_total_recorded_klasses = 0;
1409 int HeapShared::_num_total_verifications = 0;
1410 
1411 bool HeapShared::has_been_seen_during_subgraph_recording(oop obj) {
1412   return _seen_objects_table->get(obj) != NULL;
1413 }
1414 
1415 void HeapShared::set_has_been_seen_during_subgraph_recording(oop obj) {
1416   assert(!has_been_seen_during_subgraph_recording(obj), "sanity");
1417   _seen_objects_table->put(obj, true);
1418   ++ _num_new_walked_objs;
1419 }
1420 
1421 void HeapShared::start_recording_subgraph(InstanceKlass *k, const char* class_name, bool is_full_module_graph) {
1422   log_info(cds, heap)("Start recording subgraph(s) for archived fields in %s", class_name);
1423   init_subgraph_info(k, is_full_module_graph);
1424   init_seen_objects_table();
1425   _num_new_walked_objs = 0;
1426   _num_new_archived_objs = 0;
1427   _num_old_recorded_klasses = get_subgraph_info(k)->num_subgraph_object_klasses();
1428 }
1429 
1430 void HeapShared::done_recording_subgraph(InstanceKlass *k, const char* class_name) {
1431   int num_new_recorded_klasses = get_subgraph_info(k)->num_subgraph_object_klasses() -
1432     _num_old_recorded_klasses;
1433   log_info(cds, heap)("Done recording subgraph(s) for archived fields in %s: "
1434                       "walked %d objs, archived %d new objs, recorded %d classes",
1435                       class_name, _num_new_walked_objs, _num_new_archived_objs,
1436                       num_new_recorded_klasses);
1437 
1438   delete_seen_objects_table();
1439 
1440   _num_total_subgraph_recordings ++;
1441   _num_total_walked_objs      += _num_new_walked_objs;
1442   _num_total_archived_objs    += _num_new_archived_objs;
1443   _num_total_recorded_klasses +=  num_new_recorded_klasses;
1444 }
1445 
1446 class ArchivableStaticFieldFinder: public FieldClosure {
1447   InstanceKlass* _ik;
1448   Symbol* _field_name;
1449   bool _found;
1450   int _offset;
1451 public:
1452   ArchivableStaticFieldFinder(InstanceKlass* ik, Symbol* field_name) :
1453     _ik(ik), _field_name(field_name), _found(false), _offset(-1) {}
1454 
1455   virtual void do_field(fieldDescriptor* fd) {
1456     if (fd->name() == _field_name) {
1457       assert(!_found, "fields cannot be overloaded");
1458       assert(is_reference_type(fd->field_type()), "can archive only fields that are references");
1459       _found = true;
1460       _offset = fd->offset();
1461     }
1462   }
1463   bool found()     { return _found;  }
1464   int offset()     { return _offset; }
1465 };
1466 
1467 void HeapShared::init_subgraph_entry_fields(ArchivableStaticFieldInfo fields[],
1468                                             int num, TRAPS) {
1469   for (int i = 0; i < num; i++) {
1470     ArchivableStaticFieldInfo* info = &fields[i];
1471     TempNewSymbol klass_name =  SymbolTable::new_symbol(info->klass_name);
1472     TempNewSymbol field_name =  SymbolTable::new_symbol(info->field_name);
1473 
1474     Klass* k = SystemDictionary::resolve_or_fail(klass_name, true, CHECK);
1475     InstanceKlass* ik = InstanceKlass::cast(k);
1476     assert(InstanceKlass::cast(ik)->is_shared_boot_class(),
1477            "Only support boot classes");
1478     ik->initialize(CHECK);
1479 
1480     ArchivableStaticFieldFinder finder(ik, field_name);
1481     ik->do_local_static_fields(&finder);
1482     assert(finder.found(), "field must exist");
1483 
1484     info->klass = ik;
1485     info->offset = finder.offset();
1486   }
1487 }
1488 
1489 void HeapShared::init_subgraph_entry_fields(TRAPS) {
1490   assert(HeapShared::can_write(), "must be");
1491   _dump_time_subgraph_info_table = new (ResourceObj::C_HEAP, mtClass)DumpTimeKlassSubGraphInfoTable();
1492   init_subgraph_entry_fields(closed_archive_subgraph_entry_fields,
1493                              num_closed_archive_subgraph_entry_fields,
1494                              CHECK);
1495   init_subgraph_entry_fields(open_archive_subgraph_entry_fields,
1496                              num_open_archive_subgraph_entry_fields,
1497                              CHECK);
1498   if (MetaspaceShared::use_full_module_graph()) {
1499     init_subgraph_entry_fields(fmg_open_archive_subgraph_entry_fields,
1500                                num_fmg_open_archive_subgraph_entry_fields,
1501                                CHECK);
1502   }
1503 }
1504 
1505 void HeapShared::init_for_dumping(TRAPS) {
1506   if (HeapShared::can_write()) {
1507     _dumped_interned_strings = new (ResourceObj::C_HEAP, mtClass)DumpedInternedStrings();
1508     init_subgraph_entry_fields(CHECK);
1509   }
1510 }
1511 
1512 void HeapShared::archive_object_subgraphs(ArchivableStaticFieldInfo fields[],
1513                                           int num, bool is_closed_archive,
1514                                           bool is_full_module_graph) {
1515   _num_total_subgraph_recordings = 0;
1516   _num_total_walked_objs = 0;
1517   _num_total_archived_objs = 0;
1518   _num_total_recorded_klasses = 0;
1519   _num_total_verifications = 0;
1520 
1521   // For each class X that has one or more archived fields:
1522   // [1] Dump the subgraph of each archived field
1523   // [2] Create a list of all the class of the objects that can be reached
1524   //     by any of these static fields.
1525   //     At runtime, these classes are initialized before X's archived fields
1526   //     are restored by HeapShared::initialize_from_archived_subgraph().
1527   int i;
1528   for (i = 0; i < num; ) {
1529     ArchivableStaticFieldInfo* info = &fields[i];
1530     const char* klass_name = info->klass_name;
1531     start_recording_subgraph(info->klass, klass_name, is_full_module_graph);
1532 
1533     // If you have specified consecutive fields of the same klass in
1534     // fields[], these will be archived in the same
1535     // {start_recording_subgraph ... done_recording_subgraph} pass to
1536     // save time.
1537     for (; i < num; i++) {
1538       ArchivableStaticFieldInfo* f = &fields[i];
1539       if (f->klass_name != klass_name) {
1540         break;
1541       }
1542 
1543       archive_reachable_objects_from_static_field(f->klass, f->klass_name,
1544                                                   f->offset, f->field_name,
1545                                                   is_closed_archive);
1546     }
1547     done_recording_subgraph(info->klass, klass_name);
1548   }
1549 
1550   log_info(cds, heap)("Archived subgraph records in %s archive heap region = %d",
1551                       is_closed_archive ? "closed" : "open",
1552                       _num_total_subgraph_recordings);
1553   log_info(cds, heap)("  Walked %d objects", _num_total_walked_objs);
1554   log_info(cds, heap)("  Archived %d objects", _num_total_archived_objs);
1555   log_info(cds, heap)("  Recorded %d klasses", _num_total_recorded_klasses);
1556 
1557 #ifndef PRODUCT
1558   for (int i = 0; i < num; i++) {
1559     ArchivableStaticFieldInfo* f = &fields[i];
1560     verify_subgraph_from_static_field(f->klass, f->offset);
1561   }
1562   log_info(cds, heap)("  Verified %d references", _num_total_verifications);
1563 #endif
1564 }
1565 
1566 // Not all the strings in the global StringTable are dumped into the archive, because
1567 // some of those strings may be only referenced by classes that are excluded from
1568 // the archive. We need to explicitly mark the strings that are:
1569 //   [1] used by classes that WILL be archived;
1570 //   [2] included in the SharedArchiveConfigFile.
1571 void HeapShared::add_to_dumped_interned_strings(oop string) {
1572   assert_at_safepoint(); // DumpedInternedStrings uses raw oops
1573   bool created;
1574   _dumped_interned_strings->put_if_absent(string, true, &created);
1575 }
1576 
1577 // At dump-time, find the location of all the non-null oop pointers in an archived heap
1578 // region. This way we can quickly relocate all the pointers without using
1579 // BasicOopIterateClosure at runtime.
1580 class FindEmbeddedNonNullPointers: public BasicOopIterateClosure {
1581   void* _start;
1582   BitMap *_oopmap;
1583   int _num_total_oops;
1584   int _num_null_oops;
1585  public:
1586   FindEmbeddedNonNullPointers(void* start, BitMap* oopmap)
1587     : _start(start), _oopmap(oopmap), _num_total_oops(0),  _num_null_oops(0) {}
1588 
1589   virtual void do_oop(narrowOop* p) {
1590     _num_total_oops ++;
1591     narrowOop v = *p;
1592     if (!CompressedOops::is_null(v)) {
1593       size_t idx = p - (narrowOop*)_start;
1594       _oopmap->set_bit(idx);
1595     } else {
1596       _num_null_oops ++;
1597     }
1598   }
1599   virtual void do_oop(oop* p) {
1600     _num_total_oops ++;
1601     if ((*p) != NULL) {
1602       size_t idx = p - (oop*)_start;
1603       _oopmap->set_bit(idx);
1604     } else {
1605       _num_null_oops ++;
1606     }
1607   }
1608   int num_total_oops() const { return _num_total_oops; }
1609   int num_null_oops()  const { return _num_null_oops; }
1610 };
1611 
1612 ResourceBitMap HeapShared::calculate_oopmap(MemRegion region) {
1613   size_t num_bits = region.byte_size() / (UseCompressedOops ? sizeof(narrowOop) : sizeof(oop));
1614   ResourceBitMap oopmap(num_bits);
1615 
1616   HeapWord* p   = region.start();
1617   HeapWord* end = region.end();
1618   FindEmbeddedNonNullPointers finder((void*)p, &oopmap);
1619   ArchiveBuilder* builder = DumpSharedSpaces ? ArchiveBuilder::current() : NULL;
1620 
1621   int num_objs = 0;
1622   while (p < end) {
1623     oop o = cast_to_oop(p);
1624     o->oop_iterate(&finder);
1625     p += o->size();
1626     if (DumpSharedSpaces) {
1627       builder->relocate_klass_ptr(o);
1628     }
1629     ++ num_objs;
1630   }
1631 
1632   log_info(cds, heap)("calculate_oopmap: objects = %6d, embedded oops = %7d, nulls = %7d",
1633                       num_objs, finder.num_total_oops(), finder.num_null_oops());
1634   return oopmap;
1635 }
1636 
1637 // Patch all the embedded oop pointers inside an archived heap region,
1638 // to be consistent with the runtime oop encoding.
1639 class PatchCompressedEmbeddedPointers: public BitMapClosure {
1640   narrowOop* _start;
1641 
1642  public:
1643   PatchCompressedEmbeddedPointers(narrowOop* start) : _start(start) {}
1644 
1645   bool do_bit(size_t offset) {
1646     narrowOop* p = _start + offset;
1647     narrowOop v = *p;
1648     assert(!CompressedOops::is_null(v), "null oops should have been filtered out at dump time");
1649     oop o = HeapShared::decode_from_archive(v);
1650     RawAccess<IS_NOT_NULL>::oop_store(p, o);
1651     return true;
1652   }
1653 };
1654 
1655 class PatchUncompressedEmbeddedPointers: public BitMapClosure {
1656   oop* _start;
1657 
1658  public:
1659   PatchUncompressedEmbeddedPointers(oop* start) : _start(start) {}
1660 
1661   bool do_bit(size_t offset) {
1662     oop* p = _start + offset;
1663     intptr_t dumptime_oop = (intptr_t)((void*)*p);
1664     assert(dumptime_oop != 0, "null oops should have been filtered out at dump time");
1665     intptr_t runtime_oop = dumptime_oop + HeapShared::runtime_delta();
1666     RawAccess<IS_NOT_NULL>::oop_store(p, cast_to_oop(runtime_oop));
1667     return true;
1668   }
1669 };
1670 
1671 // Patch all the non-null pointers that are embedded in the archived heap objects
1672 // in this region
1673 void HeapShared::patch_embedded_pointers(MemRegion region, address oopmap,
1674                                          size_t oopmap_size_in_bits) {
1675   BitMapView bm((BitMap::bm_word_t*)oopmap, oopmap_size_in_bits);
1676 
1677 #ifndef PRODUCT
1678   ResourceMark rm;
1679   ResourceBitMap checkBm = calculate_oopmap(region);
1680   assert(bm.is_same(checkBm), "sanity");
1681 #endif
1682 
1683   if (UseCompressedOops) {
1684     PatchCompressedEmbeddedPointers patcher((narrowOop*)region.start());
1685     bm.iterate(&patcher);
1686   } else {
1687     PatchUncompressedEmbeddedPointers patcher((oop*)region.start());
1688     bm.iterate(&patcher);
1689   }
1690 }
1691 
1692 // The CDS archive remembers each heap object by its address at dump time, but
1693 // the heap object may be loaded at a different address at run time. This structure is used
1694 // to translate the dump time addresses for all objects in FileMapInfo::space_at(region_index)
1695 // to their runtime addresses.
1696 struct LoadedArchiveHeapRegion {
1697   int       _region_index;   // index for FileMapInfo::space_at(index)
1698   size_t    _region_size;    // number of bytes in this region
1699   uintptr_t _dumptime_base;  // The dump-time (decoded) address of the first object in this region
1700   intx      _runtime_offset; // If an object's dump time address P is within in this region, its
1701                              // runtime address is P + _runtime_offset
1702 
1703   static int comparator(const void* a, const void* b) {
1704     LoadedArchiveHeapRegion* reg_a = (LoadedArchiveHeapRegion*)a;
1705     LoadedArchiveHeapRegion* reg_b = (LoadedArchiveHeapRegion*)b;
1706     if (reg_a->_dumptime_base < reg_b->_dumptime_base) {
1707       return -1;
1708     } else if (reg_a->_dumptime_base == reg_b->_dumptime_base) {
1709       return 0;
1710     } else {
1711       return 1;
1712     }
1713   }
1714 
1715   uintptr_t top() {
1716     return _dumptime_base + _region_size;
1717   }
1718 };
1719 
1720 void HeapShared::init_loaded_heap_relocation(LoadedArchiveHeapRegion* loaded_regions,
1721                                              int num_loaded_regions) {
1722   _dumptime_base_0 = loaded_regions[0]._dumptime_base;
1723   _dumptime_base_1 = loaded_regions[1]._dumptime_base;
1724   _dumptime_base_2 = loaded_regions[2]._dumptime_base;
1725   _dumptime_base_3 = loaded_regions[3]._dumptime_base;
1726   _dumptime_top = loaded_regions[num_loaded_regions-1].top();
1727 
1728   _runtime_offset_0 = loaded_regions[0]._runtime_offset;
1729   _runtime_offset_1 = loaded_regions[1]._runtime_offset;
1730   _runtime_offset_2 = loaded_regions[2]._runtime_offset;
1731   _runtime_offset_3 = loaded_regions[3]._runtime_offset;
1732 
1733   assert(2 <= num_loaded_regions && num_loaded_regions <= 4, "must be");
1734   if (num_loaded_regions < 4) {
1735     _dumptime_base_3 = UINTPTR_MAX;
1736   }
1737   if (num_loaded_regions < 3) {
1738     _dumptime_base_2 = UINTPTR_MAX;
1739   }
1740 }
1741 
1742 bool HeapShared::can_load() {
1743   return Universe::heap()->can_load_archived_objects();
1744 }
1745 
1746 template <int NUM_LOADED_REGIONS>
1747 class PatchLoadedRegionPointers: public BitMapClosure {
1748   narrowOop* _start;
1749   intx _offset_0;
1750   intx _offset_1;
1751   intx _offset_2;
1752   intx _offset_3;
1753   uintptr_t _base_0;
1754   uintptr_t _base_1;
1755   uintptr_t _base_2;
1756   uintptr_t _base_3;
1757   uintptr_t _top;
1758 
1759   static_assert(MetaspaceShared::max_num_heap_regions == 4, "can't handle more than 4 regions");
1760   static_assert(NUM_LOADED_REGIONS >= 2, "we have at least 2 loaded regions");
1761   static_assert(NUM_LOADED_REGIONS <= 4, "we have at most 4 loaded regions");
1762 
1763  public:
1764   PatchLoadedRegionPointers(narrowOop* start, LoadedArchiveHeapRegion* loaded_regions)
1765     : _start(start),
1766       _offset_0(loaded_regions[0]._runtime_offset),
1767       _offset_1(loaded_regions[1]._runtime_offset),
1768       _offset_2(loaded_regions[2]._runtime_offset),
1769       _offset_3(loaded_regions[3]._runtime_offset),
1770       _base_0(loaded_regions[0]._dumptime_base),
1771       _base_1(loaded_regions[1]._dumptime_base),
1772       _base_2(loaded_regions[2]._dumptime_base),
1773       _base_3(loaded_regions[3]._dumptime_base) {
1774     _top = loaded_regions[NUM_LOADED_REGIONS-1].top();
1775   }
1776 
1777   bool do_bit(size_t offset) {
1778     narrowOop* p = _start + offset;
1779     narrowOop v = *p;
1780     assert(!CompressedOops::is_null(v), "null oops should have been filtered out at dump time");
1781     uintptr_t o = cast_from_oop<uintptr_t>(HeapShared::decode_from_archive(v));
1782     assert(_base_0 <= o && o < _top, "must be");
1783 
1784 
1785     // We usually have only 2 regions for the default archive. Use template to avoid unnecessary comparisons.
1786     if (NUM_LOADED_REGIONS > 3 && o >= _base_3) {
1787       o += _offset_3;
1788     } else if (NUM_LOADED_REGIONS > 2 && o >= _base_2) {
1789       o += _offset_2;
1790     } else if (o >= _base_1) {
1791       o += _offset_1;
1792     } else {
1793       o += _offset_0;
1794     }
1795     HeapShared::assert_in_loaded_heap(o);
1796     RawAccess<IS_NOT_NULL>::oop_store(p, cast_to_oop(o));
1797     return true;
1798   }
1799 };
1800 
1801 int HeapShared::init_loaded_regions(FileMapInfo* mapinfo, LoadedArchiveHeapRegion* loaded_regions,
1802                                     MemRegion& archive_space) {
1803   size_t total_bytes = 0;
1804   int num_loaded_regions = 0;
1805   for (int i = MetaspaceShared::first_archive_heap_region;
1806        i <= MetaspaceShared::last_archive_heap_region; i++) {
1807     FileMapRegion* r = mapinfo->space_at(i);
1808     r->assert_is_heap_region();
1809     if (r->used() > 0) {
1810       assert(is_aligned(r->used(), HeapWordSize), "must be");
1811       total_bytes += r->used();
1812       LoadedArchiveHeapRegion* ri = &loaded_regions[num_loaded_regions++];
1813       ri->_region_index = i;
1814       ri->_region_size = r->used();
1815       ri->_dumptime_base = (uintptr_t)mapinfo->start_address_as_decoded_from_archive(r);
1816     }
1817   }
1818 
1819   assert(is_aligned(total_bytes, HeapWordSize), "must be");
1820   size_t word_size = total_bytes / HeapWordSize;
1821   HeapWord* buffer = Universe::heap()->allocate_loaded_archive_space(word_size);
1822   if (buffer == nullptr) {
1823     return 0;
1824   }
1825 
1826   archive_space = MemRegion(buffer, word_size);
1827   _loaded_heap_bottom = (uintptr_t)archive_space.start();
1828   _loaded_heap_top    = _loaded_heap_bottom + total_bytes;
1829 
1830   return num_loaded_regions;
1831 }
1832 
1833 void HeapShared::sort_loaded_regions(LoadedArchiveHeapRegion* loaded_regions, int num_loaded_regions,
1834                                      uintptr_t buffer) {
1835   // Find the relocation offset of the pointers in each region
1836   qsort(loaded_regions, num_loaded_regions, sizeof(LoadedArchiveHeapRegion),
1837         LoadedArchiveHeapRegion::comparator);
1838 
1839   uintptr_t p = buffer;
1840   for (int i = 0; i < num_loaded_regions; i++) {
1841     // This region will be loaded at p, so all objects inside this
1842     // region will be shifted by ri->offset
1843     LoadedArchiveHeapRegion* ri = &loaded_regions[i];
1844     ri->_runtime_offset = p - ri->_dumptime_base;
1845     p += ri->_region_size;
1846   }
1847   assert(p == _loaded_heap_top, "must be");
1848 }
1849 
1850 bool HeapShared::load_regions(FileMapInfo* mapinfo, LoadedArchiveHeapRegion* loaded_regions,
1851                               int num_loaded_regions, uintptr_t buffer) {
1852   uintptr_t bitmap_base = (uintptr_t)mapinfo->map_bitmap_region();
1853   if (bitmap_base == 0) {
1854     _loading_failed = true;
1855     return false; // OOM or CRC error
1856   }
1857   uintptr_t load_address = buffer;
1858   for (int i = 0; i < num_loaded_regions; i++) {
1859     LoadedArchiveHeapRegion* ri = &loaded_regions[i];
1860     FileMapRegion* r = mapinfo->space_at(ri->_region_index);
1861 
1862     if (!mapinfo->read_region(ri->_region_index, (char*)load_address, r->used(), /* do_commit = */ false)) {
1863       // There's no easy way to free the buffer, so we will fill it with zero later
1864       // in fill_failed_loaded_region(), and it will eventually be GC'ed.
1865       log_warning(cds)("Loading of heap region %d has failed. Archived objects are disabled", i);
1866       _loading_failed = true;
1867       return false;
1868     }
1869     log_info(cds)("Loaded heap    region #%d at base " INTPTR_FORMAT " top " INTPTR_FORMAT
1870                   " size " SIZE_FORMAT_W(6) " delta " INTX_FORMAT,
1871                   ri->_region_index, load_address, load_address + ri->_region_size,
1872                   ri->_region_size, ri->_runtime_offset);
1873 
1874     uintptr_t oopmap = bitmap_base + r->oopmap_offset();
1875     BitMapView bm((BitMap::bm_word_t*)oopmap, r->oopmap_size_in_bits());
1876 
1877     if (num_loaded_regions == 4) {
1878       PatchLoadedRegionPointers<4> patcher((narrowOop*)load_address, loaded_regions);
1879       bm.iterate(&patcher);
1880     } else if (num_loaded_regions == 3) {
1881       PatchLoadedRegionPointers<3> patcher((narrowOop*)load_address, loaded_regions);
1882       bm.iterate(&patcher);
1883     } else {
1884       assert(num_loaded_regions == 2, "must be");
1885       PatchLoadedRegionPointers<2> patcher((narrowOop*)load_address, loaded_regions);
1886       bm.iterate(&patcher);
1887     }
1888 
1889     load_address += r->used();
1890   }
1891 
1892   return true;
1893 }
1894 
1895 bool HeapShared::load_heap_regions(FileMapInfo* mapinfo) {
1896   init_narrow_oop_decoding(mapinfo->narrow_oop_base(), mapinfo->narrow_oop_shift());
1897 
1898   LoadedArchiveHeapRegion loaded_regions[MetaspaceShared::max_num_heap_regions];
1899   memset(loaded_regions, 0, sizeof(loaded_regions));
1900 
1901   MemRegion archive_space;
1902   int num_loaded_regions = init_loaded_regions(mapinfo, loaded_regions, archive_space);
1903   if (num_loaded_regions <= 0) {
1904     return false;
1905   }
1906   sort_loaded_regions(loaded_regions, num_loaded_regions, (uintptr_t)archive_space.start());
1907   if (!load_regions(mapinfo, loaded_regions, num_loaded_regions, (uintptr_t)archive_space.start())) {
1908     assert(_loading_failed, "must be");
1909     return false;
1910   }
1911 
1912   init_loaded_heap_relocation(loaded_regions, num_loaded_regions);
1913   _is_loaded = true;
1914 
1915   return true;
1916 }
1917 
1918 class VerifyLoadedHeapEmbeddedPointers: public BasicOopIterateClosure {
1919   ResourceHashtable<uintptr_t, bool>* _table;
1920 
1921  public:
1922   VerifyLoadedHeapEmbeddedPointers(ResourceHashtable<uintptr_t, bool>* table) : _table(table) {}
1923 
1924   virtual void do_oop(narrowOop* p) {
1925     // This should be called before the loaded regions are modified, so all the embedded pointers
1926     // must be NULL, or must point to a valid object in the loaded regions.
1927     narrowOop v = *p;
1928     if (!CompressedOops::is_null(v)) {
1929       oop o = CompressedOops::decode_not_null(v);
1930       uintptr_t u = cast_from_oop<uintptr_t>(o);
1931       HeapShared::assert_in_loaded_heap(u);
1932       guarantee(_table->contains(u), "must point to beginning of object in loaded archived regions");
1933     }
1934   }
1935   virtual void do_oop(oop* p) {
1936     ShouldNotReachHere();
1937   }
1938 };
1939 
1940 void HeapShared::finish_initialization() {
1941   if (is_loaded()) {
1942     HeapWord* bottom = (HeapWord*)_loaded_heap_bottom;
1943     HeapWord* top    = (HeapWord*)_loaded_heap_top;
1944 
1945     MemRegion archive_space = MemRegion(bottom, top);
1946     Universe::heap()->complete_loaded_archive_space(archive_space);
1947   }
1948 
1949   if (VerifyArchivedFields <= 0 || !is_loaded()) {
1950     return;
1951   }
1952 
1953   log_info(cds, heap)("Verify all oops and pointers in loaded heap");
1954 
1955   ResourceMark rm;
1956   ResourceHashtable<uintptr_t, bool> table;
1957   VerifyLoadedHeapEmbeddedPointers verifier(&table);
1958   HeapWord* bottom = (HeapWord*)_loaded_heap_bottom;
1959   HeapWord* top    = (HeapWord*)_loaded_heap_top;
1960 
1961   for (HeapWord* p = bottom; p < top; ) {
1962     oop o = cast_to_oop(p);
1963     table.put(cast_from_oop<uintptr_t>(o), true);
1964     p += o->size();
1965   }
1966 
1967   for (HeapWord* p = bottom; p < top; ) {
1968     oop o = cast_to_oop(p);
1969     o->oop_iterate(&verifier);
1970     p += o->size();
1971   }
1972 }
1973 
1974 void HeapShared::fill_failed_loaded_region() {
1975   assert(_loading_failed, "must be");
1976   if (_loaded_heap_bottom != 0) {
1977     assert(_loaded_heap_top != 0, "must be");
1978     HeapWord* bottom = (HeapWord*)_loaded_heap_bottom;
1979     HeapWord* top = (HeapWord*)_loaded_heap_top;
1980     Universe::heap()->fill_with_objects(bottom, top - bottom);
1981   }
1982 }
1983 
1984 #endif // INCLUDE_CDS_JAVA_HEAP