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