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