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