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