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