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