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