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