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