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