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