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