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