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