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