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