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