1 /*
   2  * Copyright (c) 1997, 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 "jvm.h"
  27 #include "cds/heapShared.hpp"
  28 #include "classfile/classFileParser.hpp"
  29 #include "classfile/classFileStream.hpp"
  30 #include "classfile/classLoader.hpp"
  31 #include "classfile/classLoaderData.inline.hpp"
  32 #include "classfile/classLoaderDataGraph.inline.hpp"
  33 #include "classfile/classLoaderExt.hpp"
  34 #include "classfile/classLoadInfo.hpp"
  35 #include "classfile/dictionary.hpp"
  36 #include "classfile/javaClasses.inline.hpp"
  37 #include "classfile/klassFactory.hpp"
  38 #include "classfile/loaderConstraints.hpp"
  39 #include "classfile/packageEntry.hpp"
  40 #include "classfile/placeholders.hpp"
  41 #include "classfile/protectionDomainCache.hpp"
  42 #include "classfile/resolutionErrors.hpp"
  43 #include "classfile/stringTable.hpp"
  44 #include "classfile/symbolTable.hpp"
  45 #include "classfile/systemDictionary.hpp"
  46 #include "classfile/vmClasses.hpp"
  47 #include "classfile/vmSymbols.hpp"
  48 #include "code/codeCache.hpp"
  49 #include "gc/shared/gcTraceTime.inline.hpp"
  50 #include "interpreter/bootstrapInfo.hpp"
  51 #include "jfr/jfrEvents.hpp"
  52 #include "logging/log.hpp"
  53 #include "logging/logStream.hpp"
  54 #include "memory/metaspaceClosure.hpp"
  55 #include "memory/oopFactory.hpp"
  56 #include "memory/resourceArea.hpp"
  57 #include "memory/universe.hpp"
  58 #include "oops/access.inline.hpp"
  59 #include "oops/instanceKlass.hpp"
  60 #include "oops/klass.inline.hpp"
  61 #include "oops/method.inline.hpp"
  62 #include "oops/objArrayKlass.hpp"
  63 #include "oops/objArrayOop.inline.hpp"
  64 #include "oops/oop.inline.hpp"
  65 #include "oops/oopHandle.inline.hpp"
  66 #include "oops/symbol.hpp"
  67 #include "oops/typeArrayKlass.hpp"
  68 #include "prims/jvmtiExport.hpp"
  69 #include "prims/methodHandles.hpp"
  70 #include "runtime/arguments.hpp"
  71 #include "runtime/handles.inline.hpp"
  72 #include "runtime/java.hpp"
  73 #include "runtime/javaCalls.hpp"
  74 #include "runtime/mutexLocker.hpp"
  75 #include "runtime/sharedRuntime.hpp"
  76 #include "runtime/signature.hpp"
  77 #include "services/classLoadingService.hpp"
  78 #include "services/diagnosticCommand.hpp"
  79 #include "services/threadService.hpp"
  80 #include "utilities/macros.hpp"
  81 #include "utilities/utf8.hpp"
  82 #if INCLUDE_CDS
  83 #include "classfile/systemDictionaryShared.hpp"
  84 #endif
  85 #if INCLUDE_JFR
  86 #include "jfr/jfr.hpp"
  87 #endif
  88 
  89 ResolutionErrorTable*  SystemDictionary::_resolution_errors   = NULL;
  90 SymbolPropertyTable*   SystemDictionary::_invoke_method_table = NULL;
  91 ProtectionDomainCacheTable*   SystemDictionary::_pd_cache_table = NULL;
  92 
  93 OopHandle   SystemDictionary::_java_system_loader;
  94 OopHandle   SystemDictionary::_java_platform_loader;
  95 
  96 // Default ProtectionDomainCacheSize value
  97 const int defaultProtectionDomainCacheSize = 1009;
  98 
  99 const int _resolution_error_size  = 107;                     // number of entries in resolution error table
 100 const int _invoke_method_size     = 139;                     // number of entries in invoke method table
 101 
 102 // Hashtable holding placeholders for classes being loaded.
 103 const int _placeholder_table_size = 1009;
 104 static PlaceholderTable* _placeholders   = NULL;
 105 static PlaceholderTable*   placeholders() { return _placeholders; }
 106 
 107 // Constraints on class loaders
 108 const int _loader_constraint_size = 107;                     // number of entries in constraint table
 109 static LoaderConstraintTable*  _loader_constraints;
 110 static LoaderConstraintTable* constraints() { return _loader_constraints; }
 111 
 112 // ----------------------------------------------------------------------------
 113 // Java-level SystemLoader and PlatformLoader
 114 oop SystemDictionary::java_system_loader() {
 115   return _java_system_loader.resolve();
 116 }
 117 
 118 oop SystemDictionary::java_platform_loader() {
 119   return _java_platform_loader.resolve();
 120 }
 121 
 122 void SystemDictionary::compute_java_loaders(TRAPS) {
 123   JavaValue result(T_OBJECT);
 124   InstanceKlass* class_loader_klass = vmClasses::ClassLoader_klass();
 125   JavaCalls::call_static(&result,
 126                          class_loader_klass,
 127                          vmSymbols::getSystemClassLoader_name(),
 128                          vmSymbols::void_classloader_signature(),
 129                          CHECK);
 130 
 131   _java_system_loader = OopHandle(Universe::vm_global(), result.get_oop());
 132 
 133   JavaCalls::call_static(&result,
 134                          class_loader_klass,
 135                          vmSymbols::getPlatformClassLoader_name(),
 136                          vmSymbols::void_classloader_signature(),
 137                          CHECK);
 138 
 139   _java_platform_loader = OopHandle(Universe::vm_global(), result.get_oop());
 140 }
 141 
 142 ClassLoaderData* SystemDictionary::register_loader(Handle class_loader, bool create_mirror_cld) {
 143   if (create_mirror_cld) {
 144     // Add a new class loader data to the graph.
 145     return ClassLoaderDataGraph::add(class_loader, true);
 146   } else {
 147     return (class_loader() == NULL) ? ClassLoaderData::the_null_class_loader_data() :
 148                                       ClassLoaderDataGraph::find_or_create(class_loader);
 149   }
 150 }
 151 
 152 // ----------------------------------------------------------------------------
 153 // Parallel class loading check
 154 
 155 bool is_parallelCapable(Handle class_loader) {
 156   if (class_loader.is_null()) return true;
 157   return java_lang_ClassLoader::parallelCapable(class_loader());
 158 }
 159 // ----------------------------------------------------------------------------
 160 // ParallelDefineClass flag does not apply to bootclass loader
 161 bool is_parallelDefine(Handle class_loader) {
 162    if (class_loader.is_null()) return false;
 163    if (AllowParallelDefineClass && java_lang_ClassLoader::parallelCapable(class_loader())) {
 164      return true;
 165    }
 166    return false;
 167 }
 168 
 169 // Returns true if the passed class loader is the builtin application class loader
 170 // or a custom system class loader. A customer system class loader can be
 171 // specified via -Djava.system.class.loader.
 172 bool SystemDictionary::is_system_class_loader(oop class_loader) {
 173   if (class_loader == NULL) {
 174     return false;
 175   }
 176   return (class_loader->klass() == vmClasses::jdk_internal_loader_ClassLoaders_AppClassLoader_klass() ||
 177          class_loader == _java_system_loader.peek());
 178 }
 179 
 180 // Returns true if the passed class loader is the platform class loader.
 181 bool SystemDictionary::is_platform_class_loader(oop class_loader) {
 182   if (class_loader == NULL) {
 183     return false;
 184   }
 185   return (class_loader->klass() == vmClasses::jdk_internal_loader_ClassLoaders_PlatformClassLoader_klass());
 186 }
 187 
 188 Handle SystemDictionary::get_loader_lock_or_null(Handle class_loader) {
 189   // If class_loader is NULL or parallelCapable, the JVM doesn't acquire a lock while loading.
 190   if (is_parallelCapable(class_loader)) {
 191     return Handle();
 192   } else {
 193     return class_loader;
 194   }
 195 }
 196 
 197 // ----------------------------------------------------------------------------
 198 // Resolving of classes
 199 
 200 Symbol* SystemDictionary::class_name_symbol(const char* name, Symbol* exception, TRAPS) {
 201   if (name == NULL) {
 202     THROW_MSG_0(exception, "No class name given");
 203   }
 204   if ((int)strlen(name) > Symbol::max_length()) {
 205     // It's impossible to create this class;  the name cannot fit
 206     // into the constant pool.
 207     Exceptions::fthrow(THREAD_AND_LOCATION, exception,
 208                        "Class name exceeds maximum length of %d: %s",
 209                        Symbol::max_length(),
 210                        name);
 211     return NULL;
 212   }
 213   // Callers should ensure that the name is never an illegal UTF8 string.
 214   assert(UTF8::is_legal_utf8((const unsigned char*)name, (int)strlen(name), false),
 215          "Class name is not a valid utf8 string.");
 216 
 217   // Make a new symbol for the class name.
 218   return SymbolTable::new_symbol(name);
 219 }
 220 
 221 #ifdef ASSERT
 222 // Used to verify that class loading succeeded in adding k to the dictionary.
 223 void verify_dictionary_entry(Symbol* class_name, InstanceKlass* k) {
 224   MutexLocker mu(SystemDictionary_lock);
 225   ClassLoaderData* loader_data = k->class_loader_data();
 226   Dictionary* dictionary = loader_data->dictionary();
 227   assert(class_name == k->name(), "Must be the same");
 228   unsigned int name_hash = dictionary->compute_hash(class_name);
 229   InstanceKlass* kk = dictionary->find_class(name_hash, class_name);
 230   assert(kk == k, "should be present in dictionary");
 231 }
 232 #endif
 233 
 234 static void handle_resolution_exception(Symbol* class_name, bool throw_error, TRAPS) {
 235   if (HAS_PENDING_EXCEPTION) {
 236     // If we have a pending exception we forward it to the caller, unless throw_error is true,
 237     // in which case we have to check whether the pending exception is a ClassNotFoundException,
 238     // and convert it to a NoClassDefFoundError and chain the original ClassNotFoundException.
 239     if (throw_error && PENDING_EXCEPTION->is_a(vmClasses::ClassNotFoundException_klass())) {
 240       ResourceMark rm(THREAD);
 241       Handle e(THREAD, PENDING_EXCEPTION);
 242       CLEAR_PENDING_EXCEPTION;
 243       THROW_MSG_CAUSE(vmSymbols::java_lang_NoClassDefFoundError(), class_name->as_C_string(), e);
 244     } else {
 245       return; // the caller will throw the incoming exception
 246     }
 247   }
 248   // If the class is not found, ie, caller has checked that klass is NULL, throw the appropriate
 249   // error or exception depending on the value of throw_error.
 250   ResourceMark rm(THREAD);
 251   if (throw_error) {
 252     THROW_MSG(vmSymbols::java_lang_NoClassDefFoundError(), class_name->as_C_string());
 253   } else {
 254     THROW_MSG(vmSymbols::java_lang_ClassNotFoundException(), class_name->as_C_string());
 255   }
 256 }
 257 
 258 // Forwards to resolve_or_null
 259 
 260 Klass* SystemDictionary::resolve_or_fail(Symbol* class_name, Handle class_loader, Handle protection_domain,
 261                                          bool throw_error, TRAPS) {
 262   Klass* klass = resolve_or_null(class_name, class_loader, protection_domain, THREAD);
 263   // Check for pending exception or null klass, and throw exception
 264   if (HAS_PENDING_EXCEPTION || klass == NULL) {
 265     handle_resolution_exception(class_name, throw_error, CHECK_NULL);
 266   }
 267   return klass;
 268 }
 269 
 270 // Forwards to resolve_array_class_or_null or resolve_instance_class_or_null
 271 
 272 Klass* SystemDictionary::resolve_or_null(Symbol* class_name, Handle class_loader, Handle protection_domain, TRAPS) {
 273   assert(class_name != NULL, "must not be NULL");
 274   if (Signature::is_array(class_name)) {
 275     return resolve_array_class_or_null(class_name, class_loader, protection_domain, THREAD);
 276   } else {
 277     return resolve_instance_class_or_null_helper(class_name, class_loader, protection_domain, THREAD);
 278   }
 279 }
 280 
 281 // name may be in the form of "java/lang/Object" or "Ljava/lang/Object;"
 282 InstanceKlass* SystemDictionary::resolve_instance_class_or_null_helper(Symbol* class_name,
 283                                                                        Handle class_loader,
 284                                                                        Handle protection_domain,
 285                                                                        TRAPS) {
 286   assert(class_name != NULL && !Signature::is_array(class_name), "must be");
 287   if (Signature::has_envelope(class_name)) {
 288     ResourceMark rm(THREAD);
 289     // Ignore wrapping L and ;.
 290     TempNewSymbol name = SymbolTable::new_symbol(class_name->as_C_string() + 1,
 291                                                  class_name->utf8_length() - 2);
 292     return resolve_instance_class_or_null(name, class_loader, protection_domain, THREAD);
 293   } else {
 294     return resolve_instance_class_or_null(class_name, class_loader, protection_domain, THREAD);
 295   }
 296 }
 297 
 298 // Forwards to resolve_instance_class_or_null
 299 
 300 Klass* SystemDictionary::resolve_array_class_or_null(Symbol* class_name,
 301                                                      Handle class_loader,
 302                                                      Handle protection_domain,
 303                                                      TRAPS) {
 304   assert(Signature::is_array(class_name), "must be array");
 305   ResourceMark rm(THREAD);
 306   SignatureStream ss(class_name, false);
 307   int ndims = ss.skip_array_prefix();  // skip all '['s
 308   Klass* k = NULL;
 309   BasicType t = ss.type();
 310   if (ss.has_envelope()) {
 311     Symbol* obj_class = ss.as_symbol();
 312     k = SystemDictionary::resolve_instance_class_or_null(obj_class,
 313                                                          class_loader,
 314                                                          protection_domain,
 315                                                          CHECK_NULL);
 316     if (k != NULL) {
 317       k = k->array_klass(ndims, CHECK_NULL);
 318     }
 319   } else {
 320     k = Universe::typeArrayKlassObj(t);
 321     k = TypeArrayKlass::cast(k)->array_klass(ndims, CHECK_NULL);
 322   }
 323   return k;
 324 }
 325 
 326 static inline void log_circularity_error(Thread* thread, PlaceholderEntry* probe) {
 327   LogTarget(Debug, class, load, placeholders) lt;
 328   if (lt.is_enabled()) {
 329     ResourceMark rm(thread);
 330     LogStream ls(lt);
 331     ls.print("ClassCircularityError detected for placeholder ");
 332     probe->print_entry(&ls);
 333     ls.cr();
 334   }
 335 }
 336 
 337 // Must be called for any superclass or superinterface resolution
 338 // during class definition to allow class circularity checking
 339 // superinterface callers:
 340 //    parse_interfaces - from defineClass
 341 // superclass callers:
 342 //   ClassFileParser - from defineClass
 343 //   load_shared_class - while loading a class from shared archive
 344 //   resolve_instance_class_or_null:
 345 //     via: handle_parallel_super_load
 346 //      when resolving a class that has an existing placeholder with
 347 //      a saved superclass [i.e. a defineClass is currently in progress]
 348 //      If another thread is trying to resolve the class, it must do
 349 //      superclass checks on its own thread to catch class circularity and
 350 //      to avoid deadlock.
 351 //
 352 // resolve_super_or_fail adds a LOAD_SUPER placeholder to the placeholder table before calling
 353 // resolve_instance_class_or_null. ClassCircularityError is detected when a LOAD_SUPER or LOAD_INSTANCE
 354 // placeholder for the same thread, class, classloader is found.
 355 // This can be seen with logging option: -Xlog:class+load+placeholders=debug.
 356 //
 357 InstanceKlass* SystemDictionary::resolve_super_or_fail(Symbol* class_name,
 358                                                        Symbol* super_name,
 359                                                        Handle class_loader,
 360                                                        Handle protection_domain,
 361                                                        bool is_superclass,
 362                                                        TRAPS) {
 363 
 364   assert(super_name != NULL, "null superclass for resolving");
 365   assert(!Signature::is_array(super_name), "invalid superclass name");
 366 #if INCLUDE_CDS
 367   if (DumpSharedSpaces) {
 368     // Special processing for handling UNREGISTERED shared classes.
 369     InstanceKlass* k = SystemDictionaryShared::lookup_super_for_unregistered_class(class_name,
 370                            super_name, is_superclass);
 371     if (k) {
 372       return k;
 373     }
 374   }
 375 #endif // INCLUDE_CDS
 376 
 377   // If klass is already loaded, just return the superclass or superinterface.
 378   // Make sure there's a placeholder for the class_name before resolving.
 379   // This is used as a claim that this thread is currently loading superclass/classloader
 380   // and for ClassCircularity checks.
 381 
 382   ClassLoaderData* loader_data = class_loader_data(class_loader);
 383   Dictionary* dictionary = loader_data->dictionary();
 384   unsigned int name_hash = dictionary->compute_hash(class_name);
 385   assert(placeholders()->compute_hash(class_name) == name_hash, "they're the same hashcode");
 386 
 387   // can't throw error holding a lock
 388   bool throw_circularity_error = false;
 389   {
 390     MutexLocker mu(THREAD, SystemDictionary_lock);
 391     InstanceKlass* klassk = dictionary->find_class(name_hash, class_name);
 392     InstanceKlass* quicksuperk;
 393     // To support parallel loading: if class is done loading, just return the superclass
 394     // if the super_name matches class->super()->name() and if the class loaders match.
 395     // Otherwise, a LinkageError will be thrown later.
 396     if (klassk != NULL && is_superclass &&
 397         ((quicksuperk = klassk->java_super()) != NULL) &&
 398          ((quicksuperk->name() == super_name) &&
 399             (quicksuperk->class_loader() == class_loader()))) {
 400            return quicksuperk;
 401     } else {
 402       // Must check ClassCircularity before checking if superclass is already loaded.
 403       PlaceholderEntry* probe = placeholders()->get_entry(name_hash, class_name, loader_data);
 404       if (probe && probe->check_seen_thread(THREAD, PlaceholderTable::LOAD_SUPER)) {
 405           log_circularity_error(THREAD, probe);
 406           throw_circularity_error = true;
 407       }
 408     }
 409 
 410     if (!throw_circularity_error) {
 411       // Be careful not to exit resolve_super without removing this placeholder.
 412       PlaceholderEntry* newprobe = placeholders()->find_and_add(name_hash,
 413                                                                 class_name,
 414                                                                 loader_data,
 415                                                                 PlaceholderTable::LOAD_SUPER,
 416                                                                 super_name, THREAD);
 417     }
 418   }
 419 
 420   if (throw_circularity_error) {
 421       ResourceMark rm(THREAD);
 422       THROW_MSG_NULL(vmSymbols::java_lang_ClassCircularityError(), class_name->as_C_string());
 423   }
 424 
 425   // Resolve the superclass or superinterface, check results on return
 426   InstanceKlass* superk =
 427     SystemDictionary::resolve_instance_class_or_null_helper(super_name,
 428                                                             class_loader,
 429                                                             protection_domain,
 430                                                             THREAD);
 431 
 432   // Clean up placeholder entry.
 433   {
 434     MutexLocker mu(THREAD, SystemDictionary_lock);
 435     placeholders()->find_and_remove(name_hash, class_name, loader_data, PlaceholderTable::LOAD_SUPER, THREAD);
 436     SystemDictionary_lock->notify_all();
 437   }
 438 
 439   // Check for pending exception or null superk, and throw exception
 440   if (HAS_PENDING_EXCEPTION || superk == NULL) {
 441     handle_resolution_exception(super_name, true, CHECK_NULL);
 442   }
 443 
 444   return superk;
 445 }
 446 
 447 // We only get here if this thread finds that another thread
 448 // has already claimed the placeholder token for the current operation,
 449 // but that other thread either never owned or gave up the
 450 // object lock
 451 // Waits on SystemDictionary_lock to indicate placeholder table updated
 452 // On return, caller must recheck placeholder table state
 453 //
 454 // We only get here if
 455 //  1) custom classLoader, i.e. not bootstrap classloader
 456 //  2) custom classLoader has broken the class loader objectLock
 457 //     so another thread got here in parallel
 458 //
 459 // lockObject must be held.
 460 // Complicated dance due to lock ordering:
 461 // Must first release the classloader object lock to
 462 // allow initial definer to complete the class definition
 463 // and to avoid deadlock
 464 // Reclaim classloader lock object with same original recursion count
 465 // Must release SystemDictionary_lock after notify, since
 466 // class loader lock must be claimed before SystemDictionary_lock
 467 // to prevent deadlocks
 468 //
 469 // The notify allows applications that did an untimed wait() on
 470 // the classloader object lock to not hang.
 471 static void double_lock_wait(JavaThread* thread, Handle lockObject) {
 472   assert_lock_strong(SystemDictionary_lock);
 473 
 474   assert(lockObject() != NULL, "lockObject must be non-NULL");
 475   bool calledholdinglock
 476       = ObjectSynchronizer::current_thread_holds_lock(thread, lockObject);
 477   assert(calledholdinglock, "must hold lock for notify");
 478   assert(!is_parallelCapable(lockObject), "lockObject must not be parallelCapable");
 479   // These don't throw exceptions.
 480   ObjectSynchronizer::notifyall(lockObject, thread);
 481   intx recursions = ObjectSynchronizer::complete_exit(lockObject, thread);
 482   SystemDictionary_lock->wait();
 483   SystemDictionary_lock->unlock();
 484   ObjectSynchronizer::reenter(lockObject, recursions, thread);
 485   SystemDictionary_lock->lock();
 486 }
 487 
 488 // If the class in is in the placeholder table, class loading is in progress.
 489 // For cases where the application changes threads to load classes, it
 490 // is critical to ClassCircularity detection that we try loading
 491 // the superclass on the new thread internally, so we do parallel
 492 // superclass loading here.  This avoids deadlock for ClassCircularity
 493 // detection for parallelCapable class loaders that lock on a per-class lock.
 494 static void handle_parallel_super_load(Symbol* name,
 495                                        Symbol* superclassname,
 496                                        Handle class_loader,
 497                                        Handle protection_domain, TRAPS) {
 498 
 499   // superk is not used; resolve_super_or_fail is called for circularity check only.
 500   Klass* superk = SystemDictionary::resolve_super_or_fail(name,
 501                                                           superclassname,
 502                                                           class_loader,
 503                                                           protection_domain,
 504                                                           true,
 505                                                           CHECK);
 506 }
 507 
 508 // parallelCapable class loaders do NOT wait for parallel superclass loads to complete
 509 // Serial class loaders and bootstrap classloader do wait for superclass loads
 510 static bool should_wait_for_loading(Handle class_loader) {
 511   return class_loader.is_null() || !is_parallelCapable(class_loader);
 512 }
 513 
 514 // For bootstrap and non-parallelCapable class loaders, check and wait for
 515 // another thread to complete loading this class.
 516 InstanceKlass* SystemDictionary::handle_parallel_loading(JavaThread* current,
 517                                                          unsigned int name_hash,
 518                                                          Symbol* name,
 519                                                          ClassLoaderData* loader_data,
 520                                                          Handle lockObject,
 521                                                          bool* throw_circularity_error) {
 522   PlaceholderEntry* oldprobe = placeholders()->get_entry(name_hash, name, loader_data);
 523   if (oldprobe != NULL) {
 524     // only need check_seen_thread once, not on each loop
 525     // 6341374 java/lang/Instrument with -Xcomp
 526     if (oldprobe->check_seen_thread(current, PlaceholderTable::LOAD_INSTANCE)) {
 527       log_circularity_error(current, oldprobe);
 528       *throw_circularity_error = true;
 529       return NULL;
 530     } else {
 531       // Wait until the first thread has finished loading this class. Also wait until all the
 532       // threads trying to load its superclass have removed their placeholders.
 533       while (oldprobe != NULL &&
 534              (oldprobe->instance_load_in_progress() || oldprobe->super_load_in_progress())) {
 535 
 536         // We only get here if the application has released the
 537         // classloader lock when another thread was in the middle of loading a
 538         // superclass/superinterface for this class, and now
 539         // this thread is also trying to load this class.
 540         // To minimize surprises, the first thread that started to
 541         // load a class should be the one to complete the loading
 542         // with the classfile it initially expected.
 543         // This logic has the current thread wait once it has done
 544         // all the superclass/superinterface loading it can, until
 545         // the original thread completes the class loading or fails
 546         // If it completes we will use the resulting InstanceKlass
 547         // which we will find below in the systemDictionary.
 548         oldprobe = NULL;  // Other thread could delete this placeholder entry
 549 
 550         if (lockObject.is_null()) {
 551           SystemDictionary_lock->wait();
 552         } else {
 553           double_lock_wait(current, lockObject);
 554         }
 555 
 556         // Check if classloading completed while we were waiting
 557         InstanceKlass* check = loader_data->dictionary()->find_class(name_hash, name);
 558         if (check != NULL) {
 559           // Klass is already loaded, so just return it
 560           return check;
 561         }
 562         // check if other thread failed to load and cleaned up
 563         oldprobe = placeholders()->get_entry(name_hash, name, loader_data);
 564       }
 565     }
 566   }
 567   return NULL;
 568 }
 569 
 570 void SystemDictionary::post_class_load_event(EventClassLoad* event, const InstanceKlass* k, const ClassLoaderData* init_cld) {
 571   assert(event != NULL, "invariant");
 572   assert(k != NULL, "invariant");
 573   assert(event->should_commit(), "invariant");
 574   event->set_loadedClass(k);
 575   event->set_definingClassLoader(k->class_loader_data());
 576   event->set_initiatingClassLoader(init_cld);
 577   event->commit();
 578 }
 579 
 580 // SystemDictionary::resolve_instance_class_or_null is the main function for class name resolution.
 581 // After checking if the InstanceKlass already exists, it checks for ClassCircularityError and
 582 // whether the thread must wait for loading in parallel.  It eventually calls load_instance_class,
 583 // which will load the class via the bootstrap loader or call ClassLoader.loadClass().
 584 // This can return NULL, an exception or an InstanceKlass.
 585 InstanceKlass* SystemDictionary::resolve_instance_class_or_null(Symbol* name,
 586                                                                 Handle class_loader,
 587                                                                 Handle protection_domain,
 588                                                                 TRAPS) {
 589   // name must be in the form of "java/lang/Object" -- cannot be "Ljava/lang/Object;"
 590   assert(name != NULL && !Signature::is_array(name) &&
 591          !Signature::has_envelope(name), "invalid class name");
 592 
 593   EventClassLoad class_load_start_event;
 594 
 595   HandleMark hm(THREAD);
 596 
 597   // Fix for 4474172; see evaluation for more details
 598   class_loader = Handle(THREAD, java_lang_ClassLoader::non_reflection_class_loader(class_loader()));
 599   ClassLoaderData* loader_data = register_loader(class_loader);
 600   Dictionary* dictionary = loader_data->dictionary();
 601   unsigned int name_hash = dictionary->compute_hash(name);
 602 
 603   // Do lookup to see if class already exists and the protection domain
 604   // has the right access.
 605   // This call uses find which checks protection domain already matches
 606   // All subsequent calls use find_class, and set loaded_class so that
 607   // before we return a result, we call out to java to check for valid protection domain.
 608   InstanceKlass* probe = dictionary->find(name_hash, name, protection_domain);
 609   if (probe != NULL) return probe;
 610 
 611   // Non-bootstrap class loaders will call out to class loader and
 612   // define via jvm/jni_DefineClass which will acquire the
 613   // class loader object lock to protect against multiple threads
 614   // defining the class in parallel by accident.
 615   // This lock must be acquired here so the waiter will find
 616   // any successful result in the SystemDictionary and not attempt
 617   // the define.
 618   // ParallelCapable class loaders and the bootstrap classloader
 619   // do not acquire lock here.
 620   Handle lockObject = get_loader_lock_or_null(class_loader);
 621   ObjectLocker ol(lockObject, THREAD);
 622 
 623   bool super_load_in_progress  = false;
 624   InstanceKlass* loaded_class = NULL;
 625   Symbol* superclassname = NULL;
 626 
 627   assert(THREAD->can_call_java(),
 628          "can not load classes with compiler thread: class=%s, classloader=%s",
 629          name->as_C_string(),
 630          class_loader.is_null() ? "null" : class_loader->klass()->name()->as_C_string());
 631 
 632   assert(placeholders()->compute_hash(name) == name_hash, "they're the same hashcode");
 633 
 634   // Check again (after locking) if the class already exists in SystemDictionary
 635   {
 636     MutexLocker mu(THREAD, SystemDictionary_lock);
 637     InstanceKlass* check = dictionary->find_class(name_hash, name);
 638     if (check != NULL) {
 639       // InstanceKlass is already loaded, but we still need to check protection domain below.
 640       loaded_class = check;
 641     } else {
 642       PlaceholderEntry* placeholder = placeholders()->get_entry(name_hash, name, loader_data);
 643       if (placeholder != NULL && placeholder->super_load_in_progress()) {
 644          super_load_in_progress = true;
 645          superclassname = placeholder->supername();
 646          assert(superclassname != NULL, "superclass has to have a name");
 647       }
 648     }
 649   }
 650 
 651   // If the class is in the placeholder table with super_class set,
 652   // handle superclass loading in progress.
 653   if (super_load_in_progress) {
 654     handle_parallel_super_load(name, superclassname,
 655                                class_loader,
 656                                protection_domain,
 657                                CHECK_NULL);
 658   }
 659 
 660   bool throw_circularity_error = false;
 661   if (loaded_class == NULL) {
 662     bool load_placeholder_added = false;
 663 
 664     // Add placeholder entry to record loading instance class
 665     // Four cases:
 666     // case 1. Bootstrap classloader
 667     //    This classloader supports parallelism at the classloader level
 668     //    but only allows a single thread to load a class/classloader pair.
 669     //    The LOAD_INSTANCE placeholder is the mechanism for mutual exclusion.
 670     // case 2. parallelCapable user level classloaders
 671     //    These class loaders lock a per-class object lock when ClassLoader.loadClass()
 672     //    is called. A LOAD_INSTANCE placeholder isn't used for mutual exclusion.
 673     // case 3. traditional classloaders that rely on the classloader object lock
 674     //    There should be no need for need for LOAD_INSTANCE, except:
 675     // case 4. traditional class loaders that break the classloader object lock
 676     //    as a legacy deadlock workaround. Detection of this case requires that
 677     //    this check is done while holding the classloader object lock,
 678     //    and that lock is still held when calling classloader's loadClass.
 679     //    For these classloaders, we ensure that the first requestor
 680     //    completes the load and other requestors wait for completion.
 681     {
 682       MutexLocker mu(THREAD, SystemDictionary_lock);
 683       if (should_wait_for_loading(class_loader)) {
 684         loaded_class = handle_parallel_loading(THREAD,
 685                                                name_hash,
 686                                                name,
 687                                                loader_data,
 688                                                lockObject,
 689                                                &throw_circularity_error);
 690       }
 691 
 692       // Recheck if the class has been loaded for all class loader cases and
 693       // add a LOAD_INSTANCE placeholder while holding the SystemDictionary_lock.
 694       if (!throw_circularity_error && loaded_class == NULL) {
 695         InstanceKlass* check = dictionary->find_class(name_hash, name);
 696         if (check != NULL) {
 697           loaded_class = check;
 698         } else if (should_wait_for_loading(class_loader)) {
 699           // Add the LOAD_INSTANCE token. Threads will wait on loading to complete for this thread.
 700           PlaceholderEntry* newprobe = placeholders()->find_and_add(name_hash, name, loader_data,
 701                                                                     PlaceholderTable::LOAD_INSTANCE,
 702                                                                     NULL,
 703                                                                     THREAD);
 704           load_placeholder_added = true;
 705         }
 706       }
 707     }
 708 
 709     // Must throw error outside of owning lock
 710     if (throw_circularity_error) {
 711       assert(!HAS_PENDING_EXCEPTION && !load_placeholder_added, "circularity error cleanup");
 712       ResourceMark rm(THREAD);
 713       THROW_MSG_NULL(vmSymbols::java_lang_ClassCircularityError(), name->as_C_string());
 714     }
 715 
 716     // Be careful when modifying this code: once you have run
 717     // placeholders()->find_and_add(PlaceholderTable::LOAD_INSTANCE),
 718     // you need to find_and_remove it before returning.
 719     // So be careful to not exit with a CHECK_ macro between these calls.
 720 
 721     if (loaded_class == NULL) {
 722       // Do actual loading
 723       loaded_class = load_instance_class(name_hash, name, class_loader, THREAD);
 724     }
 725 
 726     if (load_placeholder_added) {
 727       // clean up placeholder entries for LOAD_INSTANCE success or error
 728       // This brackets the SystemDictionary updates for both defining
 729       // and initiating loaders
 730       MutexLocker mu(THREAD, SystemDictionary_lock);
 731       placeholders()->find_and_remove(name_hash, name, loader_data, PlaceholderTable::LOAD_INSTANCE, THREAD);
 732       SystemDictionary_lock->notify_all();
 733     }
 734   }
 735 
 736   if (HAS_PENDING_EXCEPTION || loaded_class == NULL) {
 737     return NULL;
 738   }
 739 
 740   if (class_load_start_event.should_commit()) {
 741     post_class_load_event(&class_load_start_event, loaded_class, loader_data);
 742   }
 743 
 744   // Make sure we have the right class in the dictionary
 745   DEBUG_ONLY(verify_dictionary_entry(name, loaded_class));
 746 
 747   // Check if the protection domain is present it has the right access
 748   if (protection_domain() != NULL) {
 749     // Verify protection domain. If it fails an exception is thrown
 750     dictionary->validate_protection_domain(name_hash, loaded_class, class_loader, protection_domain, CHECK_NULL);
 751   }
 752 
 753   return loaded_class;
 754 }
 755 
 756 
 757 // This routine does not lock the system dictionary.
 758 //
 759 // Since readers don't hold a lock, we must make sure that system
 760 // dictionary entries are added to in a safe way (all links must
 761 // be updated in an MT-safe manner). All entries are removed during class
 762 // unloading, when this class loader is no longer referenced.
 763 //
 764 // Callers should be aware that an entry could be added just after
 765 // _dictionary->bucket(index) is read here, so the caller will not see
 766 // the new entry.
 767 
 768 InstanceKlass* SystemDictionary::find_instance_klass(Symbol* class_name,
 769                                                      Handle class_loader,
 770                                                      Handle protection_domain) {
 771 
 772   // The result of this call should be consistent with the result
 773   // of the call to resolve_instance_class_or_null().
 774   // See evaluation 6790209 and 4474172 for more details.
 775   oop class_loader_oop = java_lang_ClassLoader::non_reflection_class_loader(class_loader());
 776   ClassLoaderData* loader_data = ClassLoaderData::class_loader_data_or_null(class_loader_oop);
 777 
 778   if (loader_data == NULL) {
 779     // If the ClassLoaderData has not been setup,
 780     // then the class loader has no entries in the dictionary.
 781     return NULL;
 782   }
 783 
 784   Dictionary* dictionary = loader_data->dictionary();
 785   unsigned int name_hash = dictionary->compute_hash(class_name);
 786   return dictionary->find(name_hash, class_name, protection_domain);
 787 }
 788 
 789 // Look for a loaded instance or array klass by name.  Do not do any loading.
 790 // return NULL in case of error.
 791 Klass* SystemDictionary::find_instance_or_array_klass(Symbol* class_name,
 792                                                       Handle class_loader,
 793                                                       Handle protection_domain) {
 794   Klass* k = NULL;
 795   assert(class_name != NULL, "class name must be non NULL");
 796 
 797   if (Signature::is_array(class_name)) {
 798     // The name refers to an array.  Parse the name.
 799     // dimension and object_key in FieldArrayInfo are assigned as a
 800     // side-effect of this call
 801     SignatureStream ss(class_name, false);
 802     int ndims = ss.skip_array_prefix();  // skip all '['s
 803     BasicType t = ss.type();
 804     if (t != T_OBJECT) {
 805       k = Universe::typeArrayKlassObj(t);
 806     } else {
 807       k = SystemDictionary::find_instance_klass(ss.as_symbol(), class_loader, protection_domain);
 808     }
 809     if (k != NULL) {
 810       k = k->array_klass_or_null(ndims);
 811     }
 812   } else {
 813     k = find_instance_klass(class_name, class_loader, protection_domain);
 814   }
 815   return k;
 816 }
 817 
 818 // Note: this method is much like resolve_class_from_stream, but
 819 // does not publish the classes in the SystemDictionary.
 820 // Handles Lookup.defineClass hidden.
 821 InstanceKlass* SystemDictionary::resolve_hidden_class_from_stream(
 822                                                      ClassFileStream* st,
 823                                                      Symbol* class_name,
 824                                                      Handle class_loader,
 825                                                      const ClassLoadInfo& cl_info,
 826                                                      TRAPS) {
 827 
 828   EventClassLoad class_load_start_event;
 829   ClassLoaderData* loader_data;
 830 
 831   // - for hidden classes that are not strong: create a new CLD that has a class holder and
 832   //                                           whose loader is the Lookup class's loader.
 833   // - for hidden class: add the class to the Lookup class's loader's CLD.
 834   assert (cl_info.is_hidden(), "only used for hidden classes");
 835   bool create_mirror_cld = !cl_info.is_strong_hidden();
 836   loader_data = register_loader(class_loader, create_mirror_cld);
 837 
 838   assert(st != NULL, "invariant");
 839   assert(st->need_verify(), "invariant");
 840 
 841   // Parse stream and create a klass.
 842   InstanceKlass* k = KlassFactory::create_from_stream(st,
 843                                                       class_name,
 844                                                       loader_data,
 845                                                       cl_info,
 846                                                       CHECK_NULL);
 847   assert(k != NULL, "no klass created");
 848 
 849   // Hidden classes that are not strong must update ClassLoaderData holder
 850   // so that they can be unloaded when the mirror is no longer referenced.
 851   if (!cl_info.is_strong_hidden()) {
 852     k->class_loader_data()->initialize_holder(Handle(THREAD, k->java_mirror()));
 853   }
 854 
 855   {
 856     MutexLocker mu_r(THREAD, Compile_lock);
 857     // Add to class hierarchy, and do possible deoptimizations.
 858     add_to_hierarchy(k);
 859     // But, do not add to dictionary.
 860   }
 861 
 862   k->link_class(CHECK_NULL);
 863 
 864   // notify jvmti
 865   if (JvmtiExport::should_post_class_load()) {
 866     JvmtiExport::post_class_load(THREAD, k);
 867   }
 868   if (class_load_start_event.should_commit()) {
 869     post_class_load_event(&class_load_start_event, k, loader_data);
 870   }
 871 
 872   return k;
 873 }
 874 
 875 // Add a klass to the system from a stream (called by jni_DefineClass and
 876 // JVM_DefineClass).
 877 // Note: class_name can be NULL. In that case we do not know the name of
 878 // the class until we have parsed the stream.
 879 // This function either returns an InstanceKlass or throws an exception.  It does
 880 // not return NULL without a pending exception.
 881 InstanceKlass* SystemDictionary::resolve_class_from_stream(
 882                                                      ClassFileStream* st,
 883                                                      Symbol* class_name,
 884                                                      Handle class_loader,
 885                                                      const ClassLoadInfo& cl_info,
 886                                                      TRAPS) {
 887 
 888   HandleMark hm(THREAD);
 889 
 890   ClassLoaderData* loader_data = register_loader(class_loader);
 891 
 892   // Classloaders that support parallelism, e.g. bootstrap classloader,
 893   // do not acquire lock here
 894   Handle lockObject = get_loader_lock_or_null(class_loader);
 895   ObjectLocker ol(lockObject, THREAD);
 896 
 897   // Parse the stream and create a klass.
 898   // Note that we do this even though this klass might
 899   // already be present in the SystemDictionary, otherwise we would not
 900   // throw potential ClassFormatErrors.
 901  InstanceKlass* k = NULL;
 902 
 903 #if INCLUDE_CDS
 904   if (!DumpSharedSpaces) {
 905     k = SystemDictionaryShared::lookup_from_stream(class_name,
 906                                                    class_loader,
 907                                                    cl_info.protection_domain(),
 908                                                    st,
 909                                                    CHECK_NULL);
 910   }
 911 #endif
 912 
 913   if (k == NULL) {
 914     k = KlassFactory::create_from_stream(st, class_name, loader_data, cl_info, CHECK_NULL);
 915   }
 916 
 917   assert(k != NULL, "no klass created");
 918   Symbol* h_name = k->name();
 919   assert(class_name == NULL || class_name == h_name, "name mismatch");
 920 
 921   // Add class just loaded
 922   // If a class loader supports parallel classloading, handle parallel define requests.
 923   // find_or_define_instance_class may return a different InstanceKlass,
 924   // in which case the old k would be deallocated
 925   if (is_parallelCapable(class_loader)) {
 926     k = find_or_define_instance_class(h_name, class_loader, k, CHECK_NULL);
 927   } else {
 928     define_instance_class(k, class_loader, THREAD);
 929 
 930     // If defining the class throws an exception register 'k' for cleanup.
 931     if (HAS_PENDING_EXCEPTION) {
 932       assert(k != NULL, "Must have an instance klass here!");
 933       loader_data->add_to_deallocate_list(k);
 934       return NULL;
 935     }
 936   }
 937 
 938   // Make sure we have an entry in the SystemDictionary on success
 939   DEBUG_ONLY(verify_dictionary_entry(h_name, k));
 940 
 941   return k;
 942 }
 943 
 944 InstanceKlass* SystemDictionary::resolve_from_stream(ClassFileStream* st,
 945                                                      Symbol* class_name,
 946                                                      Handle class_loader,
 947                                                      const ClassLoadInfo& cl_info,
 948                                                      TRAPS) {
 949   if (cl_info.is_hidden()) {
 950     return resolve_hidden_class_from_stream(st, class_name, class_loader, cl_info, CHECK_NULL);
 951   } else {
 952     return resolve_class_from_stream(st, class_name, class_loader, cl_info, CHECK_NULL);
 953   }
 954 }
 955 
 956 
 957 #if INCLUDE_CDS
 958 // Check if a shared class can be loaded by the specific classloader.
 959 bool SystemDictionary::is_shared_class_visible(Symbol* class_name,
 960                                                InstanceKlass* ik,
 961                                                PackageEntry* pkg_entry,
 962                                                Handle class_loader) {
 963   assert(!ModuleEntryTable::javabase_moduleEntry()->is_patched(),
 964          "Cannot use sharing if java.base is patched");
 965 
 966   // (1) Check if we are loading into the same loader as in dump time.
 967 
 968   if (ik->is_shared_boot_class()) {
 969     if (class_loader() != NULL) {
 970       return false;
 971     }
 972   } else if (ik->is_shared_platform_class()) {
 973     if (class_loader() != java_platform_loader()) {
 974       return false;
 975     }
 976   } else if (ik->is_shared_app_class()) {
 977     if (class_loader() != java_system_loader()) {
 978       return false;
 979     }
 980   } else {
 981     // ik was loaded by a custom loader during dump time
 982     if (class_loader_data(class_loader)->is_builtin_class_loader_data()) {
 983       return false;
 984     } else {
 985       return true;
 986     }
 987   }
 988 
 989   // (2) Check if we are loading into the same module from the same location as in dump time.
 990 
 991   if (MetaspaceShared::use_optimized_module_handling()) {
 992     // Class visibility has not changed between dump time and run time, so a class
 993     // that was visible (and thus archived) during dump time is always visible during runtime.
 994     assert(SystemDictionary::is_shared_class_visible_impl(class_name, ik, pkg_entry, class_loader),
 995            "visibility cannot change between dump time and runtime");
 996     return true;
 997   }
 998   return is_shared_class_visible_impl(class_name, ik, pkg_entry, class_loader);
 999 }
1000 
1001 bool SystemDictionary::is_shared_class_visible_impl(Symbol* class_name,
1002                                                     InstanceKlass* ik,
1003                                                     PackageEntry* pkg_entry,
1004                                                     Handle class_loader) {
1005   int scp_index = ik->shared_classpath_index();
1006   assert(!ik->is_shared_unregistered_class(), "this function should be called for built-in classes only");
1007   assert(scp_index >= 0, "must be");
1008   SharedClassPathEntry* scp_entry = FileMapInfo::shared_path(scp_index);
1009   if (!Universe::is_module_initialized()) {
1010     assert(scp_entry != NULL && scp_entry->is_modules_image(),
1011            "Loading non-bootstrap classes before the module system is initialized");
1012     assert(class_loader.is_null(), "sanity");
1013     return true;
1014   }
1015 
1016   ModuleEntry* mod_entry = (pkg_entry == NULL) ? NULL : pkg_entry->module();
1017   bool should_be_in_named_module = (mod_entry != NULL && mod_entry->is_named());
1018   bool was_archived_from_named_module = scp_entry->in_named_module();
1019   bool visible;
1020 
1021   if (was_archived_from_named_module) {
1022     if (should_be_in_named_module) {
1023       // Is the module loaded from the same location as during dump time?
1024       visible = mod_entry->shared_path_index() == scp_index;
1025       if (visible) {
1026         assert(!mod_entry->is_patched(), "cannot load archived classes for patched module");
1027       }
1028     } else {
1029       // During dump time, this class was in a named module, but at run time, this class should be
1030       // in an unnamed module.
1031       visible = false;
1032     }
1033   } else {
1034     if (should_be_in_named_module) {
1035       // During dump time, this class was in an unnamed, but at run time, this class should be
1036       // in a named module.
1037       visible = false;
1038     } else {
1039       visible = true;
1040     }
1041   }
1042 
1043   return visible;
1044 }
1045 
1046 bool SystemDictionary::check_shared_class_super_type(InstanceKlass* klass, InstanceKlass* super_type,
1047                                                      Handle class_loader,  Handle protection_domain,
1048                                                      bool is_superclass, TRAPS) {
1049   assert(super_type->is_shared(), "must be");
1050 
1051   // Quick check if the super type has been already loaded.
1052   // + Don't do it for unregistered classes -- they can be unloaded so
1053   //   super_type->class_loader_data() could be stale.
1054   // + Don't check if loader data is NULL, ie. the super_type isn't fully loaded.
1055   if (!super_type->is_shared_unregistered_class() && super_type->class_loader_data() != NULL) {
1056     // Check if the superclass is loaded by the current class_loader
1057     Symbol* name = super_type->name();
1058     InstanceKlass* check = find_instance_klass(name, class_loader, protection_domain);
1059     if (check == super_type) {
1060       return true;
1061     }
1062   }
1063 
1064   Klass *found = resolve_super_or_fail(klass->name(), super_type->name(),
1065                                        class_loader, protection_domain, is_superclass, CHECK_0);
1066   if (found == super_type) {
1067     return true;
1068   } else {
1069     // The dynamically resolved super type is not the same as the one we used during dump time,
1070     // so we cannot use the class.
1071     return false;
1072   }
1073 }
1074 
1075 bool SystemDictionary::check_shared_class_super_types(InstanceKlass* ik, Handle class_loader,
1076                                                       Handle protection_domain, TRAPS) {
1077   // Check the superclass and interfaces. They must be the same
1078   // as in dump time, because the layout of <ik> depends on
1079   // the specific layout of ik->super() and ik->local_interfaces().
1080   //
1081   // If unexpected superclass or interfaces are found, we cannot
1082   // load <ik> from the shared archive.
1083 
1084   if (ik->super() != NULL &&
1085       !check_shared_class_super_type(ik, InstanceKlass::cast(ik->super()),
1086                                      class_loader, protection_domain, true, THREAD)) {
1087     return false;
1088   }
1089 
1090   Array<InstanceKlass*>* interfaces = ik->local_interfaces();
1091   int num_interfaces = interfaces->length();
1092   for (int index = 0; index < num_interfaces; index++) {
1093     if (!check_shared_class_super_type(ik, interfaces->at(index), class_loader, protection_domain, false, THREAD)) {
1094       return false;
1095     }
1096   }
1097 
1098   return true;
1099 }
1100 
1101 InstanceKlass* SystemDictionary::load_shared_lambda_proxy_class(InstanceKlass* ik,
1102                                                                 Handle class_loader,
1103                                                                 Handle protection_domain,
1104                                                                 PackageEntry* pkg_entry,
1105                                                                 TRAPS) {
1106   InstanceKlass* shared_nest_host = SystemDictionaryShared::get_shared_nest_host(ik);
1107   assert(shared_nest_host->is_shared(), "nest host must be in CDS archive");
1108   Symbol* cn = shared_nest_host->name();
1109   Klass *s = resolve_or_fail(cn, class_loader, protection_domain, true, CHECK_NULL);
1110   if (s != shared_nest_host) {
1111     // The dynamically resolved nest_host is not the same as the one we used during dump time,
1112     // so we cannot use ik.
1113     return NULL;
1114   } else {
1115     assert(s->is_shared(), "must be");
1116   }
1117 
1118   // The lambda proxy class and its nest host have the same class loader and class loader data,
1119   // as verified in SystemDictionaryShared::add_lambda_proxy_class()
1120   assert(shared_nest_host->class_loader() == class_loader(), "mismatched class loader");
1121   assert(shared_nest_host->class_loader_data() == ClassLoaderData::class_loader_data(class_loader()), "mismatched class loader data");
1122   ik->set_nest_host(shared_nest_host);
1123 
1124   InstanceKlass* loaded_ik = load_shared_class(ik, class_loader, protection_domain, NULL, pkg_entry, CHECK_NULL);
1125 
1126   if (loaded_ik != NULL) {
1127     assert(shared_nest_host->is_same_class_package(ik),
1128            "lambda proxy class and its nest host must be in the same package");
1129   }
1130 
1131   return loaded_ik;
1132 }
1133 
1134 InstanceKlass* SystemDictionary::load_shared_class(InstanceKlass* ik,
1135                                                    Handle class_loader,
1136                                                    Handle protection_domain,
1137                                                    const ClassFileStream *cfs,
1138                                                    PackageEntry* pkg_entry,
1139                                                    TRAPS) {
1140   assert(ik != NULL, "sanity");
1141   assert(!ik->is_unshareable_info_restored(), "shared class can be loaded only once");
1142   Symbol* class_name = ik->name();
1143 
1144   if (!is_shared_class_visible(class_name, ik, pkg_entry, class_loader)) {
1145     return NULL;
1146   }
1147 
1148   if (!check_shared_class_super_types(ik, class_loader, protection_domain, THREAD)) {
1149     return NULL;
1150   }
1151 
1152   InstanceKlass* new_ik = NULL;
1153   // CFLH check is skipped for VM hidden classes (see KlassFactory::create_from_stream).
1154   // It will be skipped for shared VM hidden lambda proxy classes.
1155   if (!SystemDictionaryShared::is_hidden_lambda_proxy(ik)) {
1156     new_ik = KlassFactory::check_shared_class_file_load_hook(
1157       ik, class_name, class_loader, protection_domain, cfs, CHECK_NULL);
1158   }
1159   if (new_ik != NULL) {
1160     // The class is changed by CFLH. Return the new class. The shared class is
1161     // not used.
1162     return new_ik;
1163   }
1164 
1165   // Adjust methods to recover missing data.  They need addresses for
1166   // interpreter entry points and their default native method address
1167   // must be reset.
1168 
1169   // Shared classes are all currently loaded by either the bootstrap or
1170   // internal parallel class loaders, so this will never cause a deadlock
1171   // on a custom class loader lock.
1172   // Since this class is already locked with parallel capable class
1173   // loaders, including the bootstrap loader via the placeholder table,
1174   // this lock is currently a nop.
1175 
1176   ClassLoaderData* loader_data = ClassLoaderData::class_loader_data(class_loader());
1177   {
1178     HandleMark hm(THREAD);
1179     Handle lockObject = get_loader_lock_or_null(class_loader);
1180     ObjectLocker ol(lockObject, THREAD);
1181     // prohibited package check assumes all classes loaded from archive call
1182     // restore_unshareable_info which calls ik->set_package()
1183     ik->restore_unshareable_info(loader_data, protection_domain, pkg_entry, CHECK_NULL);
1184   }
1185 
1186   load_shared_class_misc(ik, loader_data);
1187   return ik;
1188 }
1189 
1190 void SystemDictionary::load_shared_class_misc(InstanceKlass* ik, ClassLoaderData* loader_data) {
1191   ik->print_class_load_logging(loader_data, NULL, NULL);
1192 
1193   // For boot loader, ensure that GetSystemPackage knows that a class in this
1194   // package was loaded.
1195   if (loader_data->is_the_null_class_loader_data()) {
1196     int path_index = ik->shared_classpath_index();
1197     ik->set_classpath_index(path_index);
1198   }
1199 
1200   // notify a class loaded from shared object
1201   ClassLoadingService::notify_class_loaded(ik, true /* shared class */);
1202 }
1203 
1204 #endif // INCLUDE_CDS
1205 
1206 InstanceKlass* SystemDictionary::load_instance_class_impl(Symbol* class_name, Handle class_loader, TRAPS) {
1207 
1208   if (class_loader.is_null()) {
1209     ResourceMark rm(THREAD);
1210     PackageEntry* pkg_entry = NULL;
1211     bool search_only_bootloader_append = false;
1212     ClassLoaderData *loader_data = class_loader_data(class_loader);
1213 
1214     // Find the package in the boot loader's package entry table.
1215     TempNewSymbol pkg_name = ClassLoader::package_from_class_name(class_name);
1216     if (pkg_name != NULL) {
1217       pkg_entry = loader_data->packages()->lookup_only(pkg_name);
1218     }
1219 
1220     // Prior to attempting to load the class, enforce the boot loader's
1221     // visibility boundaries.
1222     if (!Universe::is_module_initialized()) {
1223       // During bootstrapping, prior to module initialization, any
1224       // class attempting to be loaded must be checked against the
1225       // java.base packages in the boot loader's PackageEntryTable.
1226       // No class outside of java.base is allowed to be loaded during
1227       // this bootstrapping window.
1228       if (pkg_entry == NULL || pkg_entry->in_unnamed_module()) {
1229         // Class is either in the unnamed package or in
1230         // a named package within the unnamed module.  Either
1231         // case is outside of java.base, do not attempt to
1232         // load the class post java.base definition.  If
1233         // java.base has not been defined, let the class load
1234         // and its package will be checked later by
1235         // ModuleEntryTable::verify_javabase_packages.
1236         if (ModuleEntryTable::javabase_defined()) {
1237           return NULL;
1238         }
1239       } else {
1240         // Check that the class' package is defined within java.base.
1241         ModuleEntry* mod_entry = pkg_entry->module();
1242         Symbol* mod_entry_name = mod_entry->name();
1243         if (mod_entry_name->fast_compare(vmSymbols::java_base()) != 0) {
1244           return NULL;
1245         }
1246       }
1247     } else {
1248       // After the module system has been initialized, check if the class'
1249       // package is in a module defined to the boot loader.
1250       if (pkg_name == NULL || pkg_entry == NULL || pkg_entry->in_unnamed_module()) {
1251         // Class is either in the unnamed package, in a named package
1252         // within a module not defined to the boot loader or in a
1253         // a named package within the unnamed module.  In all cases,
1254         // limit visibility to search for the class only in the boot
1255         // loader's append path.
1256         if (!ClassLoader::has_bootclasspath_append()) {
1257            // If there is no bootclasspath append entry, no need to continue
1258            // searching.
1259            return NULL;
1260         }
1261         search_only_bootloader_append = true;
1262       }
1263     }
1264 
1265     // Prior to bootstrapping's module initialization, never load a class outside
1266     // of the boot loader's module path
1267     assert(Universe::is_module_initialized() ||
1268            !search_only_bootloader_append,
1269            "Attempt to load a class outside of boot loader's module path");
1270 
1271     // Search for classes in the CDS archive.
1272     InstanceKlass* k = NULL;
1273 
1274 #if INCLUDE_CDS
1275     if (UseSharedSpaces)
1276     {
1277       PerfTraceTime vmtimer(ClassLoader::perf_shared_classload_time());
1278       InstanceKlass* ik = SystemDictionaryShared::find_builtin_class(class_name);
1279       if (ik != NULL && ik->is_shared_boot_class() && !ik->shared_loading_failed()) {
1280         SharedClassLoadingMark slm(THREAD, ik);
1281         k = load_shared_class(ik, class_loader, Handle(), NULL,  pkg_entry, CHECK_NULL);
1282       }
1283     }
1284 #endif
1285 
1286     if (k == NULL) {
1287       // Use VM class loader
1288       PerfTraceTime vmtimer(ClassLoader::perf_sys_classload_time());
1289       k = ClassLoader::load_class(class_name, search_only_bootloader_append, CHECK_NULL);
1290     }
1291 
1292     // find_or_define_instance_class may return a different InstanceKlass
1293     if (k != NULL) {
1294       CDS_ONLY(SharedClassLoadingMark slm(THREAD, k);)
1295       k = find_or_define_instance_class(class_name, class_loader, k, CHECK_NULL);
1296     }
1297     return k;
1298   } else {
1299     // Use user specified class loader to load class. Call loadClass operation on class_loader.
1300     ResourceMark rm(THREAD);
1301 
1302     JavaThread* jt = THREAD;
1303 
1304     PerfClassTraceTime vmtimer(ClassLoader::perf_app_classload_time(),
1305                                ClassLoader::perf_app_classload_selftime(),
1306                                ClassLoader::perf_app_classload_count(),
1307                                jt->get_thread_stat()->perf_recursion_counts_addr(),
1308                                jt->get_thread_stat()->perf_timers_addr(),
1309                                PerfClassTraceTime::CLASS_LOAD);
1310 
1311     // Translate to external class name format, i.e., convert '/' chars to '.'
1312     Handle string = java_lang_String::externalize_classname(class_name, CHECK_NULL);
1313 
1314     JavaValue result(T_OBJECT);
1315 
1316     InstanceKlass* spec_klass = vmClasses::ClassLoader_klass();
1317 
1318     // Call public unsynchronized loadClass(String) directly for all class loaders.
1319     // For parallelCapable class loaders, JDK >=7, loadClass(String, boolean) will
1320     // acquire a class-name based lock rather than the class loader object lock.
1321     // JDK < 7 already acquire the class loader lock in loadClass(String, boolean).
1322     JavaCalls::call_virtual(&result,
1323                             class_loader,
1324                             spec_klass,
1325                             vmSymbols::loadClass_name(),
1326                             vmSymbols::string_class_signature(),
1327                             string,
1328                             CHECK_NULL);
1329 
1330     assert(result.get_type() == T_OBJECT, "just checking");
1331     oop obj = result.get_oop();
1332 
1333     // Primitive classes return null since forName() can not be
1334     // used to obtain any of the Class objects representing primitives or void
1335     if ((obj != NULL) && !(java_lang_Class::is_primitive(obj))) {
1336       InstanceKlass* k = InstanceKlass::cast(java_lang_Class::as_Klass(obj));
1337       // For user defined Java class loaders, check that the name returned is
1338       // the same as that requested.  This check is done for the bootstrap
1339       // loader when parsing the class file.
1340       if (class_name == k->name()) {
1341         return k;
1342       }
1343     }
1344     // Class is not found or has the wrong name, return NULL
1345     return NULL;
1346   }
1347 }
1348 
1349 InstanceKlass* SystemDictionary::load_instance_class(unsigned int name_hash,
1350                                                      Symbol* name,
1351                                                      Handle class_loader,
1352                                                      TRAPS) {
1353 
1354   InstanceKlass* loaded_class = load_instance_class_impl(name, class_loader, CHECK_NULL);
1355 
1356   // If everything was OK (no exceptions, no null return value), and
1357   // class_loader is NOT the defining loader, do a little more bookkeeping.
1358   if (loaded_class != NULL &&
1359     loaded_class->class_loader() != class_loader()) {
1360 
1361     check_constraints(name_hash, loaded_class, class_loader, false, CHECK_NULL);
1362 
1363     // Record dependency for non-parent delegation.
1364     // This recording keeps the defining class loader of the klass (loaded_class) found
1365     // from being unloaded while the initiating class loader is loaded
1366     // even if the reference to the defining class loader is dropped
1367     // before references to the initiating class loader.
1368     ClassLoaderData* loader_data = class_loader_data(class_loader);
1369     loader_data->record_dependency(loaded_class);
1370 
1371     { // Grabbing the Compile_lock prevents systemDictionary updates
1372       // during compilations.
1373       MutexLocker mu(THREAD, Compile_lock);
1374       update_dictionary(name_hash, loaded_class, class_loader);
1375     }
1376 
1377     if (JvmtiExport::should_post_class_load()) {
1378       JvmtiExport::post_class_load(THREAD, loaded_class);
1379     }
1380   }
1381   return loaded_class;
1382 }
1383 
1384 static void post_class_define_event(InstanceKlass* k, const ClassLoaderData* def_cld) {
1385   EventClassDefine event;
1386   if (event.should_commit()) {
1387     event.set_definedClass(k);
1388     event.set_definingClassLoader(def_cld);
1389     event.commit();
1390   }
1391 }
1392 
1393 void SystemDictionary::define_instance_class(InstanceKlass* k, Handle class_loader, TRAPS) {
1394 
1395   ClassLoaderData* loader_data = k->class_loader_data();
1396   assert(loader_data->class_loader() == class_loader(), "they must be the same");
1397 
1398   // Bootstrap and other parallel classloaders don't acquire a lock,
1399   // they use placeholder token.
1400   // If a parallelCapable class loader calls define_instance_class instead of
1401   // find_or_define_instance_class to get here, we have a timing
1402   // hole with systemDictionary updates and check_constraints
1403   if (!is_parallelCapable(class_loader)) {
1404     assert(ObjectSynchronizer::current_thread_holds_lock(THREAD,
1405            get_loader_lock_or_null(class_loader)),
1406            "define called without lock");
1407   }
1408 
1409   // Check class-loading constraints. Throw exception if violation is detected.
1410   // Grabs and releases SystemDictionary_lock
1411   // The check_constraints/find_class call and update_dictionary sequence
1412   // must be "atomic" for a specific class/classloader pair so we never
1413   // define two different instanceKlasses for that class/classloader pair.
1414   // Existing classloaders will call define_instance_class with the
1415   // classloader lock held
1416   // Parallel classloaders will call find_or_define_instance_class
1417   // which will require a token to perform the define class
1418   Symbol*  name_h = k->name();
1419   Dictionary* dictionary = loader_data->dictionary();
1420   unsigned int name_hash = dictionary->compute_hash(name_h);
1421   check_constraints(name_hash, k, class_loader, true, CHECK);
1422 
1423   // Register class just loaded with class loader (placed in ArrayList)
1424   // Note we do this before updating the dictionary, as this can
1425   // fail with an OutOfMemoryError (if it does, we will *not* put this
1426   // class in the dictionary and will not update the class hierarchy).
1427   // JVMTI FollowReferences needs to find the classes this way.
1428   if (k->class_loader() != NULL) {
1429     methodHandle m(THREAD, Universe::loader_addClass_method());
1430     JavaValue result(T_VOID);
1431     JavaCallArguments args(class_loader);
1432     args.push_oop(Handle(THREAD, k->java_mirror()));
1433     JavaCalls::call(&result, m, &args, CHECK);
1434   }
1435 
1436   // Add the new class. We need recompile lock during update of CHA.
1437   {
1438     MutexLocker mu_r(THREAD, Compile_lock);
1439 
1440     // Add to class hierarchy, and do possible deoptimizations.
1441     add_to_hierarchy(k);
1442 
1443     // Add to systemDictionary - so other classes can see it.
1444     // Grabs and releases SystemDictionary_lock
1445     update_dictionary(name_hash, k, class_loader);
1446   }
1447   k->eager_initialize(THREAD);
1448 
1449   // notify jvmti
1450   if (JvmtiExport::should_post_class_load()) {
1451     JvmtiExport::post_class_load(THREAD, k);
1452   }
1453   post_class_define_event(k, loader_data);
1454 }
1455 
1456 // Support parallel classloading
1457 // All parallel class loaders, including bootstrap classloader
1458 // lock a placeholder entry for this class/class_loader pair
1459 // to allow parallel defines of different classes for this class loader
1460 // With AllowParallelDefine flag==true, in case they do not synchronize around
1461 // FindLoadedClass/DefineClass, calls, we check for parallel
1462 // loading for them, wait if a defineClass is in progress
1463 // and return the initial requestor's results
1464 // This flag does not apply to the bootstrap classloader.
1465 // With AllowParallelDefine flag==false, call through to define_instance_class
1466 // which will throw LinkageError: duplicate class definition.
1467 // False is the requested default.
1468 // For better performance, the class loaders should synchronize
1469 // findClass(), i.e. FindLoadedClass/DefineClassIfAbsent or they
1470 // potentially waste time reading and parsing the bytestream.
1471 // Note: VM callers should ensure consistency of k/class_name,class_loader
1472 // Be careful when modifying this code: once you have run
1473 // placeholders()->find_and_add(PlaceholderTable::DEFINE_CLASS),
1474 // you need to find_and_remove it before returning.
1475 // So be careful to not exit with a CHECK_ macro between these calls.
1476 InstanceKlass* SystemDictionary::find_or_define_helper(Symbol* class_name, Handle class_loader,
1477                                                        InstanceKlass* k, TRAPS) {
1478 
1479   Symbol*  name_h = k->name(); // passed in class_name may be null
1480   ClassLoaderData* loader_data = class_loader_data(class_loader);
1481   Dictionary* dictionary = loader_data->dictionary();
1482 
1483   unsigned int name_hash = dictionary->compute_hash(name_h);
1484 
1485   // Hold SD lock around find_class and placeholder creation for DEFINE_CLASS
1486   {
1487     MutexLocker mu(THREAD, SystemDictionary_lock);
1488     // First check if class already defined
1489     if (is_parallelDefine(class_loader)) {
1490       InstanceKlass* check = dictionary->find_class(name_hash, name_h);
1491       if (check != NULL) {
1492         return check;
1493       }
1494     }
1495 
1496     // Acquire define token for this class/classloader
1497     assert(placeholders()->compute_hash(name_h) == name_hash, "they're the same hashcode");
1498     PlaceholderEntry* probe = placeholders()->find_and_add(name_hash, name_h, loader_data,
1499                                                            PlaceholderTable::DEFINE_CLASS, NULL, THREAD);
1500     // Wait if another thread defining in parallel
1501     // All threads wait - even those that will throw duplicate class: otherwise
1502     // caller is surprised by LinkageError: duplicate, but findLoadedClass fails
1503     // if other thread has not finished updating dictionary
1504     while (probe->definer() != NULL) {
1505       SystemDictionary_lock->wait();
1506     }
1507     // Only special cases allow parallel defines and can use other thread's results
1508     // Other cases fall through, and may run into duplicate defines
1509     // caught by finding an entry in the SystemDictionary
1510     if (is_parallelDefine(class_loader) && (probe->instance_klass() != NULL)) {
1511       InstanceKlass* ik = probe->instance_klass();
1512       placeholders()->find_and_remove(name_hash, name_h, loader_data, PlaceholderTable::DEFINE_CLASS, THREAD);
1513       SystemDictionary_lock->notify_all();
1514 #ifdef ASSERT
1515       InstanceKlass* check = dictionary->find_class(name_hash, name_h);
1516       assert(check != NULL, "definer missed recording success");
1517 #endif
1518       return ik;
1519     } else {
1520       // This thread will define the class (even if earlier thread tried and had an error)
1521       probe->set_definer(THREAD);
1522     }
1523   }
1524 
1525   define_instance_class(k, class_loader, THREAD);
1526 
1527   // definer must notify any waiting threads
1528   {
1529     MutexLocker mu(THREAD, SystemDictionary_lock);
1530     PlaceholderEntry* probe = placeholders()->get_entry(name_hash, name_h, loader_data);
1531     assert(probe != NULL, "DEFINE_CLASS placeholder lost?");
1532     if (!HAS_PENDING_EXCEPTION) {
1533       probe->set_instance_klass(k);
1534     }
1535     probe->set_definer(NULL);
1536     placeholders()->find_and_remove(name_hash, name_h, loader_data, PlaceholderTable::DEFINE_CLASS, THREAD);
1537     SystemDictionary_lock->notify_all();
1538   }
1539 
1540   return HAS_PENDING_EXCEPTION ? NULL : k;
1541 }
1542 
1543 // If a class loader supports parallel classloading handle parallel define requests.
1544 // find_or_define_instance_class may return a different InstanceKlass
1545 InstanceKlass* SystemDictionary::find_or_define_instance_class(Symbol* class_name, Handle class_loader,
1546                                                                InstanceKlass* k, TRAPS) {
1547   InstanceKlass* defined_k = find_or_define_helper(class_name, class_loader, k, THREAD);
1548   // Clean up original InstanceKlass if duplicate or error
1549   if (!HAS_PENDING_EXCEPTION && defined_k != k) {
1550     // If a parallel capable class loader already defined this class, register 'k' for cleanup.
1551     assert(defined_k != NULL, "Should have a klass if there's no exception");
1552     k->class_loader_data()->add_to_deallocate_list(k);
1553   } else if (HAS_PENDING_EXCEPTION) {
1554     assert(defined_k == NULL, "Should not have a klass if there's an exception");
1555     k->class_loader_data()->add_to_deallocate_list(k);
1556   }
1557   return defined_k;
1558 }
1559 
1560 
1561 // ----------------------------------------------------------------------------
1562 // Update hierachy. This is done before the new klass has been added to the SystemDictionary. The Compile_lock
1563 // is held, to ensure that the compiler is not using the class hierachy, and that deoptimization will kick in
1564 // before a new class is used.
1565 
1566 void SystemDictionary::add_to_hierarchy(InstanceKlass* k) {
1567   assert(k != NULL, "just checking");
1568   if (Universe::is_fully_initialized()) {
1569     assert_locked_or_safepoint(Compile_lock);
1570   }
1571 
1572   k->set_init_state(InstanceKlass::loaded);
1573   // make sure init_state store is already done.
1574   // The compiler reads the hierarchy outside of the Compile_lock.
1575   // Access ordering is used to add to hierarchy.
1576 
1577   // Link into hierachy.
1578   k->append_to_sibling_list();                    // add to superklass/sibling list
1579   k->process_interfaces();                        // handle all "implements" declarations
1580 
1581   // Now flush all code that depended on old class hierarchy.
1582   // Note: must be done *after* linking k into the hierarchy (was bug 12/9/97)
1583   if (Universe::is_fully_initialized()) {
1584     CodeCache::flush_dependents_on(k);
1585   }
1586 }
1587 
1588 // ----------------------------------------------------------------------------
1589 // GC support
1590 
1591 // Assumes classes in the SystemDictionary are only unloaded at a safepoint
1592 bool SystemDictionary::do_unloading(GCTimer* gc_timer) {
1593 
1594   bool unloading_occurred;
1595   bool is_concurrent = !SafepointSynchronize::is_at_safepoint();
1596   {
1597     GCTraceTime(Debug, gc, phases) t("ClassLoaderData", gc_timer);
1598     assert_locked_or_safepoint(ClassLoaderDataGraph_lock);  // caller locks.
1599     // First, mark for unload all ClassLoaderData referencing a dead class loader.
1600     unloading_occurred = ClassLoaderDataGraph::do_unloading();
1601     if (unloading_occurred) {
1602       MutexLocker ml2(is_concurrent ? Module_lock : NULL);
1603       JFR_ONLY(Jfr::on_unloading_classes();)
1604 
1605       MutexLocker ml1(is_concurrent ? SystemDictionary_lock : NULL);
1606       ClassLoaderDataGraph::clean_module_and_package_info();
1607       constraints()->purge_loader_constraints();
1608       resolution_errors()->purge_resolution_errors();
1609     }
1610   }
1611 
1612   GCTraceTime(Debug, gc, phases) t("Trigger cleanups", gc_timer);
1613 
1614   if (unloading_occurred) {
1615     SymbolTable::trigger_cleanup();
1616 
1617     if (java_lang_System::allow_security_manager()) {
1618       // Oops referenced by the protection domain cache table may get unreachable independently
1619       // of the class loader (eg. cached protection domain oops). So we need to
1620       // explicitly unlink them here.
1621       // All protection domain oops are linked to the caller class, so if nothing
1622       // unloads, this is not needed.
1623       _pd_cache_table->trigger_cleanup();
1624     } else {
1625       assert(_pd_cache_table->number_of_entries() == 0, "should be empty");
1626     }
1627 
1628     InstanceKlass::clean_initialization_error_table();
1629   }
1630 
1631   return unloading_occurred;
1632 }
1633 
1634 void SystemDictionary::methods_do(void f(Method*)) {
1635   // Walk methods in loaded classes
1636   MutexLocker ml(ClassLoaderDataGraph_lock);
1637   ClassLoaderDataGraph::methods_do(f);
1638   // Walk method handle intrinsics
1639   invoke_method_table()->methods_do(f);
1640 }
1641 
1642 // ----------------------------------------------------------------------------
1643 // Initialization
1644 
1645 void SystemDictionary::initialize(TRAPS) {
1646   // Allocate arrays
1647   _placeholders        = new PlaceholderTable(_placeholder_table_size);
1648   _loader_constraints  = new LoaderConstraintTable(_loader_constraint_size);
1649   _resolution_errors   = new ResolutionErrorTable(_resolution_error_size);
1650   _invoke_method_table = new SymbolPropertyTable(_invoke_method_size);
1651   _pd_cache_table = new ProtectionDomainCacheTable(defaultProtectionDomainCacheSize);
1652 
1653   // Resolve basic classes
1654   vmClasses::resolve_all(CHECK);
1655   // Resolve classes used by archived heap objects
1656   if (UseSharedSpaces) {
1657     HeapShared::resolve_classes(THREAD);
1658   }
1659 }
1660 
1661 // Constraints on class loaders. The details of the algorithm can be
1662 // found in the OOPSLA'98 paper "Dynamic Class Loading in the Java
1663 // Virtual Machine" by Sheng Liang and Gilad Bracha.  The basic idea is
1664 // that the dictionary needs to maintain a set of contraints that
1665 // must be satisfied by all classes in the dictionary.
1666 // if defining is true, then LinkageError if already in dictionary
1667 // if initiating loader, then ok if InstanceKlass matches existing entry
1668 
1669 void SystemDictionary::check_constraints(unsigned int name_hash,
1670                                          InstanceKlass* k,
1671                                          Handle class_loader,
1672                                          bool defining,
1673                                          TRAPS) {
1674   ResourceMark rm(THREAD);
1675   stringStream ss;
1676   bool throwException = false;
1677 
1678   {
1679     Symbol *name = k->name();
1680     ClassLoaderData *loader_data = class_loader_data(class_loader);
1681 
1682     MutexLocker mu(THREAD, SystemDictionary_lock);
1683 
1684     InstanceKlass* check = loader_data->dictionary()->find_class(name_hash, name);
1685     if (check != NULL) {
1686       // If different InstanceKlass - duplicate class definition,
1687       // else - ok, class loaded by a different thread in parallel.
1688       // We should only have found it if it was done loading and ok to use.
1689 
1690       if ((defining == true) || (k != check)) {
1691         throwException = true;
1692         ss.print("loader %s", loader_data->loader_name_and_id());
1693         ss.print(" attempted duplicate %s definition for %s. (%s)",
1694                  k->external_kind(), k->external_name(), k->class_in_module_of_loader(false, true));
1695       } else {
1696         return;
1697       }
1698     }
1699 
1700     if (throwException == false) {
1701       if (constraints()->check_or_update(k, class_loader, name) == false) {
1702         throwException = true;
1703         ss.print("loader constraint violation: loader %s", loader_data->loader_name_and_id());
1704         ss.print(" wants to load %s %s.",
1705                  k->external_kind(), k->external_name());
1706         Klass *existing_klass = constraints()->find_constrained_klass(name, class_loader);
1707         if (existing_klass != NULL && existing_klass->class_loader() != class_loader()) {
1708           ss.print(" A different %s with the same name was previously loaded by %s. (%s)",
1709                    existing_klass->external_kind(),
1710                    existing_klass->class_loader_data()->loader_name_and_id(),
1711                    existing_klass->class_in_module_of_loader(false, true));
1712         } else {
1713           ss.print(" (%s)", k->class_in_module_of_loader(false, true));
1714         }
1715       }
1716     }
1717   }
1718 
1719   // Throw error now if needed (cannot throw while holding
1720   // SystemDictionary_lock because of rank ordering)
1721   if (throwException == true) {
1722     THROW_MSG(vmSymbols::java_lang_LinkageError(), ss.as_string());
1723   }
1724 }
1725 
1726 // Update class loader data dictionary - done after check_constraint and add_to_hierachy
1727 // have been called.
1728 void SystemDictionary::update_dictionary(unsigned int hash,
1729                                          InstanceKlass* k,
1730                                          Handle class_loader) {
1731   // Compile_lock prevents systemDictionary updates during compilations
1732   assert_locked_or_safepoint(Compile_lock);
1733   Symbol*  name  = k->name();
1734   ClassLoaderData *loader_data = class_loader_data(class_loader);
1735 
1736   {
1737     MutexLocker mu1(SystemDictionary_lock);
1738 
1739     // Make a new dictionary entry.
1740     Dictionary* dictionary = loader_data->dictionary();
1741     InstanceKlass* sd_check = dictionary->find_class(hash, name);
1742     if (sd_check == NULL) {
1743       dictionary->add_klass(hash, name, k);
1744     }
1745     SystemDictionary_lock->notify_all();
1746   }
1747 }
1748 
1749 
1750 // Try to find a class name using the loader constraints.  The
1751 // loader constraints might know about a class that isn't fully loaded
1752 // yet and these will be ignored.
1753 Klass* SystemDictionary::find_constrained_instance_or_array_klass(
1754                     Thread* current, Symbol* class_name, Handle class_loader) {
1755 
1756   // First see if it has been loaded directly.
1757   // Force the protection domain to be null.  (This removes protection checks.)
1758   Handle no_protection_domain;
1759   Klass* klass = find_instance_or_array_klass(class_name, class_loader,
1760                                               no_protection_domain);
1761   if (klass != NULL)
1762     return klass;
1763 
1764   // Now look to see if it has been loaded elsewhere, and is subject to
1765   // a loader constraint that would require this loader to return the
1766   // klass that is already loaded.
1767   if (Signature::is_array(class_name)) {
1768     // For array classes, their Klass*s are not kept in the
1769     // constraint table. The element Klass*s are.
1770     SignatureStream ss(class_name, false);
1771     int ndims = ss.skip_array_prefix();  // skip all '['s
1772     BasicType t = ss.type();
1773     if (t != T_OBJECT) {
1774       klass = Universe::typeArrayKlassObj(t);
1775     } else {
1776       MutexLocker mu(current, SystemDictionary_lock);
1777       klass = constraints()->find_constrained_klass(ss.as_symbol(), class_loader);
1778     }
1779     // If element class already loaded, allocate array klass
1780     if (klass != NULL) {
1781       klass = klass->array_klass_or_null(ndims);
1782     }
1783   } else {
1784     MutexLocker mu(current, SystemDictionary_lock);
1785     // Non-array classes are easy: simply check the constraint table.
1786     klass = constraints()->find_constrained_klass(class_name, class_loader);
1787   }
1788 
1789   return klass;
1790 }
1791 
1792 bool SystemDictionary::add_loader_constraint(Symbol* class_name,
1793                                              Klass* klass_being_linked,
1794                                              Handle class_loader1,
1795                                              Handle class_loader2) {
1796   ClassLoaderData* loader_data1 = class_loader_data(class_loader1);
1797   ClassLoaderData* loader_data2 = class_loader_data(class_loader2);
1798 
1799   Symbol* constraint_name = NULL;
1800 
1801   if (!Signature::is_array(class_name)) {
1802     constraint_name = class_name;
1803   } else {
1804     // For array classes, their Klass*s are not kept in the
1805     // constraint table. The element classes are.
1806     SignatureStream ss(class_name, false);
1807     ss.skip_array_prefix();  // skip all '['s
1808     if (!ss.has_envelope()) {
1809       return true;     // primitive types always pass
1810     }
1811     constraint_name = ss.as_symbol();
1812     // Increment refcount to keep constraint_name alive after
1813     // SignatureStream is destructed. It will be decremented below
1814     // before returning.
1815     constraint_name->increment_refcount();
1816   }
1817 
1818   Dictionary* dictionary1 = loader_data1->dictionary();
1819   unsigned int name_hash1 = dictionary1->compute_hash(constraint_name);
1820 
1821   Dictionary* dictionary2 = loader_data2->dictionary();
1822   unsigned int name_hash2 = dictionary2->compute_hash(constraint_name);
1823 
1824   {
1825     MutexLocker mu_s(SystemDictionary_lock);
1826     InstanceKlass* klass1 = dictionary1->find_class(name_hash1, constraint_name);
1827     InstanceKlass* klass2 = dictionary2->find_class(name_hash2, constraint_name);
1828     bool result = constraints()->add_entry(constraint_name, klass1, class_loader1,
1829                                            klass2, class_loader2);
1830 #if INCLUDE_CDS
1831     if (Arguments::is_dumping_archive() && klass_being_linked != NULL &&
1832         !klass_being_linked->is_shared()) {
1833          SystemDictionaryShared::record_linking_constraint(constraint_name,
1834                                      InstanceKlass::cast(klass_being_linked),
1835                                      class_loader1, class_loader2);
1836     }
1837 #endif // INCLUDE_CDS
1838     if (Signature::is_array(class_name)) {
1839       constraint_name->decrement_refcount();
1840     }
1841     return result;
1842   }
1843 }
1844 
1845 // Add entry to resolution error table to record the error when the first
1846 // attempt to resolve a reference to a class has failed.
1847 void SystemDictionary::add_resolution_error(const constantPoolHandle& pool, int which,
1848                                             Symbol* error, Symbol* message,
1849                                             Symbol* cause, Symbol* cause_msg) {
1850   unsigned int hash = resolution_errors()->compute_hash(pool, which);
1851   int index = resolution_errors()->hash_to_index(hash);
1852   {
1853     MutexLocker ml(Thread::current(), SystemDictionary_lock);
1854     ResolutionErrorEntry* entry = resolution_errors()->find_entry(index, hash, pool, which);
1855     if (entry == NULL) {
1856       resolution_errors()->add_entry(index, hash, pool, which, error, message, cause, cause_msg);
1857     }
1858   }
1859 }
1860 
1861 // Delete a resolution error for RedefineClasses for a constant pool is going away
1862 void SystemDictionary::delete_resolution_error(ConstantPool* pool) {
1863   resolution_errors()->delete_entry(pool);
1864 }
1865 
1866 // Lookup resolution error table. Returns error if found, otherwise NULL.
1867 Symbol* SystemDictionary::find_resolution_error(const constantPoolHandle& pool, int which,
1868                                                 Symbol** message, Symbol** cause, Symbol** cause_msg) {
1869   unsigned int hash = resolution_errors()->compute_hash(pool, which);
1870   int index = resolution_errors()->hash_to_index(hash);
1871   {
1872     MutexLocker ml(Thread::current(), SystemDictionary_lock);
1873     ResolutionErrorEntry* entry = resolution_errors()->find_entry(index, hash, pool, which);
1874     if (entry != NULL) {
1875       *message = entry->message();
1876       *cause = entry->cause();
1877       *cause_msg = entry->cause_msg();
1878       return entry->error();
1879     } else {
1880       return NULL;
1881     }
1882   }
1883 }
1884 
1885 // Add an entry to resolution error table to record an error in resolving or
1886 // validating a nest host. This is used to construct informative error
1887 // messages when IllegalAccessError's occur. If an entry already exists it will
1888 // be updated with the nest host error message.
1889 void SystemDictionary::add_nest_host_error(const constantPoolHandle& pool,
1890                                            int which,
1891                                            const char* message) {
1892   unsigned int hash = resolution_errors()->compute_hash(pool, which);
1893   int index = resolution_errors()->hash_to_index(hash);
1894   {
1895     MutexLocker ml(Thread::current(), SystemDictionary_lock);
1896     ResolutionErrorEntry* entry = resolution_errors()->find_entry(index, hash, pool, which);
1897     if (entry != NULL && entry->nest_host_error() == NULL) {
1898       // An existing entry means we had a true resolution failure (LinkageError) with our nest host, but we
1899       // still want to add the error message for the higher-level access checks to report. We should
1900       // only reach here under the same error condition, so we can ignore the potential race with setting
1901       // the message. If we see it is already set then we can ignore it.
1902       entry->set_nest_host_error(message);
1903     } else {
1904       resolution_errors()->add_entry(index, hash, pool, which, message);
1905     }
1906   }
1907 }
1908 
1909 // Lookup any nest host error
1910 const char* SystemDictionary::find_nest_host_error(const constantPoolHandle& pool, int which) {
1911   unsigned int hash = resolution_errors()->compute_hash(pool, which);
1912   int index = resolution_errors()->hash_to_index(hash);
1913   {
1914     MutexLocker ml(Thread::current(), SystemDictionary_lock);
1915     ResolutionErrorEntry* entry = resolution_errors()->find_entry(index, hash, pool, which);
1916     if (entry != NULL) {
1917       return entry->nest_host_error();
1918     } else {
1919       return NULL;
1920     }
1921   }
1922 }
1923 
1924 
1925 // Signature constraints ensure that callers and callees agree about
1926 // the meaning of type names in their signatures.  This routine is the
1927 // intake for constraints.  It collects them from several places:
1928 //
1929 //  * LinkResolver::resolve_method (if check_access is true) requires
1930 //    that the resolving class (the caller) and the defining class of
1931 //    the resolved method (the callee) agree on each type in the
1932 //    method's signature.
1933 //
1934 //  * LinkResolver::resolve_interface_method performs exactly the same
1935 //    checks.
1936 //
1937 //  * LinkResolver::resolve_field requires that the constant pool
1938 //    attempting to link to a field agree with the field's defining
1939 //    class about the type of the field signature.
1940 //
1941 //  * klassVtable::initialize_vtable requires that, when a class
1942 //    overrides a vtable entry allocated by a superclass, that the
1943 //    overriding method (i.e., the callee) agree with the superclass
1944 //    on each type in the method's signature.
1945 //
1946 //  * klassItable::initialize_itable requires that, when a class fills
1947 //    in its itables, for each non-abstract method installed in an
1948 //    itable, the method (i.e., the callee) agree with the interface
1949 //    on each type in the method's signature.
1950 //
1951 // All those methods have a boolean (check_access, checkconstraints)
1952 // which turns off the checks.  This is used from specialized contexts
1953 // such as bootstrapping, dumping, and debugging.
1954 //
1955 // No direct constraint is placed between the class and its
1956 // supertypes.  Constraints are only placed along linked relations
1957 // between callers and callees.  When a method overrides or implements
1958 // an abstract method in a supertype (superclass or interface), the
1959 // constraints are placed as if the supertype were the caller to the
1960 // overriding method.  (This works well, since callers to the
1961 // supertype have already established agreement between themselves and
1962 // the supertype.)  As a result of all this, a class can disagree with
1963 // its supertype about the meaning of a type name, as long as that
1964 // class neither calls a relevant method of the supertype, nor is
1965 // called (perhaps via an override) from the supertype.
1966 //
1967 //
1968 // SystemDictionary::check_signature_loaders(sig, klass_being_linked, l1, l2)
1969 //
1970 // Make sure all class components (including arrays) in the given
1971 // signature will be resolved to the same class in both loaders.
1972 // Returns the name of the type that failed a loader constraint check, or
1973 // NULL if no constraint failed.  No exception except OOME is thrown.
1974 // Arrays are not added to the loader constraint table, their elements are.
1975 Symbol* SystemDictionary::check_signature_loaders(Symbol* signature,
1976                                                   Klass* klass_being_linked,
1977                                                   Handle loader1, Handle loader2,
1978                                                   bool is_method)  {
1979   // Nothing to do if loaders are the same.
1980   if (loader1() == loader2()) {
1981     return NULL;
1982   }
1983 
1984   for (SignatureStream ss(signature, is_method); !ss.is_done(); ss.next()) {
1985     if (ss.is_reference()) {
1986       Symbol* sig = ss.as_symbol();
1987       // Note: In the future, if template-like types can take
1988       // arguments, we will want to recognize them and dig out class
1989       // names hiding inside the argument lists.
1990       if (!add_loader_constraint(sig, klass_being_linked, loader1, loader2)) {
1991         return sig;
1992       }
1993     }
1994   }
1995   return NULL;
1996 }
1997 
1998 Method* SystemDictionary::find_method_handle_intrinsic(vmIntrinsicID iid,
1999                                                        Symbol* signature,
2000                                                        TRAPS) {
2001   methodHandle empty;
2002   const int iid_as_int = vmIntrinsics::as_int(iid);
2003   assert(MethodHandles::is_signature_polymorphic(iid) &&
2004          MethodHandles::is_signature_polymorphic_intrinsic(iid) &&
2005          iid != vmIntrinsics::_invokeGeneric,
2006          "must be a known MH intrinsic iid=%d: %s", iid_as_int, vmIntrinsics::name_at(iid));
2007 
2008   unsigned int hash  = invoke_method_table()->compute_hash(signature, iid_as_int);
2009   int          index = invoke_method_table()->hash_to_index(hash);
2010   SymbolPropertyEntry* spe = invoke_method_table()->find_entry(index, hash, signature, iid_as_int);
2011   methodHandle m;
2012   if (spe == NULL || spe->method() == NULL) {
2013     spe = NULL;
2014     // Must create lots of stuff here, but outside of the SystemDictionary lock.
2015     m = Method::make_method_handle_intrinsic(iid, signature, CHECK_NULL);
2016     if (!Arguments::is_interpreter_only()) {
2017       // Generate a compiled form of the MH intrinsic.
2018       AdapterHandlerLibrary::create_native_wrapper(m);
2019       // Check if have the compiled code.
2020       if (!m->has_compiled_code()) {
2021         THROW_MSG_NULL(vmSymbols::java_lang_VirtualMachineError(),
2022                        "Out of space in CodeCache for method handle intrinsic");
2023       }
2024     }
2025     // Now grab the lock.  We might have to throw away the new method,
2026     // if a racing thread has managed to install one at the same time.
2027     {
2028       MutexLocker ml(THREAD, SystemDictionary_lock);
2029       spe = invoke_method_table()->find_entry(index, hash, signature, iid_as_int);
2030       if (spe == NULL)
2031         spe = invoke_method_table()->add_entry(index, hash, signature, iid_as_int);
2032       if (spe->method() == NULL)
2033         spe->set_method(m());
2034     }
2035   }
2036 
2037   assert(spe != NULL && spe->method() != NULL, "");
2038   assert(Arguments::is_interpreter_only() || (spe->method()->has_compiled_code() &&
2039          spe->method()->code()->entry_point() == spe->method()->from_compiled_entry()),
2040          "MH intrinsic invariant");
2041   return spe->method();
2042 }
2043 
2044 // Helper for unpacking the return value from linkMethod and linkCallSite.
2045 static Method* unpack_method_and_appendix(Handle mname,
2046                                           Klass* accessing_klass,
2047                                           objArrayHandle appendix_box,
2048                                           Handle* appendix_result,
2049                                           TRAPS) {
2050   if (mname.not_null()) {
2051     Method* m = java_lang_invoke_MemberName::vmtarget(mname());
2052     if (m != NULL) {
2053       oop appendix = appendix_box->obj_at(0);
2054       LogTarget(Info, methodhandles) lt;
2055       if (lt.develop_is_enabled()) {
2056         ResourceMark rm(THREAD);
2057         LogStream ls(lt);
2058         ls.print("Linked method=" INTPTR_FORMAT ": ", p2i(m));
2059         m->print_on(&ls);
2060         if (appendix != NULL) { ls.print("appendix = "); appendix->print_on(&ls); }
2061         ls.cr();
2062       }
2063 
2064       (*appendix_result) = Handle(THREAD, appendix);
2065       // the target is stored in the cpCache and if a reference to this
2066       // MemberName is dropped we need a way to make sure the
2067       // class_loader containing this method is kept alive.
2068       methodHandle mh(THREAD, m); // record_dependency can safepoint.
2069       ClassLoaderData* this_key = accessing_klass->class_loader_data();
2070       this_key->record_dependency(m->method_holder());
2071       return mh();
2072     }
2073   }
2074   THROW_MSG_NULL(vmSymbols::java_lang_LinkageError(), "bad value from MethodHandleNatives");
2075 }
2076 
2077 Method* SystemDictionary::find_method_handle_invoker(Klass* klass,
2078                                                      Symbol* name,
2079                                                      Symbol* signature,
2080                                                           Klass* accessing_klass,
2081                                                           Handle *appendix_result,
2082                                                           TRAPS) {
2083   assert(THREAD->can_call_java() ,"");
2084   Handle method_type =
2085     SystemDictionary::find_method_handle_type(signature, accessing_klass, CHECK_NULL);
2086 
2087   int ref_kind = JVM_REF_invokeVirtual;
2088   oop name_oop = StringTable::intern(name, CHECK_NULL);
2089   Handle name_str (THREAD, name_oop);
2090   objArrayHandle appendix_box = oopFactory::new_objArray_handle(vmClasses::Object_klass(), 1, CHECK_NULL);
2091   assert(appendix_box->obj_at(0) == NULL, "");
2092 
2093   // This should not happen.  JDK code should take care of that.
2094   if (accessing_klass == NULL || method_type.is_null()) {
2095     THROW_MSG_NULL(vmSymbols::java_lang_InternalError(), "bad invokehandle");
2096   }
2097 
2098   // call java.lang.invoke.MethodHandleNatives::linkMethod(... String, MethodType) -> MemberName
2099   JavaCallArguments args;
2100   args.push_oop(Handle(THREAD, accessing_klass->java_mirror()));
2101   args.push_int(ref_kind);
2102   args.push_oop(Handle(THREAD, klass->java_mirror()));
2103   args.push_oop(name_str);
2104   args.push_oop(method_type);
2105   args.push_oop(appendix_box);
2106   JavaValue result(T_OBJECT);
2107   JavaCalls::call_static(&result,
2108                          vmClasses::MethodHandleNatives_klass(),
2109                          vmSymbols::linkMethod_name(),
2110                          vmSymbols::linkMethod_signature(),
2111                          &args, CHECK_NULL);
2112   Handle mname(THREAD, result.get_oop());
2113   return unpack_method_and_appendix(mname, accessing_klass, appendix_box, appendix_result, THREAD);
2114 }
2115 
2116 // Decide if we can globally cache a lookup of this class, to be returned to any client that asks.
2117 // We must ensure that all class loaders everywhere will reach this class, for any client.
2118 // This is a safe bet for public classes in java.lang, such as Object and String.
2119 // We also include public classes in java.lang.invoke, because they appear frequently in system-level method types.
2120 // Out of an abundance of caution, we do not include any other classes, not even for packages like java.util.
2121 static bool is_always_visible_class(oop mirror) {
2122   Klass* klass = java_lang_Class::as_Klass(mirror);
2123   if (klass->is_objArray_klass()) {
2124     klass = ObjArrayKlass::cast(klass)->bottom_klass(); // check element type
2125   }
2126   if (klass->is_typeArray_klass()) {
2127     return true; // primitive array
2128   }
2129   assert(klass->is_instance_klass(), "%s", klass->external_name());
2130   return klass->is_public() &&
2131          (InstanceKlass::cast(klass)->is_same_class_package(vmClasses::Object_klass()) ||       // java.lang
2132           InstanceKlass::cast(klass)->is_same_class_package(vmClasses::MethodHandle_klass()));  // java.lang.invoke
2133 }
2134 
2135 // Find or construct the Java mirror (java.lang.Class instance) for
2136 // the given field type signature, as interpreted relative to the
2137 // given class loader.  Handles primitives, void, references, arrays,
2138 // and all other reflectable types, except method types.
2139 // N.B.  Code in reflection should use this entry point.
2140 Handle SystemDictionary::find_java_mirror_for_type(Symbol* signature,
2141                                                    Klass* accessing_klass,
2142                                                    Handle class_loader,
2143                                                    Handle protection_domain,
2144                                                    SignatureStream::FailureMode failure_mode,
2145                                                    TRAPS) {
2146   assert(accessing_klass == NULL || (class_loader.is_null() && protection_domain.is_null()),
2147          "one or the other, or perhaps neither");
2148 
2149   // What we have here must be a valid field descriptor,
2150   // and all valid field descriptors are supported.
2151   // Produce the same java.lang.Class that reflection reports.
2152   if (accessing_klass != NULL) {
2153     class_loader      = Handle(THREAD, accessing_klass->class_loader());
2154     protection_domain = Handle(THREAD, accessing_klass->protection_domain());
2155   }
2156   ResolvingSignatureStream ss(signature, class_loader, protection_domain, false);
2157   oop mirror_oop = ss.as_java_mirror(failure_mode, CHECK_NH);
2158   if (mirror_oop == NULL) {
2159     return Handle();  // report failure this way
2160   }
2161   Handle mirror(THREAD, mirror_oop);
2162 
2163   if (accessing_klass != NULL) {
2164     // Check accessibility, emulating ConstantPool::verify_constant_pool_resolve.
2165     Klass* sel_klass = java_lang_Class::as_Klass(mirror());
2166     if (sel_klass != NULL) {
2167       LinkResolver::check_klass_accessibility(accessing_klass, sel_klass, CHECK_NH);
2168     }
2169   }
2170   return mirror;
2171 }
2172 
2173 
2174 // Ask Java code to find or construct a java.lang.invoke.MethodType for the given
2175 // signature, as interpreted relative to the given class loader.
2176 // Because of class loader constraints, all method handle usage must be
2177 // consistent with this loader.
2178 Handle SystemDictionary::find_method_handle_type(Symbol* signature,
2179                                                  Klass* accessing_klass,
2180                                                  TRAPS) {
2181   Handle empty;
2182   int null_iid = vmIntrinsics::as_int(vmIntrinsics::_none);  // distinct from all method handle invoker intrinsics
2183   unsigned int hash  = invoke_method_table()->compute_hash(signature, null_iid);
2184   int          index = invoke_method_table()->hash_to_index(hash);
2185   SymbolPropertyEntry* spe = invoke_method_table()->find_entry(index, hash, signature, null_iid);
2186   if (spe != NULL && spe->method_type() != NULL) {
2187     assert(java_lang_invoke_MethodType::is_instance(spe->method_type()), "");
2188     return Handle(THREAD, spe->method_type());
2189   } else if (!THREAD->can_call_java()) {
2190     warning("SystemDictionary::find_method_handle_type called from compiler thread");  // FIXME
2191     return Handle();  // do not attempt from within compiler, unless it was cached
2192   }
2193 
2194   Handle class_loader, protection_domain;
2195   if (accessing_klass != NULL) {
2196     class_loader      = Handle(THREAD, accessing_klass->class_loader());
2197     protection_domain = Handle(THREAD, accessing_klass->protection_domain());
2198   }
2199   bool can_be_cached = true;
2200   int npts = ArgumentCount(signature).size();
2201   objArrayHandle pts = oopFactory::new_objArray_handle(vmClasses::Class_klass(), npts, CHECK_(empty));
2202   int arg = 0;
2203   Handle rt; // the return type from the signature
2204   ResourceMark rm(THREAD);
2205   for (SignatureStream ss(signature); !ss.is_done(); ss.next()) {
2206     oop mirror = NULL;
2207     if (can_be_cached) {
2208       // Use neutral class loader to lookup candidate classes to be placed in the cache.
2209       mirror = ss.as_java_mirror(Handle(), Handle(),
2210                                  SignatureStream::ReturnNull, CHECK_(empty));
2211       if (mirror == NULL || (ss.is_reference() && !is_always_visible_class(mirror))) {
2212         // Fall back to accessing_klass context.
2213         can_be_cached = false;
2214       }
2215     }
2216     if (!can_be_cached) {
2217       // Resolve, throwing a real error if it doesn't work.
2218       mirror = ss.as_java_mirror(class_loader, protection_domain,
2219                                  SignatureStream::NCDFError, CHECK_(empty));
2220     }
2221     assert(mirror != NULL, "%s", ss.as_symbol()->as_C_string());
2222     if (ss.at_return_type())
2223       rt = Handle(THREAD, mirror);
2224     else
2225       pts->obj_at_put(arg++, mirror);
2226 
2227     // Check accessibility.
2228     if (!java_lang_Class::is_primitive(mirror) && accessing_klass != NULL) {
2229       Klass* sel_klass = java_lang_Class::as_Klass(mirror);
2230       mirror = NULL;  // safety
2231       // Emulate ConstantPool::verify_constant_pool_resolve.
2232       LinkResolver::check_klass_accessibility(accessing_klass, sel_klass, CHECK_(empty));
2233     }
2234   }
2235   assert(arg == npts, "");
2236 
2237   // call java.lang.invoke.MethodHandleNatives::findMethodHandleType(Class rt, Class[] pts) -> MethodType
2238   JavaCallArguments args(Handle(THREAD, rt()));
2239   args.push_oop(pts);
2240   JavaValue result(T_OBJECT);
2241   JavaCalls::call_static(&result,
2242                          vmClasses::MethodHandleNatives_klass(),
2243                          vmSymbols::findMethodHandleType_name(),
2244                          vmSymbols::findMethodHandleType_signature(),
2245                          &args, CHECK_(empty));
2246   Handle method_type(THREAD, result.get_oop());
2247 
2248   if (can_be_cached) {
2249     // We can cache this MethodType inside the JVM.
2250     MutexLocker ml(THREAD, SystemDictionary_lock);
2251     spe = invoke_method_table()->find_entry(index, hash, signature, null_iid);
2252     if (spe == NULL)
2253       spe = invoke_method_table()->add_entry(index, hash, signature, null_iid);
2254     if (spe->method_type() == NULL) {
2255       spe->set_method_type(method_type());
2256     }
2257   }
2258 
2259   // report back to the caller with the MethodType
2260   return method_type;
2261 }
2262 
2263 Handle SystemDictionary::find_field_handle_type(Symbol* signature,
2264                                                 Klass* accessing_klass,
2265                                                 TRAPS) {
2266   Handle empty;
2267   ResourceMark rm(THREAD);
2268   SignatureStream ss(signature, /*is_method=*/ false);
2269   if (!ss.is_done()) {
2270     Handle class_loader, protection_domain;
2271     if (accessing_klass != NULL) {
2272       class_loader      = Handle(THREAD, accessing_klass->class_loader());
2273       protection_domain = Handle(THREAD, accessing_klass->protection_domain());
2274     }
2275     oop mirror = ss.as_java_mirror(class_loader, protection_domain, SignatureStream::NCDFError, CHECK_(empty));
2276     ss.next();
2277     if (ss.is_done()) {
2278       return Handle(THREAD, mirror);
2279     }
2280   }
2281   return empty;
2282 }
2283 
2284 // Ask Java code to find or construct a method handle constant.
2285 Handle SystemDictionary::link_method_handle_constant(Klass* caller,
2286                                                      int ref_kind, //e.g., JVM_REF_invokeVirtual
2287                                                      Klass* callee,
2288                                                      Symbol* name,
2289                                                      Symbol* signature,
2290                                                      TRAPS) {
2291   Handle empty;
2292   if (caller == NULL) {
2293     THROW_MSG_(vmSymbols::java_lang_InternalError(), "bad MH constant", empty);
2294   }
2295   Handle name_str      = java_lang_String::create_from_symbol(name,      CHECK_(empty));
2296   Handle signature_str = java_lang_String::create_from_symbol(signature, CHECK_(empty));
2297 
2298   // Put symbolic info from the MH constant into freshly created MemberName and resolve it.
2299   Handle mname = vmClasses::MemberName_klass()->allocate_instance_handle(CHECK_(empty));
2300   java_lang_invoke_MemberName::set_clazz(mname(), callee->java_mirror());
2301   java_lang_invoke_MemberName::set_name (mname(), name_str());
2302   java_lang_invoke_MemberName::set_type (mname(), signature_str());
2303   java_lang_invoke_MemberName::set_flags(mname(), MethodHandles::ref_kind_to_flags(ref_kind));
2304 
2305   if (ref_kind == JVM_REF_invokeVirtual &&
2306       MethodHandles::is_signature_polymorphic_public_name(callee, name)) {
2307     // Skip resolution for public signature polymorphic methods such as
2308     // j.l.i.MethodHandle.invoke()/invokeExact() and those on VarHandle
2309     // They require appendix argument which MemberName resolution doesn't handle.
2310     // There's special logic on JDK side to handle them
2311     // (see MethodHandles.linkMethodHandleConstant() and MethodHandles.findVirtualForMH()).
2312   } else {
2313     MethodHandles::resolve_MemberName(mname, caller, 0, false /*speculative_resolve*/, CHECK_(empty));
2314   }
2315 
2316   // After method/field resolution succeeded, it's safe to resolve MH signature as well.
2317   Handle type = MethodHandles::resolve_MemberName_type(mname, caller, CHECK_(empty));
2318 
2319   // call java.lang.invoke.MethodHandleNatives::linkMethodHandleConstant(Class caller, int refKind, Class callee, String name, Object type) -> MethodHandle
2320   JavaCallArguments args;
2321   args.push_oop(Handle(THREAD, caller->java_mirror()));  // the referring class
2322   args.push_int(ref_kind);
2323   args.push_oop(Handle(THREAD, callee->java_mirror()));  // the target class
2324   args.push_oop(name_str);
2325   args.push_oop(type);
2326   JavaValue result(T_OBJECT);
2327   JavaCalls::call_static(&result,
2328                          vmClasses::MethodHandleNatives_klass(),
2329                          vmSymbols::linkMethodHandleConstant_name(),
2330                          vmSymbols::linkMethodHandleConstant_signature(),
2331                          &args, CHECK_(empty));
2332   return Handle(THREAD, result.get_oop());
2333 }
2334 
2335 // Ask Java to run a bootstrap method, in order to create a dynamic call site
2336 // while linking an invokedynamic op, or compute a constant for Dynamic_info CP entry
2337 // with linkage results being stored back into the bootstrap specifier.
2338 void SystemDictionary::invoke_bootstrap_method(BootstrapInfo& bootstrap_specifier, TRAPS) {
2339   // Resolve the bootstrap specifier, its name, type, and static arguments
2340   bootstrap_specifier.resolve_bsm(CHECK);
2341 
2342   // This should not happen.  JDK code should take care of that.
2343   if (bootstrap_specifier.caller() == NULL || bootstrap_specifier.type_arg().is_null()) {
2344     THROW_MSG(vmSymbols::java_lang_InternalError(), "Invalid bootstrap method invocation with no caller or type argument");
2345   }
2346 
2347   bool is_indy = bootstrap_specifier.is_method_call();
2348   objArrayHandle appendix_box;
2349   if (is_indy) {
2350     // Some method calls may require an appendix argument.  Arrange to receive it.
2351     appendix_box = oopFactory::new_objArray_handle(vmClasses::Object_klass(), 1, CHECK);
2352     assert(appendix_box->obj_at(0) == NULL, "");
2353   }
2354 
2355   // call condy: java.lang.invoke.MethodHandleNatives::linkDynamicConstant(caller, condy_index, bsm, type, info)
2356   //       indy: java.lang.invoke.MethodHandleNatives::linkCallSite(caller, indy_index, bsm, name, mtype, info, &appendix)
2357   JavaCallArguments args;
2358   args.push_oop(Handle(THREAD, bootstrap_specifier.caller_mirror()));
2359   args.push_int(bootstrap_specifier.bss_index());
2360   args.push_oop(bootstrap_specifier.bsm());
2361   args.push_oop(bootstrap_specifier.name_arg());
2362   args.push_oop(bootstrap_specifier.type_arg());
2363   args.push_oop(bootstrap_specifier.arg_values());
2364   if (is_indy) {
2365     args.push_oop(appendix_box);
2366   }
2367   JavaValue result(T_OBJECT);
2368   JavaCalls::call_static(&result,
2369                          vmClasses::MethodHandleNatives_klass(),
2370                          is_indy ? vmSymbols::linkCallSite_name() : vmSymbols::linkDynamicConstant_name(),
2371                          is_indy ? vmSymbols::linkCallSite_signature() : vmSymbols::linkDynamicConstant_signature(),
2372                          &args, CHECK);
2373 
2374   Handle value(THREAD, result.get_oop());
2375   if (is_indy) {
2376     Handle appendix;
2377     Method* method = unpack_method_and_appendix(value,
2378                                                 bootstrap_specifier.caller(),
2379                                                 appendix_box,
2380                                                 &appendix, CHECK);
2381     methodHandle mh(THREAD, method);
2382     bootstrap_specifier.set_resolved_method(mh, appendix);
2383   } else {
2384     bootstrap_specifier.set_resolved_value(value);
2385   }
2386 
2387   // sanity check
2388   assert(bootstrap_specifier.is_resolved() ||
2389          (bootstrap_specifier.is_method_call() &&
2390           bootstrap_specifier.resolved_method().not_null()), "bootstrap method call failed");
2391 }
2392 
2393 
2394 ClassLoaderData* SystemDictionary::class_loader_data(Handle class_loader) {
2395   return ClassLoaderData::class_loader_data(class_loader());
2396 }
2397 
2398 bool SystemDictionary::is_nonpublic_Object_method(Method* m) {
2399   assert(m != NULL, "Unexpected NULL Method*");
2400   return !m->is_public() && m->method_holder() == vmClasses::Object_klass();
2401 }
2402 
2403 // ----------------------------------------------------------------------------
2404 
2405 void SystemDictionary::print_on(outputStream *st) {
2406   CDS_ONLY(SystemDictionaryShared::print_on(st));
2407   GCMutexLocker mu(SystemDictionary_lock);
2408 
2409   ClassLoaderDataGraph::print_dictionary(st);
2410 
2411   // Placeholders
2412   placeholders()->print_on(st);
2413   st->cr();
2414 
2415   // loader constraints - print under SD_lock
2416   constraints()->print_on(st);
2417   st->cr();
2418 
2419   _pd_cache_table->print_on(st);
2420   st->cr();
2421 }
2422 
2423 void SystemDictionary::print() { print_on(tty); }
2424 
2425 void SystemDictionary::verify() {
2426   guarantee(constraints() != NULL,
2427             "Verify of loader constraints failed");
2428   guarantee(placeholders()->number_of_entries() >= 0,
2429             "Verify of placeholders failed");
2430 
2431   GCMutexLocker mu(SystemDictionary_lock);
2432 
2433   // Verify dictionary
2434   ClassLoaderDataGraph::verify_dictionary();
2435 
2436   placeholders()->verify();
2437 
2438   // Verify constraint table
2439   guarantee(constraints() != NULL, "Verify of loader constraints failed");
2440   constraints()->verify(placeholders());
2441 
2442   _pd_cache_table->verify();
2443 }
2444 
2445 void SystemDictionary::dump(outputStream *st, bool verbose) {
2446   assert_locked_or_safepoint(SystemDictionary_lock);
2447   if (verbose) {
2448     print_on(st);
2449   } else {
2450     CDS_ONLY(SystemDictionaryShared::print_table_statistics(st));
2451     ClassLoaderDataGraph::print_table_statistics(st);
2452     placeholders()->print_table_statistics(st, "Placeholder Table");
2453     constraints()->print_table_statistics(st, "LoaderConstraints Table");
2454     pd_cache_table()->print_table_statistics(st, "ProtectionDomainCache Table");
2455   }
2456 }
2457 
2458 TableStatistics SystemDictionary::placeholders_statistics() {
2459   MutexLocker ml(SystemDictionary_lock);
2460   return placeholders()->statistics_calculate();
2461 }
2462 
2463 TableStatistics SystemDictionary::loader_constraints_statistics() {
2464   MutexLocker ml(SystemDictionary_lock);
2465   return constraints()->statistics_calculate();
2466 }
2467 
2468 TableStatistics SystemDictionary::protection_domain_cache_statistics() {
2469   MutexLocker ml(SystemDictionary_lock);
2470   return pd_cache_table()->statistics_calculate();
2471 }
2472 
2473 // Utility for dumping dictionaries.
2474 SystemDictionaryDCmd::SystemDictionaryDCmd(outputStream* output, bool heap) :
2475                                  DCmdWithParser(output, heap),
2476   _verbose("-verbose", "Dump the content of each dictionary entry for all class loaders",
2477            "BOOLEAN", false, "false") {
2478   _dcmdparser.add_dcmd_option(&_verbose);
2479 }
2480 
2481 void SystemDictionaryDCmd::execute(DCmdSource source, TRAPS) {
2482   VM_DumpHashtable dumper(output(), VM_DumpHashtable::DumpSysDict,
2483                          _verbose.value());
2484   VMThread::execute(&dumper);
2485 }