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