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