rev 58452 : imported patch pkg_name_from_class

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