1 /*
   2  * Copyright (c) 2014, 2025, 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 "cds/aotClassFilter.hpp"
  26 #include "cds/aotClassLocation.hpp"
  27 #include "cds/archiveBuilder.hpp"
  28 #include "cds/archiveUtils.hpp"
  29 #include "cds/cdsConfig.hpp"
  30 #include "cds/cdsProtectionDomain.hpp"
  31 #include "cds/classListParser.hpp"
  32 #include "cds/classListWriter.hpp"
  33 #include "cds/dumpTimeClassInfo.inline.hpp"
  34 #include "cds/dynamicArchive.hpp"
  35 #include "cds/filemap.hpp"
  36 #include "cds/heapShared.hpp"
  37 #include "cds/lambdaFormInvokers.inline.hpp"
  38 #include "cds/lambdaProxyClassDictionary.hpp"
  39 #include "cds/lambdaFormInvokers.inline.hpp"
  40 #include "cds/metaspaceShared.hpp"
  41 #include "cds/runTimeClassInfo.hpp"
  42 #include "cds/unregisteredClasses.hpp"
  43 #include "classfile/classFileStream.hpp"
  44 #include "classfile/classLoader.hpp"
  45 #include "classfile/classLoaderData.inline.hpp"
  46 #include "classfile/classLoaderDataGraph.hpp"
  47 #include "classfile/classLoaderExt.hpp"
  48 #include "classfile/dictionary.hpp"
  49 #include "classfile/javaClasses.hpp"
  50 #include "classfile/javaClasses.inline.hpp"
  51 #include "classfile/symbolTable.hpp"
  52 #include "classfile/systemDictionary.hpp"
  53 #include "classfile/systemDictionaryShared.hpp"
  54 #include "classfile/verificationType.hpp"
  55 #include "classfile/vmClasses.hpp"
  56 #include "classfile/vmSymbols.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/compressedKlass.inline.hpp"
  67 #include "oops/instanceKlass.hpp"
  68 #include "oops/klass.inline.hpp"
  69 #include "oops/methodData.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 
  88 // Used by NoClassLoadingMark
  89 DEBUG_ONLY(bool SystemDictionaryShared::_class_loading_may_happen = true;)
  90 
  91 #ifdef ASSERT
  92 static void check_klass_after_loading(const Klass* k) {
  93 #ifdef _LP64
  94   if (k != nullptr && UseCompressedClassPointers && k->needs_narrow_id()) {
  95     CompressedKlassPointers::check_encodable(k);
  96   }
  97 #endif
  98 }
  99 #endif
 100 
 101 InstanceKlass* SystemDictionaryShared::load_shared_class_for_builtin_loader(
 102                  Symbol* class_name, Handle class_loader, TRAPS) {
 103   assert(CDSConfig::is_using_archive(), "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 (!CDSConfig::is_using_archive()) {
 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   return get_info_locked(k);
 203 }
 204 
 205 DumpTimeClassInfo* SystemDictionaryShared::get_info_locked(InstanceKlass* k) {
 206   assert_lock_strong(DumpTimeTable_lock);
 207   DumpTimeClassInfo* info = _dumptime_table->get_info(k);
 208   assert(info != nullptr, "must be");
 209   return info;
 210 }
 211 
 212 bool SystemDictionaryShared::check_for_exclusion(InstanceKlass* k, DumpTimeClassInfo* info) {
 213   if (CDSConfig::is_dumping_dynamic_archive() && MetaspaceShared::is_in_shared_metaspace(k)) {
 214     // We have reached a super type that's already in the base archive. Treat it
 215     // as "not excluded".
 216     return false;
 217   }
 218 
 219   if (info == nullptr) {
 220     info = _dumptime_table->get(k);
 221     assert(info != nullptr, "supertypes of any classes in _dumptime_table must either be shared, or must also be in _dumptime_table");
 222   }
 223 
 224   if (!info->has_checked_exclusion()) {
 225     if (check_for_exclusion_impl(k)) {
 226       info->set_excluded();
 227     }
 228     info->set_has_checked_exclusion();
 229   }
 230 
 231   return info->is_excluded();
 232 }
 233 
 234 // Returns true so the caller can do:    return warn_excluded(".....");
 235 bool SystemDictionaryShared::warn_excluded(InstanceKlass* k, const char* reason) {
 236   ResourceMark rm;
 237   log_warning(cds)("Skipping %s: %s", k->name()->as_C_string(), reason);
 238   return true;
 239 }
 240 
 241 bool SystemDictionaryShared::is_jfr_event_class(InstanceKlass *k) {
 242   while (k) {
 243     if (k->name()->equals("jdk/internal/event/Event")) {
 244       return true;
 245     }
 246     k = k->java_super();
 247   }
 248   return false;
 249 }
 250 
 251 bool SystemDictionaryShared::is_early_klass(InstanceKlass* ik) {
 252   DumpTimeClassInfo* info = _dumptime_table->get(ik);
 253   return (info != nullptr) ? info->is_early_klass() : false;
 254 }
 255 
 256 bool SystemDictionaryShared::check_for_exclusion_impl(InstanceKlass* k) {
 257   if (CDSConfig::is_dumping_final_static_archive() && k->is_shared_unregistered_class()
 258       && k->is_shared()) {
 259     return false; // Do not exclude: unregistered classes are passed from preimage to final image.
 260   }
 261 
 262   if (k->is_in_error_state()) {
 263     return warn_excluded(k, "In error state");
 264   }
 265   if (k->is_scratch_class()) {
 266     return warn_excluded(k, "A scratch class");
 267   }
 268   if (!k->is_loaded()) {
 269     return warn_excluded(k, "Not in loaded state");
 270   }
 271   if (has_been_redefined(k)) {
 272     return warn_excluded(k, "Has been redefined");
 273   }
 274   if (!k->is_hidden() && k->shared_classpath_index() < 0 && is_builtin(k)) {
 275     if (k->name()->starts_with("java/lang/invoke/BoundMethodHandle$Species_")) {
 276       // This class is dynamically generated by the JDK
 277       if (CDSConfig::is_dumping_method_handles()) {
 278         k->set_shared_classpath_index(0);
 279       } else {
 280         ResourceMark rm;
 281         log_info(cds)("Skipping %s because it is dynamically generated", k->name()->as_C_string());
 282         return true; // exclude without warning
 283       }
 284     } else {
 285       // These are classes loaded from unsupported locations (such as those loaded by JVMTI native
 286       // agent during dump time).
 287       return warn_excluded(k, "Unsupported location");
 288     }
 289   }
 290   if (k->signers() != nullptr) {
 291     // We cannot include signed classes in the archive because the certificates
 292     // used during dump time may be different than those used during
 293     // runtime (due to expiration, etc).
 294     return warn_excluded(k, "Signed JAR");
 295   }
 296   if (is_jfr_event_class(k)) {
 297     // We cannot include JFR event classes because they need runtime-specific
 298     // instrumentation in order to work with -XX:FlightRecorderOptions:retransform=false.
 299     // There are only a small number of these classes, so it's not worthwhile to
 300     // support them and make CDS more complicated.
 301     if (!CDSConfig::is_dumping_reflection_data()) { // FIXME: !!! HACK !!!
 302       return warn_excluded(k, "JFR event class");
 303     }
 304   }
 305 
 306   if (!k->is_linked()) {
 307     if (has_class_failed_verification(k)) {
 308       return warn_excluded(k, "Failed verification");
 309     } else if (CDSConfig::is_dumping_aot_linked_classes()) {
 310       // Most loaded classes should have been speculatively linked by MetaspaceShared::link_class_for_cds().
 311       // However, we do not speculatively link old classes, as they are not recorded by
 312       // SystemDictionaryShared::record_linking_constraint(). As a result, such an unlinked
 313       // class may fail to verify in AOTLinkedClassBulkLoader::init_required_classes_for_loader(),
 314       // causing the JVM to fail at bootstrap.
 315       return warn_excluded(k, "Unlinked class not supported by AOTClassLinking");
 316     } else if (CDSConfig::is_dumping_preimage_static_archive()) {
 317       // When dumping the final static archive, we will unconditionally load and link all
 318       // classes from tje preimage. We don't want to get a VerifyError when linking this class.
 319       return warn_excluded(k, "Unlinked class not supported by AOTConfiguration");
 320     }
 321   } else {
 322     if (!k->can_be_verified_at_dumptime() && !CDSConfig::preserve_all_dumptime_verification_states(k)) {
 323       // We have an old class that has been linked (e.g., it's been executed during
 324       // dump time). This class has been verified using the old verifier, which
 325       // doesn't save the verification constraints, so check_verification_constraints()
 326       // won't work at runtime.
 327       // As a result, we cannot store this class. It must be loaded and fully verified
 328       // at runtime.
 329       return warn_excluded(k, "Old class has been linked");
 330     }
 331   }
 332 
 333   InstanceKlass* super = k->java_super();
 334   if (super != nullptr && check_for_exclusion(super, nullptr)) {
 335     ResourceMark rm;
 336     log_warning(cds)("Skipping %s: super class %s is excluded", k->name()->as_C_string(), super->name()->as_C_string());
 337     return true;
 338   }
 339 
 340   Array<InstanceKlass*>* interfaces = k->local_interfaces();
 341   int len = interfaces->length();
 342   for (int i = 0; i < len; i++) {
 343     InstanceKlass* intf = interfaces->at(i);
 344     if (check_for_exclusion(intf, nullptr)) {
 345       ResourceMark rm;
 346       log_warning(cds)("Skipping %s: interface %s is excluded", k->name()->as_C_string(), intf->name()->as_C_string());
 347       return true;
 348     }
 349   }
 350 
 351   if (k == UnregisteredClasses::UnregisteredClassLoader_klass()) {
 352     ResourceMark rm;
 353     log_debug(cds)("Skipping %s: used only when dumping CDS archive", k->name()->as_C_string());
 354     return true;
 355   }
 356 
 357   if (k->name()->equals("jdk/internal/misc/CDS$DummyForDynamicArchive") && !CDSConfig::is_dumping_dynamic_archive()) {
 358     ResourceMark rm;
 359     log_debug(cds)("Skipping %s: used only when dumping dynamic CDS archive", k->name()->as_C_string());
 360     return true;
 361   }
 362 
 363 
 364   return false; // false == k should NOT be excluded
 365 }
 366 
 367 bool SystemDictionaryShared::is_builtin_loader(ClassLoaderData* loader_data) {
 368   oop class_loader = loader_data->class_loader();
 369   return (class_loader == nullptr ||
 370           SystemDictionary::is_system_class_loader(class_loader) ||
 371           SystemDictionary::is_platform_class_loader(class_loader));
 372 }
 373 
 374 bool SystemDictionaryShared::has_platform_or_app_classes() {
 375   if (FileMapInfo::current_info()->has_platform_or_app_classes()) {
 376     return true;
 377   }
 378   if (DynamicArchive::is_mapped() &&
 379       FileMapInfo::dynamic_info()->has_platform_or_app_classes()) {
 380     return true;
 381   }
 382   return false;
 383 }
 384 
 385 // The following stack shows how this code is reached:
 386 //
 387 //   [0] SystemDictionaryShared::find_or_load_shared_class()
 388 //   [1] JVM_FindLoadedClass
 389 //   [2] java.lang.ClassLoader.findLoadedClass0()
 390 //   [3] java.lang.ClassLoader.findLoadedClass()
 391 //   [4] jdk.internal.loader.BuiltinClassLoader.loadClassOrNull()
 392 //   [5] jdk.internal.loader.BuiltinClassLoader.loadClass()
 393 //   [6] jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(), or
 394 //       jdk.internal.loader.ClassLoaders$PlatformClassLoader.loadClass()
 395 //
 396 // AppCDS supports fast class loading for these 2 built-in class loaders:
 397 //    jdk.internal.loader.ClassLoaders$PlatformClassLoader
 398 //    jdk.internal.loader.ClassLoaders$AppClassLoader
 399 // with the following assumptions (based on the JDK core library source code):
 400 //
 401 // [a] these two loaders use the BuiltinClassLoader.loadClassOrNull() to
 402 //     load the named class.
 403 // [b] BuiltinClassLoader.loadClassOrNull() first calls findLoadedClass(name).
 404 // [c] At this point, if we can find the named class inside the
 405 //     shared_dictionary, we can perform further checks (see
 406 //     SystemDictionary::is_shared_class_visible) to ensure that this class
 407 //     was loaded by the same class loader during dump time.
 408 //
 409 // Given these assumptions, we intercept the findLoadedClass() call to invoke
 410 // SystemDictionaryShared::find_or_load_shared_class() to load the shared class from
 411 // the archive for the 2 built-in class loaders. This way,
 412 // we can improve start-up because we avoid decoding the classfile,
 413 // and avoid delegating to the parent loader.
 414 //
 415 // NOTE: there's a lot of assumption about the Java code. If any of that change, this
 416 // needs to be redesigned.
 417 
 418 InstanceKlass* SystemDictionaryShared::find_or_load_shared_class(
 419                  Symbol* name, Handle class_loader, TRAPS) {
 420   InstanceKlass* k = nullptr;
 421   if (CDSConfig::is_using_archive()) {
 422     if (!has_platform_or_app_classes()) {
 423       return nullptr;
 424     }
 425 
 426     if (SystemDictionary::is_system_class_loader(class_loader()) ||
 427         SystemDictionary::is_platform_class_loader(class_loader())) {
 428       ClassLoaderData *loader_data = register_loader(class_loader);
 429       Dictionary* dictionary = loader_data->dictionary();
 430 
 431       // Note: currently, find_or_load_shared_class is called only from
 432       // JVM_FindLoadedClass and used for PlatformClassLoader and AppClassLoader,
 433       // which are parallel-capable loaders, so a lock here is NOT taken.
 434       assert(get_loader_lock_or_null(class_loader) == nullptr, "ObjectLocker not required");
 435       {
 436         MutexLocker mu(THREAD, SystemDictionary_lock);
 437         InstanceKlass* check = dictionary->find_class(THREAD, name);
 438         if (check != nullptr) {
 439           return check;
 440         }
 441       }
 442 
 443       k = load_shared_class_for_builtin_loader(name, class_loader, THREAD);
 444       if (k != nullptr) {
 445         SharedClassLoadingMark slm(THREAD, k);
 446         k = find_or_define_instance_class(name, class_loader, k, CHECK_NULL);
 447       }
 448     }
 449   }
 450 
 451   DEBUG_ONLY(check_klass_after_loading(k);)
 452 
 453   return k;
 454 }
 455 
 456 class UnregisteredClassesTable : public ResourceHashtable<
 457   Symbol*, InstanceKlass*,
 458   15889, // prime number
 459   AnyObj::C_HEAP> {};
 460 
 461 static UnregisteredClassesTable* _unregistered_classes_table = nullptr;
 462 
 463 // true == class was successfully added; false == a duplicated class (with the same name) already exists.
 464 bool SystemDictionaryShared::add_unregistered_class(Thread* current, InstanceKlass* klass) {
 465   // We don't allow duplicated unregistered classes with the same name.
 466   // We only archive the first class with that name that succeeds putting
 467   // itself into the table.
 468   assert(CDSConfig::is_dumping_archive() || ClassListWriter::is_enabled(), "sanity");
 469   MutexLocker ml(current, UnregisteredClassesTable_lock, Mutex::_no_safepoint_check_flag);
 470   Symbol* name = klass->name();
 471   if (_unregistered_classes_table == nullptr) {
 472     _unregistered_classes_table = new (mtClass)UnregisteredClassesTable();
 473   }
 474   bool created;
 475   InstanceKlass** v = _unregistered_classes_table->put_if_absent(name, klass, &created);
 476   if (created) {
 477     name->increment_refcount();
 478   }
 479   return (klass == *v);
 480 }
 481 
 482 void SystemDictionaryShared::copy_unregistered_class_size_and_crc32(InstanceKlass* klass) {
 483   precond(CDSConfig::is_dumping_final_static_archive());
 484   precond(klass->is_shared());
 485 
 486   // A shared class must have a RunTimeClassInfo record
 487   const RunTimeClassInfo* record = find_record(&_static_archive._unregistered_dictionary,
 488                                                nullptr, klass->name());
 489   precond(record != nullptr);
 490   precond(record->klass() == klass);
 491 
 492   DumpTimeClassInfo* info = get_info(klass);
 493   info->_clsfile_size = record->crc()->_clsfile_size;
 494   info->_clsfile_crc32 = record->crc()->_clsfile_crc32;
 495 }
 496 
 497 void SystemDictionaryShared::set_shared_class_misc_info(InstanceKlass* k, ClassFileStream* cfs) {
 498   assert(CDSConfig::is_dumping_archive(), "sanity");
 499   assert(!is_builtin(k), "must be unregistered class");
 500   DumpTimeClassInfo* info = get_info(k);
 501   info->_clsfile_size  = cfs->length();
 502   info->_clsfile_crc32 = ClassLoader::crc32(0, (const char*)cfs->buffer(), cfs->length());
 503 }
 504 
 505 void SystemDictionaryShared::initialize() {
 506   if (CDSConfig::is_dumping_archive()) {
 507     _dumptime_table = new (mtClass) DumpTimeSharedClassTable;
 508     LambdaProxyClassDictionary::dumptime_init();
 509     if (CDSConfig::is_dumping_heap()) {
 510       HeapShared::init_dumping();
 511     }
 512   }
 513 }
 514 
 515 void SystemDictionaryShared::init_dumptime_info(InstanceKlass* k) {
 516   MutexLocker ml(DumpTimeTable_lock, Mutex::_no_safepoint_check_flag);
 517   assert(SystemDictionaryShared::class_loading_may_happen(), "sanity");
 518   DumpTimeClassInfo* info = _dumptime_table->allocate_info(k);
 519   if (AOTClassFilter::is_aot_tooling_class(k)) {
 520     info->set_is_aot_tooling_class();
 521   }
 522 }
 523 
 524 void SystemDictionaryShared::remove_dumptime_info(InstanceKlass* k) {
 525   MutexLocker ml(DumpTimeTable_lock, Mutex::_no_safepoint_check_flag);
 526   _dumptime_table->remove(k);
 527 }
 528 
 529 void SystemDictionaryShared::handle_class_unloading(InstanceKlass* klass) {
 530   if (CDSConfig::is_dumping_archive()) {
 531     remove_dumptime_info(klass);
 532   }
 533 
 534   if (CDSConfig::is_dumping_archive() || ClassListWriter::is_enabled()) {
 535     MutexLocker ml(Thread::current(), UnregisteredClassesTable_lock, Mutex::_no_safepoint_check_flag);
 536     if (_unregistered_classes_table != nullptr) {
 537       // Remove the class from _unregistered_classes_table: keep the entry but
 538       // set it to null. This ensure no classes with the same name can be
 539       // added again.
 540       InstanceKlass** v = _unregistered_classes_table->get(klass->name());
 541       if (v != nullptr) {
 542         *v = nullptr;
 543       }
 544     }
 545   } else {
 546     assert(_unregistered_classes_table == nullptr, "must not be used");
 547   }
 548 
 549   if (ClassListWriter::is_enabled()) {
 550     ClassListWriter cw;
 551     cw.handle_class_unloading((const InstanceKlass*)klass);
 552   }
 553 }
 554 
 555 void SystemDictionaryShared::init_dumptime_info_from_preimage(InstanceKlass* k) {
 556   init_dumptime_info(k);
 557   copy_verification_constraints_from_preimage(k);
 558   copy_linking_constraints_from_preimage(k);
 559 
 560   if (SystemDictionary::is_platform_class_loader(k->class_loader())) {
 561     AOTClassLocationConfig::dumptime_set_has_platform_classes();
 562   } else if (SystemDictionary::is_system_class_loader(k->class_loader())) {
 563     AOTClassLocationConfig::dumptime_set_has_app_classes();
 564   }
 565 }
 566 
 567 // Check if a class or any of its supertypes has been redefined.
 568 bool SystemDictionaryShared::has_been_redefined(InstanceKlass* k) {
 569   if (k->has_been_redefined()) {
 570     return true;
 571   }
 572   if (k->java_super() != nullptr && has_been_redefined(k->java_super())) {
 573     return true;
 574   }
 575   Array<InstanceKlass*>* interfaces = k->local_interfaces();
 576   int len = interfaces->length();
 577   for (int i = 0; i < len; i++) {
 578     if (has_been_redefined(interfaces->at(i))) {
 579       return true;
 580     }
 581   }
 582   return false;
 583 }
 584 
 585 // k is a class before relocating by ArchiveBuilder
 586 void SystemDictionaryShared::validate_before_archiving(InstanceKlass* k) {
 587   ResourceMark rm;
 588   const char* name = k->name()->as_C_string();
 589   DumpTimeClassInfo* info = _dumptime_table->get(k);
 590   assert(!class_loading_may_happen(), "class loading must be disabled");
 591   guarantee(info != nullptr, "Class %s must be entered into _dumptime_table", name);
 592   guarantee(!info->is_excluded(), "Should not attempt to archive excluded class %s", name);
 593   if (is_builtin(k)) {
 594     if (k->is_hidden()) {
 595       if (CDSConfig::is_dumping_lambdas_in_legacy_mode()) {
 596         assert(LambdaProxyClassDictionary::is_registered_lambda_proxy_class(k), "unexpected hidden class %s", name);
 597       }
 598     }
 599     guarantee(!k->is_shared_unregistered_class(),
 600               "Class loader type must be set for BUILTIN class %s", name);
 601 
 602   } else {
 603     guarantee(k->is_shared_unregistered_class(),
 604               "Class loader type must not be set for UNREGISTERED class %s", name);
 605   }
 606 }
 607 
 608 class UnregisteredClassesDuplicationChecker : StackObj {
 609   GrowableArray<InstanceKlass*> _list;
 610   Thread* _thread;
 611 public:
 612   UnregisteredClassesDuplicationChecker() : _thread(Thread::current()) {}
 613 
 614   void do_entry(InstanceKlass* k, DumpTimeClassInfo& info) {
 615     if (!SystemDictionaryShared::is_builtin(k)) {
 616       _list.append(k);
 617     }
 618   }
 619 
 620   static int compare_by_loader(InstanceKlass** a, InstanceKlass** b) {
 621     ClassLoaderData* loader_a = a[0]->class_loader_data();
 622     ClassLoaderData* loader_b = b[0]->class_loader_data();
 623 
 624     if (loader_a != loader_b) {
 625       return primitive_compare(loader_a, loader_b);
 626     } else {
 627       return primitive_compare(a[0], b[0]);
 628     }
 629   }
 630 
 631   void mark_duplicated_classes() {
 632     // Two loaders may load two identical or similar hierarchies of classes. If we
 633     // check for duplication in random order, we may end up excluding important base classes
 634     // in both hierarchies, causing most of the classes to be excluded.
 635     // We sort the classes by their loaders. This way we're likely to archive
 636     // all classes in the one of the two hierarchies.
 637     _list.sort(compare_by_loader);
 638     for (int i = 0; i < _list.length(); i++) {
 639       InstanceKlass* k = _list.at(i);
 640       bool i_am_first = SystemDictionaryShared::add_unregistered_class(_thread, k);
 641       if (!i_am_first) {
 642         SystemDictionaryShared::warn_excluded(k, "Duplicated unregistered class");
 643         SystemDictionaryShared::set_excluded_locked(k);
 644       }
 645     }
 646   }
 647 };
 648 
 649 // Returns true if the class should be excluded. This can be called by
 650 // AOTConstantPoolResolver before or after we enter the CDS safepoint.
 651 // When called before the safepoint, we need to link the class so that
 652 // it can be checked by check_for_exclusion().
 653 bool SystemDictionaryShared::should_be_excluded(Klass* k) {
 654   assert(CDSConfig::is_dumping_archive(), "sanity");
 655   assert(CDSConfig::current_thread_is_vm_or_dumper(), "sanity");
 656 
 657   if (k->is_objArray_klass()) {
 658     return should_be_excluded(ObjArrayKlass::cast(k)->bottom_klass());
 659   }
 660 
 661   if (!k->is_instance_klass()) {
 662     return false;
 663   } else {
 664     InstanceKlass* ik = InstanceKlass::cast(k);
 665 
 666     if (!SafepointSynchronize::is_at_safepoint()) {
 667       if (!ik->is_linked()) {
 668         // check_for_exclusion() below doesn't link unlinked classes. We come
 669         // here only when we are trying to aot-link constant pool entries, so
 670         // we'd better link the class.
 671         JavaThread* THREAD = JavaThread::current();
 672         ik->link_class(THREAD);
 673         if (HAS_PENDING_EXCEPTION) {
 674           CLEAR_PENDING_EXCEPTION;
 675           return true; // linking failed -- let's exclude it
 676         }
 677       }
 678 
 679       MutexLocker ml(DumpTimeTable_lock, Mutex::_no_safepoint_check_flag);
 680       DumpTimeClassInfo* p = get_info_locked(ik);
 681       if (p->is_excluded()) {
 682         return true;
 683       }
 684       return check_for_exclusion(ik, p);
 685     } else {
 686       // No need to check for is_linked() as all eligible classes should have
 687       // already been linked in MetaspaceShared::link_class_for_cds().
 688       // Can't take the lock as we are in safepoint.
 689       DumpTimeClassInfo* p = _dumptime_table->get(ik);
 690       if (p->is_excluded()) {
 691         return true;
 692       }
 693       return check_for_exclusion(ik, p);
 694     }
 695   }
 696 }
 697 
 698 void SystemDictionaryShared::finish_exclusion_checks() {
 699   if (CDSConfig::is_dumping_dynamic_archive() || CDSConfig::is_dumping_preimage_static_archive()) {
 700     // Do this first -- if a base class is excluded due to duplication,
 701     // all of its subclasses will also be excluded.
 702     ResourceMark rm;
 703     UnregisteredClassesDuplicationChecker dup_checker;
 704     _dumptime_table->iterate_all_live_classes(&dup_checker);
 705     dup_checker.mark_duplicated_classes();
 706   }
 707 
 708   _dumptime_table->iterate_all_live_classes([&] (InstanceKlass* k, DumpTimeClassInfo& info) {
 709     SystemDictionaryShared::check_for_exclusion(k, &info);
 710   });
 711 
 712   _dumptime_table->update_counts();
 713   if (CDSConfig::is_dumping_lambdas_in_legacy_mode()) {
 714     LambdaProxyClassDictionary::cleanup_dumptime_table();
 715   }
 716 }
 717 
 718 bool SystemDictionaryShared::is_excluded_class(InstanceKlass* k) {
 719   assert(!class_loading_may_happen(), "class loading must be disabled");
 720   assert_lock_strong(DumpTimeTable_lock);
 721   assert(CDSConfig::is_dumping_archive(), "sanity");
 722   DumpTimeClassInfo* p = get_info_locked(k);
 723   return p->is_excluded();
 724 }
 725 
 726 void SystemDictionaryShared::set_excluded_locked(InstanceKlass* k) {
 727   assert_lock_strong(DumpTimeTable_lock);
 728   assert(CDSConfig::is_dumping_archive(), "sanity");
 729   DumpTimeClassInfo* info = get_info_locked(k);
 730   info->set_excluded();
 731 }
 732 
 733 void SystemDictionaryShared::set_excluded(InstanceKlass* k) {
 734   assert(CDSConfig::is_dumping_archive(), "sanity");
 735   DumpTimeClassInfo* info = get_info(k);
 736   info->set_excluded();
 737 }
 738 
 739 void SystemDictionaryShared::set_class_has_failed_verification(InstanceKlass* ik) {
 740   assert(CDSConfig::is_dumping_archive(), "sanity");
 741   DumpTimeClassInfo* p = get_info(ik);
 742   p->set_failed_verification();
 743 }
 744 
 745 bool SystemDictionaryShared::has_class_failed_verification(InstanceKlass* ik) {
 746   assert(CDSConfig::is_dumping_archive(), "sanity");
 747   DumpTimeClassInfo* p = _dumptime_table->get(ik);
 748   return (p == nullptr) ? false : p->failed_verification();
 749 }
 750 
 751 void SystemDictionaryShared::dumptime_classes_do(MetaspaceClosure* it) {
 752   assert_lock_strong(DumpTimeTable_lock);
 753 
 754   auto do_klass = [&] (InstanceKlass* k, DumpTimeClassInfo& info) {
 755     if (CDSConfig::is_dumping_final_static_archive() && !k->is_loaded()) {
 756       assert(k->is_shared_unregistered_class(), "must be");
 757       info.metaspace_pointers_do(it);
 758     } else if (k->is_loader_alive() && !info.is_excluded()) {
 759       info.metaspace_pointers_do(it);
 760     }
 761   };
 762   _dumptime_table->iterate_all_live_classes(do_klass);
 763 
 764   if (CDSConfig::is_dumping_lambdas_in_legacy_mode()) {
 765     LambdaProxyClassDictionary::dumptime_classes_do(it);
 766   }
 767 }
 768 
 769 bool SystemDictionaryShared::add_verification_constraint(InstanceKlass* k, Symbol* name,
 770          Symbol* from_name, bool from_field_is_protected, bool from_is_array, bool from_is_object) {
 771   assert(CDSConfig::is_dumping_archive(), "sanity");
 772   if (CDSConfig::is_dumping_dynamic_archive() && k->is_shared()) {
 773     // k is a new class in the static archive, but one of its supertypes is an old class, so k wasn't
 774     // verified during dump time. No need to record constraints as k won't be included in the dynamic archive.
 775     return false;
 776   }
 777   if (CDSConfig::is_dumping_aot_linked_classes() && is_builtin(k)) {
 778     // There's no need to save verification constraints
 779     // TODO -- double check the logic before integrating into mainline!!
 780     return false;
 781   }
 782 
 783   DumpTimeClassInfo* info = get_info(k);
 784   info->add_verification_constraint(k, name, from_name, from_field_is_protected,
 785                                     from_is_array, from_is_object);
 786 
 787   if (CDSConfig::is_dumping_dynamic_archive()) {
 788     // For dynamic dumping, we can resolve all the constraint classes for all class loaders during
 789     // the initial run prior to creating the archive before vm exit. We will also perform verification
 790     // check when running with the archive.
 791     return false;
 792   } else {
 793     if (is_builtin(k)) {
 794       // For builtin class loaders, we can try to complete the verification check at dump time,
 795       // because we can resolve all the constraint classes. We will also perform verification check
 796       // when running with the archive.
 797       return false;
 798     } else {
 799       // For non-builtin class loaders, we cannot complete the verification check at dump time,
 800       // because at dump time we don't know how to resolve classes for such loaders.
 801       return true;
 802     }
 803   }
 804 }
 805 
 806 void SystemDictionaryShared::add_enum_klass_static_field(InstanceKlass* ik, int root_index) {
 807   assert(CDSConfig::is_dumping_heap(), "sanity");
 808   DumpTimeClassInfo* info = get_info_locked(ik);
 809   info->add_enum_klass_static_field(root_index);
 810 }
 811 
 812 void SystemDictionaryShared::check_verification_constraints(InstanceKlass* klass,
 813                                                             TRAPS) {
 814   assert(CDSConfig::is_using_archive(), "called at run time with CDS enabled only");
 815   RunTimeClassInfo* record = RunTimeClassInfo::get_for(klass);
 816 
 817   int length = record->num_verifier_constraints();
 818   if (length > 0) {
 819     for (int i = 0; i < length; i++) {
 820       RunTimeClassInfo::RTVerifierConstraint* vc = record->verifier_constraint_at(i);
 821       Symbol* name      = vc->name();
 822       Symbol* from_name = vc->from_name();
 823 
 824       if (log_is_enabled(Trace, cds, verification)) {
 825         ResourceMark rm(THREAD);
 826         log_trace(cds, verification)("check_verification_constraint: %s: %s must be subclass of %s [0x%x]",
 827                                      klass->external_name(), from_name->as_klass_external_name(),
 828                                      name->as_klass_external_name(), record->verifier_constraint_flag(i));
 829       }
 830 
 831       bool ok = VerificationType::resolve_and_check_assignability(klass, name, from_name,
 832          record->from_field_is_protected(i), record->from_is_array(i), record->from_is_object(i), CHECK);
 833       if (!ok) {
 834         ResourceMark rm(THREAD);
 835         stringStream ss;
 836 
 837         ss.print_cr("Bad type on operand stack");
 838         ss.print_cr("Exception Details:");
 839         ss.print_cr("  Location:\n    %s", klass->name()->as_C_string());
 840         ss.print_cr("  Reason:\n    Type '%s' is not assignable to '%s'",
 841                     from_name->as_quoted_ascii(), name->as_quoted_ascii());
 842         THROW_MSG(vmSymbols::java_lang_VerifyError(), ss.as_string());
 843       }
 844     }
 845   }
 846 }
 847 
 848 void SystemDictionaryShared::copy_verification_constraints_from_preimage(InstanceKlass* klass) {
 849   assert(CDSConfig::is_using_archive(), "called at run time with CDS enabled only");
 850   DumpTimeClassInfo* dt_info = get_info(klass);
 851   RunTimeClassInfo* rt_info = RunTimeClassInfo::get_for(klass); // from preimage
 852 
 853   int length = rt_info->num_verifier_constraints();
 854   if (length > 0) {
 855     for (int i = 0; i < length; i++) {
 856       RunTimeClassInfo::RTVerifierConstraint* vc = rt_info->verifier_constraint_at(i);
 857       Symbol* name      = vc->name();
 858       Symbol* from_name = vc->from_name();
 859 
 860       dt_info->add_verification_constraint(klass, name, from_name,
 861          rt_info->from_field_is_protected(i), rt_info->from_is_array(i), rt_info->from_is_object(i));
 862     }
 863   }
 864 }
 865 
 866 static oop get_class_loader_by(char type) {
 867   if (type == (char)ClassLoader::BOOT_LOADER) {
 868     return (oop)nullptr;
 869   } else if (type == (char)ClassLoader::PLATFORM_LOADER) {
 870     return SystemDictionary::java_platform_loader();
 871   } else {
 872     assert (type == (char)ClassLoader::APP_LOADER, "Sanity");
 873     return SystemDictionary::java_system_loader();
 874   }
 875 }
 876 
 877 // Record class loader constraints that are checked inside
 878 // InstanceKlass::link_class(), so that these can be checked quickly
 879 // at runtime without laying out the vtable/itables.
 880 void SystemDictionaryShared::record_linking_constraint(Symbol* name, InstanceKlass* klass,
 881                                                     Handle loader1, Handle loader2) {
 882   // A linking constraint check is executed when:
 883   //   - klass extends or implements type S
 884   //   - klass overrides method S.M(...) with X.M
 885   //     - If klass defines the method M, X is
 886   //       the same as klass.
 887   //     - If klass does not define the method M,
 888   //       X must be a supertype of klass and X.M is
 889   //       a default method defined by X.
 890   //   - loader1 = X->class_loader()
 891   //   - loader2 = S->class_loader()
 892   //   - loader1 != loader2
 893   //   - M's parameter(s) include an object type T
 894   // We require that
 895   //   - whenever loader1 and loader2 try to
 896   //     resolve the type T, they must always resolve to
 897   //     the same InstanceKlass.
 898   // NOTE: type T may or may not be currently resolved in
 899   // either of these two loaders. The check itself does not
 900   // try to resolve T.
 901   oop klass_loader = klass->class_loader();
 902 
 903   if (!is_system_class_loader(klass_loader) &&
 904       !is_platform_class_loader(klass_loader)) {
 905     // If klass is loaded by system/platform loaders, we can
 906     // guarantee that klass and S must be loaded by the same
 907     // respective loader between dump time and run time, and
 908     // the exact same check on (name, loader1, loader2) will
 909     // be executed. Hence, we can cache this check and execute
 910     // it at runtime without walking the vtable/itables.
 911     //
 912     // This cannot be guaranteed for classes loaded by other
 913     // loaders, so we bail.
 914     return;
 915   }
 916 
 917   assert(is_builtin(klass), "must be");
 918   assert(klass_loader != nullptr, "should not be called for boot loader");
 919   assert(loader1 != loader2, "must be");
 920 
 921   if (CDSConfig::is_dumping_dynamic_archive() && Thread::current()->is_VM_thread()) {
 922     // We are re-laying out the vtable/itables of the *copy* of
 923     // a class during the final stage of dynamic dumping. The
 924     // linking constraints for this class has already been recorded.
 925     return;
 926   }
 927   assert(!Thread::current()->is_VM_thread(), "must be");
 928 
 929   assert(CDSConfig::is_dumping_archive(), "sanity");
 930   DumpTimeClassInfo* info = get_info(klass);
 931   info->record_linking_constraint(name, loader1, loader2);
 932 }
 933 
 934 // returns true IFF there's no need to re-initialize the i/v-tables for klass for
 935 // the purpose of checking class loader constraints.
 936 bool SystemDictionaryShared::check_linking_constraints(Thread* current, InstanceKlass* klass) {
 937   assert(CDSConfig::is_using_archive(), "called at run time with CDS enabled only");
 938   LogTarget(Info, class, loader, constraints) log;
 939   if (klass->is_shared_boot_class()) {
 940     // No class loader constraint check performed for boot classes.
 941     return true;
 942   }
 943   if (klass->is_shared_platform_class() || klass->is_shared_app_class()) {
 944     RunTimeClassInfo* info = RunTimeClassInfo::get_for(klass);
 945     assert(info != nullptr, "Sanity");
 946     if (info->num_loader_constraints() > 0) {
 947       HandleMark hm(current);
 948       for (int i = 0; i < info->num_loader_constraints(); i++) {
 949         RunTimeClassInfo::RTLoaderConstraint* lc = info->loader_constraint_at(i);
 950         Symbol* name = lc->constraint_name();
 951         Handle loader1(current, get_class_loader_by(lc->_loader_type1));
 952         Handle loader2(current, get_class_loader_by(lc->_loader_type2));
 953         if (log.is_enabled()) {
 954           ResourceMark rm(current);
 955           log.print("[CDS add loader constraint for class %s symbol %s loader[0] %s loader[1] %s",
 956                     klass->external_name(), name->as_C_string(),
 957                     ClassLoaderData::class_loader_data(loader1())->loader_name_and_id(),
 958                     ClassLoaderData::class_loader_data(loader2())->loader_name_and_id());
 959         }
 960         if (!SystemDictionary::add_loader_constraint(name, klass, loader1, loader2)) {
 961           // Loader constraint violation has been found. The caller
 962           // will re-layout the vtable/itables to produce the correct
 963           // exception.
 964           if (log.is_enabled()) {
 965             log.print(" failed]");
 966           }
 967           return false;
 968         }
 969         if (log.is_enabled()) {
 970             log.print(" succeeded]");
 971         }
 972       }
 973       return true; // for all recorded constraints added successfully.
 974     }
 975   }
 976   if (log.is_enabled()) {
 977     ResourceMark rm(current);
 978     log.print("[CDS has not recorded loader constraint for class %s]", klass->external_name());
 979   }
 980   return false;
 981 }
 982 
 983 void SystemDictionaryShared::copy_linking_constraints_from_preimage(InstanceKlass* klass) {
 984   assert(CDSConfig::is_using_archive(), "called at run time with CDS enabled only");
 985   JavaThread* current = JavaThread::current();
 986   if (klass->is_shared_platform_class() || klass->is_shared_app_class()) {
 987     RunTimeClassInfo* rt_info = RunTimeClassInfo::get_for(klass); // from preimage
 988 
 989     if (rt_info->num_loader_constraints() > 0) {
 990       for (int i = 0; i < rt_info->num_loader_constraints(); i++) {
 991         RunTimeClassInfo::RTLoaderConstraint* lc = rt_info->loader_constraint_at(i);
 992         Symbol* name = lc->constraint_name();
 993         Handle loader1(current, get_class_loader_by(lc->_loader_type1));
 994         Handle loader2(current, get_class_loader_by(lc->_loader_type2));
 995         record_linking_constraint(name, klass, loader1, loader2);
 996       }
 997     }
 998   }
 999 }
1000 
1001 unsigned int SystemDictionaryShared::hash_for_shared_dictionary(address ptr) {
1002   if (ArchiveBuilder::is_active() && ArchiveBuilder::current()->is_in_buffer_space(ptr)) {
1003     uintx offset = ArchiveBuilder::current()->any_to_offset(ptr);
1004     unsigned int hash = primitive_hash<uintx>(offset);
1005     DEBUG_ONLY({
1006         if (MetaspaceObj::is_shared((const MetaspaceObj*)ptr)) {
1007           assert(hash == SystemDictionaryShared::hash_for_shared_dictionary_quick(ptr), "must be");
1008         }
1009       });
1010     return hash;
1011   } else {
1012     return SystemDictionaryShared::hash_for_shared_dictionary_quick(ptr);
1013   }
1014 }
1015 
1016 class CopySharedClassInfoToArchive : StackObj {
1017   CompactHashtableWriter* _writer;
1018   bool _is_builtin;
1019   ArchiveBuilder *_builder;
1020 public:
1021   CopySharedClassInfoToArchive(CompactHashtableWriter* writer,
1022                                bool is_builtin)
1023     : _writer(writer), _is_builtin(is_builtin), _builder(ArchiveBuilder::current()) {}
1024 
1025   void do_entry(InstanceKlass* k, DumpTimeClassInfo& info) {
1026     if (!info.is_excluded() && info.is_builtin() == _is_builtin) {
1027       size_t byte_size = info.runtime_info_bytesize();
1028       RunTimeClassInfo* record;
1029       record = (RunTimeClassInfo*)ArchiveBuilder::ro_region_alloc(byte_size);
1030       record->init(info);
1031 
1032       unsigned int hash;
1033       Symbol* name = info._klass->name();
1034       name = ArchiveBuilder::current()->get_buffered_addr(name);
1035       hash = SystemDictionaryShared::hash_for_shared_dictionary((address)name);
1036       u4 delta = _builder->buffer_to_offset_u4((address)record);
1037       if (_is_builtin && info._klass->is_hidden()) {
1038         // skip
1039       } else {
1040         _writer->add(hash, delta);
1041       }
1042       if (log_is_enabled(Trace, cds, hashtables)) {
1043         ResourceMark rm;
1044         log_trace(cds,hashtables)("%s dictionary: %s", (_is_builtin ? "builtin" : "unregistered"), info._klass->external_name());
1045       }
1046 
1047       // Save this for quick runtime lookup of InstanceKlass* -> RunTimeClassInfo*
1048       InstanceKlass* buffered_klass = ArchiveBuilder::current()->get_buffered_addr(info._klass);
1049       RunTimeClassInfo::set_for(buffered_klass, record);
1050     }
1051   }
1052 };
1053 
1054 void SystemDictionaryShared::write_dictionary(RunTimeSharedDictionary* dictionary,
1055                                               bool is_builtin) {
1056   CompactHashtableStats stats;
1057   dictionary->reset();
1058   CompactHashtableWriter writer(_dumptime_table->count_of(is_builtin), &stats);
1059   CopySharedClassInfoToArchive copy(&writer, is_builtin);
1060   assert_lock_strong(DumpTimeTable_lock);
1061   _dumptime_table->iterate_all_live_classes(&copy);
1062   writer.dump(dictionary, is_builtin ? "builtin dictionary" : "unregistered dictionary");
1063 }
1064 
1065 void SystemDictionaryShared::write_to_archive(bool is_static_archive) {
1066   ArchiveInfo* archive = get_archive(is_static_archive);
1067 
1068   write_dictionary(&archive->_builtin_dictionary, true);
1069   write_dictionary(&archive->_unregistered_dictionary, false);
1070   if (CDSConfig::is_dumping_lambdas_in_legacy_mode()) {
1071     LambdaProxyClassDictionary::write_dictionary(is_static_archive);
1072   } else {
1073     LambdaProxyClassDictionary::reset_dictionary(is_static_archive);
1074   }
1075 }
1076 
1077 void SystemDictionaryShared::serialize_dictionary_headers(SerializeClosure* soc,
1078                                                           bool is_static_archive) {
1079   ArchiveInfo* archive = get_archive(is_static_archive);
1080 
1081   archive->_builtin_dictionary.serialize_header(soc);
1082   archive->_unregistered_dictionary.serialize_header(soc);
1083   LambdaProxyClassDictionary::serialize(soc, is_static_archive);
1084 }
1085 
1086 void SystemDictionaryShared::serialize_vm_classes(SerializeClosure* soc) {
1087   for (auto id : EnumRange<vmClassID>{}) {
1088     soc->do_ptr(vmClasses::klass_addr_at(id));
1089   }
1090 }
1091 
1092 const RunTimeClassInfo*
1093 SystemDictionaryShared::find_record(RunTimeSharedDictionary* static_dict, RunTimeSharedDictionary* dynamic_dict, Symbol* name) {
1094   if (!CDSConfig::is_using_archive() || !name->is_shared()) {
1095     // The names of all shared classes must also be a shared Symbol.
1096     return nullptr;
1097   }
1098 
1099   unsigned int hash = SystemDictionaryShared::hash_for_shared_dictionary_quick(name);
1100   const RunTimeClassInfo* record = nullptr;
1101   if (DynamicArchive::is_mapped()) {
1102     // Use the regenerated holder classes in the dynamic archive as they
1103     // have more methods than those in the base archive.
1104     if (LambdaFormInvokers::may_be_regenerated_class(name)) {
1105       record = dynamic_dict->lookup(name, hash, 0);
1106       if (record != nullptr) {
1107         return record;
1108       }
1109     }
1110   }
1111 
1112   if (!MetaspaceShared::is_shared_dynamic(name)) {
1113     // The names of all shared classes in the static dict must also be in the
1114     // static archive
1115     record = static_dict->lookup(name, hash, 0);
1116   }
1117 
1118   if (record == nullptr && DynamicArchive::is_mapped()) {
1119     record = dynamic_dict->lookup(name, hash, 0);
1120   }
1121 
1122   return record;
1123 }
1124 
1125 InstanceKlass* SystemDictionaryShared::find_builtin_class(Symbol* name) {
1126   const RunTimeClassInfo* record = find_record(&_static_archive._builtin_dictionary,
1127                                                &_dynamic_archive._builtin_dictionary,
1128                                                name);
1129   if (record != nullptr) {
1130     assert(!record->klass()->is_hidden(), "hidden class cannot be looked up by name");
1131     DEBUG_ONLY(check_klass_after_loading(record->klass());)
1132     // We did not save the classfile data of the generated LambdaForm invoker classes,
1133     // so we cannot support CLFH for such classes.
1134     if (record->klass()->is_generated_shared_class() && JvmtiExport::should_post_class_file_load_hook()) {
1135        return nullptr;
1136     }
1137     return record->klass();
1138   } else {
1139     return nullptr;
1140   }
1141 }
1142 
1143 void SystemDictionaryShared::update_shared_entry(InstanceKlass* k, int id) {
1144   assert(CDSConfig::is_dumping_static_archive(), "class ID is used only for static dump (from classlist)");
1145   DumpTimeClassInfo* info = get_info(k);
1146   info->_id = id;
1147 }
1148 
1149 const char* SystemDictionaryShared::loader_type_for_shared_class(Klass* k) {
1150   assert(k != nullptr, "Sanity");
1151   assert(k->is_shared(), "Must be");
1152   assert(k->is_instance_klass(), "Must be");
1153   InstanceKlass* ik = InstanceKlass::cast(k);
1154   if (ik->is_shared_boot_class()) {
1155     return "boot_loader";
1156   } else if (ik->is_shared_platform_class()) {
1157     return "platform_loader";
1158   } else if (ik->is_shared_app_class()) {
1159     return "app_loader";
1160   } else if (ik->is_shared_unregistered_class()) {
1161     return "unregistered_loader";
1162   } else {
1163     return "unknown loader";
1164   }
1165 }
1166 
1167 class SharedDictionaryPrinter : StackObj {
1168   outputStream* _st;
1169   int _index;
1170 public:
1171   SharedDictionaryPrinter(outputStream* st) : _st(st), _index(0) {}
1172 
1173   void do_value(const RunTimeClassInfo* record) {
1174     ResourceMark rm;
1175     _st->print_cr("%4d: %s %s", _index++, record->klass()->external_name(),
1176         SystemDictionaryShared::loader_type_for_shared_class(record->klass()));
1177     if (record->klass()->array_klasses() != nullptr) {
1178       record->klass()->array_klasses()->cds_print_value_on(_st);
1179       _st->cr();
1180     }
1181   }
1182   int index() const { return _index; }
1183 };
1184 
1185 void SystemDictionaryShared::ArchiveInfo::print_on(const char* prefix,
1186                                                    outputStream* st,
1187                                                    bool is_static_archive) {
1188   st->print_cr("%sShared Dictionary", prefix);
1189   SharedDictionaryPrinter p(st);
1190   st->print_cr("%sShared Builtin Dictionary", prefix);
1191   _builtin_dictionary.iterate(&p);
1192   st->print_cr("%sShared Unregistered Dictionary", prefix);
1193   _unregistered_dictionary.iterate(&p);
1194   LambdaProxyClassDictionary::print_on(prefix, st, p.index(), is_static_archive);
1195 }
1196 
1197 void SystemDictionaryShared::ArchiveInfo::print_table_statistics(const char* prefix,
1198                                                                  outputStream* st,
1199                                                                  bool is_static_archive) {
1200   st->print_cr("%sArchve Statistics", prefix);
1201   _builtin_dictionary.print_table_statistics(st, "Builtin Shared Dictionary");
1202   _unregistered_dictionary.print_table_statistics(st, "Unregistered Shared Dictionary");
1203   LambdaProxyClassDictionary::print_statistics(st, is_static_archive);
1204 }
1205 
1206 void SystemDictionaryShared::print_shared_archive(outputStream* st, bool is_static) {
1207   if (CDSConfig::is_using_archive()) {
1208     if (is_static) {
1209       _static_archive.print_on("", st, true);
1210     } else {
1211       if (DynamicArchive::is_mapped()) {
1212         _dynamic_archive.print_on("Dynamic ", st, false);
1213       }
1214     }
1215   }
1216 }
1217 
1218 void SystemDictionaryShared::print_on(outputStream* st) {
1219   print_shared_archive(st, true);
1220   print_shared_archive(st, false);
1221 }
1222 
1223 void SystemDictionaryShared::print_table_statistics(outputStream* st) {
1224   if (CDSConfig::is_using_archive()) {
1225     _static_archive.print_table_statistics("Static ", st, true);
1226     if (DynamicArchive::is_mapped()) {
1227       _dynamic_archive.print_table_statistics("Dynamic ", st, false);
1228     }
1229   }
1230 }
1231 
1232 bool SystemDictionaryShared::is_dumptime_table_empty() {
1233   assert_lock_strong(DumpTimeTable_lock);
1234   _dumptime_table->update_counts();
1235   if (_dumptime_table->count_of(true) == 0 && _dumptime_table->count_of(false) == 0){
1236     return true;
1237   }
1238   return false;
1239 }
1240 
1241 void SystemDictionaryShared::create_loader_positive_lookup_cache(TRAPS) {
1242   GrowableArray<InstanceKlass*> shared_classes_list;
1243   {
1244     // With static dumping, we have only a single Java thread (see JVM_StartThread) so
1245     // no no other threads should be loading classes. Otherwise, the code below may miss some
1246     // classes that are loaded concurrently.
1247     assert(CDSConfig::is_dumping_static_archive(), "no other threads should be loading classes");
1248 
1249     MutexLocker ml(DumpTimeTable_lock, Mutex::_no_safepoint_check_flag);
1250     _dumptime_table->iterate_all_classes_in_builtin_loaders([&](InstanceKlass* k, DumpTimeClassInfo& info) {
1251         if (!k->is_hidden() && !check_for_exclusion(k, &info)) {
1252           shared_classes_list.append(k);
1253         }
1254       }
1255     );
1256   }
1257 
1258   InstanceKlass* ik = vmClasses::Class_klass();
1259   objArrayOop r = oopFactory::new_objArray(ik, shared_classes_list.length(), CHECK);
1260   objArrayHandle array_h(THREAD, r);
1261 
1262   for (int i = 0; i < shared_classes_list.length(); i++) {
1263     oop mirror = shared_classes_list.at(i)->java_mirror();
1264     Handle mirror_h(THREAD, mirror);
1265     array_h->obj_at_put(i, mirror_h());
1266   }
1267 
1268   TempNewSymbol method = SymbolTable::new_symbol("generatePositiveLookupCache");
1269   TempNewSymbol signature = SymbolTable::new_symbol("([Ljava/lang/Class;)V");
1270 
1271   JavaCallArguments args(Handle(THREAD, SystemDictionary::java_system_loader()));
1272   args.push_oop(array_h);
1273   JavaValue result(T_VOID);
1274   JavaCalls::call_virtual(&result,
1275                           vmClasses::jdk_internal_loader_ClassLoaders_AppClassLoader_klass(),
1276                           method,
1277                           signature,
1278                           &args,
1279                           CHECK);
1280 
1281   if (HAS_PENDING_EXCEPTION) {
1282     Handle exc_handle(THREAD, PENDING_EXCEPTION);
1283     CLEAR_PENDING_EXCEPTION;
1284     ResourceMark rm(THREAD);
1285 
1286     log_warning(cds)("Exception during AppClassLoader::generatePositiveLookupCache() call");
1287     LogStreamHandle(Debug, cds) log;
1288     if (log.is_enabled()) {
1289       java_lang_Throwable::print_stack_trace(exc_handle, &log);
1290     }
1291     return;
1292   }
1293 }