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