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