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