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