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