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