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