1 /*
   2  * Copyright (c) 2014, 2025, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "cds/aotClassLocation.hpp"
  26 #include "cds/archiveBuilder.hpp"
  27 #include "cds/archiveHeapLoader.hpp"
  28 #include "cds/archiveUtils.hpp"
  29 #include "cds/cdsConfig.hpp"
  30 #include "cds/cdsProtectionDomain.hpp"
  31 #include "cds/classListParser.hpp"
  32 #include "cds/classListWriter.hpp"
  33 #include "cds/dumpTimeClassInfo.inline.hpp"
  34 #include "cds/dynamicArchive.hpp"
  35 #include "cds/filemap.hpp"
  36 #include "cds/heapShared.hpp"
  37 #include "cds/lambdaFormInvokers.inline.hpp"
  38 #include "cds/metaspaceShared.hpp"
  39 #include "cds/runTimeClassInfo.hpp"
  40 #include "cds/unregisteredClasses.hpp"
  41 #include "classfile/classFileStream.hpp"
  42 #include "classfile/classLoader.hpp"
  43 #include "classfile/classLoaderData.inline.hpp"
  44 #include "classfile/classLoaderDataGraph.hpp"
  45 #include "classfile/classLoaderExt.hpp"
  46 #include "classfile/dictionary.hpp"
  47 #include "classfile/javaClasses.hpp"
  48 #include "classfile/javaClasses.inline.hpp"
  49 #include "classfile/symbolTable.hpp"
  50 #include "classfile/systemDictionary.hpp"
  51 #include "classfile/systemDictionaryShared.hpp"
  52 #include "classfile/verificationType.hpp"
  53 #include "classfile/vmClasses.hpp"
  54 #include "classfile/vmSymbols.hpp"
  55 #include "interpreter/bootstrapInfo.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/resourceHash.hpp"
  80 #include "utilities/stringUtils.hpp"
  81 
  82 SystemDictionaryShared::ArchiveInfo SystemDictionaryShared::_static_archive;
  83 SystemDictionaryShared::ArchiveInfo SystemDictionaryShared::_dynamic_archive;
  84 
  85 DumpTimeSharedClassTable* SystemDictionaryShared::_dumptime_table = nullptr;
  86 DumpTimeLambdaProxyClassDictionary* SystemDictionaryShared::_dumptime_lambda_proxy_class_dictionary = nullptr;
  87 
  88 static bool _ignore_new_classes = false;
  89 
  90 // Used by NoClassLoadingMark
  91 DEBUG_ONLY(bool SystemDictionaryShared::_class_loading_may_happen = true;)
  92 
  93 #ifdef ASSERT
  94 static void check_klass_after_loading(const Klass* k) {
  95 #ifdef _LP64
  96   if (k != nullptr && UseCompressedClassPointers && k->needs_narrow_id()) {
  97     CompressedKlassPointers::check_encodable(k);
  98   }
  99 #endif
 100 }
 101 #endif
 102 
 103 InstanceKlass* SystemDictionaryShared::load_shared_class_for_builtin_loader(
 104                  Symbol* class_name, Handle class_loader, TRAPS) {
 105   assert(CDSConfig::is_using_archive(), "must be");
 106   InstanceKlass* ik = find_builtin_class(class_name);
 107 
 108   if (ik != nullptr && !ik->shared_loading_failed()) {
 109     if ((SystemDictionary::is_system_class_loader(class_loader()) && ik->is_shared_app_class())  ||
 110         (SystemDictionary::is_platform_class_loader(class_loader()) && ik->is_shared_platform_class())) {
 111       SharedClassLoadingMark slm(THREAD, ik);
 112       PackageEntry* pkg_entry = CDSProtectionDomain::get_package_entry_from_class(ik, class_loader);
 113       Handle protection_domain;
 114       if (!class_name->starts_with("jdk/proxy")) // java/lang/reflect/Proxy$ProxyBuilder defines the proxy classes with a null protection domain.
 115       {
 116         protection_domain = CDSProtectionDomain::init_security_info(class_loader, ik, pkg_entry, CHECK_NULL);
 117       }
 118       return load_shared_class(ik, class_loader, protection_domain, nullptr, pkg_entry, THREAD);
 119     }
 120   }
 121   return nullptr;
 122 }
 123 
 124 // This function is called for loading only UNREGISTERED classes
 125 InstanceKlass* SystemDictionaryShared::lookup_from_stream(Symbol* class_name,
 126                                                           Handle class_loader,
 127                                                           Handle protection_domain,
 128                                                           const ClassFileStream* cfs,
 129                                                           TRAPS) {
 130   if (!CDSConfig::is_using_archive()) {
 131     return nullptr;
 132   }
 133   if (class_name == nullptr) {  // don't do this for hidden classes
 134     return nullptr;
 135   }
 136   if (class_loader.is_null() ||
 137       SystemDictionary::is_system_class_loader(class_loader()) ||
 138       SystemDictionary::is_platform_class_loader(class_loader())) {
 139     // Do nothing for the BUILTIN loaders.
 140     return nullptr;
 141   }
 142 
 143   const RunTimeClassInfo* record = find_record(&_static_archive._unregistered_dictionary,
 144                                                &_dynamic_archive._unregistered_dictionary,
 145                                                class_name);
 146   if (record == nullptr) {
 147     return nullptr;
 148   }
 149 
 150   int clsfile_size  = cfs->length();
 151   int clsfile_crc32 = ClassLoader::crc32(0, (const char*)cfs->buffer(), cfs->length());
 152 
 153   if (!record->matches(clsfile_size, clsfile_crc32)) {
 154     return nullptr;
 155   }
 156 
 157   return acquire_class_for_current_thread(record->klass(), class_loader,
 158                                           protection_domain, cfs,
 159                                           THREAD);
 160 }
 161 
 162 InstanceKlass* SystemDictionaryShared::acquire_class_for_current_thread(
 163                    InstanceKlass *ik,
 164                    Handle class_loader,
 165                    Handle protection_domain,
 166                    const ClassFileStream *cfs,
 167                    TRAPS) {
 168   ClassLoaderData* loader_data = ClassLoaderData::class_loader_data(class_loader());
 169 
 170   {
 171     MutexLocker mu(THREAD, SharedDictionary_lock);
 172     if (ik->class_loader_data() != nullptr) {
 173       //    ik is already loaded (by this loader or by a different loader)
 174       // or ik is being loaded by a different thread (by this loader or by a different loader)
 175       return nullptr;
 176     }
 177 
 178     // No other thread has acquired this yet, so give it to *this thread*
 179     ik->set_class_loader_data(loader_data);
 180   }
 181 
 182   // No longer holding SharedDictionary_lock
 183   // No need to lock, as <ik> can be held only by a single thread.
 184   loader_data->add_class(ik);
 185 
 186   // Get the package entry.
 187   PackageEntry* pkg_entry = CDSProtectionDomain::get_package_entry_from_class(ik, class_loader);
 188 
 189   // Load and check super/interfaces, restore unshareable info
 190   InstanceKlass* shared_klass = load_shared_class(ik, class_loader, protection_domain,
 191                                                   cfs, pkg_entry, THREAD);
 192   if (shared_klass == nullptr || HAS_PENDING_EXCEPTION) {
 193     // TODO: clean up <ik> so it can be used again
 194     return nullptr;
 195   }
 196 
 197   return shared_klass;
 198 }
 199 
 200 // Guaranteed to return non-null value for non-shared classes.
 201 // k must not be a shared class.
 202 DumpTimeClassInfo* SystemDictionaryShared::get_info(InstanceKlass* k) {
 203   MutexLocker ml(DumpTimeTable_lock, Mutex::_no_safepoint_check_flag);
 204   return get_info_locked(k);
 205 }
 206 
 207 DumpTimeClassInfo* SystemDictionaryShared::get_info_locked(InstanceKlass* k) {
 208   assert_lock_strong(DumpTimeTable_lock);
 209   DumpTimeClassInfo* info = _dumptime_table->get_info(k);
 210   assert(info != nullptr, "must be");
 211   return info;
 212 }
 213 
 214 bool SystemDictionaryShared::check_for_exclusion(InstanceKlass* k, DumpTimeClassInfo* info) {
 215   if (CDSConfig::is_dumping_dynamic_archive() && MetaspaceShared::is_in_shared_metaspace(k)) {
 216     // We have reached a super type that's already in the base archive. Treat it
 217     // as "not excluded".
 218     return false;
 219   }
 220 
 221   if (info == nullptr) {
 222     info = _dumptime_table->get(k);
 223     assert(info != nullptr, "supertypes of any classes in _dumptime_table must either be shared, or must also be in _dumptime_table");
 224   }
 225 
 226   if (!info->has_checked_exclusion()) {
 227     if (check_for_exclusion_impl(k)) {
 228       info->set_excluded();
 229     }
 230     info->set_has_checked_exclusion();
 231   }
 232 
 233   return info->is_excluded();
 234 }
 235 
 236 // Returns true so the caller can do:    return warn_excluded(".....");
 237 bool SystemDictionaryShared::warn_excluded(InstanceKlass* k, const char* reason) {
 238   ResourceMark rm;
 239   log_warning(cds)("Skipping %s: %s", k->name()->as_C_string(), reason);
 240   return true;
 241 }
 242 
 243 bool SystemDictionaryShared::is_jfr_event_class(InstanceKlass *k) {
 244   while (k) {
 245     if (k->name()->equals("jdk/internal/event/Event")) {
 246       return true;
 247     }
 248     k = k->java_super();
 249   }
 250   return false;
 251 }
 252 
 253 bool SystemDictionaryShared::is_registered_lambda_proxy_class(InstanceKlass* ik) {
 254   DumpTimeClassInfo* info = _dumptime_table->get(ik);
 255   bool result = (info != nullptr) ? info->_is_registered_lambda_proxy : false;
 256   if (result) {
 257     assert(!CDSConfig::is_dumping_invokedynamic(), "only used in legacy lambda proxy support");
 258   }
 259   return result;
 260 }
 261 
 262 void SystemDictionaryShared::reset_registered_lambda_proxy_class(InstanceKlass* ik) {
 263   DumpTimeClassInfo* info = _dumptime_table->get(ik);
 264   if (info != nullptr) {
 265     info->_is_registered_lambda_proxy = false;
 266     info->set_excluded();
 267   }
 268 }
 269 
 270 bool SystemDictionaryShared::is_early_klass(InstanceKlass* ik) {
 271   DumpTimeClassInfo* info = _dumptime_table->get(ik);
 272   return (info != nullptr) ? info->is_early_klass() : false;
 273 }
 274 
 275 bool SystemDictionaryShared::is_hidden_lambda_proxy(InstanceKlass* ik) {
 276   assert(ik->is_shared(), "applicable to only a shared class");
 277   if (ik->is_hidden()) {
 278     return true;
 279   } else {
 280     return false;
 281   }
 282 }
 283 
 284 void SystemDictionaryShared::ignore_new_classes() {
 285   _ignore_new_classes = true;
 286 }
 287 
 288 
 289 bool SystemDictionaryShared::check_for_exclusion_impl(InstanceKlass* k) {
 290   if (CDSConfig::is_dumping_final_static_archive() && k->is_shared_unregistered_class()
 291       && k->is_shared()) {
 292     return false; // Do not exclude: unregistered classes are passed from preimage to final image.
 293   }
 294 
 295   if (k->is_in_error_state()) {
 296     return warn_excluded(k, "In error state");
 297   }
 298   if (k->is_scratch_class()) {
 299     return warn_excluded(k, "A scratch class");
 300   }
 301   if (!k->is_loaded()) {
 302     return warn_excluded(k, "Not in loaded state");
 303   }
 304   if (has_been_redefined(k)) {
 305     return warn_excluded(k, "Has been redefined");
 306   }
 307   if (!k->is_hidden() && k->shared_classpath_index() < 0 && is_builtin(k)) {
 308     if (k->name()->starts_with("java/lang/invoke/BoundMethodHandle$Species_")) {
 309       // This class is dynamically generated by the JDK
 310       if (CDSConfig::is_dumping_aot_linked_classes()) {
 311         k->set_shared_classpath_index(0);
 312       } else {
 313         ResourceMark rm;
 314         log_info(cds)("Skipping %s because it is dynamically generated", k->name()->as_C_string());
 315         return true; // exclude without warning
 316       }
 317     } else {
 318       // These are classes loaded from unsupported locations (such as those loaded by JVMTI native
 319       // agent during dump time).
 320       return warn_excluded(k, "Unsupported location");
 321     }
 322   }
 323   if (k->signers() != nullptr) {
 324     // We cannot include signed classes in the archive because the certificates
 325     // used during dump time may be different than those used during
 326     // runtime (due to expiration, etc).
 327     return warn_excluded(k, "Signed JAR");
 328   }
 329   if (is_jfr_event_class(k)) {
 330     // We cannot include JFR event classes because they need runtime-specific
 331     // instrumentation in order to work with -XX:FlightRecorderOptions:retransform=false.
 332     // There are only a small number of these classes, so it's not worthwhile to
 333     // support them and make CDS more complicated.
 334     if (!CDSConfig::is_dumping_reflection_data()) { // FIXME: !!! HACK !!!
 335       return warn_excluded(k, "JFR event class");
 336     }
 337   }
 338 
 339   if (!k->is_linked()) {
 340     if (has_class_failed_verification(k)) {
 341       return warn_excluded(k, "Failed verification");
 342     } else if (CDSConfig::is_dumping_aot_linked_classes()) {
 343       // Most loaded classes should have been speculatively linked by MetaspaceShared::link_class_for_cds().
 344       // However, we do not speculatively link old classes, as they are not recorded by
 345       // SystemDictionaryShared::record_linking_constraint(). As a result, such an unlinked
 346       // class may fail to verify in AOTLinkedClassBulkLoader::init_required_classes_for_loader(),
 347       // causing the JVM to fail at bootstrap.
 348       return warn_excluded(k, "Unlinked class not supported by AOTClassLinking");
 349     } else if (CDSConfig::is_dumping_preimage_static_archive()) {
 350       // When dumping the final static archive, we will unconditionally load and link all
 351       // classes from tje preimage. We don't want to get a VerifyError when linking this class.
 352       return warn_excluded(k, "Unlinked class not supported by AOTConfiguration");
 353     }
 354   } else {
 355     if (!k->can_be_verified_at_dumptime() && !CDSConfig::preserve_all_dumptime_verification_states(k)) {
 356       // We have an old class that has been linked (e.g., it's been executed during
 357       // dump time). This class has been verified using the old verifier, which
 358       // doesn't save the verification constraints, so check_verification_constraints()
 359       // won't work at runtime.
 360       // As a result, we cannot store this class. It must be loaded and fully verified
 361       // at runtime.
 362       return warn_excluded(k, "Old class has been linked");
 363     }
 364   }
 365 
 366   InstanceKlass* super = k->java_super();
 367   if (super != nullptr && check_for_exclusion(super, nullptr)) {
 368     ResourceMark rm;
 369     log_warning(cds)("Skipping %s: super class %s is excluded", k->name()->as_C_string(), super->name()->as_C_string());
 370     return true;
 371   }
 372 
 373   Array<InstanceKlass*>* interfaces = k->local_interfaces();
 374   int len = interfaces->length();
 375   for (int i = 0; i < len; i++) {
 376     InstanceKlass* intf = interfaces->at(i);
 377     if (check_for_exclusion(intf, nullptr)) {
 378       ResourceMark rm;
 379       log_warning(cds)("Skipping %s: interface %s is excluded", k->name()->as_C_string(), intf->name()->as_C_string());
 380       return true;
 381     }
 382   }
 383 
 384   if (k == UnregisteredClasses::UnregisteredClassLoader_klass()) {
 385     ResourceMark rm;
 386     log_debug(cds)("Skipping %s: used only when dumping CDS archive", k->name()->as_C_string());
 387     return true;
 388   }
 389 
 390   if (k->name()->equals("jdk/internal/misc/CDS$DummyForDynamicArchive") && !CDSConfig::is_dumping_dynamic_archive()) {
 391     ResourceMark rm;
 392     log_debug(cds)("Skipping %s: used only when dumping dynamic CDS archive", k->name()->as_C_string());
 393     return true;
 394   }
 395 
 396 
 397   return false; // false == k should NOT be excluded
 398 }
 399 
 400 bool SystemDictionaryShared::is_builtin_loader(ClassLoaderData* loader_data) {
 401   oop class_loader = loader_data->class_loader();
 402   return (class_loader == nullptr ||
 403           SystemDictionary::is_system_class_loader(class_loader) ||
 404           SystemDictionary::is_platform_class_loader(class_loader));
 405 }
 406 
 407 bool SystemDictionaryShared::has_platform_or_app_classes() {
 408   if (FileMapInfo::current_info()->has_platform_or_app_classes()) {
 409     return true;
 410   }
 411   if (DynamicArchive::is_mapped() &&
 412       FileMapInfo::dynamic_info()->has_platform_or_app_classes()) {
 413     return true;
 414   }
 415   return false;
 416 }
 417 
 418 // The following stack shows how this code is reached:
 419 //
 420 //   [0] SystemDictionaryShared::find_or_load_shared_class()
 421 //   [1] JVM_FindLoadedClass
 422 //   [2] java.lang.ClassLoader.findLoadedClass0()
 423 //   [3] java.lang.ClassLoader.findLoadedClass()
 424 //   [4] jdk.internal.loader.BuiltinClassLoader.loadClassOrNull()
 425 //   [5] jdk.internal.loader.BuiltinClassLoader.loadClass()
 426 //   [6] jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(), or
 427 //       jdk.internal.loader.ClassLoaders$PlatformClassLoader.loadClass()
 428 //
 429 // AppCDS supports fast class loading for these 2 built-in class loaders:
 430 //    jdk.internal.loader.ClassLoaders$PlatformClassLoader
 431 //    jdk.internal.loader.ClassLoaders$AppClassLoader
 432 // with the following assumptions (based on the JDK core library source code):
 433 //
 434 // [a] these two loaders use the BuiltinClassLoader.loadClassOrNull() to
 435 //     load the named class.
 436 // [b] BuiltinClassLoader.loadClassOrNull() first calls findLoadedClass(name).
 437 // [c] At this point, if we can find the named class inside the
 438 //     shared_dictionary, we can perform further checks (see
 439 //     SystemDictionary::is_shared_class_visible) to ensure that this class
 440 //     was loaded by the same class loader during dump time.
 441 //
 442 // Given these assumptions, we intercept the findLoadedClass() call to invoke
 443 // SystemDictionaryShared::find_or_load_shared_class() to load the shared class from
 444 // the archive for the 2 built-in class loaders. This way,
 445 // we can improve start-up because we avoid decoding the classfile,
 446 // and avoid delegating to the parent loader.
 447 //
 448 // NOTE: there's a lot of assumption about the Java code. If any of that change, this
 449 // needs to be redesigned.
 450 
 451 InstanceKlass* SystemDictionaryShared::find_or_load_shared_class(
 452                  Symbol* name, Handle class_loader, TRAPS) {
 453   InstanceKlass* k = nullptr;
 454   if (CDSConfig::is_using_archive()) {
 455     if (!has_platform_or_app_classes()) {
 456       return nullptr;
 457     }
 458 
 459     if (SystemDictionary::is_system_class_loader(class_loader()) ||
 460         SystemDictionary::is_platform_class_loader(class_loader())) {
 461       ClassLoaderData *loader_data = register_loader(class_loader);
 462       Dictionary* dictionary = loader_data->dictionary();
 463 
 464       // Note: currently, find_or_load_shared_class is called only from
 465       // JVM_FindLoadedClass and used for PlatformClassLoader and AppClassLoader,
 466       // which are parallel-capable loaders, so a lock here is NOT taken.
 467       assert(get_loader_lock_or_null(class_loader) == nullptr, "ObjectLocker not required");
 468       {
 469         MutexLocker mu(THREAD, SystemDictionary_lock);
 470         InstanceKlass* check = dictionary->find_class(THREAD, name);
 471         if (check != nullptr) {
 472           return check;
 473         }
 474       }
 475 
 476       k = load_shared_class_for_builtin_loader(name, class_loader, THREAD);
 477       if (k != nullptr) {
 478         SharedClassLoadingMark slm(THREAD, k);
 479         k = find_or_define_instance_class(name, class_loader, k, CHECK_NULL);
 480       }
 481     }
 482   }
 483 
 484   DEBUG_ONLY(check_klass_after_loading(k);)
 485 
 486   return k;
 487 }
 488 
 489 class UnregisteredClassesTable : public ResourceHashtable<
 490   Symbol*, InstanceKlass*,
 491   15889, // prime number
 492   AnyObj::C_HEAP> {};
 493 
 494 static UnregisteredClassesTable* _unregistered_classes_table = nullptr;
 495 
 496 // true == class was successfully added; false == a duplicated class (with the same name) already exists.
 497 bool SystemDictionaryShared::add_unregistered_class(Thread* current, InstanceKlass* klass) {
 498   // We don't allow duplicated unregistered classes with the same name.
 499   // We only archive the first class with that name that succeeds putting
 500   // itself into the table.
 501   assert(CDSConfig::is_dumping_archive() || ClassListWriter::is_enabled(), "sanity");
 502   MutexLocker ml(current, UnregisteredClassesTable_lock, Mutex::_no_safepoint_check_flag);
 503   Symbol* name = klass->name();
 504   if (_unregistered_classes_table == nullptr) {
 505     _unregistered_classes_table = new (mtClass)UnregisteredClassesTable();
 506   }
 507   bool created;
 508   InstanceKlass** v = _unregistered_classes_table->put_if_absent(name, klass, &created);
 509   if (created) {
 510     name->increment_refcount();
 511   }
 512   return (klass == *v);
 513 }
 514 
 515 void SystemDictionaryShared::set_shared_class_misc_info(InstanceKlass* k, ClassFileStream* cfs) {
 516   assert(CDSConfig::is_dumping_archive(), "sanity");
 517   assert(!is_builtin(k), "must be unregistered class");
 518   DumpTimeClassInfo* info = get_info(k);
 519   info->_clsfile_size  = cfs->length();
 520   info->_clsfile_crc32 = ClassLoader::crc32(0, (const char*)cfs->buffer(), cfs->length());
 521 }
 522 
 523 void SystemDictionaryShared::initialize() {
 524   if (CDSConfig::is_dumping_archive()) {
 525     _dumptime_table = new (mtClass) DumpTimeSharedClassTable;
 526     _dumptime_lambda_proxy_class_dictionary =
 527                       new (mtClass) DumpTimeLambdaProxyClassDictionary;
 528     if (CDSConfig::is_dumping_heap()) {
 529       HeapShared::init_dumping();
 530     }
 531   }
 532 }
 533 
 534 void SystemDictionaryShared::init_dumptime_info(InstanceKlass* k) {
 535   MutexLocker ml(DumpTimeTable_lock, Mutex::_no_safepoint_check_flag);
 536   assert(SystemDictionaryShared::class_loading_may_happen(), "sanity");
 537   DumpTimeClassInfo* info = _dumptime_table->allocate_info(k);
 538   if (_ignore_new_classes) {
 539     if (!LambdaFormInvokers::may_be_regenerated_class(k->name())) {
 540       ResourceMark rm;
 541       log_debug(cds)("Skipping %s: Class loaded for lambda form invoker regeneration", k->name()->as_C_string());
 542       info->set_has_checked_exclusion();
 543       info->set_excluded();
 544     }
 545   }
 546 }
 547 
 548 void SystemDictionaryShared::remove_dumptime_info(InstanceKlass* k) {
 549   MutexLocker ml(DumpTimeTable_lock, Mutex::_no_safepoint_check_flag);
 550   _dumptime_table->remove(k);
 551 }
 552 
 553 void SystemDictionaryShared::handle_class_unloading(InstanceKlass* klass) {
 554   if (CDSConfig::is_dumping_archive()) {
 555     remove_dumptime_info(klass);
 556   }
 557 
 558   if (CDSConfig::is_dumping_archive() || ClassListWriter::is_enabled()) {
 559     MutexLocker ml(Thread::current(), UnregisteredClassesTable_lock, Mutex::_no_safepoint_check_flag);
 560     if (_unregistered_classes_table != nullptr) {
 561       // Remove the class from _unregistered_classes_table: keep the entry but
 562       // set it to null. This ensure no classes with the same name can be
 563       // added again.
 564       InstanceKlass** v = _unregistered_classes_table->get(klass->name());
 565       if (v != nullptr) {
 566         *v = nullptr;
 567       }
 568     }
 569   } else {
 570     assert(_unregistered_classes_table == nullptr, "must not be used");
 571   }
 572 
 573   if (ClassListWriter::is_enabled()) {
 574     ClassListWriter cw;
 575     cw.handle_class_unloading((const InstanceKlass*)klass);
 576   }
 577 }
 578 
 579 void SystemDictionaryShared::init_dumptime_info_from_preimage(InstanceKlass* k) {
 580   init_dumptime_info(k);
 581   copy_verification_constraints_from_preimage(k);
 582   copy_linking_constraints_from_preimage(k);
 583 
 584   if (SystemDictionary::is_platform_class_loader(k->class_loader())) {
 585     AOTClassLocationConfig::dumptime_set_has_platform_classes();
 586   } else if (SystemDictionary::is_system_class_loader(k->class_loader())) {
 587     AOTClassLocationConfig::dumptime_set_has_app_classes();
 588   }
 589 }
 590 
 591 // Check if a class or any of its supertypes has been redefined.
 592 bool SystemDictionaryShared::has_been_redefined(InstanceKlass* k) {
 593   if (k->has_been_redefined()) {
 594     return true;
 595   }
 596   if (k->java_super() != nullptr && has_been_redefined(k->java_super())) {
 597     return true;
 598   }
 599   Array<InstanceKlass*>* interfaces = k->local_interfaces();
 600   int len = interfaces->length();
 601   for (int i = 0; i < len; i++) {
 602     if (has_been_redefined(interfaces->at(i))) {
 603       return true;
 604     }
 605   }
 606   return false;
 607 }
 608 
 609 // k is a class before relocating by ArchiveBuilder
 610 void SystemDictionaryShared::validate_before_archiving(InstanceKlass* k) {
 611   ResourceMark rm;
 612   const char* name = k->name()->as_C_string();
 613   DumpTimeClassInfo* info = _dumptime_table->get(k);
 614   assert(!class_loading_may_happen(), "class loading must be disabled");
 615   guarantee(info != nullptr, "Class %s must be entered into _dumptime_table", name);
 616   guarantee(!info->is_excluded(), "Should not attempt to archive excluded class %s", name);
 617   if (is_builtin(k)) {
 618     if (k->is_hidden()) {
 619       if (!CDSConfig::is_dumping_invokedynamic()) {
 620         assert(is_registered_lambda_proxy_class(k), "unexpected hidden class %s", name);
 621       }
 622     }
 623     guarantee(!k->is_shared_unregistered_class(),
 624               "Class loader type must be set for BUILTIN class %s", name);
 625 
 626   } else {
 627     guarantee(k->is_shared_unregistered_class(),
 628               "Class loader type must not be set for UNREGISTERED class %s", name);
 629   }
 630 }
 631 
 632 class UnregisteredClassesDuplicationChecker : StackObj {
 633   GrowableArray<InstanceKlass*> _list;
 634   Thread* _thread;
 635 public:
 636   UnregisteredClassesDuplicationChecker() : _thread(Thread::current()) {}
 637 
 638   void do_entry(InstanceKlass* k, DumpTimeClassInfo& info) {
 639     if (!SystemDictionaryShared::is_builtin(k)) {
 640       _list.append(k);
 641     }
 642   }
 643 
 644   static int compare_by_loader(InstanceKlass** a, InstanceKlass** b) {
 645     ClassLoaderData* loader_a = a[0]->class_loader_data();
 646     ClassLoaderData* loader_b = b[0]->class_loader_data();
 647 
 648     if (loader_a != loader_b) {
 649       return primitive_compare(loader_a, loader_b);
 650     } else {
 651       return primitive_compare(a[0], b[0]);
 652     }
 653   }
 654 
 655   void mark_duplicated_classes() {
 656     // Two loaders may load two identical or similar hierarchies of classes. If we
 657     // check for duplication in random order, we may end up excluding important base classes
 658     // in both hierarchies, causing most of the classes to be excluded.
 659     // We sort the classes by their loaders. This way we're likely to archive
 660     // all classes in the one of the two hierarchies.
 661     _list.sort(compare_by_loader);
 662     for (int i = 0; i < _list.length(); i++) {
 663       InstanceKlass* k = _list.at(i);
 664       bool i_am_first = SystemDictionaryShared::add_unregistered_class(_thread, k);
 665       if (!i_am_first) {
 666         SystemDictionaryShared::warn_excluded(k, "Duplicated unregistered class");
 667         SystemDictionaryShared::set_excluded_locked(k);
 668       }
 669     }
 670   }
 671 };
 672 
 673 // Returns true if the class should be excluded. This can be called by
 674 // AOTConstantPoolResolver before or after we enter the CDS safepoint.
 675 // When called before the safepoint, we need to link the class so that
 676 // it can be checked by check_for_exclusion().
 677 bool SystemDictionaryShared::should_be_excluded(Klass* k) {
 678   assert(CDSConfig::is_dumping_archive(), "sanity");
 679   assert(CDSConfig::current_thread_is_vm_or_dumper(), "sanity");
 680 
 681   if (k->is_objArray_klass()) {
 682     return should_be_excluded(ObjArrayKlass::cast(k)->bottom_klass());
 683   }
 684 
 685   if (!k->is_instance_klass()) {
 686     return false;
 687   } else {
 688     InstanceKlass* ik = InstanceKlass::cast(k);
 689 
 690     if (!SafepointSynchronize::is_at_safepoint()) {
 691       if (!ik->is_linked()) {
 692         // check_for_exclusion() below doesn't link unlinked classes. We come
 693         // here only when we are trying to aot-link constant pool entries, so
 694         // we'd better link the class.
 695         JavaThread* THREAD = JavaThread::current();
 696         ik->link_class(THREAD);
 697         if (HAS_PENDING_EXCEPTION) {
 698           CLEAR_PENDING_EXCEPTION;
 699           return true; // linking failed -- let's exclude it
 700         }
 701       }
 702 
 703       MutexLocker ml(DumpTimeTable_lock, Mutex::_no_safepoint_check_flag);
 704       DumpTimeClassInfo* p = get_info_locked(ik);
 705       if (p->is_excluded()) {
 706         return true;
 707       }
 708       return check_for_exclusion(ik, p);
 709     } else {
 710       // No need to check for is_linked() as all eligible classes should have
 711       // already been linked in MetaspaceShared::link_class_for_cds().
 712       // Can't take the lock as we are in safepoint.
 713       DumpTimeClassInfo* p = _dumptime_table->get(ik);
 714       if (p->is_excluded()) {
 715         return true;
 716       }
 717       return check_for_exclusion(ik, p);
 718     }
 719   }
 720 }
 721 
 722 void SystemDictionaryShared::finish_exclusion_checks() {
 723   if (CDSConfig::is_dumping_dynamic_archive()) {
 724     // Do this first -- if a base class is excluded due to duplication,
 725     // all of its subclasses will also be excluded.
 726     ResourceMark rm;
 727     UnregisteredClassesDuplicationChecker dup_checker;
 728     _dumptime_table->iterate_all_live_classes(&dup_checker);
 729     dup_checker.mark_duplicated_classes();
 730   }
 731 
 732   _dumptime_table->iterate_all_live_classes([&] (InstanceKlass* k, DumpTimeClassInfo& info) {
 733     SystemDictionaryShared::check_for_exclusion(k, &info);
 734   });
 735 
 736   _dumptime_table->update_counts();
 737   cleanup_lambda_proxy_class_dictionary();
 738 }
 739 
 740 bool SystemDictionaryShared::is_excluded_class(InstanceKlass* k) {
 741   assert(!class_loading_may_happen(), "class loading must be disabled");
 742   assert_lock_strong(DumpTimeTable_lock);
 743   assert(CDSConfig::is_dumping_archive(), "sanity");
 744   DumpTimeClassInfo* p = get_info_locked(k);
 745   return p->is_excluded();
 746 }
 747 
 748 void SystemDictionaryShared::set_excluded_locked(InstanceKlass* k) {
 749   assert_lock_strong(DumpTimeTable_lock);
 750   assert(CDSConfig::is_dumping_archive(), "sanity");
 751   DumpTimeClassInfo* info = get_info_locked(k);
 752   info->set_excluded();
 753 }
 754 
 755 void SystemDictionaryShared::set_excluded(InstanceKlass* k) {
 756   assert(CDSConfig::is_dumping_archive(), "sanity");
 757   DumpTimeClassInfo* info = get_info(k);
 758   info->set_excluded();
 759 }
 760 
 761 void SystemDictionaryShared::set_class_has_failed_verification(InstanceKlass* ik) {
 762   assert(CDSConfig::is_dumping_archive(), "sanity");
 763   DumpTimeClassInfo* p = get_info(ik);
 764   p->set_failed_verification();
 765 }
 766 
 767 bool SystemDictionaryShared::has_class_failed_verification(InstanceKlass* ik) {
 768   assert(CDSConfig::is_dumping_archive(), "sanity");
 769   DumpTimeClassInfo* p = _dumptime_table->get(ik);
 770   return (p == nullptr) ? false : p->failed_verification();
 771 }
 772 
 773 void SystemDictionaryShared::dumptime_classes_do(class MetaspaceClosure* it) {
 774   assert_lock_strong(DumpTimeTable_lock);
 775 
 776   auto do_klass = [&] (InstanceKlass* k, DumpTimeClassInfo& info) {
 777     if (CDSConfig::is_dumping_final_static_archive() && !k->is_loaded()) {
 778       assert(k->is_shared_unregistered_class(), "must be");
 779       info.metaspace_pointers_do(it);
 780     } else if (k->is_loader_alive() && !info.is_excluded()) {
 781       info.metaspace_pointers_do(it);
 782     }
 783   };
 784   _dumptime_table->iterate_all_live_classes(do_klass);
 785 
 786   auto do_lambda = [&] (LambdaProxyClassKey& key, DumpTimeLambdaProxyClassInfo& info) {
 787     if (key.caller_ik()->is_loader_alive()) {
 788       info.metaspace_pointers_do(it);
 789       key.metaspace_pointers_do(it);
 790     }
 791   };
 792   _dumptime_lambda_proxy_class_dictionary->iterate_all(do_lambda);
 793 }
 794 
 795 bool SystemDictionaryShared::add_verification_constraint(InstanceKlass* k, Symbol* name,
 796          Symbol* from_name, bool from_field_is_protected, bool from_is_array, bool from_is_object) {
 797   assert(CDSConfig::is_dumping_archive(), "sanity");
 798   if (CDSConfig::is_dumping_dynamic_archive() && k->is_shared()) {
 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 false;
 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 false;
 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_dynamic_archive()) {
 814     // For dynamic dumping, we can resolve all the constraint classes for all class loaders during
 815     // the initial run prior to creating the archive before vm exit. We will also perform verification
 816     // check when running with the archive.
 817     return false;
 818   } else {
 819     if (is_builtin(k)) {
 820       // For builtin class loaders, we can try to complete the verification check at dump time,
 821       // because we can resolve all the constraint classes. We will also perform verification check
 822       // when running with the archive.
 823       return false;
 824     } else {
 825       // For non-builtin class loaders, we cannot complete the verification check at dump time,
 826       // because at dump time we don't know how to resolve classes for such loaders.
 827       return true;
 828     }
 829   }
 830 }
 831 
 832 void SystemDictionaryShared::add_enum_klass_static_field(InstanceKlass* ik, int root_index) {
 833   assert(CDSConfig::is_dumping_heap(), "sanity");
 834   DumpTimeClassInfo* info = get_info_locked(ik);
 835   info->add_enum_klass_static_field(root_index);
 836 }
 837 
 838 void SystemDictionaryShared::add_to_dump_time_lambda_proxy_class_dictionary(LambdaProxyClassKey& key,
 839                                                            InstanceKlass* proxy_klass) {
 840   assert_lock_strong(DumpTimeTable_lock);
 841 
 842   bool created;
 843   DumpTimeLambdaProxyClassInfo* info = _dumptime_lambda_proxy_class_dictionary->put_if_absent(key, &created);
 844   info->add_proxy_klass(proxy_klass);
 845   if (created) {
 846     ++_dumptime_lambda_proxy_class_dictionary->_count;
 847   }
 848 }
 849 
 850 void SystemDictionaryShared::add_lambda_proxy_class(InstanceKlass* caller_ik,
 851                                                     InstanceKlass* lambda_ik,
 852                                                     Symbol* invoked_name,
 853                                                     Symbol* invoked_type,
 854                                                     Symbol* method_type,
 855                                                     Method* member_method,
 856                                                     Symbol* instantiated_method_type,
 857                                                     TRAPS) {
 858   if (CDSConfig::is_dumping_invokedynamic()) {
 859     // The lambda proxy classes will be stored as part of aot-resolved constant pool entries.
 860     // There's no need to remember them in a separate table.
 861     return;
 862   }
 863 
 864   if (CDSConfig::is_dumping_preimage_static_archive()) {
 865     // Information about lambda proxies are recorded in FinalImageRecipes.
 866     return;
 867   }
 868 
 869   assert(caller_ik->class_loader() == lambda_ik->class_loader(), "mismatched class loader");
 870   assert(caller_ik->class_loader_data() == lambda_ik->class_loader_data(), "mismatched class loader data");
 871   assert(java_lang_Class::class_data(lambda_ik->java_mirror()) == nullptr, "must not have class data");
 872 
 873   MutexLocker ml(DumpTimeTable_lock, Mutex::_no_safepoint_check_flag);
 874 
 875   lambda_ik->assign_class_loader_type();
 876   lambda_ik->set_shared_classpath_index(caller_ik->shared_classpath_index());
 877   InstanceKlass* nest_host = caller_ik->nest_host(CHECK);
 878   assert(nest_host != nullptr, "unexpected nullptr nest_host");
 879 
 880   DumpTimeClassInfo* info = _dumptime_table->get(lambda_ik);
 881   if (info != nullptr && !lambda_ik->is_non_strong_hidden() && is_builtin(lambda_ik) && is_builtin(caller_ik)
 882       // Don't include the lambda proxy if its nest host is not in the "linked" state.
 883       && nest_host->is_linked()) {
 884     // Set _is_registered_lambda_proxy in DumpTimeClassInfo so that the lambda_ik
 885     // won't be excluded during dumping of shared archive.
 886     info->_is_registered_lambda_proxy = true;
 887     info->set_nest_host(nest_host);
 888 
 889     LambdaProxyClassKey key(caller_ik,
 890                             invoked_name,
 891                             invoked_type,
 892                             method_type,
 893                             member_method,
 894                             instantiated_method_type);
 895     add_to_dump_time_lambda_proxy_class_dictionary(key, lambda_ik);
 896   }
 897 }
 898 
 899 InstanceKlass* SystemDictionaryShared::get_shared_lambda_proxy_class(InstanceKlass* caller_ik,
 900                                                                      Symbol* invoked_name,
 901                                                                      Symbol* invoked_type,
 902                                                                      Symbol* method_type,
 903                                                                      Method* member_method,
 904                                                                      Symbol* instantiated_method_type) {
 905   if (CDSConfig::is_dumping_final_static_archive()) {
 906     return nullptr;
 907   }
 908 
 909   assert(caller_ik != nullptr, "sanity");
 910   assert(invoked_name != nullptr, "sanity");
 911   assert(invoked_type != nullptr, "sanity");
 912   assert(method_type != nullptr, "sanity");
 913   assert(instantiated_method_type != nullptr, "sanity");
 914 
 915   if (!caller_ik->is_shared()     ||
 916       !invoked_name->is_shared()  ||
 917       !invoked_type->is_shared()  ||
 918       !method_type->is_shared()   ||
 919       (member_method != nullptr && !member_method->is_shared()) ||
 920       !instantiated_method_type->is_shared()) {
 921     // These can't be represented as u4 offset, but we wouldn't have archived a lambda proxy in this case anyway.
 922     return nullptr;
 923   }
 924 
 925   MutexLocker ml(CDSLambda_lock, Mutex::_no_safepoint_check_flag);
 926   RunTimeLambdaProxyClassKey key =
 927     RunTimeLambdaProxyClassKey::init_for_runtime(caller_ik, invoked_name, invoked_type,
 928                                                  method_type, member_method, instantiated_method_type);
 929 
 930   // Try to retrieve the lambda proxy class from static archive.
 931   const RunTimeLambdaProxyClassInfo* info = _static_archive.lookup_lambda_proxy_class(&key);
 932   InstanceKlass* proxy_klass = retrieve_lambda_proxy_class(info);
 933   if (proxy_klass == nullptr) {
 934     if (info != nullptr && log_is_enabled(Debug, cds)) {
 935       ResourceMark rm;
 936       log_debug(cds)("Used all static archived lambda proxy classes for: %s %s%s",
 937                      caller_ik->external_name(), invoked_name->as_C_string(), invoked_type->as_C_string());
 938     }
 939   } else {
 940     return proxy_klass;
 941   }
 942 
 943   // Retrieving from static archive is unsuccessful, try dynamic archive.
 944   info = _dynamic_archive.lookup_lambda_proxy_class(&key);
 945   proxy_klass = retrieve_lambda_proxy_class(info);
 946   if (proxy_klass == nullptr) {
 947     if (info != nullptr && log_is_enabled(Debug, cds)) {
 948       ResourceMark rm;
 949       log_debug(cds)("Used all dynamic archived lambda proxy classes for: %s %s%s",
 950                      caller_ik->external_name(), invoked_name->as_C_string(), invoked_type->as_C_string());
 951     }
 952   }
 953   return proxy_klass;
 954 }
 955 
 956 InstanceKlass* SystemDictionaryShared::retrieve_lambda_proxy_class(const RunTimeLambdaProxyClassInfo* info) {
 957   InstanceKlass* proxy_klass = nullptr;
 958   if (info != nullptr) {
 959     InstanceKlass* curr_klass = info->proxy_klass_head();
 960     InstanceKlass* prev_klass = curr_klass;
 961     if (curr_klass->lambda_proxy_is_available()) {
 962       while (curr_klass->next_link() != nullptr) {
 963         prev_klass = curr_klass;
 964         curr_klass = InstanceKlass::cast(curr_klass->next_link());
 965       }
 966       assert(curr_klass->is_hidden(), "must be");
 967       assert(curr_klass->lambda_proxy_is_available(), "must be");
 968 
 969       prev_klass->set_next_link(nullptr);
 970       proxy_klass = curr_klass;
 971       proxy_klass->clear_lambda_proxy_is_available();
 972       if (log_is_enabled(Debug, cds)) {
 973         ResourceMark rm;
 974         log_debug(cds)("Loaded lambda proxy: " PTR_FORMAT " %s ", p2i(proxy_klass), proxy_klass->external_name());
 975       }
 976     }
 977   }
 978   return proxy_klass;
 979 }
 980 
 981 InstanceKlass* SystemDictionaryShared::get_shared_nest_host(InstanceKlass* lambda_ik) {
 982   assert(!CDSConfig::is_dumping_static_archive() && CDSConfig::is_using_archive(), "called at run time with CDS enabled only");
 983   RunTimeClassInfo* record = RunTimeClassInfo::get_for(lambda_ik);
 984   return record->nest_host();
 985 }
 986 
 987 InstanceKlass* SystemDictionaryShared::prepare_shared_lambda_proxy_class(InstanceKlass* lambda_ik,
 988                                                                          InstanceKlass* caller_ik, TRAPS) {
 989   Handle class_loader(THREAD, caller_ik->class_loader());
 990   Handle protection_domain;
 991   PackageEntry* pkg_entry = caller_ik->package();
 992   if (caller_ik->class_loader() != nullptr) {
 993     protection_domain = CDSProtectionDomain::init_security_info(class_loader, caller_ik, pkg_entry, CHECK_NULL);
 994   }
 995 
 996   InstanceKlass* shared_nest_host = get_shared_nest_host(lambda_ik);
 997   assert(shared_nest_host != nullptr, "unexpected nullptr _nest_host");
 998 
 999   InstanceKlass* loaded_lambda =
1000     SystemDictionary::load_shared_lambda_proxy_class(lambda_ik, class_loader, protection_domain, pkg_entry, CHECK_NULL);
1001 
1002   if (loaded_lambda == nullptr) {
1003     return nullptr;
1004   }
1005 
1006   // Ensures the nest host is the same as the lambda proxy's
1007   // nest host recorded at dump time.
1008   InstanceKlass* nest_host = caller_ik->nest_host(THREAD);
1009   assert(nest_host == shared_nest_host, "mismatched nest host");
1010 
1011   EventClassLoad class_load_start_event;
1012 
1013   // Add to class hierarchy, and do possible deoptimizations.
1014   loaded_lambda->add_to_hierarchy(THREAD);
1015   // But, do not add to dictionary.
1016 
1017   loaded_lambda->link_class(CHECK_NULL);
1018   // notify jvmti
1019   if (JvmtiExport::should_post_class_load()) {
1020     JvmtiExport::post_class_load(THREAD, loaded_lambda);
1021   }
1022   if (class_load_start_event.should_commit()) {
1023     SystemDictionary::post_class_load_event(&class_load_start_event, loaded_lambda, ClassLoaderData::class_loader_data(class_loader()));
1024   }
1025 
1026   loaded_lambda->initialize(CHECK_NULL);
1027 
1028   return loaded_lambda;
1029 }
1030 
1031 void SystemDictionaryShared::check_verification_constraints(InstanceKlass* klass,
1032                                                             TRAPS) {
1033   assert(CDSConfig::is_using_archive(), "called at run time with CDS enabled only");
1034   RunTimeClassInfo* record = RunTimeClassInfo::get_for(klass);
1035 
1036   int length = record->num_verifier_constraints();
1037   if (length > 0) {
1038     for (int i = 0; i < length; i++) {
1039       RunTimeClassInfo::RTVerifierConstraint* vc = record->verifier_constraint_at(i);
1040       Symbol* name      = vc->name();
1041       Symbol* from_name = vc->from_name();
1042 
1043       if (log_is_enabled(Trace, cds, verification)) {
1044         ResourceMark rm(THREAD);
1045         log_trace(cds, verification)("check_verification_constraint: %s: %s must be subclass of %s [0x%x]",
1046                                      klass->external_name(), from_name->as_klass_external_name(),
1047                                      name->as_klass_external_name(), record->verifier_constraint_flag(i));
1048       }
1049 
1050       bool ok = VerificationType::resolve_and_check_assignability(klass, name, from_name,
1051          record->from_field_is_protected(i), record->from_is_array(i), record->from_is_object(i), CHECK);
1052       if (!ok) {
1053         ResourceMark rm(THREAD);
1054         stringStream ss;
1055 
1056         ss.print_cr("Bad type on operand stack");
1057         ss.print_cr("Exception Details:");
1058         ss.print_cr("  Location:\n    %s", klass->name()->as_C_string());
1059         ss.print_cr("  Reason:\n    Type '%s' is not assignable to '%s'",
1060                     from_name->as_quoted_ascii(), name->as_quoted_ascii());
1061         THROW_MSG(vmSymbols::java_lang_VerifyError(), ss.as_string());
1062       }
1063     }
1064   }
1065 }
1066 
1067 void SystemDictionaryShared::copy_verification_constraints_from_preimage(InstanceKlass* klass) {
1068   assert(CDSConfig::is_using_archive(), "called at run time with CDS enabled only");
1069   DumpTimeClassInfo* dt_info = get_info(klass);
1070   RunTimeClassInfo* rt_info = RunTimeClassInfo::get_for(klass); // from preimage
1071 
1072   int length = rt_info->num_verifier_constraints();
1073   if (length > 0) {
1074     for (int i = 0; i < length; i++) {
1075       RunTimeClassInfo::RTVerifierConstraint* vc = rt_info->verifier_constraint_at(i);
1076       Symbol* name      = vc->name();
1077       Symbol* from_name = vc->from_name();
1078 
1079       dt_info->add_verification_constraint(klass, name, from_name,
1080          rt_info->from_field_is_protected(i), rt_info->from_is_array(i), rt_info->from_is_object(i));
1081     }
1082   }
1083 }
1084 
1085 static oop get_class_loader_by(char type) {
1086   if (type == (char)ClassLoader::BOOT_LOADER) {
1087     return (oop)nullptr;
1088   } else if (type == (char)ClassLoader::PLATFORM_LOADER) {
1089     return SystemDictionary::java_platform_loader();
1090   } else {
1091     assert (type == (char)ClassLoader::APP_LOADER, "Sanity");
1092     return SystemDictionary::java_system_loader();
1093   }
1094 }
1095 
1096 // Record class loader constraints that are checked inside
1097 // InstanceKlass::link_class(), so that these can be checked quickly
1098 // at runtime without laying out the vtable/itables.
1099 void SystemDictionaryShared::record_linking_constraint(Symbol* name, InstanceKlass* klass,
1100                                                     Handle loader1, Handle loader2) {
1101   // A linking constraint check is executed when:
1102   //   - klass extends or implements type S
1103   //   - klass overrides method S.M(...) with X.M
1104   //     - If klass defines the method M, X is
1105   //       the same as klass.
1106   //     - If klass does not define the method M,
1107   //       X must be a supertype of klass and X.M is
1108   //       a default method defined by X.
1109   //   - loader1 = X->class_loader()
1110   //   - loader2 = S->class_loader()
1111   //   - loader1 != loader2
1112   //   - M's parameter(s) include an object type T
1113   // We require that
1114   //   - whenever loader1 and loader2 try to
1115   //     resolve the type T, they must always resolve to
1116   //     the same InstanceKlass.
1117   // NOTE: type T may or may not be currently resolved in
1118   // either of these two loaders. The check itself does not
1119   // try to resolve T.
1120   oop klass_loader = klass->class_loader();
1121 
1122   if (!is_system_class_loader(klass_loader) &&
1123       !is_platform_class_loader(klass_loader)) {
1124     // If klass is loaded by system/platform loaders, we can
1125     // guarantee that klass and S must be loaded by the same
1126     // respective loader between dump time and run time, and
1127     // the exact same check on (name, loader1, loader2) will
1128     // be executed. Hence, we can cache this check and execute
1129     // it at runtime without walking the vtable/itables.
1130     //
1131     // This cannot be guaranteed for classes loaded by other
1132     // loaders, so we bail.
1133     return;
1134   }
1135 
1136   assert(is_builtin(klass), "must be");
1137   assert(klass_loader != nullptr, "should not be called for boot loader");
1138   assert(loader1 != loader2, "must be");
1139 
1140   if (CDSConfig::is_dumping_dynamic_archive() && Thread::current()->is_VM_thread()) {
1141     // We are re-laying out the vtable/itables of the *copy* of
1142     // a class during the final stage of dynamic dumping. The
1143     // linking constraints for this class has already been recorded.
1144     return;
1145   }
1146   assert(!Thread::current()->is_VM_thread(), "must be");
1147 
1148   assert(CDSConfig::is_dumping_archive(), "sanity");
1149   DumpTimeClassInfo* info = get_info(klass);
1150   info->record_linking_constraint(name, loader1, loader2);
1151 }
1152 
1153 // returns true IFF there's no need to re-initialize the i/v-tables for klass for
1154 // the purpose of checking class loader constraints.
1155 bool SystemDictionaryShared::check_linking_constraints(Thread* current, InstanceKlass* klass) {
1156   assert(CDSConfig::is_using_archive(), "called at run time with CDS enabled only");
1157   LogTarget(Info, class, loader, constraints) log;
1158   if (klass->is_shared_boot_class()) {
1159     // No class loader constraint check performed for boot classes.
1160     return true;
1161   }
1162   if (klass->is_shared_platform_class() || klass->is_shared_app_class()) {
1163     RunTimeClassInfo* info = RunTimeClassInfo::get_for(klass);
1164     assert(info != nullptr, "Sanity");
1165     if (info->num_loader_constraints() > 0) {
1166       HandleMark hm(current);
1167       for (int i = 0; i < info->num_loader_constraints(); i++) {
1168         RunTimeClassInfo::RTLoaderConstraint* lc = info->loader_constraint_at(i);
1169         Symbol* name = lc->constraint_name();
1170         Handle loader1(current, get_class_loader_by(lc->_loader_type1));
1171         Handle loader2(current, get_class_loader_by(lc->_loader_type2));
1172         if (log.is_enabled()) {
1173           ResourceMark rm(current);
1174           log.print("[CDS add loader constraint for class %s symbol %s loader[0] %s loader[1] %s",
1175                     klass->external_name(), name->as_C_string(),
1176                     ClassLoaderData::class_loader_data(loader1())->loader_name_and_id(),
1177                     ClassLoaderData::class_loader_data(loader2())->loader_name_and_id());
1178         }
1179         if (!SystemDictionary::add_loader_constraint(name, klass, loader1, loader2)) {
1180           // Loader constraint violation has been found. The caller
1181           // will re-layout the vtable/itables to produce the correct
1182           // exception.
1183           if (log.is_enabled()) {
1184             log.print(" failed]");
1185           }
1186           return false;
1187         }
1188         if (log.is_enabled()) {
1189             log.print(" succeeded]");
1190         }
1191       }
1192       return true; // for all recorded constraints added successfully.
1193     }
1194   }
1195   if (log.is_enabled()) {
1196     ResourceMark rm(current);
1197     log.print("[CDS has not recorded loader constraint for class %s]", klass->external_name());
1198   }
1199   return false;
1200 }
1201 
1202 void SystemDictionaryShared::copy_linking_constraints_from_preimage(InstanceKlass* klass) {
1203   assert(CDSConfig::is_using_archive(), "called at run time with CDS enabled only");
1204   JavaThread* current = JavaThread::current();
1205   if (klass->is_shared_platform_class() || klass->is_shared_app_class()) {
1206     RunTimeClassInfo* rt_info = RunTimeClassInfo::get_for(klass); // from preimage
1207 
1208     if (rt_info->num_loader_constraints() > 0) {
1209       for (int i = 0; i < rt_info->num_loader_constraints(); i++) {
1210         RunTimeClassInfo::RTLoaderConstraint* lc = rt_info->loader_constraint_at(i);
1211         Symbol* name = lc->constraint_name();
1212         Handle loader1(current, get_class_loader_by(lc->_loader_type1));
1213         Handle loader2(current, get_class_loader_by(lc->_loader_type2));
1214         record_linking_constraint(name, klass, loader1, loader2);
1215       }
1216     }
1217   }
1218 }
1219 
1220 bool SystemDictionaryShared::is_supported_invokedynamic(BootstrapInfo* bsi) {
1221   LogTarget(Debug, cds, lambda) log;
1222   if (bsi->arg_values() == nullptr || !bsi->arg_values()->is_objArray()) {
1223     if (log.is_enabled()) {
1224       LogStream log_stream(log);
1225       log.print("bsi check failed");
1226       log.print("    bsi->arg_values().not_null() %d", bsi->arg_values().not_null());
1227       if (bsi->arg_values().not_null()) {
1228         log.print("    bsi->arg_values()->is_objArray() %d", bsi->arg_values()->is_objArray());
1229         bsi->print_msg_on(&log_stream);
1230       }
1231     }
1232     return false;
1233   }
1234 
1235   Handle bsm = bsi->bsm();
1236   if (bsm.is_null() || !java_lang_invoke_DirectMethodHandle::is_instance(bsm())) {
1237     if (log.is_enabled()) {
1238       log.print("bsm check failed");
1239       log.print("    bsm.is_null() %d", bsm.is_null());
1240       log.print("    java_lang_invoke_DirectMethodHandle::is_instance(bsm()) %d",
1241         java_lang_invoke_DirectMethodHandle::is_instance(bsm()));
1242     }
1243     return false;
1244   }
1245 
1246   oop mn = java_lang_invoke_DirectMethodHandle::member(bsm());
1247   Method* method = java_lang_invoke_MemberName::vmtarget(mn);
1248   if (method->klass_name()->equals("java/lang/invoke/LambdaMetafactory") &&
1249       method->name()->equals("metafactory") &&
1250       method->signature()->equals("(Ljava/lang/invoke/MethodHandles$Lookup;Ljava/lang/String;"
1251             "Ljava/lang/invoke/MethodType;Ljava/lang/invoke/MethodType;Ljava/lang/invoke/MethodHandle;"
1252             "Ljava/lang/invoke/MethodType;)Ljava/lang/invoke/CallSite;")) {
1253       return true;
1254   } else {
1255     if (log.is_enabled()) {
1256       ResourceMark rm;
1257       log.print("method check failed");
1258       log.print("    klass_name() %s", method->klass_name()->as_C_string());
1259       log.print("    name() %s", method->name()->as_C_string());
1260       log.print("    signature() %s", method->signature()->as_C_string());
1261     }
1262   }
1263 
1264   return false;
1265 }
1266 
1267 class EstimateSizeForArchive : StackObj {
1268   size_t _shared_class_info_size;
1269   int _num_builtin_klasses;
1270   int _num_unregistered_klasses;
1271 
1272 public:
1273   EstimateSizeForArchive() {
1274     _shared_class_info_size = 0;
1275     _num_builtin_klasses = 0;
1276     _num_unregistered_klasses = 0;
1277   }
1278 
1279   void do_entry(InstanceKlass* k, DumpTimeClassInfo& info) {
1280     if (!info.is_excluded()) {
1281       size_t byte_size = info.runtime_info_bytesize();
1282       _shared_class_info_size += align_up(byte_size, SharedSpaceObjectAlignment);
1283     }
1284   }
1285 
1286   size_t total() {
1287     return _shared_class_info_size;
1288   }
1289 };
1290 
1291 size_t SystemDictionaryShared::estimate_size_for_archive() {
1292   EstimateSizeForArchive est;
1293   _dumptime_table->iterate_all_live_classes(&est);
1294   size_t total_size = est.total() +
1295     CompactHashtableWriter::estimate_size(_dumptime_table->count_of(true)) +
1296     CompactHashtableWriter::estimate_size(_dumptime_table->count_of(false));
1297 
1298   size_t bytesize = align_up(sizeof(RunTimeLambdaProxyClassInfo), SharedSpaceObjectAlignment);
1299   total_size +=
1300       (bytesize * _dumptime_lambda_proxy_class_dictionary->_count) +
1301       CompactHashtableWriter::estimate_size(_dumptime_lambda_proxy_class_dictionary->_count);
1302 
1303   return total_size;
1304 }
1305 
1306 unsigned int SystemDictionaryShared::hash_for_shared_dictionary(address ptr) {
1307   if (ArchiveBuilder::is_active() && ArchiveBuilder::current()->is_in_buffer_space(ptr)) {
1308     uintx offset = ArchiveBuilder::current()->any_to_offset(ptr);
1309     unsigned int hash = primitive_hash<uintx>(offset);
1310     DEBUG_ONLY({
1311         if (MetaspaceObj::is_shared((const MetaspaceObj*)ptr)) {
1312           assert(hash == SystemDictionaryShared::hash_for_shared_dictionary_quick(ptr), "must be");
1313         }
1314       });
1315     return hash;
1316   } else {
1317     return SystemDictionaryShared::hash_for_shared_dictionary_quick(ptr);
1318   }
1319 }
1320 
1321 class CopyLambdaProxyClassInfoToArchive : StackObj {
1322   CompactHashtableWriter* _writer;
1323   ArchiveBuilder* _builder;
1324 public:
1325   CopyLambdaProxyClassInfoToArchive(CompactHashtableWriter* writer)
1326   : _writer(writer), _builder(ArchiveBuilder::current()) {}
1327   bool do_entry(LambdaProxyClassKey& key, DumpTimeLambdaProxyClassInfo& info) {
1328     // In static dump, info._proxy_klasses->at(0) is already relocated to point to the archived class
1329     // (not the original class).
1330     ResourceMark rm;
1331     log_info(cds,dynamic)("Archiving hidden %s", info._proxy_klasses->at(0)->external_name());
1332     size_t byte_size = sizeof(RunTimeLambdaProxyClassInfo);
1333     RunTimeLambdaProxyClassInfo* runtime_info =
1334         (RunTimeLambdaProxyClassInfo*)ArchiveBuilder::ro_region_alloc(byte_size);
1335     runtime_info->init(key, info);
1336     unsigned int hash = runtime_info->hash();
1337     u4 delta = _builder->any_to_offset_u4((void*)runtime_info);
1338     _writer->add(hash, delta);
1339     return true;
1340   }
1341 };
1342 
1343 class AdjustLambdaProxyClassInfo : StackObj {
1344 public:
1345   AdjustLambdaProxyClassInfo() {}
1346   bool do_entry(LambdaProxyClassKey& key, DumpTimeLambdaProxyClassInfo& info) {
1347     int len = info._proxy_klasses->length();
1348     InstanceKlass* last_buff_k = nullptr;
1349 
1350     for (int i = len - 1; i >= 0; i--) {
1351       InstanceKlass* orig_k = info._proxy_klasses->at(i);
1352       InstanceKlass* buff_k = ArchiveBuilder::current()->get_buffered_addr(orig_k);
1353       assert(ArchiveBuilder::current()->is_in_buffer_space(buff_k), "must be");
1354       buff_k->set_lambda_proxy_is_available();
1355       buff_k->set_next_link(last_buff_k);
1356       if (last_buff_k != nullptr) {
1357         ArchivePtrMarker::mark_pointer(buff_k->next_link_addr());
1358       }
1359       last_buff_k = buff_k;
1360     }
1361 
1362     return true;
1363   }
1364 };
1365 
1366 class CopySharedClassInfoToArchive : StackObj {
1367   CompactHashtableWriter* _writer;
1368   bool _is_builtin;
1369   ArchiveBuilder *_builder;
1370 public:
1371   CopySharedClassInfoToArchive(CompactHashtableWriter* writer,
1372                                bool is_builtin)
1373     : _writer(writer), _is_builtin(is_builtin), _builder(ArchiveBuilder::current()) {}
1374 
1375   void do_entry(InstanceKlass* k, DumpTimeClassInfo& info) {
1376     if (!info.is_excluded() && info.is_builtin() == _is_builtin) {
1377       size_t byte_size = info.runtime_info_bytesize();
1378       RunTimeClassInfo* record;
1379       record = (RunTimeClassInfo*)ArchiveBuilder::ro_region_alloc(byte_size);
1380       record->init(info);
1381 
1382       unsigned int hash;
1383       Symbol* name = info._klass->name();
1384       name = ArchiveBuilder::current()->get_buffered_addr(name);
1385       hash = SystemDictionaryShared::hash_for_shared_dictionary((address)name);
1386       u4 delta = _builder->buffer_to_offset_u4((address)record);
1387       if (_is_builtin && info._klass->is_hidden()) {
1388         // skip
1389       } else {
1390         _writer->add(hash, delta);
1391       }
1392       if (log_is_enabled(Trace, cds, hashtables)) {
1393         ResourceMark rm;
1394         log_trace(cds,hashtables)("%s dictionary: %s", (_is_builtin ? "builtin" : "unregistered"), info._klass->external_name());
1395       }
1396 
1397       // Save this for quick runtime lookup of InstanceKlass* -> RunTimeClassInfo*
1398       InstanceKlass* buffered_klass = ArchiveBuilder::current()->get_buffered_addr(info._klass);
1399       RunTimeClassInfo::set_for(buffered_klass, record);
1400     }
1401   }
1402 };
1403 
1404 void SystemDictionaryShared::write_lambda_proxy_class_dictionary(LambdaProxyClassDictionary *dictionary) {
1405   CompactHashtableStats stats;
1406   dictionary->reset();
1407   CompactHashtableWriter writer(_dumptime_lambda_proxy_class_dictionary->_count, &stats);
1408   CopyLambdaProxyClassInfoToArchive copy(&writer);
1409   _dumptime_lambda_proxy_class_dictionary->iterate(&copy);
1410   writer.dump(dictionary, "lambda proxy class dictionary");
1411 }
1412 
1413 void SystemDictionaryShared::write_dictionary(RunTimeSharedDictionary* dictionary,
1414                                               bool is_builtin) {
1415   CompactHashtableStats stats;
1416   dictionary->reset();
1417   CompactHashtableWriter writer(_dumptime_table->count_of(is_builtin), &stats);
1418   CopySharedClassInfoToArchive copy(&writer, is_builtin);
1419   assert_lock_strong(DumpTimeTable_lock);
1420   _dumptime_table->iterate_all_live_classes(&copy);
1421   writer.dump(dictionary, is_builtin ? "builtin dictionary" : "unregistered dictionary");
1422 }
1423 
1424 void SystemDictionaryShared::write_to_archive(bool is_static_archive) {
1425   ArchiveInfo* archive = get_archive(is_static_archive);
1426 
1427   write_dictionary(&archive->_builtin_dictionary, true);
1428   write_dictionary(&archive->_unregistered_dictionary, false);
1429 
1430   write_lambda_proxy_class_dictionary(&archive->_lambda_proxy_class_dictionary);
1431 }
1432 
1433 void SystemDictionaryShared::adjust_lambda_proxy_class_dictionary() {
1434   AdjustLambdaProxyClassInfo adjuster;
1435   _dumptime_lambda_proxy_class_dictionary->iterate(&adjuster);
1436 }
1437 
1438 void SystemDictionaryShared::serialize_dictionary_headers(SerializeClosure* soc,
1439                                                           bool is_static_archive) {
1440   ArchiveInfo* archive = get_archive(is_static_archive);
1441 
1442   archive->_builtin_dictionary.serialize_header(soc);
1443   archive->_unregistered_dictionary.serialize_header(soc);
1444   archive->_lambda_proxy_class_dictionary.serialize_header(soc);
1445 }
1446 
1447 void SystemDictionaryShared::serialize_vm_classes(SerializeClosure* soc) {
1448   for (auto id : EnumRange<vmClassID>{}) {
1449     soc->do_ptr(vmClasses::klass_addr_at(id));
1450   }
1451 }
1452 
1453 const RunTimeClassInfo*
1454 SystemDictionaryShared::find_record(RunTimeSharedDictionary* static_dict, RunTimeSharedDictionary* dynamic_dict, Symbol* name) {
1455   if (!CDSConfig::is_using_archive() || !name->is_shared()) {
1456     // The names of all shared classes must also be a shared Symbol.
1457     return nullptr;
1458   }
1459 
1460   unsigned int hash = SystemDictionaryShared::hash_for_shared_dictionary_quick(name);
1461   const RunTimeClassInfo* record = nullptr;
1462   if (DynamicArchive::is_mapped()) {
1463     // Use the regenerated holder classes in the dynamic archive as they
1464     // have more methods than those in the base archive.
1465     if (LambdaFormInvokers::may_be_regenerated_class(name)) {
1466       record = dynamic_dict->lookup(name, hash, 0);
1467       if (record != nullptr) {
1468         return record;
1469       }
1470     }
1471   }
1472 
1473   if (!MetaspaceShared::is_shared_dynamic(name)) {
1474     // The names of all shared classes in the static dict must also be in the
1475     // static archive
1476     record = static_dict->lookup(name, hash, 0);
1477   }
1478 
1479   if (record == nullptr && DynamicArchive::is_mapped()) {
1480     record = dynamic_dict->lookup(name, hash, 0);
1481   }
1482 
1483   return record;
1484 }
1485 
1486 InstanceKlass* SystemDictionaryShared::find_builtin_class(Symbol* name) {
1487   const RunTimeClassInfo* record = find_record(&_static_archive._builtin_dictionary,
1488                                                &_dynamic_archive._builtin_dictionary,
1489                                                name);
1490   if (record != nullptr) {
1491     assert(!record->klass()->is_hidden(), "hidden class cannot be looked up by name");
1492     DEBUG_ONLY(check_klass_after_loading(record->klass());)
1493     // We did not save the classfile data of the generated LambdaForm invoker classes,
1494     // so we cannot support CLFH for such classes.
1495     if (record->klass()->is_generated_shared_class() && JvmtiExport::should_post_class_file_load_hook()) {
1496        return nullptr;
1497     }
1498     return record->klass();
1499   } else {
1500     return nullptr;
1501   }
1502 }
1503 
1504 void SystemDictionaryShared::update_shared_entry(InstanceKlass* k, int id) {
1505   assert(CDSConfig::is_dumping_static_archive(), "class ID is used only for static dump (from classlist)");
1506   DumpTimeClassInfo* info = get_info(k);
1507   info->_id = id;
1508 }
1509 
1510 const char* SystemDictionaryShared::class_loader_name_for_shared(Klass* k) {
1511   assert(k != nullptr, "Sanity");
1512   assert(k->is_shared(), "Must be");
1513   assert(k->is_instance_klass(), "Must be");
1514   InstanceKlass* ik = InstanceKlass::cast(k);
1515   if (ik->is_shared_boot_class()) {
1516     return "boot_loader";
1517   } else if (ik->is_shared_platform_class()) {
1518     return "platform_loader";
1519   } else if (ik->is_shared_app_class()) {
1520     return "app_loader";
1521   } else if (ik->is_shared_unregistered_class()) {
1522     return "unregistered_loader";
1523   } else {
1524     return "unknown loader";
1525   }
1526 }
1527 
1528 class SharedDictionaryPrinter : StackObj {
1529   outputStream* _st;
1530   int _index;
1531 public:
1532   SharedDictionaryPrinter(outputStream* st) : _st(st), _index(0) {}
1533 
1534   void do_value(const RunTimeClassInfo* record) {
1535     ResourceMark rm;
1536     _st->print_cr("%4d: %s %s", _index++, record->klass()->external_name(),
1537         SystemDictionaryShared::class_loader_name_for_shared(record->klass()));
1538     if (record->klass()->array_klasses() != nullptr) {
1539       record->klass()->array_klasses()->cds_print_value_on(_st);
1540       _st->cr();
1541     }
1542   }
1543   int index() const { return _index; }
1544 };
1545 
1546 class SharedLambdaDictionaryPrinter : StackObj {
1547   outputStream* _st;
1548   int _index;
1549 public:
1550   SharedLambdaDictionaryPrinter(outputStream* st, int idx) : _st(st), _index(idx) {}
1551 
1552   void do_value(const RunTimeLambdaProxyClassInfo* record) {
1553     if (record->proxy_klass_head()->lambda_proxy_is_available()) {
1554       ResourceMark rm;
1555       Klass* k = record->proxy_klass_head();
1556       while (k != nullptr) {
1557         _st->print_cr("%4d: %s %s", _index++, k->external_name(),
1558                       SystemDictionaryShared::class_loader_name_for_shared(k));
1559         k = k->next_link();
1560       }
1561     }
1562   }
1563 };
1564 
1565 void SystemDictionaryShared::ArchiveInfo::print_on(const char* prefix,
1566                                                    outputStream* st) {
1567   st->print_cr("%sShared Dictionary", prefix);
1568   SharedDictionaryPrinter p(st);
1569   st->print_cr("%sShared Builtin Dictionary", prefix);
1570   _builtin_dictionary.iterate(&p);
1571   st->print_cr("%sShared Unregistered Dictionary", prefix);
1572   _unregistered_dictionary.iterate(&p);
1573   if (!_lambda_proxy_class_dictionary.empty()) {
1574     st->print_cr("%sShared Lambda Dictionary", prefix);
1575     SharedLambdaDictionaryPrinter ldp(st, p.index());
1576     _lambda_proxy_class_dictionary.iterate(&ldp);
1577   }
1578 }
1579 
1580 void SystemDictionaryShared::ArchiveInfo::print_table_statistics(const char* prefix,
1581                                                                  outputStream* st) {
1582   st->print_cr("%sArchve Statistics", prefix);
1583   _builtin_dictionary.print_table_statistics(st, "Builtin Shared Dictionary");
1584   _unregistered_dictionary.print_table_statistics(st, "Unregistered Shared Dictionary");
1585   _lambda_proxy_class_dictionary.print_table_statistics(st, "Lambda Shared Dictionary");
1586 }
1587 
1588 void SystemDictionaryShared::print_shared_archive(outputStream* st, bool is_static) {
1589   if (CDSConfig::is_using_archive()) {
1590     if (is_static) {
1591       _static_archive.print_on("", st);
1592     } else {
1593       if (DynamicArchive::is_mapped()) {
1594         _dynamic_archive.print_on("Dynamic ", st);
1595       }
1596     }
1597   }
1598 }
1599 
1600 void SystemDictionaryShared::print_on(outputStream* st) {
1601   print_shared_archive(st, true);
1602   print_shared_archive(st, false);
1603 }
1604 
1605 void SystemDictionaryShared::print_table_statistics(outputStream* st) {
1606   if (CDSConfig::is_using_archive()) {
1607     _static_archive.print_table_statistics("Static ", st);
1608     if (DynamicArchive::is_mapped()) {
1609       _dynamic_archive.print_table_statistics("Dynamic ", st);
1610     }
1611   }
1612 }
1613 
1614 bool SystemDictionaryShared::is_dumptime_table_empty() {
1615   assert_lock_strong(DumpTimeTable_lock);
1616   _dumptime_table->update_counts();
1617   if (_dumptime_table->count_of(true) == 0 && _dumptime_table->count_of(false) == 0){
1618     return true;
1619   }
1620   return false;
1621 }
1622 
1623 class CleanupDumpTimeLambdaProxyClassTable: StackObj {
1624  public:
1625   bool do_entry(LambdaProxyClassKey& key, DumpTimeLambdaProxyClassInfo& info) {
1626     assert_lock_strong(DumpTimeTable_lock);
1627     InstanceKlass* caller_ik = key.caller_ik();
1628     InstanceKlass* nest_host = caller_ik->nest_host_not_null();
1629 
1630     // If the caller class and/or nest_host are excluded, the associated lambda proxy
1631     // must also be excluded.
1632     bool always_exclude = SystemDictionaryShared::check_for_exclusion(caller_ik, nullptr) ||
1633                           SystemDictionaryShared::check_for_exclusion(nest_host, nullptr);
1634 
1635     for (int i = info._proxy_klasses->length() - 1; i >= 0; i--) {
1636       InstanceKlass* ik = info._proxy_klasses->at(i);
1637       if (always_exclude || SystemDictionaryShared::check_for_exclusion(ik, nullptr)) {
1638         SystemDictionaryShared::reset_registered_lambda_proxy_class(ik);
1639         info._proxy_klasses->remove_at(i);
1640       }
1641     }
1642     return info._proxy_klasses->length() == 0 ? true /* delete the node*/ : false;
1643   }
1644 };
1645 
1646 void SystemDictionaryShared::cleanup_lambda_proxy_class_dictionary() {
1647   assert_lock_strong(DumpTimeTable_lock);
1648   CleanupDumpTimeLambdaProxyClassTable cleanup_proxy_classes;
1649   _dumptime_lambda_proxy_class_dictionary->unlink(&cleanup_proxy_classes);
1650 }
1651 
1652 void SystemDictionaryShared::create_loader_positive_lookup_cache(TRAPS) {
1653   GrowableArray<InstanceKlass*> shared_classes_list;
1654   {
1655     // With static dumping, we have only a single Java thread (see JVM_StartThread) so
1656     // no no other threads should be loading classes. Otherwise, the code below may miss some
1657     // classes that are loaded concurrently.
1658     assert(CDSConfig::is_dumping_static_archive(), "no other threads should be loading classes");
1659 
1660     MutexLocker ml(DumpTimeTable_lock, Mutex::_no_safepoint_check_flag);
1661     _dumptime_table->iterate_all_classes_in_builtin_loaders([&](InstanceKlass* k, DumpTimeClassInfo& info) {
1662         if (!k->is_hidden() && !check_for_exclusion(k, &info)) {
1663           shared_classes_list.append(k);
1664         }
1665       }
1666     );
1667   }
1668 
1669   InstanceKlass* ik = vmClasses::Class_klass();
1670   objArrayOop r = oopFactory::new_objArray(ik, shared_classes_list.length(), CHECK);
1671   objArrayHandle array_h(THREAD, r);
1672 
1673   for (int i = 0; i < shared_classes_list.length(); i++) {
1674     oop mirror = shared_classes_list.at(i)->java_mirror();
1675     Handle mirror_h(THREAD, mirror);
1676     array_h->obj_at_put(i, mirror_h());
1677   }
1678 
1679   TempNewSymbol method = SymbolTable::new_symbol("generatePositiveLookupCache");
1680   TempNewSymbol signature = SymbolTable::new_symbol("([Ljava/lang/Class;)V");
1681 
1682   JavaCallArguments args(Handle(THREAD, SystemDictionary::java_system_loader()));
1683   args.push_oop(array_h);
1684   JavaValue result(T_VOID);
1685   JavaCalls::call_virtual(&result,
1686                           vmClasses::jdk_internal_loader_ClassLoaders_AppClassLoader_klass(),
1687                           method,
1688                           signature,
1689                           &args,
1690                           CHECK);
1691 
1692   if (HAS_PENDING_EXCEPTION) {
1693     Handle exc_handle(THREAD, PENDING_EXCEPTION);
1694     CLEAR_PENDING_EXCEPTION;
1695     ResourceMark rm(THREAD);
1696 
1697     log_warning(cds)("Exception during AppClassLoader::generatePositiveLookupCache() call");
1698     LogStreamHandle(Debug, cds) log;
1699     if (log.is_enabled()) {
1700       java_lang_Throwable::print_stack_trace(exc_handle, &log);
1701     }
1702     return;
1703   }
1704 }