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