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