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