< prev index next >

src/hotspot/share/classfile/systemDictionaryShared.cpp

Print this page

  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "precompiled.hpp"
  26 #include "cds/archiveBuilder.hpp"
  27 #include "cds/archiveHeapLoader.hpp"
  28 #include "cds/archiveUtils.hpp"
  29 #include "cds/cdsConfig.hpp"
  30 #include "cds/classListParser.hpp"
  31 #include "cds/classListWriter.hpp"
  32 #include "cds/dynamicArchive.hpp"
  33 #include "cds/filemap.hpp"

  34 #include "cds/cdsProtectionDomain.hpp"
  35 #include "cds/dumpTimeClassInfo.inline.hpp"

  36 #include "cds/metaspaceShared.hpp"

  37 #include "cds/runTimeClassInfo.hpp"
  38 #include "classfile/classFileStream.hpp"
  39 #include "classfile/classLoader.hpp"
  40 #include "classfile/classLoaderData.inline.hpp"
  41 #include "classfile/classLoaderDataGraph.hpp"
  42 #include "classfile/classLoaderExt.hpp"
  43 #include "classfile/dictionary.hpp"
  44 #include "classfile/javaClasses.hpp"
  45 #include "classfile/javaClasses.inline.hpp"
  46 #include "classfile/symbolTable.hpp"
  47 #include "classfile/systemDictionary.hpp"
  48 #include "classfile/systemDictionaryShared.hpp"
  49 #include "classfile/verificationType.hpp"
  50 #include "classfile/vmClasses.hpp"
  51 #include "classfile/vmSymbols.hpp"
  52 #include "interpreter/bootstrapInfo.hpp"
  53 #include "jfr/jfrEvents.hpp"
  54 #include "logging/log.hpp"
  55 #include "logging/logStream.hpp"
  56 #include "memory/allocation.hpp"
  57 #include "memory/metadataFactory.hpp"
  58 #include "memory/metaspaceClosure.hpp"
  59 #include "memory/oopFactory.hpp"
  60 #include "memory/resourceArea.hpp"
  61 #include "memory/universe.hpp"
  62 #include "oops/instanceKlass.hpp"
  63 #include "oops/klass.inline.hpp"


  64 #include "oops/objArrayKlass.hpp"
  65 #include "oops/objArrayOop.inline.hpp"
  66 #include "oops/oop.inline.hpp"
  67 #include "oops/oopHandle.inline.hpp"
  68 #include "oops/typeArrayOop.inline.hpp"
  69 #include "runtime/arguments.hpp"
  70 #include "runtime/handles.inline.hpp"
  71 #include "runtime/java.hpp"
  72 #include "runtime/javaCalls.hpp"
  73 #include "runtime/mutexLocker.hpp"
  74 #include "utilities/resourceHash.hpp"
  75 #include "utilities/stringUtils.hpp"
  76 
  77 SystemDictionaryShared::ArchiveInfo SystemDictionaryShared::_static_archive;
  78 SystemDictionaryShared::ArchiveInfo SystemDictionaryShared::_dynamic_archive;
  79 
  80 DumpTimeSharedClassTable* SystemDictionaryShared::_dumptime_table = nullptr;
  81 DumpTimeLambdaProxyClassDictionary* SystemDictionaryShared::_dumptime_lambda_proxy_class_dictionary = nullptr;
  82 









  83 // Used by NoClassLoadingMark
  84 DEBUG_ONLY(bool SystemDictionaryShared::_class_loading_may_happen = true;)
  85 
  86 InstanceKlass* SystemDictionaryShared::load_shared_class_for_builtin_loader(
  87                  Symbol* class_name, Handle class_loader, TRAPS) {
  88   assert(CDSConfig::is_using_archive(), "must be");
  89   InstanceKlass* ik = find_builtin_class(class_name);
  90 
  91   if (ik != nullptr && !ik->shared_loading_failed()) {
  92     if ((SystemDictionary::is_system_class_loader(class_loader()) && ik->is_shared_app_class())  ||
  93         (SystemDictionary::is_platform_class_loader(class_loader()) && ik->is_shared_platform_class())) {
  94       SharedClassLoadingMark slm(THREAD, ik);
  95       PackageEntry* pkg_entry = CDSProtectionDomain::get_package_entry_from_class(ik, class_loader);
  96       Handle protection_domain =
  97         CDSProtectionDomain::init_security_info(class_loader, ik, pkg_entry, CHECK_NULL);



  98       return load_shared_class(ik, class_loader, protection_domain, nullptr, pkg_entry, THREAD);
  99     }
 100   }
 101   return nullptr;
 102 }
 103 
 104 // This function is called for loading only UNREGISTERED classes
 105 InstanceKlass* SystemDictionaryShared::lookup_from_stream(Symbol* class_name,
 106                                                           Handle class_loader,
 107                                                           Handle protection_domain,
 108                                                           const ClassFileStream* cfs,
 109                                                           TRAPS) {
 110   if (!CDSConfig::is_using_archive()) {
 111     return nullptr;
 112   }
 113   if (class_name == nullptr) {  // don't do this for hidden classes
 114     return nullptr;
 115   }
 116   if (class_loader.is_null() ||
 117       SystemDictionary::is_system_class_loader(class_loader()) ||

 164   loader_data->add_class(ik);
 165 
 166   // Get the package entry.
 167   PackageEntry* pkg_entry = CDSProtectionDomain::get_package_entry_from_class(ik, class_loader);
 168 
 169   // Load and check super/interfaces, restore unshareable info
 170   InstanceKlass* shared_klass = load_shared_class(ik, class_loader, protection_domain,
 171                                                   cfs, pkg_entry, THREAD);
 172   if (shared_klass == nullptr || HAS_PENDING_EXCEPTION) {
 173     // TODO: clean up <ik> so it can be used again
 174     return nullptr;
 175   }
 176 
 177   return shared_klass;
 178 }
 179 
 180 // Guaranteed to return non-null value for non-shared classes.
 181 // k must not be a shared class.
 182 DumpTimeClassInfo* SystemDictionaryShared::get_info(InstanceKlass* k) {
 183   MutexLocker ml(DumpTimeTable_lock, Mutex::_no_safepoint_check_flag);
 184   assert(!k->is_shared(), "sanity");
 185   return get_info_locked(k);
 186 }
 187 
 188 DumpTimeClassInfo* SystemDictionaryShared::get_info_locked(InstanceKlass* k) {
 189   assert_lock_strong(DumpTimeTable_lock);
 190   assert(!k->is_shared(), "sanity");
 191   DumpTimeClassInfo* info = _dumptime_table->get_info(k);
 192   assert(info != nullptr, "must be");
 193   return info;
 194 }
 195 








 196 bool SystemDictionaryShared::check_for_exclusion(InstanceKlass* k, DumpTimeClassInfo* info) {
 197   if (MetaspaceShared::is_in_shared_metaspace(k)) {
 198     // We have reached a super type that's already in the base archive. Treat it
 199     // as "not excluded".
 200     assert(CDSConfig::is_dumping_dynamic_archive(), "must be");
 201     return false;
 202   }
 203 
 204   if (info == nullptr) {
 205     info = _dumptime_table->get(k);
 206     assert(info != nullptr, "supertypes of any classes in _dumptime_table must either be shared, or must also be in _dumptime_table");
 207   }
 208 
 209   if (!info->has_checked_exclusion()) {
 210     if (check_for_exclusion_impl(k)) {
 211       info->set_excluded();
 212     }
 213     info->set_has_checked_exclusion();
 214   }
 215 
 216   return info->is_excluded();
 217 }

 243   if (info != nullptr) {
 244     info->_is_archived_lambda_proxy = false;
 245     info->set_excluded();
 246   }
 247 }
 248 
 249 bool SystemDictionaryShared::is_early_klass(InstanceKlass* ik) {
 250   DumpTimeClassInfo* info = _dumptime_table->get(ik);
 251   return (info != nullptr) ? info->is_early_klass() : false;
 252 }
 253 
 254 bool SystemDictionaryShared::is_hidden_lambda_proxy(InstanceKlass* ik) {
 255   assert(ik->is_shared(), "applicable to only a shared class");
 256   if (ik->is_hidden()) {
 257     return true;
 258   } else {
 259     return false;
 260   }
 261 }
 262 





 263 bool SystemDictionaryShared::check_for_exclusion_impl(InstanceKlass* k) {





 264   if (k->is_in_error_state()) {
 265     return warn_excluded(k, "In error state");
 266   }
 267   if (k->is_scratch_class()) {
 268     return warn_excluded(k, "A scratch class");
 269   }
 270   if (!k->is_loaded()) {
 271     return warn_excluded(k, "Not in loaded state");
 272   }
 273   if (has_been_redefined(k)) {
 274     return warn_excluded(k, "Has been redefined");
 275   }
 276   if (!k->is_hidden() && k->shared_classpath_index() < 0 && is_builtin(k)) {
 277     if (k->name()->starts_with("java/lang/invoke/BoundMethodHandle$Species_")) {
 278       // This class is dynamically generated by the JDK
 279       ResourceMark rm;
 280       log_info(cds)("Skipping %s because it is dynamically generated", k->name()->as_C_string());
 281       return true; // exclude without warning




 282     } else {
 283       // These are classes loaded from unsupported locations (such as those loaded by JVMTI native
 284       // agent during dump time).
 285       return warn_excluded(k, "Unsupported location");
 286     }
 287   }
 288   if (k->signers() != nullptr) {
 289     // We cannot include signed classes in the archive because the certificates
 290     // used during dump time may be different than those used during
 291     // runtime (due to expiration, etc).
 292     return warn_excluded(k, "Signed JAR");
 293   }
 294   if (is_jfr_event_class(k)) {
 295     // We cannot include JFR event classes because they need runtime-specific
 296     // instrumentation in order to work with -XX:FlightRecorderOptions:retransform=false.
 297     // There are only a small number of these classes, so it's not worthwhile to
 298     // support them and make CDS more complicated.
 299     return warn_excluded(k, "JFR event class");


 300   }
 301 
 302   if (!k->is_linked()) {
 303     if (has_class_failed_verification(k)) {
 304       return warn_excluded(k, "Failed verification");
 305     }
 306   } else {
 307     if (!k->can_be_verified_at_dumptime()) {
 308       // We have an old class that has been linked (e.g., it's been executed during
 309       // dump time). This class has been verified using the old verifier, which
 310       // doesn't save the verification constraints, so check_verification_constraints()
 311       // won't work at runtime.
 312       // As a result, we cannot store this class. It must be loaded and fully verified
 313       // at runtime.
 314       return warn_excluded(k, "Old class has been linked");


 315     }
 316   }
 317 
 318   if (k->is_hidden() && !is_registered_lambda_proxy_class(k)) {
 319     ResourceMark rm;
 320     log_debug(cds)("Skipping %s: Hidden class", k->name()->as_C_string());
 321     return true;
 322   }
 323 
 324   InstanceKlass* super = k->java_super();
 325   if (super != nullptr && check_for_exclusion(super, nullptr)) {
 326     ResourceMark rm;
 327     log_warning(cds)("Skipping %s: super class %s is excluded", k->name()->as_C_string(), super->name()->as_C_string());
 328     return true;
 329   }
 330 
 331   Array<InstanceKlass*>* interfaces = k->local_interfaces();
 332   int len = interfaces->length();
 333   for (int i = 0; i < len; i++) {
 334     InstanceKlass* intf = interfaces->at(i);
 335     if (check_for_exclusion(intf, nullptr)) {
 336       ResourceMark rm;
 337       log_warning(cds)("Skipping %s: interface %s is excluded", k->name()->as_C_string(), intf->name()->as_C_string());
 338       return true;
 339     }
 340   }
 341 






 342   return false; // false == k should NOT be excluded
 343 }
 344 
 345 bool SystemDictionaryShared::is_builtin_loader(ClassLoaderData* loader_data) {
 346   oop class_loader = loader_data->class_loader();
 347   return (class_loader == nullptr ||
 348           SystemDictionary::is_system_class_loader(class_loader) ||
 349           SystemDictionary::is_platform_class_loader(class_loader));
 350 }
 351 
 352 bool SystemDictionaryShared::has_platform_or_app_classes() {
 353   if (FileMapInfo::current_info()->has_platform_or_app_classes()) {
 354     return true;
 355   }
 356   if (DynamicArchive::is_mapped() &&
 357       FileMapInfo::dynamic_info()->has_platform_or_app_classes()) {
 358     return true;
 359   }
 360   return false;
 361 }

 492     // The VM is not trying to resolve a super type of parser->current_class_name().
 493     // Instead, it's resolving an error class (because parser->current_class_name() has
 494     // failed parsing or verification). Don't do anything here.
 495     return nullptr;
 496   }
 497 }
 498 
 499 void SystemDictionaryShared::set_shared_class_misc_info(InstanceKlass* k, ClassFileStream* cfs) {
 500   assert(CDSConfig::is_dumping_archive(), "sanity");
 501   assert(!is_builtin(k), "must be unregistered class");
 502   DumpTimeClassInfo* info = get_info(k);
 503   info->_clsfile_size  = cfs->length();
 504   info->_clsfile_crc32 = ClassLoader::crc32(0, (const char*)cfs->buffer(), cfs->length());
 505 }
 506 
 507 void SystemDictionaryShared::initialize() {
 508   if (CDSConfig::is_dumping_archive()) {
 509     _dumptime_table = new (mtClass) DumpTimeSharedClassTable;
 510     _dumptime_lambda_proxy_class_dictionary =
 511                       new (mtClass) DumpTimeLambdaProxyClassDictionary;

 512   }
 513 }
 514 
 515 void SystemDictionaryShared::init_dumptime_info(InstanceKlass* k) {
 516   MutexLocker ml(DumpTimeTable_lock, Mutex::_no_safepoint_check_flag);
 517   assert(SystemDictionaryShared::class_loading_may_happen(), "sanity");
 518   _dumptime_table->allocate_info(k);







 519 }
 520 
 521 void SystemDictionaryShared::remove_dumptime_info(InstanceKlass* k) {
 522   MutexLocker ml(DumpTimeTable_lock, Mutex::_no_safepoint_check_flag);
 523   _dumptime_table->remove(k);
 524 }
 525 
 526 void SystemDictionaryShared::handle_class_unloading(InstanceKlass* klass) {
 527   if (CDSConfig::is_dumping_archive()) {
 528     remove_dumptime_info(klass);
 529   }
 530 
 531   if (CDSConfig::is_dumping_archive() || ClassListWriter::is_enabled()) {
 532     MutexLocker ml(Thread::current(), UnregisteredClassesTable_lock, Mutex::_no_safepoint_check_flag);
 533     if (_unregistered_classes_table != nullptr) {
 534       // Remove the class from _unregistered_classes_table: keep the entry but
 535       // set it to null. This ensure no classes with the same name can be
 536       // added again.
 537       InstanceKlass** v = _unregistered_classes_table->get(klass->name());
 538       if (v != nullptr) {

 560   Array<InstanceKlass*>* interfaces = k->local_interfaces();
 561   int len = interfaces->length();
 562   for (int i = 0; i < len; i++) {
 563     if (has_been_redefined(interfaces->at(i))) {
 564       return true;
 565     }
 566   }
 567   return false;
 568 }
 569 
 570 // k is a class before relocating by ArchiveBuilder
 571 void SystemDictionaryShared::validate_before_archiving(InstanceKlass* k) {
 572   ResourceMark rm;
 573   const char* name = k->name()->as_C_string();
 574   DumpTimeClassInfo* info = _dumptime_table->get(k);
 575   assert(!class_loading_may_happen(), "class loading must be disabled");
 576   guarantee(info != nullptr, "Class %s must be entered into _dumptime_table", name);
 577   guarantee(!info->is_excluded(), "Should not attempt to archive excluded class %s", name);
 578   if (is_builtin(k)) {
 579     if (k->is_hidden()) {
 580       assert(is_registered_lambda_proxy_class(k), "unexpected hidden class %s", name);



 581     }
 582     guarantee(!k->is_shared_unregistered_class(),
 583               "Class loader type must be set for BUILTIN class %s", name);
 584 
 585   } else {
 586     guarantee(k->is_shared_unregistered_class(),
 587               "Class loader type must not be set for UNREGISTERED class %s", name);
 588   }
 589 }
 590 
 591 class UnregisteredClassesDuplicationChecker : StackObj {
 592   GrowableArray<InstanceKlass*> _list;
 593   Thread* _thread;
 594 public:
 595   UnregisteredClassesDuplicationChecker() : _thread(Thread::current()) {}
 596 
 597   void do_entry(InstanceKlass* k, DumpTimeClassInfo& info) {
 598     if (!SystemDictionaryShared::is_builtin(k)) {
 599       _list.append(k);
 600     }

 612   }
 613 
 614   void mark_duplicated_classes() {
 615     // Two loaders may load two identical or similar hierarchies of classes. If we
 616     // check for duplication in random order, we may end up excluding important base classes
 617     // in both hierarchies, causing most of the classes to be excluded.
 618     // We sort the classes by their loaders. This way we're likely to archive
 619     // all classes in the one of the two hierarchies.
 620     _list.sort(compare_by_loader);
 621     for (int i = 0; i < _list.length(); i++) {
 622       InstanceKlass* k = _list.at(i);
 623       bool i_am_first = SystemDictionaryShared::add_unregistered_class(_thread, k);
 624       if (!i_am_first) {
 625         SystemDictionaryShared::warn_excluded(k, "Duplicated unregistered class");
 626         SystemDictionaryShared::set_excluded_locked(k);
 627       }
 628     }
 629   }
 630 };
 631 
 632 void SystemDictionaryShared::check_excluded_classes() {











































































 633   assert(!class_loading_may_happen(), "class loading must be disabled");
 634   assert_lock_strong(DumpTimeTable_lock);
 635 
 636   if (CDSConfig::is_dumping_dynamic_archive()) {
 637     // Do this first -- if a base class is excluded due to duplication,
 638     // all of its subclasses will also be excluded.
 639     ResourceMark rm;
 640     UnregisteredClassesDuplicationChecker dup_checker;
 641     _dumptime_table->iterate_all_live_classes(&dup_checker);
 642     dup_checker.mark_duplicated_classes();
 643   }
 644 
 645   auto check_for_exclusion = [&] (InstanceKlass* k, DumpTimeClassInfo& info) {
 646     SystemDictionaryShared::check_for_exclusion(k, &info);









 647   };
 648   _dumptime_table->iterate_all_live_classes(check_for_exclusion);































 649   _dumptime_table->update_counts();
 650 
 651   cleanup_lambda_proxy_class_dictionary();




 652 }
 653 
 654 bool SystemDictionaryShared::is_excluded_class(InstanceKlass* k) {
 655   assert(!class_loading_may_happen(), "class loading must be disabled");
 656   assert_lock_strong(DumpTimeTable_lock);
 657   assert(CDSConfig::is_dumping_archive(), "sanity");
 658   DumpTimeClassInfo* p = get_info_locked(k);
 659   return p->is_excluded();
 660 }
 661 
 662 void SystemDictionaryShared::set_excluded_locked(InstanceKlass* k) {
 663   assert_lock_strong(DumpTimeTable_lock);
 664   assert(CDSConfig::is_dumping_archive(), "sanity");
 665   DumpTimeClassInfo* info = get_info_locked(k);
 666   info->set_excluded();
 667 }
 668 
 669 void SystemDictionaryShared::set_excluded(InstanceKlass* k) {
 670   assert(CDSConfig::is_dumping_archive(), "sanity");
 671   DumpTimeClassInfo* info = get_info(k);
 672   info->set_excluded();
 673 }
 674 
 675 void SystemDictionaryShared::set_class_has_failed_verification(InstanceKlass* ik) {
 676   assert(CDSConfig::is_dumping_archive(), "sanity");
 677   DumpTimeClassInfo* p = get_info(ik);
 678   p->set_failed_verification();
 679 }
 680 
 681 bool SystemDictionaryShared::has_class_failed_verification(InstanceKlass* ik) {
 682   assert(CDSConfig::is_dumping_archive(), "sanity");
 683   DumpTimeClassInfo* p = _dumptime_table->get(ik);
 684   return (p == nullptr) ? false : p->failed_verification();
 685 }
 686 
 687 void SystemDictionaryShared::dumptime_classes_do(class MetaspaceClosure* it) {
 688   assert_lock_strong(DumpTimeTable_lock);
 689 
 690   auto do_klass = [&] (InstanceKlass* k, DumpTimeClassInfo& info) {
 691     if (k->is_loader_alive() && !info.is_excluded()) {



 692       info.metaspace_pointers_do(it);
 693     }
 694   };
 695   _dumptime_table->iterate_all_live_classes(do_klass);
 696 
 697   auto do_lambda = [&] (LambdaProxyClassKey& key, DumpTimeLambdaProxyClassInfo& info) {
 698     if (key.caller_ik()->is_loader_alive()) {
 699       info.metaspace_pointers_do(it);
 700       key.metaspace_pointers_do(it);
 701     }
 702   };
 703   _dumptime_lambda_proxy_class_dictionary->iterate_all(do_lambda);






 704 }
 705 
 706 bool SystemDictionaryShared::add_verification_constraint(InstanceKlass* k, Symbol* name,
 707          Symbol* from_name, bool from_field_is_protected, bool from_is_array, bool from_is_object) {
 708   assert(CDSConfig::is_dumping_archive(), "sanity");











 709   DumpTimeClassInfo* info = get_info(k);
 710   info->add_verification_constraint(k, name, from_name, from_field_is_protected,
 711                                     from_is_array, from_is_object);
 712 
 713   if (CDSConfig::is_dumping_dynamic_archive()) {
 714     // For dynamic dumping, we can resolve all the constraint classes for all class loaders during
 715     // the initial run prior to creating the archive before vm exit. We will also perform verification
 716     // check when running with the archive.
 717     return false;
 718   } else {
 719     if (is_builtin(k)) {
 720       // For builtin class loaders, we can try to complete the verification check at dump time,
 721       // because we can resolve all the constraint classes. We will also perform verification check
 722       // when running with the archive.
 723       return false;
 724     } else {
 725       // For non-builtin class loaders, we cannot complete the verification check at dump time,
 726       // because at dump time we don't know how to resolve classes for such loaders.
 727       return true;
 728     }

 738 void SystemDictionaryShared::add_to_dump_time_lambda_proxy_class_dictionary(LambdaProxyClassKey& key,
 739                                                            InstanceKlass* proxy_klass) {
 740   assert_lock_strong(DumpTimeTable_lock);
 741 
 742   bool created;
 743   DumpTimeLambdaProxyClassInfo* info = _dumptime_lambda_proxy_class_dictionary->put_if_absent(key, &created);
 744   info->add_proxy_klass(proxy_klass);
 745   if (created) {
 746     ++_dumptime_lambda_proxy_class_dictionary->_count;
 747   }
 748 }
 749 
 750 void SystemDictionaryShared::add_lambda_proxy_class(InstanceKlass* caller_ik,
 751                                                     InstanceKlass* lambda_ik,
 752                                                     Symbol* invoked_name,
 753                                                     Symbol* invoked_type,
 754                                                     Symbol* method_type,
 755                                                     Method* member_method,
 756                                                     Symbol* instantiated_method_type,
 757                                                     TRAPS) {









 758 
 759   assert(caller_ik->class_loader() == lambda_ik->class_loader(), "mismatched class loader");
 760   assert(caller_ik->class_loader_data() == lambda_ik->class_loader_data(), "mismatched class loader data");
 761   assert(java_lang_Class::class_data(lambda_ik->java_mirror()) == nullptr, "must not have class data");
 762 
 763   MutexLocker ml(DumpTimeTable_lock, Mutex::_no_safepoint_check_flag);
 764 
 765   lambda_ik->assign_class_loader_type();
 766   lambda_ik->set_shared_classpath_index(caller_ik->shared_classpath_index());
 767   InstanceKlass* nest_host = caller_ik->nest_host(CHECK);
 768   assert(nest_host != nullptr, "unexpected nullptr nest_host");
 769 
 770   DumpTimeClassInfo* info = _dumptime_table->get(lambda_ik);
 771   if (info != nullptr && !lambda_ik->is_non_strong_hidden() && is_builtin(lambda_ik) && is_builtin(caller_ik)
 772       // Don't include the lambda proxy if its nest host is not in the "linked" state.
 773       && nest_host->is_linked()) {
 774     // Set _is_archived_lambda_proxy in DumpTimeClassInfo so that the lambda_ik
 775     // won't be excluded during dumping of shared archive. See ExcludeDumpTimeSharedClasses.
 776     info->_is_archived_lambda_proxy = true;
 777     info->set_nest_host(nest_host);
 778 
 779     LambdaProxyClassKey key(caller_ik,
 780                             invoked_name,
 781                             invoked_type,
 782                             method_type,
 783                             member_method,
 784                             instantiated_method_type);
 785     add_to_dump_time_lambda_proxy_class_dictionary(key, lambda_ik);
 786   }
 787 }
 788 
 789 InstanceKlass* SystemDictionaryShared::get_shared_lambda_proxy_class(InstanceKlass* caller_ik,
 790                                                                      Symbol* invoked_name,
 791                                                                      Symbol* invoked_type,
 792                                                                      Symbol* method_type,
 793                                                                      Method* member_method,
 794                                                                      Symbol* instantiated_method_type) {



 795   MutexLocker ml(CDSLambda_lock, Mutex::_no_safepoint_check_flag);
 796   LambdaProxyClassKey key(caller_ik, invoked_name, invoked_type,
 797                           method_type, member_method, instantiated_method_type);
 798 
 799   // Try to retrieve the lambda proxy class from static archive.
 800   const RunTimeLambdaProxyClassInfo* info = _static_archive.lookup_lambda_proxy_class(&key);
 801   InstanceKlass* proxy_klass = retrieve_lambda_proxy_class(info);
 802   if (proxy_klass == nullptr) {
 803     if (info != nullptr && log_is_enabled(Debug, cds)) {
 804       ResourceMark rm;
 805       log_debug(cds)("Used all static archived lambda proxy classes for: %s %s%s",
 806                      caller_ik->external_name(), invoked_name->as_C_string(), invoked_type->as_C_string());
 807     }
 808   } else {
 809     return proxy_klass;
 810   }
 811 
 812   // Retrieving from static archive is unsuccessful, try dynamic archive.
 813   info = _dynamic_archive.lookup_lambda_proxy_class(&key);
 814   proxy_klass = retrieve_lambda_proxy_class(info);

 823 }
 824 
 825 InstanceKlass* SystemDictionaryShared::retrieve_lambda_proxy_class(const RunTimeLambdaProxyClassInfo* info) {
 826   InstanceKlass* proxy_klass = nullptr;
 827   if (info != nullptr) {
 828     InstanceKlass* curr_klass = info->proxy_klass_head();
 829     InstanceKlass* prev_klass = curr_klass;
 830     if (curr_klass->lambda_proxy_is_available()) {
 831       while (curr_klass->next_link() != nullptr) {
 832         prev_klass = curr_klass;
 833         curr_klass = InstanceKlass::cast(curr_klass->next_link());
 834       }
 835       assert(curr_klass->is_hidden(), "must be");
 836       assert(curr_klass->lambda_proxy_is_available(), "must be");
 837 
 838       prev_klass->set_next_link(nullptr);
 839       proxy_klass = curr_klass;
 840       proxy_klass->clear_lambda_proxy_is_available();
 841       if (log_is_enabled(Debug, cds)) {
 842         ResourceMark rm;
 843         log_debug(cds)("Loaded lambda proxy: %s ", proxy_klass->external_name());
 844       }
 845     }
 846   }
 847   return proxy_klass;
 848 }
 849 
 850 InstanceKlass* SystemDictionaryShared::get_shared_nest_host(InstanceKlass* lambda_ik) {
 851   assert(!CDSConfig::is_dumping_static_archive() && CDSConfig::is_using_archive(), "called at run time with CDS enabled only");
 852   RunTimeClassInfo* record = RunTimeClassInfo::get_for(lambda_ik);
 853   return record->nest_host();
 854 }
 855 
 856 InstanceKlass* SystemDictionaryShared::prepare_shared_lambda_proxy_class(InstanceKlass* lambda_ik,
 857                                                                          InstanceKlass* caller_ik, TRAPS) {
 858   Handle class_loader(THREAD, caller_ik->class_loader());
 859   Handle protection_domain;
 860   PackageEntry* pkg_entry = caller_ik->package();
 861   if (caller_ik->class_loader() != nullptr) {
 862     protection_domain = CDSProtectionDomain::init_security_info(class_loader, caller_ik, pkg_entry, CHECK_NULL);
 863   }

 882   // Add to class hierarchy, and do possible deoptimizations.
 883   loaded_lambda->add_to_hierarchy(THREAD);
 884   // But, do not add to dictionary.
 885 
 886   loaded_lambda->link_class(CHECK_NULL);
 887   // notify jvmti
 888   if (JvmtiExport::should_post_class_load()) {
 889     JvmtiExport::post_class_load(THREAD, loaded_lambda);
 890   }
 891   if (class_load_start_event.should_commit()) {
 892     SystemDictionary::post_class_load_event(&class_load_start_event, loaded_lambda, ClassLoaderData::class_loader_data(class_loader()));
 893   }
 894 
 895   loaded_lambda->initialize(CHECK_NULL);
 896 
 897   return loaded_lambda;
 898 }
 899 
 900 void SystemDictionaryShared::check_verification_constraints(InstanceKlass* klass,
 901                                                             TRAPS) {
 902   assert(!CDSConfig::is_dumping_static_archive() && CDSConfig::is_using_archive(), "called at run time with CDS enabled only");
 903   RunTimeClassInfo* record = RunTimeClassInfo::get_for(klass);
 904 
 905   int length = record->_num_verifier_constraints;
 906   if (length > 0) {
 907     for (int i = 0; i < length; i++) {
 908       RunTimeClassInfo::RTVerifierConstraint* vc = record->verifier_constraint_at(i);
 909       Symbol* name      = vc->name();
 910       Symbol* from_name = vc->from_name();
 911       char c            = record->verifier_constraint_flag(i);
 912 
 913       if (log_is_enabled(Trace, cds, verification)) {
 914         ResourceMark rm(THREAD);
 915         log_trace(cds, verification)("check_verification_constraint: %s: %s must be subclass of %s [0x%x]",
 916                                      klass->external_name(), from_name->as_klass_external_name(),
 917                                      name->as_klass_external_name(), c);
 918       }
 919 
 920       bool from_field_is_protected = (c & SystemDictionaryShared::FROM_FIELD_IS_PROTECTED) ? true : false;
 921       bool from_is_array           = (c & SystemDictionaryShared::FROM_IS_ARRAY)           ? true : false;
 922       bool from_is_object          = (c & SystemDictionaryShared::FROM_IS_OBJECT)          ? true : false;

 992   assert(is_builtin(klass), "must be");
 993   assert(klass_loader != nullptr, "should not be called for boot loader");
 994   assert(loader1 != loader2, "must be");
 995 
 996   if (CDSConfig::is_dumping_dynamic_archive() && Thread::current()->is_VM_thread()) {
 997     // We are re-laying out the vtable/itables of the *copy* of
 998     // a class during the final stage of dynamic dumping. The
 999     // linking constraints for this class has already been recorded.
1000     return;
1001   }
1002   assert(!Thread::current()->is_VM_thread(), "must be");
1003 
1004   assert(CDSConfig::is_dumping_archive(), "sanity");
1005   DumpTimeClassInfo* info = get_info(klass);
1006   info->record_linking_constraint(name, loader1, loader2);
1007 }
1008 
1009 // returns true IFF there's no need to re-initialize the i/v-tables for klass for
1010 // the purpose of checking class loader constraints.
1011 bool SystemDictionaryShared::check_linking_constraints(Thread* current, InstanceKlass* klass) {
1012   assert(!CDSConfig::is_dumping_static_archive() && CDSConfig::is_using_archive(), "called at run time with CDS enabled only");
1013   LogTarget(Info, class, loader, constraints) log;
1014   if (klass->is_shared_boot_class()) {
1015     // No class loader constraint check performed for boot classes.
1016     return true;
1017   }
1018   if (klass->is_shared_platform_class() || klass->is_shared_app_class()) {
1019     RunTimeClassInfo* info = RunTimeClassInfo::get_for(klass);
1020     assert(info != nullptr, "Sanity");
1021     if (info->_num_loader_constraints > 0) {
1022       HandleMark hm(current);
1023       for (int i = 0; i < info->_num_loader_constraints; i++) {
1024         RunTimeClassInfo::RTLoaderConstraint* lc = info->loader_constraint_at(i);
1025         Symbol* name = lc->constraint_name();
1026         Handle loader1(current, get_class_loader_by(lc->_loader_type1));
1027         Handle loader2(current, get_class_loader_by(lc->_loader_type2));
1028         if (log.is_enabled()) {
1029           ResourceMark rm(current);
1030           log.print("[CDS add loader constraint for class %s symbol %s loader[0] %s loader[1] %s",
1031                     klass->external_name(), name->as_C_string(),
1032                     ClassLoaderData::class_loader_data(loader1())->loader_name_and_id(),

1121     }
1122   }
1123 
1124   size_t total() {
1125     return _shared_class_info_size;
1126   }
1127 };
1128 
1129 size_t SystemDictionaryShared::estimate_size_for_archive() {
1130   EstimateSizeForArchive est;
1131   _dumptime_table->iterate_all_live_classes(&est);
1132   size_t total_size = est.total() +
1133     CompactHashtableWriter::estimate_size(_dumptime_table->count_of(true)) +
1134     CompactHashtableWriter::estimate_size(_dumptime_table->count_of(false));
1135 
1136   size_t bytesize = align_up(sizeof(RunTimeLambdaProxyClassInfo), SharedSpaceObjectAlignment);
1137   total_size +=
1138       (bytesize * _dumptime_lambda_proxy_class_dictionary->_count) +
1139       CompactHashtableWriter::estimate_size(_dumptime_lambda_proxy_class_dictionary->_count);
1140 





1141   return total_size;
1142 }
1143 
1144 unsigned int SystemDictionaryShared::hash_for_shared_dictionary(address ptr) {
1145   if (ArchiveBuilder::is_active()) {
1146     uintx offset = ArchiveBuilder::current()->any_to_offset(ptr);
1147     unsigned int hash = primitive_hash<uintx>(offset);
1148     DEBUG_ONLY({
1149         if (MetaspaceObj::is_shared((const MetaspaceObj*)ptr)) {
1150           assert(hash == SystemDictionaryShared::hash_for_shared_dictionary_quick(ptr), "must be");
1151         }
1152       });
1153     return hash;
1154   } else {
1155     return SystemDictionaryShared::hash_for_shared_dictionary_quick(ptr);
1156   }
1157 }
1158 
1159 class CopyLambdaProxyClassInfoToArchive : StackObj {
1160   CompactHashtableWriter* _writer;
1161   ArchiveBuilder* _builder;
1162 public:
1163   CopyLambdaProxyClassInfoToArchive(CompactHashtableWriter* writer)
1164   : _writer(writer), _builder(ArchiveBuilder::current()) {}
1165   bool do_entry(LambdaProxyClassKey& key, DumpTimeLambdaProxyClassInfo& info) {
1166     // In static dump, info._proxy_klasses->at(0) is already relocated to point to the archived class
1167     // (not the original class).
1168     //
1169     // The following check has been moved to SystemDictionaryShared::check_excluded_classes(), which
1170     // happens before the classes are copied.
1171     //
1172     // if (SystemDictionaryShared::is_excluded_class(info._proxy_klasses->at(0))) {
1173     //  return true;
1174     //}
1175     ResourceMark rm;
1176     log_info(cds,dynamic)("Archiving hidden %s", info._proxy_klasses->at(0)->external_name());
1177     size_t byte_size = sizeof(RunTimeLambdaProxyClassInfo);
1178     RunTimeLambdaProxyClassInfo* runtime_info =
1179         (RunTimeLambdaProxyClassInfo*)ArchiveBuilder::ro_region_alloc(byte_size);
1180     runtime_info->init(key, info);
1181     unsigned int hash = runtime_info->hash();
1182     u4 delta = _builder->any_to_offset_u4((void*)runtime_info);
1183     _writer->add(hash, delta);
1184     return true;
1185   }
1186 };
1187 
1188 class AdjustLambdaProxyClassInfo : StackObj {
1189 public:

1238         ResourceMark rm;
1239         log_trace(cds,hashtables)("%s dictionary: %s", (_is_builtin ? "builtin" : "unregistered"), info._klass->external_name());
1240       }
1241 
1242       // Save this for quick runtime lookup of InstanceKlass* -> RunTimeClassInfo*
1243       InstanceKlass* buffered_klass = ArchiveBuilder::current()->get_buffered_addr(info._klass);
1244       RunTimeClassInfo::set_for(buffered_klass, record);
1245     }
1246   }
1247 };
1248 
1249 void SystemDictionaryShared::write_lambda_proxy_class_dictionary(LambdaProxyClassDictionary *dictionary) {
1250   CompactHashtableStats stats;
1251   dictionary->reset();
1252   CompactHashtableWriter writer(_dumptime_lambda_proxy_class_dictionary->_count, &stats);
1253   CopyLambdaProxyClassInfoToArchive copy(&writer);
1254   _dumptime_lambda_proxy_class_dictionary->iterate(&copy);
1255   writer.dump(dictionary, "lambda proxy class dictionary");
1256 }
1257 


































1258 void SystemDictionaryShared::write_dictionary(RunTimeSharedDictionary* dictionary,
1259                                               bool is_builtin) {
1260   CompactHashtableStats stats;
1261   dictionary->reset();
1262   CompactHashtableWriter writer(_dumptime_table->count_of(is_builtin), &stats);
1263   CopySharedClassInfoToArchive copy(&writer, is_builtin);
1264   assert_lock_strong(DumpTimeTable_lock);
1265   _dumptime_table->iterate_all_live_classes(&copy);
1266   writer.dump(dictionary, is_builtin ? "builtin dictionary" : "unregistered dictionary");
1267 }
1268 
1269 void SystemDictionaryShared::write_to_archive(bool is_static_archive) {
1270   ArchiveInfo* archive = get_archive(is_static_archive);
1271 
1272   write_dictionary(&archive->_builtin_dictionary, true);
1273   write_dictionary(&archive->_unregistered_dictionary, false);
1274 
1275   write_lambda_proxy_class_dictionary(&archive->_lambda_proxy_class_dictionary);


1276 }
1277 
1278 void SystemDictionaryShared::adjust_lambda_proxy_class_dictionary() {
1279   AdjustLambdaProxyClassInfo adjuster;
1280   _dumptime_lambda_proxy_class_dictionary->iterate(&adjuster);
1281 }
1282 






























1283 void SystemDictionaryShared::serialize_dictionary_headers(SerializeClosure* soc,
1284                                                           bool is_static_archive) {
1285   ArchiveInfo* archive = get_archive(is_static_archive);
1286 
1287   archive->_builtin_dictionary.serialize_header(soc);
1288   archive->_unregistered_dictionary.serialize_header(soc);
1289   archive->_lambda_proxy_class_dictionary.serialize_header(soc);

1290 }
1291 
1292 void SystemDictionaryShared::serialize_vm_classes(SerializeClosure* soc) {
1293   for (auto id : EnumRange<vmClassID>{}) {
1294     soc->do_ptr(vmClasses::klass_addr_at(id));
1295   }





1296 }
1297 
1298 const RunTimeClassInfo*
1299 SystemDictionaryShared::find_record(RunTimeSharedDictionary* static_dict, RunTimeSharedDictionary* dynamic_dict, Symbol* name) {
1300   if (!CDSConfig::is_using_archive() || !name->is_shared()) {
1301     // The names of all shared classes must also be a shared Symbol.
1302     return nullptr;
1303   }
1304 
1305   unsigned int hash = SystemDictionaryShared::hash_for_shared_dictionary_quick(name);
1306   const RunTimeClassInfo* record = nullptr;
1307   if (DynamicArchive::is_mapped()) {
1308     // Use the regenerated holder classes in the dynamic archive as they
1309     // have more methods than those in the base archive.
1310     if (name == vmSymbols::java_lang_invoke_Invokers_Holder() ||
1311         name == vmSymbols::java_lang_invoke_DirectMethodHandle_Holder() ||
1312         name == vmSymbols::java_lang_invoke_LambdaForm_Holder() ||
1313         name == vmSymbols::java_lang_invoke_DelegatingMethodHandle_Holder()) {
1314       record = dynamic_dict->lookup(name, hash, 0);
1315       if (record != nullptr) {
1316         return record;
1317       }
1318     }
1319   }
1320 
1321   if (!MetaspaceShared::is_shared_dynamic(name)) {
1322     // The names of all shared classes in the static dict must also be in the
1323     // static archive
1324     record = static_dict->lookup(name, hash, 0);
1325   }
1326 
1327   if (record == nullptr && DynamicArchive::is_mapped()) {
1328     record = dynamic_dict->lookup(name, hash, 0);
1329   }
1330 
1331   return record;
1332 }
1333 

1338   if (record != nullptr) {
1339     assert(!record->_klass->is_hidden(), "hidden class cannot be looked up by name");
1340     assert(check_alignment(record->_klass), "Address not aligned");
1341     // We did not save the classfile data of the generated LambdaForm invoker classes,
1342     // so we cannot support CLFH for such classes.
1343     if (record->_klass->is_generated_shared_class() && JvmtiExport::should_post_class_file_load_hook()) {
1344        return nullptr;
1345     }
1346     return record->_klass;
1347   } else {
1348     return nullptr;
1349   }
1350 }
1351 
1352 void SystemDictionaryShared::update_shared_entry(InstanceKlass* k, int id) {
1353   assert(CDSConfig::is_dumping_static_archive(), "class ID is used only for static dump (from classlist)");
1354   DumpTimeClassInfo* info = get_info(k);
1355   info->_id = id;
1356 }
1357 
1358 static const char* class_loader_name_for_shared(Klass* k) {
1359   assert(k != nullptr, "Sanity");
1360   assert(k->is_shared(), "Must be");
1361   assert(k->is_instance_klass(), "Must be");
1362   InstanceKlass* ik = InstanceKlass::cast(k);
1363   if (ik->is_shared_boot_class()) {
1364     return "boot_loader";
1365   } else if (ik->is_shared_platform_class()) {
1366     return "platform_loader";
1367   } else if (ik->is_shared_app_class()) {
1368     return "app_loader";
1369   } else if (ik->is_shared_unregistered_class()) {
1370     return "unregistered_loader";
1371   } else {
1372     return "unknown loader";
1373   }
1374 }
1375 
1376 class SharedDictionaryPrinter : StackObj {
1377   outputStream* _st;
1378   int _index;
1379 public:
1380   SharedDictionaryPrinter(outputStream* st) : _st(st), _index(0) {}
1381 
1382   void do_value(const RunTimeClassInfo* record) {
1383     ResourceMark rm;
1384     _st->print_cr("%4d: %s %s", _index++, record->_klass->external_name(),
1385         class_loader_name_for_shared(record->_klass));
1386     if (record->_klass->array_klasses() != nullptr) {
1387       record->_klass->array_klasses()->cds_print_value_on(_st);
1388       _st->cr();
1389     }
1390   }
1391   int index() const { return _index; }
1392 };
1393 
1394 class SharedLambdaDictionaryPrinter : StackObj {
1395   outputStream* _st;
1396   int _index;
1397 public:
1398   SharedLambdaDictionaryPrinter(outputStream* st, int idx) : _st(st), _index(idx) {}
1399 
1400   void do_value(const RunTimeLambdaProxyClassInfo* record) {
1401     if (record->proxy_klass_head()->lambda_proxy_is_available()) {
1402       ResourceMark rm;
1403       Klass* k = record->proxy_klass_head();
1404       while (k != nullptr) {
1405         _st->print_cr("%4d: %s %s", _index++, k->external_name(),
1406                       class_loader_name_for_shared(k));
1407         k = k->next_link();
1408       }
1409     }
1410   }
1411 };
1412 










































1413 void SystemDictionaryShared::ArchiveInfo::print_on(const char* prefix,
1414                                                    outputStream* st) {
1415   st->print_cr("%sShared Dictionary", prefix);
1416   SharedDictionaryPrinter p(st);
1417   st->print_cr("%sShared Builtin Dictionary", prefix);
1418   _builtin_dictionary.iterate(&p);
1419   st->print_cr("%sShared Unregistered Dictionary", prefix);
1420   _unregistered_dictionary.iterate(&p);
1421   if (!_lambda_proxy_class_dictionary.empty()) {
1422     st->print_cr("%sShared Lambda Dictionary", prefix);
1423     SharedLambdaDictionaryPrinter ldp(st, p.index());
1424     _lambda_proxy_class_dictionary.iterate(&ldp);
1425   }





1426 }
1427 
1428 void SystemDictionaryShared::ArchiveInfo::print_table_statistics(const char* prefix,
1429                                                                  outputStream* st) {
1430   st->print_cr("%sArchve Statistics", prefix);
1431   _builtin_dictionary.print_table_statistics(st, "Builtin Shared Dictionary");
1432   _unregistered_dictionary.print_table_statistics(st, "Unregistered Shared Dictionary");
1433   _lambda_proxy_class_dictionary.print_table_statistics(st, "Lambda Shared Dictionary");

1434 }
1435 
1436 void SystemDictionaryShared::print_shared_archive(outputStream* st, bool is_static) {
1437   if (CDSConfig::is_using_archive()) {
1438     if (is_static) {
1439       _static_archive.print_on("", st);
1440     } else {
1441       if (DynamicArchive::is_mapped()) {
1442         _dynamic_archive.print_on("Dynamic ", st);
1443       }
1444     }
1445   }
1446 }
1447 
1448 void SystemDictionaryShared::print_on(outputStream* st) {
1449   print_shared_archive(st, true);
1450   print_shared_archive(st, false);
1451 }
1452 
1453 void SystemDictionaryShared::print_table_statistics(outputStream* st) {

1479     // must also be excluded.
1480     bool always_exclude = SystemDictionaryShared::check_for_exclusion(caller_ik, nullptr) ||
1481                           SystemDictionaryShared::check_for_exclusion(nest_host, nullptr);
1482 
1483     for (int i = info._proxy_klasses->length() - 1; i >= 0; i--) {
1484       InstanceKlass* ik = info._proxy_klasses->at(i);
1485       if (always_exclude || SystemDictionaryShared::check_for_exclusion(ik, nullptr)) {
1486         SystemDictionaryShared::reset_registered_lambda_proxy_class(ik);
1487         info._proxy_klasses->remove_at(i);
1488       }
1489     }
1490     return info._proxy_klasses->length() == 0 ? true /* delete the node*/ : false;
1491   }
1492 };
1493 
1494 void SystemDictionaryShared::cleanup_lambda_proxy_class_dictionary() {
1495   assert_lock_strong(DumpTimeTable_lock);
1496   CleanupDumpTimeLambdaProxyClassTable cleanup_proxy_classes;
1497   _dumptime_lambda_proxy_class_dictionary->unlink(&cleanup_proxy_classes);
1498 }









































































  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "precompiled.hpp"
  26 #include "cds/archiveBuilder.hpp"
  27 #include "cds/archiveHeapLoader.hpp"
  28 #include "cds/archiveUtils.hpp"
  29 #include "cds/cdsConfig.hpp"
  30 #include "cds/classListParser.hpp"
  31 #include "cds/classListWriter.hpp"
  32 #include "cds/dynamicArchive.hpp"
  33 #include "cds/filemap.hpp"
  34 #include "cds/heapShared.hpp"
  35 #include "cds/cdsProtectionDomain.hpp"
  36 #include "cds/dumpTimeClassInfo.inline.hpp"
  37 #include "cds/lambdaFormInvokers.inline.hpp"
  38 #include "cds/metaspaceShared.hpp"
  39 #include "cds/methodDataDictionary.hpp"
  40 #include "cds/runTimeClassInfo.hpp"
  41 #include "classfile/classFileStream.hpp"
  42 #include "classfile/classLoader.hpp"
  43 #include "classfile/classLoaderData.inline.hpp"
  44 #include "classfile/classLoaderDataGraph.hpp"
  45 #include "classfile/classLoaderExt.hpp"
  46 #include "classfile/dictionary.hpp"
  47 #include "classfile/javaClasses.hpp"
  48 #include "classfile/javaClasses.inline.hpp"
  49 #include "classfile/symbolTable.hpp"
  50 #include "classfile/systemDictionary.hpp"
  51 #include "classfile/systemDictionaryShared.hpp"
  52 #include "classfile/verificationType.hpp"
  53 #include "classfile/vmClasses.hpp"
  54 #include "classfile/vmSymbols.hpp"
  55 #include "interpreter/bootstrapInfo.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/instanceKlass.hpp"
  66 #include "oops/klass.inline.hpp"
  67 #include "oops/methodData.hpp"
  68 #include "oops/trainingData.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/resourceHash.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 DumpTimeLambdaProxyClassDictionary* SystemDictionaryShared::_dumptime_lambda_proxy_class_dictionary = nullptr;
  87 
  88 DumpTimeMethodInfoDictionary* SystemDictionaryShared::_dumptime_method_info_dictionary = nullptr;
  89 DumpTimeMethodInfoDictionary* SystemDictionaryShared::_cloned_dumptime_method_info_dictionary = nullptr;
  90 static Array<InstanceKlass*>* _archived_lambda_form_classes = nullptr;
  91 static Array<InstanceKlass*>* _archived_lambda_proxy_classes_boot = nullptr;
  92 static Array<InstanceKlass*>* _archived_lambda_proxy_classes_boot2 = nullptr;
  93 static Array<InstanceKlass*>* _archived_lambda_proxy_classes_platform = nullptr;
  94 static Array<InstanceKlass*>* _archived_lambda_proxy_classes_app = nullptr;
  95 static bool _ignore_new_classes = false;
  96 
  97 // Used by NoClassLoadingMark
  98 DEBUG_ONLY(bool SystemDictionaryShared::_class_loading_may_happen = true;)
  99 
 100 InstanceKlass* SystemDictionaryShared::load_shared_class_for_builtin_loader(
 101                  Symbol* class_name, Handle class_loader, TRAPS) {
 102   assert(CDSConfig::is_using_archive(), "must be");
 103   InstanceKlass* ik = find_builtin_class(class_name);
 104 
 105   if (ik != nullptr && !ik->shared_loading_failed()) {
 106     if ((SystemDictionary::is_system_class_loader(class_loader()) && ik->is_shared_app_class())  ||
 107         (SystemDictionary::is_platform_class_loader(class_loader()) && ik->is_shared_platform_class())) {
 108       SharedClassLoadingMark slm(THREAD, ik);
 109       PackageEntry* pkg_entry = CDSProtectionDomain::get_package_entry_from_class(ik, class_loader);
 110       Handle protection_domain;
 111       if (!class_name->starts_with("jdk/proxy")) // java/lang/reflect/Proxy$ProxyBuilder defines the proxy classes with a null protection domain.
 112       {
 113         protection_domain = CDSProtectionDomain::init_security_info(class_loader, ik, pkg_entry, CHECK_NULL);
 114       }
 115       return load_shared_class(ik, class_loader, protection_domain, nullptr, pkg_entry, THREAD);
 116     }
 117   }
 118   return nullptr;
 119 }
 120 
 121 // This function is called for loading only UNREGISTERED classes
 122 InstanceKlass* SystemDictionaryShared::lookup_from_stream(Symbol* class_name,
 123                                                           Handle class_loader,
 124                                                           Handle protection_domain,
 125                                                           const ClassFileStream* cfs,
 126                                                           TRAPS) {
 127   if (!CDSConfig::is_using_archive()) {
 128     return nullptr;
 129   }
 130   if (class_name == nullptr) {  // don't do this for hidden classes
 131     return nullptr;
 132   }
 133   if (class_loader.is_null() ||
 134       SystemDictionary::is_system_class_loader(class_loader()) ||

 181   loader_data->add_class(ik);
 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 //assert(!k->is_shared(), "sanity"); // FIXME new workflow
 202   return get_info_locked(k);
 203 }
 204 
 205 DumpTimeClassInfo* SystemDictionaryShared::get_info_locked(InstanceKlass* k) {
 206   assert_lock_strong(DumpTimeTable_lock);
 207 //assert(!k->is_shared(), "sanity"); // FIXME new workflow
 208   DumpTimeClassInfo* info = _dumptime_table->get_info(k);
 209   assert(info != nullptr, "must be");
 210   return info;
 211 }
 212 
 213 void SystemDictionaryShared::mark_required_class(InstanceKlass* k) {
 214   DumpTimeClassInfo* info = _dumptime_table->get(k);
 215   ResourceMark rm;
 216   if (info != nullptr) {
 217     info->set_is_required();
 218   }
 219 }
 220 
 221 bool SystemDictionaryShared::check_for_exclusion(InstanceKlass* k, DumpTimeClassInfo* info) {
 222   if (!CDSConfig::is_dumping_final_static_archive() && MetaspaceShared::is_in_shared_metaspace(k)) {
 223     // We have reached a super type that's already in the base archive. Treat it
 224     // as "not excluded".
 225     assert(CDSConfig::is_dumping_dynamic_archive(), "must be");
 226     return false;
 227   }
 228 
 229   if (info == nullptr) {
 230     info = _dumptime_table->get(k);
 231     assert(info != nullptr, "supertypes of any classes in _dumptime_table must either be shared, or must also be in _dumptime_table");
 232   }
 233 
 234   if (!info->has_checked_exclusion()) {
 235     if (check_for_exclusion_impl(k)) {
 236       info->set_excluded();
 237     }
 238     info->set_has_checked_exclusion();
 239   }
 240 
 241   return info->is_excluded();
 242 }

 268   if (info != nullptr) {
 269     info->_is_archived_lambda_proxy = false;
 270     info->set_excluded();
 271   }
 272 }
 273 
 274 bool SystemDictionaryShared::is_early_klass(InstanceKlass* ik) {
 275   DumpTimeClassInfo* info = _dumptime_table->get(ik);
 276   return (info != nullptr) ? info->is_early_klass() : false;
 277 }
 278 
 279 bool SystemDictionaryShared::is_hidden_lambda_proxy(InstanceKlass* ik) {
 280   assert(ik->is_shared(), "applicable to only a shared class");
 281   if (ik->is_hidden()) {
 282     return true;
 283   } else {
 284     return false;
 285   }
 286 }
 287 
 288 void SystemDictionaryShared::ignore_new_classes() {
 289   _ignore_new_classes = true;
 290 }
 291 
 292 
 293 bool SystemDictionaryShared::check_for_exclusion_impl(InstanceKlass* k) {
 294   if (CDSConfig::is_dumping_final_static_archive() && k->is_shared_unregistered_class()
 295       && k->is_shared()) {
 296     return false; // Do not exclude: unregistered classes are passed from preimage to final image.
 297   }
 298 
 299   if (k->is_in_error_state()) {
 300     return warn_excluded(k, "In error state");
 301   }
 302   if (k->is_scratch_class()) {
 303     return warn_excluded(k, "A scratch class");
 304   }
 305   if (!k->is_loaded()) {
 306     return warn_excluded(k, "Not in loaded state");
 307   }
 308   if (has_been_redefined(k)) {
 309     return warn_excluded(k, "Has been redefined");
 310   }
 311   if (!k->is_hidden() && k->shared_classpath_index() < 0 && is_builtin(k)) {
 312     if (k->name()->starts_with("java/lang/invoke/BoundMethodHandle$Species_")) {
 313       // This class is dynamically generated by the JDK
 314       if (CDSConfig::is_dumping_aot_linked_classes()) {
 315         k->set_shared_classpath_index(0);
 316       } else {
 317         ResourceMark rm;
 318         log_info(cds)("Skipping %s because it is dynamically generated", k->name()->as_C_string());
 319         return true; // exclude without warning
 320       }
 321     } else {
 322       // These are classes loaded from unsupported locations (such as those loaded by JVMTI native
 323       // agent during dump time).
 324       return warn_excluded(k, "Unsupported location");
 325     }
 326   }
 327   if (k->signers() != nullptr) {
 328     // We cannot include signed classes in the archive because the certificates
 329     // used during dump time may be different than those used during
 330     // runtime (due to expiration, etc).
 331     return warn_excluded(k, "Signed JAR");
 332   }
 333   if (is_jfr_event_class(k)) {
 334     // We cannot include JFR event classes because they need runtime-specific
 335     // instrumentation in order to work with -XX:FlightRecorderOptions:retransform=false.
 336     // There are only a small number of these classes, so it's not worthwhile to
 337     // support them and make CDS more complicated.
 338     if (!CDSConfig::is_dumping_reflection_data()) { // FIXME: !!! HACK !!!
 339       return warn_excluded(k, "JFR event class");
 340     }
 341   }
 342 
 343   if (!CDSConfig::preserve_all_dumptime_verification_states(k)) {
 344     if (!k->is_linked()) {
 345       if (has_class_failed_verification(k)) {
 346         return warn_excluded(k, "Failed verification");
 347       }
 348     } else {
 349       if (!k->can_be_verified_at_dumptime()) {
 350         // We have an old class that has been linked (e.g., it's been executed during
 351         // dump time). This class has been verified using the old verifier, which
 352         // doesn't save the verification constraints, so check_verification_constraints()
 353         // won't work at runtime.
 354         // As a result, we cannot store this class. It must be loaded and fully verified
 355         // at runtime.
 356         return warn_excluded(k, "Old class has been linked");
 357       }
 358     }
 359   }
 360 
 361   if (k->is_hidden() && !should_hidden_class_be_archived(k)) {
 362     log_info(cds)("Skipping %s: Hidden class", k->name()->as_C_string());

 363     return true;
 364   }
 365 
 366   InstanceKlass* super = k->java_super();
 367   if (super != nullptr && check_for_exclusion(super, nullptr)) {
 368     ResourceMark rm;
 369     log_warning(cds)("Skipping %s: super class %s is excluded", k->name()->as_C_string(), super->name()->as_C_string());
 370     return true;
 371   }
 372 
 373   Array<InstanceKlass*>* interfaces = k->local_interfaces();
 374   int len = interfaces->length();
 375   for (int i = 0; i < len; i++) {
 376     InstanceKlass* intf = interfaces->at(i);
 377     if (check_for_exclusion(intf, nullptr)) {
 378       ResourceMark rm;
 379       log_warning(cds)("Skipping %s: interface %s is excluded", k->name()->as_C_string(), intf->name()->as_C_string());
 380       return true;
 381     }
 382   }
 383 
 384   if (ClassLoaderExt::should_be_excluded(k)) {
 385     ResourceMark rm;
 386     log_info(cds)("Skipping %s: excluded via -XX:CacheOnlyClassesIn", k->name()->as_C_string());
 387     return true;
 388   }
 389 
 390   return false; // false == k should NOT be excluded
 391 }
 392 
 393 bool SystemDictionaryShared::is_builtin_loader(ClassLoaderData* loader_data) {
 394   oop class_loader = loader_data->class_loader();
 395   return (class_loader == nullptr ||
 396           SystemDictionary::is_system_class_loader(class_loader) ||
 397           SystemDictionary::is_platform_class_loader(class_loader));
 398 }
 399 
 400 bool SystemDictionaryShared::has_platform_or_app_classes() {
 401   if (FileMapInfo::current_info()->has_platform_or_app_classes()) {
 402     return true;
 403   }
 404   if (DynamicArchive::is_mapped() &&
 405       FileMapInfo::dynamic_info()->has_platform_or_app_classes()) {
 406     return true;
 407   }
 408   return false;
 409 }

 540     // The VM is not trying to resolve a super type of parser->current_class_name().
 541     // Instead, it's resolving an error class (because parser->current_class_name() has
 542     // failed parsing or verification). Don't do anything here.
 543     return nullptr;
 544   }
 545 }
 546 
 547 void SystemDictionaryShared::set_shared_class_misc_info(InstanceKlass* k, ClassFileStream* cfs) {
 548   assert(CDSConfig::is_dumping_archive(), "sanity");
 549   assert(!is_builtin(k), "must be unregistered class");
 550   DumpTimeClassInfo* info = get_info(k);
 551   info->_clsfile_size  = cfs->length();
 552   info->_clsfile_crc32 = ClassLoader::crc32(0, (const char*)cfs->buffer(), cfs->length());
 553 }
 554 
 555 void SystemDictionaryShared::initialize() {
 556   if (CDSConfig::is_dumping_archive()) {
 557     _dumptime_table = new (mtClass) DumpTimeSharedClassTable;
 558     _dumptime_lambda_proxy_class_dictionary =
 559                       new (mtClass) DumpTimeLambdaProxyClassDictionary;
 560     _dumptime_method_info_dictionary = new (mtClass) DumpTimeMethodInfoDictionary;
 561   }
 562 }
 563 
 564 void SystemDictionaryShared::init_dumptime_info(InstanceKlass* k) {
 565   MutexLocker ml(DumpTimeTable_lock, Mutex::_no_safepoint_check_flag);
 566   assert(SystemDictionaryShared::class_loading_may_happen(), "sanity");
 567   DumpTimeClassInfo* info = _dumptime_table->allocate_info(k);
 568   if (_ignore_new_classes) {
 569     if (!LambdaFormInvokers::may_be_regenerated_class(k->name())) {
 570       ResourceMark rm;
 571       log_debug(cds)("Skipping %s: Class loaded for lambda form invoker regeneration", k->name()->as_C_string());
 572       info->set_excluded();
 573     }
 574   }
 575 }
 576 
 577 void SystemDictionaryShared::remove_dumptime_info(InstanceKlass* k) {
 578   MutexLocker ml(DumpTimeTable_lock, Mutex::_no_safepoint_check_flag);
 579   _dumptime_table->remove(k);
 580 }
 581 
 582 void SystemDictionaryShared::handle_class_unloading(InstanceKlass* klass) {
 583   if (CDSConfig::is_dumping_archive()) {
 584     remove_dumptime_info(klass);
 585   }
 586 
 587   if (CDSConfig::is_dumping_archive() || ClassListWriter::is_enabled()) {
 588     MutexLocker ml(Thread::current(), UnregisteredClassesTable_lock, Mutex::_no_safepoint_check_flag);
 589     if (_unregistered_classes_table != nullptr) {
 590       // Remove the class from _unregistered_classes_table: keep the entry but
 591       // set it to null. This ensure no classes with the same name can be
 592       // added again.
 593       InstanceKlass** v = _unregistered_classes_table->get(klass->name());
 594       if (v != nullptr) {

 616   Array<InstanceKlass*>* interfaces = k->local_interfaces();
 617   int len = interfaces->length();
 618   for (int i = 0; i < len; i++) {
 619     if (has_been_redefined(interfaces->at(i))) {
 620       return true;
 621     }
 622   }
 623   return false;
 624 }
 625 
 626 // k is a class before relocating by ArchiveBuilder
 627 void SystemDictionaryShared::validate_before_archiving(InstanceKlass* k) {
 628   ResourceMark rm;
 629   const char* name = k->name()->as_C_string();
 630   DumpTimeClassInfo* info = _dumptime_table->get(k);
 631   assert(!class_loading_may_happen(), "class loading must be disabled");
 632   guarantee(info != nullptr, "Class %s must be entered into _dumptime_table", name);
 633   guarantee(!info->is_excluded(), "Should not attempt to archive excluded class %s", name);
 634   if (is_builtin(k)) {
 635     if (k->is_hidden()) {
 636       if (CDSConfig::is_dumping_invokedynamic()) { // FIXME -- clean up
 637         return;
 638       }
 639       assert(should_hidden_class_be_archived(k), "unexpected hidden class %s", name);
 640     }
 641     guarantee(!k->is_shared_unregistered_class(),
 642               "Class loader type must be set for BUILTIN class %s", name);
 643 
 644   } else {
 645     guarantee(k->is_shared_unregistered_class(),
 646               "Class loader type must not be set for UNREGISTERED class %s", name);
 647   }
 648 }
 649 
 650 class UnregisteredClassesDuplicationChecker : StackObj {
 651   GrowableArray<InstanceKlass*> _list;
 652   Thread* _thread;
 653 public:
 654   UnregisteredClassesDuplicationChecker() : _thread(Thread::current()) {}
 655 
 656   void do_entry(InstanceKlass* k, DumpTimeClassInfo& info) {
 657     if (!SystemDictionaryShared::is_builtin(k)) {
 658       _list.append(k);
 659     }

 671   }
 672 
 673   void mark_duplicated_classes() {
 674     // Two loaders may load two identical or similar hierarchies of classes. If we
 675     // check for duplication in random order, we may end up excluding important base classes
 676     // in both hierarchies, causing most of the classes to be excluded.
 677     // We sort the classes by their loaders. This way we're likely to archive
 678     // all classes in the one of the two hierarchies.
 679     _list.sort(compare_by_loader);
 680     for (int i = 0; i < _list.length(); i++) {
 681       InstanceKlass* k = _list.at(i);
 682       bool i_am_first = SystemDictionaryShared::add_unregistered_class(_thread, k);
 683       if (!i_am_first) {
 684         SystemDictionaryShared::warn_excluded(k, "Duplicated unregistered class");
 685         SystemDictionaryShared::set_excluded_locked(k);
 686       }
 687     }
 688   }
 689 };
 690 
 691 void SystemDictionaryShared::scan_constant_pool(InstanceKlass* k) {
 692   k->constants()->find_archivable_hidden_classes();
 693 }
 694 
 695 bool SystemDictionaryShared::should_hidden_class_be_archived(InstanceKlass* k) {
 696   assert(k->is_hidden(), "sanity");
 697   if (is_registered_lambda_proxy_class(k)) {
 698     return true;
 699   }
 700 
 701   if (CDSConfig::is_dumping_invokedynamic()) {
 702     if (HeapShared::is_archivable_hidden_klass(k)) {
 703       return true;
 704     }
 705 
 706     // TODO: merge the following with HeapShared::is_archivable_hidden_klass()
 707     DumpTimeClassInfo* info = _dumptime_table->get(k);
 708     if (info != nullptr && info->is_required()) {
 709       return true;
 710     }
 711   }
 712 
 713   return false;
 714 }
 715 
 716 // Returns true if the class should be excluded. This can be called before
 717 // SystemDictionaryShared::find_all_archivable_classes().
 718 bool SystemDictionaryShared::check_for_exclusion(Klass* k) {
 719   assert(CDSConfig::is_dumping_archive(), "sanity");
 720 
 721   if (k->is_objArray_klass()) {
 722     return check_for_exclusion(ObjArrayKlass::cast(k)->bottom_klass());
 723   }
 724 
 725   if (!k->is_instance_klass()) {
 726     return false;
 727   } else {
 728     InstanceKlass* ik = InstanceKlass::cast(k);
 729 
 730     if (SafepointSynchronize::is_at_safepoint()) {
 731       return is_excluded_class(ik);
 732     }
 733 
 734     if (!ik->is_linked()) {
 735       JavaThread* THREAD = JavaThread::current();
 736       ik->link_class(THREAD);
 737       if (HAS_PENDING_EXCEPTION) {
 738         CLEAR_PENDING_EXCEPTION;
 739         return true;
 740       }
 741     }
 742 
 743     MutexLocker ml(DumpTimeTable_lock, Mutex::_no_safepoint_check_flag);
 744     DumpTimeClassInfo* p = get_info_locked(ik);
 745     if (p->is_excluded()) {
 746       return true;
 747     }
 748     return check_for_exclusion(ik, p);
 749   }
 750 }
 751 
 752 void SystemDictionaryShared::find_all_archivable_classes() {
 753   HeapShared::start_finding_archivable_hidden_classes();
 754   find_all_archivable_classes_impl();
 755   HeapShared::end_finding_archivable_hidden_classes();
 756 }
 757 
 758 // Iterate over all the classes in _dumptime_table, marking the ones that must be
 759 // excluded from the archive. Those that are not excluded will be archivable.
 760 //
 761 // (a) Non-hidden classes are easy. They are only check by the rules in 
 762 //     SystemDictionaryShared::check_for_exclusion().
 763 // (b) For hidden classes, we only archive those that are required (i.e., they are
 764 //     referenced by Java objects (such as CallSites) that are reachable from
 765 //     ConstantPools.
 766 void SystemDictionaryShared::find_all_archivable_classes_impl() {
 767   assert(!class_loading_may_happen(), "class loading must be disabled");
 768   assert_lock_strong(DumpTimeTable_lock);
 769 
 770   if (CDSConfig::is_dumping_dynamic_archive()) {
 771     // Do this first -- if a base class is excluded due to duplication,
 772     // all of its subclasses will also be excluded.
 773     ResourceMark rm;
 774     UnregisteredClassesDuplicationChecker dup_checker;
 775     _dumptime_table->iterate_all_live_classes(&dup_checker);
 776     dup_checker.mark_duplicated_classes();
 777   }
 778 
 779   ResourceMark rm;
 780 
 781   // First, scan all non-hidden classes
 782   auto check_non_hidden = [&] (InstanceKlass* k, DumpTimeClassInfo& info) {
 783     if (!k->is_hidden()) {
 784       SystemDictionaryShared::check_for_exclusion(k, &info);
 785       if (!info.is_excluded() && !info.has_scanned_constant_pool()) {
 786         scan_constant_pool(k);
 787         info.set_has_scanned_constant_pool();
 788       }
 789     }
 790   };
 791   _dumptime_table->iterate_all_live_classes(check_non_hidden);
 792 
 793   // Then, scan all the hidden classes that have been marked as required to
 794   // discover more hidden classes. Stop when we cannot make progress anymore.
 795   bool made_progress;
 796   do {
 797     made_progress = false;
 798     auto check_hidden = [&] (InstanceKlass* k, DumpTimeClassInfo& info) {
 799       if (k->is_hidden() && should_hidden_class_be_archived(k)) {
 800         SystemDictionaryShared::check_for_exclusion(k, &info);
 801         if (info.is_excluded()) {
 802           guarantee(!info.is_required(), "A required hidden class cannot be marked as excluded");
 803         } else if (!info.has_scanned_constant_pool()) {
 804           scan_constant_pool(k);
 805           info.set_has_scanned_constant_pool();
 806           // The CP entries in k *MAY* refer to other hidden classes, so scan
 807           // every hidden class again.
 808           made_progress = true;
 809         }
 810       }
 811     };
 812     _dumptime_table->iterate_all_live_classes(check_hidden);
 813   } while (made_progress);
 814 
 815   // Now, all hidden classes that have not yet been scanned must be marked as excluded
 816   auto exclude_remaining_hidden = [&] (InstanceKlass* k, DumpTimeClassInfo& info) {
 817     if (k->is_hidden() && !info.has_checked_exclusion()) {
 818       SystemDictionaryShared::check_for_exclusion(k, &info);
 819       guarantee(info.is_excluded(), "Must be");
 820     }
 821   };
 822   _dumptime_table->iterate_all_live_classes(exclude_remaining_hidden);
 823   _dumptime_table->update_counts();
 824 
 825   cleanup_lambda_proxy_class_dictionary();
 826 
 827   cleanup_method_info_dictionary();
 828 
 829   TrainingData::cleanup_training_data();
 830 }
 831 
 832 bool SystemDictionaryShared::is_excluded_class(InstanceKlass* k) {
 833   assert(!class_loading_may_happen(), "class loading must be disabled");
 834   assert_lock_strong(DumpTimeTable_lock);
 835   assert(CDSConfig::is_dumping_archive(), "sanity");
 836   DumpTimeClassInfo* p = get_info_locked(k);
 837   return p->is_excluded();
 838 }
 839 
 840 void SystemDictionaryShared::set_excluded_locked(InstanceKlass* k) {
 841   assert_lock_strong(DumpTimeTable_lock);
 842   assert(CDSConfig::is_dumping_archive(), "sanity");
 843   DumpTimeClassInfo* info = get_info_locked(k);
 844   info->set_excluded();
 845 }
 846 
 847 void SystemDictionaryShared::set_excluded(InstanceKlass* k) {
 848   assert(CDSConfig::is_dumping_archive(), "sanity");
 849   DumpTimeClassInfo* info = get_info(k);
 850   info->set_excluded();
 851 }
 852 
 853 void SystemDictionaryShared::set_class_has_failed_verification(InstanceKlass* ik) {
 854   assert(CDSConfig::is_dumping_archive(), "sanity");
 855   DumpTimeClassInfo* p = get_info(ik);
 856   p->set_failed_verification();
 857 }
 858 
 859 bool SystemDictionaryShared::has_class_failed_verification(InstanceKlass* ik) {
 860   assert(CDSConfig::is_dumping_archive(), "sanity");
 861   DumpTimeClassInfo* p = _dumptime_table->get(ik);
 862   return (p == nullptr) ? false : p->failed_verification();
 863 }
 864 
 865 void SystemDictionaryShared::dumptime_classes_do(class MetaspaceClosure* it) {
 866   assert_lock_strong(DumpTimeTable_lock);
 867 
 868   auto do_klass = [&] (InstanceKlass* k, DumpTimeClassInfo& info) {
 869     if (CDSConfig::is_dumping_final_static_archive() && !k->is_loaded()) {
 870       assert(k->is_shared_unregistered_class(), "must be");
 871       info.metaspace_pointers_do(it);
 872     } else if (k->is_loader_alive() && !info.is_excluded()) {
 873       info.metaspace_pointers_do(it);
 874     }
 875   };
 876   _dumptime_table->iterate_all_live_classes(do_klass);
 877 
 878   auto do_lambda = [&] (LambdaProxyClassKey& key, DumpTimeLambdaProxyClassInfo& info) {
 879     if (key.caller_ik()->is_loader_alive()) {
 880       info.metaspace_pointers_do(it);
 881       key.metaspace_pointers_do(it);
 882     }
 883   };
 884   _dumptime_lambda_proxy_class_dictionary->iterate_all(do_lambda);
 885 
 886   auto do_method_info = [&] (MethodDataKey& key, DumpTimeMethodDataInfo& info) {
 887     info.metaspace_pointers_do(it);
 888     key.metaspace_pointers_do(it);
 889   };
 890   _dumptime_method_info_dictionary->iterate_all(do_method_info);
 891 }
 892 
 893 bool SystemDictionaryShared::add_verification_constraint(InstanceKlass* k, Symbol* name,
 894          Symbol* from_name, bool from_field_is_protected, bool from_is_array, bool from_is_object) {
 895   assert(CDSConfig::is_dumping_archive(), "sanity");
 896   if (CDSConfig::is_dumping_dynamic_archive() && k->is_shared()) {
 897     // k is a new class in the static archive, but one of its supertypes is an old class, so k wasn't
 898     // verified during dump time. No need to record constraints as k won't be included in the dynamic archive.
 899     return false;
 900   }
 901   if (CDSConfig::is_dumping_aot_linked_classes() && is_builtin(k)) {
 902     // There's no need to save verification constraints
 903     // TODO -- double check the logic before integrating into mainline!!
 904     return false;
 905   }
 906 
 907   DumpTimeClassInfo* info = get_info(k);
 908   info->add_verification_constraint(k, name, from_name, from_field_is_protected,
 909                                     from_is_array, from_is_object);
 910 
 911   if (CDSConfig::is_dumping_dynamic_archive()) {
 912     // For dynamic dumping, we can resolve all the constraint classes for all class loaders during
 913     // the initial run prior to creating the archive before vm exit. We will also perform verification
 914     // check when running with the archive.
 915     return false;
 916   } else {
 917     if (is_builtin(k)) {
 918       // For builtin class loaders, we can try to complete the verification check at dump time,
 919       // because we can resolve all the constraint classes. We will also perform verification check
 920       // when running with the archive.
 921       return false;
 922     } else {
 923       // For non-builtin class loaders, we cannot complete the verification check at dump time,
 924       // because at dump time we don't know how to resolve classes for such loaders.
 925       return true;
 926     }

 936 void SystemDictionaryShared::add_to_dump_time_lambda_proxy_class_dictionary(LambdaProxyClassKey& key,
 937                                                            InstanceKlass* proxy_klass) {
 938   assert_lock_strong(DumpTimeTable_lock);
 939 
 940   bool created;
 941   DumpTimeLambdaProxyClassInfo* info = _dumptime_lambda_proxy_class_dictionary->put_if_absent(key, &created);
 942   info->add_proxy_klass(proxy_klass);
 943   if (created) {
 944     ++_dumptime_lambda_proxy_class_dictionary->_count;
 945   }
 946 }
 947 
 948 void SystemDictionaryShared::add_lambda_proxy_class(InstanceKlass* caller_ik,
 949                                                     InstanceKlass* lambda_ik,
 950                                                     Symbol* invoked_name,
 951                                                     Symbol* invoked_type,
 952                                                     Symbol* method_type,
 953                                                     Method* member_method,
 954                                                     Symbol* instantiated_method_type,
 955                                                     TRAPS) {
 956   if (CDSConfig::is_dumping_invokedynamic()) {
 957     // The lambda proxy classes will be stored as part of aot-resolved constant pool entries.
 958     // There's no need to remember them in a separate table.
 959     return;
 960   }
 961   if (CDSConfig::is_dumping_preimage_static_archive() || CDSConfig::is_dumping_final_static_archive()) {
 962     // TODO: not supported in new workflow
 963     return;
 964   }
 965 
 966   assert(caller_ik->class_loader() == lambda_ik->class_loader(), "mismatched class loader");
 967   assert(caller_ik->class_loader_data() == lambda_ik->class_loader_data(), "mismatched class loader data");
 968   assert(java_lang_Class::class_data(lambda_ik->java_mirror()) == nullptr, "must not have class data");
 969 
 970   MutexLocker ml(DumpTimeTable_lock, Mutex::_no_safepoint_check_flag);
 971 
 972   lambda_ik->assign_class_loader_type();
 973   lambda_ik->set_shared_classpath_index(caller_ik->shared_classpath_index());
 974   InstanceKlass* nest_host = caller_ik->nest_host(CHECK);
 975   assert(nest_host != nullptr, "unexpected nullptr nest_host");
 976 
 977   DumpTimeClassInfo* info = _dumptime_table->get(lambda_ik);
 978   if (info != nullptr && !lambda_ik->is_non_strong_hidden() && is_builtin(lambda_ik) && is_builtin(caller_ik)
 979       // Don't include the lambda proxy if its nest host is not in the "linked" state.
 980       && nest_host->is_linked()) {
 981     // Set _is_archived_lambda_proxy in DumpTimeClassInfo so that the lambda_ik
 982     // won't be excluded during dumping of shared archive. See ExcludeDumpTimeSharedClasses.
 983     info->_is_archived_lambda_proxy = true;
 984     info->set_nest_host(nest_host);
 985 
 986     LambdaProxyClassKey key(caller_ik,
 987                             invoked_name,
 988                             invoked_type,
 989                             method_type,
 990                             member_method,
 991                             instantiated_method_type);
 992     add_to_dump_time_lambda_proxy_class_dictionary(key, lambda_ik);
 993   }
 994 }
 995 
 996 InstanceKlass* SystemDictionaryShared::get_shared_lambda_proxy_class(InstanceKlass* caller_ik,
 997                                                                      Symbol* invoked_name,
 998                                                                      Symbol* invoked_type,
 999                                                                      Symbol* method_type,
1000                                                                      Method* member_method,
1001                                                                      Symbol* instantiated_method_type) {
1002   if (CDSConfig::is_dumping_final_static_archive()) {
1003     return nullptr;
1004   }
1005   MutexLocker ml(CDSLambda_lock, Mutex::_no_safepoint_check_flag);
1006   LambdaProxyClassKey key(caller_ik, invoked_name, invoked_type,
1007                           method_type, member_method, instantiated_method_type);
1008 
1009   // Try to retrieve the lambda proxy class from static archive.
1010   const RunTimeLambdaProxyClassInfo* info = _static_archive.lookup_lambda_proxy_class(&key);
1011   InstanceKlass* proxy_klass = retrieve_lambda_proxy_class(info);
1012   if (proxy_klass == nullptr) {
1013     if (info != nullptr && log_is_enabled(Debug, cds)) {
1014       ResourceMark rm;
1015       log_debug(cds)("Used all static archived lambda proxy classes for: %s %s%s",
1016                      caller_ik->external_name(), invoked_name->as_C_string(), invoked_type->as_C_string());
1017     }
1018   } else {
1019     return proxy_klass;
1020   }
1021 
1022   // Retrieving from static archive is unsuccessful, try dynamic archive.
1023   info = _dynamic_archive.lookup_lambda_proxy_class(&key);
1024   proxy_klass = retrieve_lambda_proxy_class(info);

1033 }
1034 
1035 InstanceKlass* SystemDictionaryShared::retrieve_lambda_proxy_class(const RunTimeLambdaProxyClassInfo* info) {
1036   InstanceKlass* proxy_klass = nullptr;
1037   if (info != nullptr) {
1038     InstanceKlass* curr_klass = info->proxy_klass_head();
1039     InstanceKlass* prev_klass = curr_klass;
1040     if (curr_klass->lambda_proxy_is_available()) {
1041       while (curr_klass->next_link() != nullptr) {
1042         prev_klass = curr_klass;
1043         curr_klass = InstanceKlass::cast(curr_klass->next_link());
1044       }
1045       assert(curr_klass->is_hidden(), "must be");
1046       assert(curr_klass->lambda_proxy_is_available(), "must be");
1047 
1048       prev_klass->set_next_link(nullptr);
1049       proxy_klass = curr_klass;
1050       proxy_klass->clear_lambda_proxy_is_available();
1051       if (log_is_enabled(Debug, cds)) {
1052         ResourceMark rm;
1053         log_debug(cds)("Loaded lambda proxy: " PTR_FORMAT " %s ", p2i(proxy_klass), proxy_klass->external_name());
1054       }
1055     }
1056   }
1057   return proxy_klass;
1058 }
1059 
1060 InstanceKlass* SystemDictionaryShared::get_shared_nest_host(InstanceKlass* lambda_ik) {
1061   assert(!CDSConfig::is_dumping_static_archive() && CDSConfig::is_using_archive(), "called at run time with CDS enabled only");
1062   RunTimeClassInfo* record = RunTimeClassInfo::get_for(lambda_ik);
1063   return record->nest_host();
1064 }
1065 
1066 InstanceKlass* SystemDictionaryShared::prepare_shared_lambda_proxy_class(InstanceKlass* lambda_ik,
1067                                                                          InstanceKlass* caller_ik, TRAPS) {
1068   Handle class_loader(THREAD, caller_ik->class_loader());
1069   Handle protection_domain;
1070   PackageEntry* pkg_entry = caller_ik->package();
1071   if (caller_ik->class_loader() != nullptr) {
1072     protection_domain = CDSProtectionDomain::init_security_info(class_loader, caller_ik, pkg_entry, CHECK_NULL);
1073   }

1092   // Add to class hierarchy, and do possible deoptimizations.
1093   loaded_lambda->add_to_hierarchy(THREAD);
1094   // But, do not add to dictionary.
1095 
1096   loaded_lambda->link_class(CHECK_NULL);
1097   // notify jvmti
1098   if (JvmtiExport::should_post_class_load()) {
1099     JvmtiExport::post_class_load(THREAD, loaded_lambda);
1100   }
1101   if (class_load_start_event.should_commit()) {
1102     SystemDictionary::post_class_load_event(&class_load_start_event, loaded_lambda, ClassLoaderData::class_loader_data(class_loader()));
1103   }
1104 
1105   loaded_lambda->initialize(CHECK_NULL);
1106 
1107   return loaded_lambda;
1108 }
1109 
1110 void SystemDictionaryShared::check_verification_constraints(InstanceKlass* klass,
1111                                                             TRAPS) {
1112   //assert(!CDSConfig::is_dumping_static_archive() && CDSConfig::is_using_archive(), "called at run time with CDS enabled only");
1113   RunTimeClassInfo* record = RunTimeClassInfo::get_for(klass);
1114 
1115   int length = record->_num_verifier_constraints;
1116   if (length > 0) {
1117     for (int i = 0; i < length; i++) {
1118       RunTimeClassInfo::RTVerifierConstraint* vc = record->verifier_constraint_at(i);
1119       Symbol* name      = vc->name();
1120       Symbol* from_name = vc->from_name();
1121       char c            = record->verifier_constraint_flag(i);
1122 
1123       if (log_is_enabled(Trace, cds, verification)) {
1124         ResourceMark rm(THREAD);
1125         log_trace(cds, 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(), c);
1128       }
1129 
1130       bool from_field_is_protected = (c & SystemDictionaryShared::FROM_FIELD_IS_PROTECTED) ? true : false;
1131       bool from_is_array           = (c & SystemDictionaryShared::FROM_IS_ARRAY)           ? true : false;
1132       bool from_is_object          = (c & SystemDictionaryShared::FROM_IS_OBJECT)          ? true : false;

1202   assert(is_builtin(klass), "must be");
1203   assert(klass_loader != nullptr, "should not be called for boot loader");
1204   assert(loader1 != loader2, "must be");
1205 
1206   if (CDSConfig::is_dumping_dynamic_archive() && Thread::current()->is_VM_thread()) {
1207     // We are re-laying out the vtable/itables of the *copy* of
1208     // a class during the final stage of dynamic dumping. The
1209     // linking constraints for this class has already been recorded.
1210     return;
1211   }
1212   assert(!Thread::current()->is_VM_thread(), "must be");
1213 
1214   assert(CDSConfig::is_dumping_archive(), "sanity");
1215   DumpTimeClassInfo* info = get_info(klass);
1216   info->record_linking_constraint(name, loader1, loader2);
1217 }
1218 
1219 // returns true IFF there's no need to re-initialize the i/v-tables for klass for
1220 // the purpose of checking class loader constraints.
1221 bool SystemDictionaryShared::check_linking_constraints(Thread* current, InstanceKlass* klass) {
1222   //assert(!CDSConfig::is_dumping_static_archive() && CDSConfig::is_using_archive(), "called at run time with CDS enabled only");
1223   LogTarget(Info, class, loader, constraints) log;
1224   if (klass->is_shared_boot_class()) {
1225     // No class loader constraint check performed for boot classes.
1226     return true;
1227   }
1228   if (klass->is_shared_platform_class() || klass->is_shared_app_class()) {
1229     RunTimeClassInfo* info = RunTimeClassInfo::get_for(klass);
1230     assert(info != nullptr, "Sanity");
1231     if (info->_num_loader_constraints > 0) {
1232       HandleMark hm(current);
1233       for (int i = 0; i < info->_num_loader_constraints; i++) {
1234         RunTimeClassInfo::RTLoaderConstraint* lc = info->loader_constraint_at(i);
1235         Symbol* name = lc->constraint_name();
1236         Handle loader1(current, get_class_loader_by(lc->_loader_type1));
1237         Handle loader2(current, get_class_loader_by(lc->_loader_type2));
1238         if (log.is_enabled()) {
1239           ResourceMark rm(current);
1240           log.print("[CDS add loader constraint for class %s symbol %s loader[0] %s loader[1] %s",
1241                     klass->external_name(), name->as_C_string(),
1242                     ClassLoaderData::class_loader_data(loader1())->loader_name_and_id(),

1331     }
1332   }
1333 
1334   size_t total() {
1335     return _shared_class_info_size;
1336   }
1337 };
1338 
1339 size_t SystemDictionaryShared::estimate_size_for_archive() {
1340   EstimateSizeForArchive est;
1341   _dumptime_table->iterate_all_live_classes(&est);
1342   size_t total_size = est.total() +
1343     CompactHashtableWriter::estimate_size(_dumptime_table->count_of(true)) +
1344     CompactHashtableWriter::estimate_size(_dumptime_table->count_of(false));
1345 
1346   size_t bytesize = align_up(sizeof(RunTimeLambdaProxyClassInfo), SharedSpaceObjectAlignment);
1347   total_size +=
1348       (bytesize * _dumptime_lambda_proxy_class_dictionary->_count) +
1349       CompactHashtableWriter::estimate_size(_dumptime_lambda_proxy_class_dictionary->_count);
1350 
1351   size_t method_info_byte_size = align_up(sizeof(RunTimeMethodDataInfo), SharedSpaceObjectAlignment);
1352   total_size +=
1353       (method_info_byte_size * _dumptime_method_info_dictionary->_count) +
1354       CompactHashtableWriter::estimate_size(_dumptime_method_info_dictionary->_count);
1355 
1356   return total_size;
1357 }
1358 
1359 unsigned int SystemDictionaryShared::hash_for_shared_dictionary(address ptr) {
1360   if (ArchiveBuilder::is_active() && ArchiveBuilder::current()->is_in_buffer_space(ptr)) {
1361     uintx offset = ArchiveBuilder::current()->any_to_offset(ptr);
1362     unsigned int hash = primitive_hash<uintx>(offset);
1363     DEBUG_ONLY({
1364         if (MetaspaceObj::is_shared((const MetaspaceObj*)ptr)) {
1365           assert(hash == SystemDictionaryShared::hash_for_shared_dictionary_quick(ptr), "must be");
1366         }
1367       });
1368     return hash;
1369   } else {
1370     return SystemDictionaryShared::hash_for_shared_dictionary_quick(ptr);
1371   }
1372 }
1373 
1374 class CopyLambdaProxyClassInfoToArchive : StackObj {
1375   CompactHashtableWriter* _writer;
1376   ArchiveBuilder* _builder;
1377 public:
1378   CopyLambdaProxyClassInfoToArchive(CompactHashtableWriter* writer)
1379   : _writer(writer), _builder(ArchiveBuilder::current()) {}
1380   bool do_entry(LambdaProxyClassKey& key, DumpTimeLambdaProxyClassInfo& info) {
1381     // In static dump, info._proxy_klasses->at(0) is already relocated to point to the archived class
1382     // (not the original class).
1383     //
1384     // The following check has been moved to SystemDictionaryShared::find_all_archivable_classes(), which
1385     // happens before the classes are copied.
1386     //
1387     // if (SystemDictionaryShared::is_excluded_class(info._proxy_klasses->at(0))) {
1388     //  return true;
1389     //}
1390     ResourceMark rm;
1391     log_info(cds,dynamic)("Archiving hidden %s", info._proxy_klasses->at(0)->external_name());
1392     size_t byte_size = sizeof(RunTimeLambdaProxyClassInfo);
1393     RunTimeLambdaProxyClassInfo* runtime_info =
1394         (RunTimeLambdaProxyClassInfo*)ArchiveBuilder::ro_region_alloc(byte_size);
1395     runtime_info->init(key, info);
1396     unsigned int hash = runtime_info->hash();
1397     u4 delta = _builder->any_to_offset_u4((void*)runtime_info);
1398     _writer->add(hash, delta);
1399     return true;
1400   }
1401 };
1402 
1403 class AdjustLambdaProxyClassInfo : StackObj {
1404 public:

1453         ResourceMark rm;
1454         log_trace(cds,hashtables)("%s dictionary: %s", (_is_builtin ? "builtin" : "unregistered"), info._klass->external_name());
1455       }
1456 
1457       // Save this for quick runtime lookup of InstanceKlass* -> RunTimeClassInfo*
1458       InstanceKlass* buffered_klass = ArchiveBuilder::current()->get_buffered_addr(info._klass);
1459       RunTimeClassInfo::set_for(buffered_klass, record);
1460     }
1461   }
1462 };
1463 
1464 void SystemDictionaryShared::write_lambda_proxy_class_dictionary(LambdaProxyClassDictionary *dictionary) {
1465   CompactHashtableStats stats;
1466   dictionary->reset();
1467   CompactHashtableWriter writer(_dumptime_lambda_proxy_class_dictionary->_count, &stats);
1468   CopyLambdaProxyClassInfoToArchive copy(&writer);
1469   _dumptime_lambda_proxy_class_dictionary->iterate(&copy);
1470   writer.dump(dictionary, "lambda proxy class dictionary");
1471 }
1472 
1473 class CopyMethodDataInfoToArchive : StackObj {
1474   CompactHashtableWriter* _writer;
1475   ArchiveBuilder* _builder;
1476 public:
1477   CopyMethodDataInfoToArchive(CompactHashtableWriter* writer)
1478       : _writer(writer), _builder(ArchiveBuilder::current()) {}
1479 
1480   bool do_entry(MethodDataKey& key, DumpTimeMethodDataInfo& info) {
1481     Method* holder = key.method();
1482     log_info(cds,dynamic)("Archiving method info for %s", holder->external_name());
1483 
1484     size_t byte_size = sizeof(RunTimeMethodDataInfo);
1485     RunTimeMethodDataInfo* record = (RunTimeMethodDataInfo*)ArchiveBuilder::ro_region_alloc(byte_size);
1486 
1487     DumpTimeMethodDataInfo data(info.method_data(), info.method_counters());
1488     record->init(key, data);
1489 
1490     uint hash = SystemDictionaryShared::hash_for_shared_dictionary((address)holder);
1491     u4 delta = _builder->buffer_to_offset_u4((address)record);
1492     _writer->add(hash, delta);
1493 
1494     return true;
1495   }
1496 };
1497 
1498 void SystemDictionaryShared::write_method_info_dictionary(MethodDataInfoDictionary* dictionary) {
1499   CompactHashtableStats stats;
1500   dictionary->reset();
1501   CompactHashtableWriter writer(_dumptime_method_info_dictionary->_count, &stats);
1502   CopyMethodDataInfoToArchive copy(&writer);
1503   _dumptime_method_info_dictionary->iterate(&copy);
1504   writer.dump(dictionary, "method info dictionary");
1505 }
1506 
1507 void SystemDictionaryShared::write_dictionary(RunTimeSharedDictionary* dictionary,
1508                                               bool is_builtin) {
1509   CompactHashtableStats stats;
1510   dictionary->reset();
1511   CompactHashtableWriter writer(_dumptime_table->count_of(is_builtin), &stats);
1512   CopySharedClassInfoToArchive copy(&writer, is_builtin);
1513   assert_lock_strong(DumpTimeTable_lock);
1514   _dumptime_table->iterate_all_live_classes(&copy);
1515   writer.dump(dictionary, is_builtin ? "builtin dictionary" : "unregistered dictionary");
1516 }
1517 
1518 void SystemDictionaryShared::write_to_archive(bool is_static_archive) {
1519   ArchiveInfo* archive = get_archive(is_static_archive);
1520 
1521   write_dictionary(&archive->_builtin_dictionary, true);
1522   write_dictionary(&archive->_unregistered_dictionary, false);
1523 
1524   write_lambda_proxy_class_dictionary(&archive->_lambda_proxy_class_dictionary);
1525 
1526   write_method_info_dictionary(&archive->_method_info_dictionary);
1527 }
1528 
1529 void SystemDictionaryShared::adjust_lambda_proxy_class_dictionary() {
1530   AdjustLambdaProxyClassInfo adjuster;
1531   _dumptime_lambda_proxy_class_dictionary->iterate(&adjuster);
1532 }
1533 
1534 class AdjustMethodInfo : StackObj {
1535 public:
1536   AdjustMethodInfo() {}
1537   bool do_entry(MethodDataKey& key, DumpTimeMethodDataInfo& info) {
1538     // TODO: is it possible for the data to become stale/invalid?
1539     MethodData*     md = info.method_data();
1540     MethodCounters* mc = info.method_counters();
1541     if (md != nullptr) {
1542       md = ArchiveBuilder::current()->get_buffered_addr(md);
1543     }
1544     if (mc != nullptr) {
1545       mc = ArchiveBuilder::current()->get_buffered_addr(mc);
1546     }
1547     assert(ArchiveBuilder::current()->is_in_buffer_space(md) || md == nullptr, "must be");
1548     assert(ArchiveBuilder::current()->is_in_buffer_space(mc) || mc == nullptr, "must be");
1549     if (md != nullptr) {
1550       md->remove_unshareable_info();
1551     }
1552     if (mc != nullptr) {
1553       mc->remove_unshareable_info();
1554     }
1555     return true;
1556   }
1557 };
1558 
1559 void SystemDictionaryShared::adjust_method_info_dictionary() {
1560   AdjustMethodInfo adjuster;
1561   _dumptime_method_info_dictionary->iterate(&adjuster);
1562 }
1563 
1564 void SystemDictionaryShared::serialize_dictionary_headers(SerializeClosure* soc,
1565                                                           bool is_static_archive) {
1566   ArchiveInfo* archive = get_archive(is_static_archive);
1567 
1568   archive->_builtin_dictionary.serialize_header(soc);
1569   archive->_unregistered_dictionary.serialize_header(soc);
1570   archive->_lambda_proxy_class_dictionary.serialize_header(soc);
1571   archive->_method_info_dictionary.serialize_header(soc);
1572 }
1573 
1574 void SystemDictionaryShared::serialize_vm_classes(SerializeClosure* soc) {
1575   for (auto id : EnumRange<vmClassID>{}) {
1576     soc->do_ptr(vmClasses::klass_addr_at(id));
1577   }
1578   soc->do_ptr((void**)&_archived_lambda_form_classes);
1579   soc->do_ptr((void**)&_archived_lambda_proxy_classes_boot);
1580   soc->do_ptr((void**)&_archived_lambda_proxy_classes_boot2);
1581   soc->do_ptr((void**)&_archived_lambda_proxy_classes_platform);
1582   soc->do_ptr((void**)&_archived_lambda_proxy_classes_app);
1583 }
1584 
1585 const RunTimeClassInfo*
1586 SystemDictionaryShared::find_record(RunTimeSharedDictionary* static_dict, RunTimeSharedDictionary* dynamic_dict, Symbol* name) {
1587   if (!CDSConfig::is_using_archive() || !name->is_shared()) {
1588     // The names of all shared classes must also be a shared Symbol.
1589     return nullptr;
1590   }
1591 
1592   unsigned int hash = SystemDictionaryShared::hash_for_shared_dictionary_quick(name);
1593   const RunTimeClassInfo* record = nullptr;
1594   if (DynamicArchive::is_mapped()) {
1595     // Use the regenerated holder classes in the dynamic archive as they
1596     // have more methods than those in the base archive.
1597     if (LambdaFormInvokers::may_be_regenerated_class(name)) {



1598       record = dynamic_dict->lookup(name, hash, 0);
1599       if (record != nullptr) {
1600         return record;
1601       }
1602     }
1603   }
1604 
1605   if (!MetaspaceShared::is_shared_dynamic(name)) {
1606     // The names of all shared classes in the static dict must also be in the
1607     // static archive
1608     record = static_dict->lookup(name, hash, 0);
1609   }
1610 
1611   if (record == nullptr && DynamicArchive::is_mapped()) {
1612     record = dynamic_dict->lookup(name, hash, 0);
1613   }
1614 
1615   return record;
1616 }
1617 

1622   if (record != nullptr) {
1623     assert(!record->_klass->is_hidden(), "hidden class cannot be looked up by name");
1624     assert(check_alignment(record->_klass), "Address not aligned");
1625     // We did not save the classfile data of the generated LambdaForm invoker classes,
1626     // so we cannot support CLFH for such classes.
1627     if (record->_klass->is_generated_shared_class() && JvmtiExport::should_post_class_file_load_hook()) {
1628        return nullptr;
1629     }
1630     return record->_klass;
1631   } else {
1632     return nullptr;
1633   }
1634 }
1635 
1636 void SystemDictionaryShared::update_shared_entry(InstanceKlass* k, int id) {
1637   assert(CDSConfig::is_dumping_static_archive(), "class ID is used only for static dump (from classlist)");
1638   DumpTimeClassInfo* info = get_info(k);
1639   info->_id = id;
1640 }
1641 
1642 const char* SystemDictionaryShared::class_loader_name_for_shared(Klass* k) {
1643   assert(k != nullptr, "Sanity");
1644   assert(k->is_shared(), "Must be");
1645   assert(k->is_instance_klass(), "Must be");
1646   InstanceKlass* ik = InstanceKlass::cast(k);
1647   if (ik->is_shared_boot_class()) {
1648     return "boot_loader";
1649   } else if (ik->is_shared_platform_class()) {
1650     return "platform_loader";
1651   } else if (ik->is_shared_app_class()) {
1652     return "app_loader";
1653   } else if (ik->is_shared_unregistered_class()) {
1654     return "unregistered_loader";
1655   } else {
1656     return "unknown loader";
1657   }
1658 }
1659 
1660 class SharedDictionaryPrinter : StackObj {
1661   outputStream* _st;
1662   int _index;
1663 public:
1664   SharedDictionaryPrinter(outputStream* st) : _st(st), _index(0) {}
1665 
1666   void do_value(const RunTimeClassInfo* record) {
1667     ResourceMark rm;
1668     _st->print_cr("%4d: %s %s", _index++, record->_klass->external_name(),
1669         SystemDictionaryShared::class_loader_name_for_shared(record->_klass));
1670     if (record->_klass->array_klasses() != nullptr) {
1671       record->_klass->array_klasses()->cds_print_value_on(_st);
1672       _st->cr();
1673     }
1674   }
1675   int index() const { return _index; }
1676 };
1677 
1678 class SharedLambdaDictionaryPrinter : StackObj {
1679   outputStream* _st;
1680   int _index;
1681 public:
1682   SharedLambdaDictionaryPrinter(outputStream* st, int idx) : _st(st), _index(idx) {}
1683 
1684   void do_value(const RunTimeLambdaProxyClassInfo* record) {
1685     if (record->proxy_klass_head()->lambda_proxy_is_available()) {
1686       ResourceMark rm;
1687       Klass* k = record->proxy_klass_head();
1688       while (k != nullptr) {
1689         _st->print_cr("%4d: %s %s", _index++, k->external_name(),
1690                       SystemDictionaryShared::class_loader_name_for_shared(k));
1691         k = k->next_link();
1692       }
1693     }
1694   }
1695 };
1696 
1697 class SharedMethodInfoDictionaryPrinter : StackObj {
1698   outputStream* _st;
1699   int _index;
1700 
1701 private:
1702   static const char* tag(void* p) {
1703     if (p == nullptr) {
1704       return "   ";
1705     } else if (MetaspaceShared::is_shared_dynamic(p)) {
1706       return "<D>";
1707     } else if (MetaspaceShared::is_in_shared_metaspace(p)) {
1708       return "<S>";
1709     } else {
1710       return "???";
1711     }
1712   }
1713 public:
1714   SharedMethodInfoDictionaryPrinter(outputStream* st) : _st(st), _index(0) {}
1715 
1716   void do_value(const RunTimeMethodDataInfo* record) {
1717     ResourceMark rm;
1718     Method*         m  = record->method();
1719     MethodCounters* mc = record->method_counters();
1720     MethodData*     md = record->method_data();
1721 
1722     _st->print_cr("%4d: %s" PTR_FORMAT " %s" PTR_FORMAT " %s" PTR_FORMAT " %s", _index++,
1723                   tag(m), p2i(m),
1724                   tag(mc), p2i(mc),
1725                   tag(md), p2i(md),
1726                   m->external_name());
1727     if (Verbose) {
1728       if (mc != nullptr) {
1729         mc->print_on(_st);
1730       }
1731       if (md != nullptr) {
1732         md->print_on(_st);
1733       }
1734       _st->cr();
1735     }
1736   }
1737 };
1738 
1739 void SystemDictionaryShared::ArchiveInfo::print_on(const char* prefix,
1740                                                    outputStream* st) {
1741   st->print_cr("%sShared Dictionary", prefix);
1742   SharedDictionaryPrinter p(st);
1743   st->print_cr("%sShared Builtin Dictionary", prefix);
1744   _builtin_dictionary.iterate(&p);
1745   st->print_cr("%sShared Unregistered Dictionary", prefix);
1746   _unregistered_dictionary.iterate(&p);
1747   if (!_lambda_proxy_class_dictionary.empty()) {
1748     st->print_cr("%sShared Lambda Dictionary", prefix);
1749     SharedLambdaDictionaryPrinter ldp(st, p.index());
1750     _lambda_proxy_class_dictionary.iterate(&ldp);
1751   }
1752   if (!_method_info_dictionary.empty()) {
1753     st->print_cr("%sShared MethodData Dictionary", prefix);
1754     SharedMethodInfoDictionaryPrinter mdp(st);
1755     _method_info_dictionary.iterate(&mdp);
1756   }
1757 }
1758 
1759 void SystemDictionaryShared::ArchiveInfo::print_table_statistics(const char* prefix,
1760                                                                  outputStream* st) {
1761   st->print_cr("%sArchve Statistics", prefix);
1762   _builtin_dictionary.print_table_statistics(st, "Builtin Shared Dictionary");
1763   _unregistered_dictionary.print_table_statistics(st, "Unregistered Shared Dictionary");
1764   _lambda_proxy_class_dictionary.print_table_statistics(st, "Lambda Shared Dictionary");
1765   _method_info_dictionary.print_table_statistics(st, "MethodData Dictionary");
1766 }
1767 
1768 void SystemDictionaryShared::print_shared_archive(outputStream* st, bool is_static) {
1769   if (CDSConfig::is_using_archive()) {
1770     if (is_static) {
1771       _static_archive.print_on("", st);
1772     } else {
1773       if (DynamicArchive::is_mapped()) {
1774         _dynamic_archive.print_on("Dynamic ", st);
1775       }
1776     }
1777   }
1778 }
1779 
1780 void SystemDictionaryShared::print_on(outputStream* st) {
1781   print_shared_archive(st, true);
1782   print_shared_archive(st, false);
1783 }
1784 
1785 void SystemDictionaryShared::print_table_statistics(outputStream* st) {

1811     // must also be excluded.
1812     bool always_exclude = SystemDictionaryShared::check_for_exclusion(caller_ik, nullptr) ||
1813                           SystemDictionaryShared::check_for_exclusion(nest_host, nullptr);
1814 
1815     for (int i = info._proxy_klasses->length() - 1; i >= 0; i--) {
1816       InstanceKlass* ik = info._proxy_klasses->at(i);
1817       if (always_exclude || SystemDictionaryShared::check_for_exclusion(ik, nullptr)) {
1818         SystemDictionaryShared::reset_registered_lambda_proxy_class(ik);
1819         info._proxy_klasses->remove_at(i);
1820       }
1821     }
1822     return info._proxy_klasses->length() == 0 ? true /* delete the node*/ : false;
1823   }
1824 };
1825 
1826 void SystemDictionaryShared::cleanup_lambda_proxy_class_dictionary() {
1827   assert_lock_strong(DumpTimeTable_lock);
1828   CleanupDumpTimeLambdaProxyClassTable cleanup_proxy_classes;
1829   _dumptime_lambda_proxy_class_dictionary->unlink(&cleanup_proxy_classes);
1830 }
1831 
1832 class CleanupDumpTimeMethodInfoTable : StackObj {
1833 public:
1834   bool do_entry(MethodDataKey& key, DumpTimeMethodDataInfo& info) {
1835     assert_lock_strong(DumpTimeTable_lock);
1836     assert(MetaspaceShared::is_in_shared_metaspace(key.method()), "");
1837     InstanceKlass* holder = key.method()->method_holder();
1838     bool is_excluded = SystemDictionaryShared::check_for_exclusion(holder, nullptr);
1839     return is_excluded;
1840   }
1841 };
1842 
1843 void SystemDictionaryShared::cleanup_method_info_dictionary() {
1844   assert_lock_strong(DumpTimeTable_lock);
1845 
1846   CleanupDumpTimeMethodInfoTable cleanup_method_info;
1847   _dumptime_method_info_dictionary->unlink(&cleanup_method_info);
1848 }
1849 
1850 void SystemDictionaryShared::create_loader_positive_lookup_cache(TRAPS) {
1851   GrowableArray<InstanceKlass*> shared_classes_list;
1852   {
1853     // With static dumping, we have only a single Java thread (see JVM_StartThread) so
1854     // no no other threads should be loading classes. Otherwise, the code below may miss some
1855     // classes that are loaded concurrently.
1856     assert(CDSConfig::is_dumping_static_archive(), "no other threads should be loading classes");
1857 
1858     MutexLocker ml(DumpTimeTable_lock, Mutex::_no_safepoint_check_flag);
1859     _dumptime_table->iterate_all_classes_in_builtin_loaders([&](InstanceKlass* k, DumpTimeClassInfo& info) {
1860         if (!k->is_hidden() && !check_for_exclusion(k, &info)) {
1861           shared_classes_list.append(k);
1862         }
1863       }
1864     );
1865   }
1866 
1867   InstanceKlass* ik = vmClasses::Class_klass();
1868   objArrayOop r = oopFactory::new_objArray(ik, shared_classes_list.length(), CHECK);
1869   objArrayHandle array_h(THREAD, r);
1870 
1871   for (int i = 0; i < shared_classes_list.length(); i++) {
1872     oop mirror = shared_classes_list.at(i)->java_mirror();
1873     Handle mirror_h(THREAD, mirror);
1874     array_h->obj_at_put(i, mirror_h());
1875   }
1876 
1877   TempNewSymbol method = SymbolTable::new_symbol("generatePositiveLookupCache");
1878   TempNewSymbol signature = SymbolTable::new_symbol("([Ljava/lang/Class;)V");
1879 
1880   JavaCallArguments args(Handle(THREAD, SystemDictionary::java_system_loader()));
1881   args.push_oop(array_h);
1882   JavaValue result(T_VOID);
1883   JavaCalls::call_virtual(&result,
1884                           vmClasses::jdk_internal_loader_ClassLoaders_AppClassLoader_klass(),
1885                           method,
1886                           signature,
1887                           &args,
1888                           CHECK);
1889 
1890   if (HAS_PENDING_EXCEPTION) {
1891     Handle exc_handle(THREAD, PENDING_EXCEPTION);
1892     CLEAR_PENDING_EXCEPTION;
1893     ResourceMark rm(THREAD);
1894 
1895     log_warning(cds)("Exception during AppClassLoader::generatePositiveLookupCache() call");
1896     LogStreamHandle(Debug, cds) log;
1897     if (log.is_enabled()) {
1898       java_lang_Throwable::print_stack_trace(exc_handle, &log);
1899     }
1900     return;
1901   }
1902 }
< prev index next >