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