1 /*
   2  * Copyright (c) 2014, 2025, 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 "cds/aotClassFilter.hpp"
  26 #include "cds/aotClassLocation.hpp"
  27 #include "cds/archiveBuilder.hpp"
  28 #include "cds/archiveUtils.hpp"
  29 #include "cds/cdsConfig.hpp"
  30 #include "cds/cdsProtectionDomain.hpp"
  31 #include "cds/classListParser.hpp"
  32 #include "cds/classListWriter.hpp"
  33 #include "cds/dumpTimeClassInfo.inline.hpp"
  34 #include "cds/dynamicArchive.hpp"
  35 #include "cds/filemap.hpp"
  36 #include "cds/heapShared.hpp"
  37 #include "cds/lambdaProxyClassDictionary.hpp"
  38 #include "cds/lambdaFormInvokers.inline.hpp"
  39 #include "cds/metaspaceShared.hpp"
  40 #include "cds/runTimeClassInfo.hpp"
  41 #include "cds/unregisteredClasses.hpp"
  42 #include "classfile/classFileStream.hpp"
  43 #include "classfile/classLoader.hpp"
  44 #include "classfile/classLoaderData.inline.hpp"
  45 #include "classfile/classLoaderDataGraph.hpp"
  46 #include "classfile/classLoaderExt.hpp"
  47 #include "classfile/dictionary.hpp"
  48 #include "classfile/javaClasses.hpp"
  49 #include "classfile/javaClasses.inline.hpp"
  50 #include "classfile/symbolTable.hpp"
  51 #include "classfile/systemDictionary.hpp"
  52 #include "classfile/systemDictionaryShared.hpp"
  53 #include "classfile/verificationType.hpp"
  54 #include "classfile/vmClasses.hpp"
  55 #include "classfile/vmSymbols.hpp"
  56 #include "jfr/jfrEvents.hpp"
  57 #include "logging/log.hpp"
  58 #include "logging/logStream.hpp"
  59 #include "memory/allocation.hpp"
  60 #include "memory/metadataFactory.hpp"
  61 #include "memory/metaspaceClosure.hpp"
  62 #include "memory/oopFactory.hpp"
  63 #include "memory/resourceArea.hpp"
  64 #include "memory/universe.hpp"
  65 #include "oops/compressedKlass.inline.hpp"
  66 #include "oops/instanceKlass.hpp"
  67 #include "oops/klass.inline.hpp"
  68 #include "oops/objArrayKlass.hpp"
  69 #include "oops/objArrayOop.inline.hpp"
  70 #include "oops/oop.inline.hpp"
  71 #include "oops/oopHandle.inline.hpp"
  72 #include "oops/typeArrayOop.inline.hpp"
  73 #include "runtime/arguments.hpp"
  74 #include "runtime/handles.inline.hpp"
  75 #include "runtime/java.hpp"
  76 #include "runtime/javaCalls.hpp"
  77 #include "runtime/mutexLocker.hpp"
  78 #include "utilities/resourceHash.hpp"
  79 #include "utilities/stringUtils.hpp"
  80 
  81 SystemDictionaryShared::ArchiveInfo SystemDictionaryShared::_static_archive;
  82 SystemDictionaryShared::ArchiveInfo SystemDictionaryShared::_dynamic_archive;
  83 
  84 DumpTimeSharedClassTable* SystemDictionaryShared::_dumptime_table = nullptr;
  85 
  86 // Used by NoClassLoadingMark
  87 DEBUG_ONLY(bool SystemDictionaryShared::_class_loading_may_happen = true;)
  88 
  89 #ifdef ASSERT
  90 static void check_klass_after_loading(const Klass* k) {
  91 #ifdef _LP64
  92   if (k != nullptr && UseCompressedClassPointers && k->needs_narrow_id()) {
  93     CompressedKlassPointers::check_encodable(k);
  94   }
  95 #endif
  96 }
  97 #endif
  98 
  99 InstanceKlass* SystemDictionaryShared::load_shared_class_for_builtin_loader(
 100                  Symbol* class_name, Handle class_loader, TRAPS) {
 101   assert(CDSConfig::is_using_archive(), "must be");
 102   InstanceKlass* ik = find_builtin_class(class_name);
 103 
 104   if (ik != nullptr && !ik->shared_loading_failed()) {
 105     if ((SystemDictionary::is_system_class_loader(class_loader()) && ik->is_shared_app_class())  ||
 106         (SystemDictionary::is_platform_class_loader(class_loader()) && ik->is_shared_platform_class())) {
 107       SharedClassLoadingMark slm(THREAD, ik);
 108       PackageEntry* pkg_entry = CDSProtectionDomain::get_package_entry_from_class(ik, class_loader);
 109       Handle protection_domain =
 110         CDSProtectionDomain::init_security_info(class_loader, ik, pkg_entry, CHECK_NULL);
 111       return load_shared_class(ik, class_loader, protection_domain, nullptr, pkg_entry, THREAD);
 112     }
 113   }
 114   return nullptr;
 115 }
 116 
 117 // This function is called for loading only UNREGISTERED classes
 118 InstanceKlass* SystemDictionaryShared::lookup_from_stream(Symbol* class_name,
 119                                                           Handle class_loader,
 120                                                           Handle protection_domain,
 121                                                           const ClassFileStream* cfs,
 122                                                           TRAPS) {
 123   if (!CDSConfig::is_using_archive()) {
 124     return nullptr;
 125   }
 126   if (class_name == nullptr) {  // don't do this for hidden classes
 127     return nullptr;
 128   }
 129   if (class_loader.is_null() ||
 130       SystemDictionary::is_system_class_loader(class_loader()) ||
 131       SystemDictionary::is_platform_class_loader(class_loader())) {
 132     // Do nothing for the BUILTIN loaders.
 133     return nullptr;
 134   }
 135 
 136   const RunTimeClassInfo* record = find_record(&_static_archive._unregistered_dictionary,
 137                                                &_dynamic_archive._unregistered_dictionary,
 138                                                class_name);
 139   if (record == nullptr) {
 140     return nullptr;
 141   }
 142 
 143   int clsfile_size  = cfs->length();
 144   int clsfile_crc32 = ClassLoader::crc32(0, (const char*)cfs->buffer(), cfs->length());
 145 
 146   if (!record->matches(clsfile_size, clsfile_crc32)) {
 147     return nullptr;
 148   }
 149 
 150   return acquire_class_for_current_thread(record->klass(), class_loader,
 151                                           protection_domain, cfs,
 152                                           THREAD);
 153 }
 154 
 155 InstanceKlass* SystemDictionaryShared::acquire_class_for_current_thread(
 156                    InstanceKlass *ik,
 157                    Handle class_loader,
 158                    Handle protection_domain,
 159                    const ClassFileStream *cfs,
 160                    TRAPS) {
 161   ClassLoaderData* loader_data = ClassLoaderData::class_loader_data(class_loader());
 162 
 163   {
 164     MutexLocker mu(THREAD, SharedDictionary_lock);
 165     if (ik->class_loader_data() != nullptr) {
 166       //    ik is already loaded (by this loader or by a different loader)
 167       // or ik is being loaded by a different thread (by this loader or by a different loader)
 168       return nullptr;
 169     }
 170 
 171     // No other thread has acquired this yet, so give it to *this thread*
 172     ik->set_class_loader_data(loader_data);
 173   }
 174 
 175   // No longer holding SharedDictionary_lock
 176   // No need to lock, as <ik> can be held only by a single thread.
 177   loader_data->add_class(ik);
 178 
 179   // Get the package entry.
 180   PackageEntry* pkg_entry = CDSProtectionDomain::get_package_entry_from_class(ik, class_loader);
 181 
 182   // Load and check super/interfaces, restore unshareable info
 183   InstanceKlass* shared_klass = load_shared_class(ik, class_loader, protection_domain,
 184                                                   cfs, pkg_entry, THREAD);
 185   if (shared_klass == nullptr || HAS_PENDING_EXCEPTION) {
 186     // TODO: clean up <ik> so it can be used again
 187     return nullptr;
 188   }
 189 
 190   return shared_klass;
 191 }
 192 
 193 // Guaranteed to return non-null value for non-shared classes.
 194 // k must not be a shared class.
 195 DumpTimeClassInfo* SystemDictionaryShared::get_info(InstanceKlass* k) {
 196   MutexLocker ml(DumpTimeTable_lock, Mutex::_no_safepoint_check_flag);
 197   return get_info_locked(k);
 198 }
 199 
 200 DumpTimeClassInfo* SystemDictionaryShared::get_info_locked(InstanceKlass* k) {
 201   assert_lock_strong(DumpTimeTable_lock);
 202   DumpTimeClassInfo* info = _dumptime_table->get_info(k);
 203   assert(info != nullptr, "must be");
 204   return info;
 205 }
 206 
 207 bool SystemDictionaryShared::check_for_exclusion(InstanceKlass* k, DumpTimeClassInfo* info) {
 208   if (CDSConfig::is_dumping_dynamic_archive() && MetaspaceShared::is_in_shared_metaspace(k)) {
 209     // We have reached a super type that's already in the base archive. Treat it
 210     // as "not excluded".
 211     return false;
 212   }
 213 
 214   if (info == nullptr) {
 215     info = _dumptime_table->get(k);
 216     assert(info != nullptr, "supertypes of any classes in _dumptime_table must either be shared, or must also be in _dumptime_table");
 217   }
 218 
 219   if (!info->has_checked_exclusion()) {
 220     if (check_for_exclusion_impl(k)) {
 221       info->set_excluded();
 222     }
 223     info->set_has_checked_exclusion();
 224   }
 225 
 226   return info->is_excluded();
 227 }
 228 
 229 // Returns true so the caller can do:    return warn_excluded(".....");
 230 bool SystemDictionaryShared::warn_excluded(InstanceKlass* k, const char* reason) {
 231   ResourceMark rm;
 232   log_warning(cds)("Skipping %s: %s", k->name()->as_C_string(), reason);
 233   return true;
 234 }
 235 
 236 bool SystemDictionaryShared::is_jfr_event_class(InstanceKlass *k) {
 237   while (k) {
 238     if (k->name()->equals("jdk/internal/event/Event")) {
 239       return true;
 240     }
 241     k = k->java_super();
 242   }
 243   return false;
 244 }
 245 
 246 bool SystemDictionaryShared::is_early_klass(InstanceKlass* ik) {
 247   DumpTimeClassInfo* info = _dumptime_table->get(ik);
 248   return (info != nullptr) ? info->is_early_klass() : false;
 249 }
 250 
 251 bool SystemDictionaryShared::check_for_exclusion_impl(InstanceKlass* k) {
 252   if (CDSConfig::is_dumping_final_static_archive() && k->is_shared_unregistered_class()
 253       && k->is_shared()) {
 254     return false; // Do not exclude: unregistered classes are passed from preimage to final image.
 255   }
 256 
 257   if (k->is_in_error_state()) {
 258     return warn_excluded(k, "In error state");
 259   }
 260   if (k->is_scratch_class()) {
 261     return warn_excluded(k, "A scratch class");
 262   }
 263   if (!k->is_loaded()) {
 264     return warn_excluded(k, "Not in loaded state");
 265   }
 266   if (has_been_redefined(k)) {
 267     return warn_excluded(k, "Has been redefined");
 268   }
 269   if (!k->is_hidden() && k->shared_classpath_index() < 0 && is_builtin(k)) {
 270     if (k->name()->starts_with("java/lang/invoke/BoundMethodHandle$Species_")) {
 271       // This class is dynamically generated by the JDK
 272       if (CDSConfig::is_dumping_method_handles()) {
 273         k->set_shared_classpath_index(0);
 274       } else {
 275         ResourceMark rm;
 276         log_info(cds)("Skipping %s because it is dynamically generated", k->name()->as_C_string());
 277         return true; // exclude without warning
 278       }
 279     } else {
 280       // These are classes loaded from unsupported locations (such as those loaded by JVMTI native
 281       // agent during dump time).
 282       return warn_excluded(k, "Unsupported location");
 283     }
 284   }
 285   if (k->signers() != nullptr) {
 286     // We cannot include signed classes in the archive because the certificates
 287     // used during dump time may be different than those used during
 288     // runtime (due to expiration, etc).
 289     return warn_excluded(k, "Signed JAR");
 290   }
 291   if (is_jfr_event_class(k)) {
 292     // We cannot include JFR event classes because they need runtime-specific
 293     // instrumentation in order to work with -XX:FlightRecorderOptions:retransform=false.
 294     // There are only a small number of these classes, so it's not worthwhile to
 295     // support them and make CDS more complicated.
 296     return warn_excluded(k, "JFR event class");
 297   }
 298 
 299   if (!k->is_linked()) {
 300     if (has_class_failed_verification(k)) {
 301       return warn_excluded(k, "Failed verification");
 302     } else if (CDSConfig::is_dumping_aot_linked_classes()) {
 303       // Most loaded classes should have been speculatively linked by MetaspaceShared::link_class_for_cds().
 304       // However, we do not speculatively link old classes, as they are not recorded by
 305       // SystemDictionaryShared::record_linking_constraint(). As a result, such an unlinked
 306       // class may fail to verify in AOTLinkedClassBulkLoader::init_required_classes_for_loader(),
 307       // causing the JVM to fail at bootstrap.
 308       return warn_excluded(k, "Unlinked class not supported by AOTClassLinking");
 309     } else if (CDSConfig::is_dumping_preimage_static_archive()) {
 310       // When dumping the final static archive, we will unconditionally load and link all
 311       // classes from tje preimage. We don't want to get a VerifyError when linking this class.
 312       return warn_excluded(k, "Unlinked class not supported by AOTConfiguration");
 313     }
 314   } else {
 315     if (!k->can_be_verified_at_dumptime()) {
 316       // We have an old class that has been linked (e.g., it's been executed during
 317       // dump time). This class has been verified using the old verifier, which
 318       // doesn't save the verification constraints, so check_verification_constraints()
 319       // won't work at runtime.
 320       // As a result, we cannot store this class. It must be loaded and fully verified
 321       // at runtime.
 322       return warn_excluded(k, "Old class has been linked");
 323     }
 324   }
 325 
 326   InstanceKlass* super = k->java_super();
 327   if (super != nullptr && check_for_exclusion(super, nullptr)) {
 328     ResourceMark rm;
 329     log_warning(cds)("Skipping %s: super class %s is excluded", k->name()->as_C_string(), super->name()->as_C_string());
 330     return true;
 331   }
 332 
 333   Array<InstanceKlass*>* interfaces = k->local_interfaces();
 334   int len = interfaces->length();
 335   for (int i = 0; i < len; i++) {
 336     InstanceKlass* intf = interfaces->at(i);
 337     if (check_for_exclusion(intf, nullptr)) {
 338       ResourceMark rm;
 339       log_warning(cds)("Skipping %s: interface %s is excluded", k->name()->as_C_string(), intf->name()->as_C_string());
 340       return true;
 341     }
 342   }
 343 
 344   if (k == UnregisteredClasses::UnregisteredClassLoader_klass()) {
 345     ResourceMark rm;
 346     log_info(cds)("Skipping %s: used only when dumping CDS archive", k->name()->as_C_string());
 347     return true;
 348   }
 349 
 350   return false; // false == k should NOT be excluded
 351 }
 352 
 353 bool SystemDictionaryShared::is_builtin_loader(ClassLoaderData* loader_data) {
 354   oop class_loader = loader_data->class_loader();
 355   return (class_loader == nullptr ||
 356           SystemDictionary::is_system_class_loader(class_loader) ||
 357           SystemDictionary::is_platform_class_loader(class_loader));
 358 }
 359 
 360 bool SystemDictionaryShared::has_platform_or_app_classes() {
 361   if (FileMapInfo::current_info()->has_platform_or_app_classes()) {
 362     return true;
 363   }
 364   if (DynamicArchive::is_mapped() &&
 365       FileMapInfo::dynamic_info()->has_platform_or_app_classes()) {
 366     return true;
 367   }
 368   return false;
 369 }
 370 
 371 // The following stack shows how this code is reached:
 372 //
 373 //   [0] SystemDictionaryShared::find_or_load_shared_class()
 374 //   [1] JVM_FindLoadedClass
 375 //   [2] java.lang.ClassLoader.findLoadedClass0()
 376 //   [3] java.lang.ClassLoader.findLoadedClass()
 377 //   [4] jdk.internal.loader.BuiltinClassLoader.loadClassOrNull()
 378 //   [5] jdk.internal.loader.BuiltinClassLoader.loadClass()
 379 //   [6] jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(), or
 380 //       jdk.internal.loader.ClassLoaders$PlatformClassLoader.loadClass()
 381 //
 382 // AppCDS supports fast class loading for these 2 built-in class loaders:
 383 //    jdk.internal.loader.ClassLoaders$PlatformClassLoader
 384 //    jdk.internal.loader.ClassLoaders$AppClassLoader
 385 // with the following assumptions (based on the JDK core library source code):
 386 //
 387 // [a] these two loaders use the BuiltinClassLoader.loadClassOrNull() to
 388 //     load the named class.
 389 // [b] BuiltinClassLoader.loadClassOrNull() first calls findLoadedClass(name).
 390 // [c] At this point, if we can find the named class inside the
 391 //     shared_dictionary, we can perform further checks (see
 392 //     SystemDictionary::is_shared_class_visible) to ensure that this class
 393 //     was loaded by the same class loader during dump time.
 394 //
 395 // Given these assumptions, we intercept the findLoadedClass() call to invoke
 396 // SystemDictionaryShared::find_or_load_shared_class() to load the shared class from
 397 // the archive for the 2 built-in class loaders. This way,
 398 // we can improve start-up because we avoid decoding the classfile,
 399 // and avoid delegating to the parent loader.
 400 //
 401 // NOTE: there's a lot of assumption about the Java code. If any of that change, this
 402 // needs to be redesigned.
 403 
 404 InstanceKlass* SystemDictionaryShared::find_or_load_shared_class(
 405                  Symbol* name, Handle class_loader, TRAPS) {
 406   InstanceKlass* k = nullptr;
 407   if (CDSConfig::is_using_archive()) {
 408     if (!has_platform_or_app_classes()) {
 409       return nullptr;
 410     }
 411 
 412     if (SystemDictionary::is_system_class_loader(class_loader()) ||
 413         SystemDictionary::is_platform_class_loader(class_loader())) {
 414       ClassLoaderData *loader_data = register_loader(class_loader);
 415       Dictionary* dictionary = loader_data->dictionary();
 416 
 417       // Note: currently, find_or_load_shared_class is called only from
 418       // JVM_FindLoadedClass and used for PlatformClassLoader and AppClassLoader,
 419       // which are parallel-capable loaders, so a lock here is NOT taken.
 420       assert(get_loader_lock_or_null(class_loader) == nullptr, "ObjectLocker not required");
 421       {
 422         MutexLocker mu(THREAD, SystemDictionary_lock);
 423         InstanceKlass* check = dictionary->find_class(THREAD, name);
 424         if (check != nullptr) {
 425           return check;
 426         }
 427       }
 428 
 429       k = load_shared_class_for_builtin_loader(name, class_loader, THREAD);
 430       if (k != nullptr) {
 431         SharedClassLoadingMark slm(THREAD, k);
 432         k = find_or_define_instance_class(name, class_loader, k, CHECK_NULL);
 433       }
 434     }
 435   }
 436 
 437   DEBUG_ONLY(check_klass_after_loading(k);)
 438 
 439   return k;
 440 }
 441 
 442 class UnregisteredClassesTable : public ResourceHashtable<
 443   Symbol*, InstanceKlass*,
 444   15889, // prime number
 445   AnyObj::C_HEAP> {};
 446 
 447 static UnregisteredClassesTable* _unregistered_classes_table = nullptr;
 448 
 449 // true == class was successfully added; false == a duplicated class (with the same name) already exists.
 450 bool SystemDictionaryShared::add_unregistered_class(Thread* current, InstanceKlass* klass) {
 451   // We don't allow duplicated unregistered classes with the same name.
 452   // We only archive the first class with that name that succeeds putting
 453   // itself into the table.
 454   assert(CDSConfig::is_dumping_archive() || ClassListWriter::is_enabled(), "sanity");
 455   MutexLocker ml(current, UnregisteredClassesTable_lock, Mutex::_no_safepoint_check_flag);
 456   Symbol* name = klass->name();
 457   if (_unregistered_classes_table == nullptr) {
 458     _unregistered_classes_table = new (mtClass)UnregisteredClassesTable();
 459   }
 460   bool created;
 461   InstanceKlass** v = _unregistered_classes_table->put_if_absent(name, klass, &created);
 462   if (created) {
 463     name->increment_refcount();
 464   }
 465   return (klass == *v);
 466 }
 467 
 468 void SystemDictionaryShared::copy_unregistered_class_size_and_crc32(InstanceKlass* klass) {
 469   precond(CDSConfig::is_dumping_final_static_archive());
 470   precond(klass->is_shared());
 471 
 472   // A shared class must have a RunTimeClassInfo record
 473   const RunTimeClassInfo* record = find_record(&_static_archive._unregistered_dictionary,
 474                                                nullptr, klass->name());
 475   precond(record != nullptr);
 476   precond(record->klass() == klass);
 477 
 478   DumpTimeClassInfo* info = get_info(klass);
 479   info->_clsfile_size = record->crc()->_clsfile_size;
 480   info->_clsfile_crc32 = record->crc()->_clsfile_crc32;
 481 }
 482 
 483 void SystemDictionaryShared::set_shared_class_misc_info(InstanceKlass* k, ClassFileStream* cfs) {
 484   assert(CDSConfig::is_dumping_archive(), "sanity");
 485   assert(!is_builtin(k), "must be unregistered class");
 486   DumpTimeClassInfo* info = get_info(k);
 487   info->_clsfile_size  = cfs->length();
 488   info->_clsfile_crc32 = ClassLoader::crc32(0, (const char*)cfs->buffer(), cfs->length());
 489 }
 490 
 491 void SystemDictionaryShared::initialize() {
 492   if (CDSConfig::is_dumping_archive()) {
 493     _dumptime_table = new (mtClass) DumpTimeSharedClassTable;
 494     LambdaProxyClassDictionary::dumptime_init();
 495     if (CDSConfig::is_dumping_heap()) {
 496       HeapShared::init_dumping();
 497     }
 498   }
 499 }
 500 
 501 void SystemDictionaryShared::init_dumptime_info(InstanceKlass* k) {
 502   MutexLocker ml(DumpTimeTable_lock, Mutex::_no_safepoint_check_flag);
 503   assert(SystemDictionaryShared::class_loading_may_happen(), "sanity");
 504   DumpTimeClassInfo* info = _dumptime_table->allocate_info(k);
 505   if (AOTClassFilter::is_aot_tooling_class(k)) {
 506     info->set_is_aot_tooling_class();
 507   }
 508 }
 509 
 510 void SystemDictionaryShared::remove_dumptime_info(InstanceKlass* k) {
 511   MutexLocker ml(DumpTimeTable_lock, Mutex::_no_safepoint_check_flag);
 512   _dumptime_table->remove(k);
 513 }
 514 
 515 void SystemDictionaryShared::handle_class_unloading(InstanceKlass* klass) {
 516   if (CDSConfig::is_dumping_archive()) {
 517     remove_dumptime_info(klass);
 518   }
 519 
 520   if (CDSConfig::is_dumping_archive() || ClassListWriter::is_enabled()) {
 521     MutexLocker ml(Thread::current(), UnregisteredClassesTable_lock, Mutex::_no_safepoint_check_flag);
 522     if (_unregistered_classes_table != nullptr) {
 523       // Remove the class from _unregistered_classes_table: keep the entry but
 524       // set it to null. This ensure no classes with the same name can be
 525       // added again.
 526       InstanceKlass** v = _unregistered_classes_table->get(klass->name());
 527       if (v != nullptr) {
 528         *v = nullptr;
 529       }
 530     }
 531   } else {
 532     assert(_unregistered_classes_table == nullptr, "must not be used");
 533   }
 534 
 535   if (ClassListWriter::is_enabled()) {
 536     ClassListWriter cw;
 537     cw.handle_class_unloading((const InstanceKlass*)klass);
 538   }
 539 }
 540 
 541 void SystemDictionaryShared::init_dumptime_info_from_preimage(InstanceKlass* k) {
 542   init_dumptime_info(k);
 543   copy_verification_constraints_from_preimage(k);
 544   copy_linking_constraints_from_preimage(k);
 545 
 546   if (SystemDictionary::is_platform_class_loader(k->class_loader())) {
 547     AOTClassLocationConfig::dumptime_set_has_platform_classes();
 548   } else if (SystemDictionary::is_system_class_loader(k->class_loader())) {
 549     AOTClassLocationConfig::dumptime_set_has_app_classes();
 550   }
 551 }
 552 
 553 // Check if a class or any of its supertypes has been redefined.
 554 bool SystemDictionaryShared::has_been_redefined(InstanceKlass* k) {
 555   if (k->has_been_redefined()) {
 556     return true;
 557   }
 558   if (k->java_super() != nullptr && has_been_redefined(k->java_super())) {
 559     return true;
 560   }
 561   Array<InstanceKlass*>* interfaces = k->local_interfaces();
 562   int len = interfaces->length();
 563   for (int i = 0; i < len; i++) {
 564     if (has_been_redefined(interfaces->at(i))) {
 565       return true;
 566     }
 567   }
 568   return false;
 569 }
 570 
 571 // k is a class before relocating by ArchiveBuilder
 572 void SystemDictionaryShared::validate_before_archiving(InstanceKlass* k) {
 573   ResourceMark rm;
 574   const char* name = k->name()->as_C_string();
 575   DumpTimeClassInfo* info = _dumptime_table->get(k);
 576   assert(!class_loading_may_happen(), "class loading must be disabled");
 577   guarantee(info != nullptr, "Class %s must be entered into _dumptime_table", name);
 578   guarantee(!info->is_excluded(), "Should not attempt to archive excluded class %s", name);
 579   if (is_builtin(k)) {
 580     if (k->is_hidden()) {
 581       if (CDSConfig::is_dumping_lambdas_in_legacy_mode()) {
 582         assert(LambdaProxyClassDictionary::is_registered_lambda_proxy_class(k), "unexpected hidden class %s", name);
 583       }
 584     }
 585     guarantee(!k->is_shared_unregistered_class(),
 586               "Class loader type must be set for BUILTIN class %s", name);
 587 
 588   } else {
 589     guarantee(k->is_shared_unregistered_class(),
 590               "Class loader type must not be set for UNREGISTERED class %s", name);
 591   }
 592 }
 593 
 594 class UnregisteredClassesDuplicationChecker : StackObj {
 595   GrowableArray<InstanceKlass*> _list;
 596   Thread* _thread;
 597 public:
 598   UnregisteredClassesDuplicationChecker() : _thread(Thread::current()) {}
 599 
 600   void do_entry(InstanceKlass* k, DumpTimeClassInfo& info) {
 601     if (!SystemDictionaryShared::is_builtin(k)) {
 602       _list.append(k);
 603     }
 604   }
 605 
 606   static int compare_by_loader(InstanceKlass** a, InstanceKlass** b) {
 607     ClassLoaderData* loader_a = a[0]->class_loader_data();
 608     ClassLoaderData* loader_b = b[0]->class_loader_data();
 609 
 610     if (loader_a != loader_b) {
 611       return primitive_compare(loader_a, loader_b);
 612     } else {
 613       return primitive_compare(a[0], b[0]);
 614     }
 615   }
 616 
 617   void mark_duplicated_classes() {
 618     // Two loaders may load two identical or similar hierarchies of classes. If we
 619     // check for duplication in random order, we may end up excluding important base classes
 620     // in both hierarchies, causing most of the classes to be excluded.
 621     // We sort the classes by their loaders. This way we're likely to archive
 622     // all classes in the one of the two hierarchies.
 623     _list.sort(compare_by_loader);
 624     for (int i = 0; i < _list.length(); i++) {
 625       InstanceKlass* k = _list.at(i);
 626       bool i_am_first = SystemDictionaryShared::add_unregistered_class(_thread, k);
 627       if (!i_am_first) {
 628         SystemDictionaryShared::warn_excluded(k, "Duplicated unregistered class");
 629         SystemDictionaryShared::set_excluded_locked(k);
 630       }
 631     }
 632   }
 633 };
 634 
 635 // Returns true if the class should be excluded. This can be called by
 636 // AOTConstantPoolResolver before or after we enter the CDS safepoint.
 637 // When called before the safepoint, we need to link the class so that
 638 // it can be checked by check_for_exclusion().
 639 bool SystemDictionaryShared::should_be_excluded(Klass* k) {
 640   assert(CDSConfig::is_dumping_archive(), "sanity");
 641   assert(CDSConfig::current_thread_is_vm_or_dumper(), "sanity");
 642 
 643   if (k->is_objArray_klass()) {
 644     return should_be_excluded(ObjArrayKlass::cast(k)->bottom_klass());
 645   }
 646 
 647   if (!k->is_instance_klass()) {
 648     return false;
 649   } else {
 650     InstanceKlass* ik = InstanceKlass::cast(k);
 651 
 652     if (!SafepointSynchronize::is_at_safepoint()) {
 653       if (!ik->is_linked()) {
 654         // check_for_exclusion() below doesn't link unlinked classes. We come
 655         // here only when we are trying to aot-link constant pool entries, so
 656         // we'd better link the class.
 657         JavaThread* THREAD = JavaThread::current();
 658         ik->link_class(THREAD);
 659         if (HAS_PENDING_EXCEPTION) {
 660           CLEAR_PENDING_EXCEPTION;
 661           return true; // linking failed -- let's exclude it
 662         }
 663       }
 664 
 665       MutexLocker ml(DumpTimeTable_lock, Mutex::_no_safepoint_check_flag);
 666       DumpTimeClassInfo* p = get_info_locked(ik);
 667       if (p->is_excluded()) {
 668         return true;
 669       }
 670       return check_for_exclusion(ik, p);
 671     } else {
 672       // No need to check for is_linked() as all eligible classes should have
 673       // already been linked in MetaspaceShared::link_class_for_cds().
 674       // Can't take the lock as we are in safepoint.
 675       DumpTimeClassInfo* p = _dumptime_table->get(ik);
 676       if (p->is_excluded()) {
 677         return true;
 678       }
 679       return check_for_exclusion(ik, p);
 680     }
 681   }
 682 }
 683 
 684 void SystemDictionaryShared::finish_exclusion_checks() {
 685   if (CDSConfig::is_dumping_dynamic_archive() || CDSConfig::is_dumping_preimage_static_archive()) {
 686     // Do this first -- if a base class is excluded due to duplication,
 687     // all of its subclasses will also be excluded.
 688     ResourceMark rm;
 689     UnregisteredClassesDuplicationChecker dup_checker;
 690     _dumptime_table->iterate_all_live_classes(&dup_checker);
 691     dup_checker.mark_duplicated_classes();
 692   }
 693 
 694   _dumptime_table->iterate_all_live_classes([&] (InstanceKlass* k, DumpTimeClassInfo& info) {
 695     SystemDictionaryShared::check_for_exclusion(k, &info);
 696   });
 697 
 698   _dumptime_table->update_counts();
 699   if (CDSConfig::is_dumping_lambdas_in_legacy_mode()) {
 700     LambdaProxyClassDictionary::cleanup_dumptime_table();
 701   }
 702 }
 703 
 704 bool SystemDictionaryShared::is_excluded_class(InstanceKlass* k) {
 705   assert(!class_loading_may_happen(), "class loading must be disabled");
 706   assert_lock_strong(DumpTimeTable_lock);
 707   assert(CDSConfig::is_dumping_archive(), "sanity");
 708   DumpTimeClassInfo* p = get_info_locked(k);
 709   return p->is_excluded();
 710 }
 711 
 712 void SystemDictionaryShared::set_excluded_locked(InstanceKlass* k) {
 713   assert_lock_strong(DumpTimeTable_lock);
 714   assert(CDSConfig::is_dumping_archive(), "sanity");
 715   DumpTimeClassInfo* info = get_info_locked(k);
 716   info->set_excluded();
 717 }
 718 
 719 void SystemDictionaryShared::set_excluded(InstanceKlass* k) {
 720   assert(CDSConfig::is_dumping_archive(), "sanity");
 721   DumpTimeClassInfo* info = get_info(k);
 722   info->set_excluded();
 723 }
 724 
 725 void SystemDictionaryShared::set_class_has_failed_verification(InstanceKlass* ik) {
 726   assert(CDSConfig::is_dumping_archive(), "sanity");
 727   DumpTimeClassInfo* p = get_info(ik);
 728   p->set_failed_verification();
 729 }
 730 
 731 bool SystemDictionaryShared::has_class_failed_verification(InstanceKlass* ik) {
 732   assert(CDSConfig::is_dumping_archive(), "sanity");
 733   DumpTimeClassInfo* p = _dumptime_table->get(ik);
 734   return (p == nullptr) ? false : p->failed_verification();
 735 }
 736 
 737 void SystemDictionaryShared::dumptime_classes_do(MetaspaceClosure* it) {
 738   assert_lock_strong(DumpTimeTable_lock);
 739 
 740   auto do_klass = [&] (InstanceKlass* k, DumpTimeClassInfo& info) {
 741     if (CDSConfig::is_dumping_final_static_archive() && !k->is_loaded()) {
 742       assert(k->is_shared_unregistered_class(), "must be");
 743       info.metaspace_pointers_do(it);
 744     } else if (k->is_loader_alive() && !info.is_excluded()) {
 745       info.metaspace_pointers_do(it);
 746     }
 747   };
 748   _dumptime_table->iterate_all_live_classes(do_klass);
 749 
 750   if (CDSConfig::is_dumping_lambdas_in_legacy_mode()) {
 751     LambdaProxyClassDictionary::dumptime_classes_do(it);
 752   }
 753 }
 754 
 755 bool SystemDictionaryShared::add_verification_constraint(InstanceKlass* k, Symbol* name,
 756          Symbol* from_name, bool from_field_is_protected, bool from_is_array, bool from_is_object) {
 757   assert(CDSConfig::is_dumping_archive(), "sanity");
 758   DumpTimeClassInfo* info = get_info(k);
 759   info->add_verification_constraint(k, name, from_name, from_field_is_protected,
 760                                     from_is_array, from_is_object);
 761 
 762   if (CDSConfig::is_dumping_dynamic_archive()) {
 763     // For dynamic dumping, we can resolve all the constraint classes for all class loaders during
 764     // the initial run prior to creating the archive before vm exit. We will also perform verification
 765     // check when running with the archive.
 766     return false;
 767   } else {
 768     if (is_builtin(k)) {
 769       // For builtin class loaders, we can try to complete the verification check at dump time,
 770       // because we can resolve all the constraint classes. We will also perform verification check
 771       // when running with the archive.
 772       return false;
 773     } else {
 774       // For non-builtin class loaders, we cannot complete the verification check at dump time,
 775       // because at dump time we don't know how to resolve classes for such loaders.
 776       return true;
 777     }
 778   }
 779 }
 780 
 781 void SystemDictionaryShared::add_enum_klass_static_field(InstanceKlass* ik, int root_index) {
 782   assert(CDSConfig::is_dumping_heap(), "sanity");
 783   DumpTimeClassInfo* info = get_info_locked(ik);
 784   info->add_enum_klass_static_field(root_index);
 785 }
 786 
 787 void SystemDictionaryShared::check_verification_constraints(InstanceKlass* klass,
 788                                                             TRAPS) {
 789   assert(CDSConfig::is_using_archive(), "called at run time with CDS enabled only");
 790   RunTimeClassInfo* record = RunTimeClassInfo::get_for(klass);
 791 
 792   int length = record->num_verifier_constraints();
 793   if (length > 0) {
 794     for (int i = 0; i < length; i++) {
 795       RunTimeClassInfo::RTVerifierConstraint* vc = record->verifier_constraint_at(i);
 796       Symbol* name      = vc->name();
 797       Symbol* from_name = vc->from_name();
 798 
 799       if (log_is_enabled(Trace, cds, verification)) {
 800         ResourceMark rm(THREAD);
 801         log_trace(cds, verification)("check_verification_constraint: %s: %s must be subclass of %s [0x%x]",
 802                                      klass->external_name(), from_name->as_klass_external_name(),
 803                                      name->as_klass_external_name(), record->verifier_constraint_flag(i));
 804       }
 805 
 806       bool ok = VerificationType::resolve_and_check_assignability(klass, name, from_name,
 807          record->from_field_is_protected(i), record->from_is_array(i), record->from_is_object(i), CHECK);
 808       if (!ok) {
 809         ResourceMark rm(THREAD);
 810         stringStream ss;
 811 
 812         ss.print_cr("Bad type on operand stack");
 813         ss.print_cr("Exception Details:");
 814         ss.print_cr("  Location:\n    %s", klass->name()->as_C_string());
 815         ss.print_cr("  Reason:\n    Type '%s' is not assignable to '%s'",
 816                     from_name->as_quoted_ascii(), name->as_quoted_ascii());
 817         THROW_MSG(vmSymbols::java_lang_VerifyError(), ss.as_string());
 818       }
 819     }
 820   }
 821 }
 822 
 823 void SystemDictionaryShared::copy_verification_constraints_from_preimage(InstanceKlass* klass) {
 824   assert(CDSConfig::is_using_archive(), "called at run time with CDS enabled only");
 825   DumpTimeClassInfo* dt_info = get_info(klass);
 826   RunTimeClassInfo* rt_info = RunTimeClassInfo::get_for(klass); // from preimage
 827 
 828   int length = rt_info->num_verifier_constraints();
 829   if (length > 0) {
 830     for (int i = 0; i < length; i++) {
 831       RunTimeClassInfo::RTVerifierConstraint* vc = rt_info->verifier_constraint_at(i);
 832       Symbol* name      = vc->name();
 833       Symbol* from_name = vc->from_name();
 834 
 835       dt_info->add_verification_constraint(klass, name, from_name,
 836          rt_info->from_field_is_protected(i), rt_info->from_is_array(i), rt_info->from_is_object(i));
 837     }
 838   }
 839 }
 840 
 841 static oop get_class_loader_by(char type) {
 842   if (type == (char)ClassLoader::BOOT_LOADER) {
 843     return (oop)nullptr;
 844   } else if (type == (char)ClassLoader::PLATFORM_LOADER) {
 845     return SystemDictionary::java_platform_loader();
 846   } else {
 847     assert (type == (char)ClassLoader::APP_LOADER, "Sanity");
 848     return SystemDictionary::java_system_loader();
 849   }
 850 }
 851 
 852 // Record class loader constraints that are checked inside
 853 // InstanceKlass::link_class(), so that these can be checked quickly
 854 // at runtime without laying out the vtable/itables.
 855 void SystemDictionaryShared::record_linking_constraint(Symbol* name, InstanceKlass* klass,
 856                                                     Handle loader1, Handle loader2) {
 857   // A linking constraint check is executed when:
 858   //   - klass extends or implements type S
 859   //   - klass overrides method S.M(...) with X.M
 860   //     - If klass defines the method M, X is
 861   //       the same as klass.
 862   //     - If klass does not define the method M,
 863   //       X must be a supertype of klass and X.M is
 864   //       a default method defined by X.
 865   //   - loader1 = X->class_loader()
 866   //   - loader2 = S->class_loader()
 867   //   - loader1 != loader2
 868   //   - M's parameter(s) include an object type T
 869   // We require that
 870   //   - whenever loader1 and loader2 try to
 871   //     resolve the type T, they must always resolve to
 872   //     the same InstanceKlass.
 873   // NOTE: type T may or may not be currently resolved in
 874   // either of these two loaders. The check itself does not
 875   // try to resolve T.
 876   oop klass_loader = klass->class_loader();
 877 
 878   if (!is_system_class_loader(klass_loader) &&
 879       !is_platform_class_loader(klass_loader)) {
 880     // If klass is loaded by system/platform loaders, we can
 881     // guarantee that klass and S must be loaded by the same
 882     // respective loader between dump time and run time, and
 883     // the exact same check on (name, loader1, loader2) will
 884     // be executed. Hence, we can cache this check and execute
 885     // it at runtime without walking the vtable/itables.
 886     //
 887     // This cannot be guaranteed for classes loaded by other
 888     // loaders, so we bail.
 889     return;
 890   }
 891 
 892   assert(is_builtin(klass), "must be");
 893   assert(klass_loader != nullptr, "should not be called for boot loader");
 894   assert(loader1 != loader2, "must be");
 895 
 896   if (CDSConfig::is_dumping_dynamic_archive() && Thread::current()->is_VM_thread()) {
 897     // We are re-laying out the vtable/itables of the *copy* of
 898     // a class during the final stage of dynamic dumping. The
 899     // linking constraints for this class has already been recorded.
 900     return;
 901   }
 902   assert(!Thread::current()->is_VM_thread(), "must be");
 903 
 904   assert(CDSConfig::is_dumping_archive(), "sanity");
 905   DumpTimeClassInfo* info = get_info(klass);
 906   info->record_linking_constraint(name, loader1, loader2);
 907 }
 908 
 909 // returns true IFF there's no need to re-initialize the i/v-tables for klass for
 910 // the purpose of checking class loader constraints.
 911 bool SystemDictionaryShared::check_linking_constraints(Thread* current, InstanceKlass* klass) {
 912   assert(CDSConfig::is_using_archive(), "called at run time with CDS enabled only");
 913   LogTarget(Info, class, loader, constraints) log;
 914   if (klass->is_shared_boot_class()) {
 915     // No class loader constraint check performed for boot classes.
 916     return true;
 917   }
 918   if (klass->is_shared_platform_class() || klass->is_shared_app_class()) {
 919     RunTimeClassInfo* info = RunTimeClassInfo::get_for(klass);
 920     assert(info != nullptr, "Sanity");
 921     if (info->num_loader_constraints() > 0) {
 922       HandleMark hm(current);
 923       for (int i = 0; i < info->num_loader_constraints(); i++) {
 924         RunTimeClassInfo::RTLoaderConstraint* lc = info->loader_constraint_at(i);
 925         Symbol* name = lc->constraint_name();
 926         Handle loader1(current, get_class_loader_by(lc->_loader_type1));
 927         Handle loader2(current, get_class_loader_by(lc->_loader_type2));
 928         if (log.is_enabled()) {
 929           ResourceMark rm(current);
 930           log.print("[CDS add loader constraint for class %s symbol %s loader[0] %s loader[1] %s",
 931                     klass->external_name(), name->as_C_string(),
 932                     ClassLoaderData::class_loader_data(loader1())->loader_name_and_id(),
 933                     ClassLoaderData::class_loader_data(loader2())->loader_name_and_id());
 934         }
 935         if (!SystemDictionary::add_loader_constraint(name, klass, loader1, loader2)) {
 936           // Loader constraint violation has been found. The caller
 937           // will re-layout the vtable/itables to produce the correct
 938           // exception.
 939           if (log.is_enabled()) {
 940             log.print(" failed]");
 941           }
 942           return false;
 943         }
 944         if (log.is_enabled()) {
 945             log.print(" succeeded]");
 946         }
 947       }
 948       return true; // for all recorded constraints added successfully.
 949     }
 950   }
 951   if (log.is_enabled()) {
 952     ResourceMark rm(current);
 953     log.print("[CDS has not recorded loader constraint for class %s]", klass->external_name());
 954   }
 955   return false;
 956 }
 957 
 958 void SystemDictionaryShared::copy_linking_constraints_from_preimage(InstanceKlass* klass) {
 959   assert(CDSConfig::is_using_archive(), "called at run time with CDS enabled only");
 960   JavaThread* current = JavaThread::current();
 961   if (klass->is_shared_platform_class() || klass->is_shared_app_class()) {
 962     RunTimeClassInfo* rt_info = RunTimeClassInfo::get_for(klass); // from preimage
 963 
 964     if (rt_info->num_loader_constraints() > 0) {
 965       for (int i = 0; i < rt_info->num_loader_constraints(); i++) {
 966         RunTimeClassInfo::RTLoaderConstraint* lc = rt_info->loader_constraint_at(i);
 967         Symbol* name = lc->constraint_name();
 968         Handle loader1(current, get_class_loader_by(lc->_loader_type1));
 969         Handle loader2(current, get_class_loader_by(lc->_loader_type2));
 970         record_linking_constraint(name, klass, loader1, loader2);
 971       }
 972     }
 973   }
 974 }
 975 
 976 unsigned int SystemDictionaryShared::hash_for_shared_dictionary(address ptr) {
 977   if (ArchiveBuilder::is_active()) {
 978     uintx offset = ArchiveBuilder::current()->any_to_offset(ptr);
 979     unsigned int hash = primitive_hash<uintx>(offset);
 980     DEBUG_ONLY({
 981         if (MetaspaceObj::is_shared((const MetaspaceObj*)ptr)) {
 982           assert(hash == SystemDictionaryShared::hash_for_shared_dictionary_quick(ptr), "must be");
 983         }
 984       });
 985     return hash;
 986   } else {
 987     return SystemDictionaryShared::hash_for_shared_dictionary_quick(ptr);
 988   }
 989 }
 990 
 991 class CopySharedClassInfoToArchive : StackObj {
 992   CompactHashtableWriter* _writer;
 993   bool _is_builtin;
 994   ArchiveBuilder *_builder;
 995 public:
 996   CopySharedClassInfoToArchive(CompactHashtableWriter* writer,
 997                                bool is_builtin)
 998     : _writer(writer), _is_builtin(is_builtin), _builder(ArchiveBuilder::current()) {}
 999 
1000   void do_entry(InstanceKlass* k, DumpTimeClassInfo& info) {
1001     if (!info.is_excluded() && info.is_builtin() == _is_builtin) {
1002       size_t byte_size = info.runtime_info_bytesize();
1003       RunTimeClassInfo* record;
1004       record = (RunTimeClassInfo*)ArchiveBuilder::ro_region_alloc(byte_size);
1005       record->init(info);
1006 
1007       unsigned int hash;
1008       Symbol* name = info._klass->name();
1009       name = ArchiveBuilder::current()->get_buffered_addr(name);
1010       hash = SystemDictionaryShared::hash_for_shared_dictionary((address)name);
1011       u4 delta = _builder->buffer_to_offset_u4((address)record);
1012       if (_is_builtin && info._klass->is_hidden()) {
1013         // skip
1014       } else {
1015         _writer->add(hash, delta);
1016       }
1017       if (log_is_enabled(Trace, cds, hashtables)) {
1018         ResourceMark rm;
1019         log_trace(cds,hashtables)("%s dictionary: %s", (_is_builtin ? "builtin" : "unregistered"), info._klass->external_name());
1020       }
1021 
1022       // Save this for quick runtime lookup of InstanceKlass* -> RunTimeClassInfo*
1023       InstanceKlass* buffered_klass = ArchiveBuilder::current()->get_buffered_addr(info._klass);
1024       RunTimeClassInfo::set_for(buffered_klass, record);
1025     }
1026   }
1027 };
1028 
1029 void SystemDictionaryShared::write_dictionary(RunTimeSharedDictionary* dictionary,
1030                                               bool is_builtin) {
1031   CompactHashtableStats stats;
1032   dictionary->reset();
1033   CompactHashtableWriter writer(_dumptime_table->count_of(is_builtin), &stats);
1034   CopySharedClassInfoToArchive copy(&writer, is_builtin);
1035   assert_lock_strong(DumpTimeTable_lock);
1036   _dumptime_table->iterate_all_live_classes(&copy);
1037   writer.dump(dictionary, is_builtin ? "builtin dictionary" : "unregistered dictionary");
1038 }
1039 
1040 void SystemDictionaryShared::write_to_archive(bool is_static_archive) {
1041   ArchiveInfo* archive = get_archive(is_static_archive);
1042 
1043   write_dictionary(&archive->_builtin_dictionary, true);
1044   write_dictionary(&archive->_unregistered_dictionary, false);
1045   if (CDSConfig::is_dumping_lambdas_in_legacy_mode()) {
1046     LambdaProxyClassDictionary::write_dictionary(is_static_archive);
1047   } else {
1048     LambdaProxyClassDictionary::reset_dictionary(is_static_archive);
1049   }
1050 }
1051 
1052 void SystemDictionaryShared::serialize_dictionary_headers(SerializeClosure* soc,
1053                                                           bool is_static_archive) {
1054   ArchiveInfo* archive = get_archive(is_static_archive);
1055 
1056   archive->_builtin_dictionary.serialize_header(soc);
1057   archive->_unregistered_dictionary.serialize_header(soc);
1058   LambdaProxyClassDictionary::serialize(soc, is_static_archive);
1059 }
1060 
1061 void SystemDictionaryShared::serialize_vm_classes(SerializeClosure* soc) {
1062   for (auto id : EnumRange<vmClassID>{}) {
1063     soc->do_ptr(vmClasses::klass_addr_at(id));
1064   }
1065 }
1066 
1067 const RunTimeClassInfo*
1068 SystemDictionaryShared::find_record(RunTimeSharedDictionary* static_dict, RunTimeSharedDictionary* dynamic_dict, Symbol* name) {
1069   if (!CDSConfig::is_using_archive() || !name->is_shared()) {
1070     // The names of all shared classes must also be a shared Symbol.
1071     return nullptr;
1072   }
1073 
1074   unsigned int hash = SystemDictionaryShared::hash_for_shared_dictionary_quick(name);
1075   const RunTimeClassInfo* record = nullptr;
1076   if (DynamicArchive::is_mapped()) {
1077     // Use the regenerated holder classes in the dynamic archive as they
1078     // have more methods than those in the base archive.
1079     if (LambdaFormInvokers::may_be_regenerated_class(name)) {
1080       record = dynamic_dict->lookup(name, hash, 0);
1081       if (record != nullptr) {
1082         return record;
1083       }
1084     }
1085   }
1086 
1087   if (!MetaspaceShared::is_shared_dynamic(name)) {
1088     // The names of all shared classes in the static dict must also be in the
1089     // static archive
1090     record = static_dict->lookup(name, hash, 0);
1091   }
1092 
1093   if (record == nullptr && DynamicArchive::is_mapped()) {
1094     record = dynamic_dict->lookup(name, hash, 0);
1095   }
1096 
1097   return record;
1098 }
1099 
1100 InstanceKlass* SystemDictionaryShared::find_builtin_class(Symbol* name) {
1101   const RunTimeClassInfo* record = find_record(&_static_archive._builtin_dictionary,
1102                                                &_dynamic_archive._builtin_dictionary,
1103                                                name);
1104   if (record != nullptr) {
1105     assert(!record->klass()->is_hidden(), "hidden class cannot be looked up by name");
1106     DEBUG_ONLY(check_klass_after_loading(record->klass());)
1107     // We did not save the classfile data of the generated LambdaForm invoker classes,
1108     // so we cannot support CLFH for such classes.
1109     if (record->klass()->is_generated_shared_class() && JvmtiExport::should_post_class_file_load_hook()) {
1110        return nullptr;
1111     }
1112     return record->klass();
1113   } else {
1114     return nullptr;
1115   }
1116 }
1117 
1118 void SystemDictionaryShared::update_shared_entry(InstanceKlass* k, int id) {
1119   assert(CDSConfig::is_dumping_static_archive(), "class ID is used only for static dump (from classlist)");
1120   DumpTimeClassInfo* info = get_info(k);
1121   info->_id = id;
1122 }
1123 
1124 const char* SystemDictionaryShared::loader_type_for_shared_class(Klass* k) {
1125   assert(k != nullptr, "Sanity");
1126   assert(k->is_shared(), "Must be");
1127   assert(k->is_instance_klass(), "Must be");
1128   InstanceKlass* ik = InstanceKlass::cast(k);
1129   if (ik->is_shared_boot_class()) {
1130     return "boot_loader";
1131   } else if (ik->is_shared_platform_class()) {
1132     return "platform_loader";
1133   } else if (ik->is_shared_app_class()) {
1134     return "app_loader";
1135   } else if (ik->is_shared_unregistered_class()) {
1136     return "unregistered_loader";
1137   } else {
1138     return "unknown loader";
1139   }
1140 }
1141 
1142 class SharedDictionaryPrinter : StackObj {
1143   outputStream* _st;
1144   int _index;
1145 public:
1146   SharedDictionaryPrinter(outputStream* st) : _st(st), _index(0) {}
1147 
1148   void do_value(const RunTimeClassInfo* record) {
1149     ResourceMark rm;
1150     _st->print_cr("%4d: %s %s", _index++, record->klass()->external_name(),
1151         SystemDictionaryShared::loader_type_for_shared_class(record->klass()));
1152     if (record->klass()->array_klasses() != nullptr) {
1153       record->klass()->array_klasses()->cds_print_value_on(_st);
1154       _st->cr();
1155     }
1156   }
1157   int index() const { return _index; }
1158 };
1159 
1160 void SystemDictionaryShared::ArchiveInfo::print_on(const char* prefix,
1161                                                    outputStream* st,
1162                                                    bool is_static_archive) {
1163   st->print_cr("%sShared Dictionary", prefix);
1164   SharedDictionaryPrinter p(st);
1165   st->print_cr("%sShared Builtin Dictionary", prefix);
1166   _builtin_dictionary.iterate(&p);
1167   st->print_cr("%sShared Unregistered Dictionary", prefix);
1168   _unregistered_dictionary.iterate(&p);
1169   LambdaProxyClassDictionary::print_on(prefix, st, p.index(), is_static_archive);
1170 }
1171 
1172 void SystemDictionaryShared::ArchiveInfo::print_table_statistics(const char* prefix,
1173                                                                  outputStream* st,
1174                                                                  bool is_static_archive) {
1175   st->print_cr("%sArchve Statistics", prefix);
1176   _builtin_dictionary.print_table_statistics(st, "Builtin Shared Dictionary");
1177   _unregistered_dictionary.print_table_statistics(st, "Unregistered Shared Dictionary");
1178   LambdaProxyClassDictionary::print_statistics(st, is_static_archive);
1179 }
1180 
1181 void SystemDictionaryShared::print_shared_archive(outputStream* st, bool is_static) {
1182   if (CDSConfig::is_using_archive()) {
1183     if (is_static) {
1184       _static_archive.print_on("", st, true);
1185     } else {
1186       if (DynamicArchive::is_mapped()) {
1187         _dynamic_archive.print_on("Dynamic ", st, false);
1188       }
1189     }
1190   }
1191 }
1192 
1193 void SystemDictionaryShared::print_on(outputStream* st) {
1194   print_shared_archive(st, true);
1195   print_shared_archive(st, false);
1196 }
1197 
1198 void SystemDictionaryShared::print_table_statistics(outputStream* st) {
1199   if (CDSConfig::is_using_archive()) {
1200     _static_archive.print_table_statistics("Static ", st, true);
1201     if (DynamicArchive::is_mapped()) {
1202       _dynamic_archive.print_table_statistics("Dynamic ", st, false);
1203     }
1204   }
1205 }
1206 
1207 bool SystemDictionaryShared::is_dumptime_table_empty() {
1208   assert_lock_strong(DumpTimeTable_lock);
1209   _dumptime_table->update_counts();
1210   if (_dumptime_table->count_of(true) == 0 && _dumptime_table->count_of(false) == 0){
1211     return true;
1212   }
1213   return false;
1214 }