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