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