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