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