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