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