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