1 /*
   2  * Copyright (c) 2014, 2021, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "precompiled.hpp"
  26 #include "cds/archiveUtils.hpp"
  27 #include "cds/archiveBuilder.hpp"
  28 #include "cds/classListParser.hpp"
  29 #include "cds/classListWriter.hpp"
  30 #include "cds/dynamicArchive.hpp"
  31 #include "cds/filemap.hpp"
  32 #include "cds/heapShared.hpp"
  33 #include "cds/cdsProtectionDomain.hpp"
  34 #include "cds/dumpTimeClassInfo.hpp"
  35 #include "cds/metaspaceShared.hpp"
  36 #include "cds/runTimeClassInfo.hpp"
  37 #include "classfile/classFileStream.hpp"
  38 #include "classfile/classLoader.hpp"
  39 #include "classfile/classLoaderData.inline.hpp"
  40 #include "classfile/classLoaderDataGraph.hpp"
  41 #include "classfile/classLoaderExt.hpp"
  42 #include "classfile/dictionary.hpp"
  43 #include "classfile/javaClasses.hpp"
  44 #include "classfile/javaClasses.inline.hpp"
  45 #include "classfile/symbolTable.hpp"
  46 #include "classfile/systemDictionary.hpp"
  47 #include "classfile/systemDictionaryShared.hpp"
  48 #include "classfile/verificationType.hpp"
  49 #include "classfile/vmClasses.hpp"
  50 #include "classfile/vmSymbols.hpp"
  51 #include "interpreter/bootstrapInfo.hpp"
  52 #include "jfr/jfrEvents.hpp"
  53 #include "logging/log.hpp"
  54 #include "logging/logStream.hpp"
  55 #include "memory/allocation.hpp"
  56 #include "memory/metadataFactory.hpp"
  57 #include "memory/metaspaceClosure.hpp"
  58 #include "memory/oopFactory.hpp"
  59 #include "memory/resourceArea.hpp"
  60 #include "memory/universe.hpp"
  61 #include "oops/compressedKlass.hpp"
  62 #include "oops/instanceKlass.hpp"
  63 #include "oops/klass.inline.hpp"
  64 #include "oops/objArrayOop.inline.hpp"
  65 #include "oops/oop.inline.hpp"
  66 #include "oops/oopHandle.inline.hpp"
  67 #include "oops/typeArrayOop.inline.hpp"
  68 #include "runtime/arguments.hpp"
  69 #include "runtime/handles.inline.hpp"
  70 #include "runtime/java.hpp"
  71 #include "runtime/javaCalls.hpp"
  72 #include "runtime/mutexLocker.hpp"
  73 #include "utilities/hashtable.inline.hpp"
  74 #include "utilities/resourceHash.hpp"
  75 #include "utilities/stringUtils.hpp"
  76 
  77 DumpTimeSharedClassTable* SystemDictionaryShared::_dumptime_table = NULL;
  78 DumpTimeSharedClassTable* SystemDictionaryShared::_cloned_dumptime_table = NULL;
  79 DumpTimeLambdaProxyClassDictionary* SystemDictionaryShared::_dumptime_lambda_proxy_class_dictionary = NULL;
  80 DumpTimeLambdaProxyClassDictionary* SystemDictionaryShared::_cloned_dumptime_lambda_proxy_class_dictionary = NULL;
  81 // SystemDictionaries in the base layer static archive
  82 RunTimeSharedDictionary SystemDictionaryShared::_builtin_dictionary;
  83 RunTimeSharedDictionary SystemDictionaryShared::_unregistered_dictionary;
  84 // SystemDictionaries in the top layer dynamic archive
  85 RunTimeSharedDictionary SystemDictionaryShared::_dynamic_builtin_dictionary;
  86 RunTimeSharedDictionary SystemDictionaryShared::_dynamic_unregistered_dictionary;
  87 
  88 LambdaProxyClassDictionary SystemDictionaryShared::_lambda_proxy_class_dictionary;
  89 LambdaProxyClassDictionary SystemDictionaryShared::_dynamic_lambda_proxy_class_dictionary;
  90 
  91 DEBUG_ONLY(bool SystemDictionaryShared::_no_class_loading_should_happen = false;)
  92 bool SystemDictionaryShared::_dump_in_progress = false;
  93 
  94 InstanceKlass* SystemDictionaryShared::load_shared_class_for_builtin_loader(
  95                  Symbol* class_name, Handle class_loader, TRAPS) {
  96   assert(UseSharedSpaces, "must be");
  97   InstanceKlass* ik = find_builtin_class(class_name);
  98 
  99   if (ik != NULL && !ik->shared_loading_failed()) {
 100     if ((SystemDictionary::is_system_class_loader(class_loader()) && ik->is_shared_app_class())  ||
 101         (SystemDictionary::is_platform_class_loader(class_loader()) && ik->is_shared_platform_class())) {
 102       SharedClassLoadingMark slm(THREAD, ik);
 103       PackageEntry* pkg_entry = CDSProtectionDomain::get_package_entry_from_class(ik, class_loader);
 104       Handle protection_domain =
 105         CDSProtectionDomain::init_security_info(class_loader, ik, pkg_entry, CHECK_NULL);
 106       return load_shared_class(ik, class_loader, protection_domain, NULL, pkg_entry, THREAD);
 107     }
 108   }
 109   return NULL;
 110 }
 111 
 112 // This function is called for loading only UNREGISTERED classes
 113 InstanceKlass* SystemDictionaryShared::lookup_from_stream(Symbol* class_name,
 114                                                           Handle class_loader,
 115                                                           Handle protection_domain,
 116                                                           const ClassFileStream* cfs,
 117                                                           TRAPS) {
 118   if (!UseSharedSpaces) {
 119     return NULL;
 120   }
 121   if (class_name == NULL) {  // don't do this for hidden classes
 122     return NULL;
 123   }
 124   if (class_loader.is_null() ||
 125       SystemDictionary::is_system_class_loader(class_loader()) ||
 126       SystemDictionary::is_platform_class_loader(class_loader())) {
 127     // Do nothing for the BUILTIN loaders.
 128     return NULL;
 129   }
 130 
 131   const RunTimeClassInfo* record = find_record(&_unregistered_dictionary, &_dynamic_unregistered_dictionary, class_name);
 132   if (record == NULL) {
 133     return NULL;
 134   }
 135 
 136   int clsfile_size  = cfs->length();
 137   int clsfile_crc32 = ClassLoader::crc32(0, (const char*)cfs->buffer(), cfs->length());
 138 
 139   if (!record->matches(clsfile_size, clsfile_crc32)) {
 140     return NULL;
 141   }
 142 
 143   return acquire_class_for_current_thread(record->_klass, class_loader,
 144                                           protection_domain, cfs,
 145                                           THREAD);
 146 }
 147 
 148 InstanceKlass* SystemDictionaryShared::acquire_class_for_current_thread(
 149                    InstanceKlass *ik,
 150                    Handle class_loader,
 151                    Handle protection_domain,
 152                    const ClassFileStream *cfs,
 153                    TRAPS) {
 154   ClassLoaderData* loader_data = ClassLoaderData::class_loader_data(class_loader());
 155 
 156   {
 157     MutexLocker mu(THREAD, SharedDictionary_lock);
 158     if (ik->class_loader_data() != NULL) {
 159       //    ik is already loaded (by this loader or by a different loader)
 160       // or ik is being loaded by a different thread (by this loader or by a different loader)
 161       return NULL;
 162     }
 163 
 164     // No other thread has acquired this yet, so give it to *this thread*
 165     ik->set_class_loader_data(loader_data);
 166   }
 167 
 168   // No longer holding SharedDictionary_lock
 169   // No need to lock, as <ik> can be held only by a single thread.
 170   loader_data->add_class(ik);
 171 
 172   // Get the package entry.
 173   PackageEntry* pkg_entry = CDSProtectionDomain::get_package_entry_from_class(ik, class_loader);
 174 
 175   // Load and check super/interfaces, restore unsharable info
 176   InstanceKlass* shared_klass = load_shared_class(ik, class_loader, protection_domain,
 177                                                   cfs, pkg_entry, THREAD);
 178   if (shared_klass == NULL || HAS_PENDING_EXCEPTION) {
 179     // TODO: clean up <ik> so it can be used again
 180     return NULL;
 181   }
 182 
 183   return shared_klass;
 184 }
 185 
 186 void SystemDictionaryShared::start_dumping() {
 187   MutexLocker ml(DumpTimeTable_lock, Mutex::_no_safepoint_check_flag);
 188   _dump_in_progress = true;
 189 }
 190 
 191 DumpTimeClassInfo* SystemDictionaryShared::find_or_allocate_info_for(InstanceKlass* k) {
 192   MutexLocker ml(DumpTimeTable_lock, Mutex::_no_safepoint_check_flag);
 193   return find_or_allocate_info_for_locked(k);
 194 }
 195 
 196 DumpTimeClassInfo* SystemDictionaryShared::find_or_allocate_info_for_locked(InstanceKlass* k) {
 197   assert_lock_strong(DumpTimeTable_lock);
 198   if (_dumptime_table == NULL) {
 199     _dumptime_table = new (ResourceObj::C_HEAP, mtClass) DumpTimeSharedClassTable;
 200   }
 201   return _dumptime_table->find_or_allocate_info_for(k, _dump_in_progress);
 202 }
 203 
 204 bool SystemDictionaryShared::check_for_exclusion(InstanceKlass* k, DumpTimeClassInfo* info) {
 205   if (MetaspaceShared::is_in_shared_metaspace(k)) {
 206     // We have reached a super type that's already in the base archive. Treat it
 207     // as "not excluded".
 208     assert(DynamicDumpSharedSpaces, "must be");
 209     return false;
 210   }
 211 
 212   if (info == NULL) {
 213     info = _dumptime_table->get(k);
 214     assert(info != NULL, "supertypes of any classes in _dumptime_table must either be shared, or must also be in _dumptime_table");
 215   }
 216 
 217   if (!info->has_checked_exclusion()) {
 218     if (check_for_exclusion_impl(k)) {
 219       info->set_excluded();
 220     }
 221     info->set_has_checked_exclusion();
 222   }
 223 
 224   return info->is_excluded();
 225 }
 226 
 227 // Returns true so the caller can do:    return warn_excluded(".....");
 228 bool SystemDictionaryShared::warn_excluded(InstanceKlass* k, const char* reason) {
 229   ResourceMark rm;
 230   log_warning(cds)("Skipping %s: %s", k->name()->as_C_string(), reason);
 231   return true;
 232 }
 233 
 234 bool SystemDictionaryShared::is_jfr_event_class(InstanceKlass *k) {
 235   while (k) {
 236     if (k->name()->equals("jdk/internal/event/Event")) {
 237       return true;
 238     }
 239     k = k->java_super();
 240   }
 241   return false;
 242 }
 243 
 244 bool SystemDictionaryShared::is_registered_lambda_proxy_class(InstanceKlass* ik) {
 245   DumpTimeClassInfo* info = _dumptime_table->get(ik);
 246   return (info != NULL) ? info->_is_archived_lambda_proxy : false;
 247 }
 248 
 249 void SystemDictionaryShared::reset_registered_lambda_proxy_class(InstanceKlass* ik) {
 250   DumpTimeClassInfo* info = _dumptime_table->get(ik);
 251   if (info != NULL) {
 252     info->_is_archived_lambda_proxy = false;
 253     info->set_excluded();
 254   }
 255 }
 256 
 257 bool SystemDictionaryShared::is_early_klass(InstanceKlass* ik) {
 258   DumpTimeClassInfo* info = _dumptime_table->get(ik);
 259   return (info != NULL) ? info->is_early_klass() : false;
 260 }
 261 
 262 bool SystemDictionaryShared::is_hidden_lambda_proxy(InstanceKlass* ik) {
 263   assert(ik->is_shared(), "applicable to only a shared class");
 264   if (ik->is_hidden()) {
 265     return true;
 266   } else {
 267     return false;
 268   }
 269 }
 270 
 271 bool SystemDictionaryShared::check_for_exclusion_impl(InstanceKlass* k) {
 272   if (k->is_in_error_state()) {
 273     return warn_excluded(k, "In error state");
 274   }
 275   if (k->is_scratch_class()) {
 276     return warn_excluded(k, "A scratch class");
 277   }
 278   if (!k->is_loaded()) {
 279     return warn_excluded(k, "Not in loaded state");
 280   }
 281   if (has_been_redefined(k)) {
 282     return warn_excluded(k, "Has been redefined");
 283   }
 284   if (!k->is_hidden() && k->shared_classpath_index() < 0 && is_builtin(k)) {
 285     // These are classes loaded from unsupported locations (such as those loaded by JVMTI native
 286     // agent during dump time).
 287     return warn_excluded(k, "Unsupported location");
 288   }
 289   if (k->signers() != NULL) {
 290     // We cannot include signed classes in the archive because the certificates
 291     // used during dump time may be different than those used during
 292     // runtime (due to expiration, etc).
 293     return warn_excluded(k, "Signed JAR");
 294   }
 295   if (is_jfr_event_class(k)) {
 296     // We cannot include JFR event classes because they need runtime-specific
 297     // instrumentation in order to work with -XX:FlightRecorderOptions:retransform=false.
 298     // There are only a small number of these classes, so it's not worthwhile to
 299     // support them and make CDS more complicated.
 300     return warn_excluded(k, "JFR event class");
 301   }
 302 
 303   if (!k->is_linked()) {
 304     if (has_class_failed_verification(k)) {
 305       return warn_excluded(k, "Failed verification");
 306     }
 307   } else {
 308     if (!k->can_be_verified_at_dumptime()) {
 309       // We have an old class that has been linked (e.g., it's been executed during
 310       // dump time). This class has been verified using the old verifier, which
 311       // doesn't save the verification constraints, so check_verification_constraints()
 312       // won't work at runtime.
 313       // As a result, we cannot store this class. It must be loaded and fully verified
 314       // at runtime.
 315       return warn_excluded(k, "Old class has been linked");
 316     }
 317   }
 318 
 319   if (k->is_hidden() && !is_registered_lambda_proxy_class(k)) {
 320     ResourceMark rm;
 321     log_debug(cds)("Skipping %s: Hidden class", k->name()->as_C_string());
 322     return true;
 323   }
 324 
 325   InstanceKlass* super = k->java_super();
 326   if (super != NULL && check_for_exclusion(super, NULL)) {
 327     ResourceMark rm;
 328     log_warning(cds)("Skipping %s: super class %s is excluded", k->name()->as_C_string(), super->name()->as_C_string());
 329     return true;
 330   }
 331 
 332   Array<InstanceKlass*>* interfaces = k->local_interfaces();
 333   int len = interfaces->length();
 334   for (int i = 0; i < len; i++) {
 335     InstanceKlass* intf = interfaces->at(i);
 336     if (check_for_exclusion(intf, NULL)) {
 337       ResourceMark rm;
 338       log_warning(cds)("Skipping %s: interface %s is excluded", k->name()->as_C_string(), intf->name()->as_C_string());
 339       return true;
 340     }
 341   }
 342 
 343   return false; // false == k should NOT be excluded
 344 }
 345 
 346 bool SystemDictionaryShared::is_builtin_loader(ClassLoaderData* loader_data) {
 347   oop class_loader = loader_data->class_loader();
 348   return (class_loader == NULL ||
 349           SystemDictionary::is_system_class_loader(class_loader) ||
 350           SystemDictionary::is_platform_class_loader(class_loader));
 351 }
 352 
 353 bool SystemDictionaryShared::has_platform_or_app_classes() {
 354   if (FileMapInfo::current_info()->has_platform_or_app_classes()) {
 355     return true;
 356   }
 357   if (DynamicArchive::is_mapped() &&
 358       FileMapInfo::dynamic_info()->has_platform_or_app_classes()) {
 359     return true;
 360   }
 361   return false;
 362 }
 363 
 364 // The following stack shows how this code is reached:
 365 //
 366 //   [0] SystemDictionaryShared::find_or_load_shared_class()
 367 //   [1] JVM_FindLoadedClass
 368 //   [2] java.lang.ClassLoader.findLoadedClass0()
 369 //   [3] java.lang.ClassLoader.findLoadedClass()
 370 //   [4] jdk.internal.loader.BuiltinClassLoader.loadClassOrNull()
 371 //   [5] jdk.internal.loader.BuiltinClassLoader.loadClass()
 372 //   [6] jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(), or
 373 //       jdk.internal.loader.ClassLoaders$PlatformClassLoader.loadClass()
 374 //
 375 // AppCDS supports fast class loading for these 2 built-in class loaders:
 376 //    jdk.internal.loader.ClassLoaders$PlatformClassLoader
 377 //    jdk.internal.loader.ClassLoaders$AppClassLoader
 378 // with the following assumptions (based on the JDK core library source code):
 379 //
 380 // [a] these two loaders use the BuiltinClassLoader.loadClassOrNull() to
 381 //     load the named class.
 382 // [b] BuiltinClassLoader.loadClassOrNull() first calls findLoadedClass(name).
 383 // [c] At this point, if we can find the named class inside the
 384 //     shared_dictionary, we can perform further checks (see
 385 //     SystemDictionary::is_shared_class_visible) to ensure that this class
 386 //     was loaded by the same class loader during dump time.
 387 //
 388 // Given these assumptions, we intercept the findLoadedClass() call to invoke
 389 // SystemDictionaryShared::find_or_load_shared_class() to load the shared class from
 390 // the archive for the 2 built-in class loaders. This way,
 391 // we can improve start-up because we avoid decoding the classfile,
 392 // and avoid delegating to the parent loader.
 393 //
 394 // NOTE: there's a lot of assumption about the Java code. If any of that change, this
 395 // needs to be redesigned.
 396 
 397 InstanceKlass* SystemDictionaryShared::find_or_load_shared_class(
 398                  Symbol* name, Handle class_loader, TRAPS) {
 399   InstanceKlass* k = NULL;
 400   if (UseSharedSpaces) {
 401     if (!has_platform_or_app_classes()) {
 402       return NULL;
 403     }
 404 
 405     if (SystemDictionary::is_system_class_loader(class_loader()) ||
 406         SystemDictionary::is_platform_class_loader(class_loader())) {
 407       // Fix for 4474172; see evaluation for more details
 408       class_loader = Handle(
 409         THREAD, java_lang_ClassLoader::non_reflection_class_loader(class_loader()));
 410       ClassLoaderData *loader_data = register_loader(class_loader);
 411       Dictionary* dictionary = loader_data->dictionary();
 412       unsigned int d_hash = dictionary->compute_hash(name);
 413 
 414       // Note: currently, find_or_load_shared_class is called only from
 415       // JVM_FindLoadedClass and used for PlatformClassLoader and AppClassLoader,
 416       // which are parallel-capable loaders, so a lock here is NOT taken.
 417       assert(get_loader_lock_or_null(class_loader) == NULL, "ObjectLocker not required");
 418       {
 419         MutexLocker mu(THREAD, SystemDictionary_lock);
 420         InstanceKlass* check = dictionary->find_class(d_hash, name);
 421         if (check != NULL) {
 422           return check;
 423         }
 424       }
 425 
 426       k = load_shared_class_for_builtin_loader(name, class_loader, THREAD);
 427       if (k != NULL) {
 428         SharedClassLoadingMark slm(THREAD, k);
 429         k = find_or_define_instance_class(name, class_loader, k, CHECK_NULL);
 430       }
 431     }
 432   }
 433   return k;
 434 }
 435 
 436 class UnregisteredClassesTable : public ResourceHashtable<
 437   Symbol*, InstanceKlass*,
 438   15889, // prime number
 439   ResourceObj::C_HEAP> {};
 440 
 441 static UnregisteredClassesTable* _unregistered_classes_table = NULL;
 442 
 443 // true == class was successfully added; false == a duplicated class (with the same name) already exists.
 444 bool SystemDictionaryShared::add_unregistered_class(Thread* current, InstanceKlass* klass) {
 445   // We don't allow duplicated unregistered classes with the same name.
 446   // We only archive the first class with that name that succeeds putting
 447   // itself into the table.
 448   assert(Arguments::is_dumping_archive() || ClassListWriter::is_enabled(), "sanity");
 449   MutexLocker ml(current, UnregisteredClassesTable_lock);
 450   Symbol* name = klass->name();
 451   if (_unregistered_classes_table == NULL) {
 452     _unregistered_classes_table = new (ResourceObj::C_HEAP, mtClass)UnregisteredClassesTable();
 453   }
 454   bool created;
 455   InstanceKlass** v = _unregistered_classes_table->put_if_absent(name, klass, &created);
 456   if (created) {
 457     name->increment_refcount();
 458   }
 459   return (klass == *v);
 460 }
 461 
 462 // This function is called to lookup the super/interfaces of shared classes for
 463 // unregistered loaders. E.g., SharedClass in the below example
 464 // where "super:" (and optionally "interface:") have been specified.
 465 //
 466 // java/lang/Object id: 0
 467 // Interface    id: 2 super: 0 source: cust.jar
 468 // SharedClass  id: 4 super: 0 interfaces: 2 source: cust.jar
 469 InstanceKlass* SystemDictionaryShared::lookup_super_for_unregistered_class(
 470     Symbol* class_name, Symbol* super_name, bool is_superclass) {
 471 
 472   assert(DumpSharedSpaces, "only when static dumping");
 473 
 474   if (!ClassListParser::is_parsing_thread()) {
 475     // Unregistered classes can be created only by ClassListParser::_parsing_thread.
 476 
 477     return NULL;
 478   }
 479 
 480   ClassListParser* parser = ClassListParser::instance();
 481   if (parser == NULL) {
 482     // We're still loading the well-known classes, before the ClassListParser is created.
 483     return NULL;
 484   }
 485   if (class_name->equals(parser->current_class_name())) {
 486     // When this function is called, all the numbered super and interface types
 487     // must have already been loaded. Hence this function is never recursively called.
 488     if (is_superclass) {
 489       return parser->lookup_super_for_current_class(super_name);
 490     } else {
 491       return parser->lookup_interface_for_current_class(super_name);
 492     }
 493   } else {
 494     // The VM is not trying to resolve a super type of parser->current_class_name().
 495     // Instead, it's resolving an error class (because parser->current_class_name() has
 496     // failed parsing or verification). Don't do anything here.
 497     return NULL;
 498   }
 499 }
 500 
 501 void SystemDictionaryShared::set_shared_class_misc_info(InstanceKlass* k, ClassFileStream* cfs) {
 502   Arguments::assert_is_dumping_archive();
 503   assert(!is_builtin(k), "must be unregistered class");
 504   DumpTimeClassInfo* info = find_or_allocate_info_for(k);
 505   if (info != NULL) {
 506     info->_clsfile_size  = cfs->length();
 507     info->_clsfile_crc32 = ClassLoader::crc32(0, (const char*)cfs->buffer(), cfs->length());
 508   }
 509 }
 510 
 511 void SystemDictionaryShared::init_dumptime_info(InstanceKlass* k) {
 512   (void)find_or_allocate_info_for(k);
 513 }
 514 
 515 void SystemDictionaryShared::remove_dumptime_info(InstanceKlass* k) {
 516   MutexLocker ml(DumpTimeTable_lock, Mutex::_no_safepoint_check_flag);
 517   DumpTimeClassInfo* p = _dumptime_table->get(k);
 518   if (p == NULL) {
 519     return;
 520   }
 521   if (p->_verifier_constraints != NULL) {
 522     for (int i = 0; i < p->_verifier_constraints->length(); i++) {
 523       DumpTimeClassInfo::DTVerifierConstraint constraint = p->_verifier_constraints->at(i);
 524       if (constraint._name != NULL ) {
 525         constraint._name->decrement_refcount();
 526       }
 527       if (constraint._from_name != NULL ) {
 528         constraint._from_name->decrement_refcount();
 529       }
 530     }
 531     FREE_C_HEAP_ARRAY(DumpTimeClassInfo::DTVerifierConstraint, p->_verifier_constraints);
 532     p->_verifier_constraints = NULL;
 533     FREE_C_HEAP_ARRAY(char, p->_verifier_constraint_flags);
 534     p->_verifier_constraint_flags = NULL;
 535   }
 536   if (p->_loader_constraints != NULL) {
 537     for (int i = 0; i < p->_loader_constraints->length(); i++) {
 538       DumpTimeClassInfo::DTLoaderConstraint ld =  p->_loader_constraints->at(i);
 539       if (ld._name != NULL) {
 540         ld._name->decrement_refcount();
 541       }
 542     }
 543     FREE_C_HEAP_ARRAY(DumpTimeClassInfo::DTLoaderConstraint, p->_loader_constraints);
 544     p->_loader_constraints = NULL;
 545   }
 546   _dumptime_table->remove(k);
 547 }
 548 
 549 void SystemDictionaryShared::handle_class_unloading(InstanceKlass* klass) {
 550   if (Arguments::is_dumping_archive()) {
 551     remove_dumptime_info(klass);
 552   }
 553 
 554   if (_unregistered_classes_table != NULL) {
 555     // Remove the class from _unregistered_classes_table: keep the entry but
 556     // set it to NULL. This ensure no classes with the same name can be
 557     // added again.
 558     MutexLocker ml(Thread::current(), UnregisteredClassesTable_lock);
 559     InstanceKlass** v = _unregistered_classes_table->get(klass->name());
 560     if (v != NULL) {
 561       *v = NULL;
 562     }
 563   }
 564 
 565   if (ClassListWriter::is_enabled()) {
 566     ClassListWriter cw;
 567     cw.handle_class_unloading((const InstanceKlass*)klass);
 568   }
 569 }
 570 
 571 // Check if a class or any of its supertypes has been redefined.
 572 bool SystemDictionaryShared::has_been_redefined(InstanceKlass* k) {
 573   if (k->has_been_redefined()) {
 574     return true;
 575   }
 576   if (k->java_super() != NULL && has_been_redefined(k->java_super())) {
 577     return true;
 578   }
 579   Array<InstanceKlass*>* interfaces = k->local_interfaces();
 580   int len = interfaces->length();
 581   for (int i = 0; i < len; i++) {
 582     if (has_been_redefined(interfaces->at(i))) {
 583       return true;
 584     }
 585   }
 586   return false;
 587 }
 588 
 589 // k is a class before relocating by ArchiveBuilder
 590 void SystemDictionaryShared::validate_before_archiving(InstanceKlass* k) {
 591   ResourceMark rm;
 592   const char* name = k->name()->as_C_string();
 593   DumpTimeClassInfo* info = _dumptime_table->get(k);
 594   assert(_no_class_loading_should_happen, "class loading must be disabled");
 595   guarantee(info != NULL, "Class %s must be entered into _dumptime_table", name);
 596   guarantee(!info->is_excluded(), "Should not attempt to archive excluded class %s", name);
 597   if (is_builtin(k)) {
 598     if (k->is_hidden()) {
 599       assert(is_registered_lambda_proxy_class(k), "unexpected hidden class %s", name);
 600     }
 601     guarantee(!k->is_shared_unregistered_class(),
 602               "Class loader type must be set for BUILTIN class %s", name);
 603 
 604   } else {
 605     guarantee(k->is_shared_unregistered_class(),
 606               "Class loader type must not be set for UNREGISTERED class %s", name);
 607   }
 608 }
 609 
 610 class UnregisteredClassesDuplicationChecker : StackObj {
 611   GrowableArray<InstanceKlass*> _list;
 612   Thread* _thread;
 613 public:
 614   UnregisteredClassesDuplicationChecker() : _thread(Thread::current()) {}
 615 
 616   bool do_entry(InstanceKlass* k, DumpTimeClassInfo& info) {
 617     if (!SystemDictionaryShared::is_builtin(k)) {
 618       _list.append(k);
 619     }
 620     return true;  // keep on iterating
 621   }
 622 
 623   static int compare_by_loader(InstanceKlass** a, InstanceKlass** b) {
 624     ClassLoaderData* loader_a = a[0]->class_loader_data();
 625     ClassLoaderData* loader_b = b[0]->class_loader_data();
 626 
 627     if (loader_a != loader_b) {
 628       return intx(loader_a) - intx(loader_b);
 629     } else {
 630       return intx(a[0]) - intx(b[0]);
 631     }
 632   }
 633 
 634   void mark_duplicated_classes() {
 635     // Two loaders may load two identical or similar hierarchies of classes. If we
 636     // check for duplication in random order, we may end up excluding important base classes
 637     // in both hierarchies, causing most of the classes to be excluded.
 638     // We sort the classes by their loaders. This way we're likely to archive
 639     // all classes in the one of the two hierarchies.
 640     _list.sort(compare_by_loader);
 641     for (int i = 0; i < _list.length(); i++) {
 642       InstanceKlass* k = _list.at(i);
 643       bool i_am_first = SystemDictionaryShared::add_unregistered_class(_thread, k);
 644       if (!i_am_first) {
 645         SystemDictionaryShared::warn_excluded(k, "Duplicated unregistered class");
 646         SystemDictionaryShared::set_excluded_locked(k);
 647       }
 648     }
 649   }
 650 };
 651 
 652 class ExcludeDumpTimeSharedClasses : StackObj {
 653 public:
 654   bool do_entry(InstanceKlass* k, DumpTimeClassInfo& info) {
 655     SystemDictionaryShared::check_for_exclusion(k, &info);
 656     return true; // keep on iterating
 657   }
 658 };
 659 
 660 void SystemDictionaryShared::check_excluded_classes() {
 661   assert(no_class_loading_should_happen(), "sanity");
 662   assert_lock_strong(DumpTimeTable_lock);
 663 
 664   if (DynamicDumpSharedSpaces) {
 665     // Do this first -- if a base class is excluded due to duplication,
 666     // all of its subclasses will also be excluded by ExcludeDumpTimeSharedClasses
 667     ResourceMark rm;
 668     UnregisteredClassesDuplicationChecker dup_checker;
 669     _dumptime_table->iterate(&dup_checker);
 670     dup_checker.mark_duplicated_classes();
 671   }
 672 
 673   ExcludeDumpTimeSharedClasses excl;
 674   _dumptime_table->iterate(&excl);
 675   _dumptime_table->update_counts();
 676 
 677   cleanup_lambda_proxy_class_dictionary();
 678 }
 679 
 680 bool SystemDictionaryShared::is_excluded_class(InstanceKlass* k) {
 681   assert(_no_class_loading_should_happen, "sanity");
 682   assert_lock_strong(DumpTimeTable_lock);
 683   Arguments::assert_is_dumping_archive();
 684   DumpTimeClassInfo* p = find_or_allocate_info_for_locked(k);
 685   return (p == NULL) ? true : p->is_excluded();
 686 }
 687 
 688 void SystemDictionaryShared::set_excluded_locked(InstanceKlass* k) {
 689   assert_lock_strong(DumpTimeTable_lock);
 690   Arguments::assert_is_dumping_archive();
 691   DumpTimeClassInfo* info = find_or_allocate_info_for_locked(k);
 692   if (info != NULL) {
 693     info->set_excluded();
 694   }
 695 }
 696 
 697 void SystemDictionaryShared::set_excluded(InstanceKlass* k) {
 698   Arguments::assert_is_dumping_archive();
 699   DumpTimeClassInfo* info = find_or_allocate_info_for(k);
 700   if (info != NULL) {
 701     info->set_excluded();
 702   }
 703 }
 704 
 705 void SystemDictionaryShared::set_class_has_failed_verification(InstanceKlass* ik) {
 706   Arguments::assert_is_dumping_archive();
 707   DumpTimeClassInfo* p = find_or_allocate_info_for(ik);
 708   if (p != NULL) {
 709     p->set_failed_verification();
 710   }
 711 }
 712 
 713 bool SystemDictionaryShared::has_class_failed_verification(InstanceKlass* ik) {
 714   Arguments::assert_is_dumping_archive();
 715   if (_dumptime_table == NULL) {
 716     assert(DynamicDumpSharedSpaces, "sanity");
 717     assert(ik->is_shared(), "must be a shared class in the static archive");
 718     return false;
 719   }
 720   DumpTimeClassInfo* p = _dumptime_table->get(ik);
 721   return (p == NULL) ? false : p->failed_verification();
 722 }
 723 
 724 class IterateDumpTimeSharedClassTable : StackObj {
 725   MetaspaceClosure *_it;
 726 public:
 727   IterateDumpTimeSharedClassTable(MetaspaceClosure* it) : _it(it) {}
 728 
 729   bool do_entry(InstanceKlass* k, DumpTimeClassInfo& info) {
 730     assert_lock_strong(DumpTimeTable_lock);
 731     if (k->is_loader_alive() && !info.is_excluded()) {
 732       info.metaspace_pointers_do(_it);
 733     }
 734     return true; // keep on iterating
 735   }
 736 };
 737 
 738 class IterateDumpTimeLambdaProxyClassDictionary : StackObj {
 739   MetaspaceClosure *_it;
 740 public:
 741   IterateDumpTimeLambdaProxyClassDictionary(MetaspaceClosure* it) : _it(it) {}
 742 
 743   bool do_entry(LambdaProxyClassKey& key, DumpTimeLambdaProxyClassInfo& info) {
 744     assert_lock_strong(DumpTimeTable_lock);
 745     if (key.caller_ik()->is_loader_alive()) {
 746       info.metaspace_pointers_do(_it);
 747       key.metaspace_pointers_do(_it);
 748     }
 749     return true; // keep on iterating
 750   }
 751 };
 752 
 753 void SystemDictionaryShared::dumptime_classes_do(class MetaspaceClosure* it) {
 754   assert_lock_strong(DumpTimeTable_lock);
 755   IterateDumpTimeSharedClassTable iter(it);
 756   _dumptime_table->iterate(&iter);
 757   if (_dumptime_lambda_proxy_class_dictionary != NULL) {
 758     IterateDumpTimeLambdaProxyClassDictionary iter_lambda(it);
 759     _dumptime_lambda_proxy_class_dictionary->iterate(&iter_lambda);
 760   }
 761 }
 762 
 763 bool SystemDictionaryShared::add_verification_constraint(InstanceKlass* k, Symbol* name,
 764          Symbol* from_name, bool from_field_is_protected, bool from_is_array, bool from_is_object) {
 765   Arguments::assert_is_dumping_archive();
 766   DumpTimeClassInfo* info = find_or_allocate_info_for(k);
 767   if (info != NULL) {
 768     info->add_verification_constraint(k, name, from_name, from_field_is_protected,
 769                                       from_is_array, from_is_object);
 770   } else {
 771     return true;
 772   }
 773   if (DynamicDumpSharedSpaces) {
 774     // For dynamic dumping, we can resolve all the constraint classes for all class loaders during
 775     // the initial run prior to creating the archive before vm exit. We will also perform verification
 776     // check when running with the archive.
 777     return false;
 778   } else {
 779     if (is_builtin(k)) {
 780       // For builtin class loaders, we can try to complete the verification check at dump time,
 781       // because we can resolve all the constraint classes. We will also perform verification check
 782       // when running with the archive.
 783       return false;
 784     } else {
 785       // For non-builtin class loaders, we cannot complete the verification check at dump time,
 786       // because at dump time we don't know how to resolve classes for such loaders.
 787       return true;
 788     }
 789   }
 790 }
 791 
 792 void SystemDictionaryShared::add_to_dump_time_lambda_proxy_class_dictionary(LambdaProxyClassKey& key,
 793                                                            InstanceKlass* proxy_klass) {
 794   assert_lock_strong(DumpTimeTable_lock);
 795   if (_dumptime_lambda_proxy_class_dictionary == NULL) {
 796     _dumptime_lambda_proxy_class_dictionary =
 797       new (ResourceObj::C_HEAP, mtClass) DumpTimeLambdaProxyClassDictionary;
 798   }
 799   DumpTimeLambdaProxyClassInfo* lambda_info = _dumptime_lambda_proxy_class_dictionary->get(key);
 800   if (lambda_info == NULL) {
 801     DumpTimeLambdaProxyClassInfo info;
 802     info.add_proxy_klass(proxy_klass);
 803     _dumptime_lambda_proxy_class_dictionary->put(key, info);
 804     //lambda_info = _dumptime_lambda_proxy_class_dictionary->get(key);
 805     //assert(lambda_info->_proxy_klass == proxy_klass, "must be"); // debug only -- remove
 806     ++_dumptime_lambda_proxy_class_dictionary->_count;
 807   } else {
 808     lambda_info->add_proxy_klass(proxy_klass);
 809   }
 810 }
 811 
 812 void SystemDictionaryShared::add_lambda_proxy_class(InstanceKlass* caller_ik,
 813                                                     InstanceKlass* lambda_ik,
 814                                                     Symbol* invoked_name,
 815                                                     Symbol* invoked_type,
 816                                                     Symbol* method_type,
 817                                                     Method* member_method,
 818                                                     Symbol* instantiated_method_type,
 819                                                     TRAPS) {
 820 
 821   assert(caller_ik->class_loader() == lambda_ik->class_loader(), "mismatched class loader");
 822   assert(caller_ik->class_loader_data() == lambda_ik->class_loader_data(), "mismatched class loader data");
 823   assert(java_lang_Class::class_data(lambda_ik->java_mirror()) == NULL, "must not have class data");
 824 
 825   MutexLocker ml(DumpTimeTable_lock, Mutex::_no_safepoint_check_flag);
 826 
 827   lambda_ik->assign_class_loader_type();
 828   lambda_ik->set_shared_classpath_index(caller_ik->shared_classpath_index());
 829   InstanceKlass* nest_host = caller_ik->nest_host(CHECK);
 830   assert(nest_host != NULL, "unexpected NULL nest_host");
 831 
 832   DumpTimeClassInfo* info = _dumptime_table->get(lambda_ik);
 833   if (info != NULL && !lambda_ik->is_non_strong_hidden() && is_builtin(lambda_ik) && is_builtin(caller_ik)
 834       // Don't include the lambda proxy if its nest host is not in the "linked" state.
 835       && nest_host->is_linked()) {
 836     // Set _is_archived_lambda_proxy in DumpTimeClassInfo so that the lambda_ik
 837     // won't be excluded during dumping of shared archive. See ExcludeDumpTimeSharedClasses.
 838     info->_is_archived_lambda_proxy = true;
 839     info->set_nest_host(nest_host);
 840 
 841     LambdaProxyClassKey key(caller_ik,
 842                             invoked_name,
 843                             invoked_type,
 844                             method_type,
 845                             member_method,
 846                             instantiated_method_type);
 847     add_to_dump_time_lambda_proxy_class_dictionary(key, lambda_ik);
 848   }
 849 }
 850 
 851 InstanceKlass* SystemDictionaryShared::get_shared_lambda_proxy_class(InstanceKlass* caller_ik,
 852                                                                      Symbol* invoked_name,
 853                                                                      Symbol* invoked_type,
 854                                                                      Symbol* method_type,
 855                                                                      Method* member_method,
 856                                                                      Symbol* instantiated_method_type) {
 857   MutexLocker ml(CDSLambda_lock, Mutex::_no_safepoint_check_flag);
 858   LambdaProxyClassKey key(caller_ik, invoked_name, invoked_type,
 859                           method_type, member_method, instantiated_method_type);
 860   const RunTimeLambdaProxyClassInfo* info = _lambda_proxy_class_dictionary.lookup(&key, key.hash(), 0);
 861   if (info == NULL) {
 862     // Try lookup from the dynamic lambda proxy class dictionary.
 863     info = _dynamic_lambda_proxy_class_dictionary.lookup(&key, key.hash(), 0);
 864   }
 865   InstanceKlass* proxy_klass = NULL;
 866   if (info != NULL) {
 867     InstanceKlass* curr_klass = info->proxy_klass_head();
 868     InstanceKlass* prev_klass = curr_klass;
 869     if (curr_klass->lambda_proxy_is_available()) {
 870       while (curr_klass->next_link() != NULL) {
 871         prev_klass = curr_klass;
 872         curr_klass = InstanceKlass::cast(curr_klass->next_link());
 873       }
 874       assert(curr_klass->is_hidden(), "must be");
 875       assert(curr_klass->lambda_proxy_is_available(), "must be");
 876 
 877       prev_klass->set_next_link(NULL);
 878       proxy_klass = curr_klass;
 879       proxy_klass->clear_lambda_proxy_is_available();
 880       if (log_is_enabled(Debug, cds)) {
 881         ResourceMark rm;
 882         log_debug(cds)("Loaded lambda proxy: %s ", proxy_klass->external_name());
 883       }
 884     } else {
 885       if (log_is_enabled(Debug, cds)) {
 886         ResourceMark rm;
 887         log_debug(cds)("Used all archived lambda proxy classes for: %s %s%s",
 888                        caller_ik->external_name(), invoked_name->as_C_string(), invoked_type->as_C_string());
 889       }
 890     }
 891   }
 892   return proxy_klass;
 893 }
 894 
 895 InstanceKlass* SystemDictionaryShared::get_shared_nest_host(InstanceKlass* lambda_ik) {
 896   assert(!DumpSharedSpaces && UseSharedSpaces, "called at run time with CDS enabled only");
 897   RunTimeClassInfo* record = RunTimeClassInfo::get_for(lambda_ik);
 898   return record->nest_host();
 899 }
 900 
 901 InstanceKlass* SystemDictionaryShared::prepare_shared_lambda_proxy_class(InstanceKlass* lambda_ik,
 902                                                                          InstanceKlass* caller_ik, TRAPS) {
 903   Handle class_loader(THREAD, caller_ik->class_loader());
 904   Handle protection_domain;
 905   PackageEntry* pkg_entry = caller_ik->package();
 906   if (caller_ik->class_loader() != NULL) {
 907     protection_domain = CDSProtectionDomain::init_security_info(class_loader, caller_ik, pkg_entry, CHECK_NULL);
 908   }
 909 
 910   InstanceKlass* shared_nest_host = get_shared_nest_host(lambda_ik);
 911   assert(shared_nest_host != NULL, "unexpected NULL _nest_host");
 912 
 913   InstanceKlass* loaded_lambda =
 914     SystemDictionary::load_shared_lambda_proxy_class(lambda_ik, class_loader, protection_domain, pkg_entry, CHECK_NULL);
 915 
 916   if (loaded_lambda == NULL) {
 917     return NULL;
 918   }
 919 
 920   // Ensures the nest host is the same as the lambda proxy's
 921   // nest host recorded at dump time.
 922   InstanceKlass* nest_host = caller_ik->nest_host(THREAD);
 923   assert(nest_host == shared_nest_host, "mismatched nest host");
 924 
 925   EventClassLoad class_load_start_event;
 926   {
 927     MutexLocker mu_r(THREAD, Compile_lock);
 928 
 929     // Add to class hierarchy, and do possible deoptimizations.
 930     SystemDictionary::add_to_hierarchy(loaded_lambda);
 931     // But, do not add to dictionary.
 932   }
 933   loaded_lambda->link_class(CHECK_NULL);
 934   // notify jvmti
 935   if (JvmtiExport::should_post_class_load()) {
 936     JvmtiExport::post_class_load(THREAD, loaded_lambda);
 937   }
 938   if (class_load_start_event.should_commit()) {
 939     SystemDictionary::post_class_load_event(&class_load_start_event, loaded_lambda, ClassLoaderData::class_loader_data(class_loader()));
 940   }
 941 
 942   loaded_lambda->initialize(CHECK_NULL);
 943 
 944   return loaded_lambda;
 945 }
 946 
 947 void SystemDictionaryShared::check_verification_constraints(InstanceKlass* klass,
 948                                                             TRAPS) {
 949   assert(!DumpSharedSpaces && UseSharedSpaces, "called at run time with CDS enabled only");
 950   RunTimeClassInfo* record = RunTimeClassInfo::get_for(klass);
 951 
 952   int length = record->_num_verifier_constraints;
 953   if (length > 0) {
 954     for (int i = 0; i < length; i++) {
 955       RunTimeClassInfo::RTVerifierConstraint* vc = record->verifier_constraint_at(i);
 956       Symbol* name      = vc->name();
 957       Symbol* from_name = vc->from_name();
 958       char c            = record->verifier_constraint_flag(i);
 959 
 960       if (log_is_enabled(Trace, cds, verification)) {
 961         ResourceMark rm(THREAD);
 962         log_trace(cds, verification)("check_verification_constraint: %s: %s must be subclass of %s [0x%x]",
 963                                      klass->external_name(), from_name->as_klass_external_name(),
 964                                      name->as_klass_external_name(), c);
 965       }
 966 
 967       bool from_field_is_protected = (c & SystemDictionaryShared::FROM_FIELD_IS_PROTECTED) ? true : false;
 968       bool from_is_array           = (c & SystemDictionaryShared::FROM_IS_ARRAY)           ? true : false;
 969       bool from_is_object          = (c & SystemDictionaryShared::FROM_IS_OBJECT)          ? true : false;
 970 
 971       bool ok = VerificationType::resolve_and_check_assignability(klass, name,
 972          from_name, from_field_is_protected, from_is_array, from_is_object, CHECK);
 973       if (!ok) {
 974         ResourceMark rm(THREAD);
 975         stringStream ss;
 976 
 977         ss.print_cr("Bad type on operand stack");
 978         ss.print_cr("Exception Details:");
 979         ss.print_cr("  Location:\n    %s", klass->name()->as_C_string());
 980         ss.print_cr("  Reason:\n    Type '%s' is not assignable to '%s'",
 981                     from_name->as_quoted_ascii(), name->as_quoted_ascii());
 982         THROW_MSG(vmSymbols::java_lang_VerifyError(), ss.as_string());
 983       }
 984     }
 985   }
 986 }
 987 
 988 static oop get_class_loader_by(char type) {
 989   if (type == (char)ClassLoader::BOOT_LOADER) {
 990     return (oop)NULL;
 991   } else if (type == (char)ClassLoader::PLATFORM_LOADER) {
 992     return SystemDictionary::java_platform_loader();
 993   } else {
 994     assert (type == (char)ClassLoader::APP_LOADER, "Sanity");
 995     return SystemDictionary::java_system_loader();
 996   }
 997 }
 998 
 999 // Record class loader constraints that are checked inside
1000 // InstanceKlass::link_class(), so that these can be checked quickly
1001 // at runtime without laying out the vtable/itables.
1002 void SystemDictionaryShared::record_linking_constraint(Symbol* name, InstanceKlass* klass,
1003                                                     Handle loader1, Handle loader2) {
1004   // A linking constraint check is executed when:
1005   //   - klass extends or implements type S
1006   //   - klass overrides method S.M(...) with X.M
1007   //     - If klass defines the method M, X is
1008   //       the same as klass.
1009   //     - If klass does not define the method M,
1010   //       X must be a supertype of klass and X.M is
1011   //       a default method defined by X.
1012   //   - loader1 = X->class_loader()
1013   //   - loader2 = S->class_loader()
1014   //   - loader1 != loader2
1015   //   - M's paramater(s) include an object type T
1016   // We require that
1017   //   - whenever loader1 and loader2 try to
1018   //     resolve the type T, they must always resolve to
1019   //     the same InstanceKlass.
1020   // NOTE: type T may or may not be currently resolved in
1021   // either of these two loaders. The check itself does not
1022   // try to resolve T.
1023   oop klass_loader = klass->class_loader();
1024 
1025   if (!is_system_class_loader(klass_loader) &&
1026       !is_platform_class_loader(klass_loader)) {
1027     // If klass is loaded by system/platform loaders, we can
1028     // guarantee that klass and S must be loaded by the same
1029     // respective loader between dump time and run time, and
1030     // the exact same check on (name, loader1, loader2) will
1031     // be executed. Hence, we can cache this check and execute
1032     // it at runtime without walking the vtable/itables.
1033     //
1034     // This cannot be guaranteed for classes loaded by other
1035     // loaders, so we bail.
1036     return;
1037   }
1038 
1039   if (DumpSharedSpaces && !is_builtin(klass)) {
1040     // During static dump, unregistered classes (those intended for
1041     // custom loaders) are loaded by the boot loader. Need to
1042     // exclude these for the same reason as above.
1043     // This should be fixed by JDK-8261941.
1044     return;
1045   }
1046 
1047   assert(klass_loader != NULL, "should not be called for boot loader");
1048   assert(loader1 != loader2, "must be");
1049 
1050   if (DynamicDumpSharedSpaces && Thread::current()->is_VM_thread()) {
1051     // We are re-laying out the vtable/itables of the *copy* of
1052     // a class during the final stage of dynamic dumping. The
1053     // linking constraints for this class has already been recorded.
1054     return;
1055   }
1056   assert(!Thread::current()->is_VM_thread(), "must be");
1057 
1058   Arguments::assert_is_dumping_archive();
1059   DumpTimeClassInfo* info = find_or_allocate_info_for(klass);
1060   if (info != NULL) {
1061     info->record_linking_constraint(name, loader1, loader2);
1062   }
1063 }
1064 
1065 // returns true IFF there's no need to re-initialize the i/v-tables for klass for
1066 // the purpose of checking class loader constraints.
1067 bool SystemDictionaryShared::check_linking_constraints(Thread* current, InstanceKlass* klass) {
1068   assert(!DumpSharedSpaces && UseSharedSpaces, "called at run time with CDS enabled only");
1069   LogTarget(Info, class, loader, constraints) log;
1070   if (klass->is_shared_boot_class()) {
1071     // No class loader constraint check performed for boot classes.
1072     return true;
1073   }
1074   if (klass->is_shared_platform_class() || klass->is_shared_app_class()) {
1075     RunTimeClassInfo* info = RunTimeClassInfo::get_for(klass);
1076     assert(info != NULL, "Sanity");
1077     if (info->_num_loader_constraints > 0) {
1078       HandleMark hm(current);
1079       for (int i = 0; i < info->_num_loader_constraints; i++) {
1080         RunTimeClassInfo::RTLoaderConstraint* lc = info->loader_constraint_at(i);
1081         Symbol* name = lc->constraint_name();
1082         Handle loader1(current, get_class_loader_by(lc->_loader_type1));
1083         Handle loader2(current, get_class_loader_by(lc->_loader_type2));
1084         if (log.is_enabled()) {
1085           ResourceMark rm(current);
1086           log.print("[CDS add loader constraint for class %s symbol %s loader[0] %s loader[1] %s",
1087                     klass->external_name(), name->as_C_string(),
1088                     ClassLoaderData::class_loader_data(loader1())->loader_name_and_id(),
1089                     ClassLoaderData::class_loader_data(loader2())->loader_name_and_id());
1090         }
1091         if (!SystemDictionary::add_loader_constraint(name, klass, loader1, loader2)) {
1092           // Loader constraint violation has been found. The caller
1093           // will re-layout the vtable/itables to produce the correct
1094           // exception.
1095           if (log.is_enabled()) {
1096             log.print(" failed]");
1097           }
1098           return false;
1099         }
1100         if (log.is_enabled()) {
1101             log.print(" succeeded]");
1102         }
1103       }
1104       return true; // for all recorded constraints added successully.
1105     }
1106   }
1107   if (log.is_enabled()) {
1108     ResourceMark rm(current);
1109     log.print("[CDS has not recorded loader constraint for class %s]", klass->external_name());
1110   }
1111   return false;
1112 }
1113 
1114 bool SystemDictionaryShared::is_supported_invokedynamic(BootstrapInfo* bsi) {
1115   LogTarget(Debug, cds, lambda) log;
1116   if (bsi->arg_values() == NULL || !bsi->arg_values()->is_objArray()) {
1117     if (log.is_enabled()) {
1118       LogStream log_stream(log);
1119       log.print("bsi check failed");
1120       log.print("    bsi->arg_values().not_null() %d", bsi->arg_values().not_null());
1121       if (bsi->arg_values().not_null()) {
1122         log.print("    bsi->arg_values()->is_objArray() %d", bsi->arg_values()->is_objArray());
1123         bsi->print_msg_on(&log_stream);
1124       }
1125     }
1126     return false;
1127   }
1128 
1129   Handle bsm = bsi->bsm();
1130   if (bsm.is_null() || !java_lang_invoke_DirectMethodHandle::is_instance(bsm())) {
1131     if (log.is_enabled()) {
1132       log.print("bsm check failed");
1133       log.print("    bsm.is_null() %d", bsm.is_null());
1134       log.print("    java_lang_invoke_DirectMethodHandle::is_instance(bsm()) %d",
1135         java_lang_invoke_DirectMethodHandle::is_instance(bsm()));
1136     }
1137     return false;
1138   }
1139 
1140   oop mn = java_lang_invoke_DirectMethodHandle::member(bsm());
1141   Method* method = java_lang_invoke_MemberName::vmtarget(mn);
1142   if (method->klass_name()->equals("java/lang/invoke/LambdaMetafactory") &&
1143       method->name()->equals("metafactory") &&
1144       method->signature()->equals("(Ljava/lang/invoke/MethodHandles$Lookup;Ljava/lang/String;Ljava/lang/invoke/MethodType;Ljava/lang/invoke/MethodType;Ljava/lang/invoke/MethodHandle;Ljava/lang/invoke/MethodType;)Ljava/lang/invoke/CallSite;")) {
1145       return true;
1146   } else {
1147     if (log.is_enabled()) {
1148       ResourceMark rm;
1149       log.print("method check failed");
1150       log.print("    klass_name() %s", method->klass_name()->as_C_string());
1151       log.print("    name() %s", method->name()->as_C_string());
1152       log.print("    signature() %s", method->signature()->as_C_string());
1153     }
1154   }
1155 
1156   return false;
1157 }
1158 
1159 class EstimateSizeForArchive : StackObj {
1160   size_t _shared_class_info_size;
1161   int _num_builtin_klasses;
1162   int _num_unregistered_klasses;
1163 
1164 public:
1165   EstimateSizeForArchive() {
1166     _shared_class_info_size = 0;
1167     _num_builtin_klasses = 0;
1168     _num_unregistered_klasses = 0;
1169   }
1170 
1171   bool do_entry(InstanceKlass* k, DumpTimeClassInfo& info) {
1172     if (!info.is_excluded()) {
1173       size_t byte_size = RunTimeClassInfo::byte_size(info._klass, info.num_verifier_constraints(), info.num_loader_constraints());
1174       _shared_class_info_size += align_up(byte_size, SharedSpaceObjectAlignment);
1175     }
1176     return true; // keep on iterating
1177   }
1178 
1179   size_t total() {
1180     return _shared_class_info_size;
1181   }
1182 };
1183 
1184 size_t SystemDictionaryShared::estimate_size_for_archive() {
1185   EstimateSizeForArchive est;
1186   _dumptime_table->iterate(&est);
1187   size_t total_size = est.total() +
1188     CompactHashtableWriter::estimate_size(_dumptime_table->count_of(true)) +
1189     CompactHashtableWriter::estimate_size(_dumptime_table->count_of(false));
1190   if (_dumptime_lambda_proxy_class_dictionary != NULL) {
1191     size_t bytesize = align_up(sizeof(RunTimeLambdaProxyClassInfo), SharedSpaceObjectAlignment);
1192     total_size +=
1193       (bytesize * _dumptime_lambda_proxy_class_dictionary->_count) +
1194       CompactHashtableWriter::estimate_size(_dumptime_lambda_proxy_class_dictionary->_count);
1195   } else {
1196     total_size += CompactHashtableWriter::estimate_size(0);
1197   }
1198   return total_size;
1199 }
1200 
1201 unsigned int SystemDictionaryShared::hash_for_shared_dictionary(address ptr) {
1202   if (ArchiveBuilder::is_active()) {
1203     uintx offset = ArchiveBuilder::current()->any_to_offset(ptr);
1204     unsigned int hash = primitive_hash<uintx>(offset);
1205     DEBUG_ONLY({
1206         if (MetaspaceObj::is_shared((const MetaspaceObj*)ptr)) {
1207           assert(hash == SystemDictionaryShared::hash_for_shared_dictionary_quick(ptr), "must be");
1208         }
1209       });
1210     return hash;
1211   } else {
1212     return SystemDictionaryShared::hash_for_shared_dictionary_quick(ptr);
1213   }
1214 }
1215 
1216 class CopyLambdaProxyClassInfoToArchive : StackObj {
1217   CompactHashtableWriter* _writer;
1218   ArchiveBuilder* _builder;
1219 public:
1220   CopyLambdaProxyClassInfoToArchive(CompactHashtableWriter* writer)
1221   : _writer(writer), _builder(ArchiveBuilder::current()) {}
1222   bool do_entry(LambdaProxyClassKey& key, DumpTimeLambdaProxyClassInfo& info) {
1223     // In static dump, info._proxy_klasses->at(0) is already relocated to point to the archived class
1224     // (not the original class).
1225     //
1226     // The following check has been moved to SystemDictionaryShared::check_excluded_classes(), which
1227     // happens before the classes are copied.
1228     //
1229     // if (SystemDictionaryShared::is_excluded_class(info._proxy_klasses->at(0))) {
1230     //  return true;
1231     //}
1232     ResourceMark rm;
1233     log_info(cds,dynamic)("Archiving hidden %s", info._proxy_klasses->at(0)->external_name());
1234     size_t byte_size = sizeof(RunTimeLambdaProxyClassInfo);
1235     RunTimeLambdaProxyClassInfo* runtime_info =
1236         (RunTimeLambdaProxyClassInfo*)ArchiveBuilder::ro_region_alloc(byte_size);
1237     runtime_info->init(key, info);
1238     unsigned int hash = runtime_info->hash();
1239     u4 delta = _builder->any_to_offset_u4((void*)runtime_info);
1240     _writer->add(hash, delta);
1241     return true;
1242   }
1243 };
1244 
1245 class AdjustLambdaProxyClassInfo : StackObj {
1246 public:
1247   AdjustLambdaProxyClassInfo() {}
1248   bool do_entry(LambdaProxyClassKey& key, DumpTimeLambdaProxyClassInfo& info) {
1249     int len = info._proxy_klasses->length();
1250     if (len > 1) {
1251       for (int i = 0; i < len-1; i++) {
1252         InstanceKlass* ok0 = info._proxy_klasses->at(i+0); // this is original klass
1253         InstanceKlass* ok1 = info._proxy_klasses->at(i+1); // this is original klass
1254         assert(ArchiveBuilder::current()->is_in_buffer_space(ok0), "must be");
1255         assert(ArchiveBuilder::current()->is_in_buffer_space(ok1), "must be");
1256         InstanceKlass* bk0 = ok0;
1257         InstanceKlass* bk1 = ok1;
1258         assert(bk0->next_link() == 0, "must be called after Klass::remove_unshareable_info()");
1259         assert(bk1->next_link() == 0, "must be called after Klass::remove_unshareable_info()");
1260         bk0->set_next_link(bk1);
1261         bk1->set_lambda_proxy_is_available();
1262         ArchivePtrMarker::mark_pointer(bk0->next_link_addr());
1263       }
1264     }
1265     info._proxy_klasses->at(0)->set_lambda_proxy_is_available();
1266 
1267     return true;
1268   }
1269 };
1270 
1271 class CopySharedClassInfoToArchive : StackObj {
1272   CompactHashtableWriter* _writer;
1273   bool _is_builtin;
1274   ArchiveBuilder *_builder;
1275 public:
1276   CopySharedClassInfoToArchive(CompactHashtableWriter* writer,
1277                                bool is_builtin)
1278     : _writer(writer), _is_builtin(is_builtin), _builder(ArchiveBuilder::current()) {}
1279 
1280   bool do_entry(InstanceKlass* k, DumpTimeClassInfo& info) {
1281     if (!info.is_excluded() && info.is_builtin() == _is_builtin) {
1282       size_t byte_size = RunTimeClassInfo::byte_size(info._klass, info.num_verifier_constraints(), info.num_loader_constraints());
1283       RunTimeClassInfo* record;
1284       record = (RunTimeClassInfo*)ArchiveBuilder::ro_region_alloc(byte_size);
1285       record->init(info);
1286 
1287       unsigned int hash;
1288       Symbol* name = info._klass->name();
1289       hash = SystemDictionaryShared::hash_for_shared_dictionary((address)name);
1290       u4 delta = _builder->buffer_to_offset_u4((address)record);
1291       if (_is_builtin && info._klass->is_hidden()) {
1292         // skip
1293       } else {
1294         _writer->add(hash, delta);
1295       }
1296       if (log_is_enabled(Trace, cds, hashtables)) {
1297         ResourceMark rm;
1298         log_trace(cds,hashtables)("%s dictionary: %s", (_is_builtin ? "builtin" : "unregistered"), info._klass->external_name());
1299       }
1300 
1301       // Save this for quick runtime lookup of InstanceKlass* -> RunTimeClassInfo*
1302       RunTimeClassInfo::set_for(info._klass, record);
1303     }
1304     return true; // keep on iterating
1305   }
1306 };
1307 
1308 void SystemDictionaryShared::write_lambda_proxy_class_dictionary(LambdaProxyClassDictionary *dictionary) {
1309   CompactHashtableStats stats;
1310   dictionary->reset();
1311   CompactHashtableWriter writer(_dumptime_lambda_proxy_class_dictionary->_count, &stats);
1312   CopyLambdaProxyClassInfoToArchive copy(&writer);
1313   _dumptime_lambda_proxy_class_dictionary->iterate(&copy);
1314   writer.dump(dictionary, "lambda proxy class dictionary");
1315 }
1316 
1317 void SystemDictionaryShared::write_dictionary(RunTimeSharedDictionary* dictionary,
1318                                               bool is_builtin) {
1319   CompactHashtableStats stats;
1320   dictionary->reset();
1321   CompactHashtableWriter writer(_dumptime_table->count_of(is_builtin), &stats);
1322   CopySharedClassInfoToArchive copy(&writer, is_builtin);
1323   assert_lock_strong(DumpTimeTable_lock);
1324   _dumptime_table->iterate(&copy);
1325   writer.dump(dictionary, is_builtin ? "builtin dictionary" : "unregistered dictionary");
1326 }
1327 
1328 void SystemDictionaryShared::write_to_archive(bool is_static_archive) {
1329   if (is_static_archive) {
1330     write_dictionary(&_builtin_dictionary, true);
1331     write_dictionary(&_unregistered_dictionary, false);
1332   } else {
1333     write_dictionary(&_dynamic_builtin_dictionary, true);
1334     write_dictionary(&_dynamic_unregistered_dictionary, false);
1335   }
1336   if (_dumptime_lambda_proxy_class_dictionary != NULL) {
1337     write_lambda_proxy_class_dictionary(&_lambda_proxy_class_dictionary);
1338   }
1339 }
1340 
1341 void SystemDictionaryShared::adjust_lambda_proxy_class_dictionary() {
1342   if (_dumptime_lambda_proxy_class_dictionary != NULL) {
1343     AdjustLambdaProxyClassInfo adjuster;
1344     _dumptime_lambda_proxy_class_dictionary->iterate(&adjuster);
1345   }
1346 }
1347 
1348 void SystemDictionaryShared::serialize_dictionary_headers(SerializeClosure* soc,
1349                                                           bool is_static_archive) {
1350   FileMapInfo *dynamic_mapinfo = FileMapInfo::dynamic_info();
1351   if (is_static_archive) {
1352     _builtin_dictionary.serialize_header(soc);
1353     _unregistered_dictionary.serialize_header(soc);
1354     if (dynamic_mapinfo == NULL || DynamicDumpSharedSpaces || (dynamic_mapinfo != NULL && UseSharedSpaces)) {
1355       _lambda_proxy_class_dictionary.serialize_header(soc);
1356     }
1357   } else {
1358     _dynamic_builtin_dictionary.serialize_header(soc);
1359     _dynamic_unregistered_dictionary.serialize_header(soc);
1360     if (DynamicDumpSharedSpaces) {
1361       _lambda_proxy_class_dictionary.serialize_header(soc);
1362     } else {
1363       _dynamic_lambda_proxy_class_dictionary.serialize_header(soc);
1364     }
1365   }
1366 }
1367 
1368 void SystemDictionaryShared::serialize_vm_classes(SerializeClosure* soc) {
1369   for (auto id : EnumRange<vmClassID>{}) {
1370     soc->do_ptr((void**)vmClasses::klass_addr_at(id));
1371   }
1372 }
1373 
1374 const RunTimeClassInfo*
1375 SystemDictionaryShared::find_record(RunTimeSharedDictionary* static_dict, RunTimeSharedDictionary* dynamic_dict, Symbol* name) {
1376   if (!UseSharedSpaces || !name->is_shared()) {
1377     // The names of all shared classes must also be a shared Symbol.
1378     return NULL;
1379   }
1380 
1381   unsigned int hash = SystemDictionaryShared::hash_for_shared_dictionary_quick(name);
1382   const RunTimeClassInfo* record = NULL;
1383   if (DynamicArchive::is_mapped()) {
1384     // Those regenerated holder classes are in dynamic archive
1385     if (name == vmSymbols::java_lang_invoke_Invokers_Holder() ||
1386         name == vmSymbols::java_lang_invoke_DirectMethodHandle_Holder() ||
1387         name == vmSymbols::java_lang_invoke_LambdaForm_Holder() ||
1388         name == vmSymbols::java_lang_invoke_DelegatingMethodHandle_Holder()) {
1389       record = dynamic_dict->lookup(name, hash, 0);
1390       if (record != nullptr) {
1391         return record;
1392       }
1393     }
1394   }
1395 
1396   if (!MetaspaceShared::is_shared_dynamic(name)) {
1397     // The names of all shared classes in the static dict must also be in the
1398     // static archive
1399     record = static_dict->lookup(name, hash, 0);
1400   }
1401 
1402   if (record == NULL && DynamicArchive::is_mapped()) {
1403     record = dynamic_dict->lookup(name, hash, 0);
1404   }
1405 
1406   return record;
1407 }
1408 
1409 InstanceKlass* SystemDictionaryShared::find_builtin_class(Symbol* name) {
1410   const RunTimeClassInfo* record = find_record(&_builtin_dictionary, &_dynamic_builtin_dictionary, name);
1411   if (record != NULL) {
1412 #ifdef ASSERT
1413     if (UseCompressedClassPointers) {
1414       CompressedKlassPointers::verify_klass_pointer(record->_klass);
1415     }
1416 #endif
1417     assert(!record->_klass->is_hidden(), "hidden class cannot be looked up by name");
1418     return record->_klass;
1419   } else {
1420     return NULL;
1421   }
1422 }
1423 
1424 void SystemDictionaryShared::update_shared_entry(InstanceKlass* k, int id) {
1425   assert(DumpSharedSpaces, "supported only when dumping");
1426   DumpTimeClassInfo* info = find_or_allocate_info_for(k);
1427   info->_id = id;
1428 }
1429 
1430 const char* class_loader_name_for_shared(Klass* k) {
1431   assert(k != nullptr, "Sanity");
1432   assert(k->is_shared(), "Must be");
1433   assert(k->is_instance_klass(), "Must be");
1434   InstanceKlass* ik = InstanceKlass::cast(k);
1435   if (ik->is_shared_boot_class()) {
1436     return "boot_loader";
1437   } else if (ik->is_shared_platform_class()) {
1438     return "platform_loader";
1439   } else if (ik->is_shared_app_class()) {
1440     return "app_loader";
1441   } else if (ik->is_shared_unregistered_class()) {
1442     return "unregistered_loader";
1443   } else {
1444     return "unknown loader";
1445   }
1446 }
1447 
1448 class SharedDictionaryPrinter : StackObj {
1449   outputStream* _st;
1450   int _index;
1451 public:
1452   SharedDictionaryPrinter(outputStream* st) : _st(st), _index(0) {}
1453 
1454   void do_value(const RunTimeClassInfo* record) {
1455     ResourceMark rm;
1456     _st->print_cr("%4d: %s %s", _index++, record->_klass->external_name(),
1457         class_loader_name_for_shared(record->_klass));
1458   }
1459   int index() const { return _index; }
1460 };
1461 
1462 class SharedLambdaDictionaryPrinter : StackObj {
1463   outputStream* _st;
1464   int _index;
1465 public:
1466   SharedLambdaDictionaryPrinter(outputStream* st, int idx) : _st(st), _index(idx) {}
1467 
1468   void do_value(const RunTimeLambdaProxyClassInfo* record) {
1469     if (record->proxy_klass_head()->lambda_proxy_is_available()) {
1470       ResourceMark rm;
1471       Klass* k = record->proxy_klass_head();
1472       while (k != nullptr) {
1473         _st->print_cr("%4d: %s %s", _index++, k->external_name(),
1474                       class_loader_name_for_shared(k));
1475         k = k->next_link();
1476       }
1477     }
1478   }
1479 };
1480 
1481 void SystemDictionaryShared::print_on(const char* prefix,
1482                                       RunTimeSharedDictionary* builtin_dictionary,
1483                                       RunTimeSharedDictionary* unregistered_dictionary,
1484                                       LambdaProxyClassDictionary* lambda_dictionary,
1485                                       outputStream* st) {
1486   st->print_cr("%sShared Dictionary", prefix);
1487   SharedDictionaryPrinter p(st);
1488   st->print_cr("%sShared Builtin Dictionary", prefix);
1489   builtin_dictionary->iterate(&p);
1490   st->print_cr("%sShared Unregistered Dictionary", prefix);
1491   unregistered_dictionary->iterate(&p);
1492   if (!lambda_dictionary->empty()) {
1493     st->print_cr("%sShared Lambda Dictionary", prefix);
1494     SharedLambdaDictionaryPrinter ldp(st, p.index());
1495     lambda_dictionary->iterate(&ldp);
1496   }
1497 }
1498 
1499 void SystemDictionaryShared::print_shared_archive(outputStream* st, bool is_static) {
1500   if (UseSharedSpaces) {
1501     if (is_static) {
1502       print_on("", &_builtin_dictionary, &_unregistered_dictionary, &_lambda_proxy_class_dictionary, st);
1503     } else {
1504       if (DynamicArchive::is_mapped()) {
1505         print_on("", &_dynamic_builtin_dictionary, &_dynamic_unregistered_dictionary,
1506                &_dynamic_lambda_proxy_class_dictionary, st);
1507       }
1508     }
1509   }
1510 }
1511 
1512 void SystemDictionaryShared::print_on(outputStream* st) {
1513   if (UseSharedSpaces) {
1514     print_on("", &_builtin_dictionary, &_unregistered_dictionary, &_lambda_proxy_class_dictionary, st);
1515     if (DynamicArchive::is_mapped()) {
1516       print_on("", &_dynamic_builtin_dictionary, &_dynamic_unregistered_dictionary,
1517                &_dynamic_lambda_proxy_class_dictionary, st);
1518     }
1519   }
1520 }
1521 
1522 void SystemDictionaryShared::print_table_statistics(outputStream* st) {
1523   if (UseSharedSpaces) {
1524     _builtin_dictionary.print_table_statistics(st, "Builtin Shared Dictionary");
1525     _unregistered_dictionary.print_table_statistics(st, "Unregistered Shared Dictionary");
1526     _lambda_proxy_class_dictionary.print_table_statistics(st, "Lambda Shared Dictionary");
1527     if (DynamicArchive::is_mapped()) {
1528       _dynamic_builtin_dictionary.print_table_statistics(st, "Dynamic Builtin Shared Dictionary");
1529       _dynamic_unregistered_dictionary.print_table_statistics(st, "Unregistered Shared Dictionary");
1530       _dynamic_lambda_proxy_class_dictionary.print_table_statistics(st, "Dynamic Lambda Shared Dictionary");
1531     }
1532   }
1533 }
1534 
1535 bool SystemDictionaryShared::is_dumptime_table_empty() {
1536   if (_dumptime_table == NULL) {
1537     return true;
1538   }
1539   _dumptime_table->update_counts();
1540   if (_dumptime_table->count_of(true) == 0 && _dumptime_table->count_of(false) == 0){
1541     return true;
1542   }
1543   return false;
1544 }
1545 
1546 class CloneDumpTimeClassTable: public StackObj {
1547   DumpTimeSharedClassTable* _table;
1548   DumpTimeSharedClassTable* _cloned_table;
1549  public:
1550   CloneDumpTimeClassTable(DumpTimeSharedClassTable* table, DumpTimeSharedClassTable* clone) :
1551                       _table(table), _cloned_table(clone) {
1552     assert(_table != NULL, "_dumptime_table is NULL");
1553     assert(_cloned_table != NULL, "_cloned_table is NULL");
1554   }
1555   bool do_entry(InstanceKlass* k, DumpTimeClassInfo& info) {
1556     if (!info.is_excluded()) {
1557       bool created;
1558       _cloned_table->put_if_absent(k, info.clone(), &created);
1559     }
1560     return true; // keep on iterating
1561   }
1562 };
1563 
1564 class CloneDumpTimeLambdaProxyClassTable: StackObj {
1565   DumpTimeLambdaProxyClassDictionary* _table;
1566   DumpTimeLambdaProxyClassDictionary* _cloned_table;
1567  public:
1568   CloneDumpTimeLambdaProxyClassTable(DumpTimeLambdaProxyClassDictionary* table,
1569                                      DumpTimeLambdaProxyClassDictionary* clone) :
1570                       _table(table), _cloned_table(clone) {
1571     assert(_table != NULL, "_dumptime_table is NULL");
1572     assert(_cloned_table != NULL, "_cloned_table is NULL");
1573   }
1574 
1575   bool do_entry(LambdaProxyClassKey& key, DumpTimeLambdaProxyClassInfo& info) {
1576     assert_lock_strong(DumpTimeTable_lock);
1577     bool created;
1578     // make copies then store in _clone_table
1579     LambdaProxyClassKey keyCopy = key;
1580     _cloned_table->put_if_absent(keyCopy, info.clone(), &created);
1581     ++ _cloned_table->_count;
1582     return true; // keep on iterating
1583   }
1584 };
1585 
1586 void SystemDictionaryShared::clone_dumptime_tables() {
1587   Arguments::assert_is_dumping_archive();
1588   assert_lock_strong(DumpTimeTable_lock);
1589   if (_dumptime_table != NULL) {
1590     assert(_cloned_dumptime_table == NULL, "_cloned_dumptime_table must be cleaned");
1591     _cloned_dumptime_table = new (ResourceObj::C_HEAP, mtClass) DumpTimeSharedClassTable;
1592     CloneDumpTimeClassTable copy_classes(_dumptime_table, _cloned_dumptime_table);
1593     _dumptime_table->iterate(&copy_classes);
1594     _cloned_dumptime_table->update_counts();
1595   }
1596   if (_dumptime_lambda_proxy_class_dictionary != NULL) {
1597     assert(_cloned_dumptime_lambda_proxy_class_dictionary == NULL,
1598            "_cloned_dumptime_lambda_proxy_class_dictionary must be cleaned");
1599     _cloned_dumptime_lambda_proxy_class_dictionary =
1600                                           new (ResourceObj::C_HEAP, mtClass) DumpTimeLambdaProxyClassDictionary;
1601     CloneDumpTimeLambdaProxyClassTable copy_proxy_classes(_dumptime_lambda_proxy_class_dictionary,
1602                                                           _cloned_dumptime_lambda_proxy_class_dictionary);
1603     _dumptime_lambda_proxy_class_dictionary->iterate(&copy_proxy_classes);
1604   }
1605 }
1606 
1607 void SystemDictionaryShared::restore_dumptime_tables() {
1608   assert_lock_strong(DumpTimeTable_lock);
1609   delete _dumptime_table;
1610   _dumptime_table = _cloned_dumptime_table;
1611   _cloned_dumptime_table = NULL;
1612   delete _dumptime_lambda_proxy_class_dictionary;
1613   _dumptime_lambda_proxy_class_dictionary = _cloned_dumptime_lambda_proxy_class_dictionary;
1614   _cloned_dumptime_lambda_proxy_class_dictionary = NULL;
1615 }
1616 
1617 class CleanupDumpTimeLambdaProxyClassTable: StackObj {
1618  public:
1619   bool do_entry(LambdaProxyClassKey& key, DumpTimeLambdaProxyClassInfo& info) {
1620     assert_lock_strong(DumpTimeTable_lock);
1621     InstanceKlass* caller_ik = key.caller_ik();
1622     if (SystemDictionaryShared::check_for_exclusion(caller_ik, NULL)) {
1623       // If the caller class is excluded, unregister all the associated lambda proxy classes
1624       // so that they will not be included in the CDS archive.
1625       for (int i = info._proxy_klasses->length() - 1; i >= 0; i--) {
1626         SystemDictionaryShared::reset_registered_lambda_proxy_class(info._proxy_klasses->at(i));
1627         info._proxy_klasses->remove_at(i);
1628       }
1629     }
1630     for (int i = info._proxy_klasses->length() - 1; i >= 0; i--) {
1631       InstanceKlass* ik = info._proxy_klasses->at(i);
1632       if (SystemDictionaryShared::check_for_exclusion(ik, NULL)) {
1633         SystemDictionaryShared::reset_registered_lambda_proxy_class(ik);
1634         info._proxy_klasses->remove_at(i);
1635       }
1636     }
1637     return info._proxy_klasses->length() == 0 ? true /* delete the node*/ : false;
1638   }
1639 };
1640 
1641 void SystemDictionaryShared::cleanup_lambda_proxy_class_dictionary() {
1642   assert_lock_strong(DumpTimeTable_lock);
1643   if (_dumptime_lambda_proxy_class_dictionary != NULL) {
1644     CleanupDumpTimeLambdaProxyClassTable cleanup_proxy_classes;
1645     _dumptime_lambda_proxy_class_dictionary->unlink(&cleanup_proxy_classes);
1646   }
1647 }
1648 
1649 #if INCLUDE_CDS_JAVA_HEAP
1650 
1651 class ArchivedMirrorPatcher {
1652 protected:
1653   static void update(Klass* k) {
1654     if (k->has_archived_mirror_index()) {
1655       oop m = k->archived_java_mirror();
1656       if (m != NULL) {
1657         java_lang_Class::update_archived_mirror_native_pointers(m);
1658       }
1659     }
1660   }
1661 
1662 public:
1663   static void update_array_klasses(Klass* ak) {
1664     while (ak != NULL) {
1665       update(ak);
1666       ak = ArrayKlass::cast(ak)->higher_dimension();
1667     }
1668   }
1669 
1670   void do_value(const RunTimeClassInfo* info) {
1671     InstanceKlass* ik = info->_klass;
1672     update(ik);
1673     update_array_klasses(ik->array_klasses());
1674   }
1675 };
1676 
1677 class ArchivedLambdaMirrorPatcher : public ArchivedMirrorPatcher {
1678 public:
1679   void do_value(const RunTimeLambdaProxyClassInfo* info) {
1680     InstanceKlass* ik = info->proxy_klass_head();
1681     while (ik != NULL) {
1682       update(ik);
1683       Klass* k = ik->next_link();
1684       ik = (k != NULL) ? InstanceKlass::cast(k) : NULL;
1685     }
1686   }
1687 };
1688 
1689 void SystemDictionaryShared::update_archived_mirror_native_pointers_for(RunTimeSharedDictionary* dict) {
1690   ArchivedMirrorPatcher patcher;
1691   dict->iterate(&patcher);
1692 }
1693 
1694 void SystemDictionaryShared::update_archived_mirror_native_pointers_for(LambdaProxyClassDictionary* dict) {
1695   ArchivedLambdaMirrorPatcher patcher;
1696   dict->iterate(&patcher);
1697 }
1698 
1699 void SystemDictionaryShared::update_archived_mirror_native_pointers() {
1700   if (!HeapShared::are_archived_mirrors_available()) {
1701     return;
1702   }
1703   if (MetaspaceShared::relocation_delta() == 0) {
1704     return;
1705   }
1706   update_archived_mirror_native_pointers_for(&_builtin_dictionary);
1707   update_archived_mirror_native_pointers_for(&_unregistered_dictionary);
1708   update_archived_mirror_native_pointers_for(&_lambda_proxy_class_dictionary);
1709 
1710   for (int t = T_BOOLEAN; t <= T_LONG; t++) {
1711     Klass* k = Universe::typeArrayKlassObj((BasicType)t);
1712     ArchivedMirrorPatcher::update_array_klasses(k);
1713   }
1714 }
1715 #endif