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