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