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