1 /*
   2  * Copyright (c) 2018, 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 "classfile/javaClasses.inline.hpp"
  27 #include "classfile/stringTable.hpp"
  28 #include "classfile/symbolTable.hpp"
  29 #include "classfile/vmSymbols.hpp"
  30 #include "logging/log.hpp"
  31 #include "logging/logMessage.hpp"
  32 #include "logging/logStream.hpp"
  33 #include "memory/filemap.hpp"
  34 #include "memory/heapShared.inline.hpp"
  35 #include "memory/iterator.inline.hpp"
  36 #include "memory/metadataFactory.hpp"
  37 #include "memory/metaspaceClosure.hpp"
  38 #include "memory/resourceArea.hpp"
  39 #include "oops/compressedOops.inline.hpp"
  40 #include "oops/oop.inline.hpp"
  41 #include "runtime/fieldDescriptor.inline.hpp"
  42 #include "runtime/safepointVerifiers.hpp"
  43 #include "utilities/bitMap.inline.hpp"
  44 #if INCLUDE_G1GC
  45 #include "gc/g1/g1CollectedHeap.hpp"
  46 #endif
  47 
  48 #if INCLUDE_CDS_JAVA_HEAP
  49 
  50 bool HeapShared::_open_archive_heap_region_mapped = false;
  51 bool HeapShared::_archive_heap_region_fixed = false;
  52 
  53 address   HeapShared::_narrow_oop_base;
  54 int       HeapShared::_narrow_oop_shift;
  55 
  56 ////////////////////////////////////////////////////////////////
  57 //
  58 // Java heap object archiving support
  59 //
  60 ////////////////////////////////////////////////////////////////
  61 void HeapShared::fixup_mapped_heap_regions() {
  62   FileMapInfo *mapinfo = FileMapInfo::current_info();
  63   mapinfo->fixup_mapped_heap_regions();
  64   set_archive_heap_region_fixed();
  65 }
  66 
  67 unsigned HeapShared::oop_hash(oop const& p) {
  68   assert(!p->mark()->has_bias_pattern(),
  69          "this object should never have been locked");  // so identity_hash won't safepoin
  70   unsigned hash = (unsigned)p->identity_hash();
  71   return hash;
  72 }
  73 
  74 HeapShared::ArchivedObjectCache* HeapShared::_archived_object_cache = NULL;
  75 oop HeapShared::find_archived_heap_object(oop obj) {
  76   assert(DumpSharedSpaces, "dump-time only");
  77   ArchivedObjectCache* cache = archived_object_cache();
  78   oop* p = cache->get(obj);
  79   if (p != NULL) {
  80     return *p;
  81   } else {
  82     return NULL;
  83   }
  84 }
  85 
  86 oop HeapShared::archive_heap_object(oop obj, Thread* THREAD) {
  87   assert(DumpSharedSpaces, "dump-time only");
  88 
  89   oop ao = find_archived_heap_object(obj);
  90   if (ao != NULL) {
  91     // already archived
  92     return ao;
  93   }
  94 
  95   int len = obj->size();
  96   if (G1CollectedHeap::heap()->is_archive_alloc_too_large(len)) {
  97     log_debug(cds, heap)("Cannot archive, object (" PTR_FORMAT ") is too large: " SIZE_FORMAT,
  98                          p2i(obj), (size_t)obj->size());
  99     return NULL;
 100   }
 101 
 102   // Pre-compute object identity hash at CDS dump time.
 103   obj->identity_hash();
 104 
 105   oop archived_oop = (oop)G1CollectedHeap::heap()->archive_mem_allocate(len);
 106   if (archived_oop != NULL) {
 107     Copy::aligned_disjoint_words((HeapWord*)obj, (HeapWord*)archived_oop, len);
 108     MetaspaceShared::relocate_klass_ptr(archived_oop);
 109     ArchivedObjectCache* cache = archived_object_cache();
 110     cache->put(obj, archived_oop);
 111     log_debug(cds, heap)("Archived heap object " PTR_FORMAT " ==> " PTR_FORMAT,
 112                          p2i(obj), p2i(archived_oop));
 113   } else {
 114     log_error(cds, heap)(
 115       "Cannot allocate space for object " PTR_FORMAT " in archived heap region",
 116       p2i(obj));
 117     vm_exit(1);
 118   }
 119   return archived_oop;
 120 }
 121 
 122 oop HeapShared::materialize_archived_object(narrowOop v) {
 123   assert(archive_heap_region_fixed(),
 124          "must be called after archive heap regions are fixed");
 125   if (!CompressedOops::is_null(v)) {
 126     oop obj = HeapShared::decode_from_archive(v);
 127     return G1CollectedHeap::heap()->materialize_archived_object(obj);
 128   }
 129   return NULL;
 130 }
 131 
 132 void HeapShared::archive_klass_objects(Thread* THREAD) {
 133   GrowableArray<Klass*>* klasses = MetaspaceShared::collected_klasses();
 134   assert(klasses != NULL, "sanity");
 135   for (int i = 0; i < klasses->length(); i++) {
 136     Klass* k = klasses->at(i);
 137 
 138     // archive mirror object
 139     java_lang_Class::archive_mirror(k, CHECK);
 140 
 141     // archive the resolved_referenes array
 142     if (k->is_instance_klass()) {
 143       InstanceKlass* ik = InstanceKlass::cast(k);
 144       ik->constants()->archive_resolved_references(THREAD);
 145     }
 146   }
 147 }
 148 
 149 void HeapShared::archive_java_heap_objects(GrowableArray<MemRegion> *closed,
 150                                            GrowableArray<MemRegion> *open) {
 151   if (!is_heap_object_archiving_allowed()) {
 152     if (log_is_enabled(Info, cds)) {
 153       log_info(cds)(
 154         "Archived java heap is not supported as UseG1GC, "
 155         "UseCompressedOops and UseCompressedClassPointers are required."
 156         "Current settings: UseG1GC=%s, UseCompressedOops=%s, UseCompressedClassPointers=%s.",
 157         BOOL_TO_STR(UseG1GC), BOOL_TO_STR(UseCompressedOops),
 158         BOOL_TO_STR(UseCompressedClassPointers));
 159     }
 160     return;
 161   }
 162 
 163   {
 164     NoSafepointVerifier nsv;
 165 
 166     // Cache for recording where the archived objects are copied to
 167     create_archived_object_cache();
 168 
 169     tty->print_cr("Dumping objects to closed archive heap region ...");
 170     NOT_PRODUCT(StringTable::verify());
 171     copy_closed_archive_heap_objects(closed);
 172 
 173     tty->print_cr("Dumping objects to open archive heap region ...");
 174     copy_open_archive_heap_objects(open);
 175 
 176     destroy_archived_object_cache();
 177   }
 178 
 179   G1HeapVerifier::verify_archive_regions();
 180 }
 181 
 182 void HeapShared::copy_closed_archive_heap_objects(
 183                                     GrowableArray<MemRegion> * closed_archive) {
 184   assert(is_heap_object_archiving_allowed(), "Cannot archive java heap objects");
 185 
 186   Thread* THREAD = Thread::current();
 187   G1CollectedHeap::heap()->begin_archive_alloc_range();
 188 
 189   // Archive interned string objects
 190   StringTable::write_to_archive();
 191 
 192   G1CollectedHeap::heap()->end_archive_alloc_range(closed_archive,
 193                                                    os::vm_allocation_granularity());
 194 }
 195 
 196 void HeapShared::copy_open_archive_heap_objects(
 197                                     GrowableArray<MemRegion> * open_archive) {
 198   assert(is_heap_object_archiving_allowed(), "Cannot archive java heap objects");
 199 
 200   Thread* THREAD = Thread::current();
 201   G1CollectedHeap::heap()->begin_archive_alloc_range(true /* open */);
 202 
 203   java_lang_Class::archive_basic_type_mirrors(THREAD);
 204 
 205   archive_klass_objects(THREAD);
 206 
 207   archive_object_subgraphs(THREAD);
 208 
 209   G1CollectedHeap::heap()->end_archive_alloc_range(open_archive,
 210                                                    os::vm_allocation_granularity());
 211 }
 212 
 213 void HeapShared::init_narrow_oop_decoding(address base, int shift) {
 214   _narrow_oop_base = base;
 215   _narrow_oop_shift = shift;
 216 }
 217 
 218 //
 219 // Subgraph archiving support
 220 //
 221 HeapShared::DumpTimeKlassSubGraphInfoTable* HeapShared::_dump_time_subgraph_info_table = NULL;
 222 HeapShared::RunTimeKlassSubGraphInfoTable   HeapShared::_run_time_subgraph_info_table;
 223 
 224 // Get the subgraph_info for Klass k. A new subgraph_info is created if
 225 // there is no existing one for k. The subgraph_info records the relocated
 226 // Klass* of the original k.
 227 KlassSubGraphInfo* HeapShared::get_subgraph_info(Klass* k) {
 228   assert(DumpSharedSpaces, "dump time only");
 229   Klass* relocated_k = MetaspaceShared::get_relocated_klass(k);
 230   KlassSubGraphInfo* info = _dump_time_subgraph_info_table->get(relocated_k);
 231   if (info == NULL) {
 232     _dump_time_subgraph_info_table->put(relocated_k, KlassSubGraphInfo(relocated_k));
 233     info = _dump_time_subgraph_info_table->get(relocated_k);
 234     ++ _dump_time_subgraph_info_table->_count;
 235   }
 236   return info;
 237 }
 238 
 239 // Add an entry field to the current KlassSubGraphInfo.
 240 void KlassSubGraphInfo::add_subgraph_entry_field(int static_field_offset, oop v) {
 241   assert(DumpSharedSpaces, "dump time only");
 242   if (_subgraph_entry_fields == NULL) {
 243     _subgraph_entry_fields =
 244       new(ResourceObj::C_HEAP, mtClass) GrowableArray<juint>(10, true);
 245   }
 246   _subgraph_entry_fields->append((juint)static_field_offset);
 247   _subgraph_entry_fields->append(CompressedOops::encode(v));
 248 }
 249 
 250 // Add the Klass* for an object in the current KlassSubGraphInfo's subgraphs.
 251 // Only objects of boot classes can be included in sub-graph.
 252 void KlassSubGraphInfo::add_subgraph_object_klass(Klass* orig_k, Klass *relocated_k) {
 253   assert(DumpSharedSpaces, "dump time only");
 254   assert(relocated_k == MetaspaceShared::get_relocated_klass(orig_k),
 255          "must be the relocated Klass in the shared space");
 256 
 257   if (_subgraph_object_klasses == NULL) {
 258     _subgraph_object_klasses =
 259       new(ResourceObj::C_HEAP, mtClass) GrowableArray<Klass*>(50, true);
 260   }
 261 
 262   assert(relocated_k->is_shared(), "must be a shared class");
 263 
 264   if (_k == relocated_k) {
 265     // Don't add the Klass containing the sub-graph to it's own klass
 266     // initialization list.
 267     return;
 268   }
 269 
 270   if (relocated_k->is_instance_klass()) {
 271     assert(InstanceKlass::cast(relocated_k)->is_shared_boot_class(),
 272           "must be boot class");
 273     // SystemDictionary::xxx_klass() are not updated, need to check
 274     // the original Klass*
 275     if (orig_k == SystemDictionary::String_klass() ||
 276         orig_k == SystemDictionary::Object_klass()) {
 277       // Initialized early during VM initialization. No need to be added
 278       // to the sub-graph object class list.
 279       return;
 280     }
 281   } else if (relocated_k->is_objArray_klass()) {
 282     Klass* abk = ObjArrayKlass::cast(relocated_k)->bottom_klass();
 283     if (abk->is_instance_klass()) {
 284       assert(InstanceKlass::cast(abk)->is_shared_boot_class(),
 285             "must be boot class");
 286     }
 287     if (relocated_k == Universe::objectArrayKlassObj()) {
 288       // Initialized early during Universe::genesis. No need to be added
 289       // to the list.
 290       return;
 291     }
 292   } else {
 293     assert(relocated_k->is_typeArray_klass(), "must be");
 294     // Primitive type arrays are created early during Universe::genesis.
 295     return;
 296   }
 297 
 298   if (log_is_enabled(Debug, cds, heap)) {
 299     if (!_subgraph_object_klasses->contains(relocated_k)) {
 300       ResourceMark rm;
 301       log_debug(cds, heap)("Adding klass %s", orig_k->external_name());
 302     }
 303   }
 304 
 305   _subgraph_object_klasses->append_if_missing(relocated_k);
 306 }
 307 
 308 // Initialize an archived subgraph_info_record from the given KlassSubGraphInfo.
 309 void ArchivedKlassSubGraphInfoRecord::init(KlassSubGraphInfo* info) {
 310   _k = info->klass();
 311   _entry_field_records = NULL;
 312   _subgraph_object_klasses = NULL;
 313 
 314   // populate the entry fields
 315   GrowableArray<juint>* entry_fields = info->subgraph_entry_fields();
 316   if (entry_fields != NULL) {
 317     int num_entry_fields = entry_fields->length();
 318     assert(num_entry_fields % 2 == 0, "sanity");
 319     _entry_field_records =
 320       MetaspaceShared::new_ro_array<juint>(num_entry_fields);
 321     for (int i = 0 ; i < num_entry_fields; i++) {
 322       _entry_field_records->at_put(i, entry_fields->at(i));
 323     }
 324   }
 325 
 326   // the Klasses of the objects in the sub-graphs
 327   GrowableArray<Klass*>* subgraph_object_klasses = info->subgraph_object_klasses();
 328   if (subgraph_object_klasses != NULL) {
 329     int num_subgraphs_klasses = subgraph_object_klasses->length();
 330     _subgraph_object_klasses =
 331       MetaspaceShared::new_ro_array<Klass*>(num_subgraphs_klasses);
 332     for (int i = 0; i < num_subgraphs_klasses; i++) {
 333       Klass* subgraph_k = subgraph_object_klasses->at(i);
 334       if (log_is_enabled(Info, cds, heap)) {
 335         ResourceMark rm;
 336         log_info(cds, heap)(
 337           "Archived object klass %s (%2d) => %s",
 338           _k->external_name(), i, subgraph_k->external_name());
 339       }
 340       _subgraph_object_klasses->at_put(i, subgraph_k);
 341     }
 342   }
 343 }
 344 
 345 struct CopyKlassSubGraphInfoToArchive : StackObj {
 346   CompactHashtableWriter* _writer;
 347   CopyKlassSubGraphInfoToArchive(CompactHashtableWriter* writer) : _writer(writer) {}
 348 
 349   bool do_entry(Klass* klass, KlassSubGraphInfo& info) {
 350     if (info.subgraph_object_klasses() != NULL || info.subgraph_entry_fields() != NULL) {
 351       ArchivedKlassSubGraphInfoRecord* record =
 352         (ArchivedKlassSubGraphInfoRecord*)MetaspaceShared::read_only_space_alloc(sizeof(ArchivedKlassSubGraphInfoRecord));
 353       record->init(&info);
 354 
 355       unsigned int hash = primitive_hash<Klass*>(klass);
 356       uintx deltax = MetaspaceShared::object_delta(record);
 357       guarantee(deltax <= MAX_SHARED_DELTA, "must not be");
 358       u4 delta = u4(deltax);
 359       _writer->add(hash, delta);
 360     }
 361     return true; // keep on iterating
 362   }
 363 };
 364 
 365 // Build the records of archived subgraph infos, which include:
 366 // - Entry points to all subgraphs from the containing class mirror. The entry
 367 //   points are static fields in the mirror. For each entry point, the field
 368 //   offset and value are recorded in the sub-graph info. The value are stored
 369 //   back to the corresponding field at runtime.
 370 // - A list of klasses that need to be loaded/initialized before archived
 371 //   java object sub-graph can be accessed at runtime.
 372 void HeapShared::write_subgraph_info_table() {
 373   // Allocate the contents of the hashtable(s) inside the RO region of the CDS archive.
 374   DumpTimeKlassSubGraphInfoTable* d_table = _dump_time_subgraph_info_table;
 375   CompactHashtableStats stats;
 376 
 377   _run_time_subgraph_info_table.reset();
 378 
 379   int num_buckets = CompactHashtableWriter::default_num_buckets(d_table->_count);
 380   CompactHashtableWriter writer(num_buckets, &stats);
 381   CopyKlassSubGraphInfoToArchive copy(&writer);
 382   _dump_time_subgraph_info_table->iterate(&copy);
 383 
 384   writer.dump(&_run_time_subgraph_info_table, "subgraphs");
 385 }
 386 
 387 void HeapShared::serialize_subgraph_info_table_header(SerializeClosure* soc) {
 388   _run_time_subgraph_info_table.serialize_header(soc);
 389 }
 390 
 391 void HeapShared::initialize_from_archived_subgraph(Klass* k) {
 392   if (!open_archive_heap_region_mapped()) {
 393     return; // nothing to do
 394   }
 395   assert(!DumpSharedSpaces, "Should not be called with DumpSharedSpaces");
 396 
 397   unsigned int hash = primitive_hash<Klass*>(k);
 398   ArchivedKlassSubGraphInfoRecord* record = _run_time_subgraph_info_table.lookup(k, hash, 0);
 399 
 400   // Initialize from archived data. Currently this is done only
 401   // during VM initialization time. No lock is needed.
 402   if (record != NULL) {
 403     Thread* THREAD = Thread::current();
 404     if (log_is_enabled(Info, cds, heap)) {
 405       ResourceMark rm;
 406       log_info(cds, heap)("initialize_from_archived_subgraph " PTR_FORMAT " %s", p2i(k),
 407                           k->external_name());
 408     }
 409 
 410     int i;
 411     // Load/link/initialize the klasses of the objects in the subgraph.
 412     // NULL class loader is used.
 413     Array<Klass*>* klasses = record->subgraph_object_klasses();
 414     if (klasses != NULL) {
 415       for (i = 0; i < klasses->length(); i++) {
 416         Klass* obj_k = klasses->at(i);
 417         Klass* resolved_k = SystemDictionary::resolve_or_null(
 418                                               (obj_k)->name(), THREAD);
 419         if (resolved_k != obj_k) {
 420           return;
 421         }
 422         if ((obj_k)->is_instance_klass()) {
 423           InstanceKlass* ik = InstanceKlass::cast(obj_k);
 424           ik->initialize(THREAD);
 425         } else if ((obj_k)->is_objArray_klass()) {
 426           ObjArrayKlass* oak = ObjArrayKlass::cast(obj_k);
 427           oak->initialize(THREAD);
 428         }
 429       }
 430     }
 431 
 432     if (HAS_PENDING_EXCEPTION) {
 433       CLEAR_PENDING_EXCEPTION;
 434       // None of the field value will be set if there was an exception.
 435       // The java code will not see any of the archived objects in the
 436       // subgraphs referenced from k in this case.
 437       return;
 438     }
 439 
 440     // Load the subgraph entry fields from the record and store them back to
 441     // the corresponding fields within the mirror.
 442     oop m = k->java_mirror();
 443     Array<juint>* entry_field_records = record->entry_field_records();
 444     if (entry_field_records != NULL) {
 445       int efr_len = entry_field_records->length();
 446       assert(efr_len % 2 == 0, "sanity");
 447       for (i = 0; i < efr_len;) {
 448         int field_offset = entry_field_records->at(i);
 449         // The object refereced by the field becomes 'known' by GC from this
 450         // point. All objects in the subgraph reachable from the object are
 451         // also 'known' by GC.
 452         oop v = materialize_archived_object(entry_field_records->at(i+1));
 453         m->obj_field_put(field_offset, v);
 454         i += 2;
 455 
 456         log_debug(cds, heap)("  " PTR_FORMAT " init field @ %2d = " PTR_FORMAT, p2i(k), field_offset, p2i(v));
 457       }
 458 
 459     // Done. Java code can see the archived sub-graphs referenced from k's
 460     // mirror after this point.
 461     }
 462   }
 463 }
 464 
 465 class WalkOopAndArchiveClosure: public BasicOopIterateClosure {
 466   int _level;
 467   bool _record_klasses_only;
 468   KlassSubGraphInfo* _subgraph_info;
 469   oop _orig_referencing_obj;
 470   oop _archived_referencing_obj;
 471   Thread* _thread;
 472  public:
 473   WalkOopAndArchiveClosure(int level, bool record_klasses_only,
 474                            KlassSubGraphInfo* subgraph_info,
 475                            oop orig, oop archived, TRAPS) :
 476     _level(level), _record_klasses_only(record_klasses_only),
 477     _subgraph_info(subgraph_info),
 478     _orig_referencing_obj(orig), _archived_referencing_obj(archived),
 479     _thread(THREAD) {}
 480   void do_oop(narrowOop *p) { WalkOopAndArchiveClosure::do_oop_work(p); }
 481   void do_oop(      oop *p) { WalkOopAndArchiveClosure::do_oop_work(p); }
 482 
 483  protected:
 484   template <class T> void do_oop_work(T *p) {
 485     oop obj = RawAccess<>::oop_load(p);
 486     if (!CompressedOops::is_null(obj)) {
 487       assert(!HeapShared::is_archived_object(obj),
 488              "original objects must not point to archived objects");
 489 
 490       size_t field_delta = pointer_delta(p, _orig_referencing_obj, sizeof(char));
 491       T* new_p = (T*)(address(_archived_referencing_obj) + field_delta);
 492       Thread* THREAD = _thread;
 493 
 494       if (!_record_klasses_only && log_is_enabled(Debug, cds, heap)) {
 495         ResourceMark rm;
 496         log_debug(cds, heap)("(%d) %s[" SIZE_FORMAT "] ==> " PTR_FORMAT " size %d %s", _level,
 497                              _orig_referencing_obj->klass()->external_name(), field_delta,
 498                              p2i(obj), obj->size() * HeapWordSize, obj->klass()->external_name());
 499         LogTarget(Trace, cds, heap) log;
 500         LogStream out(log);
 501         obj->print_on(&out);
 502       }
 503 
 504       oop archived = HeapShared::archive_reachable_objects_from(_level + 1, _subgraph_info, obj, THREAD);
 505       assert(archived != NULL, "VM should have exited with unarchivable objects for _level > 1");
 506       assert(HeapShared::is_archived_object(archived), "must be");
 507 
 508       if (!_record_klasses_only) {
 509         // Update the reference in the archived copy of the referencing object.
 510         log_debug(cds, heap)("(%d) updating oop @[" PTR_FORMAT "] " PTR_FORMAT " ==> " PTR_FORMAT,
 511                              _level, p2i(new_p), p2i(obj), p2i(archived));
 512         RawAccess<IS_NOT_NULL>::oop_store(new_p, archived);
 513       }
 514     }
 515   }
 516 };
 517 
 518 // (1) If orig_obj has not been archived yet, archive it.
 519 // (2) If orig_obj has not been seen yet (since start_recording_subgraph() was called),
 520 //     trace all  objects that are reachable from it, and make sure these objects are archived.
 521 // (3) Record the klasses of all orig_obj and all reachable objects.
 522 oop HeapShared::archive_reachable_objects_from(int level, KlassSubGraphInfo* subgraph_info, oop orig_obj, TRAPS) {
 523   assert(orig_obj != NULL, "must be");
 524   assert(!is_archived_object(orig_obj), "sanity");
 525 
 526   // java.lang.Class instances cannot be included in an archived
 527   // object sub-graph.
 528   if (java_lang_Class::is_instance(orig_obj)) {
 529     log_error(cds, heap)("(%d) Unknown java.lang.Class object is in the archived sub-graph", level);
 530     vm_exit(1);
 531   }
 532 
 533   oop archived_obj = find_archived_heap_object(orig_obj);
 534   if (java_lang_String::is_instance(orig_obj) && archived_obj != NULL) {
 535     // To save time, don't walk strings that are already archived. They just contain
 536     // pointers to a type array, whose klass doesn't need to be recorded.
 537     return archived_obj;
 538   }
 539 
 540   if (has_been_seen_during_subgraph_recording(orig_obj)) {
 541     // orig_obj has already been archived and traced. Nothing more to do.
 542     return archived_obj;
 543   } else {
 544     set_has_been_seen_during_subgraph_recording(orig_obj);
 545   }
 546 
 547   bool record_klasses_only = (archived_obj != NULL);
 548   if (archived_obj == NULL) {
 549     ++_num_new_archived_objs;
 550     archived_obj = archive_heap_object(orig_obj, THREAD);
 551     if (archived_obj == NULL) {
 552       // Skip archiving the sub-graph referenced from the current entry field.
 553       ResourceMark rm;
 554       log_error(cds, heap)(
 555         "Cannot archive the sub-graph referenced from %s object ("
 556         PTR_FORMAT ") size %d, skipped.",
 557         orig_obj->klass()->external_name(), p2i(orig_obj), orig_obj->size() * HeapWordSize);
 558       if (level == 1) {
 559         // Don't archive a subgraph root that's too big. For archives static fields, that's OK
 560         // as the Java code will take care of initializing this field dynamically.
 561         return NULL;
 562       } else {
 563         // We don't know how to handle an object that has been archived, but some of its reachable
 564         // objects cannot be archived. Bail out for now. We might need to fix this in the future if
 565         // we have a real use case.
 566         vm_exit(1);
 567       }
 568     }
 569   }
 570 
 571   assert(archived_obj != NULL, "must be");
 572   Klass *orig_k = orig_obj->klass();
 573   Klass *relocated_k = archived_obj->klass();
 574   subgraph_info->add_subgraph_object_klass(orig_k, relocated_k);
 575 
 576   WalkOopAndArchiveClosure walker(level, record_klasses_only, subgraph_info, orig_obj, archived_obj, THREAD);
 577   orig_obj->oop_iterate(&walker);
 578   return archived_obj;
 579 }
 580 
 581 //
 582 // Start from the given static field in a java mirror and archive the
 583 // complete sub-graph of java heap objects that are reached directly
 584 // or indirectly from the starting object by following references.
 585 // Sub-graph archiving restrictions (current):
 586 //
 587 // - All classes of objects in the archived sub-graph (including the
 588 //   entry class) must be boot class only.
 589 // - No java.lang.Class instance (java mirror) can be included inside
 590 //   an archived sub-graph. Mirror can only be the sub-graph entry object.
 591 //
 592 // The Java heap object sub-graph archiving process (see
 593 // WalkOopAndArchiveClosure):
 594 //
 595 // 1) Java object sub-graph archiving starts from a given static field
 596 // within a Class instance (java mirror). If the static field is a
 597 // refererence field and points to a non-null java object, proceed to
 598 // the next step.
 599 //
 600 // 2) Archives the referenced java object. If an archived copy of the
 601 // current object already exists, updates the pointer in the archived
 602 // copy of the referencing object to point to the current archived object.
 603 // Otherwise, proceed to the next step.
 604 //
 605 // 3) Follows all references within the current java object and recursively
 606 // archive the sub-graph of objects starting from each reference.
 607 //
 608 // 4) Updates the pointer in the archived copy of referencing object to
 609 // point to the current archived object.
 610 //
 611 // 5) The Klass of the current java object is added to the list of Klasses
 612 // for loading and initialzing before any object in the archived graph can
 613 // be accessed at runtime.
 614 //
 615 void HeapShared::archive_reachable_objects_from_static_field(InstanceKlass *k,
 616                                                              const char* klass_name,
 617                                                              int field_offset,
 618                                                              const char* field_name,
 619                                                              TRAPS) {
 620   assert(DumpSharedSpaces, "dump time only");
 621   assert(k->is_shared_boot_class(), "must be boot class");
 622 
 623   oop m = k->java_mirror();
 624   oop archived_m = find_archived_heap_object(m);
 625   if (CompressedOops::is_null(archived_m)) {
 626     return;
 627   }
 628 
 629   KlassSubGraphInfo* subgraph_info = get_subgraph_info(k);
 630   oop f = m->obj_field(field_offset);
 631 
 632   log_debug(cds, heap)("Start archiving from: %s::%s (" PTR_FORMAT ")", klass_name, field_name, p2i(f));
 633 
 634   if (!CompressedOops::is_null(f)) {
 635     if (log_is_enabled(Trace, cds, heap)) {
 636       LogTarget(Trace, cds, heap) log;
 637       LogStream out(log);
 638       f->print_on(&out);
 639     }
 640 
 641     oop af = archive_reachable_objects_from(1, subgraph_info, f, CHECK);
 642 
 643     if (af == NULL) {
 644       log_error(cds, heap)("Archiving failed %s::%s (some reachable objects cannot be archived)",
 645                            klass_name, field_name);
 646     } else {
 647       // Note: the field value is not preserved in the archived mirror.
 648       // Record the field as a new subGraph entry point. The recorded
 649       // information is restored from the archive at runtime.
 650       subgraph_info->add_subgraph_entry_field(field_offset, af);
 651       log_info(cds, heap)("Archived field %s::%s => " PTR_FORMAT, klass_name, field_name, p2i(af));
 652     }
 653   } else {
 654     // The field contains null, we still need to record the entry point,
 655     // so it can be restored at runtime.
 656     subgraph_info->add_subgraph_entry_field(field_offset, NULL);
 657   }
 658 }
 659 
 660 #ifndef PRODUCT
 661 class VerifySharedOopClosure: public BasicOopIterateClosure {
 662  private:
 663   bool _is_archived;
 664 
 665  public:
 666   VerifySharedOopClosure(bool is_archived) : _is_archived(is_archived) {}
 667 
 668   void do_oop(narrowOop *p) { VerifySharedOopClosure::do_oop_work(p); }
 669   void do_oop(      oop *p) { VerifySharedOopClosure::do_oop_work(p); }
 670 
 671  protected:
 672   template <class T> void do_oop_work(T *p) {
 673     oop obj = RawAccess<>::oop_load(p);
 674     if (!CompressedOops::is_null(obj)) {
 675       HeapShared::verify_reachable_objects_from(obj, _is_archived);
 676     }
 677   }
 678 };
 679 
 680 void HeapShared::verify_subgraph_from_static_field(InstanceKlass* k, int field_offset) {
 681   assert(DumpSharedSpaces, "dump time only");
 682   assert(k->is_shared_boot_class(), "must be boot class");
 683 
 684   oop m = k->java_mirror();
 685   oop archived_m = find_archived_heap_object(m);
 686   if (CompressedOops::is_null(archived_m)) {
 687     return;
 688   }
 689   oop f = m->obj_field(field_offset);
 690   if (!CompressedOops::is_null(f)) {
 691     verify_subgraph_from(f);
 692   }
 693 }
 694 
 695 void HeapShared::verify_subgraph_from(oop orig_obj) {
 696   oop archived_obj = find_archived_heap_object(orig_obj);
 697   if (archived_obj == NULL) {
 698     // It's OK for the root of a subgraph to be not archived. See comments in
 699     // archive_reachable_objects_from().
 700     return;
 701   }
 702 
 703   // Verify that all objects reachable from orig_obj are archived.
 704   init_seen_objects_table();
 705   verify_reachable_objects_from(orig_obj, false);
 706   delete_seen_objects_table();
 707 
 708   // Note: we could also verify that all objects reachable from the archived
 709   // copy of orig_obj can only point to archived objects, with:
 710   //      init_seen_objects_table();
 711   //      verify_reachable_objects_from(archived_obj, true);
 712   //      init_seen_objects_table();
 713   // but that's already done in G1HeapVerifier::verify_archive_regions so we
 714   // won't do it here.
 715 }
 716 
 717 void HeapShared::verify_reachable_objects_from(oop obj, bool is_archived) {
 718   _num_total_verifications ++;
 719   if (!has_been_seen_during_subgraph_recording(obj)) {
 720     set_has_been_seen_during_subgraph_recording(obj);
 721 
 722     if (is_archived) {
 723       assert(is_archived_object(obj), "must be");
 724       assert(find_archived_heap_object(obj) == NULL, "must be");
 725     } else {
 726       assert(!is_archived_object(obj), "must be");
 727       assert(find_archived_heap_object(obj) != NULL, "must be");
 728     }
 729 
 730     VerifySharedOopClosure walker(is_archived);
 731     obj->oop_iterate(&walker);
 732   }
 733 }
 734 #endif
 735 
 736 HeapShared::SeenObjectsTable* HeapShared::_seen_objects_table = NULL;
 737 int HeapShared::_num_new_walked_objs;
 738 int HeapShared::_num_new_archived_objs;
 739 int HeapShared::_num_old_recorded_klasses;
 740 
 741 int HeapShared::_num_total_subgraph_recordings = 0;
 742 int HeapShared::_num_total_walked_objs = 0;
 743 int HeapShared::_num_total_archived_objs = 0;
 744 int HeapShared::_num_total_recorded_klasses = 0;
 745 int HeapShared::_num_total_verifications = 0;
 746 
 747 bool HeapShared::has_been_seen_during_subgraph_recording(oop obj) {
 748   return _seen_objects_table->get(obj) != NULL;
 749 }
 750 
 751 void HeapShared::set_has_been_seen_during_subgraph_recording(oop obj) {
 752   assert(!has_been_seen_during_subgraph_recording(obj), "sanity");
 753   _seen_objects_table->put(obj, true);
 754   ++ _num_new_walked_objs;
 755 }
 756 
 757 void HeapShared::start_recording_subgraph(InstanceKlass *k, const char* class_name) {
 758   log_info(cds, heap)("Start recording subgraph(s) for archived fields in %s", class_name);
 759   init_seen_objects_table();
 760   _num_new_walked_objs = 0;
 761   _num_new_archived_objs = 0;
 762   _num_old_recorded_klasses = get_subgraph_info(k)->num_subgraph_object_klasses();
 763 }
 764 
 765 void HeapShared::done_recording_subgraph(InstanceKlass *k, const char* class_name) {
 766   int num_new_recorded_klasses = get_subgraph_info(k)->num_subgraph_object_klasses() -
 767     _num_old_recorded_klasses;
 768   log_info(cds, heap)("Done recording subgraph(s) for archived fields in %s: "
 769                       "walked %d objs, archived %d new objs, recorded %d classes",
 770                       class_name, _num_new_walked_objs, _num_new_archived_objs,
 771                       num_new_recorded_klasses);
 772 
 773   delete_seen_objects_table();
 774 
 775   _num_total_subgraph_recordings ++;
 776   _num_total_walked_objs      += _num_new_walked_objs;
 777   _num_total_archived_objs    += _num_new_archived_objs;
 778   _num_total_recorded_klasses +=  num_new_recorded_klasses;
 779 }
 780 
 781 struct ArchivableStaticFieldInfo {
 782   const char* klass_name;
 783   const char* field_name;
 784   InstanceKlass* klass;
 785   int offset;
 786   BasicType type;
 787 };
 788 
 789 // If you add new entries to this table, you should know what you're doing!
 790 static ArchivableStaticFieldInfo archivable_static_fields[] = {
 791   {"jdk/internal/module/ArchivedModuleGraph",  "archivedSystemModules"},
 792   {"jdk/internal/module/ArchivedModuleGraph",  "archivedModuleFinder"},
 793   {"jdk/internal/module/ArchivedModuleGraph",  "archivedMainModule"},
 794   {"jdk/internal/module/ArchivedModuleGraph",  "archivedConfiguration"},
 795   {"java/util/ImmutableCollections$ListN",     "EMPTY_LIST"},
 796   {"java/util/ImmutableCollections$MapN",      "EMPTY_MAP"},
 797   {"java/util/ImmutableCollections$SetN",      "EMPTY_SET"},
 798   {"java/lang/Integer$IntegerCache",           "archivedCache"},
 799   {"java/lang/module/Configuration",           "EMPTY_CONFIGURATION"},
 800 };
 801 
 802 const static int num_archivable_static_fields =
 803   sizeof(archivable_static_fields) / sizeof(ArchivableStaticFieldInfo);
 804 
 805 class ArchivableStaticFieldFinder: public FieldClosure {
 806   InstanceKlass* _ik;
 807   Symbol* _field_name;
 808   bool _found;
 809   int _offset;
 810 public:
 811   ArchivableStaticFieldFinder(InstanceKlass* ik, Symbol* field_name) :
 812     _ik(ik), _field_name(field_name), _found(false), _offset(-1) {}
 813 
 814   virtual void do_field(fieldDescriptor* fd) {
 815     if (fd->name() == _field_name) {
 816       assert(!_found, "fields cannot be overloaded");
 817       assert(fd->field_type() == T_OBJECT || fd->field_type() == T_ARRAY, "can archive only obj or array fields");
 818       _found = true;
 819       _offset = fd->offset();
 820     }
 821   }
 822   bool found()     { return _found;  }
 823   int offset()     { return _offset; }
 824 };
 825 
 826 void HeapShared::init_archivable_static_fields(Thread* THREAD) {
 827   _dump_time_subgraph_info_table = new (ResourceObj::C_HEAP, mtClass)DumpTimeKlassSubGraphInfoTable();
 828 
 829   for (int i = 0; i < num_archivable_static_fields; i++) {
 830     ArchivableStaticFieldInfo* info = &archivable_static_fields[i];
 831     TempNewSymbol klass_name =  SymbolTable::new_symbol(info->klass_name, THREAD);
 832     TempNewSymbol field_name =  SymbolTable::new_symbol(info->field_name, THREAD);
 833 
 834     Klass* k = SystemDictionary::resolve_or_null(klass_name, THREAD);
 835     assert(k != NULL && !HAS_PENDING_EXCEPTION, "class must exist");
 836     InstanceKlass* ik = InstanceKlass::cast(k);
 837 
 838     ArchivableStaticFieldFinder finder(ik, field_name);
 839     ik->do_local_static_fields(&finder);
 840     assert(finder.found(), "field must exist");
 841 
 842     info->klass = ik;
 843     info->offset = finder.offset();
 844   }
 845 }
 846 
 847 void HeapShared::archive_object_subgraphs(Thread* THREAD) {
 848   // For each class X that has one or more archived fields:
 849   // [1] Dump the subgraph of each archived field
 850   // [2] Create a list of all the class of the objects that can be reached
 851   //     by any of these static fields.
 852   //     At runtime, these classes are initialized before X's archived fields
 853   //     are restored by HeapShared::initialize_from_archived_subgraph().
 854   int i;
 855   for (i = 0; i < num_archivable_static_fields; ) {
 856     ArchivableStaticFieldInfo* info = &archivable_static_fields[i];
 857     const char* klass_name = info->klass_name;
 858     start_recording_subgraph(info->klass, klass_name);
 859 
 860     // If you have specified consecutive fields of the same klass in
 861     // archivable_static_fields[], these will be archived in the same
 862     // {start_recording_subgraph ... done_recording_subgraph} pass to
 863     // save time.
 864     for (; i < num_archivable_static_fields; i++) {
 865       ArchivableStaticFieldInfo* f = &archivable_static_fields[i];
 866       if (f->klass_name != klass_name) {
 867         break;
 868       }
 869       archive_reachable_objects_from_static_field(f->klass, f->klass_name,
 870                                                   f->offset, f->field_name, CHECK);
 871     }
 872     done_recording_subgraph(info->klass, klass_name);
 873   }
 874 
 875   log_info(cds, heap)("Performed subgraph records = %d times", _num_total_subgraph_recordings);
 876   log_info(cds, heap)("Walked %d objects", _num_total_walked_objs);
 877   log_info(cds, heap)("Archived %d objects", _num_total_archived_objs);
 878   log_info(cds, heap)("Recorded %d klasses", _num_total_recorded_klasses);
 879 
 880 
 881 #ifndef PRODUCT
 882   for (int i = 0; i < num_archivable_static_fields; i++) {
 883     ArchivableStaticFieldInfo* f = &archivable_static_fields[i];
 884     verify_subgraph_from_static_field(f->klass, f->offset);
 885   }
 886   log_info(cds, heap)("Verified %d references", _num_total_verifications);
 887 #endif
 888 }
 889 
 890 // At dump-time, find the location of all the non-null oop pointers in an archived heap
 891 // region. This way we can quickly relocate all the pointers without using
 892 // BasicOopIterateClosure at runtime.
 893 class FindEmbeddedNonNullPointers: public BasicOopIterateClosure {
 894   narrowOop* _start;
 895   BitMap *_oopmap;
 896   int _num_total_oops;
 897   int _num_null_oops;
 898  public:
 899   FindEmbeddedNonNullPointers(narrowOop* start, BitMap* oopmap)
 900     : _start(start), _oopmap(oopmap), _num_total_oops(0),  _num_null_oops(0) {}
 901 
 902   virtual bool should_verify_oops(void) {
 903     return false;
 904   }
 905   virtual void do_oop(narrowOop* p) {
 906     _num_total_oops ++;
 907     narrowOop v = *p;
 908     if (!CompressedOops::is_null(v)) {
 909       size_t idx = p - _start;
 910       _oopmap->set_bit(idx);
 911     } else {
 912       _num_null_oops ++;
 913     }
 914   }
 915   virtual void do_oop(oop *p) {
 916     ShouldNotReachHere();
 917   }
 918   int num_total_oops() const { return _num_total_oops; }
 919   int num_null_oops()  const { return _num_null_oops; }
 920 };
 921 
 922 ResourceBitMap HeapShared::calculate_oopmap(MemRegion region) {
 923   assert(UseCompressedOops, "must be");
 924   size_t num_bits = region.byte_size() / sizeof(narrowOop);
 925   ResourceBitMap oopmap(num_bits);
 926 
 927   HeapWord* p   = region.start();
 928   HeapWord* end = region.end();
 929   FindEmbeddedNonNullPointers finder((narrowOop*)p, &oopmap);
 930 
 931   int num_objs = 0;
 932   while (p < end) {
 933     oop o = (oop)p;
 934     o->oop_iterate(&finder);
 935     p += o->size();
 936     ++ num_objs;
 937   }
 938 
 939   log_info(cds, heap)("calculate_oopmap: objects = %6d, embedded oops = %7d, nulls = %7d",
 940                       num_objs, finder.num_total_oops(), finder.num_null_oops());
 941   return oopmap;
 942 }
 943 
 944 // Patch all the embedded oop pointers inside an archived heap region,
 945 // to be consistent with the runtime oop encoding.
 946 class PatchEmbeddedPointers: public BitMapClosure {
 947   narrowOop* _start;
 948 
 949  public:
 950   PatchEmbeddedPointers(narrowOop* start) : _start(start) {}
 951 
 952   bool do_bit(size_t offset) {
 953     narrowOop* p = _start + offset;
 954     narrowOop v = *p;
 955     assert(!CompressedOops::is_null(v), "null oops should have been filtered out at dump time");
 956     oop o = HeapShared::decode_from_archive(v);
 957     RawAccess<IS_NOT_NULL>::oop_store(p, o);
 958     return true;
 959   }
 960 };
 961 
 962 void HeapShared::patch_archived_heap_embedded_pointers(MemRegion region, address oopmap,
 963                                                        size_t oopmap_size_in_bits) {
 964   BitMapView bm((BitMap::bm_word_t*)oopmap, oopmap_size_in_bits);
 965 
 966 #ifndef PRODUCT
 967   ResourceMark rm;
 968   ResourceBitMap checkBm = calculate_oopmap(region);
 969   assert(bm.is_same(checkBm), "sanity");
 970 #endif
 971 
 972   PatchEmbeddedPointers patcher((narrowOop*)region.start());
 973   bm.iterate(&patcher);
 974 }
 975 
 976 #endif // INCLUDE_CDS_JAVA_HEAP