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