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