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