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