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