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