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