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