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