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