1 /* 2 * Copyright (c) 2018, 2024, 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 "cds/archiveBuilder.hpp" 27 #include "cds/archiveHeapLoader.hpp" 28 #include "cds/archiveHeapWriter.hpp" 29 #include "cds/archiveUtils.hpp" 30 #include "cds/cdsConfig.hpp" 31 #include "cds/cdsEnumKlass.hpp" 32 #include "cds/cdsHeapVerifier.hpp" 33 #include "cds/heapShared.hpp" 34 #include "cds/metaspaceShared.hpp" 35 #include "classfile/classLoaderData.hpp" 36 #include "classfile/classLoaderExt.hpp" 37 #include "classfile/javaClasses.inline.hpp" 38 #include "classfile/modules.hpp" 39 #include "classfile/stringTable.hpp" 40 #include "classfile/symbolTable.hpp" 41 #include "classfile/systemDictionary.hpp" 42 #include "classfile/systemDictionaryShared.hpp" 43 #include "classfile/vmClasses.hpp" 44 #include "classfile/vmSymbols.hpp" 45 #include "gc/shared/collectedHeap.hpp" 46 #include "gc/shared/gcLocker.hpp" 47 #include "gc/shared/gcVMOperations.hpp" 48 #include "logging/log.hpp" 49 #include "logging/logStream.hpp" 50 #include "memory/iterator.inline.hpp" 51 #include "memory/resourceArea.hpp" 52 #include "memory/universe.hpp" 53 #include "oops/compressedOops.inline.hpp" 54 #include "oops/fieldStreams.inline.hpp" 55 #include "oops/objArrayOop.inline.hpp" 56 #include "oops/oop.inline.hpp" 57 #include "oops/typeArrayOop.inline.hpp" 58 #include "prims/jvmtiExport.hpp" 59 #include "runtime/arguments.hpp" 60 #include "runtime/fieldDescriptor.inline.hpp" 61 #include "runtime/init.hpp" 62 #include "runtime/javaCalls.hpp" 63 #include "runtime/mutexLocker.hpp" 64 #include "runtime/safepointVerifiers.hpp" 65 #include "utilities/bitMap.inline.hpp" 66 #include "utilities/copy.hpp" 67 #if INCLUDE_G1GC 68 #include "gc/g1/g1CollectedHeap.hpp" 69 #endif 70 71 #if INCLUDE_CDS_JAVA_HEAP 72 73 struct ArchivableStaticFieldInfo { 74 const char* klass_name; 75 const char* field_name; 76 InstanceKlass* klass; 77 int offset; 78 BasicType type; 79 80 ArchivableStaticFieldInfo(const char* k, const char* f) 81 : klass_name(k), field_name(f), klass(nullptr), offset(0), type(T_ILLEGAL) {} 82 83 bool valid() { 84 return klass_name != nullptr; 85 } 86 }; 87 88 bool HeapShared::_disable_writing = false; 89 DumpedInternedStrings *HeapShared::_dumped_interned_strings = nullptr; 90 91 size_t HeapShared::_alloc_count[HeapShared::ALLOC_STAT_SLOTS]; 92 size_t HeapShared::_alloc_size[HeapShared::ALLOC_STAT_SLOTS]; 93 size_t HeapShared::_total_obj_count; 94 size_t HeapShared::_total_obj_size; 95 96 #ifndef PRODUCT 97 #define ARCHIVE_TEST_FIELD_NAME "archivedObjects" 98 static Array<char>* _archived_ArchiveHeapTestClass = nullptr; 99 static const char* _test_class_name = nullptr; 100 static const Klass* _test_class = nullptr; 101 static const ArchivedKlassSubGraphInfoRecord* _test_class_record = nullptr; 102 #endif 103 104 105 // 106 // If you add new entries to the following tables, you should know what you're doing! 107 // 108 109 static ArchivableStaticFieldInfo archive_subgraph_entry_fields[] = { 110 {"java/lang/Integer$IntegerCache", "archivedCache"}, 111 {"java/lang/Long$LongCache", "archivedCache"}, 112 {"java/lang/Byte$ByteCache", "archivedCache"}, 113 {"java/lang/Short$ShortCache", "archivedCache"}, 114 {"java/lang/Character$CharacterCache", "archivedCache"}, 115 {"java/util/jar/Attributes$Name", "KNOWN_NAMES"}, 116 {"sun/util/locale/BaseLocale", "constantBaseLocales"}, 117 {"jdk/internal/module/ArchivedModuleGraph", "archivedModuleGraph"}, 118 {"java/util/ImmutableCollections", "archivedObjects"}, 119 {"java/lang/ModuleLayer", "EMPTY_LAYER"}, 120 {"java/lang/module/Configuration", "EMPTY_CONFIGURATION"}, 121 {"jdk/internal/math/FDBigInteger", "archivedCaches"}, 122 #ifndef PRODUCT 123 {nullptr, nullptr}, // Extra slot for -XX:ArchiveHeapTestClass 124 #endif 125 {nullptr, nullptr}, 126 }; 127 128 // full module graph 129 static ArchivableStaticFieldInfo fmg_archive_subgraph_entry_fields[] = { 130 {"jdk/internal/loader/ArchivedClassLoaders", "archivedClassLoaders"}, 131 {ARCHIVED_BOOT_LAYER_CLASS, ARCHIVED_BOOT_LAYER_FIELD}, 132 {"java/lang/Module$ArchivedData", "archivedData"}, 133 {nullptr, nullptr}, 134 }; 135 136 KlassSubGraphInfo* HeapShared::_default_subgraph_info; 137 GrowableArrayCHeap<oop, mtClassShared>* HeapShared::_pending_roots = nullptr; 138 GrowableArrayCHeap<OopHandle, mtClassShared>* HeapShared::_root_segments; 139 int HeapShared::_root_segment_max_size_elems; 140 OopHandle HeapShared::_scratch_basic_type_mirrors[T_VOID+1]; 141 MetaspaceObjToOopHandleTable* HeapShared::_scratch_java_mirror_table = nullptr; 142 MetaspaceObjToOopHandleTable* HeapShared::_scratch_references_table = nullptr; 143 144 static bool is_subgraph_root_class_of(ArchivableStaticFieldInfo fields[], InstanceKlass* ik) { 145 for (int i = 0; fields[i].valid(); i++) { 146 if (fields[i].klass == ik) { 147 return true; 148 } 149 } 150 return false; 151 } 152 153 bool HeapShared::is_subgraph_root_class(InstanceKlass* ik) { 154 return is_subgraph_root_class_of(archive_subgraph_entry_fields, ik) || 155 is_subgraph_root_class_of(fmg_archive_subgraph_entry_fields, ik); 156 } 157 158 unsigned HeapShared::oop_hash(oop const& p) { 159 // Do not call p->identity_hash() as that will update the 160 // object header. 161 return primitive_hash(cast_from_oop<intptr_t>(p)); 162 } 163 164 static void reset_states(oop obj, TRAPS) { 165 Handle h_obj(THREAD, obj); 166 InstanceKlass* klass = InstanceKlass::cast(obj->klass()); 167 TempNewSymbol method_name = SymbolTable::new_symbol("resetArchivedStates"); 168 Symbol* method_sig = vmSymbols::void_method_signature(); 169 170 while (klass != nullptr) { 171 Method* method = klass->find_method(method_name, method_sig); 172 if (method != nullptr) { 173 assert(method->is_private(), "must be"); 174 if (log_is_enabled(Debug, cds)) { 175 ResourceMark rm(THREAD); 176 log_debug(cds)(" calling %s", method->name_and_sig_as_C_string()); 177 } 178 JavaValue result(T_VOID); 179 JavaCalls::call_special(&result, h_obj, klass, 180 method_name, method_sig, CHECK); 181 } 182 klass = klass->java_super(); 183 } 184 } 185 186 void HeapShared::reset_archived_object_states(TRAPS) { 187 assert(CDSConfig::is_dumping_heap(), "dump-time only"); 188 log_debug(cds)("Resetting platform loader"); 189 reset_states(SystemDictionary::java_platform_loader(), CHECK); 190 log_debug(cds)("Resetting system loader"); 191 reset_states(SystemDictionary::java_system_loader(), CHECK); 192 193 // Clean up jdk.internal.loader.ClassLoaders::bootLoader(), which is not 194 // directly used for class loading, but rather is used by the core library 195 // to keep track of resources, etc, loaded by the null class loader. 196 // 197 // Note, this object is non-null, and is not the same as 198 // ClassLoaderData::the_null_class_loader_data()->class_loader(), 199 // which is null. 200 log_debug(cds)("Resetting boot loader"); 201 JavaValue result(T_OBJECT); 202 JavaCalls::call_static(&result, 203 vmClasses::jdk_internal_loader_ClassLoaders_klass(), 204 vmSymbols::bootLoader_name(), 205 vmSymbols::void_BuiltinClassLoader_signature(), 206 CHECK); 207 Handle boot_loader(THREAD, result.get_oop()); 208 reset_states(boot_loader(), CHECK); 209 } 210 211 HeapShared::ArchivedObjectCache* HeapShared::_archived_object_cache = nullptr; 212 213 bool HeapShared::has_been_archived(oop obj) { 214 assert(CDSConfig::is_dumping_heap(), "dump-time only"); 215 return archived_object_cache()->get(obj) != nullptr; 216 } 217 218 int HeapShared::append_root(oop obj) { 219 assert(CDSConfig::is_dumping_heap(), "dump-time only"); 220 221 // No GC should happen since we aren't scanning _pending_roots. 222 assert(Thread::current() == (Thread*)VMThread::vm_thread(), "should be in vm thread"); 223 224 if (_pending_roots == nullptr) { 225 _pending_roots = new GrowableArrayCHeap<oop, mtClassShared>(500); 226 } 227 228 return _pending_roots->append(obj); 229 } 230 231 objArrayOop HeapShared::root_segment(int segment_idx) { 232 if (CDSConfig::is_dumping_heap()) { 233 assert(Thread::current() == (Thread*)VMThread::vm_thread(), "should be in vm thread"); 234 if (!HeapShared::can_write()) { 235 return nullptr; 236 } 237 } else { 238 assert(CDSConfig::is_using_archive(), "must be"); 239 } 240 241 objArrayOop segment = (objArrayOop)_root_segments->at(segment_idx).resolve(); 242 assert(segment != nullptr, "should have been initialized"); 243 return segment; 244 } 245 246 void HeapShared::get_segment_indexes(int idx, int& seg_idx, int& int_idx) { 247 assert(_root_segment_max_size_elems > 0, "sanity"); 248 249 // Try to avoid divisions for the common case. 250 if (idx < _root_segment_max_size_elems) { 251 seg_idx = 0; 252 int_idx = idx; 253 } else { 254 seg_idx = idx / _root_segment_max_size_elems; 255 int_idx = idx % _root_segment_max_size_elems; 256 } 257 258 assert(idx == seg_idx * _root_segment_max_size_elems + int_idx, 259 "sanity: %d index maps to %d segment and %d internal", idx, seg_idx, int_idx); 260 } 261 262 // Returns an objArray that contains all the roots of the archived objects 263 oop HeapShared::get_root(int index, bool clear) { 264 assert(index >= 0, "sanity"); 265 assert(!CDSConfig::is_dumping_heap() && CDSConfig::is_using_archive(), "runtime only"); 266 assert(!_root_segments->is_empty(), "must have loaded shared heap"); 267 int seg_idx, int_idx; 268 get_segment_indexes(index, seg_idx, int_idx); 269 oop result = root_segment(seg_idx)->obj_at(int_idx); 270 if (clear) { 271 clear_root(index); 272 } 273 return result; 274 } 275 276 void HeapShared::clear_root(int index) { 277 assert(index >= 0, "sanity"); 278 assert(CDSConfig::is_using_archive(), "must be"); 279 if (ArchiveHeapLoader::is_in_use()) { 280 int seg_idx, int_idx; 281 get_segment_indexes(index, seg_idx, int_idx); 282 if (log_is_enabled(Debug, cds, heap)) { 283 oop old = root_segment(seg_idx)->obj_at(int_idx); 284 log_debug(cds, heap)("Clearing root %d: was " PTR_FORMAT, index, p2i(old)); 285 } 286 root_segment(seg_idx)->obj_at_put(int_idx, nullptr); 287 } 288 } 289 290 bool HeapShared::archive_object(oop obj) { 291 assert(CDSConfig::is_dumping_heap(), "dump-time only"); 292 293 assert(!obj->is_stackChunk(), "do not archive stack chunks"); 294 if (has_been_archived(obj)) { 295 return true; 296 } 297 298 if (ArchiveHeapWriter::is_too_large_to_archive(obj->size())) { 299 log_debug(cds, heap)("Cannot archive, object (" PTR_FORMAT ") is too large: " SIZE_FORMAT, 300 p2i(obj), obj->size()); 301 return false; 302 } else { 303 count_allocation(obj->size()); 304 ArchiveHeapWriter::add_source_obj(obj); 305 CachedOopInfo info = make_cached_oop_info(obj); 306 archived_object_cache()->put_when_absent(obj, info); 307 archived_object_cache()->maybe_grow(); 308 mark_native_pointers(obj); 309 310 if (log_is_enabled(Debug, cds, heap)) { 311 ResourceMark rm; 312 log_debug(cds, heap)("Archived heap object " PTR_FORMAT " : %s", 313 p2i(obj), obj->klass()->external_name()); 314 } 315 316 if (java_lang_Module::is_instance(obj) && Modules::check_archived_module_oop(obj)) { 317 Modules::update_oops_in_archived_module(obj, append_root(obj)); 318 } 319 320 return true; 321 } 322 } 323 324 class MetaspaceObjToOopHandleTable: public ResourceHashtable<MetaspaceObj*, OopHandle, 325 36137, // prime number 326 AnyObj::C_HEAP, 327 mtClassShared> { 328 public: 329 oop get_oop(MetaspaceObj* ptr) { 330 MutexLocker ml(ScratchObjects_lock, Mutex::_no_safepoint_check_flag); 331 OopHandle* handle = get(ptr); 332 if (handle != nullptr) { 333 return handle->resolve(); 334 } else { 335 return nullptr; 336 } 337 } 338 void set_oop(MetaspaceObj* ptr, oop o) { 339 MutexLocker ml(ScratchObjects_lock, Mutex::_no_safepoint_check_flag); 340 OopHandle handle(Universe::vm_global(), o); 341 bool is_new = put(ptr, handle); 342 assert(is_new, "cannot set twice"); 343 } 344 void remove_oop(MetaspaceObj* ptr) { 345 MutexLocker ml(ScratchObjects_lock, Mutex::_no_safepoint_check_flag); 346 OopHandle* handle = get(ptr); 347 if (handle != nullptr) { 348 handle->release(Universe::vm_global()); 349 remove(ptr); 350 } 351 } 352 }; 353 354 void HeapShared::add_scratch_resolved_references(ConstantPool* src, objArrayOop dest) { 355 _scratch_references_table->set_oop(src, dest); 356 } 357 358 objArrayOop HeapShared::scratch_resolved_references(ConstantPool* src) { 359 return (objArrayOop)_scratch_references_table->get_oop(src); 360 } 361 362 void HeapShared::init_scratch_objects(TRAPS) { 363 for (int i = T_BOOLEAN; i < T_VOID+1; i++) { 364 BasicType bt = (BasicType)i; 365 if (!is_reference_type(bt)) { 366 oop m = java_lang_Class::create_basic_type_mirror(type2name(bt), bt, CHECK); 367 _scratch_basic_type_mirrors[i] = OopHandle(Universe::vm_global(), m); 368 } 369 } 370 _scratch_java_mirror_table = new (mtClass)MetaspaceObjToOopHandleTable(); 371 _scratch_references_table = new (mtClass)MetaspaceObjToOopHandleTable(); 372 } 373 374 oop HeapShared::scratch_java_mirror(BasicType t) { 375 assert((uint)t < T_VOID+1, "range check"); 376 assert(!is_reference_type(t), "sanity"); 377 return _scratch_basic_type_mirrors[t].resolve(); 378 } 379 380 oop HeapShared::scratch_java_mirror(Klass* k) { 381 return _scratch_java_mirror_table->get_oop(k); 382 } 383 384 void HeapShared::set_scratch_java_mirror(Klass* k, oop mirror) { 385 _scratch_java_mirror_table->set_oop(k, mirror); 386 } 387 388 void HeapShared::remove_scratch_objects(Klass* k) { 389 _scratch_java_mirror_table->remove_oop(k); 390 if (k->is_instance_klass()) { 391 _scratch_references_table->remove(InstanceKlass::cast(k)->constants()); 392 } 393 } 394 395 void HeapShared::archive_java_mirrors() { 396 for (int i = T_BOOLEAN; i < T_VOID+1; i++) { 397 BasicType bt = (BasicType)i; 398 if (!is_reference_type(bt)) { 399 oop m = _scratch_basic_type_mirrors[i].resolve(); 400 assert(m != nullptr, "sanity"); 401 bool success = archive_reachable_objects_from(1, _default_subgraph_info, m); 402 assert(success, "sanity"); 403 404 log_trace(cds, heap, mirror)( 405 "Archived %s mirror object from " PTR_FORMAT, 406 type2name(bt), p2i(m)); 407 408 Universe::set_archived_basic_type_mirror_index(bt, append_root(m)); 409 } 410 } 411 412 GrowableArray<Klass*>* klasses = ArchiveBuilder::current()->klasses(); 413 assert(klasses != nullptr, "sanity"); 414 for (int i = 0; i < klasses->length(); i++) { 415 Klass* orig_k = klasses->at(i); 416 oop m = scratch_java_mirror(orig_k); 417 if (m != nullptr) { 418 Klass* buffered_k = ArchiveBuilder::get_buffered_klass(orig_k); 419 bool success = archive_reachable_objects_from(1, _default_subgraph_info, m); 420 guarantee(success, "scratch mirrors must point to only archivable objects"); 421 buffered_k->set_archived_java_mirror(append_root(m)); 422 ResourceMark rm; 423 log_trace(cds, heap, mirror)( 424 "Archived %s mirror object from " PTR_FORMAT, 425 buffered_k->external_name(), p2i(m)); 426 427 // archive the resolved_referenes array 428 if (buffered_k->is_instance_klass()) { 429 InstanceKlass* ik = InstanceKlass::cast(buffered_k); 430 oop rr = ik->constants()->prepare_resolved_references_for_archiving(); 431 if (rr != nullptr && !ArchiveHeapWriter::is_too_large_to_archive(rr)) { 432 bool success = HeapShared::archive_reachable_objects_from(1, _default_subgraph_info, rr); 433 assert(success, "must be"); 434 int root_index = append_root(rr); 435 ik->constants()->cache()->set_archived_references(root_index); 436 } 437 } 438 } 439 } 440 } 441 442 void HeapShared::archive_strings() { 443 oop shared_strings_array = StringTable::init_shared_table(_dumped_interned_strings); 444 bool success = archive_reachable_objects_from(1, _default_subgraph_info, shared_strings_array); 445 // We must succeed because: 446 // - _dumped_interned_strings do not contain any large strings. 447 // - StringTable::init_shared_table() doesn't create any large arrays. 448 assert(success, "shared strings array must not point to arrays or strings that are too large to archive"); 449 StringTable::set_shared_strings_array_index(append_root(shared_strings_array)); 450 } 451 452 int HeapShared::archive_exception_instance(oop exception) { 453 bool success = archive_reachable_objects_from(1, _default_subgraph_info, exception); 454 assert(success, "sanity"); 455 return append_root(exception); 456 } 457 458 void HeapShared::mark_native_pointers(oop orig_obj) { 459 if (java_lang_Class::is_instance(orig_obj)) { 460 ArchiveHeapWriter::mark_native_pointer(orig_obj, java_lang_Class::klass_offset()); 461 ArchiveHeapWriter::mark_native_pointer(orig_obj, java_lang_Class::array_klass_offset()); 462 } 463 } 464 465 void HeapShared::get_pointer_info(oop src_obj, bool& has_oop_pointers, bool& has_native_pointers) { 466 CachedOopInfo* info = archived_object_cache()->get(src_obj); 467 assert(info != nullptr, "must be"); 468 has_oop_pointers = info->has_oop_pointers(); 469 has_native_pointers = info->has_native_pointers(); 470 } 471 472 void HeapShared::set_has_native_pointers(oop src_obj) { 473 CachedOopInfo* info = archived_object_cache()->get(src_obj); 474 assert(info != nullptr, "must be"); 475 info->set_has_native_pointers(); 476 } 477 478 void HeapShared::archive_objects(ArchiveHeapInfo *heap_info) { 479 { 480 NoSafepointVerifier nsv; 481 482 _default_subgraph_info = init_subgraph_info(vmClasses::Object_klass(), false); 483 484 // Cache for recording where the archived objects are copied to 485 create_archived_object_cache(); 486 487 if (UseCompressedOops || UseG1GC) { 488 log_info(cds)("Heap range = [" PTR_FORMAT " - " PTR_FORMAT "]", 489 UseCompressedOops ? p2i(CompressedOops::begin()) : 490 p2i((address)G1CollectedHeap::heap()->reserved().start()), 491 UseCompressedOops ? p2i(CompressedOops::end()) : 492 p2i((address)G1CollectedHeap::heap()->reserved().end())); 493 } 494 copy_objects(); 495 496 CDSHeapVerifier::verify(); 497 check_default_subgraph_classes(); 498 } 499 500 ArchiveHeapWriter::write(_pending_roots, heap_info); 501 } 502 503 void HeapShared::copy_interned_strings() { 504 init_seen_objects_table(); 505 506 auto copier = [&] (oop s, bool value_ignored) { 507 assert(s != nullptr, "sanity"); 508 assert(!ArchiveHeapWriter::is_string_too_large_to_archive(s), "large strings must have been filtered"); 509 bool success = archive_reachable_objects_from(1, _default_subgraph_info, s); 510 assert(success, "must be"); 511 // Prevent string deduplication from changing the value field to 512 // something not in the archive. 513 java_lang_String::set_deduplication_forbidden(s); 514 }; 515 _dumped_interned_strings->iterate_all(copier); 516 517 delete_seen_objects_table(); 518 } 519 520 void HeapShared::copy_special_objects() { 521 // Archive special objects that do not belong to any subgraphs 522 init_seen_objects_table(); 523 archive_java_mirrors(); 524 archive_strings(); 525 Universe::archive_exception_instances(); 526 delete_seen_objects_table(); 527 } 528 529 void HeapShared::copy_objects() { 530 assert(HeapShared::can_write(), "must be"); 531 532 copy_interned_strings(); 533 copy_special_objects(); 534 535 archive_object_subgraphs(archive_subgraph_entry_fields, 536 false /* is_full_module_graph */); 537 538 if (CDSConfig::is_dumping_full_module_graph()) { 539 archive_object_subgraphs(fmg_archive_subgraph_entry_fields, 540 true /* is_full_module_graph */); 541 Modules::verify_archived_modules(); 542 } 543 } 544 545 // 546 // Subgraph archiving support 547 // 548 HeapShared::DumpTimeKlassSubGraphInfoTable* HeapShared::_dump_time_subgraph_info_table = nullptr; 549 HeapShared::RunTimeKlassSubGraphInfoTable HeapShared::_run_time_subgraph_info_table; 550 551 // Get the subgraph_info for Klass k. A new subgraph_info is created if 552 // there is no existing one for k. The subgraph_info records the "buffered" 553 // address of the class. 554 KlassSubGraphInfo* HeapShared::init_subgraph_info(Klass* k, bool is_full_module_graph) { 555 assert(CDSConfig::is_dumping_heap(), "dump time only"); 556 bool created; 557 Klass* buffered_k = ArchiveBuilder::get_buffered_klass(k); 558 KlassSubGraphInfo* info = 559 _dump_time_subgraph_info_table->put_if_absent(k, KlassSubGraphInfo(buffered_k, is_full_module_graph), 560 &created); 561 assert(created, "must not initialize twice"); 562 return info; 563 } 564 565 KlassSubGraphInfo* HeapShared::get_subgraph_info(Klass* k) { 566 assert(CDSConfig::is_dumping_heap(), "dump time only"); 567 KlassSubGraphInfo* info = _dump_time_subgraph_info_table->get(k); 568 assert(info != nullptr, "must have been initialized"); 569 return info; 570 } 571 572 // Add an entry field to the current KlassSubGraphInfo. 573 void KlassSubGraphInfo::add_subgraph_entry_field(int static_field_offset, oop v) { 574 assert(CDSConfig::is_dumping_heap(), "dump time only"); 575 if (_subgraph_entry_fields == nullptr) { 576 _subgraph_entry_fields = 577 new (mtClass) GrowableArray<int>(10, mtClass); 578 } 579 _subgraph_entry_fields->append(static_field_offset); 580 _subgraph_entry_fields->append(HeapShared::append_root(v)); 581 } 582 583 // Add the Klass* for an object in the current KlassSubGraphInfo's subgraphs. 584 // Only objects of boot classes can be included in sub-graph. 585 void KlassSubGraphInfo::add_subgraph_object_klass(Klass* orig_k) { 586 assert(CDSConfig::is_dumping_heap(), "dump time only"); 587 Klass* buffered_k = ArchiveBuilder::get_buffered_klass(orig_k); 588 589 if (_subgraph_object_klasses == nullptr) { 590 _subgraph_object_klasses = 591 new (mtClass) GrowableArray<Klass*>(50, mtClass); 592 } 593 594 assert(ArchiveBuilder::current()->is_in_buffer_space(buffered_k), "must be a shared class"); 595 596 if (_k == buffered_k) { 597 // Don't add the Klass containing the sub-graph to it's own klass 598 // initialization list. 599 return; 600 } 601 602 if (buffered_k->is_instance_klass()) { 603 assert(InstanceKlass::cast(buffered_k)->is_shared_boot_class(), 604 "must be boot class"); 605 // vmClasses::xxx_klass() are not updated, need to check 606 // the original Klass* 607 if (orig_k == vmClasses::String_klass() || 608 orig_k == vmClasses::Object_klass()) { 609 // Initialized early during VM initialization. No need to be added 610 // to the sub-graph object class list. 611 return; 612 } 613 check_allowed_klass(InstanceKlass::cast(orig_k)); 614 } else if (buffered_k->is_objArray_klass()) { 615 Klass* abk = ObjArrayKlass::cast(buffered_k)->bottom_klass(); 616 if (abk->is_instance_klass()) { 617 assert(InstanceKlass::cast(abk)->is_shared_boot_class(), 618 "must be boot class"); 619 check_allowed_klass(InstanceKlass::cast(ObjArrayKlass::cast(orig_k)->bottom_klass())); 620 } 621 if (buffered_k == Universe::objectArrayKlass()) { 622 // Initialized early during Universe::genesis. No need to be added 623 // to the list. 624 return; 625 } 626 } else { 627 assert(buffered_k->is_typeArray_klass(), "must be"); 628 // Primitive type arrays are created early during Universe::genesis. 629 return; 630 } 631 632 if (log_is_enabled(Debug, cds, heap)) { 633 if (!_subgraph_object_klasses->contains(buffered_k)) { 634 ResourceMark rm; 635 log_debug(cds, heap)("Adding klass %s", orig_k->external_name()); 636 } 637 } 638 639 _subgraph_object_klasses->append_if_missing(buffered_k); 640 _has_non_early_klasses |= is_non_early_klass(orig_k); 641 } 642 643 void KlassSubGraphInfo::check_allowed_klass(InstanceKlass* ik) { 644 if (ik->module()->name() == vmSymbols::java_base()) { 645 assert(ik->package() != nullptr, "classes in java.base cannot be in unnamed package"); 646 return; 647 } 648 649 #ifndef PRODUCT 650 if (!ik->module()->is_named() && ik->package() == nullptr) { 651 // This class is loaded by ArchiveHeapTestClass 652 return; 653 } 654 const char* extra_msg = ", or in an unnamed package of an unnamed module"; 655 #else 656 const char* extra_msg = ""; 657 #endif 658 659 ResourceMark rm; 660 log_error(cds, heap)("Class %s not allowed in archive heap. Must be in java.base%s", 661 ik->external_name(), extra_msg); 662 MetaspaceShared::unrecoverable_writing_error(); 663 } 664 665 bool KlassSubGraphInfo::is_non_early_klass(Klass* k) { 666 if (k->is_objArray_klass()) { 667 k = ObjArrayKlass::cast(k)->bottom_klass(); 668 } 669 if (k->is_instance_klass()) { 670 if (!SystemDictionaryShared::is_early_klass(InstanceKlass::cast(k))) { 671 ResourceMark rm; 672 log_info(cds, heap)("non-early: %s", k->external_name()); 673 return true; 674 } else { 675 return false; 676 } 677 } else { 678 return false; 679 } 680 } 681 682 // Initialize an archived subgraph_info_record from the given KlassSubGraphInfo. 683 void ArchivedKlassSubGraphInfoRecord::init(KlassSubGraphInfo* info) { 684 _k = info->klass(); 685 _entry_field_records = nullptr; 686 _subgraph_object_klasses = nullptr; 687 _is_full_module_graph = info->is_full_module_graph(); 688 689 if (_is_full_module_graph) { 690 // Consider all classes referenced by the full module graph as early -- we will be 691 // allocating objects of these classes during JVMTI early phase, so they cannot 692 // be processed by (non-early) JVMTI ClassFileLoadHook 693 _has_non_early_klasses = false; 694 } else { 695 _has_non_early_klasses = info->has_non_early_klasses(); 696 } 697 698 if (_has_non_early_klasses) { 699 ResourceMark rm; 700 log_info(cds, heap)( 701 "Subgraph of klass %s has non-early klasses and cannot be used when JVMTI ClassFileLoadHook is enabled", 702 _k->external_name()); 703 } 704 705 // populate the entry fields 706 GrowableArray<int>* entry_fields = info->subgraph_entry_fields(); 707 if (entry_fields != nullptr) { 708 int num_entry_fields = entry_fields->length(); 709 assert(num_entry_fields % 2 == 0, "sanity"); 710 _entry_field_records = 711 ArchiveBuilder::new_ro_array<int>(num_entry_fields); 712 for (int i = 0 ; i < num_entry_fields; i++) { 713 _entry_field_records->at_put(i, entry_fields->at(i)); 714 } 715 } 716 717 // the Klasses of the objects in the sub-graphs 718 GrowableArray<Klass*>* subgraph_object_klasses = info->subgraph_object_klasses(); 719 if (subgraph_object_klasses != nullptr) { 720 int num_subgraphs_klasses = subgraph_object_klasses->length(); 721 _subgraph_object_klasses = 722 ArchiveBuilder::new_ro_array<Klass*>(num_subgraphs_klasses); 723 for (int i = 0; i < num_subgraphs_klasses; i++) { 724 Klass* subgraph_k = subgraph_object_klasses->at(i); 725 if (log_is_enabled(Info, cds, heap)) { 726 ResourceMark rm; 727 log_info(cds, heap)( 728 "Archived object klass %s (%2d) => %s", 729 _k->external_name(), i, subgraph_k->external_name()); 730 } 731 _subgraph_object_klasses->at_put(i, subgraph_k); 732 ArchivePtrMarker::mark_pointer(_subgraph_object_klasses->adr_at(i)); 733 } 734 } 735 736 ArchivePtrMarker::mark_pointer(&_k); 737 ArchivePtrMarker::mark_pointer(&_entry_field_records); 738 ArchivePtrMarker::mark_pointer(&_subgraph_object_klasses); 739 } 740 741 struct CopyKlassSubGraphInfoToArchive : StackObj { 742 CompactHashtableWriter* _writer; 743 CopyKlassSubGraphInfoToArchive(CompactHashtableWriter* writer) : _writer(writer) {} 744 745 bool do_entry(Klass* klass, KlassSubGraphInfo& info) { 746 if (info.subgraph_object_klasses() != nullptr || info.subgraph_entry_fields() != nullptr) { 747 ArchivedKlassSubGraphInfoRecord* record = 748 (ArchivedKlassSubGraphInfoRecord*)ArchiveBuilder::ro_region_alloc(sizeof(ArchivedKlassSubGraphInfoRecord)); 749 record->init(&info); 750 751 Klass* buffered_k = ArchiveBuilder::get_buffered_klass(klass); 752 unsigned int hash = SystemDictionaryShared::hash_for_shared_dictionary((address)buffered_k); 753 u4 delta = ArchiveBuilder::current()->any_to_offset_u4(record); 754 _writer->add(hash, delta); 755 } 756 return true; // keep on iterating 757 } 758 }; 759 760 // Build the records of archived subgraph infos, which include: 761 // - Entry points to all subgraphs from the containing class mirror. The entry 762 // points are static fields in the mirror. For each entry point, the field 763 // offset, and value are recorded in the sub-graph 764 // info. The value is stored back to the corresponding field at runtime. 765 // - A list of klasses that need to be loaded/initialized before archived 766 // java object sub-graph can be accessed at runtime. 767 void HeapShared::write_subgraph_info_table() { 768 // Allocate the contents of the hashtable(s) inside the RO region of the CDS archive. 769 DumpTimeKlassSubGraphInfoTable* d_table = _dump_time_subgraph_info_table; 770 CompactHashtableStats stats; 771 772 _run_time_subgraph_info_table.reset(); 773 774 CompactHashtableWriter writer(d_table->_count, &stats); 775 CopyKlassSubGraphInfoToArchive copy(&writer); 776 d_table->iterate(©); 777 writer.dump(&_run_time_subgraph_info_table, "subgraphs"); 778 779 #ifndef PRODUCT 780 if (ArchiveHeapTestClass != nullptr) { 781 size_t len = strlen(ArchiveHeapTestClass) + 1; 782 Array<char>* array = ArchiveBuilder::new_ro_array<char>((int)len); 783 strncpy(array->adr_at(0), ArchiveHeapTestClass, len); 784 _archived_ArchiveHeapTestClass = array; 785 } 786 #endif 787 if (log_is_enabled(Info, cds, heap)) { 788 print_stats(); 789 } 790 } 791 792 void HeapShared::add_root_segment(objArrayOop segment_oop) { 793 assert(segment_oop != nullptr, "must be"); 794 assert(ArchiveHeapLoader::is_in_use(), "must be"); 795 if (_root_segments == nullptr) { 796 _root_segments = new GrowableArrayCHeap<OopHandle, mtClassShared>(10); 797 } 798 _root_segments->push(OopHandle(Universe::vm_global(), segment_oop)); 799 } 800 801 void HeapShared::init_root_segment_sizes(int max_size_elems) { 802 _root_segment_max_size_elems = max_size_elems; 803 } 804 805 void HeapShared::serialize_tables(SerializeClosure* soc) { 806 807 #ifndef PRODUCT 808 soc->do_ptr(&_archived_ArchiveHeapTestClass); 809 if (soc->reading() && _archived_ArchiveHeapTestClass != nullptr) { 810 _test_class_name = _archived_ArchiveHeapTestClass->adr_at(0); 811 setup_test_class(_test_class_name); 812 } 813 #endif 814 815 _run_time_subgraph_info_table.serialize_header(soc); 816 } 817 818 static void verify_the_heap(Klass* k, const char* which) { 819 if (VerifyArchivedFields > 0) { 820 ResourceMark rm; 821 log_info(cds, heap)("Verify heap %s initializing static field(s) in %s", 822 which, k->external_name()); 823 824 VM_Verify verify_op; 825 VMThread::execute(&verify_op); 826 827 if (VerifyArchivedFields > 1 && is_init_completed()) { 828 // At this time, the oop->klass() of some archived objects in the heap may not 829 // have been loaded into the system dictionary yet. Nevertheless, oop->klass() should 830 // have enough information (object size, oop maps, etc) so that a GC can be safely 831 // performed. 832 // 833 // -XX:VerifyArchivedFields=2 force a GC to happen in such an early stage 834 // to check for GC safety. 835 log_info(cds, heap)("Trigger GC %s initializing static field(s) in %s", 836 which, k->external_name()); 837 FlagSetting fs1(VerifyBeforeGC, true); 838 FlagSetting fs2(VerifyDuringGC, true); 839 FlagSetting fs3(VerifyAfterGC, true); 840 Universe::heap()->collect(GCCause::_java_lang_system_gc); 841 } 842 } 843 } 844 845 // Before GC can execute, we must ensure that all oops reachable from HeapShared::roots() 846 // have a valid klass. I.e., oopDesc::klass() must have already been resolved. 847 // 848 // Note: if a ArchivedKlassSubGraphInfoRecord contains non-early classes, and JVMTI 849 // ClassFileLoadHook is enabled, it's possible for this class to be dynamically replaced. In 850 // this case, we will not load the ArchivedKlassSubGraphInfoRecord and will clear its roots. 851 void HeapShared::resolve_classes(JavaThread* current) { 852 assert(CDSConfig::is_using_archive(), "runtime only!"); 853 if (!ArchiveHeapLoader::is_in_use()) { 854 return; // nothing to do 855 } 856 resolve_classes_for_subgraphs(current, archive_subgraph_entry_fields); 857 resolve_classes_for_subgraphs(current, fmg_archive_subgraph_entry_fields); 858 } 859 860 void HeapShared::resolve_classes_for_subgraphs(JavaThread* current, ArchivableStaticFieldInfo fields[]) { 861 for (int i = 0; fields[i].valid(); i++) { 862 ArchivableStaticFieldInfo* info = &fields[i]; 863 TempNewSymbol klass_name = SymbolTable::new_symbol(info->klass_name); 864 InstanceKlass* k = SystemDictionaryShared::find_builtin_class(klass_name); 865 assert(k != nullptr && k->is_shared_boot_class(), "sanity"); 866 resolve_classes_for_subgraph_of(current, k); 867 } 868 } 869 870 void HeapShared::resolve_classes_for_subgraph_of(JavaThread* current, Klass* k) { 871 JavaThread* THREAD = current; 872 ExceptionMark em(THREAD); 873 const ArchivedKlassSubGraphInfoRecord* record = 874 resolve_or_init_classes_for_subgraph_of(k, /*do_init=*/false, THREAD); 875 if (HAS_PENDING_EXCEPTION) { 876 CLEAR_PENDING_EXCEPTION; 877 } 878 if (record == nullptr) { 879 clear_archived_roots_of(k); 880 } 881 } 882 883 void HeapShared::initialize_from_archived_subgraph(JavaThread* current, Klass* k) { 884 JavaThread* THREAD = current; 885 if (!ArchiveHeapLoader::is_in_use()) { 886 return; // nothing to do 887 } 888 889 if (k->name()->equals("jdk/internal/module/ArchivedModuleGraph") && 890 !CDSConfig::is_using_optimized_module_handling() && 891 // archive was created with --module-path 892 ClassLoaderExt::num_module_paths() > 0) { 893 // ArchivedModuleGraph was created with a --module-path that's different than the runtime --module-path. 894 // Thus, it might contain references to modules that do not exist at runtime. We cannot use it. 895 log_info(cds, heap)("Skip initializing ArchivedModuleGraph subgraph: is_using_optimized_module_handling=%s num_module_paths=%d", 896 BOOL_TO_STR(CDSConfig::is_using_optimized_module_handling()), ClassLoaderExt::num_module_paths()); 897 return; 898 } 899 900 ExceptionMark em(THREAD); 901 const ArchivedKlassSubGraphInfoRecord* record = 902 resolve_or_init_classes_for_subgraph_of(k, /*do_init=*/true, THREAD); 903 904 if (HAS_PENDING_EXCEPTION) { 905 CLEAR_PENDING_EXCEPTION; 906 // None of the field value will be set if there was an exception when initializing the classes. 907 // The java code will not see any of the archived objects in the 908 // subgraphs referenced from k in this case. 909 return; 910 } 911 912 if (record != nullptr) { 913 init_archived_fields_for(k, record); 914 } 915 } 916 917 const ArchivedKlassSubGraphInfoRecord* 918 HeapShared::resolve_or_init_classes_for_subgraph_of(Klass* k, bool do_init, TRAPS) { 919 assert(!CDSConfig::is_dumping_heap(), "Should not be called when dumping heap"); 920 921 if (!k->is_shared()) { 922 return nullptr; 923 } 924 unsigned int hash = SystemDictionaryShared::hash_for_shared_dictionary_quick(k); 925 const ArchivedKlassSubGraphInfoRecord* record = _run_time_subgraph_info_table.lookup(k, hash, 0); 926 927 #ifndef PRODUCT 928 if (_test_class_name != nullptr && k->name()->equals(_test_class_name) && record != nullptr) { 929 _test_class = k; 930 _test_class_record = record; 931 } 932 #endif 933 934 // Initialize from archived data. Currently this is done only 935 // during VM initialization time. No lock is needed. 936 if (record == nullptr) { 937 if (log_is_enabled(Info, cds, heap)) { 938 ResourceMark rm(THREAD); 939 log_info(cds, heap)("subgraph %s is not recorded", 940 k->external_name()); 941 } 942 return nullptr; 943 } else { 944 if (record->is_full_module_graph() && !CDSConfig::is_using_full_module_graph()) { 945 if (log_is_enabled(Info, cds, heap)) { 946 ResourceMark rm(THREAD); 947 log_info(cds, heap)("subgraph %s cannot be used because full module graph is disabled", 948 k->external_name()); 949 } 950 return nullptr; 951 } 952 953 if (record->has_non_early_klasses() && JvmtiExport::should_post_class_file_load_hook()) { 954 if (log_is_enabled(Info, cds, heap)) { 955 ResourceMark rm(THREAD); 956 log_info(cds, heap)("subgraph %s cannot be used because JVMTI ClassFileLoadHook is enabled", 957 k->external_name()); 958 } 959 return nullptr; 960 } 961 962 if (log_is_enabled(Info, cds, heap)) { 963 ResourceMark rm; 964 log_info(cds, heap)("%s subgraph %s ", do_init ? "init" : "resolve", k->external_name()); 965 } 966 967 resolve_or_init(k, do_init, CHECK_NULL); 968 969 // Load/link/initialize the klasses of the objects in the subgraph. 970 // nullptr class loader is used. 971 Array<Klass*>* klasses = record->subgraph_object_klasses(); 972 if (klasses != nullptr) { 973 for (int i = 0; i < klasses->length(); i++) { 974 Klass* klass = klasses->at(i); 975 if (!klass->is_shared()) { 976 return nullptr; 977 } 978 resolve_or_init(klass, do_init, CHECK_NULL); 979 } 980 } 981 } 982 983 return record; 984 } 985 986 void HeapShared::resolve_or_init(Klass* k, bool do_init, TRAPS) { 987 if (!do_init) { 988 if (k->class_loader_data() == nullptr) { 989 Klass* resolved_k = SystemDictionary::resolve_or_null(k->name(), CHECK); 990 assert(resolved_k == k, "classes used by archived heap must not be replaced by JVMTI ClassFileLoadHook"); 991 } 992 } else { 993 assert(k->class_loader_data() != nullptr, "must have been resolved by HeapShared::resolve_classes"); 994 if (k->is_instance_klass()) { 995 InstanceKlass* ik = InstanceKlass::cast(k); 996 ik->initialize(CHECK); 997 } else if (k->is_objArray_klass()) { 998 ObjArrayKlass* oak = ObjArrayKlass::cast(k); 999 oak->initialize(CHECK); 1000 } 1001 } 1002 } 1003 1004 void HeapShared::init_archived_fields_for(Klass* k, const ArchivedKlassSubGraphInfoRecord* record) { 1005 verify_the_heap(k, "before"); 1006 1007 // Load the subgraph entry fields from the record and store them back to 1008 // the corresponding fields within the mirror. 1009 oop m = k->java_mirror(); 1010 Array<int>* entry_field_records = record->entry_field_records(); 1011 if (entry_field_records != nullptr) { 1012 int efr_len = entry_field_records->length(); 1013 assert(efr_len % 2 == 0, "sanity"); 1014 for (int i = 0; i < efr_len; i += 2) { 1015 int field_offset = entry_field_records->at(i); 1016 int root_index = entry_field_records->at(i+1); 1017 oop v = get_root(root_index, /*clear=*/true); 1018 m->obj_field_put(field_offset, v); 1019 log_debug(cds, heap)(" " PTR_FORMAT " init field @ %2d = " PTR_FORMAT, p2i(k), field_offset, p2i(v)); 1020 } 1021 1022 // Done. Java code can see the archived sub-graphs referenced from k's 1023 // mirror after this point. 1024 if (log_is_enabled(Info, cds, heap)) { 1025 ResourceMark rm; 1026 log_info(cds, heap)("initialize_from_archived_subgraph %s " PTR_FORMAT "%s", 1027 k->external_name(), p2i(k), JvmtiExport::is_early_phase() ? " (early)" : ""); 1028 } 1029 } 1030 1031 verify_the_heap(k, "after "); 1032 } 1033 1034 void HeapShared::clear_archived_roots_of(Klass* k) { 1035 unsigned int hash = SystemDictionaryShared::hash_for_shared_dictionary_quick(k); 1036 const ArchivedKlassSubGraphInfoRecord* record = _run_time_subgraph_info_table.lookup(k, hash, 0); 1037 if (record != nullptr) { 1038 Array<int>* entry_field_records = record->entry_field_records(); 1039 if (entry_field_records != nullptr) { 1040 int efr_len = entry_field_records->length(); 1041 assert(efr_len % 2 == 0, "sanity"); 1042 for (int i = 0; i < efr_len; i += 2) { 1043 int root_index = entry_field_records->at(i+1); 1044 clear_root(root_index); 1045 } 1046 } 1047 } 1048 } 1049 1050 class WalkOopAndArchiveClosure: public BasicOopIterateClosure { 1051 int _level; 1052 bool _record_klasses_only; 1053 KlassSubGraphInfo* _subgraph_info; 1054 oop _referencing_obj; 1055 1056 // The following are for maintaining a stack for determining 1057 // CachedOopInfo::_referrer 1058 static WalkOopAndArchiveClosure* _current; 1059 WalkOopAndArchiveClosure* _last; 1060 public: 1061 WalkOopAndArchiveClosure(int level, 1062 bool record_klasses_only, 1063 KlassSubGraphInfo* subgraph_info, 1064 oop orig) : 1065 _level(level), 1066 _record_klasses_only(record_klasses_only), 1067 _subgraph_info(subgraph_info), 1068 _referencing_obj(orig) { 1069 _last = _current; 1070 _current = this; 1071 } 1072 ~WalkOopAndArchiveClosure() { 1073 _current = _last; 1074 } 1075 void do_oop(narrowOop *p) { WalkOopAndArchiveClosure::do_oop_work(p); } 1076 void do_oop( oop *p) { WalkOopAndArchiveClosure::do_oop_work(p); } 1077 1078 protected: 1079 template <class T> void do_oop_work(T *p) { 1080 oop obj = RawAccess<>::oop_load(p); 1081 if (!CompressedOops::is_null(obj)) { 1082 size_t field_delta = pointer_delta(p, _referencing_obj, sizeof(char)); 1083 1084 if (!_record_klasses_only && log_is_enabled(Debug, cds, heap)) { 1085 ResourceMark rm; 1086 log_debug(cds, heap)("(%d) %s[" SIZE_FORMAT "] ==> " PTR_FORMAT " size " SIZE_FORMAT " %s", _level, 1087 _referencing_obj->klass()->external_name(), field_delta, 1088 p2i(obj), obj->size() * HeapWordSize, obj->klass()->external_name()); 1089 if (log_is_enabled(Trace, cds, heap)) { 1090 LogTarget(Trace, cds, heap) log; 1091 LogStream out(log); 1092 obj->print_on(&out); 1093 } 1094 } 1095 1096 bool success = HeapShared::archive_reachable_objects_from( 1097 _level + 1, _subgraph_info, obj); 1098 assert(success, "VM should have exited with unarchivable objects for _level > 1"); 1099 } 1100 } 1101 1102 public: 1103 static WalkOopAndArchiveClosure* current() { return _current; } 1104 oop referencing_obj() { return _referencing_obj; } 1105 KlassSubGraphInfo* subgraph_info() { return _subgraph_info; } 1106 }; 1107 1108 WalkOopAndArchiveClosure* WalkOopAndArchiveClosure::_current = nullptr; 1109 1110 // Checks if an oop has any non-null oop fields 1111 class PointsToOopsChecker : public BasicOopIterateClosure { 1112 bool _result; 1113 1114 template <class T> void check(T *p) { 1115 _result |= (HeapAccess<>::oop_load(p) != nullptr); 1116 } 1117 1118 public: 1119 PointsToOopsChecker() : _result(false) {} 1120 void do_oop(narrowOop *p) { check(p); } 1121 void do_oop( oop *p) { check(p); } 1122 bool result() { return _result; } 1123 }; 1124 1125 HeapShared::CachedOopInfo HeapShared::make_cached_oop_info(oop obj) { 1126 WalkOopAndArchiveClosure* walker = WalkOopAndArchiveClosure::current(); 1127 oop referrer = (walker == nullptr) ? nullptr : walker->referencing_obj(); 1128 PointsToOopsChecker points_to_oops_checker; 1129 obj->oop_iterate(&points_to_oops_checker); 1130 return CachedOopInfo(referrer, points_to_oops_checker.result()); 1131 } 1132 1133 // (1) If orig_obj has not been archived yet, archive it. 1134 // (2) If orig_obj has not been seen yet (since start_recording_subgraph() was called), 1135 // trace all objects that are reachable from it, and make sure these objects are archived. 1136 // (3) Record the klasses of all orig_obj and all reachable objects. 1137 bool HeapShared::archive_reachable_objects_from(int level, 1138 KlassSubGraphInfo* subgraph_info, 1139 oop orig_obj) { 1140 assert(orig_obj != nullptr, "must be"); 1141 1142 if (!JavaClasses::is_supported_for_archiving(orig_obj)) { 1143 // This object has injected fields that cannot be supported easily, so we disallow them for now. 1144 // If you get an error here, you probably made a change in the JDK library that has added 1145 // these objects that are referenced (directly or indirectly) by static fields. 1146 ResourceMark rm; 1147 log_error(cds, heap)("Cannot archive object of class %s", orig_obj->klass()->external_name()); 1148 if (log_is_enabled(Trace, cds, heap)) { 1149 WalkOopAndArchiveClosure* walker = WalkOopAndArchiveClosure::current(); 1150 if (walker != nullptr) { 1151 LogStream ls(Log(cds, heap)::trace()); 1152 CDSHeapVerifier::trace_to_root(&ls, walker->referencing_obj()); 1153 } 1154 } 1155 MetaspaceShared::unrecoverable_writing_error(); 1156 } 1157 1158 // java.lang.Class instances cannot be included in an archived object sub-graph. We only support 1159 // them as Klass::_archived_mirror because they need to be specially restored at run time. 1160 // 1161 // If you get an error here, you probably made a change in the JDK library that has added a Class 1162 // object that is referenced (directly or indirectly) by static fields. 1163 if (java_lang_Class::is_instance(orig_obj) && subgraph_info != _default_subgraph_info) { 1164 log_error(cds, heap)("(%d) Unknown java.lang.Class object is in the archived sub-graph", level); 1165 MetaspaceShared::unrecoverable_writing_error(); 1166 } 1167 1168 if (has_been_seen_during_subgraph_recording(orig_obj)) { 1169 // orig_obj has already been archived and traced. Nothing more to do. 1170 return true; 1171 } else { 1172 set_has_been_seen_during_subgraph_recording(orig_obj); 1173 } 1174 1175 bool already_archived = has_been_archived(orig_obj); 1176 bool record_klasses_only = already_archived; 1177 if (!already_archived) { 1178 ++_num_new_archived_objs; 1179 if (!archive_object(orig_obj)) { 1180 // Skip archiving the sub-graph referenced from the current entry field. 1181 ResourceMark rm; 1182 log_error(cds, heap)( 1183 "Cannot archive the sub-graph referenced from %s object (" 1184 PTR_FORMAT ") size " SIZE_FORMAT ", skipped.", 1185 orig_obj->klass()->external_name(), p2i(orig_obj), orig_obj->size() * HeapWordSize); 1186 if (level == 1) { 1187 // Don't archive a subgraph root that's too big. For archives static fields, that's OK 1188 // as the Java code will take care of initializing this field dynamically. 1189 return false; 1190 } else { 1191 // We don't know how to handle an object that has been archived, but some of its reachable 1192 // objects cannot be archived. Bail out for now. We might need to fix this in the future if 1193 // we have a real use case. 1194 MetaspaceShared::unrecoverable_writing_error(); 1195 } 1196 } 1197 } 1198 1199 Klass *orig_k = orig_obj->klass(); 1200 subgraph_info->add_subgraph_object_klass(orig_k); 1201 1202 WalkOopAndArchiveClosure walker(level, record_klasses_only, subgraph_info, orig_obj); 1203 orig_obj->oop_iterate(&walker); 1204 1205 if (CDSEnumKlass::is_enum_obj(orig_obj)) { 1206 CDSEnumKlass::handle_enum_obj(level + 1, subgraph_info, orig_obj); 1207 } 1208 return true; 1209 } 1210 1211 // 1212 // Start from the given static field in a java mirror and archive the 1213 // complete sub-graph of java heap objects that are reached directly 1214 // or indirectly from the starting object by following references. 1215 // Sub-graph archiving restrictions (current): 1216 // 1217 // - All classes of objects in the archived sub-graph (including the 1218 // entry class) must be boot class only. 1219 // - No java.lang.Class instance (java mirror) can be included inside 1220 // an archived sub-graph. Mirror can only be the sub-graph entry object. 1221 // 1222 // The Java heap object sub-graph archiving process (see 1223 // WalkOopAndArchiveClosure): 1224 // 1225 // 1) Java object sub-graph archiving starts from a given static field 1226 // within a Class instance (java mirror). If the static field is a 1227 // reference field and points to a non-null java object, proceed to 1228 // the next step. 1229 // 1230 // 2) Archives the referenced java object. If an archived copy of the 1231 // current object already exists, updates the pointer in the archived 1232 // copy of the referencing object to point to the current archived object. 1233 // Otherwise, proceed to the next step. 1234 // 1235 // 3) Follows all references within the current java object and recursively 1236 // archive the sub-graph of objects starting from each reference. 1237 // 1238 // 4) Updates the pointer in the archived copy of referencing object to 1239 // point to the current archived object. 1240 // 1241 // 5) The Klass of the current java object is added to the list of Klasses 1242 // for loading and initializing before any object in the archived graph can 1243 // be accessed at runtime. 1244 // 1245 void HeapShared::archive_reachable_objects_from_static_field(InstanceKlass *k, 1246 const char* klass_name, 1247 int field_offset, 1248 const char* field_name) { 1249 assert(CDSConfig::is_dumping_heap(), "dump time only"); 1250 assert(k->is_shared_boot_class(), "must be boot class"); 1251 1252 oop m = k->java_mirror(); 1253 1254 KlassSubGraphInfo* subgraph_info = get_subgraph_info(k); 1255 oop f = m->obj_field(field_offset); 1256 1257 log_debug(cds, heap)("Start archiving from: %s::%s (" PTR_FORMAT ")", klass_name, field_name, p2i(f)); 1258 1259 if (!CompressedOops::is_null(f)) { 1260 if (log_is_enabled(Trace, cds, heap)) { 1261 LogTarget(Trace, cds, heap) log; 1262 LogStream out(log); 1263 f->print_on(&out); 1264 } 1265 1266 bool success = archive_reachable_objects_from(1, subgraph_info, f); 1267 if (!success) { 1268 log_error(cds, heap)("Archiving failed %s::%s (some reachable objects cannot be archived)", 1269 klass_name, field_name); 1270 } else { 1271 // Note: the field value is not preserved in the archived mirror. 1272 // Record the field as a new subGraph entry point. The recorded 1273 // information is restored from the archive at runtime. 1274 subgraph_info->add_subgraph_entry_field(field_offset, f); 1275 log_info(cds, heap)("Archived field %s::%s => " PTR_FORMAT, klass_name, field_name, p2i(f)); 1276 } 1277 } else { 1278 // The field contains null, we still need to record the entry point, 1279 // so it can be restored at runtime. 1280 subgraph_info->add_subgraph_entry_field(field_offset, nullptr); 1281 } 1282 } 1283 1284 #ifndef PRODUCT 1285 class VerifySharedOopClosure: public BasicOopIterateClosure { 1286 public: 1287 void do_oop(narrowOop *p) { VerifySharedOopClosure::do_oop_work(p); } 1288 void do_oop( oop *p) { VerifySharedOopClosure::do_oop_work(p); } 1289 1290 protected: 1291 template <class T> void do_oop_work(T *p) { 1292 oop obj = RawAccess<>::oop_load(p); 1293 if (!CompressedOops::is_null(obj)) { 1294 HeapShared::verify_reachable_objects_from(obj); 1295 } 1296 } 1297 }; 1298 1299 void HeapShared::verify_subgraph_from_static_field(InstanceKlass* k, int field_offset) { 1300 assert(CDSConfig::is_dumping_heap(), "dump time only"); 1301 assert(k->is_shared_boot_class(), "must be boot class"); 1302 1303 oop m = k->java_mirror(); 1304 oop f = m->obj_field(field_offset); 1305 if (!CompressedOops::is_null(f)) { 1306 verify_subgraph_from(f); 1307 } 1308 } 1309 1310 void HeapShared::verify_subgraph_from(oop orig_obj) { 1311 if (!has_been_archived(orig_obj)) { 1312 // It's OK for the root of a subgraph to be not archived. See comments in 1313 // archive_reachable_objects_from(). 1314 return; 1315 } 1316 1317 // Verify that all objects reachable from orig_obj are archived. 1318 init_seen_objects_table(); 1319 verify_reachable_objects_from(orig_obj); 1320 delete_seen_objects_table(); 1321 } 1322 1323 void HeapShared::verify_reachable_objects_from(oop obj) { 1324 _num_total_verifications ++; 1325 if (!has_been_seen_during_subgraph_recording(obj)) { 1326 set_has_been_seen_during_subgraph_recording(obj); 1327 assert(has_been_archived(obj), "must be"); 1328 VerifySharedOopClosure walker; 1329 obj->oop_iterate(&walker); 1330 } 1331 } 1332 #endif 1333 1334 // The "default subgraph" contains special objects (see heapShared.hpp) that 1335 // can be accessed before we load any Java classes (including java/lang/Class). 1336 // Make sure that these are only instances of the very few specific types 1337 // that we can handle. 1338 void HeapShared::check_default_subgraph_classes() { 1339 GrowableArray<Klass*>* klasses = _default_subgraph_info->subgraph_object_klasses(); 1340 int num = klasses->length(); 1341 for (int i = 0; i < num; i++) { 1342 Klass* subgraph_k = klasses->at(i); 1343 if (log_is_enabled(Info, cds, heap)) { 1344 ResourceMark rm; 1345 log_info(cds, heap)( 1346 "Archived object klass (default subgraph %d) => %s", 1347 i, subgraph_k->external_name()); 1348 } 1349 1350 Symbol* name = ArchiveBuilder::current()->get_source_addr(subgraph_k->name()); 1351 guarantee(name == vmSymbols::java_lang_Class() || 1352 name == vmSymbols::java_lang_String() || 1353 name == vmSymbols::java_lang_ArithmeticException() || 1354 name == vmSymbols::java_lang_NullPointerException() || 1355 name == vmSymbols::java_lang_InternalError() || 1356 name == vmSymbols::java_lang_ArrayIndexOutOfBoundsException() || 1357 name == vmSymbols::java_lang_ArrayStoreException() || 1358 name == vmSymbols::java_lang_ClassCastException() || 1359 name == vmSymbols::object_array_signature() || 1360 name == vmSymbols::byte_array_signature() || 1361 name == vmSymbols::char_array_signature(), 1362 "default subgraph can have only these objects"); 1363 } 1364 } 1365 1366 HeapShared::SeenObjectsTable* HeapShared::_seen_objects_table = nullptr; 1367 int HeapShared::_num_new_walked_objs; 1368 int HeapShared::_num_new_archived_objs; 1369 int HeapShared::_num_old_recorded_klasses; 1370 1371 int HeapShared::_num_total_subgraph_recordings = 0; 1372 int HeapShared::_num_total_walked_objs = 0; 1373 int HeapShared::_num_total_archived_objs = 0; 1374 int HeapShared::_num_total_recorded_klasses = 0; 1375 int HeapShared::_num_total_verifications = 0; 1376 1377 bool HeapShared::has_been_seen_during_subgraph_recording(oop obj) { 1378 return _seen_objects_table->get(obj) != nullptr; 1379 } 1380 1381 void HeapShared::set_has_been_seen_during_subgraph_recording(oop obj) { 1382 assert(!has_been_seen_during_subgraph_recording(obj), "sanity"); 1383 _seen_objects_table->put_when_absent(obj, true); 1384 _seen_objects_table->maybe_grow(); 1385 ++ _num_new_walked_objs; 1386 } 1387 1388 void HeapShared::start_recording_subgraph(InstanceKlass *k, const char* class_name, bool is_full_module_graph) { 1389 log_info(cds, heap)("Start recording subgraph(s) for archived fields in %s", class_name); 1390 init_subgraph_info(k, is_full_module_graph); 1391 init_seen_objects_table(); 1392 _num_new_walked_objs = 0; 1393 _num_new_archived_objs = 0; 1394 _num_old_recorded_klasses = get_subgraph_info(k)->num_subgraph_object_klasses(); 1395 } 1396 1397 void HeapShared::done_recording_subgraph(InstanceKlass *k, const char* class_name) { 1398 int num_new_recorded_klasses = get_subgraph_info(k)->num_subgraph_object_klasses() - 1399 _num_old_recorded_klasses; 1400 log_info(cds, heap)("Done recording subgraph(s) for archived fields in %s: " 1401 "walked %d objs, archived %d new objs, recorded %d classes", 1402 class_name, _num_new_walked_objs, _num_new_archived_objs, 1403 num_new_recorded_klasses); 1404 1405 delete_seen_objects_table(); 1406 1407 _num_total_subgraph_recordings ++; 1408 _num_total_walked_objs += _num_new_walked_objs; 1409 _num_total_archived_objs += _num_new_archived_objs; 1410 _num_total_recorded_klasses += num_new_recorded_klasses; 1411 } 1412 1413 class ArchivableStaticFieldFinder: public FieldClosure { 1414 InstanceKlass* _ik; 1415 Symbol* _field_name; 1416 bool _found; 1417 int _offset; 1418 public: 1419 ArchivableStaticFieldFinder(InstanceKlass* ik, Symbol* field_name) : 1420 _ik(ik), _field_name(field_name), _found(false), _offset(-1) {} 1421 1422 virtual void do_field(fieldDescriptor* fd) { 1423 if (fd->name() == _field_name) { 1424 assert(!_found, "fields can never be overloaded"); 1425 if (is_reference_type(fd->field_type())) { 1426 _found = true; 1427 _offset = fd->offset(); 1428 } 1429 } 1430 } 1431 bool found() { return _found; } 1432 int offset() { return _offset; } 1433 }; 1434 1435 void HeapShared::init_subgraph_entry_fields(ArchivableStaticFieldInfo fields[], 1436 TRAPS) { 1437 for (int i = 0; fields[i].valid(); i++) { 1438 ArchivableStaticFieldInfo* info = &fields[i]; 1439 TempNewSymbol klass_name = SymbolTable::new_symbol(info->klass_name); 1440 TempNewSymbol field_name = SymbolTable::new_symbol(info->field_name); 1441 ResourceMark rm; // for stringStream::as_string() etc. 1442 1443 #ifndef PRODUCT 1444 bool is_test_class = (ArchiveHeapTestClass != nullptr) && (strcmp(info->klass_name, ArchiveHeapTestClass) == 0); 1445 const char* test_class_name = ArchiveHeapTestClass; 1446 #else 1447 bool is_test_class = false; 1448 const char* test_class_name = ""; // avoid C++ printf checks warnings. 1449 #endif 1450 1451 if (is_test_class) { 1452 log_warning(cds)("Loading ArchiveHeapTestClass %s ...", test_class_name); 1453 } 1454 1455 Klass* k = SystemDictionary::resolve_or_fail(klass_name, true, THREAD); 1456 if (HAS_PENDING_EXCEPTION) { 1457 CLEAR_PENDING_EXCEPTION; 1458 stringStream st; 1459 st.print("Fail to initialize archive heap: %s cannot be loaded by the boot loader", info->klass_name); 1460 THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), st.as_string()); 1461 } 1462 1463 if (!k->is_instance_klass()) { 1464 stringStream st; 1465 st.print("Fail to initialize archive heap: %s is not an instance class", info->klass_name); 1466 THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), st.as_string()); 1467 } 1468 1469 InstanceKlass* ik = InstanceKlass::cast(k); 1470 assert(InstanceKlass::cast(ik)->is_shared_boot_class(), 1471 "Only support boot classes"); 1472 1473 if (is_test_class) { 1474 if (ik->module()->is_named()) { 1475 // We don't want ArchiveHeapTestClass to be abused to easily load/initialize arbitrary 1476 // core-lib classes. You need to at least append to the bootclasspath. 1477 stringStream st; 1478 st.print("ArchiveHeapTestClass %s is not in unnamed module", test_class_name); 1479 THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), st.as_string()); 1480 } 1481 1482 if (ik->package() != nullptr) { 1483 // This restriction makes HeapShared::is_a_test_class_in_unnamed_module() easy. 1484 stringStream st; 1485 st.print("ArchiveHeapTestClass %s is not in unnamed package", test_class_name); 1486 THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), st.as_string()); 1487 } 1488 } else { 1489 if (ik->module()->name() != vmSymbols::java_base()) { 1490 // We don't want to deal with cases when a module is unavailable at runtime. 1491 // FUTURE -- load from archived heap only when module graph has not changed 1492 // between dump and runtime. 1493 stringStream st; 1494 st.print("%s is not in java.base module", info->klass_name); 1495 THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), st.as_string()); 1496 } 1497 } 1498 1499 if (is_test_class) { 1500 log_warning(cds)("Initializing ArchiveHeapTestClass %s ...", test_class_name); 1501 } 1502 ik->initialize(CHECK); 1503 1504 ArchivableStaticFieldFinder finder(ik, field_name); 1505 ik->do_local_static_fields(&finder); 1506 if (!finder.found()) { 1507 stringStream st; 1508 st.print("Unable to find the static T_OBJECT field %s::%s", info->klass_name, info->field_name); 1509 THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), st.as_string()); 1510 } 1511 1512 info->klass = ik; 1513 info->offset = finder.offset(); 1514 } 1515 } 1516 1517 void HeapShared::init_subgraph_entry_fields(TRAPS) { 1518 assert(HeapShared::can_write(), "must be"); 1519 _dump_time_subgraph_info_table = new (mtClass)DumpTimeKlassSubGraphInfoTable(); 1520 init_subgraph_entry_fields(archive_subgraph_entry_fields, CHECK); 1521 if (CDSConfig::is_dumping_full_module_graph()) { 1522 init_subgraph_entry_fields(fmg_archive_subgraph_entry_fields, CHECK); 1523 } 1524 } 1525 1526 #ifndef PRODUCT 1527 void HeapShared::setup_test_class(const char* test_class_name) { 1528 ArchivableStaticFieldInfo* p = archive_subgraph_entry_fields; 1529 int num_slots = sizeof(archive_subgraph_entry_fields) / sizeof(ArchivableStaticFieldInfo); 1530 assert(p[num_slots - 2].klass_name == nullptr, "must have empty slot that's patched below"); 1531 assert(p[num_slots - 1].klass_name == nullptr, "must have empty slot that marks the end of the list"); 1532 1533 if (test_class_name != nullptr) { 1534 p[num_slots - 2].klass_name = test_class_name; 1535 p[num_slots - 2].field_name = ARCHIVE_TEST_FIELD_NAME; 1536 } 1537 } 1538 1539 // See if ik is one of the test classes that are pulled in by -XX:ArchiveHeapTestClass 1540 // during runtime. This may be called before the module system is initialized so 1541 // we cannot rely on InstanceKlass::module(), etc. 1542 bool HeapShared::is_a_test_class_in_unnamed_module(Klass* ik) { 1543 if (_test_class != nullptr) { 1544 if (ik == _test_class) { 1545 return true; 1546 } 1547 Array<Klass*>* klasses = _test_class_record->subgraph_object_klasses(); 1548 if (klasses == nullptr) { 1549 return false; 1550 } 1551 1552 for (int i = 0; i < klasses->length(); i++) { 1553 Klass* k = klasses->at(i); 1554 if (k == ik) { 1555 Symbol* name; 1556 if (k->is_instance_klass()) { 1557 name = InstanceKlass::cast(k)->name(); 1558 } else if (k->is_objArray_klass()) { 1559 Klass* bk = ObjArrayKlass::cast(k)->bottom_klass(); 1560 if (!bk->is_instance_klass()) { 1561 return false; 1562 } 1563 name = bk->name(); 1564 } else { 1565 return false; 1566 } 1567 1568 // See KlassSubGraphInfo::check_allowed_klass() - only two types of 1569 // classes are allowed: 1570 // (A) java.base classes (which must not be in the unnamed module) 1571 // (B) test classes which must be in the unnamed package of the unnamed module. 1572 // So if we see a '/' character in the class name, it must be in (A); 1573 // otherwise it must be in (B). 1574 if (name->index_of_at(0, "/", 1) >= 0) { 1575 return false; // (A) 1576 } 1577 1578 return true; // (B) 1579 } 1580 } 1581 } 1582 1583 return false; 1584 } 1585 #endif 1586 1587 void HeapShared::init_for_dumping(TRAPS) { 1588 if (HeapShared::can_write()) { 1589 setup_test_class(ArchiveHeapTestClass); 1590 _dumped_interned_strings = new (mtClass)DumpedInternedStrings(INITIAL_TABLE_SIZE, MAX_TABLE_SIZE); 1591 init_subgraph_entry_fields(CHECK); 1592 } 1593 } 1594 1595 void HeapShared::archive_object_subgraphs(ArchivableStaticFieldInfo fields[], 1596 bool is_full_module_graph) { 1597 _num_total_subgraph_recordings = 0; 1598 _num_total_walked_objs = 0; 1599 _num_total_archived_objs = 0; 1600 _num_total_recorded_klasses = 0; 1601 _num_total_verifications = 0; 1602 1603 // For each class X that has one or more archived fields: 1604 // [1] Dump the subgraph of each archived field 1605 // [2] Create a list of all the class of the objects that can be reached 1606 // by any of these static fields. 1607 // At runtime, these classes are initialized before X's archived fields 1608 // are restored by HeapShared::initialize_from_archived_subgraph(). 1609 for (int i = 0; fields[i].valid(); ) { 1610 ArchivableStaticFieldInfo* info = &fields[i]; 1611 const char* klass_name = info->klass_name; 1612 start_recording_subgraph(info->klass, klass_name, is_full_module_graph); 1613 1614 // If you have specified consecutive fields of the same klass in 1615 // fields[], these will be archived in the same 1616 // {start_recording_subgraph ... done_recording_subgraph} pass to 1617 // save time. 1618 for (; fields[i].valid(); i++) { 1619 ArchivableStaticFieldInfo* f = &fields[i]; 1620 if (f->klass_name != klass_name) { 1621 break; 1622 } 1623 1624 archive_reachable_objects_from_static_field(f->klass, f->klass_name, 1625 f->offset, f->field_name); 1626 } 1627 done_recording_subgraph(info->klass, klass_name); 1628 } 1629 1630 log_info(cds, heap)("Archived subgraph records = %d", 1631 _num_total_subgraph_recordings); 1632 log_info(cds, heap)(" Walked %d objects", _num_total_walked_objs); 1633 log_info(cds, heap)(" Archived %d objects", _num_total_archived_objs); 1634 log_info(cds, heap)(" Recorded %d klasses", _num_total_recorded_klasses); 1635 1636 #ifndef PRODUCT 1637 for (int i = 0; fields[i].valid(); i++) { 1638 ArchivableStaticFieldInfo* f = &fields[i]; 1639 verify_subgraph_from_static_field(f->klass, f->offset); 1640 } 1641 log_info(cds, heap)(" Verified %d references", _num_total_verifications); 1642 #endif 1643 } 1644 1645 // Not all the strings in the global StringTable are dumped into the archive, because 1646 // some of those strings may be only referenced by classes that are excluded from 1647 // the archive. We need to explicitly mark the strings that are: 1648 // [1] used by classes that WILL be archived; 1649 // [2] included in the SharedArchiveConfigFile. 1650 void HeapShared::add_to_dumped_interned_strings(oop string) { 1651 assert_at_safepoint(); // DumpedInternedStrings uses raw oops 1652 assert(!ArchiveHeapWriter::is_string_too_large_to_archive(string), "must be"); 1653 bool created; 1654 _dumped_interned_strings->put_if_absent(string, true, &created); 1655 if (created) { 1656 _dumped_interned_strings->maybe_grow(); 1657 } 1658 } 1659 1660 #ifndef PRODUCT 1661 // At dump-time, find the location of all the non-null oop pointers in an archived heap 1662 // region. This way we can quickly relocate all the pointers without using 1663 // BasicOopIterateClosure at runtime. 1664 class FindEmbeddedNonNullPointers: public BasicOopIterateClosure { 1665 void* _start; 1666 BitMap *_oopmap; 1667 int _num_total_oops; 1668 int _num_null_oops; 1669 public: 1670 FindEmbeddedNonNullPointers(void* start, BitMap* oopmap) 1671 : _start(start), _oopmap(oopmap), _num_total_oops(0), _num_null_oops(0) {} 1672 1673 virtual void do_oop(narrowOop* p) { 1674 assert(UseCompressedOops, "sanity"); 1675 _num_total_oops ++; 1676 narrowOop v = *p; 1677 if (!CompressedOops::is_null(v)) { 1678 size_t idx = p - (narrowOop*)_start; 1679 _oopmap->set_bit(idx); 1680 } else { 1681 _num_null_oops ++; 1682 } 1683 } 1684 virtual void do_oop(oop* p) { 1685 assert(!UseCompressedOops, "sanity"); 1686 _num_total_oops ++; 1687 if ((*p) != nullptr) { 1688 size_t idx = p - (oop*)_start; 1689 _oopmap->set_bit(idx); 1690 } else { 1691 _num_null_oops ++; 1692 } 1693 } 1694 int num_total_oops() const { return _num_total_oops; } 1695 int num_null_oops() const { return _num_null_oops; } 1696 }; 1697 #endif 1698 1699 void HeapShared::count_allocation(size_t size) { 1700 _total_obj_count ++; 1701 _total_obj_size += size; 1702 for (int i = 0; i < ALLOC_STAT_SLOTS; i++) { 1703 if (size <= (size_t(1) << i)) { 1704 _alloc_count[i] ++; 1705 _alloc_size[i] += size; 1706 return; 1707 } 1708 } 1709 } 1710 1711 static double avg_size(size_t size, size_t count) { 1712 double avg = 0; 1713 if (count > 0) { 1714 avg = double(size * HeapWordSize) / double(count); 1715 } 1716 return avg; 1717 } 1718 1719 void HeapShared::print_stats() { 1720 size_t huge_count = _total_obj_count; 1721 size_t huge_size = _total_obj_size; 1722 1723 for (int i = 0; i < ALLOC_STAT_SLOTS; i++) { 1724 size_t byte_size_limit = (size_t(1) << i) * HeapWordSize; 1725 size_t count = _alloc_count[i]; 1726 size_t size = _alloc_size[i]; 1727 log_info(cds, heap)(SIZE_FORMAT_W(8) " objects are <= " SIZE_FORMAT_W(-6) 1728 " bytes (total " SIZE_FORMAT_W(8) " bytes, avg %8.1f bytes)", 1729 count, byte_size_limit, size * HeapWordSize, avg_size(size, count)); 1730 huge_count -= count; 1731 huge_size -= size; 1732 } 1733 1734 log_info(cds, heap)(SIZE_FORMAT_W(8) " huge objects (total " SIZE_FORMAT_W(8) " bytes" 1735 ", avg %8.1f bytes)", 1736 huge_count, huge_size * HeapWordSize, 1737 avg_size(huge_size, huge_count)); 1738 log_info(cds, heap)(SIZE_FORMAT_W(8) " total objects (total " SIZE_FORMAT_W(8) " bytes" 1739 ", avg %8.1f bytes)", 1740 _total_obj_count, _total_obj_size * HeapWordSize, 1741 avg_size(_total_obj_size, _total_obj_count)); 1742 } 1743 1744 bool HeapShared::is_archived_boot_layer_available(JavaThread* current) { 1745 TempNewSymbol klass_name = SymbolTable::new_symbol(ARCHIVED_BOOT_LAYER_CLASS); 1746 InstanceKlass* k = SystemDictionary::find_instance_klass(current, klass_name, Handle(), Handle()); 1747 if (k == nullptr) { 1748 return false; 1749 } else { 1750 TempNewSymbol field_name = SymbolTable::new_symbol(ARCHIVED_BOOT_LAYER_FIELD); 1751 TempNewSymbol field_signature = SymbolTable::new_symbol("Ljdk/internal/module/ArchivedBootLayer;"); 1752 fieldDescriptor fd; 1753 if (k->find_field(field_name, field_signature, true, &fd) != nullptr) { 1754 oop m = k->java_mirror(); 1755 oop f = m->obj_field(fd.offset()); 1756 if (CompressedOops::is_null(f)) { 1757 return false; 1758 } 1759 } else { 1760 return false; 1761 } 1762 } 1763 return true; 1764 } 1765 1766 #endif // INCLUDE_CDS_JAVA_HEAP