1 /*
   2  * Copyright (c) 2014, 2026, 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 
  26 #include "cds/aotClassFilter.hpp"
  27 #include "cds/aotClassLocation.hpp"
  28 #include "cds/aotCompressedPointers.hpp"
  29 #include "cds/aotLogging.hpp"
  30 #include "cds/aotMetaspace.hpp"
  31 #include "cds/archiveBuilder.hpp"
  32 #include "cds/archiveUtils.hpp"
  33 #include "cds/cdsConfig.hpp"
  34 #include "cds/cdsProtectionDomain.hpp"
  35 #include "cds/classListParser.hpp"
  36 #include "cds/classListWriter.hpp"
  37 #include "cds/dumpTimeClassInfo.inline.hpp"
  38 #include "cds/dynamicArchive.hpp"
  39 #include "cds/filemap.hpp"
  40 #include "cds/heapShared.hpp"
  41 #include "cds/lambdaFormInvokers.inline.hpp"
  42 #include "cds/lambdaProxyClassDictionary.hpp"
  43 #include "cds/runTimeClassInfo.hpp"
  44 #include "cds/unregisteredClasses.hpp"
  45 #include "classfile/classFileStream.hpp"
  46 #include "classfile/classLoader.hpp"
  47 #include "classfile/classLoaderData.inline.hpp"
  48 #include "classfile/classLoaderDataGraph.hpp"
  49 #include "classfile/dictionary.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/objArrayKlass.hpp"
  70 #include "oops/objArrayOop.inline.hpp"
  71 #include "oops/oop.inline.hpp"
  72 #include "oops/oopHandle.inline.hpp"
  73 #include "oops/typeArrayOop.inline.hpp"
  74 #include "runtime/arguments.hpp"
  75 #include "runtime/handles.inline.hpp"
  76 #include "runtime/java.hpp"
  77 #include "runtime/javaCalls.hpp"
  78 #include "runtime/mutexLocker.hpp"
  79 #include "utilities/hashTable.hpp"
  80 #include "utilities/stringUtils.hpp"
  81 
  82 SystemDictionaryShared::ArchiveInfo SystemDictionaryShared::_static_archive;
  83 SystemDictionaryShared::ArchiveInfo SystemDictionaryShared::_dynamic_archive;
  84 
  85 DumpTimeSharedClassTable* SystemDictionaryShared::_dumptime_table = nullptr;
  86 
  87 // Used by NoClassLoadingMark
  88 DEBUG_ONLY(bool SystemDictionaryShared::_class_loading_may_happen = true;)
  89 
  90 #ifdef ASSERT
  91 static void check_klass_after_loading(const Klass* k) {
  92 #ifdef _LP64
  93   if (k != nullptr && UseCompressedClassPointers) {
  94     CompressedKlassPointers::check_encodable(k);
  95   }
  96 #endif
  97 }
  98 #endif
  99 
 100 InstanceKlass* SystemDictionaryShared::load_shared_class_for_builtin_loader(
 101                  Symbol* class_name, Handle class_loader, TRAPS) {
 102   assert(CDSConfig::is_using_archive(), "must be");
 103   InstanceKlass* ik = find_builtin_class(class_name);
 104 
 105   if (ik != nullptr && !ik->shared_loading_failed()) {
 106     if ((SystemDictionary::is_system_class_loader(class_loader()) && ik->defined_by_app_loader())  ||
 107         (SystemDictionary::is_platform_class_loader(class_loader()) && ik->defined_by_platform_loader())) {
 108       SharedClassLoadingMark slm(THREAD, ik);
 109       PackageEntry* pkg_entry = CDSProtectionDomain::get_package_entry_from_class(ik, class_loader);
 110       Handle protection_domain =
 111         CDSProtectionDomain::init_security_info(class_loader, ik, pkg_entry, CHECK_NULL);
 112       return load_shared_class(ik, class_loader, protection_domain, nullptr, pkg_entry, THREAD);
 113     }
 114   }
 115   return nullptr;
 116 }
 117 
 118 // This function is called for loading only UNREGISTERED classes
 119 InstanceKlass* SystemDictionaryShared::lookup_from_stream(Symbol* class_name,
 120                                                           Handle class_loader,
 121                                                           Handle protection_domain,
 122                                                           const ClassFileStream* cfs,
 123                                                           TRAPS) {
 124   if (!CDSConfig::is_using_archive()) {
 125     return nullptr;
 126   }
 127   if (class_name == nullptr) {  // don't do this for hidden classes
 128     return nullptr;
 129   }
 130   if (class_loader.is_null() ||
 131       SystemDictionary::is_system_class_loader(class_loader()) ||
 132       SystemDictionary::is_platform_class_loader(class_loader())) {
 133     // Do nothing for the BUILTIN loaders.
 134     return nullptr;
 135   }
 136 
 137   const RunTimeClassInfo* record = find_record(&_static_archive._unregistered_dictionary,
 138                                                &_dynamic_archive._unregistered_dictionary,
 139                                                class_name);
 140   if (record == nullptr) {
 141     return nullptr;
 142   }
 143 
 144   int clsfile_size  = cfs->length();
 145   int clsfile_crc32 = ClassLoader::crc32(0, (const char*)cfs->buffer(), cfs->length());
 146 
 147   if (!record->matches(clsfile_size, clsfile_crc32)) {
 148     return nullptr;
 149   }
 150 
 151   return acquire_class_for_current_thread(record->klass(), class_loader,
 152                                           protection_domain, cfs,
 153                                           THREAD);
 154 }
 155 
 156 InstanceKlass* SystemDictionaryShared::acquire_class_for_current_thread(
 157                    InstanceKlass *ik,
 158                    Handle class_loader,
 159                    Handle protection_domain,
 160                    const ClassFileStream *cfs,
 161                    TRAPS) {
 162   ClassLoaderData* loader_data = ClassLoaderData::class_loader_data(class_loader());
 163 
 164   {
 165     MutexLocker mu(THREAD, SharedDictionary_lock);
 166     if (ik->class_loader_data() != nullptr) {
 167       //    ik is already loaded (by this loader or by a different loader)
 168       // or ik is being loaded by a different thread (by this loader or by a different loader)
 169       return nullptr;
 170     }
 171 
 172     // No other thread has acquired this yet, so give it to *this thread*
 173     ik->set_class_loader_data(loader_data);
 174   }
 175 
 176   // No longer holding SharedDictionary_lock
 177   // No need to lock, as <ik> can be held only by a single thread.
 178 
 179   // Get the package entry.
 180   PackageEntry* pkg_entry = CDSProtectionDomain::get_package_entry_from_class(ik, class_loader);
 181 
 182   // Load and check super/interfaces, restore unshareable info
 183   InstanceKlass* shared_klass = load_shared_class(ik, class_loader, protection_domain,
 184                                                   cfs, pkg_entry, THREAD);
 185   if (shared_klass == nullptr || HAS_PENDING_EXCEPTION) {
 186     // TODO: clean up <ik> so it can be used again
 187     return nullptr;
 188   }
 189 
 190   return shared_klass;
 191 }
 192 
 193 // Guaranteed to return non-null value for non-shared classes.
 194 // k must not be a shared class.
 195 DumpTimeClassInfo* SystemDictionaryShared::get_info(InstanceKlass* k) {
 196   MutexLocker ml(DumpTimeTable_lock, Mutex::_no_safepoint_check_flag);
 197   return get_info_locked(k);
 198 }
 199 
 200 DumpTimeClassInfo* SystemDictionaryShared::get_info_locked(InstanceKlass* k) {
 201   assert_lock_strong(DumpTimeTable_lock);
 202   DumpTimeClassInfo* info = _dumptime_table->get_info(k);
 203   assert(info != nullptr, "must be");
 204   return info;
 205 }
 206 
 207 bool SystemDictionaryShared::should_be_excluded_impl(InstanceKlass* k, DumpTimeClassInfo* info) {
 208   assert_lock_strong(DumpTimeTable_lock);
 209 
 210   if (!info->has_checked_exclusion()) {
 211     check_exclusion_for_self_and_dependencies(k);
 212     assert(info->has_checked_exclusion(), "must be");
 213   }
 214 
 215   return info->is_excluded();
 216 }
 217 
 218 // <func> returns bool and takes a single parameter of Symbol*
 219 // The return value indicates whether we want to keep on iterating or not.
 220 template<typename Function>
 221 void SystemDictionaryShared::iterate_verification_constraint_names(InstanceKlass* k, DumpTimeClassInfo* info, Function func) {
 222   int n = info->num_verifier_constraints();
 223   bool cont; // continue iterating?
 224   for (int i = 0; i < n; i++) {
 225     cont = func(info->verifier_constraint_name_at(i));
 226     if (!cont) {
 227       return; // early termination
 228     }
 229     Symbol* from_name = info->verifier_constraint_from_name_at(i);
 230     if (from_name != nullptr) {
 231       cont = func(from_name);
 232       if (!cont) {
 233         return; // early termination
 234       }
 235     }
 236   }
 237 }
 238 
 239 // This is a table of classes that need to be checked for exclusion.
 240 class SystemDictionaryShared::ExclusionCheckCandidates
 241   : public HashTable<InstanceKlass*, DumpTimeClassInfo*, 15889> {
 242   void add_candidate(InstanceKlass* k) {
 243     if (contains(k)) {
 244       return;
 245     }
 246     if (CDSConfig::is_dumping_dynamic_archive() && AOTMetaspace::in_aot_cache(k)) {
 247       return;
 248     }
 249 
 250     DumpTimeClassInfo* info = SystemDictionaryShared::get_info_locked(k);
 251     if (info->has_checked_exclusion()) {
 252       // We have check exclusion of k and all of its dependencies, so there's no need to check again.
 253       return;
 254     }
 255 
 256     put(k, info);
 257 
 258     if (!k->is_loaded()) {
 259       // super types are not yet initialized for k.
 260       return;
 261     }
 262 
 263     InstanceKlass* super = k->java_super();
 264     if (super != nullptr) {
 265       add_candidate(super);
 266     }
 267 
 268     Array<InstanceKlass*>* interfaces = k->local_interfaces();
 269     int len = interfaces->length();
 270     for (int i = 0; i < len; i++) {
 271       add_candidate(interfaces->at(i));
 272     }
 273 
 274     InstanceKlass* nest_host = k->nest_host_or_null();
 275     if (nest_host != nullptr && nest_host != k) {
 276       add_candidate(nest_host);
 277     }
 278 
 279     if (CDSConfig::is_preserving_verification_constraints()) {
 280       SystemDictionaryShared::iterate_verification_constraint_names(k, info, [&] (Symbol* constraint_class_name) {
 281         Klass* constraint_bottom_class = find_verification_constraint_bottom_class(k, constraint_class_name);
 282         if (constraint_bottom_class != nullptr && constraint_bottom_class->is_instance_klass()) {
 283           add_candidate(InstanceKlass::cast(constraint_bottom_class));
 284         }
 285         return true; // Keep iterating.
 286       });
 287     }
 288   }
 289 
 290 public:
 291   ExclusionCheckCandidates(InstanceKlass* k) {
 292     add_candidate(k);
 293   }
 294 };
 295 
 296 // A class X is excluded if check_self_exclusion() returns true for X or any of
 297 // X's "exclusion dependency" classes, which include:
 298 //     - ik's super types
 299 //     - ik's nest host (if any)
 300 //
 301 //  plus, if CDSConfig::is_preserving_verification_constraints()==true:
 302 //     - ik's verification constraints. These are the classes used in assignability checks
 303 //         when verifying ik's bytecodes.
 304 //
 305 // This method ensure that exclusion check is performed on X and all of its exclusion dependencies.
 306 void SystemDictionaryShared::check_exclusion_for_self_and_dependencies(InstanceKlass* ik) {
 307   assert_lock_strong(DumpTimeTable_lock);
 308   ResourceMark rm;
 309 
 310   // This will recursively find ik and all of its exclusion dependencies that have not yet been checked.
 311   ExclusionCheckCandidates candidates(ik);
 312 
 313   // (1) Check each class to see if it should be excluded due to its own problems
 314   candidates.iterate_all([&] (InstanceKlass* k, DumpTimeClassInfo* info) {
 315     if (check_self_exclusion(k)) {
 316       info->set_excluded();
 317     }
 318   });
 319 
 320   // (2) Check each class to see if it should be excluded because of problems in a depeendency class
 321   while (true) {
 322     bool found_new_exclusion = false;
 323 
 324     candidates.iterate_all([&] (InstanceKlass* k, DumpTimeClassInfo* info) {
 325       if (!info->is_excluded() && check_dependencies_exclusion(k, info)) {
 326         info->set_excluded();
 327         found_new_exclusion = true;
 328       }
 329     });
 330 
 331     // Algorithm notes:
 332     //
 333     // The dependencies form a directed graph, possibly cyclic. Class X is excluded
 334     // if it has at least one directed path that reaches class Y, where
 335     // check_self_exclusion(Y) returns true.
 336     //
 337     // Because of the possibility of cycles in the graph, we cannot use simple
 338     // recursion. Otherwise we will either never terminate, or will miss some paths.
 339     //
 340     // Hence, we keep doing a linear scan of the candidates until we stop finding
 341     // new exclusions.
 342     //
 343     // In the worst case, we find one exclusion per iteration of the while loop,
 344     // so the while loop gets executed O(N^2) times. However, in reality we have
 345     // very few exclusions, so in most cases the while loop executes only once, and we
 346     // walk each edge in the dependencies graph exactly once.
 347     if (!found_new_exclusion) {
 348       break;
 349     }
 350   }
 351   candidates.iterate_all([&] (InstanceKlass* k, DumpTimeClassInfo* info) {
 352     // All candidates have been fully checked, so we don't need to check them again.
 353     info->set_has_checked_exclusion();
 354   });
 355 }
 356 
 357 void SystemDictionaryShared::log_exclusion(InstanceKlass* k, const char* reason, bool is_warning) {
 358   ResourceMark rm;
 359   if (is_warning) {
 360     aot_log_warning(aot)("Skipping %s: %s", k->name()->as_C_string(), reason);
 361   } else {
 362     aot_log_info(aot)("Skipping %s: %s", k->name()->as_C_string(), reason);
 363   }
 364 }
 365 
 366 bool SystemDictionaryShared::is_jfr_event_class(InstanceKlass *k) {
 367   while (k) {
 368     if (k->name()->equals("jdk/internal/event/Event")) {
 369       return true;
 370     }
 371     k = k->super();
 372   }
 373   return false;
 374 }
 375 
 376 bool SystemDictionaryShared::is_early_klass(InstanceKlass* ik) {
 377   DumpTimeClassInfo* info = _dumptime_table->get(ik);
 378   return (info != nullptr) ? info->is_early_klass() : false;
 379 }
 380 
 381 bool SystemDictionaryShared::check_self_exclusion(InstanceKlass* k) {
 382   bool log_warning = false;
 383   const char* error = check_self_exclusion_helper(k, log_warning);
 384   if (error != nullptr) {
 385     log_exclusion(k, error, log_warning);
 386     return true; // Should be excluded
 387   } else {
 388     return false; // Should not be excluded
 389   }
 390 }
 391 
 392 const char* SystemDictionaryShared::check_self_exclusion_helper(InstanceKlass* k, bool& log_warning) {
 393   assert_lock_strong(DumpTimeTable_lock);
 394   if (CDSConfig::is_dumping_final_static_archive() && k->defined_by_other_loaders()
 395       && k->in_aot_cache()) {
 396     return nullptr; // Do not exclude: unregistered classes are passed from preimage to final image.
 397   }
 398 
 399   if (k->is_in_error_state()) {
 400     log_warning = true;
 401     return "In error state";
 402   }
 403   if (k->is_scratch_class()) {
 404     return "A scratch class";
 405   }
 406   if (!k->is_loaded()) {
 407     return "Not in loaded state";
 408   }
 409   if (has_been_redefined(k)) {
 410     return "Has been redefined";
 411   }
 412   if (!k->is_hidden() && k->shared_classpath_index() < 0 && is_builtin(k)) {
 413     if (k->name()->starts_with("java/lang/invoke/BoundMethodHandle$Species_")) {
 414       // This class is dynamically generated by the JDK
 415       if (CDSConfig::is_dumping_method_handles()) {
 416         k->set_shared_classpath_index(0);
 417       } else {
 418         return "dynamically generated";
 419       }
 420     } else {
 421       // These are classes loaded from unsupported locations (such as those loaded by JVMTI native
 422       // agent during dump time).
 423       return "Unsupported location";
 424     }
 425   }
 426   if (k->signers() != nullptr) {
 427     // We cannot include signed classes in the archive because the certificates
 428     // used during dump time may be different than those used during
 429     // runtime (due to expiration, etc).
 430     return "Signed JAR";
 431   }
 432   if (is_jfr_event_class(k)) {
 433     // We cannot include JFR event classes because they need runtime-specific
 434     // instrumentation in order to work with -XX:FlightRecorderOptions:retransform=false.
 435     // There are only a small number of these classes, so it's not worthwhile to
 436     // support them and make CDS more complicated.
 437     return "JFR event class";
 438   }
 439 
 440   if (!k->is_linked()) {
 441     if (has_class_failed_verification(k)) {
 442       log_warning = true;
 443       return "Failed verification";
 444     } else if (CDSConfig::is_dumping_aot_linked_classes()) {
 445       // Most loaded classes should have been speculatively linked by AOTMetaspace::link_class_for_cds().
 446       // Old classes may not be linked if CDSConfig::is_preserving_verification_constraints()==false.
 447       // An unlinked class may fail to verify in AOTLinkedClassBulkLoader::init_required_classes_for_loader(),
 448       // causing the JVM to fail at bootstrap.
 449       return "Unlinked class not supported by AOTClassLinking";
 450     } else if (CDSConfig::is_dumping_preimage_static_archive()) {
 451       // When dumping the final static archive, we will unconditionally load and link all
 452       // classes from the preimage. We don't want to get a VerifyError when linking this class.
 453       return "Unlinked class not supported by AOTConfiguration";
 454     }
 455   } else {
 456     if (!k->can_be_verified_at_dumptime()) {
 457       // We have an old class that has been linked (e.g., it's been executed during
 458       // dump time). This class has been verified using the old verifier, which
 459       // doesn't save the verification constraints, so check_verification_constraints()
 460       // won't work at runtime.
 461       // As a result, we cannot store this class. It must be loaded and fully verified
 462       // at runtime.
 463       return "Old class has been linked";
 464     }
 465   }
 466 
 467   if (UnregisteredClasses::check_for_exclusion(k)) {
 468     return "used only when dumping CDS archive";
 469   }
 470 
 471   return nullptr;
 472 }
 473 
 474 // Returns true if DumpTimeClassInfo::is_excluded() is true for at least one of k's exclusion dependencies.
 475 bool SystemDictionaryShared::check_dependencies_exclusion(InstanceKlass* k, DumpTimeClassInfo* info) {
 476   InstanceKlass* super = k->java_super();
 477   if (super != nullptr && is_dependency_excluded(k, super, "super")) {
 478     return true;
 479   }
 480 
 481   Array<InstanceKlass*>* interfaces = k->local_interfaces();
 482   int len = interfaces->length();
 483   for (int i = 0; i < len; i++) {
 484     InstanceKlass* intf = interfaces->at(i);
 485     if (is_dependency_excluded(k, intf, "interface")) {
 486       return true;
 487     }
 488   }
 489 
 490   InstanceKlass* nest_host = k->nest_host_or_null();
 491   if (nest_host != nullptr && nest_host != k && is_dependency_excluded(k, nest_host, "nest host class")) {
 492     return true;
 493   }
 494 
 495   if (CDSConfig::is_preserving_verification_constraints()) {
 496     bool excluded = false;
 497 
 498     iterate_verification_constraint_names(k, info, [&] (Symbol* constraint_class_name) {
 499       if (check_verification_constraint_exclusion(k, constraint_class_name)) {
 500         // If one of the verification constraint class has been excluded, the assignability checks
 501         // by the verifier may no longer be valid in the production run. For safety, exclude this class.
 502         excluded = true;
 503         return false; // terminate iteration; k will be excluded
 504       } else {
 505         return true; // keep iterating
 506       }
 507     });
 508 
 509     if (excluded) {
 510       // At least one verification constraint class has been excluded
 511       return true;
 512     }
 513   }
 514 
 515   return false;
 516 }
 517 
 518 bool SystemDictionaryShared::is_dependency_excluded(InstanceKlass* k, InstanceKlass* dependency, const char* type) {
 519   if (CDSConfig::is_dumping_dynamic_archive() && AOTMetaspace::in_aot_cache(dependency)) {
 520     return false;
 521   }
 522   DumpTimeClassInfo* dependency_info = get_info_locked(dependency);
 523   if (dependency_info->is_excluded()) {
 524     ResourceMark rm;
 525     aot_log_info(aot)("Skipping %s: %s %s is excluded", k->name()->as_C_string(), type, dependency->name()->as_C_string());
 526     return true;
 527   }
 528   return false;
 529 }
 530 
 531 bool SystemDictionaryShared::check_verification_constraint_exclusion(InstanceKlass* k, Symbol* constraint_class_name) {
 532   Klass* constraint_bottom_class = find_verification_constraint_bottom_class(k, constraint_class_name);
 533   if (constraint_bottom_class == nullptr) {
 534     // We don't have a bottom class (constraint_class_name is a type array), or constraint_class_name
 535     // has not been loaded. The latter case happens when the new verifier was checking
 536     // if constraint_class_name is assignable to an interface, and found the answer without resolving
 537     // constraint_class_name.
 538     //
 539     // Since this class is not even loaded, it surely cannot be excluded.
 540     return false;
 541   } else if (constraint_bottom_class->is_instance_klass()) {
 542     if (is_dependency_excluded(k, InstanceKlass::cast(constraint_bottom_class), "verification constraint")) {
 543       return true;
 544     }
 545   } else {
 546     assert(constraint_bottom_class->is_typeArray_klass(), "must be");
 547   }
 548 
 549   return false;
 550 }
 551 
 552 Klass* SystemDictionaryShared::find_verification_constraint_bottom_class(InstanceKlass* k, Symbol* constraint_class_name) {
 553   Thread* current = Thread::current();
 554   Handle loader(current, k->class_loader());
 555   Klass* constraint_class = SystemDictionary::find_instance_or_array_klass(current, constraint_class_name, loader);
 556   if (constraint_class == nullptr) {
 557     return nullptr;
 558   }
 559 
 560   if (constraint_class->is_objArray_klass()) {
 561     constraint_class = ObjArrayKlass::cast(constraint_class)->bottom_klass();
 562   }
 563 
 564   precond(constraint_class->is_typeArray_klass() || constraint_class->is_instance_klass());
 565   return constraint_class;
 566 }
 567 
 568 bool SystemDictionaryShared::is_builtin_loader(ClassLoaderData* loader_data) {
 569   oop class_loader = loader_data->class_loader();
 570   return (class_loader == nullptr ||
 571           SystemDictionary::is_system_class_loader(class_loader) ||
 572           SystemDictionary::is_platform_class_loader(class_loader));
 573 }
 574 
 575 bool SystemDictionaryShared::has_platform_or_app_classes() {
 576   if (FileMapInfo::current_info()->has_platform_or_app_classes()) {
 577     return true;
 578   }
 579   if (DynamicArchive::is_mapped() &&
 580       FileMapInfo::dynamic_info()->has_platform_or_app_classes()) {
 581     return true;
 582   }
 583   return false;
 584 }
 585 
 586 // The following stack shows how this code is reached:
 587 //
 588 //   [0] SystemDictionaryShared::find_or_load_shared_class()
 589 //   [1] JVM_FindLoadedClass
 590 //   [2] java.lang.ClassLoader.findLoadedClass0()
 591 //   [3] java.lang.ClassLoader.findLoadedClass()
 592 //   [4] jdk.internal.loader.BuiltinClassLoader.loadClassOrNull()
 593 //   [5] jdk.internal.loader.BuiltinClassLoader.loadClass()
 594 //   [6] jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(), or
 595 //       jdk.internal.loader.ClassLoaders$PlatformClassLoader.loadClass()
 596 //
 597 // AppCDS supports fast class loading for these 2 built-in class loaders:
 598 //    jdk.internal.loader.ClassLoaders$PlatformClassLoader
 599 //    jdk.internal.loader.ClassLoaders$AppClassLoader
 600 // with the following assumptions (based on the JDK core library source code):
 601 //
 602 // [a] these two loaders use the BuiltinClassLoader.loadClassOrNull() to
 603 //     load the named class.
 604 // [b] BuiltinClassLoader.loadClassOrNull() first calls findLoadedClass(name).
 605 // [c] At this point, if we can find the named class inside the
 606 //     shared_dictionary, we can perform further checks (see
 607 //     SystemDictionary::is_shared_class_visible) to ensure that this class
 608 //     was loaded by the same class loader during dump time.
 609 //
 610 // Given these assumptions, we intercept the findLoadedClass() call to invoke
 611 // SystemDictionaryShared::find_or_load_shared_class() to load the shared class from
 612 // the archive for the 2 built-in class loaders. This way,
 613 // we can improve start-up because we avoid decoding the classfile,
 614 // and avoid delegating to the parent loader.
 615 //
 616 // NOTE: there's a lot of assumption about the Java code. If any of that change, this
 617 // needs to be redesigned.
 618 
 619 InstanceKlass* SystemDictionaryShared::find_or_load_shared_class(
 620                  Symbol* name, Handle class_loader, TRAPS) {
 621   InstanceKlass* k = nullptr;
 622   if (CDSConfig::is_using_archive()) {
 623     if (!has_platform_or_app_classes()) {
 624       return nullptr;
 625     }
 626 
 627     if (SystemDictionary::is_system_class_loader(class_loader()) ||
 628         SystemDictionary::is_platform_class_loader(class_loader())) {
 629       ClassLoaderData *loader_data = register_loader(class_loader);
 630       Dictionary* dictionary = loader_data->dictionary();
 631 
 632       // Note: currently, find_or_load_shared_class is called only from
 633       // JVM_FindLoadedClass and used for PlatformClassLoader and AppClassLoader,
 634       // which are parallel-capable loaders, so a lock here is NOT taken.
 635       assert(get_loader_lock_or_null(class_loader) == nullptr, "ObjectLocker not required");
 636       {
 637         MutexLocker mu(THREAD, SystemDictionary_lock);
 638         InstanceKlass* check = dictionary->find_class(THREAD, name);
 639         if (check != nullptr) {
 640           return check;
 641         }
 642       }
 643 
 644       k = load_shared_class_for_builtin_loader(name, class_loader, THREAD);
 645       if (k != nullptr) {
 646         SharedClassLoadingMark slm(THREAD, k);
 647         k = find_or_define_instance_class(name, class_loader, k, CHECK_NULL);
 648       }
 649     }
 650   }
 651 
 652   DEBUG_ONLY(check_klass_after_loading(k);)
 653 
 654   return k;
 655 }
 656 
 657 class UnregisteredClassesTable : public HashTable<
 658   Symbol*, InstanceKlass*,
 659   15889, // prime number
 660   AnyObj::C_HEAP> {};
 661 
 662 static UnregisteredClassesTable* _unregistered_classes_table = nullptr;
 663 
 664 // true == class was successfully added; false == a duplicated class (with the same name) already exists.
 665 bool SystemDictionaryShared::add_unregistered_class(Thread* current, InstanceKlass* klass) {
 666   // We don't allow duplicated unregistered classes with the same name.
 667   // We only archive the first class with that name that succeeds putting
 668   // itself into the table.
 669   assert(CDSConfig::is_dumping_archive() || ClassListWriter::is_enabled(), "sanity");
 670   MutexLocker ml(current, UnregisteredClassesTable_lock, Mutex::_no_safepoint_check_flag);
 671   Symbol* name = klass->name();
 672   if (_unregistered_classes_table == nullptr) {
 673     _unregistered_classes_table = new (mtClass)UnregisteredClassesTable();
 674   }
 675   bool created;
 676   InstanceKlass** v = _unregistered_classes_table->put_if_absent(name, klass, &created);
 677   if (created) {
 678     name->increment_refcount();
 679   }
 680   return (klass == *v);
 681 }
 682 
 683 InstanceKlass* SystemDictionaryShared::get_unregistered_class(Symbol* name) {
 684   assert(CDSConfig::is_dumping_archive() || ClassListWriter::is_enabled(), "sanity");
 685   if (_unregistered_classes_table == nullptr) {
 686     return nullptr;
 687   }
 688   InstanceKlass** k = _unregistered_classes_table->get(name);
 689   return k != nullptr ? *k : nullptr;
 690 }
 691 
 692 void SystemDictionaryShared::copy_unregistered_class_size_and_crc32(InstanceKlass* klass) {
 693   precond(CDSConfig::is_dumping_final_static_archive());
 694   precond(klass->in_aot_cache());
 695 
 696   // A shared class must have a RunTimeClassInfo record
 697   const RunTimeClassInfo* record = find_record(&_static_archive._unregistered_dictionary,
 698                                                nullptr, klass->name());
 699   precond(record != nullptr);
 700   precond(record->klass() == klass);
 701 
 702   DumpTimeClassInfo* info = get_info(klass);
 703   info->_clsfile_size = record->crc()->_clsfile_size;
 704   info->_clsfile_crc32 = record->crc()->_clsfile_crc32;
 705 }
 706 
 707 void SystemDictionaryShared::set_shared_class_misc_info(InstanceKlass* k, ClassFileStream* cfs) {
 708   assert(CDSConfig::is_dumping_archive(), "sanity");
 709   assert(!is_builtin(k), "must be unregistered class");
 710   DumpTimeClassInfo* info = get_info(k);
 711   info->_clsfile_size  = cfs->length();
 712   info->_clsfile_crc32 = ClassLoader::crc32(0, (const char*)cfs->buffer(), cfs->length());
 713 }
 714 
 715 void SystemDictionaryShared::initialize() {
 716   if (CDSConfig::is_dumping_archive()) {
 717     _dumptime_table = new (mtClass) DumpTimeSharedClassTable;
 718     LambdaProxyClassDictionary::dumptime_init();
 719     if (CDSConfig::is_dumping_heap()) {
 720       HeapShared::init_dumping();
 721     }
 722   }
 723 }
 724 
 725 void SystemDictionaryShared::init_dumptime_info(InstanceKlass* k) {
 726   MutexLocker ml(DumpTimeTable_lock, Mutex::_no_safepoint_check_flag);
 727   assert(SystemDictionaryShared::class_loading_may_happen(), "sanity");
 728   DumpTimeClassInfo* info = _dumptime_table->allocate_info(k);
 729   if (AOTClassFilter::is_aot_tooling_class(k)) {
 730     info->set_is_aot_tooling_class();
 731   }
 732 }
 733 
 734 void SystemDictionaryShared::remove_dumptime_info(InstanceKlass* k) {
 735   MutexLocker ml(DumpTimeTable_lock, Mutex::_no_safepoint_check_flag);
 736   _dumptime_table->remove(k);
 737 }
 738 
 739 void SystemDictionaryShared::handle_class_unloading(InstanceKlass* klass) {
 740   if (CDSConfig::is_dumping_archive()) {
 741     remove_dumptime_info(klass);
 742   }
 743 
 744   if (CDSConfig::is_dumping_archive() || ClassListWriter::is_enabled()) {
 745     MutexLocker ml(Thread::current(), UnregisteredClassesTable_lock, Mutex::_no_safepoint_check_flag);
 746     if (_unregistered_classes_table != nullptr) {
 747       // Remove the class from _unregistered_classes_table: keep the entry but
 748       // set it to null. This ensure no classes with the same name can be
 749       // added again.
 750       InstanceKlass** v = _unregistered_classes_table->get(klass->name());
 751       if (v != nullptr) {
 752         *v = nullptr;
 753       }
 754     }
 755   } else {
 756     assert(_unregistered_classes_table == nullptr, "must not be used");
 757   }
 758 
 759   if (ClassListWriter::is_enabled()) {
 760     ClassListWriter cw;
 761     cw.handle_class_unloading((const InstanceKlass*)klass);
 762   }
 763 }
 764 
 765 void SystemDictionaryShared::init_dumptime_info_from_preimage(InstanceKlass* k) {
 766   init_dumptime_info(k);
 767   copy_verification_info_from_preimage(k);
 768   copy_linking_constraints_from_preimage(k);
 769 
 770   if (SystemDictionary::is_platform_class_loader(k->class_loader())) {
 771     AOTClassLocationConfig::dumptime_set_has_platform_classes();
 772   } else if (SystemDictionary::is_system_class_loader(k->class_loader())) {
 773     AOTClassLocationConfig::dumptime_set_has_app_classes();
 774   }
 775 }
 776 
 777 // Check if a class or any of its supertypes has been redefined.
 778 bool SystemDictionaryShared::has_been_redefined(InstanceKlass* k) {
 779   if (k->has_been_redefined()) {
 780     return true;
 781   }
 782   if (k->super() != nullptr && has_been_redefined(k->super())) {
 783     return true;
 784   }
 785   Array<InstanceKlass*>* interfaces = k->local_interfaces();
 786   int len = interfaces->length();
 787   for (int i = 0; i < len; i++) {
 788     if (has_been_redefined(interfaces->at(i))) {
 789       return true;
 790     }
 791   }
 792   return false;
 793 }
 794 
 795 // k is a class before relocating by ArchiveBuilder
 796 void SystemDictionaryShared::validate_before_archiving(InstanceKlass* k) {
 797   ResourceMark rm;
 798   const char* name = k->name()->as_C_string();
 799   DumpTimeClassInfo* info = _dumptime_table->get(k);
 800   assert(!class_loading_may_happen(), "class loading must be disabled");
 801   guarantee(info != nullptr, "Class %s must be entered into _dumptime_table", name);
 802   guarantee(!info->is_excluded(), "Should not attempt to archive excluded class %s", name);
 803   if (is_builtin(k)) {
 804     if (k->is_hidden()) {
 805       if (CDSConfig::is_dumping_lambdas_in_legacy_mode()) {
 806         assert(LambdaProxyClassDictionary::is_registered_lambda_proxy_class(k), "unexpected hidden class %s", name);
 807       }
 808     }
 809     guarantee(!k->defined_by_other_loaders(),
 810               "Class loader type must be set for BUILTIN class %s", name);
 811 
 812   } else {
 813     guarantee(k->defined_by_other_loaders(),
 814               "Class loader type must not be set for UNREGISTERED class %s", name);
 815   }
 816 }
 817 
 818 class UnregisteredClassesDuplicationChecker : StackObj {
 819   GrowableArray<InstanceKlass*> _list;
 820   Thread* _thread;
 821 public:
 822   UnregisteredClassesDuplicationChecker() : _thread(Thread::current()) {}
 823 
 824   void do_entry(InstanceKlass* k, DumpTimeClassInfo& info) {
 825     if (!SystemDictionaryShared::is_builtin(k)) {
 826       _list.append(k);
 827     }
 828   }
 829 
 830   static int compare_by_loader(InstanceKlass** a, InstanceKlass** b) {
 831     ClassLoaderData* loader_a = a[0]->class_loader_data();
 832     ClassLoaderData* loader_b = b[0]->class_loader_data();
 833 
 834     if (loader_a != loader_b) {
 835       return primitive_compare(loader_a, loader_b);
 836     } else {
 837       return primitive_compare(a[0], b[0]);
 838     }
 839   }
 840 
 841   void mark_duplicated_classes() {
 842     // Two loaders may load two identical or similar hierarchies of classes. If we
 843     // check for duplication in random order, we may end up excluding important base classes
 844     // in both hierarchies, causing most of the classes to be excluded.
 845     // We sort the classes by their loaders. This way we're likely to archive
 846     // all classes in the one of the two hierarchies.
 847     _list.sort(compare_by_loader);
 848     for (int i = 0; i < _list.length(); i++) {
 849       InstanceKlass* k = _list.at(i);
 850       bool i_am_first = SystemDictionaryShared::add_unregistered_class(_thread, k);
 851       if (!i_am_first) {
 852         SystemDictionaryShared::log_exclusion(k, "Duplicated unregistered class");
 853         SystemDictionaryShared::set_excluded_locked(k);
 854       }
 855     }
 856   }
 857 };
 858 
 859 void SystemDictionaryShared::link_all_exclusion_check_candidates(InstanceKlass* ik) {
 860   bool need_to_link = false;
 861   {
 862     MutexLocker ml(DumpTimeTable_lock, Mutex::_no_safepoint_check_flag);
 863     ExclusionCheckCandidates candidates(ik);
 864 
 865     candidates.iterate_all([&] (InstanceKlass* k, DumpTimeClassInfo* info) {
 866       if (!k->is_linked()) {
 867         need_to_link = true;
 868       }
 869     });
 870   }
 871   if (need_to_link) {
 872     JavaThread* THREAD = JavaThread::current();
 873     if (log_is_enabled(Info, aot, link)) {
 874       ResourceMark rm(THREAD);
 875       log_info(aot, link)("Link all loaded classes for %s", ik->external_name());
 876     }
 877     AOTMetaspace::link_all_loaded_classes(THREAD);
 878   }
 879 }
 880 
 881 // Returns true if the class should be excluded. This can be called by
 882 // AOTConstantPoolResolver before or after we enter the CDS safepoint.
 883 // When called before the safepoint, we need to link the class so that
 884 // it can be checked by should_be_excluded_impl().
 885 bool SystemDictionaryShared::should_be_excluded(Klass* k) {
 886   assert(CDSConfig::is_dumping_archive(), "sanity");
 887   assert(CDSConfig::current_thread_is_vm_or_dumper(), "sanity");
 888 
 889   if (CDSConfig::is_dumping_dynamic_archive() && AOTMetaspace::in_aot_cache(k)) {
 890     // We have reached a super type that's already in the base archive. Treat it
 891     // as "not excluded".
 892     return false;
 893   }
 894 
 895   if (k->is_objArray_klass()) {
 896     return should_be_excluded(ObjArrayKlass::cast(k)->bottom_klass());
 897   } else if (!k->is_instance_klass()) {
 898     assert(k->is_typeArray_klass(), "must be");
 899     return false;
 900   } else {
 901     InstanceKlass* ik = InstanceKlass::cast(k);
 902 
 903     if (!SafepointSynchronize::is_at_safepoint()) {
 904       {
 905         // fast path
 906         MutexLocker ml(DumpTimeTable_lock, Mutex::_no_safepoint_check_flag);
 907         DumpTimeClassInfo* p = get_info_locked(ik);
 908         if (p->has_checked_exclusion()) {
 909           return p->is_excluded();
 910         }
 911       }
 912 
 913       link_all_exclusion_check_candidates(ik);
 914 
 915       MutexLocker ml(DumpTimeTable_lock, Mutex::_no_safepoint_check_flag);
 916       DumpTimeClassInfo* p = get_info_locked(ik);
 917       return should_be_excluded_impl(ik, p);
 918     } else {
 919       // When called within the CDS safepoint, the correctness of this function
 920       // relies on the call to AOTMetaspace::link_all_loaded_classes()
 921       // that happened right before we enter the CDS safepoint.
 922       //
 923       // Do not call this function in other types of safepoints. For example, if this
 924       // is called in a GC safepoint, a klass may be improperly excluded because some
 925       // of its verification constraints have not yet been linked.
 926       assert(CDSConfig::is_at_aot_safepoint(), "Do not call this function in any other safepoint");
 927 
 928       // No need to check for is_linked() as all eligible classes should have
 929       // already been linked in AOTMetaspace::link_class_for_cds().
 930       // Don't take DumpTimeTable_lock as we are in safepoint.
 931       DumpTimeClassInfo* p = _dumptime_table->get(ik);
 932       if (p->is_excluded()) {
 933         return true;
 934       }
 935       return should_be_excluded_impl(ik, p);
 936     }
 937   }
 938 }
 939 
 940 void SystemDictionaryShared::finish_exclusion_checks() {
 941   assert_at_safepoint();
 942   if (CDSConfig::is_dumping_dynamic_archive() || CDSConfig::is_dumping_preimage_static_archive()) {
 943     // Do this first -- if a base class is excluded due to duplication,
 944     // all of its subclasses will also be excluded.
 945     ResourceMark rm;
 946     UnregisteredClassesDuplicationChecker dup_checker;
 947     _dumptime_table->iterate_all_live_classes(&dup_checker);
 948     dup_checker.mark_duplicated_classes();
 949   }
 950 
 951   _dumptime_table->iterate_all_live_classes([&] (InstanceKlass* k, DumpTimeClassInfo& info) {
 952     SystemDictionaryShared::should_be_excluded_impl(k, &info);
 953   });
 954 
 955   _dumptime_table->update_counts();
 956   if (CDSConfig::is_dumping_lambdas_in_legacy_mode()) {
 957     LambdaProxyClassDictionary::cleanup_dumptime_table();
 958   }
 959 }
 960 
 961 bool SystemDictionaryShared::is_excluded_class(InstanceKlass* k) {
 962   assert(!class_loading_may_happen(), "class loading must be disabled");
 963   assert_lock_strong(DumpTimeTable_lock);
 964   assert(CDSConfig::is_dumping_archive(), "sanity");
 965   DumpTimeClassInfo* p = get_info_locked(k);
 966   return p->is_excluded();
 967 }
 968 
 969 void SystemDictionaryShared::set_excluded_locked(InstanceKlass* k) {
 970   assert_lock_strong(DumpTimeTable_lock);
 971   assert(CDSConfig::is_dumping_archive(), "sanity");
 972   DumpTimeClassInfo* info = get_info_locked(k);
 973   info->set_excluded();
 974 }
 975 
 976 void SystemDictionaryShared::set_excluded(InstanceKlass* k) {
 977   assert(CDSConfig::is_dumping_archive(), "sanity");
 978   DumpTimeClassInfo* info = get_info(k);
 979   info->set_excluded();
 980 }
 981 
 982 void SystemDictionaryShared::set_class_has_failed_verification(InstanceKlass* ik) {
 983   assert(CDSConfig::is_dumping_archive(), "sanity");
 984   DumpTimeClassInfo* p = get_info(ik);
 985   p->set_failed_verification();
 986 }
 987 
 988 bool SystemDictionaryShared::has_class_failed_verification(InstanceKlass* ik) {
 989   assert(CDSConfig::is_dumping_archive(), "sanity");
 990   DumpTimeClassInfo* p = _dumptime_table->get(ik);
 991   return (p == nullptr) ? false : p->failed_verification();
 992 }
 993 
 994 void SystemDictionaryShared::set_from_class_file_load_hook(InstanceKlass* ik) {
 995   log_exclusion(ik, "From ClassFileLoadHook");
 996   set_excluded(ik);
 997 }
 998 
 999 void SystemDictionaryShared::dumptime_classes_do(MetaspaceClosure* it) {
1000   assert_lock_strong(DumpTimeTable_lock);
1001 
1002   auto do_klass = [&] (InstanceKlass* k, DumpTimeClassInfo& info) {
1003     if (CDSConfig::is_dumping_final_static_archive() && !k->is_loaded()) {
1004       assert(k->defined_by_other_loaders(), "must be");
1005       info.metaspace_pointers_do(it);
1006     } else if (k->is_loader_alive() && !info.is_excluded()) {
1007       info.metaspace_pointers_do(it);
1008     }
1009   };
1010   _dumptime_table->iterate_all_live_classes(do_klass);
1011 
1012   if (CDSConfig::is_dumping_lambdas_in_legacy_mode()) {
1013     LambdaProxyClassDictionary::dumptime_classes_do(it);
1014   }
1015 }
1016 
1017 // Called from VerificationType::is_reference_assignable_from() before performing the assignability check of
1018 //     T1 must be assignable from T2
1019 // Where:
1020 //     L is the class loader of <k>
1021 //     T1 is the type resolved by L using the name <name>
1022 //     T2 is the type resolved by L using the name <from_name>
1023 //
1024 // The meaning of (*skip_assignability_check):
1025 //     true:  is_reference_assignable_from() should SKIP the assignability check
1026 //     false: is_reference_assignable_from() should COMPLETE the assignability check
1027 void SystemDictionaryShared::add_verification_constraint(InstanceKlass* k, Symbol* name,
1028          Symbol* from_name, bool from_field_is_protected, bool from_is_array, bool from_is_object,
1029          bool* skip_assignability_check) {
1030   assert(CDSConfig::is_dumping_archive(), "sanity");
1031   DumpTimeClassInfo* info = get_info(k);
1032   info->add_verification_constraint(name, from_name, from_field_is_protected,
1033                                     from_is_array, from_is_object);
1034 
1035   if (CDSConfig::is_dumping_classic_static_archive() && !is_builtin(k)) {
1036     // This applies ONLY to the "classic" CDS static dump, which reads the list of
1037     // unregistered classes (those intended for custom class loaders) from the classlist
1038     // and loads them using jdk.internal.misc.CDS$UnregisteredClassLoader.
1039     //
1040     // When the classlist contains an unregistered class k, the supertypes of k are also
1041     // recorded in the classlist. However, the classlist does not contain information about
1042     // any class X that's not a supertype of k but is needed in the verification of k.
1043     // As a result, CDS$UnregisteredClassLoader will not know how to resolve X.
1044     //
1045     // Therefore, we tell the verifier to refrain from resolving X. Instead, X is recorded
1046     // (symbolically) in the verification constraints of k. In the production run,
1047     // when k is loaded, we will go through its verification constraints and resolve X to complete
1048     // the is_reference_assignable_from() checks.
1049     *skip_assignability_check = true;
1050   } else {
1051     // In all other cases, we are using an *actual* class loader to load k, so it should be able
1052     // to resolve any types that are needed for the verification of k.
1053     *skip_assignability_check = false;
1054   }
1055 }
1056 
1057 // When the old verifier is verifying the class <ik> at dump time, it tries to resolve a
1058 // class with the given <name>. For the verification result to be valid at run time, we must
1059 // ensure that <name> resolves to the exact same Klass as in dump time.
1060 void SystemDictionaryShared::add_old_verification_constraint(Thread* current, InstanceKlass* ik, Symbol* name) {
1061   precond(CDSConfig::is_preserving_verification_constraints());
1062   DumpTimeClassInfo* info = get_info(ik);
1063   info->add_verification_constraint(name);
1064 }
1065 
1066 void SystemDictionaryShared::add_enum_klass_static_field(InstanceKlass* ik, int root_index) {
1067   assert(CDSConfig::is_dumping_heap(), "sanity");
1068   DumpTimeClassInfo* info = get_info_locked(ik);
1069   info->add_enum_klass_static_field(root_index);
1070 }
1071 
1072 void SystemDictionaryShared::check_verification_constraints(InstanceKlass* klass,
1073                                                             TRAPS) {
1074   assert(CDSConfig::is_using_archive(), "called at run time with CDS enabled only");
1075   RunTimeClassInfo* record = RunTimeClassInfo::get_for(klass);
1076 
1077   int length = record->num_verifier_constraints();
1078   if (length > 0) {
1079     for (int i = 0; i < length; i++) {
1080       RunTimeClassInfo::RTVerifierConstraint* vc = record->verifier_constraint_at(i);
1081       Symbol* name      = vc->name();
1082       Symbol* from_name = vc->from_name();
1083 
1084       if (from_name == nullptr) {
1085         // This is for old verifier. No need to check, as we can guarantee that all classes checked by
1086         // the old verifier during AOT training phase cannot be replaced in the asembly phase.
1087         precond(CDSConfig::is_dumping_final_static_archive());
1088         continue;
1089       }
1090 
1091       if (log_is_enabled(Trace, aot, verification)) {
1092         ResourceMark rm(THREAD);
1093         log_trace(aot, verification)("check_verification_constraint: %s: %s must be subclass of %s [0x%x]",
1094                                      klass->external_name(), from_name->as_klass_external_name(),
1095                                      name->as_klass_external_name(), record->verifier_constraint_flag(i));
1096       }
1097 
1098       bool ok = VerificationType::resolve_and_check_assignability(klass, name, from_name,
1099          record->from_field_is_protected(i), record->from_is_array(i), record->from_is_object(i), CHECK);
1100       if (!ok) {
1101         ResourceMark rm(THREAD);
1102         stringStream ss;
1103 
1104         ss.print_cr("Bad type on operand stack");
1105         ss.print_cr("Exception Details:");
1106         ss.print_cr("  Location:\n    %s", klass->name()->as_C_string());
1107         ss.print_cr("  Reason:\n    Type '%s' is not assignable to '%s'",
1108                     from_name->as_quoted_ascii(), name->as_quoted_ascii());
1109         THROW_MSG(vmSymbols::java_lang_VerifyError(), ss.as_string());
1110       }
1111     }
1112   }
1113 }
1114 
1115 void SystemDictionaryShared::copy_verification_info_from_preimage(InstanceKlass* klass) {
1116   assert(CDSConfig::is_using_archive(), "called at run time with CDS enabled only");
1117   DumpTimeClassInfo* dt_info = get_info(klass);
1118   RunTimeClassInfo* rt_info = RunTimeClassInfo::get_for(klass); // from preimage
1119 
1120   int length = rt_info->num_verifier_constraints();
1121   if (length > 0) {
1122     for (int i = 0; i < length; i++) {
1123       RunTimeClassInfo::RTVerifierConstraint* vc = rt_info->verifier_constraint_at(i);
1124       Symbol* name      = vc->name();
1125       Symbol* from_name = vc->from_name();
1126 
1127       dt_info->add_verification_constraint(name, from_name,
1128          rt_info->from_field_is_protected(i), rt_info->from_is_array(i), rt_info->from_is_object(i));
1129     }
1130   }
1131 }
1132 
1133 static oop get_class_loader_by(char type) {
1134   if (type == (char)ClassLoader::BOOT_LOADER) {
1135     return (oop)nullptr;
1136   } else if (type == (char)ClassLoader::PLATFORM_LOADER) {
1137     return SystemDictionary::java_platform_loader();
1138   } else {
1139     assert (type == (char)ClassLoader::APP_LOADER, "Sanity");
1140     return SystemDictionary::java_system_loader();
1141   }
1142 }
1143 
1144 // Record class loader constraints that are checked inside
1145 // InstanceKlass::link_class(), so that these can be checked quickly
1146 // at runtime without laying out the vtable/itables.
1147 void SystemDictionaryShared::record_linking_constraint(Symbol* name, InstanceKlass* klass,
1148                                                     Handle loader1, Handle loader2) {
1149   // A linking constraint check is executed when:
1150   //   - klass extends or implements type S
1151   //   - klass overrides method S.M(...) with X.M
1152   //     - If klass defines the method M, X is
1153   //       the same as klass.
1154   //     - If klass does not define the method M,
1155   //       X must be a supertype of klass and X.M is
1156   //       a default method defined by X.
1157   //   - loader1 = X->class_loader()
1158   //   - loader2 = S->class_loader()
1159   //   - loader1 != loader2
1160   //   - M's parameter(s) include an object type T
1161   // We require that
1162   //   - whenever loader1 and loader2 try to
1163   //     resolve the type T, they must always resolve to
1164   //     the same InstanceKlass.
1165   // NOTE: type T may or may not be currently resolved in
1166   // either of these two loaders. The check itself does not
1167   // try to resolve T.
1168   oop klass_loader = klass->class_loader();
1169 
1170   if (!is_system_class_loader(klass_loader) &&
1171       !is_platform_class_loader(klass_loader)) {
1172     // If klass is loaded by system/platform loaders, we can
1173     // guarantee that klass and S must be loaded by the same
1174     // respective loader between dump time and run time, and
1175     // the exact same check on (name, loader1, loader2) will
1176     // be executed. Hence, we can cache this check and execute
1177     // it at runtime without walking the vtable/itables.
1178     //
1179     // This cannot be guaranteed for classes loaded by other
1180     // loaders, so we bail.
1181     return;
1182   }
1183 
1184   assert(is_builtin(klass), "must be");
1185   assert(klass_loader != nullptr, "should not be called for boot loader");
1186   assert(loader1 != loader2, "must be");
1187 
1188   if (CDSConfig::is_dumping_dynamic_archive() && Thread::current()->is_VM_thread()) {
1189     // We are re-laying out the vtable/itables of the *copy* of
1190     // a class during the final stage of dynamic dumping. The
1191     // linking constraints for this class has already been recorded.
1192     return;
1193   }
1194   assert(!Thread::current()->is_VM_thread(), "must be");
1195 
1196   assert(CDSConfig::is_dumping_archive(), "sanity");
1197   DumpTimeClassInfo* info = get_info(klass);
1198   info->record_linking_constraint(name, loader1, loader2);
1199 }
1200 
1201 // returns true IFF there's no need to re-initialize the i/v-tables for klass for
1202 // the purpose of checking class loader constraints.
1203 bool SystemDictionaryShared::check_linking_constraints(Thread* current, InstanceKlass* klass) {
1204   assert(CDSConfig::is_using_archive(), "called at run time with CDS enabled only");
1205   LogTarget(Info, class, loader, constraints) log;
1206   if (klass->defined_by_boot_loader()) {
1207     // No class loader constraint check performed for boot classes.
1208     return true;
1209   }
1210   if (klass->defined_by_platform_loader() || klass->defined_by_app_loader()) {
1211     RunTimeClassInfo* info = RunTimeClassInfo::get_for(klass);
1212     assert(info != nullptr, "Sanity");
1213     if (info->num_loader_constraints() > 0) {
1214       HandleMark hm(current);
1215       for (int i = 0; i < info->num_loader_constraints(); i++) {
1216         RunTimeClassInfo::RTLoaderConstraint* lc = info->loader_constraint_at(i);
1217         Symbol* name = lc->constraint_name();
1218         Handle loader1(current, get_class_loader_by(lc->_loader_type1));
1219         Handle loader2(current, get_class_loader_by(lc->_loader_type2));
1220         if (log.is_enabled()) {
1221           ResourceMark rm(current);
1222           log.print("[CDS add loader constraint for class %s symbol %s loader[0] %s loader[1] %s",
1223                     klass->external_name(), name->as_C_string(),
1224                     ClassLoaderData::class_loader_data(loader1())->loader_name_and_id(),
1225                     ClassLoaderData::class_loader_data(loader2())->loader_name_and_id());
1226         }
1227         if (!SystemDictionary::add_loader_constraint(name, klass, loader1, loader2)) {
1228           // Loader constraint violation has been found. The caller
1229           // will re-layout the vtable/itables to produce the correct
1230           // exception.
1231           if (log.is_enabled()) {
1232             log.print(" failed]");
1233           }
1234           return false;
1235         }
1236         if (log.is_enabled()) {
1237             log.print(" succeeded]");
1238         }
1239       }
1240       return true; // for all recorded constraints added successfully.
1241     }
1242   }
1243   if (log.is_enabled()) {
1244     ResourceMark rm(current);
1245     log.print("[CDS has not recorded loader constraint for class %s]", klass->external_name());
1246   }
1247   return false;
1248 }
1249 
1250 void SystemDictionaryShared::copy_linking_constraints_from_preimage(InstanceKlass* klass) {
1251   assert(CDSConfig::is_using_archive(), "called at run time with CDS enabled only");
1252   JavaThread* current = JavaThread::current();
1253   if (klass->defined_by_platform_loader() || klass->defined_by_app_loader()) {
1254     RunTimeClassInfo* rt_info = RunTimeClassInfo::get_for(klass); // from preimage
1255 
1256     if (rt_info->num_loader_constraints() > 0) {
1257       for (int i = 0; i < rt_info->num_loader_constraints(); i++) {
1258         RunTimeClassInfo::RTLoaderConstraint* lc = rt_info->loader_constraint_at(i);
1259         Symbol* name = lc->constraint_name();
1260         Handle loader1(current, get_class_loader_by(lc->_loader_type1));
1261         Handle loader2(current, get_class_loader_by(lc->_loader_type2));
1262         record_linking_constraint(name, klass, loader1, loader2);
1263       }
1264     }
1265   }
1266 }
1267 
1268 unsigned int SystemDictionaryShared::hash_for_shared_dictionary(address ptr) {
1269   if (ArchiveBuilder::is_active() && ArchiveBuilder::current()->is_in_buffer_space(ptr)) {
1270     uintx offset = ArchiveBuilder::current()->any_to_offset(ptr);
1271     unsigned int hash = primitive_hash<uintx>(offset);
1272     DEBUG_ONLY({
1273         if (MetaspaceObj::in_aot_cache((const MetaspaceObj*)ptr)) {
1274           assert(hash == SystemDictionaryShared::hash_for_shared_dictionary_quick(ptr), "must be");
1275         }
1276       });
1277     return hash;
1278   } else {
1279     return SystemDictionaryShared::hash_for_shared_dictionary_quick(ptr);
1280   }
1281 }
1282 
1283 class CopySharedClassInfoToArchive : StackObj {
1284   CompactHashtableWriter* _writer;
1285   bool _is_builtin;
1286 public:
1287   CopySharedClassInfoToArchive(CompactHashtableWriter* writer,
1288                                bool is_builtin)
1289     : _writer(writer), _is_builtin(is_builtin) {}
1290 
1291   void do_entry(InstanceKlass* k, DumpTimeClassInfo& info) {
1292     if (!info.is_excluded() && info.is_builtin() == _is_builtin) {
1293       size_t byte_size = info.runtime_info_bytesize();
1294       RunTimeClassInfo* record;
1295       record = (RunTimeClassInfo*)ArchiveBuilder::ro_region_alloc(byte_size);
1296       record->init(info);
1297 
1298       unsigned int hash;
1299       Symbol* name = info._klass->name();
1300       name = ArchiveBuilder::current()->get_buffered_addr(name);
1301       hash = SystemDictionaryShared::hash_for_shared_dictionary((address)name);
1302       if (_is_builtin && info._klass->is_hidden()) {
1303         // skip
1304       } else {
1305         _writer->add(hash, AOTCompressedPointers::encode_not_null(record));
1306       }
1307       if (log_is_enabled(Trace, aot, hashtables)) {
1308         ResourceMark rm;
1309         log_trace(aot, hashtables)("%s dictionary: %s", (_is_builtin ? "builtin" : "unregistered"), info._klass->external_name());
1310       }
1311 
1312       // Save this for quick runtime lookup of InstanceKlass* -> RunTimeClassInfo*
1313       InstanceKlass* buffered_klass = ArchiveBuilder::current()->get_buffered_addr(info._klass);
1314       RunTimeClassInfo::set_for(buffered_klass, record);
1315     }
1316   }
1317 };
1318 
1319 void SystemDictionaryShared::write_dictionary(RunTimeSharedDictionary* dictionary,
1320                                               bool is_builtin) {
1321   CompactHashtableStats stats;
1322   dictionary->reset();
1323   CompactHashtableWriter writer(_dumptime_table->count_of(is_builtin), &stats);
1324   CopySharedClassInfoToArchive copy(&writer, is_builtin);
1325   assert_lock_strong(DumpTimeTable_lock);
1326   _dumptime_table->iterate_all_live_classes(&copy);
1327   writer.dump(dictionary, is_builtin ? "builtin dictionary" : "unregistered dictionary");
1328 }
1329 
1330 void SystemDictionaryShared::write_to_archive(bool is_static_archive) {
1331   ArchiveInfo* archive = get_archive(is_static_archive);
1332 
1333   write_dictionary(&archive->_builtin_dictionary, true);
1334   write_dictionary(&archive->_unregistered_dictionary, false);
1335   if (CDSConfig::is_dumping_lambdas_in_legacy_mode()) {
1336     LambdaProxyClassDictionary::write_dictionary(is_static_archive);
1337   } else {
1338     LambdaProxyClassDictionary::reset_dictionary(is_static_archive);
1339   }
1340 }
1341 
1342 void SystemDictionaryShared::serialize_dictionary_headers(SerializeClosure* soc,
1343                                                           bool is_static_archive) {
1344   ArchiveInfo* archive = get_archive(is_static_archive);
1345 
1346   archive->_builtin_dictionary.serialize_header(soc);
1347   archive->_unregistered_dictionary.serialize_header(soc);
1348   LambdaProxyClassDictionary::serialize(soc, is_static_archive);
1349 }
1350 
1351 void SystemDictionaryShared::serialize_vm_classes(SerializeClosure* soc) {
1352   for (auto id : EnumRange<vmClassID>{}) {
1353     soc->do_ptr(vmClasses::klass_addr_at(id));
1354   }
1355 }
1356 
1357 const RunTimeClassInfo*
1358 SystemDictionaryShared::find_record(RunTimeSharedDictionary* static_dict, RunTimeSharedDictionary* dynamic_dict, Symbol* name) {
1359   if (!CDSConfig::is_using_archive() || !name->in_aot_cache()) {
1360     // The names of all shared classes must also be a shared Symbol.
1361     return nullptr;
1362   }
1363 
1364   unsigned int hash = SystemDictionaryShared::hash_for_shared_dictionary_quick(name);
1365   const RunTimeClassInfo* record = nullptr;
1366   if (DynamicArchive::is_mapped()) {
1367     // Use the regenerated holder classes in the dynamic archive as they
1368     // have more methods than those in the base archive.
1369     if (LambdaFormInvokers::may_be_regenerated_class(name)) {
1370       record = dynamic_dict->lookup(name, hash, 0);
1371       if (record != nullptr) {
1372         return record;
1373       }
1374     }
1375   }
1376 
1377   if (!AOTMetaspace::in_aot_cache_dynamic_region(name)) {
1378     // The names of all shared classes in the static dict must also be in the
1379     // static archive
1380     record = static_dict->lookup(name, hash, 0);
1381   }
1382 
1383   if (record == nullptr && DynamicArchive::is_mapped()) {
1384     record = dynamic_dict->lookup(name, hash, 0);
1385   }
1386 
1387   return record;
1388 }
1389 
1390 InstanceKlass* SystemDictionaryShared::find_builtin_class(Symbol* name) {
1391   const RunTimeClassInfo* record = find_record(&_static_archive._builtin_dictionary,
1392                                                &_dynamic_archive._builtin_dictionary,
1393                                                name);
1394   if (record != nullptr) {
1395     assert(!record->klass()->is_hidden(), "hidden class cannot be looked up by name");
1396     DEBUG_ONLY(check_klass_after_loading(record->klass());)
1397     // We did not save the classfile data of the generated LambdaForm invoker classes,
1398     // so we cannot support CLFH for such classes.
1399     if (record->klass()->is_aot_generated_class() && JvmtiExport::should_post_class_file_load_hook()) {
1400        return nullptr;
1401     }
1402     return record->klass();
1403   } else {
1404     return nullptr;
1405   }
1406 }
1407 
1408 void SystemDictionaryShared::update_shared_entry(InstanceKlass* k, int id) {
1409   assert(CDSConfig::is_dumping_static_archive(), "class ID is used only for static dump (from classlist)");
1410   DumpTimeClassInfo* info = get_info(k);
1411   info->_id = id;
1412 }
1413 
1414 const char* SystemDictionaryShared::loader_type_for_shared_class(Klass* k) {
1415   assert(k != nullptr, "Sanity");
1416   assert(k->in_aot_cache(), "Must be");
1417   assert(k->is_instance_klass(), "Must be");
1418   InstanceKlass* ik = InstanceKlass::cast(k);
1419   if (ik->defined_by_boot_loader()) {
1420     return "boot_loader";
1421   } else if (ik->defined_by_platform_loader()) {
1422     return "platform_loader";
1423   } else if (ik->defined_by_app_loader()) {
1424     return "app_loader";
1425   } else if (ik->defined_by_other_loaders()) {
1426     return "unregistered_loader";
1427   } else {
1428     return "unknown loader";
1429   }
1430 }
1431 
1432 void SystemDictionaryShared::get_all_archived_classes(bool is_static_archive, GrowableArray<Klass*>* classes) {
1433   get_archive(is_static_archive)->_builtin_dictionary.iterate_all([&] (const RunTimeClassInfo* record) {
1434       classes->append(record->klass());
1435     });
1436 
1437   get_archive(is_static_archive)->_unregistered_dictionary.iterate_all([&] (const RunTimeClassInfo* record) {
1438       classes->append(record->klass());
1439     });
1440 }
1441 
1442 class SharedDictionaryPrinter : StackObj {
1443   outputStream* _st;
1444   int _index;
1445 public:
1446   SharedDictionaryPrinter(outputStream* st) : _st(st), _index(0) {}
1447 
1448   void do_value(const RunTimeClassInfo* record) {
1449     ResourceMark rm;
1450     _st->print_cr("%4d: %s %s", _index++, record->klass()->external_name(),
1451         SystemDictionaryShared::loader_type_for_shared_class(record->klass()));
1452     if (record->klass()->array_klasses() != nullptr) {
1453       record->klass()->array_klasses()->cds_print_value_on(_st);
1454       _st->cr();
1455     }
1456   }
1457   int index() const { return _index; }
1458 };
1459 
1460 void SystemDictionaryShared::ArchiveInfo::print_on(const char* prefix,
1461                                                    outputStream* st,
1462                                                    bool is_static_archive) {
1463   st->print_cr("%sShared Dictionary", prefix);
1464   SharedDictionaryPrinter p(st);
1465   st->print_cr("%sShared Builtin Dictionary", prefix);
1466   _builtin_dictionary.iterate_all(&p);
1467   st->print_cr("%sShared Unregistered Dictionary", prefix);
1468   _unregistered_dictionary.iterate_all(&p);
1469   LambdaProxyClassDictionary::print_on(prefix, st, p.index(), is_static_archive);
1470 }
1471 
1472 void SystemDictionaryShared::ArchiveInfo::print_table_statistics(const char* prefix,
1473                                                                  outputStream* st,
1474                                                                  bool is_static_archive) {
1475   st->print_cr("%sArchve Statistics", prefix);
1476   _builtin_dictionary.print_table_statistics(st, "Builtin Shared Dictionary");
1477   _unregistered_dictionary.print_table_statistics(st, "Unregistered Shared Dictionary");
1478   LambdaProxyClassDictionary::print_statistics(st, is_static_archive);
1479 }
1480 
1481 void SystemDictionaryShared::print_shared_archive(outputStream* st, bool is_static) {
1482   if (CDSConfig::is_using_archive()) {
1483     if (is_static) {
1484       _static_archive.print_on("", st, true);
1485     } else {
1486       if (DynamicArchive::is_mapped()) {
1487         _dynamic_archive.print_on("Dynamic ", st, false);
1488       }
1489     }
1490   }
1491 }
1492 
1493 void SystemDictionaryShared::print_on(outputStream* st) {
1494   print_shared_archive(st, true);
1495   print_shared_archive(st, false);
1496 }
1497 
1498 void SystemDictionaryShared::print_table_statistics(outputStream* st) {
1499   if (CDSConfig::is_using_archive()) {
1500     _static_archive.print_table_statistics("Static ", st, true);
1501     if (DynamicArchive::is_mapped()) {
1502       _dynamic_archive.print_table_statistics("Dynamic ", st, false);
1503     }
1504   }
1505 }
1506 
1507 bool SystemDictionaryShared::is_dumptime_table_empty() {
1508   assert_lock_strong(DumpTimeTable_lock);
1509   _dumptime_table->update_counts();
1510   if (_dumptime_table->count_of(true) == 0 && _dumptime_table->count_of(false) == 0){
1511     return true;
1512   }
1513   return false;
1514 }