1 /*
   2  * Copyright (c) 1997, 2020, 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 "aot/aotLoader.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/vmSymbols.hpp"
  47 #include "code/codeCache.hpp"
  48 #include "compiler/compileBroker.hpp"
  49 #include "gc/shared/gcTraceTime.inline.hpp"
  50 #include "interpreter/bytecodeStream.hpp"
  51 #include "interpreter/interpreter.hpp"
  52 #include "jfr/jfrEvents.hpp"
  53 #include "logging/log.hpp"
  54 #include "logging/logStream.hpp"
  55 #include "memory/filemap.hpp"
  56 #include "memory/heapShared.hpp"
  57 #include "memory/metaspaceClosure.hpp"
  58 #include "memory/oopFactory.hpp"
  59 #include "memory/resourceArea.hpp"
  60 #include "memory/universe.hpp"
  61 #include "oops/access.inline.hpp"
  62 #include "oops/instanceKlass.hpp"
  63 #include "oops/instanceRefKlass.hpp"
  64 #include "oops/klass.inline.hpp"
  65 #include "oops/method.inline.hpp"
  66 #include "oops/methodData.hpp"
  67 #include "oops/objArrayKlass.hpp"
  68 #include "oops/objArrayOop.inline.hpp"
  69 #include "oops/oop.inline.hpp"
  70 #include "oops/oopHandle.inline.hpp"
  71 #include "oops/symbol.hpp"
  72 #include "oops/typeArrayKlass.hpp"
  73 #include "prims/jvmtiExport.hpp"
  74 #include "prims/methodHandles.hpp"
  75 #include "runtime/arguments.hpp"
  76 #include "runtime/biasedLocking.hpp"
  77 #include "runtime/handles.inline.hpp"
  78 #include "runtime/java.hpp"
  79 #include "runtime/javaCalls.hpp"
  80 #include "runtime/mutexLocker.hpp"
  81 #include "runtime/sharedRuntime.hpp"
  82 #include "runtime/signature.hpp"
  83 #include "services/classLoadingService.hpp"
  84 #include "services/diagnosticCommand.hpp"
  85 #include "services/threadService.hpp"
  86 #include "utilities/macros.hpp"
  87 #include "utilities/utf8.hpp"
  88 #if INCLUDE_CDS
  89 #include "classfile/systemDictionaryShared.hpp"
  90 #endif
  91 #if INCLUDE_JFR
  92 #include "jfr/jfr.hpp"
  93 #endif
  94 
  95 PlaceholderTable*      SystemDictionary::_placeholders        = NULL;
  96 LoaderConstraintTable* SystemDictionary::_loader_constraints  = NULL;
  97 ResolutionErrorTable*  SystemDictionary::_resolution_errors   = NULL;
  98 SymbolPropertyTable*   SystemDictionary::_invoke_method_table = NULL;
  99 ProtectionDomainCacheTable*   SystemDictionary::_pd_cache_table = NULL;
 100 
 101 InstanceKlass*      SystemDictionary::_well_known_klasses[SystemDictionary::WKID_LIMIT]
 102                                                           =  { NULL /*, NULL...*/ };
 103 
 104 InstanceKlass*      SystemDictionary::_box_klasses[T_VOID+1]      =  { NULL /*, NULL...*/ };
 105 
 106 
 107 OopHandle   SystemDictionary::_system_loader_lock_obj;
 108 OopHandle   SystemDictionary::_java_system_loader;
 109 OopHandle   SystemDictionary::_java_platform_loader;
 110 
 111 // Default ProtectionDomainCacheSize value
 112 
 113 const int defaultProtectionDomainCacheSize = 1009;
 114 
 115 // ----------------------------------------------------------------------------
 116 // Java-level SystemLoader and PlatformLoader
 117 
 118 oop SystemDictionary::system_loader_lock() {
 119   return _system_loader_lock_obj.resolve();
 120 }
 121 
 122 oop SystemDictionary::java_system_loader() {
 123   return _java_system_loader.resolve();
 124 }
 125 
 126 oop SystemDictionary::java_platform_loader() {
 127   return _java_platform_loader.resolve();
 128 }
 129 
 130 void SystemDictionary::compute_java_loaders(TRAPS) {
 131   JavaValue result(T_OBJECT);
 132   InstanceKlass* class_loader_klass = SystemDictionary::ClassLoader_klass();
 133   JavaCalls::call_static(&result,
 134                          class_loader_klass,
 135                          vmSymbols::getSystemClassLoader_name(),
 136                          vmSymbols::void_classloader_signature(),
 137                          CHECK);
 138 
 139   _java_system_loader = OopHandle(Universe::vm_global(), (oop)result.get_jobject());
 140 
 141   JavaCalls::call_static(&result,
 142                          class_loader_klass,
 143                          vmSymbols::getPlatformClassLoader_name(),
 144                          vmSymbols::void_classloader_signature(),
 145                          CHECK);
 146 
 147   _java_platform_loader = OopHandle(Universe::vm_global(), (oop)result.get_jobject());
 148 }
 149 
 150 ClassLoaderData* SystemDictionary::register_loader(Handle class_loader, bool create_mirror_cld) {
 151   if (create_mirror_cld) {
 152     // Add a new class loader data to the graph.
 153     return ClassLoaderDataGraph::add(class_loader, true);
 154   } else {
 155     return (class_loader() == NULL) ? ClassLoaderData::the_null_class_loader_data() :
 156                                       ClassLoaderDataGraph::find_or_create(class_loader);
 157   }
 158 }
 159 
 160 // ----------------------------------------------------------------------------
 161 // Parallel class loading check
 162 
 163 bool SystemDictionary::is_parallelCapable(Handle class_loader) {
 164   if (class_loader.is_null()) return true;
 165   if (AlwaysLockClassLoader) return false;
 166   return java_lang_ClassLoader::parallelCapable(class_loader());
 167 }
 168 // ----------------------------------------------------------------------------
 169 // ParallelDefineClass flag does not apply to bootclass loader
 170 bool SystemDictionary::is_parallelDefine(Handle class_loader) {
 171    if (class_loader.is_null()) return false;
 172    if (AllowParallelDefineClass && java_lang_ClassLoader::parallelCapable(class_loader())) {
 173      return true;
 174    }
 175    return false;
 176 }
 177 
 178 // Returns true if the passed class loader is the builtin application class loader
 179 // or a custom system class loader. A customer system class loader can be
 180 // specified via -Djava.system.class.loader.
 181 bool SystemDictionary::is_system_class_loader(oop class_loader) {
 182   if (class_loader == NULL) {
 183     return false;
 184   }
 185   return (class_loader->klass() == SystemDictionary::jdk_internal_loader_ClassLoaders_AppClassLoader_klass() ||
 186          class_loader == _java_system_loader.peek());
 187 }
 188 
 189 // Returns true if the passed class loader is the platform class loader.
 190 bool SystemDictionary::is_platform_class_loader(oop class_loader) {
 191   if (class_loader == NULL) {
 192     return false;
 193   }
 194   return (class_loader->klass() == SystemDictionary::jdk_internal_loader_ClassLoaders_PlatformClassLoader_klass());
 195 }
 196 
 197 // ----------------------------------------------------------------------------
 198 // Resolving of classes
 199 
 200 Symbol* SystemDictionary::class_name_symbol(const char* name, Symbol* exception, TRAPS) {
 201   if (name == NULL) {
 202     THROW_MSG_0(exception, "No class name given");
 203   }
 204   if ((int)strlen(name) > Symbol::max_length()) {
 205     // It's impossible to create this class;  the name cannot fit
 206     // into the constant pool.
 207     Exceptions::fthrow(THREAD_AND_LOCATION, exception,
 208                        "Class name exceeds maximum length of %d: %s",
 209                        Symbol::max_length(),
 210                        name);
 211     return NULL;
 212   }
 213   // Callers should ensure that the name is never an illegal UTF8 string.
 214   assert(UTF8::is_legal_utf8((const unsigned char*)name, (int)strlen(name), false),
 215          "Class name is not a valid utf8 string.");
 216 
 217   // Make a new symbol for the class name.
 218   return SymbolTable::new_symbol(name);
 219 }
 220 
 221 // Forwards to resolve_or_null
 222 
 223 Klass* SystemDictionary::resolve_or_fail(Symbol* class_name, Handle class_loader, Handle protection_domain, bool throw_error, TRAPS) {
 224   Klass* klass = resolve_or_null(class_name, class_loader, protection_domain, THREAD);
 225   if (HAS_PENDING_EXCEPTION || klass == NULL) {
 226     // can return a null klass
 227     klass = handle_resolution_exception(class_name, throw_error, klass, THREAD);
 228   }
 229   return klass;
 230 }
 231 
 232 Klass* SystemDictionary::handle_resolution_exception(Symbol* class_name,
 233                                                      bool throw_error,
 234                                                      Klass* klass, TRAPS) {
 235   if (HAS_PENDING_EXCEPTION) {
 236     // If we have a pending exception we forward it to the caller, unless throw_error is true,
 237     // in which case we have to check whether the pending exception is a ClassNotFoundException,
 238     // and if so convert it to a NoClassDefFoundError
 239     // And chain the original ClassNotFoundException
 240     if (throw_error && PENDING_EXCEPTION->is_a(SystemDictionary::ClassNotFoundException_klass())) {
 241       ResourceMark rm(THREAD);
 242       assert(klass == NULL, "Should not have result with exception pending");
 243       Handle e(THREAD, PENDING_EXCEPTION);
 244       CLEAR_PENDING_EXCEPTION;
 245       THROW_MSG_CAUSE_NULL(vmSymbols::java_lang_NoClassDefFoundError(), class_name->as_C_string(), e);
 246     } else {
 247       return NULL;
 248     }
 249   }
 250   // Class not found, throw appropriate error or exception depending on value of throw_error
 251   if (klass == NULL) {
 252     ResourceMark rm(THREAD);
 253     if (throw_error) {
 254       THROW_MSG_NULL(vmSymbols::java_lang_NoClassDefFoundError(), class_name->as_C_string());
 255     } else {
 256       THROW_MSG_NULL(vmSymbols::java_lang_ClassNotFoundException(), class_name->as_C_string());
 257     }
 258   }
 259   return klass;
 260 }
 261 
 262 
 263 Klass* SystemDictionary::resolve_or_fail(Symbol* class_name,
 264                                            bool throw_error, TRAPS)
 265 {
 266   return resolve_or_fail(class_name, Handle(), Handle(), throw_error, THREAD);
 267 }
 268 
 269 
 270 // Forwards to resolve_array_class_or_null or resolve_instance_class_or_null
 271 
 272 Klass* SystemDictionary::resolve_or_null(Symbol* class_name, Handle class_loader, Handle protection_domain, TRAPS) {
 273   if (Signature::is_array(class_name)) {
 274     return resolve_array_class_or_null(class_name, class_loader, protection_domain, THREAD);
 275   } else {
 276     return resolve_instance_class_or_null_helper(class_name, class_loader, protection_domain, THREAD);
 277   }
 278 }
 279 
 280 // name may be in the form of "java/lang/Object" or "Ljava/lang/Object;"
 281 InstanceKlass* SystemDictionary::resolve_instance_class_or_null_helper(Symbol* class_name,
 282                                                                        Handle class_loader,
 283                                                                        Handle protection_domain,
 284                                                                        TRAPS) {
 285   assert(class_name != NULL && !Signature::is_array(class_name), "must be");
 286   if (Signature::has_envelope(class_name)) {
 287     ResourceMark rm(THREAD);
 288     // Ignore wrapping L and ;.
 289     TempNewSymbol name = SymbolTable::new_symbol(class_name->as_C_string() + 1,
 290                                                  class_name->utf8_length() - 2);
 291     return resolve_instance_class_or_null(name, class_loader, protection_domain, THREAD);
 292   } else {
 293     return resolve_instance_class_or_null(class_name, class_loader, protection_domain, THREAD);
 294   }
 295 }
 296 
 297 Klass* SystemDictionary::resolve_or_null(Symbol* class_name, TRAPS) {
 298   return resolve_or_null(class_name, Handle(), Handle(), THREAD);
 299 }
 300 
 301 // Forwards to resolve_instance_class_or_null
 302 
 303 Klass* SystemDictionary::resolve_array_class_or_null(Symbol* class_name,
 304                                                      Handle class_loader,
 305                                                      Handle protection_domain,
 306                                                      TRAPS) {
 307   assert(Signature::is_array(class_name), "must be array");
 308   ResourceMark rm(THREAD);
 309   SignatureStream ss(class_name, false);
 310   int ndims = ss.skip_array_prefix();  // skip all '['s
 311   Klass* k = NULL;
 312   BasicType t = ss.type();
 313   if (ss.has_envelope()) {
 314     Symbol* obj_class = ss.as_symbol();
 315     k = SystemDictionary::resolve_instance_class_or_null(obj_class,
 316                                                          class_loader,
 317                                                          protection_domain,
 318                                                          CHECK_NULL);
 319     if (k != NULL) {
 320       k = k->array_klass(ndims, CHECK_NULL);
 321     }
 322   } else {
 323     k = Universe::typeArrayKlassObj(t);
 324     k = TypeArrayKlass::cast(k)->array_klass(ndims, CHECK_NULL);
 325   }
 326   return k;
 327 }
 328 
 329 
 330 // Must be called for any super-class or super-interface resolution
 331 // during class definition to allow class circularity checking
 332 // super-interface callers:
 333 //    parse_interfaces - for defineClass & jvmtiRedefineClasses
 334 // super-class callers:
 335 //   ClassFileParser - for defineClass & jvmtiRedefineClasses
 336 //   load_shared_class - while loading a class from shared archive
 337 //   resolve_instance_class_or_null:
 338 //     via: handle_parallel_super_load
 339 //      when resolving a class that has an existing placeholder with
 340 //      a saved superclass [i.e. a defineClass is currently in progress]
 341 //      if another thread is trying to resolve the class, it must do
 342 //      super-class checks on its own thread to catch class circularity
 343 // This last call is critical in class circularity checking for cases
 344 // where classloading is delegated to different threads and the
 345 // classloader lock is released.
 346 // Take the case: Base->Super->Base
 347 //   1. If thread T1 tries to do a defineClass of class Base
 348 //    resolve_super_or_fail creates placeholder: T1, Base (super Super)
 349 //   2. resolve_instance_class_or_null does not find SD or placeholder for Super
 350 //    so it tries to load Super
 351 //   3. If we load the class internally, or user classloader uses same thread
 352 //      loadClassFromxxx or defineClass via parseClassFile Super ...
 353 //      3.1 resolve_super_or_fail creates placeholder: T1, Super (super Base)
 354 //      3.3 resolve_instance_class_or_null Base, finds placeholder for Base
 355 //      3.4 calls resolve_super_or_fail Base
 356 //      3.5 finds T1,Base -> throws class circularity
 357 //OR 4. If T2 tries to resolve Super via defineClass Super ...
 358 //      4.1 resolve_super_or_fail creates placeholder: T2, Super (super Base)
 359 //      4.2 resolve_instance_class_or_null Base, finds placeholder for Base (super Super)
 360 //      4.3 calls resolve_super_or_fail Super in parallel on own thread T2
 361 //      4.4 finds T2, Super -> throws class circularity
 362 // Must be called, even if superclass is null, since this is
 363 // where the placeholder entry is created which claims this
 364 // thread is loading this class/classloader.
 365 // Be careful when modifying this code: once you have run
 366 // placeholders()->find_and_add(PlaceholderTable::LOAD_SUPER),
 367 // you need to find_and_remove it before returning.
 368 // So be careful to not exit with a CHECK_ macro betweeen these calls.
 369 InstanceKlass* SystemDictionary::resolve_super_or_fail(Symbol* child_name,
 370                                                        Symbol* super_name,
 371                                                        Handle class_loader,
 372                                                        Handle protection_domain,
 373                                                        bool is_superclass,
 374                                                        TRAPS) {
 375   assert(!Signature::is_array(super_name), "invalid super class name");
 376 #if INCLUDE_CDS
 377   if (DumpSharedSpaces) {
 378     // Special processing for handling UNREGISTERED shared classes.
 379     InstanceKlass* k = SystemDictionaryShared::dump_time_resolve_super_or_fail(child_name,
 380         super_name, class_loader, protection_domain, is_superclass, CHECK_NULL);
 381     if (k) {
 382       return k;
 383     }
 384   }
 385 #endif // INCLUDE_CDS
 386 
 387   // Double-check, if child class is already loaded, just return super-class,interface
 388   // Don't add a placedholder if already loaded, i.e. already in appropriate class loader
 389   // dictionary.
 390   // Make sure there's a placeholder for the *child* before resolving.
 391   // Used as a claim that this thread is currently loading superclass/classloader
 392   // Used here for ClassCircularity checks and also for heap verification
 393   // (every InstanceKlass needs to be in its class loader dictionary or have a placeholder).
 394   // Must check ClassCircularity before checking if super class is already loaded.
 395   //
 396   // We might not already have a placeholder if this child_name was
 397   // first seen via resolve_from_stream (jni_DefineClass or JVM_DefineClass);
 398   // the name of the class might not be known until the stream is actually
 399   // parsed.
 400   // Bugs 4643874, 4715493
 401 
 402   ClassLoaderData* loader_data = class_loader_data(class_loader);
 403   Dictionary* dictionary = loader_data->dictionary();
 404   unsigned int d_hash = dictionary->compute_hash(child_name);
 405   unsigned int p_hash = placeholders()->compute_hash(child_name);
 406   int p_index = placeholders()->hash_to_index(p_hash);
 407   // can't throw error holding a lock
 408   bool child_already_loaded = false;
 409   bool throw_circularity_error = false;
 410   {
 411     MutexLocker mu(THREAD, SystemDictionary_lock);
 412     InstanceKlass* childk = find_class(d_hash, child_name, dictionary);
 413     InstanceKlass* quicksuperk;
 414     // to support // loading: if child done loading, just return superclass
 415     // if super_name, & class_loader don't match:
 416     // if initial define, SD update will give LinkageError
 417     // if redefine: compare_class_versions will give HIERARCHY_CHANGED
 418     // so we don't throw an exception here.
 419     // see: nsk redefclass014 & java.lang.instrument Instrument032
 420     if ((childk != NULL ) && (is_superclass) &&
 421         ((quicksuperk = childk->java_super()) != NULL) &&
 422          ((quicksuperk->name() == super_name) &&
 423             (quicksuperk->class_loader() == class_loader()))) {
 424            return quicksuperk;
 425     } else {
 426       PlaceholderEntry* probe = placeholders()->get_entry(p_index, p_hash, child_name, loader_data);
 427       if (probe && probe->check_seen_thread(THREAD, PlaceholderTable::LOAD_SUPER)) {
 428           throw_circularity_error = true;
 429       }
 430     }
 431     if (!throw_circularity_error) {
 432       // Be careful not to exit resolve_super
 433       PlaceholderEntry* newprobe = placeholders()->find_and_add(p_index, p_hash, child_name, loader_data, PlaceholderTable::LOAD_SUPER, super_name, THREAD);
 434     }
 435   }
 436   if (throw_circularity_error) {
 437       ResourceMark rm(THREAD);
 438       THROW_MSG_NULL(vmSymbols::java_lang_ClassCircularityError(), child_name->as_C_string());
 439   }
 440 
 441 // java.lang.Object should have been found above
 442   assert(super_name != NULL, "null super class for resolving");
 443   // Resolve the super class or interface, check results on return
 444   InstanceKlass* superk =
 445     SystemDictionary::resolve_instance_class_or_null_helper(super_name,
 446                                                             class_loader,
 447                                                             protection_domain,
 448                                                             THREAD);
 449 
 450   // Clean up of placeholders moved so that each classloadAction registrar self-cleans up
 451   // It is no longer necessary to keep the placeholder table alive until update_dictionary
 452   // or error. GC used to walk the placeholder table as strong roots.
 453   // The instanceKlass is kept alive because the class loader is on the stack,
 454   // which keeps the loader_data alive, as well as all instanceKlasses in
 455   // the loader_data. parseClassFile adds the instanceKlass to loader_data.
 456   {
 457     MutexLocker mu(THREAD, SystemDictionary_lock);
 458     placeholders()->find_and_remove(p_index, p_hash, child_name, loader_data, PlaceholderTable::LOAD_SUPER, THREAD);
 459     SystemDictionary_lock->notify_all();
 460   }
 461   if (HAS_PENDING_EXCEPTION || superk == NULL) {
 462     // can null superk
 463     Klass* k = handle_resolution_exception(super_name, true, superk, THREAD);
 464     assert(k == NULL || k == superk, "must be");
 465     if (k == NULL) {
 466       superk = NULL;
 467     }
 468   }
 469 
 470   return superk;
 471 }
 472 
 473 void SystemDictionary::validate_protection_domain(InstanceKlass* klass,
 474                                                   Handle class_loader,
 475                                                   Handle protection_domain,
 476                                                   TRAPS) {
 477   // Now we have to call back to java to check if the initating class has access
 478   JavaValue result(T_VOID);
 479   LogTarget(Debug, protectiondomain) lt;
 480   if (lt.is_enabled()) {
 481     ResourceMark rm(THREAD);
 482     // Print out trace information
 483     LogStream ls(lt);
 484     ls.print_cr("Checking package access");
 485     if (class_loader() != NULL) {
 486       ls.print("class loader: ");
 487       class_loader()->print_value_on(&ls);
 488     } else {
 489       ls.print_cr("class loader: NULL");
 490     }
 491     if (protection_domain() != NULL) {
 492       ls.print(" protection domain: ");
 493       protection_domain()->print_value_on(&ls);
 494     } else {
 495       ls.print_cr(" protection domain: NULL");
 496     }
 497     ls.print(" loading: "); klass->print_value_on(&ls);
 498     ls.cr();
 499   }
 500 
 501   // This handle and the class_loader handle passed in keeps this class from
 502   // being unloaded through several GC points.
 503   // The class_loader handle passed in is the initiating loader.
 504   Handle mirror(THREAD, klass->java_mirror());
 505 
 506   InstanceKlass* system_loader = SystemDictionary::ClassLoader_klass();
 507   JavaCalls::call_special(&result,
 508                          class_loader,
 509                          system_loader,
 510                          vmSymbols::checkPackageAccess_name(),
 511                          vmSymbols::class_protectiondomain_signature(),
 512                          mirror,
 513                          protection_domain,
 514                          THREAD);
 515 
 516   if (HAS_PENDING_EXCEPTION) {
 517     log_debug(protectiondomain)("DENIED !!!!!!!!!!!!!!!!!!!!!");
 518   } else {
 519    log_debug(protectiondomain)("granted");
 520   }
 521 
 522   if (HAS_PENDING_EXCEPTION) return;
 523 
 524   // If no exception has been thrown, we have validated the protection domain
 525   // Insert the protection domain of the initiating class into the set.
 526   {
 527     ClassLoaderData* loader_data = class_loader_data(class_loader);
 528     Dictionary* dictionary = loader_data->dictionary();
 529 
 530     Symbol*  kn = klass->name();
 531     unsigned int d_hash = dictionary->compute_hash(kn);
 532 
 533     MutexLocker mu(THREAD, SystemDictionary_lock);
 534     int d_index = dictionary->hash_to_index(d_hash);
 535     dictionary->add_protection_domain(d_index, d_hash, klass,
 536                                       protection_domain, THREAD);
 537   }
 538 }
 539 
 540 // We only get here if this thread finds that another thread
 541 // has already claimed the placeholder token for the current operation,
 542 // but that other thread either never owned or gave up the
 543 // object lock
 544 // Waits on SystemDictionary_lock to indicate placeholder table updated
 545 // On return, caller must recheck placeholder table state
 546 //
 547 // We only get here if
 548 //  1) custom classLoader, i.e. not bootstrap classloader
 549 //  2) custom classLoader has broken the class loader objectLock
 550 //     so another thread got here in parallel
 551 //
 552 // lockObject must be held.
 553 // Complicated dance due to lock ordering:
 554 // Must first release the classloader object lock to
 555 // allow initial definer to complete the class definition
 556 // and to avoid deadlock
 557 // Reclaim classloader lock object with same original recursion count
 558 // Must release SystemDictionary_lock after notify, since
 559 // class loader lock must be claimed before SystemDictionary_lock
 560 // to prevent deadlocks
 561 //
 562 // The notify allows applications that did an untimed wait() on
 563 // the classloader object lock to not hang.
 564 void SystemDictionary::double_lock_wait(Handle lockObject, TRAPS) {
 565   assert_lock_strong(SystemDictionary_lock);
 566 
 567   bool calledholdinglock
 568       = ObjectSynchronizer::current_thread_holds_lock(THREAD->as_Java_thread(), lockObject);
 569   assert(calledholdinglock,"must hold lock for notify");
 570   assert((lockObject() != _system_loader_lock_obj.resolve() &&
 571          !is_parallelCapable(lockObject)), "unexpected double_lock_wait");
 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 same thread internally, so we do parallel
 584 // super class loading here.
 585 // This also is critical in cases where the original thread gets stalled
 586 // even in non-circularity situations.
 587 // Note: must call resolve_super_or_fail even if null super -
 588 // to force placeholder entry creation for this class for circularity detection
 589 // Caller must check for pending exception
 590 // Returns non-null Klass* if other thread has completed load
 591 // and we are done,
 592 // If return null Klass* and no pending exception, the caller must load the class
 593 InstanceKlass* SystemDictionary::handle_parallel_super_load(
 594     Symbol* name, Symbol* superclassname, Handle class_loader,
 595     Handle protection_domain, Handle lockObject, TRAPS) {
 596 
 597   ClassLoaderData* loader_data = class_loader_data(class_loader);
 598   Dictionary* dictionary = loader_data->dictionary();
 599   unsigned int d_hash = dictionary->compute_hash(name);
 600   unsigned int p_hash = placeholders()->compute_hash(name);
 601   int p_index = placeholders()->hash_to_index(p_hash);
 602 
 603   // superk is not used, resolve_super called for circularity check only
 604   // This code is reached in two situations. One if this thread
 605   // is loading the same class twice (e.g. ClassCircularity, or
 606   // java.lang.instrument).
 607   // The second is if another thread started the resolve_super first
 608   // and has not yet finished.
 609   // In both cases the original caller will clean up the placeholder
 610   // entry on error.
 611   Klass* superk = SystemDictionary::resolve_super_or_fail(name,
 612                                                           superclassname,
 613                                                           class_loader,
 614                                                           protection_domain,
 615                                                           true,
 616                                                           CHECK_NULL);
 617 
 618   // parallelCapable class loaders do NOT wait for parallel superclass loads to complete
 619   // Serial class loaders and bootstrap classloader do wait for superclass loads
 620  if (!class_loader.is_null() && is_parallelCapable(class_loader)) {
 621     MutexLocker mu(THREAD, SystemDictionary_lock);
 622     // Check if classloading completed while we were loading superclass or waiting
 623     return find_class(d_hash, name, dictionary);
 624   }
 625 
 626   // must loop to both handle other placeholder updates
 627   // and spurious notifications
 628   bool super_load_in_progress = true;
 629   PlaceholderEntry* placeholder;
 630   while (super_load_in_progress) {
 631     MutexLocker mu(THREAD, SystemDictionary_lock);
 632     // Check if classloading completed while we were loading superclass or waiting
 633     InstanceKlass* check = find_class(d_hash, name, dictionary);
 634     if (check != NULL) {
 635       // Klass is already loaded, so just return it
 636       return check;
 637     } else {
 638       placeholder = placeholders()->get_entry(p_index, p_hash, name, loader_data);
 639       if (placeholder && placeholder->super_load_in_progress() ){
 640         // We only get here if the application has released the
 641         // classloader lock when another thread was in the middle of loading a
 642         // superclass/superinterface for this class, and now
 643         // this thread is also trying to load this class.
 644         // To minimize surprises, the first thread that started to
 645         // load a class should be the one to complete the loading
 646         // with the classfile it initially expected.
 647         // This logic has the current thread wait once it has done
 648         // all the superclass/superinterface loading it can, until
 649         // the original thread completes the class loading or fails
 650         // If it completes we will use the resulting InstanceKlass
 651         // which we will find below in the systemDictionary.
 652         // We also get here for parallel bootstrap classloader
 653         if (class_loader.is_null()) {
 654           SystemDictionary_lock->wait();
 655         } else {
 656           double_lock_wait(lockObject, THREAD);
 657         }
 658       } else {
 659         // If not in SD and not in PH, other thread's load must have failed
 660         super_load_in_progress = false;
 661       }
 662     }
 663   }
 664   return NULL;
 665 }
 666 
 667 void SystemDictionary::post_class_load_event(EventClassLoad* event, const InstanceKlass* k, const ClassLoaderData* init_cld) {
 668   assert(event != NULL, "invariant");
 669   assert(k != NULL, "invariant");
 670   assert(event->should_commit(), "invariant");
 671   event->set_loadedClass(k);
 672   event->set_definingClassLoader(k->class_loader_data());
 673   event->set_initiatingClassLoader(init_cld);
 674   event->commit();
 675 }
 676 
 677 
 678 // Be careful when modifying this code: once you have run
 679 // placeholders()->find_and_add(PlaceholderTable::LOAD_INSTANCE),
 680 // you need to find_and_remove it before returning.
 681 // So be careful to not exit with a CHECK_ macro betweeen these calls.
 682 //
 683 // name must be in the form of "java/lang/Object" -- cannot be "Ljava/lang/Object;"
 684 InstanceKlass* SystemDictionary::resolve_instance_class_or_null(Symbol* name,
 685                                                                 Handle class_loader,
 686                                                                 Handle protection_domain,
 687                                                                 TRAPS) {
 688   assert(name != NULL && !Signature::is_array(name) &&
 689          !Signature::has_envelope(name), "invalid class name");
 690 
 691   EventClassLoad class_load_start_event;
 692 
 693   HandleMark hm(THREAD);
 694 
 695   // Fix for 4474172; see evaluation for more details
 696   class_loader = Handle(THREAD, java_lang_ClassLoader::non_reflection_class_loader(class_loader()));
 697   ClassLoaderData* loader_data = register_loader(class_loader);
 698   Dictionary* dictionary = loader_data->dictionary();
 699   unsigned int d_hash = dictionary->compute_hash(name);
 700 
 701   // Do lookup to see if class already exist and the protection domain
 702   // has the right access
 703   // This call uses find which checks protection domain already matches
 704   // All subsequent calls use find_class, and set has_loaded_class so that
 705   // before we return a result we call out to java to check for valid protection domain
 706   // to allow returning the Klass* and add it to the pd_set if it is valid
 707   {
 708     InstanceKlass* probe = dictionary->find(d_hash, name, protection_domain);
 709     if (probe != NULL) return probe;
 710   }
 711 
 712   // Non-bootstrap class loaders will call out to class loader and
 713   // define via jvm/jni_DefineClass which will acquire the
 714   // class loader object lock to protect against multiple threads
 715   // defining the class in parallel by accident.
 716   // This lock must be acquired here so the waiter will find
 717   // any successful result in the SystemDictionary and not attempt
 718   // the define.
 719   // ParallelCapable Classloaders and the bootstrap classloader
 720   // do not acquire lock here.
 721   bool DoObjectLock = true;
 722   if (is_parallelCapable(class_loader)) {
 723     DoObjectLock = false;
 724   }
 725 
 726   unsigned int p_hash = placeholders()->compute_hash(name);
 727   int p_index = placeholders()->hash_to_index(p_hash);
 728 
 729   // Class is not in SystemDictionary so we have to do loading.
 730   // Make sure we are synchronized on the class loader before we proceed
 731   Handle lockObject = compute_loader_lock_object(class_loader, THREAD);
 732   check_loader_lock_contention(lockObject, THREAD);
 733   ObjectLocker ol(lockObject, THREAD, DoObjectLock);
 734 
 735   // Check again (after locking) if class already exist in SystemDictionary
 736   bool class_has_been_loaded   = false;
 737   bool super_load_in_progress  = false;
 738   bool havesupername = false;
 739   InstanceKlass* k = NULL;
 740   PlaceholderEntry* placeholder;
 741   Symbol* superclassname = NULL;
 742 
 743   assert(THREAD->can_call_java(),
 744          "can not load classes with compiler thread: class=%s, classloader=%s",
 745          name->as_C_string(),
 746          class_loader.is_null() ? "null" : class_loader->klass()->name()->as_C_string());
 747   {
 748     MutexLocker mu(THREAD, SystemDictionary_lock);
 749     InstanceKlass* check = find_class(d_hash, name, dictionary);
 750     if (check != NULL) {
 751       // InstanceKlass is already loaded, so just return it
 752       class_has_been_loaded = true;
 753       k = check;
 754     } else {
 755       placeholder = placeholders()->get_entry(p_index, p_hash, name, loader_data);
 756       if (placeholder && placeholder->super_load_in_progress()) {
 757          super_load_in_progress = true;
 758          if (placeholder->havesupername() == true) {
 759            superclassname = placeholder->supername();
 760            havesupername = true;
 761          }
 762       }
 763     }
 764   }
 765 
 766   // If the class is in the placeholder table, class loading is in progress
 767   if (super_load_in_progress && havesupername==true) {
 768     k = handle_parallel_super_load(name,
 769                                    superclassname,
 770                                    class_loader,
 771                                    protection_domain,
 772                                    lockObject, THREAD);
 773     if (HAS_PENDING_EXCEPTION) {
 774       return NULL;
 775     }
 776     if (k != NULL) {
 777       class_has_been_loaded = true;
 778     }
 779   }
 780 
 781   bool throw_circularity_error = false;
 782   if (!class_has_been_loaded) {
 783     bool load_instance_added = false;
 784 
 785     // add placeholder entry to record loading instance class
 786     // Five cases:
 787     // All cases need to prevent modifying bootclasssearchpath
 788     // in parallel with a classload of same classname
 789     // Redefineclasses uses existence of the placeholder for the duration
 790     // of the class load to prevent concurrent redefinition of not completely
 791     // defined classes.
 792     // case 1. traditional classloaders that rely on the classloader object lock
 793     //   - no other need for LOAD_INSTANCE
 794     // case 2. traditional classloaders that break the classloader object lock
 795     //    as a deadlock workaround. Detection of this case requires that
 796     //    this check is done while holding the classloader object lock,
 797     //    and that lock is still held when calling classloader's loadClass.
 798     //    For these classloaders, we ensure that the first requestor
 799     //    completes the load and other requestors wait for completion.
 800     // case 3. Bootstrap classloader - don't own objectLocker
 801     //    This classloader supports parallelism at the classloader level,
 802     //    but only allows a single load of a class/classloader pair.
 803     //    No performance benefit and no deadlock issues.
 804     // case 4. parallelCapable user level classloaders - without objectLocker
 805     //    Allow parallel classloading of a class/classloader pair
 806 
 807     {
 808       MutexLocker mu(THREAD, SystemDictionary_lock);
 809       if (class_loader.is_null() || !is_parallelCapable(class_loader)) {
 810         PlaceholderEntry* oldprobe = placeholders()->get_entry(p_index, p_hash, name, loader_data);
 811         if (oldprobe) {
 812           // only need check_seen_thread once, not on each loop
 813           // 6341374 java/lang/Instrument with -Xcomp
 814           if (oldprobe->check_seen_thread(THREAD, PlaceholderTable::LOAD_INSTANCE)) {
 815             throw_circularity_error = true;
 816           } else {
 817             // case 1: traditional: should never see load_in_progress.
 818             while (!class_has_been_loaded && oldprobe && oldprobe->instance_load_in_progress()) {
 819 
 820               // case 3: bootstrap classloader: prevent futile classloading,
 821               // wait on first requestor
 822               if (class_loader.is_null()) {
 823                 SystemDictionary_lock->wait();
 824               } else {
 825               // case 2: traditional with broken classloader lock. wait on first
 826               // requestor.
 827                 double_lock_wait(lockObject, THREAD);
 828               }
 829               // Check if classloading completed while we were waiting
 830               InstanceKlass* check = find_class(d_hash, name, dictionary);
 831               if (check != NULL) {
 832                 // Klass is already loaded, so just return it
 833                 k = check;
 834                 class_has_been_loaded = true;
 835               }
 836               // check if other thread failed to load and cleaned up
 837               oldprobe = placeholders()->get_entry(p_index, p_hash, name, loader_data);
 838             }
 839           }
 840         }
 841       }
 842       // All cases: add LOAD_INSTANCE holding SystemDictionary_lock
 843       // case 4: parallelCapable: allow competing threads to try
 844       // LOAD_INSTANCE in parallel
 845 
 846       if (!throw_circularity_error && !class_has_been_loaded) {
 847         PlaceholderEntry* newprobe = placeholders()->find_and_add(p_index, p_hash, name, loader_data, PlaceholderTable::LOAD_INSTANCE, NULL, THREAD);
 848         load_instance_added = true;
 849         // For class loaders that do not acquire the classloader object lock,
 850         // if they did not catch another thread holding LOAD_INSTANCE,
 851         // need a check analogous to the acquire ObjectLocker/find_class
 852         // i.e. now that we hold the LOAD_INSTANCE token on loading this class/CL
 853         // one final check if the load has already completed
 854         // class loaders holding the ObjectLock shouldn't find the class here
 855         InstanceKlass* check = find_class(d_hash, name, dictionary);
 856         if (check != NULL) {
 857           // Klass is already loaded, so return it after checking/adding protection domain
 858           k = check;
 859           class_has_been_loaded = true;
 860         }
 861       }
 862     }
 863 
 864     // must throw error outside of owning lock
 865     if (throw_circularity_error) {
 866       assert(!HAS_PENDING_EXCEPTION && load_instance_added == false,"circularity error cleanup");
 867       ResourceMark rm(THREAD);
 868       THROW_MSG_NULL(vmSymbols::java_lang_ClassCircularityError(), name->as_C_string());
 869     }
 870 
 871     if (!class_has_been_loaded) {
 872 
 873       // Do actual loading
 874       k = load_instance_class(name, class_loader, THREAD);
 875 
 876       // If everything was OK (no exceptions, no null return value), and
 877       // class_loader is NOT the defining loader, do a little more bookkeeping.
 878       if (!HAS_PENDING_EXCEPTION && k != NULL &&
 879         k->class_loader() != class_loader()) {
 880 
 881         check_constraints(d_hash, k, class_loader, false, THREAD);
 882 
 883         // Need to check for a PENDING_EXCEPTION again; check_constraints
 884         // can throw but we may have to remove entry from the placeholder table below.
 885         if (!HAS_PENDING_EXCEPTION) {
 886           // Record dependency for non-parent delegation.
 887           // This recording keeps the defining class loader of the klass (k) found
 888           // from being unloaded while the initiating class loader is loaded
 889           // even if the reference to the defining class loader is dropped
 890           // before references to the initiating class loader.
 891           loader_data->record_dependency(k);
 892 
 893           { // Grabbing the Compile_lock prevents systemDictionary updates
 894             // during compilations.
 895             MutexLocker mu(THREAD, Compile_lock);
 896             update_dictionary(d_hash, p_index, p_hash,
 897               k, class_loader, THREAD);
 898           }
 899 
 900           if (JvmtiExport::should_post_class_load()) {
 901             JvmtiExport::post_class_load(THREAD->as_Java_thread(), k);
 902           }
 903         }
 904       }
 905     } // load_instance_class
 906 
 907     if (load_instance_added == true) {
 908       // clean up placeholder entries for LOAD_INSTANCE success or error
 909       // This brackets the SystemDictionary updates for both defining
 910       // and initiating loaders
 911       MutexLocker mu(THREAD, SystemDictionary_lock);
 912       placeholders()->find_and_remove(p_index, p_hash, name, loader_data, PlaceholderTable::LOAD_INSTANCE, THREAD);
 913       SystemDictionary_lock->notify_all();
 914     }
 915   }
 916 
 917   if (HAS_PENDING_EXCEPTION || k == NULL) {
 918     return NULL;
 919   }
 920   if (class_load_start_event.should_commit()) {
 921     post_class_load_event(&class_load_start_event, k, loader_data);
 922   }
 923 #ifdef ASSERT
 924   {
 925     ClassLoaderData* loader_data = k->class_loader_data();
 926     MutexLocker mu(THREAD, SystemDictionary_lock);
 927     InstanceKlass* kk = find_class(name, loader_data);
 928     assert(kk == k, "should be present in dictionary");
 929   }
 930 #endif
 931 
 932   // return if the protection domain in NULL
 933   if (protection_domain() == NULL) return k;
 934 
 935   // Check the protection domain has the right access
 936   if (dictionary->is_valid_protection_domain(d_hash, name,
 937                                              protection_domain)) {
 938     return k;
 939   }
 940 
 941   // Verify protection domain. If it fails an exception is thrown
 942   validate_protection_domain(k, class_loader, protection_domain, CHECK_NULL);
 943 
 944   return k;
 945 }
 946 
 947 
 948 // This routine does not lock the system dictionary.
 949 //
 950 // Since readers don't hold a lock, we must make sure that system
 951 // dictionary entries are only removed at a safepoint (when only one
 952 // thread is running), and are added to in a safe way (all links must
 953 // be updated in an MT-safe manner).
 954 //
 955 // Callers should be aware that an entry could be added just after
 956 // _dictionary->bucket(index) is read here, so the caller will not see
 957 // the new entry.
 958 
 959 Klass* SystemDictionary::find(Symbol* class_name,
 960                               Handle class_loader,
 961                               Handle protection_domain,
 962                               TRAPS) {
 963 
 964   // The result of this call should be consistent with the result
 965   // of the call to resolve_instance_class_or_null().
 966   // See evaluation 6790209 and 4474172 for more details.
 967   class_loader = Handle(THREAD, java_lang_ClassLoader::non_reflection_class_loader(class_loader()));
 968   ClassLoaderData* loader_data = ClassLoaderData::class_loader_data_or_null(class_loader());
 969 
 970   if (loader_data == NULL) {
 971     // If the ClassLoaderData has not been setup,
 972     // then the class loader has no entries in the dictionary.
 973     return NULL;
 974   }
 975 
 976   Dictionary* dictionary = loader_data->dictionary();
 977   unsigned int d_hash = dictionary->compute_hash(class_name);
 978   return dictionary->find(d_hash, class_name,
 979                           protection_domain);
 980 }
 981 
 982 
 983 // Look for a loaded instance or array klass by name.  Do not do any loading.
 984 // return NULL in case of error.
 985 Klass* SystemDictionary::find_instance_or_array_klass(Symbol* class_name,
 986                                                       Handle class_loader,
 987                                                       Handle protection_domain,
 988                                                       TRAPS) {
 989   Klass* k = NULL;
 990   assert(class_name != NULL, "class name must be non NULL");
 991 
 992   if (Signature::is_array(class_name)) {
 993     // The name refers to an array.  Parse the name.
 994     // dimension and object_key in FieldArrayInfo are assigned as a
 995     // side-effect of this call
 996     SignatureStream ss(class_name, false);
 997     int ndims = ss.skip_array_prefix();  // skip all '['s
 998     BasicType t = ss.type();
 999     if (t != T_OBJECT) {
1000       k = Universe::typeArrayKlassObj(t);
1001     } else {
1002       k = SystemDictionary::find(ss.as_symbol(), class_loader, protection_domain, THREAD);
1003     }
1004     if (k != NULL) {
1005       k = k->array_klass_or_null(ndims);
1006     }
1007   } else {
1008     k = find(class_name, class_loader, protection_domain, THREAD);
1009   }
1010   return k;
1011 }
1012 
1013 // Note: this method is much like resolve_from_stream, but
1014 // does not publish the classes via the SystemDictionary.
1015 // Handles Lookup.defineClass hidden, unsafe_DefineAnonymousClass
1016 // and redefineclasses. RedefinedClasses do not add to the class hierarchy.
1017 InstanceKlass* SystemDictionary::parse_stream(Symbol* class_name,
1018                                               Handle class_loader,
1019                                               ClassFileStream* st,
1020                                               const ClassLoadInfo& cl_info,
1021                                               TRAPS) {
1022 
1023   EventClassLoad class_load_start_event;
1024   ClassLoaderData* loader_data;
1025   bool is_unsafe_anon_class = cl_info.unsafe_anonymous_host() != NULL;
1026 
1027   // - for unsafe anonymous class: create a new CLD whith a class holder that uses
1028   //                               the same class loader as the unsafe_anonymous_host.
1029   // - for hidden classes that are not strong: create a new CLD that has a class holder and
1030   //                                           whose loader is the Lookup class's loader.
1031   // - for hidden class: add the class to the Lookup class's loader's CLD.
1032   if (is_unsafe_anon_class || cl_info.is_hidden()) {
1033     guarantee(!is_unsafe_anon_class || cl_info.unsafe_anonymous_host()->class_loader() == class_loader(),
1034               "should be NULL or the same");
1035     bool create_mirror_cld = is_unsafe_anon_class || !cl_info.is_strong_hidden();
1036     loader_data = register_loader(class_loader, create_mirror_cld);
1037   } else {
1038     loader_data = ClassLoaderData::class_loader_data(class_loader());
1039   }
1040 
1041   assert(st != NULL, "invariant");
1042   assert(st->need_verify(), "invariant");
1043 
1044   // Parse stream and create a klass.
1045   // Note that we do this even though this klass might
1046   // already be present in the SystemDictionary, otherwise we would not
1047   // throw potential ClassFormatErrors.
1048 
1049   InstanceKlass* k = KlassFactory::create_from_stream(st,
1050                                                       class_name,
1051                                                       loader_data,
1052                                                       cl_info,
1053                                                       CHECK_NULL);
1054 
1055   if ((cl_info.is_hidden() || is_unsafe_anon_class) && k != NULL) {
1056     // Hidden classes that are not strong and unsafe anonymous classes must update
1057     // ClassLoaderData holder so that they can be unloaded when the mirror is no
1058     // longer referenced.
1059     if (!cl_info.is_strong_hidden() || is_unsafe_anon_class) {
1060       k->class_loader_data()->initialize_holder(Handle(THREAD, k->java_mirror()));
1061     }
1062 
1063     {
1064       MutexLocker mu_r(THREAD, Compile_lock);
1065 
1066       // Add to class hierarchy, initialize vtables, and do possible
1067       // deoptimizations.
1068       add_to_hierarchy(k, CHECK_NULL); // No exception, but can block
1069       // But, do not add to dictionary.
1070     }
1071 
1072     // Rewrite and patch constant pool here.
1073     k->link_class(CHECK_NULL);
1074     if (cl_info.cp_patches() != NULL) {
1075       k->constants()->patch_resolved_references(cl_info.cp_patches());
1076     }
1077 
1078     // If it's anonymous, initialize it now, since nobody else will.
1079     if (is_unsafe_anon_class) {
1080       k->eager_initialize(CHECK_NULL);
1081     }
1082 
1083     // notify jvmti
1084     if (JvmtiExport::should_post_class_load()) {
1085       JvmtiExport::post_class_load(THREAD->as_Java_thread(), k);
1086     }
1087     if (class_load_start_event.should_commit()) {
1088       post_class_load_event(&class_load_start_event, k, loader_data);
1089     }
1090   }
1091   assert(is_unsafe_anon_class || NULL == cl_info.cp_patches(),
1092          "cp_patches only found with unsafe_anonymous_host");
1093 
1094   return k;
1095 }
1096 
1097 // Add a klass to the system from a stream (called by jni_DefineClass and
1098 // JVM_DefineClass).
1099 // Note: class_name can be NULL. In that case we do not know the name of
1100 // the class until we have parsed the stream.
1101 
1102 InstanceKlass* SystemDictionary::resolve_from_stream(Symbol* class_name,
1103                                                      Handle class_loader,
1104                                                      Handle protection_domain,
1105                                                      ClassFileStream* st,
1106                                                      TRAPS) {
1107 
1108   HandleMark hm(THREAD);
1109 
1110   // Classloaders that support parallelism, e.g. bootstrap classloader,
1111   // do not acquire lock here
1112   bool DoObjectLock = true;
1113   if (is_parallelCapable(class_loader)) {
1114     DoObjectLock = false;
1115   }
1116 
1117   ClassLoaderData* loader_data = register_loader(class_loader);
1118 
1119   // Make sure we are synchronized on the class loader before we proceed
1120   Handle lockObject = compute_loader_lock_object(class_loader, THREAD);
1121   check_loader_lock_contention(lockObject, THREAD);
1122   ObjectLocker ol(lockObject, THREAD, DoObjectLock);
1123 
1124   assert(st != NULL, "invariant");
1125 
1126   // Parse the stream and create a klass.
1127   // Note that we do this even though this klass might
1128   // already be present in the SystemDictionary, otherwise we would not
1129   // throw potential ClassFormatErrors.
1130  InstanceKlass* k = NULL;
1131 
1132 #if INCLUDE_CDS
1133   if (!DumpSharedSpaces) {
1134     k = SystemDictionaryShared::lookup_from_stream(class_name,
1135                                                    class_loader,
1136                                                    protection_domain,
1137                                                    st,
1138                                                    CHECK_NULL);
1139   }
1140 #endif
1141 
1142   if (k == NULL) {
1143     if (st->buffer() == NULL) {
1144       return NULL;
1145     }
1146     ClassLoadInfo cl_info(protection_domain);
1147     k = KlassFactory::create_from_stream(st, class_name, loader_data, cl_info, CHECK_NULL);
1148   }
1149 
1150   assert(k != NULL, "no klass created");
1151   Symbol* h_name = k->name();
1152   assert(class_name == NULL || class_name == h_name, "name mismatch");
1153 
1154   // Add class just loaded
1155   // If a class loader supports parallel classloading handle parallel define requests
1156   // find_or_define_instance_class may return a different InstanceKlass
1157   if (is_parallelCapable(class_loader)) {
1158     InstanceKlass* defined_k = find_or_define_instance_class(h_name, class_loader, k, THREAD);
1159     if (!HAS_PENDING_EXCEPTION && defined_k != k) {
1160       // If a parallel capable class loader already defined this class, register 'k' for cleanup.
1161       assert(defined_k != NULL, "Should have a klass if there's no exception");
1162       loader_data->add_to_deallocate_list(k);
1163       k = defined_k;
1164     }
1165   } else {
1166     define_instance_class(k, THREAD);
1167   }
1168 
1169   // If defining the class throws an exception register 'k' for cleanup.
1170   if (HAS_PENDING_EXCEPTION) {
1171     assert(k != NULL, "Must have an instance klass here!");
1172     loader_data->add_to_deallocate_list(k);
1173     return NULL;
1174   }
1175 
1176   // Make sure we have an entry in the SystemDictionary on success
1177   debug_only( {
1178     MutexLocker mu(THREAD, SystemDictionary_lock);
1179 
1180     Klass* check = find_class(h_name, k->class_loader_data());
1181     assert(check == k, "should be present in the dictionary");
1182   } );
1183 
1184   return k;
1185 }
1186 
1187 #if INCLUDE_CDS
1188 // Load a class for boot loader from the shared spaces. This also
1189 // forces the super class and all interfaces to be loaded.
1190 InstanceKlass* SystemDictionary::load_shared_boot_class(Symbol* class_name,
1191                                                         PackageEntry* pkg_entry,
1192                                                         TRAPS) {
1193   assert(UseSharedSpaces, "Sanity check");
1194   InstanceKlass* ik = SystemDictionaryShared::find_builtin_class(class_name);
1195   if (ik != NULL && ik->is_shared_boot_class()) {
1196     return load_shared_class(ik, Handle(), Handle(), NULL, pkg_entry, THREAD);
1197   }
1198   return NULL;
1199 }
1200 
1201 // Check if a shared class can be loaded by the specific classloader.
1202 bool SystemDictionary::is_shared_class_visible(Symbol* class_name,
1203                                                InstanceKlass* ik,
1204                                                PackageEntry* pkg_entry,
1205                                                Handle class_loader, TRAPS) {
1206   assert(!ModuleEntryTable::javabase_moduleEntry()->is_patched(),
1207          "Cannot use sharing if java.base is patched");
1208 
1209   // (1) Check if we are loading into the same loader as in dump time.
1210 
1211   if (ik->is_shared_boot_class()) {
1212     if (class_loader() != NULL) {
1213       return false;
1214     }
1215   } else if (ik->is_shared_platform_class()) {
1216     if (class_loader() != java_platform_loader()) {
1217       return false;
1218     }
1219   } else if (ik->is_shared_app_class()) {
1220     if (class_loader() != java_system_loader()) {
1221       return false;
1222     }
1223   } else {
1224     // ik was loaded by a custom loader during dump time
1225     if (class_loader_data(class_loader)->is_builtin_class_loader_data()) {
1226       return false;
1227     } else {
1228       return true;
1229     }
1230   }
1231 
1232   // (2) Check if we are loading into the same module from the same location as in dump time.
1233 
1234   if (MetaspaceShared::use_optimized_module_handling()) {
1235     // Class visibility has not changed between dump time and run time, so a class
1236     // that was visible (and thus archived) during dump time is always visible during runtime.
1237     assert(SystemDictionary::is_shared_class_visible_impl(class_name, ik, pkg_entry, class_loader, THREAD),
1238            "visibility cannot change between dump time and runtime");
1239     return true;
1240   }
1241   return is_shared_class_visible_impl(class_name, ik, pkg_entry, class_loader, THREAD);
1242 }
1243 
1244 bool SystemDictionary::is_shared_class_visible_impl(Symbol* class_name,
1245                                                     InstanceKlass* ik,
1246                                                     PackageEntry* pkg_entry,
1247                                                     Handle class_loader, TRAPS) {
1248   int scp_index = ik->shared_classpath_index();
1249   assert(!ik->is_shared_unregistered_class(), "this function should be called for built-in classes only");
1250   assert(scp_index >= 0, "must be");
1251   SharedClassPathEntry* scp_entry = FileMapInfo::shared_path(scp_index);
1252   if (!Universe::is_module_initialized()) {
1253     assert(scp_entry != NULL && scp_entry->is_modules_image(),
1254            "Loading non-bootstrap classes before the module system is initialized");
1255     assert(class_loader.is_null(), "sanity");
1256     return true;
1257   }
1258 
1259   ModuleEntry* mod_entry = (pkg_entry == NULL) ? NULL : pkg_entry->module();
1260   bool should_be_in_named_module = (mod_entry != NULL && mod_entry->is_named());
1261   bool was_archived_from_named_module = scp_entry->in_named_module();
1262   bool visible;
1263 
1264   if (was_archived_from_named_module) {
1265     if (should_be_in_named_module) {
1266       // Is the module loaded from the same location as during dump time?
1267       visible = mod_entry->shared_path_index() == scp_index;
1268       if (visible) {
1269         assert(!mod_entry->is_patched(), "cannot load archived classes for patched module");
1270       }
1271     } else {
1272       // During dump time, this class was in a named module, but at run time, this class should be
1273       // in an unnamed module.
1274       visible = false;
1275     }
1276   } else {
1277     if (should_be_in_named_module) {
1278       // During dump time, this class was in an unnamed, but at run time, this class should be
1279       // in a named module.
1280       visible = false;
1281     } else {
1282       visible = true;
1283     }
1284   }
1285 
1286   return visible;
1287 }
1288 
1289 bool SystemDictionary::check_shared_class_super_type(InstanceKlass* child, InstanceKlass* super_type,
1290                                                      Handle class_loader,  Handle protection_domain,
1291                                                      bool is_superclass, TRAPS) {
1292   assert(super_type->is_shared(), "must be");
1293 
1294   Klass *found = resolve_super_or_fail(child->name(), super_type->name(),
1295                                        class_loader, protection_domain, is_superclass, CHECK_0);
1296   if (found == super_type) {
1297     return true;
1298   } else {
1299     // The dynamically resolved super type is not the same as the one we used during dump time,
1300     // so we cannot use the child class.
1301     return false;
1302   }
1303 }
1304 
1305 bool SystemDictionary::check_shared_class_super_types(InstanceKlass* ik, Handle class_loader,
1306                                                       Handle protection_domain, TRAPS) {
1307   // Check the superclass and interfaces. They must be the same
1308   // as in dump time, because the layout of <ik> depends on
1309   // the specific layout of ik->super() and ik->local_interfaces().
1310   //
1311   // If unexpected superclass or interfaces are found, we cannot
1312   // load <ik> from the shared archive.
1313 
1314   if (ik->super() != NULL &&
1315       !check_shared_class_super_type(ik, InstanceKlass::cast(ik->super()),
1316                                      class_loader, protection_domain, true, THREAD)) {
1317     return false;
1318   }
1319 
1320   Array<InstanceKlass*>* interfaces = ik->local_interfaces();
1321   int num_interfaces = interfaces->length();
1322   for (int index = 0; index < num_interfaces; index++) {
1323     if (!check_shared_class_super_type(ik, interfaces->at(index), class_loader, protection_domain, false, THREAD)) {
1324       return false;
1325     }
1326   }
1327 
1328   return true;
1329 }
1330 
1331 InstanceKlass* SystemDictionary::load_shared_lambda_proxy_class(InstanceKlass* ik,
1332                                                                 Handle class_loader,
1333                                                                 Handle protection_domain,
1334                                                                 PackageEntry* pkg_entry,
1335                                                                 TRAPS) {
1336   InstanceKlass* shared_nest_host = SystemDictionaryShared::get_shared_nest_host(ik);
1337   assert(shared_nest_host->is_shared(), "nest host must be in CDS archive");
1338   Symbol* cn = shared_nest_host->name();
1339   Klass *s = resolve_or_fail(cn, class_loader, protection_domain, true, CHECK_NULL);
1340   if (s != shared_nest_host) {
1341     // The dynamically resolved nest_host is not the same as the one we used during dump time,
1342     // so we cannot use ik.
1343     return NULL;
1344   } else {
1345     assert(s->is_shared(), "must be");
1346   }
1347 
1348   // The lambda proxy class and its nest host have the same class loader and class loader data,
1349   // as verified in SystemDictionaryShared::add_lambda_proxy_class()
1350   assert(shared_nest_host->class_loader() == class_loader(), "mismatched class loader");
1351   assert(shared_nest_host->class_loader_data() == ClassLoaderData::class_loader_data(class_loader()), "mismatched class loader data");
1352   ik->set_nest_host(shared_nest_host, THREAD);
1353 
1354   InstanceKlass* loaded_ik = load_shared_class(ik, class_loader, protection_domain, NULL, pkg_entry, CHECK_NULL);
1355 
1356   assert(shared_nest_host->is_same_class_package(ik),
1357          "lambda proxy class and its nest host must be in the same package");
1358 
1359   return loaded_ik;
1360 }
1361 
1362 InstanceKlass* SystemDictionary::load_shared_class(InstanceKlass* ik,
1363                                                    Handle class_loader,
1364                                                    Handle protection_domain,
1365                                                    const ClassFileStream *cfs,
1366                                                    PackageEntry* pkg_entry,
1367                                                    TRAPS) {
1368   assert(ik != NULL, "sanity");
1369   assert(!ik->is_unshareable_info_restored(), "shared class can be loaded only once");
1370   Symbol* class_name = ik->name();
1371 
1372   bool visible = is_shared_class_visible(
1373                           class_name, ik, pkg_entry, class_loader, CHECK_NULL);
1374   if (!visible) {
1375     return NULL;
1376   }
1377 
1378   if (!check_shared_class_super_types(ik, class_loader, protection_domain, THREAD)) {
1379     return NULL;
1380   }
1381 
1382   InstanceKlass* new_ik = NULL;
1383   // CFLH check is skipped for VM hidden or anonymous classes (see KlassFactory::create_from_stream).
1384   // It will be skipped for shared VM hidden lambda proxy classes.
1385   if (!SystemDictionaryShared::is_hidden_lambda_proxy(ik)) {
1386     new_ik = KlassFactory::check_shared_class_file_load_hook(
1387       ik, class_name, class_loader, protection_domain, cfs, CHECK_NULL);
1388   }
1389   if (new_ik != NULL) {
1390     // The class is changed by CFLH. Return the new class. The shared class is
1391     // not used.
1392     return new_ik;
1393   }
1394 
1395   // Adjust methods to recover missing data.  They need addresses for
1396   // interpreter entry points and their default native method address
1397   // must be reset.
1398 
1399   // Updating methods must be done under a lock so multiple
1400   // threads don't update these in parallel
1401   //
1402   // Shared classes are all currently loaded by either the bootstrap or
1403   // internal parallel class loaders, so this will never cause a deadlock
1404   // on a custom class loader lock.
1405 
1406   ClassLoaderData* loader_data = ClassLoaderData::class_loader_data(class_loader());
1407   {
1408     HandleMark hm(THREAD);
1409     Handle lockObject = compute_loader_lock_object(class_loader, THREAD);
1410     check_loader_lock_contention(lockObject, THREAD);
1411     ObjectLocker ol(lockObject, THREAD, true);
1412     // prohibited package check assumes all classes loaded from archive call
1413     // restore_unshareable_info which calls ik->set_package()
1414     ik->restore_unshareable_info(loader_data, protection_domain, pkg_entry, CHECK_NULL);
1415   }
1416 
1417   load_shared_class_misc(ik, loader_data, CHECK_NULL);
1418   return ik;
1419 }
1420 
1421 void SystemDictionary::load_shared_class_misc(InstanceKlass* ik, ClassLoaderData* loader_data, TRAPS) {
1422   ik->print_class_load_logging(loader_data, NULL, NULL);
1423 
1424   // For boot loader, ensure that GetSystemPackage knows that a class in this
1425   // package was loaded.
1426   if (loader_data->is_the_null_class_loader_data()) {
1427     int path_index = ik->shared_classpath_index();
1428     ik->set_classpath_index(path_index, THREAD);
1429   }
1430 
1431   // notify a class loaded from shared object
1432   ClassLoadingService::notify_class_loaded(ik, true /* shared class */);
1433 
1434   ik->set_has_passed_fingerprint_check(false);
1435   if (UseAOT && ik->supers_have_passed_fingerprint_checks()) {
1436     uint64_t aot_fp = AOTLoader::get_saved_fingerprint(ik);
1437     uint64_t cds_fp = ik->get_stored_fingerprint();
1438     if (aot_fp != 0 && aot_fp == cds_fp) {
1439       // This class matches with a class saved in an AOT library
1440       ik->set_has_passed_fingerprint_check(true);
1441     } else {
1442       if (log_is_enabled(Info, class, fingerprint)) {
1443         ResourceMark rm(THREAD);
1444         log_info(class, fingerprint)("%s :  expected = " PTR64_FORMAT " actual = " PTR64_FORMAT, ik->external_name(), aot_fp, cds_fp);
1445       }
1446     }
1447   }
1448 }
1449 
1450 void SystemDictionary::quick_resolve(InstanceKlass* klass, ClassLoaderData* loader_data, Handle domain, TRAPS) {
1451   assert(!Universe::is_fully_initialized(), "We can make short cuts only during VM initialization");
1452   assert(klass->is_shared(), "Must be shared class");
1453   if (klass->class_loader_data() != NULL) {
1454     return;
1455   }
1456 
1457   // add super and interfaces first
1458   Klass* super = klass->super();
1459   if (super != NULL && super->class_loader_data() == NULL) {
1460     assert(super->is_instance_klass(), "Super should be instance klass");
1461     quick_resolve(InstanceKlass::cast(super), loader_data, domain, CHECK);
1462   }
1463 
1464   Array<InstanceKlass*>* ifs = klass->local_interfaces();
1465   for (int i = 0; i < ifs->length(); i++) {
1466     InstanceKlass* ik = ifs->at(i);
1467     if (ik->class_loader_data()  == NULL) {
1468       quick_resolve(ik, loader_data, domain, CHECK);
1469     }
1470   }
1471 
1472   klass->restore_unshareable_info(loader_data, domain, NULL, THREAD);
1473   load_shared_class_misc(klass, loader_data, CHECK);
1474   Dictionary* dictionary = loader_data->dictionary();
1475   unsigned int hash = dictionary->compute_hash(klass->name());
1476   dictionary->add_klass(hash, klass->name(), klass);
1477   add_to_hierarchy(klass, CHECK);
1478   assert(klass->is_loaded(), "Must be in at least loaded state");
1479 }
1480 #endif // INCLUDE_CDS
1481 
1482 InstanceKlass* SystemDictionary::load_instance_class(Symbol* class_name, Handle class_loader, TRAPS) {
1483 
1484   if (class_loader.is_null()) {
1485     ResourceMark rm(THREAD);
1486     PackageEntry* pkg_entry = NULL;
1487     bool search_only_bootloader_append = false;
1488     ClassLoaderData *loader_data = class_loader_data(class_loader);
1489 
1490     // Find the package in the boot loader's package entry table.
1491     TempNewSymbol pkg_name = ClassLoader::package_from_class_name(class_name);
1492     if (pkg_name != NULL) {
1493       pkg_entry = loader_data->packages()->lookup_only(pkg_name);
1494     }
1495 
1496     // Prior to attempting to load the class, enforce the boot loader's
1497     // visibility boundaries.
1498     if (!Universe::is_module_initialized()) {
1499       // During bootstrapping, prior to module initialization, any
1500       // class attempting to be loaded must be checked against the
1501       // java.base packages in the boot loader's PackageEntryTable.
1502       // No class outside of java.base is allowed to be loaded during
1503       // this bootstrapping window.
1504       if (pkg_entry == NULL || pkg_entry->in_unnamed_module()) {
1505         // Class is either in the unnamed package or in
1506         // a named package within the unnamed module.  Either
1507         // case is outside of java.base, do not attempt to
1508         // load the class post java.base definition.  If
1509         // java.base has not been defined, let the class load
1510         // and its package will be checked later by
1511         // ModuleEntryTable::verify_javabase_packages.
1512         if (ModuleEntryTable::javabase_defined()) {
1513           return NULL;
1514         }
1515       } else {
1516         // Check that the class' package is defined within java.base.
1517         ModuleEntry* mod_entry = pkg_entry->module();
1518         Symbol* mod_entry_name = mod_entry->name();
1519         if (mod_entry_name->fast_compare(vmSymbols::java_base()) != 0) {
1520           return NULL;
1521         }
1522       }
1523     } else {
1524       // After the module system has been initialized, check if the class'
1525       // package is in a module defined to the boot loader.
1526       if (pkg_name == NULL || pkg_entry == NULL || pkg_entry->in_unnamed_module()) {
1527         // Class is either in the unnamed package, in a named package
1528         // within a module not defined to the boot loader or in a
1529         // a named package within the unnamed module.  In all cases,
1530         // limit visibility to search for the class only in the boot
1531         // loader's append path.
1532         if (!ClassLoader::has_bootclasspath_append()) {
1533            // If there is no bootclasspath append entry, no need to continue
1534            // searching.
1535            return NULL;
1536         }
1537         search_only_bootloader_append = true;
1538       }
1539     }
1540 
1541     // Prior to bootstrapping's module initialization, never load a class outside
1542     // of the boot loader's module path
1543     assert(Universe::is_module_initialized() ||
1544            !search_only_bootloader_append,
1545            "Attempt to load a class outside of boot loader's module path");
1546 
1547     // Search for classes in the CDS archive.
1548     InstanceKlass* k = NULL;
1549 
1550 #if INCLUDE_CDS
1551     if (UseSharedSpaces)
1552     {
1553       PerfTraceTime vmtimer(ClassLoader::perf_shared_classload_time());
1554       k = load_shared_boot_class(class_name, pkg_entry, THREAD);
1555     }
1556 #endif
1557 
1558     if (k == NULL) {
1559       // Use VM class loader
1560       PerfTraceTime vmtimer(ClassLoader::perf_sys_classload_time());
1561       k = ClassLoader::load_class(class_name, search_only_bootloader_append, CHECK_NULL);
1562     }
1563 
1564     // find_or_define_instance_class may return a different InstanceKlass
1565     if (k != NULL) {
1566       InstanceKlass* defined_k =
1567         find_or_define_instance_class(class_name, class_loader, k, THREAD);
1568       if (!HAS_PENDING_EXCEPTION && defined_k != k) {
1569         // If a parallel capable class loader already defined this class, register 'k' for cleanup.
1570         assert(defined_k != NULL, "Should have a klass if there's no exception");
1571         loader_data->add_to_deallocate_list(k);
1572         k = defined_k;
1573       } else if (HAS_PENDING_EXCEPTION) {
1574         loader_data->add_to_deallocate_list(k);
1575         return NULL;
1576       }
1577     }
1578     return k;
1579   } else {
1580     // Use user specified class loader to load class. Call loadClass operation on class_loader.
1581     ResourceMark rm(THREAD);
1582 
1583     JavaThread* jt = THREAD->as_Java_thread();
1584 
1585     PerfClassTraceTime vmtimer(ClassLoader::perf_app_classload_time(),
1586                                ClassLoader::perf_app_classload_selftime(),
1587                                ClassLoader::perf_app_classload_count(),
1588                                jt->get_thread_stat()->perf_recursion_counts_addr(),
1589                                jt->get_thread_stat()->perf_timers_addr(),
1590                                PerfClassTraceTime::CLASS_LOAD);
1591 
1592     Handle s = java_lang_String::create_from_symbol(class_name, CHECK_NULL);
1593     // Translate to external class name format, i.e., convert '/' chars to '.'
1594     Handle string = java_lang_String::externalize_classname(s, CHECK_NULL);
1595 
1596     JavaValue result(T_OBJECT);
1597 
1598     InstanceKlass* spec_klass = SystemDictionary::ClassLoader_klass();
1599 
1600     // Call public unsynchronized loadClass(String) directly for all class loaders.
1601     // For parallelCapable class loaders, JDK >=7, loadClass(String, boolean) will
1602     // acquire a class-name based lock rather than the class loader object lock.
1603     // JDK < 7 already acquire the class loader lock in loadClass(String, boolean).
1604     JavaCalls::call_virtual(&result,
1605                             class_loader,
1606                             spec_klass,
1607                             vmSymbols::loadClass_name(),
1608                             vmSymbols::string_class_signature(),
1609                             string,
1610                             CHECK_NULL);
1611 
1612     assert(result.get_type() == T_OBJECT, "just checking");
1613     oop obj = (oop) result.get_jobject();
1614 
1615     // Primitive classes return null since forName() can not be
1616     // used to obtain any of the Class objects representing primitives or void
1617     if ((obj != NULL) && !(java_lang_Class::is_primitive(obj))) {
1618       InstanceKlass* k = InstanceKlass::cast(java_lang_Class::as_Klass(obj));
1619       // For user defined Java class loaders, check that the name returned is
1620       // the same as that requested.  This check is done for the bootstrap
1621       // loader when parsing the class file.
1622       if (class_name == k->name()) {
1623         return k;
1624       }
1625     }
1626     // Class is not found or has the wrong name, return NULL
1627     return NULL;
1628   }
1629 }
1630 
1631 static void post_class_define_event(InstanceKlass* k, const ClassLoaderData* def_cld) {
1632   EventClassDefine event;
1633   if (event.should_commit()) {
1634     event.set_definedClass(k);
1635     event.set_definingClassLoader(def_cld);
1636     event.commit();
1637   }
1638 }
1639 
1640 void SystemDictionary::define_instance_class(InstanceKlass* k, TRAPS) {
1641 
1642   HandleMark hm(THREAD);
1643   ClassLoaderData* loader_data = k->class_loader_data();
1644   Handle class_loader_h(THREAD, loader_data->class_loader());
1645 
1646   // for bootstrap and other parallel classloaders don't acquire lock,
1647   // use placeholder token
1648   // If a parallelCapable class loader calls define_instance_class instead of
1649   // find_or_define_instance_class to get here, we have a timing
1650   // hole with systemDictionary updates and check_constraints
1651   if (!class_loader_h.is_null() && !is_parallelCapable(class_loader_h)) {
1652     assert(ObjectSynchronizer::current_thread_holds_lock(THREAD->as_Java_thread(),
1653            compute_loader_lock_object(class_loader_h, THREAD)),
1654            "define called without lock");
1655   }
1656 
1657   // Check class-loading constraints. Throw exception if violation is detected.
1658   // Grabs and releases SystemDictionary_lock
1659   // The check_constraints/find_class call and update_dictionary sequence
1660   // must be "atomic" for a specific class/classloader pair so we never
1661   // define two different instanceKlasses for that class/classloader pair.
1662   // Existing classloaders will call define_instance_class with the
1663   // classloader lock held
1664   // Parallel classloaders will call find_or_define_instance_class
1665   // which will require a token to perform the define class
1666   Symbol*  name_h = k->name();
1667   Dictionary* dictionary = loader_data->dictionary();
1668   unsigned int d_hash = dictionary->compute_hash(name_h);
1669   check_constraints(d_hash, k, class_loader_h, true, CHECK);
1670 
1671   // Register class just loaded with class loader (placed in ArrayList)
1672   // Note we do this before updating the dictionary, as this can
1673   // fail with an OutOfMemoryError (if it does, we will *not* put this
1674   // class in the dictionary and will not update the class hierarchy).
1675   // JVMTI FollowReferences needs to find the classes this way.
1676   if (k->class_loader() != NULL) {
1677     methodHandle m(THREAD, Universe::loader_addClass_method());
1678     JavaValue result(T_VOID);
1679     JavaCallArguments args(class_loader_h);
1680     args.push_oop(Handle(THREAD, k->java_mirror()));
1681     JavaCalls::call(&result, m, &args, CHECK);
1682   }
1683 
1684   // Add the new class. We need recompile lock during update of CHA.
1685   {
1686     unsigned int p_hash = placeholders()->compute_hash(name_h);
1687     int p_index = placeholders()->hash_to_index(p_hash);
1688 
1689     MutexLocker mu_r(THREAD, Compile_lock);
1690 
1691     // Add to class hierarchy, initialize vtables, and do possible
1692     // deoptimizations.
1693     add_to_hierarchy(k, CHECK); // No exception, but can block
1694 
1695     // Add to systemDictionary - so other classes can see it.
1696     // Grabs and releases SystemDictionary_lock
1697     update_dictionary(d_hash, p_index, p_hash,
1698                       k, class_loader_h, THREAD);
1699   }
1700   k->eager_initialize(THREAD);
1701 
1702   // notify jvmti
1703   if (JvmtiExport::should_post_class_load()) {
1704     JvmtiExport::post_class_load(THREAD->as_Java_thread(), k);
1705   }
1706   post_class_define_event(k, loader_data);
1707 }
1708 
1709 // Support parallel classloading
1710 // All parallel class loaders, including bootstrap classloader
1711 // lock a placeholder entry for this class/class_loader pair
1712 // to allow parallel defines of different classes for this class loader
1713 // With AllowParallelDefine flag==true, in case they do not synchronize around
1714 // FindLoadedClass/DefineClass, calls, we check for parallel
1715 // loading for them, wait if a defineClass is in progress
1716 // and return the initial requestor's results
1717 // This flag does not apply to the bootstrap classloader.
1718 // With AllowParallelDefine flag==false, call through to define_instance_class
1719 // which will throw LinkageError: duplicate class definition.
1720 // False is the requested default.
1721 // For better performance, the class loaders should synchronize
1722 // findClass(), i.e. FindLoadedClass/DefineClassIfAbsent or they
1723 // potentially waste time reading and parsing the bytestream.
1724 // Note: VM callers should ensure consistency of k/class_name,class_loader
1725 // Be careful when modifying this code: once you have run
1726 // placeholders()->find_and_add(PlaceholderTable::DEFINE_CLASS),
1727 // you need to find_and_remove it before returning.
1728 // So be careful to not exit with a CHECK_ macro betweeen these calls.
1729 InstanceKlass* SystemDictionary::find_or_define_instance_class(Symbol* class_name, Handle class_loader,
1730                                                                InstanceKlass* k, TRAPS) {
1731 
1732   Symbol*  name_h = k->name(); // passed in class_name may be null
1733   ClassLoaderData* loader_data = class_loader_data(class_loader);
1734   Dictionary* dictionary = loader_data->dictionary();
1735 
1736   unsigned int d_hash = dictionary->compute_hash(name_h);
1737 
1738   // Hold SD lock around find_class and placeholder creation for DEFINE_CLASS
1739   unsigned int p_hash = placeholders()->compute_hash(name_h);
1740   int p_index = placeholders()->hash_to_index(p_hash);
1741   PlaceholderEntry* probe;
1742 
1743   {
1744     MutexLocker mu(THREAD, SystemDictionary_lock);
1745     // First check if class already defined
1746     if (is_parallelDefine(class_loader)) {
1747       InstanceKlass* check = find_class(d_hash, name_h, dictionary);
1748       if (check != NULL) {
1749         return check;
1750       }
1751     }
1752 
1753     // Acquire define token for this class/classloader
1754     probe = placeholders()->find_and_add(p_index, p_hash, name_h, loader_data, PlaceholderTable::DEFINE_CLASS, NULL, THREAD);
1755     // Wait if another thread defining in parallel
1756     // All threads wait - even those that will throw duplicate class: otherwise
1757     // caller is surprised by LinkageError: duplicate, but findLoadedClass fails
1758     // if other thread has not finished updating dictionary
1759     while (probe->definer() != NULL) {
1760       SystemDictionary_lock->wait();
1761     }
1762     // Only special cases allow parallel defines and can use other thread's results
1763     // Other cases fall through, and may run into duplicate defines
1764     // caught by finding an entry in the SystemDictionary
1765     if (is_parallelDefine(class_loader) && (probe->instance_klass() != NULL)) {
1766         placeholders()->find_and_remove(p_index, p_hash, name_h, loader_data, PlaceholderTable::DEFINE_CLASS, THREAD);
1767         SystemDictionary_lock->notify_all();
1768 #ifdef ASSERT
1769         InstanceKlass* check = find_class(d_hash, name_h, dictionary);
1770         assert(check != NULL, "definer missed recording success");
1771 #endif
1772         return probe->instance_klass();
1773     } else {
1774       // This thread will define the class (even if earlier thread tried and had an error)
1775       probe->set_definer(THREAD);
1776     }
1777   }
1778 
1779   define_instance_class(k, THREAD);
1780 
1781   Handle linkage_exception = Handle(); // null handle
1782 
1783   // definer must notify any waiting threads
1784   {
1785     MutexLocker mu(THREAD, SystemDictionary_lock);
1786     PlaceholderEntry* probe = placeholders()->get_entry(p_index, p_hash, name_h, loader_data);
1787     assert(probe != NULL, "DEFINE_CLASS placeholder lost?");
1788     if (probe != NULL) {
1789       if (HAS_PENDING_EXCEPTION) {
1790         linkage_exception = Handle(THREAD,PENDING_EXCEPTION);
1791         CLEAR_PENDING_EXCEPTION;
1792       } else {
1793         probe->set_instance_klass(k);
1794       }
1795       probe->set_definer(NULL);
1796       placeholders()->find_and_remove(p_index, p_hash, name_h, loader_data, PlaceholderTable::DEFINE_CLASS, THREAD);
1797       SystemDictionary_lock->notify_all();
1798     }
1799   }
1800 
1801   // Can't throw exception while holding lock due to rank ordering
1802   if (linkage_exception() != NULL) {
1803     THROW_OOP_(linkage_exception(), NULL); // throws exception and returns
1804   }
1805 
1806   return k;
1807 }
1808 
1809 Handle SystemDictionary::compute_loader_lock_object(Handle class_loader, TRAPS) {
1810   // If class_loader is NULL we synchronize on _system_loader_lock_obj
1811   if (class_loader.is_null()) {
1812     return Handle(THREAD, _system_loader_lock_obj.resolve());
1813   } else {
1814     return class_loader;
1815   }
1816 }
1817 
1818 // This method is added to check how often we have to wait to grab loader
1819 // lock. The results are being recorded in the performance counters defined in
1820 // ClassLoader::_sync_systemLoaderLockContentionRate and
1821 // ClassLoader::_sync_nonSystemLoaderLockConteionRate.
1822 void SystemDictionary::check_loader_lock_contention(Handle loader_lock, TRAPS) {
1823   if (!UsePerfData) {
1824     return;
1825   }
1826 
1827   assert(!loader_lock.is_null(), "NULL lock object");
1828 
1829   if (ObjectSynchronizer::query_lock_ownership(THREAD->as_Java_thread(), loader_lock)
1830       == ObjectSynchronizer::owner_other) {
1831     // contention will likely happen, so increment the corresponding
1832     // contention counter.
1833     if (loader_lock() == _system_loader_lock_obj.resolve()) {
1834       ClassLoader::sync_systemLoaderLockContentionRate()->inc();
1835     } else {
1836       ClassLoader::sync_nonSystemLoaderLockContentionRate()->inc();
1837     }
1838   }
1839 }
1840 
1841 // ----------------------------------------------------------------------------
1842 // Lookup
1843 
1844 InstanceKlass* SystemDictionary::find_class(unsigned int hash,
1845                                             Symbol* class_name,
1846                                             Dictionary* dictionary) {
1847   assert_locked_or_safepoint(SystemDictionary_lock);
1848   int index = dictionary->hash_to_index(hash);
1849   return dictionary->find_class(index, hash, class_name);
1850 }
1851 
1852 
1853 // Basic find on classes in the midst of being loaded
1854 Symbol* SystemDictionary::find_placeholder(Symbol* class_name,
1855                                            ClassLoaderData* loader_data) {
1856   assert_locked_or_safepoint(SystemDictionary_lock);
1857   unsigned int p_hash = placeholders()->compute_hash(class_name);
1858   int p_index = placeholders()->hash_to_index(p_hash);
1859   return placeholders()->find_entry(p_index, p_hash, class_name, loader_data);
1860 }
1861 
1862 
1863 // Used for assertions and verification only
1864 // Precalculating the hash and index is an optimization because there are many lookups
1865 // before adding the class.
1866 InstanceKlass* SystemDictionary::find_class(Symbol* class_name, ClassLoaderData* loader_data) {
1867   assert_locked_or_safepoint(SystemDictionary_lock);
1868   #ifndef ASSERT
1869   guarantee(VerifyBeforeGC      ||
1870             VerifyDuringGC      ||
1871             VerifyBeforeExit    ||
1872             VerifyDuringStartup ||
1873             VerifyAfterGC, "too expensive");
1874   #endif
1875 
1876   Dictionary* dictionary = loader_data->dictionary();
1877   unsigned int d_hash = dictionary->compute_hash(class_name);
1878   return find_class(d_hash, class_name, dictionary);
1879 }
1880 
1881 
1882 // ----------------------------------------------------------------------------
1883 // Update hierachy. This is done before the new klass has been added to the SystemDictionary. The Recompile_lock
1884 // is held, to ensure that the compiler is not using the class hierachy, and that deoptimization will kick in
1885 // before a new class is used.
1886 
1887 void SystemDictionary::add_to_hierarchy(InstanceKlass* k, TRAPS) {
1888   assert(k != NULL, "just checking");
1889   if (Universe::is_fully_initialized()) {
1890     assert_locked_or_safepoint(Compile_lock);
1891   }
1892 
1893   k->set_init_state(InstanceKlass::loaded);
1894   // make sure init_state store is already done.
1895   // The compiler reads the hierarchy outside of the Compile_lock.
1896   // Access ordering is used to add to hierarchy.
1897 
1898   // Link into hierachy.
1899   k->append_to_sibling_list();                    // add to superklass/sibling list
1900   k->process_interfaces(THREAD);                  // handle all "implements" declarations
1901 
1902   // Now flush all code that depended on old class hierarchy.
1903   // Note: must be done *after* linking k into the hierarchy (was bug 12/9/97)
1904   if (Universe::is_fully_initialized()) {
1905     CodeCache::flush_dependents_on(k);
1906   }
1907 }
1908 
1909 // ----------------------------------------------------------------------------
1910 // GC support
1911 
1912 // Assumes classes in the SystemDictionary are only unloaded at a safepoint
1913 // Note: anonymous classes are not in the SD.
1914 bool SystemDictionary::do_unloading(GCTimer* gc_timer) {
1915 
1916   bool unloading_occurred;
1917   bool is_concurrent = !SafepointSynchronize::is_at_safepoint();
1918   {
1919     GCTraceTime(Debug, gc, phases) t("ClassLoaderData", gc_timer);
1920     assert_locked_or_safepoint(ClassLoaderDataGraph_lock);  // caller locks.
1921     // First, mark for unload all ClassLoaderData referencing a dead class loader.
1922     unloading_occurred = ClassLoaderDataGraph::do_unloading();
1923     if (unloading_occurred) {
1924       MutexLocker ml2(is_concurrent ? Module_lock : NULL);
1925       JFR_ONLY(Jfr::on_unloading_classes();)
1926 
1927       MutexLocker ml1(is_concurrent ? SystemDictionary_lock : NULL);
1928       ClassLoaderDataGraph::clean_module_and_package_info();
1929       constraints()->purge_loader_constraints();
1930       resolution_errors()->purge_resolution_errors();
1931     }
1932   }
1933 
1934   GCTraceTime(Debug, gc, phases) t("Trigger cleanups", gc_timer);
1935 
1936   if (unloading_occurred) {
1937     SymbolTable::trigger_cleanup();
1938 
1939     // Oops referenced by the protection domain cache table may get unreachable independently
1940     // of the class loader (eg. cached protection domain oops). So we need to
1941     // explicitly unlink them here.
1942     // All protection domain oops are linked to the caller class, so if nothing
1943     // unloads, this is not needed.
1944     _pd_cache_table->trigger_cleanup();
1945   }
1946 
1947   return unloading_occurred;
1948 }
1949 
1950 // CDS: scan and relocate all classes referenced by _well_known_klasses[].
1951 void SystemDictionary::well_known_klasses_do(MetaspaceClosure* it) {
1952   for (int id = FIRST_WKID; id < WKID_LIMIT; id++) {
1953     it->push(well_known_klass_addr((WKID)id));
1954   }
1955 }
1956 
1957 void SystemDictionary::methods_do(void f(Method*)) {
1958   // Walk methods in loaded classes
1959   MutexLocker ml(ClassLoaderDataGraph_lock);
1960   ClassLoaderDataGraph::methods_do(f);
1961   // Walk method handle intrinsics
1962   invoke_method_table()->methods_do(f);
1963 }
1964 
1965 // ----------------------------------------------------------------------------
1966 // Initialization
1967 
1968 void SystemDictionary::initialize(TRAPS) {
1969   // Allocate arrays
1970   _placeholders        = new PlaceholderTable(_placeholder_table_size);
1971   _loader_constraints  = new LoaderConstraintTable(_loader_constraint_size);
1972   _resolution_errors   = new ResolutionErrorTable(_resolution_error_size);
1973   _invoke_method_table = new SymbolPropertyTable(_invoke_method_size);
1974   _pd_cache_table = new ProtectionDomainCacheTable(defaultProtectionDomainCacheSize);
1975 
1976   // Allocate private object used as system class loader lock
1977   oop lock_obj = oopFactory::new_intArray(0, CHECK);
1978   _system_loader_lock_obj = OopHandle(Universe::vm_global(), lock_obj);
1979 
1980   // Resolve basic classes
1981   resolve_well_known_classes(CHECK);
1982   // Resolve classes used by archived heap objects
1983   if (UseSharedSpaces) {
1984     HeapShared::resolve_classes(CHECK);
1985   }
1986 }
1987 
1988 // Compact table of directions on the initialization of klasses:
1989 static const short wk_init_info[] = {
1990   #define WK_KLASS_INIT_INFO(name, symbol) \
1991     ((short)vmSymbols::VM_SYMBOL_ENUM_NAME(symbol)),
1992 
1993   WK_KLASSES_DO(WK_KLASS_INIT_INFO)
1994   #undef WK_KLASS_INIT_INFO
1995   0
1996 };
1997 
1998 #ifdef ASSERT
1999 bool SystemDictionary::is_well_known_klass(Symbol* class_name) {
2000   int sid;
2001   for (int i = 0; (sid = wk_init_info[i]) != 0; i++) {
2002     Symbol* symbol = vmSymbols::symbol_at((vmSymbols::SID)sid);
2003     if (class_name == symbol) {
2004       return true;
2005     }
2006   }
2007   return false;
2008 }
2009 
2010 bool SystemDictionary::is_well_known_klass(Klass* k) {
2011   return is_well_known_klass(k->name());
2012 }
2013 #endif
2014 
2015 bool SystemDictionary::resolve_wk_klass(WKID id, TRAPS) {
2016   assert(id >= (int)FIRST_WKID && id < (int)WKID_LIMIT, "oob");
2017   int sid = wk_init_info[id - FIRST_WKID];
2018   Symbol* symbol = vmSymbols::symbol_at((vmSymbols::SID)sid);
2019   InstanceKlass** klassp = &_well_known_klasses[id];
2020 
2021 #if INCLUDE_CDS
2022   if (UseSharedSpaces && !JvmtiExport::should_post_class_prepare()) {
2023     InstanceKlass* k = *klassp;
2024     assert(k->is_shared_boot_class(), "must be");
2025 
2026     ClassLoaderData* loader_data = ClassLoaderData::the_null_class_loader_data();
2027     quick_resolve(k, loader_data, Handle(), CHECK_false);
2028     return true;
2029   }
2030 #endif // INCLUDE_CDS
2031 
2032   if (!is_wk_klass_loaded(*klassp)) {
2033     Klass* k = resolve_or_fail(symbol, true, CHECK_false);
2034     (*klassp) = InstanceKlass::cast(k);
2035   }
2036   return ((*klassp) != NULL);
2037 }
2038 
2039 void SystemDictionary::resolve_wk_klasses_until(WKID limit_id, WKID &start_id, TRAPS) {
2040   assert((int)start_id <= (int)limit_id, "IDs are out of order!");
2041   for (int id = (int)start_id; id < (int)limit_id; id++) {
2042     assert(id >= (int)FIRST_WKID && id < (int)WKID_LIMIT, "oob");
2043     resolve_wk_klass((WKID)id, CHECK);
2044   }
2045 
2046   // move the starting value forward to the limit:
2047   start_id = limit_id;
2048 }
2049 
2050 void SystemDictionary::resolve_well_known_classes(TRAPS) {
2051   assert(!Object_klass_loaded(), "well-known classes should only be initialized once");
2052 
2053   // Create the ModuleEntry for java.base.  This call needs to be done here,
2054   // after vmSymbols::initialize() is called but before any classes are pre-loaded.
2055   ClassLoader::classLoader_init2(CHECK);
2056 
2057   // Preload commonly used klasses
2058   WKID scan = FIRST_WKID;
2059   // first do Object, then String, Class
2060 #if INCLUDE_CDS
2061   if (UseSharedSpaces) {
2062     resolve_wk_klasses_through(WK_KLASS_ENUM_NAME(Object_klass), scan, CHECK);
2063 
2064     // It's unsafe to access the archived heap regions before they
2065     // are fixed up, so we must do the fixup as early as possible
2066     // before the archived java objects are accessed by functions
2067     // such as java_lang_Class::restore_archived_mirror and
2068     // ConstantPool::restore_unshareable_info (restores the archived
2069     // resolved_references array object).
2070     //
2071     // HeapShared::fixup_mapped_heap_regions() fills the empty
2072     // spaces in the archived heap regions and may use
2073     // SystemDictionary::Object_klass(), so we can do this only after
2074     // Object_klass is resolved. See the above resolve_wk_klasses_through()
2075     // call. No mirror objects are accessed/restored in the above call.
2076     // Mirrors are restored after java.lang.Class is loaded.
2077     HeapShared::fixup_mapped_heap_regions();
2078 
2079     // Initialize the constant pool for the Object_class
2080     assert(Object_klass()->is_shared(), "must be");
2081     Object_klass()->constants()->restore_unshareable_info(CHECK);
2082     resolve_wk_klasses_through(WK_KLASS_ENUM_NAME(Class_klass), scan, CHECK);
2083   } else
2084 #endif
2085   {
2086     resolve_wk_klasses_through(WK_KLASS_ENUM_NAME(Class_klass), scan, CHECK);
2087   }
2088 
2089   assert(WK_KLASS(Object_klass) != NULL, "well-known classes should now be initialized");
2090 
2091   java_lang_Object::register_natives(CHECK);
2092 
2093   // Calculate offsets for String and Class classes since they are loaded and
2094   // can be used after this point.
2095   java_lang_String::compute_offsets();
2096   java_lang_Class::compute_offsets();
2097 
2098   // Fixup mirrors for classes loaded before java.lang.Class.
2099   Universe::initialize_basic_type_mirrors(CHECK);
2100   Universe::fixup_mirrors(CHECK);
2101 
2102   // do a bunch more:
2103   resolve_wk_klasses_through(WK_KLASS_ENUM_NAME(Reference_klass), scan, CHECK);
2104 
2105   // The offsets for jlr.Reference must be computed before
2106   // InstanceRefKlass::update_nonstatic_oop_maps is called. That function uses
2107   // the offsets to remove the referent and discovered fields from the oop maps,
2108   // as they are treated in a special way by the GC. Removing these oops from the
2109   // oop maps must be done before the usual subclasses of jlr.Reference are loaded.
2110   java_lang_ref_Reference::compute_offsets();
2111 
2112   // Preload ref klasses and set reference types
2113   WK_KLASS(Reference_klass)->set_reference_type(REF_OTHER);
2114   InstanceRefKlass::update_nonstatic_oop_maps(WK_KLASS(Reference_klass));
2115 
2116   resolve_wk_klasses_through(WK_KLASS_ENUM_NAME(PhantomReference_klass), scan, CHECK);
2117   WK_KLASS(SoftReference_klass)->set_reference_type(REF_SOFT);
2118   WK_KLASS(WeakReference_klass)->set_reference_type(REF_WEAK);
2119   WK_KLASS(FinalReference_klass)->set_reference_type(REF_FINAL);
2120   WK_KLASS(PhantomReference_klass)->set_reference_type(REF_PHANTOM);
2121 
2122   // JSR 292 classes
2123   WKID jsr292_group_start = WK_KLASS_ENUM_NAME(MethodHandle_klass);
2124   WKID jsr292_group_end   = WK_KLASS_ENUM_NAME(VolatileCallSite_klass);
2125   resolve_wk_klasses_until(jsr292_group_start, scan, CHECK);
2126   resolve_wk_klasses_through(jsr292_group_end, scan, CHECK);
2127   WKID last = WKID_LIMIT;
2128   resolve_wk_klasses_until(last, scan, CHECK);
2129 
2130   _box_klasses[T_BOOLEAN] = WK_KLASS(Boolean_klass);
2131   _box_klasses[T_CHAR]    = WK_KLASS(Character_klass);
2132   _box_klasses[T_FLOAT]   = WK_KLASS(Float_klass);
2133   _box_klasses[T_DOUBLE]  = WK_KLASS(Double_klass);
2134   _box_klasses[T_BYTE]    = WK_KLASS(Byte_klass);
2135   _box_klasses[T_SHORT]   = WK_KLASS(Short_klass);
2136   _box_klasses[T_INT]     = WK_KLASS(Integer_klass);
2137   _box_klasses[T_LONG]    = WK_KLASS(Long_klass);
2138   //_box_klasses[T_OBJECT]  = WK_KLASS(object_klass);
2139   //_box_klasses[T_ARRAY]   = WK_KLASS(object_klass);
2140 
2141   if (DiagnoseSyncOnPrimitiveWrappers != 0) {
2142     for (int i = T_BOOLEAN; i < T_LONG + 1; i++) {
2143       assert(_box_klasses[i] != NULL, "NULL box class");
2144       _box_klasses[i]->set_is_box();
2145       _box_klasses[i]->set_prototype_header(markWord::prototype());
2146     }
2147   }
2148 
2149 #ifdef ASSERT
2150   if (UseSharedSpaces) {
2151     JVMTI_ONLY(assert(JvmtiExport::is_early_phase(),
2152                       "All well known classes must be resolved in JVMTI early phase"));
2153     for (int i = FIRST_WKID; i < last; i++) {
2154       InstanceKlass* k = _well_known_klasses[i];
2155       assert(k->is_shared(), "must not be replaced by JVMTI class file load hook");
2156     }
2157   }
2158 #endif
2159 }
2160 
2161 // Tells if a given klass is a box (wrapper class, such as java.lang.Integer).
2162 // If so, returns the basic type it holds.  If not, returns T_OBJECT.
2163 BasicType SystemDictionary::box_klass_type(Klass* k) {
2164   assert(k != NULL, "");
2165   for (int i = T_BOOLEAN; i < T_VOID+1; i++) {
2166     if (_box_klasses[i] == k)
2167       return (BasicType)i;
2168   }
2169   return T_OBJECT;
2170 }
2171 
2172 // Constraints on class loaders. The details of the algorithm can be
2173 // found in the OOPSLA'98 paper "Dynamic Class Loading in the Java
2174 // Virtual Machine" by Sheng Liang and Gilad Bracha.  The basic idea is
2175 // that the dictionary needs to maintain a set of contraints that
2176 // must be satisfied by all classes in the dictionary.
2177 // if defining is true, then LinkageError if already in dictionary
2178 // if initiating loader, then ok if InstanceKlass matches existing entry
2179 
2180 void SystemDictionary::check_constraints(unsigned int d_hash,
2181                                          InstanceKlass* k,
2182                                          Handle class_loader,
2183                                          bool defining,
2184                                          TRAPS) {
2185   ResourceMark rm(THREAD);
2186   stringStream ss;
2187   bool throwException = false;
2188 
2189   {
2190     Symbol *name = k->name();
2191     ClassLoaderData *loader_data = class_loader_data(class_loader);
2192 
2193     MutexLocker mu(THREAD, SystemDictionary_lock);
2194 
2195     InstanceKlass* check = find_class(d_hash, name, loader_data->dictionary());
2196     if (check != NULL) {
2197       // If different InstanceKlass - duplicate class definition,
2198       // else - ok, class loaded by a different thread in parallel.
2199       // We should only have found it if it was done loading and ok to use.
2200       // The dictionary only holds instance classes, placeholders
2201       // also hold array classes.
2202 
2203       assert(check->is_instance_klass(), "noninstance in systemdictionary");
2204       if ((defining == true) || (k != check)) {
2205         throwException = true;
2206         ss.print("loader %s", loader_data->loader_name_and_id());
2207         ss.print(" attempted duplicate %s definition for %s. (%s)",
2208                  k->external_kind(), k->external_name(), k->class_in_module_of_loader(false, true));
2209       } else {
2210         return;
2211       }
2212     }
2213 
2214 #ifdef ASSERT
2215     Symbol* ph_check = find_placeholder(name, loader_data);
2216     assert(ph_check == NULL || ph_check == name, "invalid symbol");
2217 #endif
2218 
2219     if (throwException == false) {
2220       if (constraints()->check_or_update(k, class_loader, name) == false) {
2221         throwException = true;
2222         ss.print("loader constraint violation: loader %s", loader_data->loader_name_and_id());
2223         ss.print(" wants to load %s %s.",
2224                  k->external_kind(), k->external_name());
2225         Klass *existing_klass = constraints()->find_constrained_klass(name, class_loader);
2226         if (existing_klass != NULL && existing_klass->class_loader() != class_loader()) {
2227           ss.print(" A different %s with the same name was previously loaded by %s. (%s)",
2228                    existing_klass->external_kind(),
2229                    existing_klass->class_loader_data()->loader_name_and_id(),
2230                    existing_klass->class_in_module_of_loader(false, true));
2231         } else {
2232           ss.print(" (%s)", k->class_in_module_of_loader(false, true));
2233         }
2234       }
2235     }
2236   }
2237 
2238   // Throw error now if needed (cannot throw while holding
2239   // SystemDictionary_lock because of rank ordering)
2240   if (throwException == true) {
2241     THROW_MSG(vmSymbols::java_lang_LinkageError(), ss.as_string());
2242   }
2243 }
2244 
2245 // Update class loader data dictionary - done after check_constraint and add_to_hierachy
2246 // have been called.
2247 void SystemDictionary::update_dictionary(unsigned int d_hash,
2248                                          int p_index, unsigned int p_hash,
2249                                          InstanceKlass* k,
2250                                          Handle class_loader,
2251                                          TRAPS) {
2252   // Compile_lock prevents systemDictionary updates during compilations
2253   assert_locked_or_safepoint(Compile_lock);
2254   Symbol*  name  = k->name();
2255   ClassLoaderData *loader_data = class_loader_data(class_loader);
2256 
2257   {
2258     MutexLocker mu1(THREAD, SystemDictionary_lock);
2259 
2260     // Make a new dictionary entry.
2261     Dictionary* dictionary = loader_data->dictionary();
2262     InstanceKlass* sd_check = find_class(d_hash, name, dictionary);
2263     if (sd_check == NULL) {
2264       dictionary->add_klass(d_hash, name, k);
2265     }
2266   #ifdef ASSERT
2267     sd_check = find_class(d_hash, name, dictionary);
2268     assert (sd_check != NULL, "should have entry in dictionary");
2269     // Note: there may be a placeholder entry: for circularity testing
2270     // or for parallel defines
2271   #endif
2272     SystemDictionary_lock->notify_all();
2273   }
2274 }
2275 
2276 
2277 // Try to find a class name using the loader constraints.  The
2278 // loader constraints might know about a class that isn't fully loaded
2279 // yet and these will be ignored.
2280 Klass* SystemDictionary::find_constrained_instance_or_array_klass(
2281                     Symbol* class_name, Handle class_loader, TRAPS) {
2282 
2283   // First see if it has been loaded directly.
2284   // Force the protection domain to be null.  (This removes protection checks.)
2285   Handle no_protection_domain;
2286   Klass* klass = find_instance_or_array_klass(class_name, class_loader,
2287                                               no_protection_domain, CHECK_NULL);
2288   if (klass != NULL)
2289     return klass;
2290 
2291   // Now look to see if it has been loaded elsewhere, and is subject to
2292   // a loader constraint that would require this loader to return the
2293   // klass that is already loaded.
2294   if (Signature::is_array(class_name)) {
2295     // For array classes, their Klass*s are not kept in the
2296     // constraint table. The element Klass*s are.
2297     SignatureStream ss(class_name, false);
2298     int ndims = ss.skip_array_prefix();  // skip all '['s
2299     BasicType t = ss.type();
2300     if (t != T_OBJECT) {
2301       klass = Universe::typeArrayKlassObj(t);
2302     } else {
2303       MutexLocker mu(THREAD, SystemDictionary_lock);
2304       klass = constraints()->find_constrained_klass(ss.as_symbol(), class_loader);
2305     }
2306     // If element class already loaded, allocate array klass
2307     if (klass != NULL) {
2308       klass = klass->array_klass_or_null(ndims);
2309     }
2310   } else {
2311     MutexLocker mu(THREAD, SystemDictionary_lock);
2312     // Non-array classes are easy: simply check the constraint table.
2313     klass = constraints()->find_constrained_klass(class_name, class_loader);
2314   }
2315 
2316   return klass;
2317 }
2318 
2319 bool SystemDictionary::add_loader_constraint(Symbol* class_name,
2320                                              Klass* klass_being_linked,
2321                                              Handle class_loader1,
2322                                              Handle class_loader2,
2323                                              Thread* THREAD) {
2324   ClassLoaderData* loader_data1 = class_loader_data(class_loader1);
2325   ClassLoaderData* loader_data2 = class_loader_data(class_loader2);
2326 
2327   Symbol* constraint_name = NULL;
2328 
2329   if (!Signature::is_array(class_name)) {
2330     constraint_name = class_name;
2331   } else {
2332     // For array classes, their Klass*s are not kept in the
2333     // constraint table. The element classes are.
2334     SignatureStream ss(class_name, false);
2335     ss.skip_array_prefix();  // skip all '['s
2336     if (!ss.has_envelope()) {
2337       return true;     // primitive types always pass
2338     }
2339     constraint_name = ss.as_symbol();
2340     // Increment refcount to keep constraint_name alive after
2341     // SignatureStream is destructed. It will be decremented below
2342     // before returning.
2343     constraint_name->increment_refcount();
2344   }
2345 
2346   Dictionary* dictionary1 = loader_data1->dictionary();
2347   unsigned int d_hash1 = dictionary1->compute_hash(constraint_name);
2348 
2349   Dictionary* dictionary2 = loader_data2->dictionary();
2350   unsigned int d_hash2 = dictionary2->compute_hash(constraint_name);
2351 
2352   {
2353     MutexLocker mu_s(THREAD, SystemDictionary_lock);
2354     InstanceKlass* klass1 = find_class(d_hash1, constraint_name, dictionary1);
2355     InstanceKlass* klass2 = find_class(d_hash2, constraint_name, dictionary2);
2356     bool result = constraints()->add_entry(constraint_name, klass1, class_loader1,
2357                                            klass2, class_loader2);
2358 #if INCLUDE_CDS
2359     if (Arguments::is_dumping_archive() && klass_being_linked != NULL &&
2360         !klass_being_linked->is_shared()) {
2361          SystemDictionaryShared::record_linking_constraint(constraint_name,
2362                                      InstanceKlass::cast(klass_being_linked),
2363                                      class_loader1, class_loader2, THREAD);
2364     }
2365 #endif // INCLUDE_CDS
2366     if (Signature::is_array(class_name)) {
2367       constraint_name->decrement_refcount();
2368     }
2369     return result;
2370   }
2371 }
2372 
2373 // Add entry to resolution error table to record the error when the first
2374 // attempt to resolve a reference to a class has failed.
2375 void SystemDictionary::add_resolution_error(const constantPoolHandle& pool, int which,
2376                                             Symbol* error, Symbol* message) {
2377   unsigned int hash = resolution_errors()->compute_hash(pool, which);
2378   int index = resolution_errors()->hash_to_index(hash);
2379   {
2380     MutexLocker ml(Thread::current(), SystemDictionary_lock);
2381     resolution_errors()->add_entry(index, hash, pool, which, error, message);
2382   }
2383 }
2384 
2385 // Delete a resolution error for RedefineClasses for a constant pool is going away
2386 void SystemDictionary::delete_resolution_error(ConstantPool* pool) {
2387   resolution_errors()->delete_entry(pool);
2388 }
2389 
2390 // Lookup resolution error table. Returns error if found, otherwise NULL.
2391 Symbol* SystemDictionary::find_resolution_error(const constantPoolHandle& pool, int which,
2392                                                 Symbol** message) {
2393   unsigned int hash = resolution_errors()->compute_hash(pool, which);
2394   int index = resolution_errors()->hash_to_index(hash);
2395   {
2396     MutexLocker ml(Thread::current(), SystemDictionary_lock);
2397     ResolutionErrorEntry* entry = resolution_errors()->find_entry(index, hash, pool, which);
2398     if (entry != NULL) {
2399       *message = entry->message();
2400       return entry->error();
2401     } else {
2402       return NULL;
2403     }
2404   }
2405 }
2406 
2407 // Add an entry to resolution error table to record an error in resolving or
2408 // validating a nest host. This is used to construct informative error
2409 // messages when IllegalAccessError's occur. If an entry already exists it will
2410 // be updated with the nest host error message.
2411 void SystemDictionary::add_nest_host_error(const constantPoolHandle& pool,
2412                                            int which,
2413                                            const char* message) {
2414   unsigned int hash = resolution_errors()->compute_hash(pool, which);
2415   int index = resolution_errors()->hash_to_index(hash);
2416   {
2417     MutexLocker ml(Thread::current(), SystemDictionary_lock);
2418     ResolutionErrorEntry* entry = resolution_errors()->find_entry(index, hash, pool, which);
2419     if (entry != NULL) {
2420       assert(entry->nest_host_error() == NULL, "Nest host error message already set!");
2421       entry->set_nest_host_error(message);
2422     } else {
2423       resolution_errors()->add_entry(index, hash, pool, which, message);
2424     }
2425   }
2426 }
2427 
2428 // Lookup any nest host error
2429 const char* SystemDictionary::find_nest_host_error(const constantPoolHandle& pool, int which) {
2430   unsigned int hash = resolution_errors()->compute_hash(pool, which);
2431   int index = resolution_errors()->hash_to_index(hash);
2432   {
2433     MutexLocker ml(Thread::current(), SystemDictionary_lock);
2434     ResolutionErrorEntry* entry = resolution_errors()->find_entry(index, hash, pool, which);
2435     if (entry != NULL) {
2436       return entry->nest_host_error();
2437     } else {
2438       return NULL;
2439     }
2440   }
2441 }
2442 
2443 
2444 // Signature constraints ensure that callers and callees agree about
2445 // the meaning of type names in their signatures.  This routine is the
2446 // intake for constraints.  It collects them from several places:
2447 //
2448 //  * LinkResolver::resolve_method (if check_access is true) requires
2449 //    that the resolving class (the caller) and the defining class of
2450 //    the resolved method (the callee) agree on each type in the
2451 //    method's signature.
2452 //
2453 //  * LinkResolver::resolve_interface_method performs exactly the same
2454 //    checks.
2455 //
2456 //  * LinkResolver::resolve_field requires that the constant pool
2457 //    attempting to link to a field agree with the field's defining
2458 //    class about the type of the field signature.
2459 //
2460 //  * klassVtable::initialize_vtable requires that, when a class
2461 //    overrides a vtable entry allocated by a superclass, that the
2462 //    overriding method (i.e., the callee) agree with the superclass
2463 //    on each type in the method's signature.
2464 //
2465 //  * klassItable::initialize_itable requires that, when a class fills
2466 //    in its itables, for each non-abstract method installed in an
2467 //    itable, the method (i.e., the callee) agree with the interface
2468 //    on each type in the method's signature.
2469 //
2470 // All those methods have a boolean (check_access, checkconstraints)
2471 // which turns off the checks.  This is used from specialized contexts
2472 // such as bootstrapping, dumping, and debugging.
2473 //
2474 // No direct constraint is placed between the class and its
2475 // supertypes.  Constraints are only placed along linked relations
2476 // between callers and callees.  When a method overrides or implements
2477 // an abstract method in a supertype (superclass or interface), the
2478 // constraints are placed as if the supertype were the caller to the
2479 // overriding method.  (This works well, since callers to the
2480 // supertype have already established agreement between themselves and
2481 // the supertype.)  As a result of all this, a class can disagree with
2482 // its supertype about the meaning of a type name, as long as that
2483 // class neither calls a relevant method of the supertype, nor is
2484 // called (perhaps via an override) from the supertype.
2485 //
2486 //
2487 // SystemDictionary::check_signature_loaders(sig, klass_being_linked, l1, l2)
2488 //
2489 // Make sure all class components (including arrays) in the given
2490 // signature will be resolved to the same class in both loaders.
2491 // Returns the name of the type that failed a loader constraint check, or
2492 // NULL if no constraint failed.  No exception except OOME is thrown.
2493 // Arrays are not added to the loader constraint table, their elements are.
2494 Symbol* SystemDictionary::check_signature_loaders(Symbol* signature,
2495                                                Klass* klass_being_linked,
2496                                                Handle loader1, Handle loader2,
2497                                                bool is_method, TRAPS)  {
2498   // Nothing to do if loaders are the same.
2499   if (loader1() == loader2()) {
2500     return NULL;
2501   }
2502 
2503   for (SignatureStream ss(signature, is_method); !ss.is_done(); ss.next()) {
2504     if (ss.is_reference()) {
2505       Symbol* sig = ss.as_symbol();
2506       // Note: In the future, if template-like types can take
2507       // arguments, we will want to recognize them and dig out class
2508       // names hiding inside the argument lists.
2509       if (!add_loader_constraint(sig, klass_being_linked, loader1, loader2, THREAD)) {
2510         return sig;
2511       }
2512     }
2513   }
2514   return NULL;
2515 }
2516 
2517 Method* SystemDictionary::find_method_handle_intrinsic(vmIntrinsics::ID iid,
2518                                                        Symbol* signature,
2519                                                        TRAPS) {
2520   methodHandle empty;
2521   assert(MethodHandles::is_signature_polymorphic(iid) &&
2522          MethodHandles::is_signature_polymorphic_intrinsic(iid) &&
2523          iid != vmIntrinsics::_invokeGeneric,
2524          "must be a known MH intrinsic iid=%d: %s", iid, vmIntrinsics::name_at(iid));
2525 
2526   unsigned int hash  = invoke_method_table()->compute_hash(signature, iid);
2527   int          index = invoke_method_table()->hash_to_index(hash);
2528   SymbolPropertyEntry* spe = invoke_method_table()->find_entry(index, hash, signature, iid);
2529   methodHandle m;
2530   if (spe == NULL || spe->method() == NULL) {
2531     spe = NULL;
2532     // Must create lots of stuff here, but outside of the SystemDictionary lock.
2533     m = Method::make_method_handle_intrinsic(iid, signature, CHECK_NULL);
2534     if (!Arguments::is_interpreter_only()) {
2535       // Generate a compiled form of the MH intrinsic.
2536       AdapterHandlerLibrary::create_native_wrapper(m);
2537       // Check if have the compiled code.
2538       if (!m->has_compiled_code()) {
2539         THROW_MSG_NULL(vmSymbols::java_lang_VirtualMachineError(),
2540                        "Out of space in CodeCache for method handle intrinsic");
2541       }
2542     }
2543     // Now grab the lock.  We might have to throw away the new method,
2544     // if a racing thread has managed to install one at the same time.
2545     {
2546       MutexLocker ml(THREAD, SystemDictionary_lock);
2547       spe = invoke_method_table()->find_entry(index, hash, signature, iid);
2548       if (spe == NULL)
2549         spe = invoke_method_table()->add_entry(index, hash, signature, iid);
2550       if (spe->method() == NULL)
2551         spe->set_method(m());
2552     }
2553   }
2554 
2555   assert(spe != NULL && spe->method() != NULL, "");
2556   assert(Arguments::is_interpreter_only() || (spe->method()->has_compiled_code() &&
2557          spe->method()->code()->entry_point() == spe->method()->from_compiled_entry()),
2558          "MH intrinsic invariant");
2559   return spe->method();
2560 }
2561 
2562 // Helper for unpacking the return value from linkMethod and linkCallSite.
2563 static Method* unpack_method_and_appendix(Handle mname,
2564                                           Klass* accessing_klass,
2565                                           objArrayHandle appendix_box,
2566                                           Handle* appendix_result,
2567                                           TRAPS) {
2568   if (mname.not_null()) {
2569     Method* m = java_lang_invoke_MemberName::vmtarget(mname());
2570     if (m != NULL) {
2571       oop appendix = appendix_box->obj_at(0);
2572       LogTarget(Info, methodhandles) lt;
2573       if (lt.develop_is_enabled()) {
2574         ResourceMark rm(THREAD);
2575         LogStream ls(lt);
2576         ls.print("Linked method=" INTPTR_FORMAT ": ", p2i(m));
2577         m->print_on(&ls);
2578         if (appendix != NULL) { ls.print("appendix = "); appendix->print_on(&ls); }
2579         ls.cr();
2580       }
2581 
2582       (*appendix_result) = Handle(THREAD, appendix);
2583       // the target is stored in the cpCache and if a reference to this
2584       // MemberName is dropped we need a way to make sure the
2585       // class_loader containing this method is kept alive.
2586       methodHandle mh(THREAD, m); // record_dependency can safepoint.
2587       ClassLoaderData* this_key = accessing_klass->class_loader_data();
2588       this_key->record_dependency(m->method_holder());
2589       return mh();
2590     }
2591   }
2592   THROW_MSG_NULL(vmSymbols::java_lang_LinkageError(), "bad value from MethodHandleNatives");
2593 }
2594 
2595 Method* SystemDictionary::find_method_handle_invoker(Klass* klass,
2596                                                      Symbol* name,
2597                                                      Symbol* signature,
2598                                                           Klass* accessing_klass,
2599                                                           Handle *appendix_result,
2600                                                           TRAPS) {
2601   assert(THREAD->can_call_java() ,"");
2602   Handle method_type =
2603     SystemDictionary::find_method_handle_type(signature, accessing_klass, CHECK_NULL);
2604 
2605   int ref_kind = JVM_REF_invokeVirtual;
2606   oop name_oop = StringTable::intern(name, CHECK_NULL);
2607   Handle name_str (THREAD, name_oop);
2608   objArrayHandle appendix_box = oopFactory::new_objArray_handle(SystemDictionary::Object_klass(), 1, CHECK_NULL);
2609   assert(appendix_box->obj_at(0) == NULL, "");
2610 
2611   // This should not happen.  JDK code should take care of that.
2612   if (accessing_klass == NULL || method_type.is_null()) {
2613     THROW_MSG_NULL(vmSymbols::java_lang_InternalError(), "bad invokehandle");
2614   }
2615 
2616   // call java.lang.invoke.MethodHandleNatives::linkMethod(... String, MethodType) -> MemberName
2617   JavaCallArguments args;
2618   args.push_oop(Handle(THREAD, accessing_klass->java_mirror()));
2619   args.push_int(ref_kind);
2620   args.push_oop(Handle(THREAD, klass->java_mirror()));
2621   args.push_oop(name_str);
2622   args.push_oop(method_type);
2623   args.push_oop(appendix_box);
2624   JavaValue result(T_OBJECT);
2625   JavaCalls::call_static(&result,
2626                          SystemDictionary::MethodHandleNatives_klass(),
2627                          vmSymbols::linkMethod_name(),
2628                          vmSymbols::linkMethod_signature(),
2629                          &args, CHECK_NULL);
2630   Handle mname(THREAD, (oop) result.get_jobject());
2631   return unpack_method_and_appendix(mname, accessing_klass, appendix_box, appendix_result, THREAD);
2632 }
2633 
2634 // Decide if we can globally cache a lookup of this class, to be returned to any client that asks.
2635 // We must ensure that all class loaders everywhere will reach this class, for any client.
2636 // This is a safe bet for public classes in java.lang, such as Object and String.
2637 // We also include public classes in java.lang.invoke, because they appear frequently in system-level method types.
2638 // Out of an abundance of caution, we do not include any other classes, not even for packages like java.util.
2639 static bool is_always_visible_class(oop mirror) {
2640   Klass* klass = java_lang_Class::as_Klass(mirror);
2641   if (klass->is_objArray_klass()) {
2642     klass = ObjArrayKlass::cast(klass)->bottom_klass(); // check element type
2643   }
2644   if (klass->is_typeArray_klass()) {
2645     return true; // primitive array
2646   }
2647   assert(klass->is_instance_klass(), "%s", klass->external_name());
2648   return klass->is_public() &&
2649          (InstanceKlass::cast(klass)->is_same_class_package(SystemDictionary::Object_klass()) ||       // java.lang
2650           InstanceKlass::cast(klass)->is_same_class_package(SystemDictionary::MethodHandle_klass()));  // java.lang.invoke
2651 }
2652 
2653 // Find or construct the Java mirror (java.lang.Class instance) for
2654 // the given field type signature, as interpreted relative to the
2655 // given class loader.  Handles primitives, void, references, arrays,
2656 // and all other reflectable types, except method types.
2657 // N.B.  Code in reflection should use this entry point.
2658 Handle SystemDictionary::find_java_mirror_for_type(Symbol* signature,
2659                                                    Klass* accessing_klass,
2660                                                    Handle class_loader,
2661                                                    Handle protection_domain,
2662                                                    SignatureStream::FailureMode failure_mode,
2663                                                    TRAPS) {
2664   assert(accessing_klass == NULL || (class_loader.is_null() && protection_domain.is_null()),
2665          "one or the other, or perhaps neither");
2666 
2667   // What we have here must be a valid field descriptor,
2668   // and all valid field descriptors are supported.
2669   // Produce the same java.lang.Class that reflection reports.
2670   if (accessing_klass != NULL) {
2671     class_loader      = Handle(THREAD, accessing_klass->class_loader());
2672     protection_domain = Handle(THREAD, accessing_klass->protection_domain());
2673   }
2674   ResolvingSignatureStream ss(signature, class_loader, protection_domain, false);
2675   oop mirror_oop = ss.as_java_mirror(failure_mode, CHECK_NH);
2676   if (mirror_oop == NULL) {
2677     return Handle();  // report failure this way
2678   }
2679   Handle mirror(THREAD, mirror_oop);
2680 
2681   if (accessing_klass != NULL) {
2682     // Check accessibility, emulating ConstantPool::verify_constant_pool_resolve.
2683     Klass* sel_klass = java_lang_Class::as_Klass(mirror());
2684     if (sel_klass != NULL) {
2685       LinkResolver::check_klass_accessibility(accessing_klass, sel_klass, CHECK_NH);
2686     }
2687   }
2688   return mirror;
2689 }
2690 
2691 
2692 // Ask Java code to find or construct a java.lang.invoke.MethodType for the given
2693 // signature, as interpreted relative to the given class loader.
2694 // Because of class loader constraints, all method handle usage must be
2695 // consistent with this loader.
2696 Handle SystemDictionary::find_method_handle_type(Symbol* signature,
2697                                                  Klass* accessing_klass,
2698                                                  TRAPS) {
2699   Handle empty;
2700   vmIntrinsics::ID null_iid = vmIntrinsics::_none;  // distinct from all method handle invoker intrinsics
2701   unsigned int hash  = invoke_method_table()->compute_hash(signature, null_iid);
2702   int          index = invoke_method_table()->hash_to_index(hash);
2703   SymbolPropertyEntry* spe = invoke_method_table()->find_entry(index, hash, signature, null_iid);
2704   if (spe != NULL && spe->method_type() != NULL) {
2705     assert(java_lang_invoke_MethodType::is_instance(spe->method_type()), "");
2706     return Handle(THREAD, spe->method_type());
2707   } else if (!THREAD->can_call_java()) {
2708     warning("SystemDictionary::find_method_handle_type called from compiler thread");  // FIXME
2709     return Handle();  // do not attempt from within compiler, unless it was cached
2710   }
2711 
2712   Handle class_loader, protection_domain;
2713   if (accessing_klass != NULL) {
2714     class_loader      = Handle(THREAD, accessing_klass->class_loader());
2715     protection_domain = Handle(THREAD, accessing_klass->protection_domain());
2716   }
2717   bool can_be_cached = true;
2718   int npts = ArgumentCount(signature).size();
2719   objArrayHandle pts = oopFactory::new_objArray_handle(SystemDictionary::Class_klass(), npts, CHECK_(empty));
2720   int arg = 0;
2721   Handle rt; // the return type from the signature
2722   ResourceMark rm(THREAD);
2723   for (SignatureStream ss(signature); !ss.is_done(); ss.next()) {
2724     oop mirror = NULL;
2725     if (can_be_cached) {
2726       // Use neutral class loader to lookup candidate classes to be placed in the cache.
2727       mirror = ss.as_java_mirror(Handle(), Handle(),
2728                                  SignatureStream::ReturnNull, CHECK_(empty));
2729       if (mirror == NULL || (ss.is_reference() && !is_always_visible_class(mirror))) {
2730         // Fall back to accessing_klass context.
2731         can_be_cached = false;
2732       }
2733     }
2734     if (!can_be_cached) {
2735       // Resolve, throwing a real error if it doesn't work.
2736       mirror = ss.as_java_mirror(class_loader, protection_domain,
2737                                  SignatureStream::NCDFError, CHECK_(empty));
2738     }
2739     assert(mirror != NULL, "%s", ss.as_symbol()->as_C_string());
2740     if (ss.at_return_type())
2741       rt = Handle(THREAD, mirror);
2742     else
2743       pts->obj_at_put(arg++, mirror);
2744 
2745     // Check accessibility.
2746     if (!java_lang_Class::is_primitive(mirror) && accessing_klass != NULL) {
2747       Klass* sel_klass = java_lang_Class::as_Klass(mirror);
2748       mirror = NULL;  // safety
2749       // Emulate ConstantPool::verify_constant_pool_resolve.
2750       LinkResolver::check_klass_accessibility(accessing_klass, sel_klass, CHECK_(empty));
2751     }
2752   }
2753   assert(arg == npts, "");
2754 
2755   // call java.lang.invoke.MethodHandleNatives::findMethodHandleType(Class rt, Class[] pts) -> MethodType
2756   JavaCallArguments args(Handle(THREAD, rt()));
2757   args.push_oop(pts);
2758   JavaValue result(T_OBJECT);
2759   JavaCalls::call_static(&result,
2760                          SystemDictionary::MethodHandleNatives_klass(),
2761                          vmSymbols::findMethodHandleType_name(),
2762                          vmSymbols::findMethodHandleType_signature(),
2763                          &args, CHECK_(empty));
2764   Handle method_type(THREAD, (oop) result.get_jobject());
2765 
2766   if (can_be_cached) {
2767     // We can cache this MethodType inside the JVM.
2768     MutexLocker ml(THREAD, SystemDictionary_lock);
2769     spe = invoke_method_table()->find_entry(index, hash, signature, null_iid);
2770     if (spe == NULL)
2771       spe = invoke_method_table()->add_entry(index, hash, signature, null_iid);
2772     if (spe->method_type() == NULL) {
2773       spe->set_method_type(method_type());
2774     }
2775   }
2776 
2777   // report back to the caller with the MethodType
2778   return method_type;
2779 }
2780 
2781 Handle SystemDictionary::find_field_handle_type(Symbol* signature,
2782                                                 Klass* accessing_klass,
2783                                                 TRAPS) {
2784   Handle empty;
2785   ResourceMark rm(THREAD);
2786   SignatureStream ss(signature, /*is_method=*/ false);
2787   if (!ss.is_done()) {
2788     Handle class_loader, protection_domain;
2789     if (accessing_klass != NULL) {
2790       class_loader      = Handle(THREAD, accessing_klass->class_loader());
2791       protection_domain = Handle(THREAD, accessing_klass->protection_domain());
2792     }
2793     oop mirror = ss.as_java_mirror(class_loader, protection_domain, SignatureStream::NCDFError, CHECK_(empty));
2794     ss.next();
2795     if (ss.is_done()) {
2796       return Handle(THREAD, mirror);
2797     }
2798   }
2799   return empty;
2800 }
2801 
2802 // Ask Java code to find or construct a method handle constant.
2803 Handle SystemDictionary::link_method_handle_constant(Klass* caller,
2804                                                      int ref_kind, //e.g., JVM_REF_invokeVirtual
2805                                                      Klass* callee,
2806                                                      Symbol* name,
2807                                                      Symbol* signature,
2808                                                      TRAPS) {
2809   Handle empty;
2810   if (caller == NULL) {
2811     THROW_MSG_(vmSymbols::java_lang_InternalError(), "bad MH constant", empty);
2812   }
2813   Handle name_str      = java_lang_String::create_from_symbol(name,      CHECK_(empty));
2814   Handle signature_str = java_lang_String::create_from_symbol(signature, CHECK_(empty));
2815 
2816   // Put symbolic info from the MH constant into freshly created MemberName and resolve it.
2817   Handle mname = MemberName_klass()->allocate_instance_handle(CHECK_(empty));
2818   java_lang_invoke_MemberName::set_clazz(mname(), callee->java_mirror());
2819   java_lang_invoke_MemberName::set_name (mname(), name_str());
2820   java_lang_invoke_MemberName::set_type (mname(), signature_str());
2821   java_lang_invoke_MemberName::set_flags(mname(), MethodHandles::ref_kind_to_flags(ref_kind));
2822 
2823   if (ref_kind == JVM_REF_invokeVirtual &&
2824       MethodHandles::is_signature_polymorphic_public_name(callee, name)) {
2825     // Skip resolution for public signature polymorphic methods such as
2826     // j.l.i.MethodHandle.invoke()/invokeExact() and those on VarHandle
2827     // They require appendix argument which MemberName resolution doesn't handle.
2828     // There's special logic on JDK side to handle them
2829     // (see MethodHandles.linkMethodHandleConstant() and MethodHandles.findVirtualForMH()).
2830   } else {
2831     MethodHandles::resolve_MemberName(mname, caller, 0, false /*speculative_resolve*/, CHECK_(empty));
2832   }
2833 
2834   // After method/field resolution succeeded, it's safe to resolve MH signature as well.
2835   Handle type = MethodHandles::resolve_MemberName_type(mname, caller, CHECK_(empty));
2836 
2837   // call java.lang.invoke.MethodHandleNatives::linkMethodHandleConstant(Class caller, int refKind, Class callee, String name, Object type) -> MethodHandle
2838   JavaCallArguments args;
2839   args.push_oop(Handle(THREAD, caller->java_mirror()));  // the referring class
2840   args.push_int(ref_kind);
2841   args.push_oop(Handle(THREAD, callee->java_mirror()));  // the target class
2842   args.push_oop(name_str);
2843   args.push_oop(type);
2844   JavaValue result(T_OBJECT);
2845   JavaCalls::call_static(&result,
2846                          SystemDictionary::MethodHandleNatives_klass(),
2847                          vmSymbols::linkMethodHandleConstant_name(),
2848                          vmSymbols::linkMethodHandleConstant_signature(),
2849                          &args, CHECK_(empty));
2850   return Handle(THREAD, (oop) result.get_jobject());
2851 }
2852 
2853 // Ask Java to run a bootstrap method, in order to create a dynamic call site
2854 // while linking an invokedynamic op, or compute a constant for Dynamic_info CP entry
2855 // with linkage results being stored back into the bootstrap specifier.
2856 void SystemDictionary::invoke_bootstrap_method(BootstrapInfo& bootstrap_specifier, TRAPS) {
2857   // Resolve the bootstrap specifier, its name, type, and static arguments
2858   bootstrap_specifier.resolve_bsm(CHECK);
2859 
2860   // This should not happen.  JDK code should take care of that.
2861   if (bootstrap_specifier.caller() == NULL || bootstrap_specifier.type_arg().is_null()) {
2862     THROW_MSG(vmSymbols::java_lang_InternalError(), "Invalid bootstrap method invocation with no caller or type argument");
2863   }
2864 
2865   bool is_indy = bootstrap_specifier.is_method_call();
2866   objArrayHandle appendix_box;
2867   if (is_indy) {
2868     // Some method calls may require an appendix argument.  Arrange to receive it.
2869     appendix_box = oopFactory::new_objArray_handle(SystemDictionary::Object_klass(), 1, CHECK);
2870     assert(appendix_box->obj_at(0) == NULL, "");
2871   }
2872 
2873   // call condy: java.lang.invoke.MethodHandleNatives::linkDynamicConstant(caller, condy_index, bsm, type, info)
2874   //       indy: java.lang.invoke.MethodHandleNatives::linkCallSite(caller, indy_index, bsm, name, mtype, info, &appendix)
2875   JavaCallArguments args;
2876   args.push_oop(Handle(THREAD, bootstrap_specifier.caller_mirror()));
2877   args.push_int(bootstrap_specifier.bss_index());
2878   args.push_oop(bootstrap_specifier.bsm());
2879   args.push_oop(bootstrap_specifier.name_arg());
2880   args.push_oop(bootstrap_specifier.type_arg());
2881   args.push_oop(bootstrap_specifier.arg_values());
2882   if (is_indy) {
2883     args.push_oop(appendix_box);
2884   }
2885   JavaValue result(T_OBJECT);
2886   JavaCalls::call_static(&result,
2887                          SystemDictionary::MethodHandleNatives_klass(),
2888                          is_indy ? vmSymbols::linkCallSite_name() : vmSymbols::linkDynamicConstant_name(),
2889                          is_indy ? vmSymbols::linkCallSite_signature() : vmSymbols::linkDynamicConstant_signature(),
2890                          &args, CHECK);
2891 
2892   Handle value(THREAD, (oop) result.get_jobject());
2893   if (is_indy) {
2894     Handle appendix;
2895     Method* method = unpack_method_and_appendix(value,
2896                                                 bootstrap_specifier.caller(),
2897                                                 appendix_box,
2898                                                 &appendix, CHECK);
2899     methodHandle mh(THREAD, method);
2900     bootstrap_specifier.set_resolved_method(mh, appendix);
2901   } else {
2902     bootstrap_specifier.set_resolved_value(value);
2903   }
2904 
2905   // sanity check
2906   assert(bootstrap_specifier.is_resolved() ||
2907          (bootstrap_specifier.is_method_call() &&
2908           bootstrap_specifier.resolved_method().not_null()), "bootstrap method call failed");
2909 }
2910 
2911 // Protection domain cache table handling
2912 
2913 ProtectionDomainCacheEntry* SystemDictionary::cache_get(Handle protection_domain) {
2914   return _pd_cache_table->get(protection_domain);
2915 }
2916 
2917 ClassLoaderData* SystemDictionary::class_loader_data(Handle class_loader) {
2918   return ClassLoaderData::class_loader_data(class_loader());
2919 }
2920 
2921 bool SystemDictionary::is_wk_klass_loaded(InstanceKlass* klass) {
2922   return !(klass == NULL || !klass->is_loaded());
2923 }
2924 
2925 bool SystemDictionary::is_nonpublic_Object_method(Method* m) {
2926   assert(m != NULL, "Unexpected NULL Method*");
2927   return !m->is_public() && m->method_holder() == SystemDictionary::Object_klass();
2928 }
2929 
2930 // ----------------------------------------------------------------------------
2931 
2932 void SystemDictionary::print_on(outputStream *st) {
2933   CDS_ONLY(SystemDictionaryShared::print_on(st));
2934   GCMutexLocker mu(SystemDictionary_lock);
2935 
2936   ClassLoaderDataGraph::print_dictionary(st);
2937 
2938   // Placeholders
2939   placeholders()->print_on(st);
2940   st->cr();
2941 
2942   // loader constraints - print under SD_lock
2943   constraints()->print_on(st);
2944   st->cr();
2945 
2946   _pd_cache_table->print_on(st);
2947   st->cr();
2948 }
2949 
2950 void SystemDictionary::print() { print_on(tty); }
2951 
2952 void SystemDictionary::verify() {
2953   guarantee(constraints() != NULL,
2954             "Verify of loader constraints failed");
2955   guarantee(placeholders()->number_of_entries() >= 0,
2956             "Verify of placeholders failed");
2957 
2958   GCMutexLocker mu(SystemDictionary_lock);
2959 
2960   // Verify dictionary
2961   ClassLoaderDataGraph::verify_dictionary();
2962 
2963   placeholders()->verify();
2964 
2965   // Verify constraint table
2966   guarantee(constraints() != NULL, "Verify of loader constraints failed");
2967   constraints()->verify(placeholders());
2968 
2969   _pd_cache_table->verify();
2970 }
2971 
2972 void SystemDictionary::dump(outputStream *st, bool verbose) {
2973   assert_locked_or_safepoint(SystemDictionary_lock);
2974   if (verbose) {
2975     print_on(st);
2976   } else {
2977     CDS_ONLY(SystemDictionaryShared::print_table_statistics(st));
2978     ClassLoaderDataGraph::print_table_statistics(st);
2979     placeholders()->print_table_statistics(st, "Placeholder Table");
2980     constraints()->print_table_statistics(st, "LoaderConstraints Table");
2981     pd_cache_table()->print_table_statistics(st, "ProtectionDomainCache Table");
2982   }
2983 }
2984 
2985 TableStatistics SystemDictionary::placeholders_statistics() {
2986   MutexLocker ml(SystemDictionary_lock);
2987   return placeholders()->statistics_calculate();
2988 }
2989 
2990 TableStatistics SystemDictionary::loader_constraints_statistics() {
2991   MutexLocker ml(SystemDictionary_lock);
2992   return constraints()->statistics_calculate();
2993 }
2994 
2995 TableStatistics SystemDictionary::protection_domain_cache_statistics() {
2996   MutexLocker ml(SystemDictionary_lock);
2997   return pd_cache_table()->statistics_calculate();
2998 }
2999 
3000 // Utility for dumping dictionaries.
3001 SystemDictionaryDCmd::SystemDictionaryDCmd(outputStream* output, bool heap) :
3002                                  DCmdWithParser(output, heap),
3003   _verbose("-verbose", "Dump the content of each dictionary entry for all class loaders",
3004            "BOOLEAN", false, "false") {
3005   _dcmdparser.add_dcmd_option(&_verbose);
3006 }
3007 
3008 void SystemDictionaryDCmd::execute(DCmdSource source, TRAPS) {
3009   VM_DumpHashtable dumper(output(), VM_DumpHashtable::DumpSysDict,
3010                          _verbose.value());
3011   VMThread::execute(&dumper);
3012 }
3013 
3014 int SystemDictionaryDCmd::num_arguments() {
3015   ResourceMark rm;
3016   SystemDictionaryDCmd* dcmd = new SystemDictionaryDCmd(NULL, false);
3017   if (dcmd != NULL) {
3018     DCmdMark mark(dcmd);
3019     return dcmd->_dcmdparser.num_arguments();
3020   } else {
3021     return 0;
3022   }
3023 }