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