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