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