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 oop         SystemDictionary::_system_loader_lock_obj     =  NULL;
 102 
 103 InstanceKlass*      SystemDictionary::_well_known_klasses[SystemDictionary::WKID_LIMIT]
 104                                                           =  { NULL /*, NULL...*/ };
 105 
 106 InstanceKlass*      SystemDictionary::_box_klasses[T_VOID+1]      =  { NULL /*, NULL...*/ };
 107 
 108 oop         SystemDictionary::_java_system_loader         =  NULL;
 109 oop         SystemDictionary::_java_platform_loader       =  NULL;
 110 
 111 bool        SystemDictionary::_has_checkPackageAccess     =  false;
 112 
 113 // Default ProtectionDomainCacheSize value
 114 
 115 const int defaultProtectionDomainCacheSize = 1009;
 116 
 117 OopStorage* SystemDictionary::_vm_global_oop_storage = NULL;
 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       // But, do not add to dictionary.
1043     }
1044 
1045     // Rewrite and patch constant pool here.
1046     k->link_class(CHECK_NULL);
1047     if (cp_patches != NULL) {
1048       k->constants()->patch_resolved_references(cp_patches);
1049     }
1050 
1051     // If it's anonymous, initialize it now, since nobody else will.
1052     k->eager_initialize(CHECK_NULL);
1053 
1054     // notify jvmti
1055     if (JvmtiExport::should_post_class_load()) {
1056         assert(THREAD->is_Java_thread(), "thread->is_Java_thread()");
1057         JvmtiExport::post_class_load((JavaThread *) THREAD, k);
1058     }
1059     if (class_load_start_event.should_commit()) {
1060       post_class_load_event(&class_load_start_event, k, loader_data);
1061     }
1062   }
1063   assert(unsafe_anonymous_host != NULL || NULL == cp_patches,
1064          "cp_patches only found with unsafe_anonymous_host");
1065 
1066   return k;
1067 }
1068 
1069 // Add a klass to the system from a stream (called by jni_DefineClass and
1070 // JVM_DefineClass).
1071 // Note: class_name can be NULL. In that case we do not know the name of
1072 // the class until we have parsed the stream.
1073 
1074 InstanceKlass* SystemDictionary::resolve_from_stream(Symbol* class_name,
1075                                                      Handle class_loader,
1076                                                      Handle protection_domain,
1077                                                      ClassFileStream* st,
1078                                                      TRAPS) {
1079 
1080   HandleMark hm(THREAD);
1081 
1082   // Classloaders that support parallelism, e.g. bootstrap classloader,
1083   // do not acquire lock here
1084   bool DoObjectLock = true;
1085   if (is_parallelCapable(class_loader)) {
1086     DoObjectLock = false;
1087   }
1088 
1089   ClassLoaderData* loader_data = register_loader(class_loader);
1090 
1091   // Make sure we are synchronized on the class loader before we proceed
1092   Handle lockObject = compute_loader_lock_object(class_loader, THREAD);
1093   check_loader_lock_contention(lockObject, THREAD);
1094   ObjectLocker ol(lockObject, THREAD, DoObjectLock);
1095 
1096   assert(st != NULL, "invariant");
1097 
1098   // Parse the stream and create a klass.
1099   // Note that we do this even though this klass might
1100   // already be present in the SystemDictionary, otherwise we would not
1101   // throw potential ClassFormatErrors.
1102  InstanceKlass* k = NULL;
1103 
1104 #if INCLUDE_CDS
1105   if (!DumpSharedSpaces) {
1106     k = SystemDictionaryShared::lookup_from_stream(class_name,
1107                                                    class_loader,
1108                                                    protection_domain,
1109                                                    st,
1110                                                    CHECK_NULL);
1111   }
1112 #endif
1113 
1114   if (k == NULL) {
1115     if (st->buffer() == NULL) {
1116       return NULL;
1117     }
1118     k = KlassFactory::create_from_stream(st,
1119                                          class_name,
1120                                          loader_data,
1121                                          protection_domain,
1122                                          NULL, // unsafe_anonymous_host
1123                                          NULL, // cp_patches
1124                                          CHECK_NULL);
1125   }
1126 
1127   assert(k != NULL, "no klass created");
1128   Symbol* h_name = k->name();
1129   assert(class_name == NULL || class_name == h_name, "name mismatch");
1130 
1131   // Add class just loaded
1132   // If a class loader supports parallel classloading handle parallel define requests
1133   // find_or_define_instance_class may return a different InstanceKlass
1134   if (is_parallelCapable(class_loader)) {
1135     InstanceKlass* defined_k = find_or_define_instance_class(h_name, class_loader, k, THREAD);
1136     if (!HAS_PENDING_EXCEPTION && defined_k != k) {
1137       // If a parallel capable class loader already defined this class, register 'k' for cleanup.
1138       assert(defined_k != NULL, "Should have a klass if there's no exception");
1139       loader_data->add_to_deallocate_list(k);
1140       k = defined_k;
1141     }
1142   } else {
1143     define_instance_class(k, THREAD);
1144   }
1145 
1146   // If defining the class throws an exception register 'k' for cleanup.
1147   if (HAS_PENDING_EXCEPTION) {
1148     assert(k != NULL, "Must have an instance klass here!");
1149     loader_data->add_to_deallocate_list(k);
1150     return NULL;
1151   }
1152 
1153   // Make sure we have an entry in the SystemDictionary on success
1154   debug_only( {
1155     MutexLocker mu(SystemDictionary_lock, THREAD);
1156 
1157     Klass* check = find_class(h_name, k->class_loader_data());
1158     assert(check == k, "should be present in the dictionary");
1159   } );
1160 
1161   return k;
1162 }
1163 
1164 #if INCLUDE_CDS
1165 // Load a class for boot loader from the shared spaces. This also
1166 // forces the super class and all interfaces to be loaded.
1167 InstanceKlass* SystemDictionary::load_shared_boot_class(Symbol* class_name,
1168                                                         TRAPS) {
1169   InstanceKlass* ik = SystemDictionaryShared::find_builtin_class(class_name);
1170   if (ik != NULL && ik->is_shared_boot_class()) {
1171     return load_shared_class(ik, Handle(), Handle(), NULL, THREAD);
1172   }
1173   return NULL;
1174 }
1175 
1176 // Check if a shared class can be loaded by the specific classloader:
1177 //
1178 // NULL classloader:
1179 //   - Module class from "modules" jimage. ModuleEntry must be defined in the classloader.
1180 //   - Class from -Xbootclasspath/a. The class has no defined PackageEntry, or must
1181 //     be defined in an unnamed module.
1182 bool SystemDictionary::is_shared_class_visible(Symbol* class_name,
1183                                                InstanceKlass* ik,
1184                                                Handle class_loader, TRAPS) {
1185   assert(!ModuleEntryTable::javabase_moduleEntry()->is_patched(),
1186          "Cannot use sharing if java.base is patched");
1187   ResourceMark rm;
1188   int path_index = ik->shared_classpath_index();
1189   ClassLoaderData* loader_data = class_loader_data(class_loader);
1190   if (path_index < 0) {
1191     // path_index < 0 indicates that the class is intended for a custom loader
1192     // and should not be loaded by boot/platform/app loaders
1193     if (loader_data->is_builtin_class_loader_data()) {
1194       return false;
1195     } else {
1196       return true;
1197     }
1198   }
1199   SharedClassPathEntry* ent =
1200             (SharedClassPathEntry*)FileMapInfo::shared_path(path_index);
1201   if (!Universe::is_module_initialized()) {
1202     assert(ent != NULL && ent->is_modules_image(),
1203            "Loading non-bootstrap classes before the module system is initialized");
1204     assert(class_loader.is_null(), "sanity");
1205     return true;
1206   }
1207   // Get the pkg_entry from the classloader
1208   TempNewSymbol pkg_name = NULL;
1209   PackageEntry* pkg_entry = NULL;
1210   ModuleEntry* mod_entry = NULL;
1211   const char* pkg_string = NULL;
1212   pkg_name = InstanceKlass::package_from_name(class_name, CHECK_false);
1213   if (pkg_name != NULL) {
1214     pkg_string = pkg_name->as_C_string();
1215     if (loader_data != NULL) {
1216       pkg_entry = loader_data->packages()->lookup_only(pkg_name);
1217     }
1218     if (pkg_entry != NULL) {
1219       mod_entry = pkg_entry->module();
1220     }
1221   }
1222 
1223   // If the archived class is from a module that has been patched at runtime,
1224   // the class cannot be loaded from the archive.
1225   if (mod_entry != NULL && mod_entry->is_patched()) {
1226     return false;
1227   }
1228 
1229   if (class_loader.is_null()) {
1230     assert(ent != NULL, "Shared class for NULL classloader must have valid SharedClassPathEntry");
1231     // The NULL classloader can load archived class originated from the
1232     // "modules" jimage and the -Xbootclasspath/a. For class from the
1233     // "modules" jimage, the PackageEntry/ModuleEntry must be defined
1234     // by the NULL classloader.
1235     if (mod_entry != NULL) {
1236       // PackageEntry/ModuleEntry is found in the classloader. Check if the
1237       // ModuleEntry's location agrees with the archived class' origination.
1238       if (ent->is_modules_image() && mod_entry->location()->starts_with("jrt:")) {
1239         return true; // Module class from the "module" jimage
1240       }
1241     }
1242 
1243     // If the archived class is not from the "module" jimage, the class can be
1244     // loaded by the NULL classloader if
1245     //
1246     // 1. the class is from the unamed package
1247     // 2. or, the class is not from a module defined in the NULL classloader
1248     // 3. or, the class is from an unamed module
1249     if (!ent->is_modules_image() && ik->is_shared_boot_class()) {
1250       // the class is from the -Xbootclasspath/a
1251       if (pkg_string == NULL ||
1252           pkg_entry == NULL ||
1253           pkg_entry->in_unnamed_module()) {
1254         assert(mod_entry == NULL ||
1255                mod_entry == loader_data->unnamed_module(),
1256                "the unnamed module is not defined in the classloader");
1257         return true;
1258       }
1259     }
1260     return false;
1261   } else {
1262     bool res = SystemDictionaryShared::is_shared_class_visible_for_classloader(
1263               ik, class_loader, pkg_string, pkg_name,
1264               pkg_entry, mod_entry, CHECK_(false));
1265     return res;
1266   }
1267 }
1268 
1269 InstanceKlass* SystemDictionary::load_shared_class(InstanceKlass* ik,
1270                                                    Handle class_loader,
1271                                                    Handle protection_domain,
1272                                                    const ClassFileStream *cfs,
1273                                                    TRAPS) {
1274 
1275   if (ik != NULL) {
1276     Symbol* class_name = ik->name();
1277 
1278     bool visible = is_shared_class_visible(
1279                             class_name, ik, class_loader, CHECK_NULL);
1280     if (!visible) {
1281       return NULL;
1282     }
1283 
1284     // Resolve the superclass and interfaces. They must be the same
1285     // as in dump time, because the layout of <ik> depends on
1286     // the specific layout of ik->super() and ik->local_interfaces().
1287     //
1288     // If unexpected superclass or interfaces are found, we cannot
1289     // load <ik> from the shared archive.
1290 
1291     if (ik->super() != NULL) {
1292       Symbol*  cn = ik->super()->name();
1293       Klass *s = resolve_super_or_fail(class_name, cn,
1294                                        class_loader, protection_domain, true, CHECK_NULL);
1295       if (s != ik->super()) {
1296         // The dynamically resolved super class is not the same as the one we used during dump time,
1297         // so we cannot use ik.
1298         return NULL;
1299       } else {
1300         assert(s->is_shared(), "must be");
1301       }
1302     }
1303 
1304     Array<InstanceKlass*>* interfaces = ik->local_interfaces();
1305     int num_interfaces = interfaces->length();
1306     for (int index = 0; index < num_interfaces; index++) {
1307       InstanceKlass* k = interfaces->at(index);
1308       Symbol* name  = k->name();
1309       Klass* i = resolve_super_or_fail(class_name, name, class_loader, protection_domain, false, CHECK_NULL);
1310       if (k != i) {
1311         // The dynamically resolved interface class is not the same as the one we used during dump time,
1312         // so we cannot use ik.
1313         return NULL;
1314       } else {
1315         assert(i->is_shared(), "must be");
1316       }
1317     }
1318 
1319     InstanceKlass* new_ik = KlassFactory::check_shared_class_file_load_hook(
1320         ik, class_name, class_loader, protection_domain, cfs, CHECK_NULL);
1321     if (new_ik != NULL) {
1322       // The class is changed by CFLH. Return the new class. The shared class is
1323       // not used.
1324       return new_ik;
1325     }
1326 
1327     // Adjust methods to recover missing data.  They need addresses for
1328     // interpreter entry points and their default native method address
1329     // must be reset.
1330 
1331     // Updating methods must be done under a lock so multiple
1332     // threads don't update these in parallel
1333     //
1334     // Shared classes are all currently loaded by either the bootstrap or
1335     // internal parallel class loaders, so this will never cause a deadlock
1336     // on a custom class loader lock.
1337 
1338     ClassLoaderData* loader_data = ClassLoaderData::class_loader_data(class_loader());
1339     {
1340       HandleMark hm(THREAD);
1341       Handle lockObject = compute_loader_lock_object(class_loader, THREAD);
1342       check_loader_lock_contention(lockObject, THREAD);
1343       ObjectLocker ol(lockObject, THREAD, true);
1344       // prohibited package check assumes all classes loaded from archive call
1345       // restore_unshareable_info which calls ik->set_package()
1346       ik->restore_unshareable_info(loader_data, protection_domain, CHECK_NULL);
1347     }
1348 
1349     ik->print_class_load_logging(loader_data, NULL, NULL);
1350 
1351     // For boot loader, ensure that GetSystemPackage knows that a class in this
1352     // package was loaded.
1353     if (class_loader.is_null()) {
1354       int path_index = ik->shared_classpath_index();
1355       ResourceMark rm;
1356       ClassLoader::add_package(ik->name()->as_C_string(), path_index, THREAD);
1357     }
1358 
1359     if (DumpLoadedClassList != NULL && classlist_file->is_open()) {
1360       // Only dump the classes that can be stored into CDS archive
1361       if (SystemDictionaryShared::is_sharing_possible(loader_data)) {
1362         ResourceMark rm(THREAD);
1363         classlist_file->print_cr("%s", ik->name()->as_C_string());
1364         classlist_file->flush();
1365       }
1366     }
1367 
1368     // notify a class loaded from shared object
1369     ClassLoadingService::notify_class_loaded(ik, true /* shared class */);
1370 
1371     ik->set_has_passed_fingerprint_check(false);
1372     if (UseAOT && ik->supers_have_passed_fingerprint_checks()) {
1373       uint64_t aot_fp = AOTLoader::get_saved_fingerprint(ik);
1374       uint64_t cds_fp = ik->get_stored_fingerprint();
1375       if (aot_fp != 0 && aot_fp == cds_fp) {
1376         // This class matches with a class saved in an AOT library
1377         ik->set_has_passed_fingerprint_check(true);
1378       } else {
1379         ResourceMark rm;
1380         log_info(class, fingerprint)("%s :  expected = " PTR64_FORMAT " actual = " PTR64_FORMAT, ik->external_name(), aot_fp, cds_fp);
1381       }
1382     }
1383   }
1384   return ik;
1385 }
1386 #endif // INCLUDE_CDS
1387 
1388 InstanceKlass* SystemDictionary::load_instance_class(Symbol* class_name, Handle class_loader, TRAPS) {
1389 
1390   if (class_loader.is_null()) {
1391     ResourceMark rm;
1392     PackageEntry* pkg_entry = NULL;
1393     bool search_only_bootloader_append = false;
1394     ClassLoaderData *loader_data = class_loader_data(class_loader);
1395 
1396     // Find the package in the boot loader's package entry table.
1397     TempNewSymbol pkg_name = InstanceKlass::package_from_name(class_name, CHECK_NULL);
1398     if (pkg_name != NULL) {
1399       pkg_entry = loader_data->packages()->lookup_only(pkg_name);
1400     }
1401 
1402     // Prior to attempting to load the class, enforce the boot loader's
1403     // visibility boundaries.
1404     if (!Universe::is_module_initialized()) {
1405       // During bootstrapping, prior to module initialization, any
1406       // class attempting to be loaded must be checked against the
1407       // java.base packages in the boot loader's PackageEntryTable.
1408       // No class outside of java.base is allowed to be loaded during
1409       // this bootstrapping window.
1410       if (pkg_entry == NULL || pkg_entry->in_unnamed_module()) {
1411         // Class is either in the unnamed package or in
1412         // a named package within the unnamed module.  Either
1413         // case is outside of java.base, do not attempt to
1414         // load the class post java.base definition.  If
1415         // java.base has not been defined, let the class load
1416         // and its package will be checked later by
1417         // ModuleEntryTable::verify_javabase_packages.
1418         if (ModuleEntryTable::javabase_defined()) {
1419           return NULL;
1420         }
1421       } else {
1422         // Check that the class' package is defined within java.base.
1423         ModuleEntry* mod_entry = pkg_entry->module();
1424         Symbol* mod_entry_name = mod_entry->name();
1425         if (mod_entry_name->fast_compare(vmSymbols::java_base()) != 0) {
1426           return NULL;
1427         }
1428       }
1429     } else {
1430       // After the module system has been initialized, check if the class'
1431       // package is in a module defined to the boot loader.
1432       if (pkg_name == NULL || pkg_entry == NULL || pkg_entry->in_unnamed_module()) {
1433         // Class is either in the unnamed package, in a named package
1434         // within a module not defined to the boot loader or in a
1435         // a named package within the unnamed module.  In all cases,
1436         // limit visibility to search for the class only in the boot
1437         // loader's append path.
1438         search_only_bootloader_append = true;
1439       }
1440     }
1441 
1442     // Prior to bootstrapping's module initialization, never load a class outside
1443     // of the boot loader's module path
1444     assert(Universe::is_module_initialized() ||
1445            !search_only_bootloader_append,
1446            "Attempt to load a class outside of boot loader's module path");
1447 
1448     // Search for classes in the CDS archive.
1449     InstanceKlass* k = NULL;
1450     {
1451 #if INCLUDE_CDS
1452       PerfTraceTime vmtimer(ClassLoader::perf_shared_classload_time());
1453       k = load_shared_boot_class(class_name, THREAD);
1454 #endif
1455     }
1456 
1457     if (k == NULL) {
1458       // Use VM class loader
1459       PerfTraceTime vmtimer(ClassLoader::perf_sys_classload_time());
1460       k = ClassLoader::load_class(class_name, search_only_bootloader_append, CHECK_NULL);
1461     }
1462 
1463     // find_or_define_instance_class may return a different InstanceKlass
1464     if (k != NULL) {
1465       InstanceKlass* defined_k =
1466         find_or_define_instance_class(class_name, class_loader, k, THREAD);
1467       if (!HAS_PENDING_EXCEPTION && defined_k != k) {
1468         // If a parallel capable class loader already defined this class, register 'k' for cleanup.
1469         assert(defined_k != NULL, "Should have a klass if there's no exception");
1470         loader_data->add_to_deallocate_list(k);
1471         k = defined_k;
1472       } else if (HAS_PENDING_EXCEPTION) {
1473         loader_data->add_to_deallocate_list(k);
1474         return NULL;
1475       }
1476     }
1477     return k;
1478   } else {
1479     // Use user specified class loader to load class. Call loadClass operation on class_loader.
1480     ResourceMark rm(THREAD);
1481 
1482     assert(THREAD->is_Java_thread(), "must be a JavaThread");
1483     JavaThread* jt = (JavaThread*) THREAD;
1484 
1485     PerfClassTraceTime vmtimer(ClassLoader::perf_app_classload_time(),
1486                                ClassLoader::perf_app_classload_selftime(),
1487                                ClassLoader::perf_app_classload_count(),
1488                                jt->get_thread_stat()->perf_recursion_counts_addr(),
1489                                jt->get_thread_stat()->perf_timers_addr(),
1490                                PerfClassTraceTime::CLASS_LOAD);
1491 
1492     Handle s = java_lang_String::create_from_symbol(class_name, CHECK_NULL);
1493     // Translate to external class name format, i.e., convert '/' chars to '.'
1494     Handle string = java_lang_String::externalize_classname(s, CHECK_NULL);
1495 
1496     JavaValue result(T_OBJECT);
1497 
1498     InstanceKlass* spec_klass = SystemDictionary::ClassLoader_klass();
1499 
1500     // Call public unsynchronized loadClass(String) directly for all class loaders.
1501     // For parallelCapable class loaders, JDK >=7, loadClass(String, boolean) will
1502     // acquire a class-name based lock rather than the class loader object lock.
1503     // JDK < 7 already acquire the class loader lock in loadClass(String, boolean).
1504     JavaCalls::call_virtual(&result,
1505                             class_loader,
1506                             spec_klass,
1507                             vmSymbols::loadClass_name(),
1508                             vmSymbols::string_class_signature(),
1509                             string,
1510                             CHECK_NULL);
1511 
1512     assert(result.get_type() == T_OBJECT, "just checking");
1513     oop obj = (oop) result.get_jobject();
1514 
1515     // Primitive classes return null since forName() can not be
1516     // used to obtain any of the Class objects representing primitives or void
1517     if ((obj != NULL) && !(java_lang_Class::is_primitive(obj))) {
1518       InstanceKlass* k = InstanceKlass::cast(java_lang_Class::as_Klass(obj));
1519       // For user defined Java class loaders, check that the name returned is
1520       // the same as that requested.  This check is done for the bootstrap
1521       // loader when parsing the class file.
1522       if (class_name == k->name()) {
1523         return k;
1524       }
1525     }
1526     // Class is not found or has the wrong name, return NULL
1527     return NULL;
1528   }
1529 }
1530 
1531 static void post_class_define_event(InstanceKlass* k, const ClassLoaderData* def_cld) {
1532   EventClassDefine event;
1533   if (event.should_commit()) {
1534     event.set_definedClass(k);
1535     event.set_definingClassLoader(def_cld);
1536     event.commit();
1537   }
1538 }
1539 
1540 void SystemDictionary::define_instance_class(InstanceKlass* k, TRAPS) {
1541 
1542   HandleMark hm(THREAD);
1543   ClassLoaderData* loader_data = k->class_loader_data();
1544   Handle class_loader_h(THREAD, loader_data->class_loader());
1545 
1546  // for bootstrap and other parallel classloaders don't acquire lock,
1547  // use placeholder token
1548  // If a parallelCapable class loader calls define_instance_class instead of
1549  // find_or_define_instance_class to get here, we have a timing
1550  // hole with systemDictionary updates and check_constraints
1551  if (!class_loader_h.is_null() && !is_parallelCapable(class_loader_h)) {
1552     assert(ObjectSynchronizer::current_thread_holds_lock((JavaThread*)THREAD,
1553          compute_loader_lock_object(class_loader_h, THREAD)),
1554          "define called without lock");
1555   }
1556 
1557   // Check class-loading constraints. Throw exception if violation is detected.
1558   // Grabs and releases SystemDictionary_lock
1559   // The check_constraints/find_class call and update_dictionary sequence
1560   // must be "atomic" for a specific class/classloader pair so we never
1561   // define two different instanceKlasses for that class/classloader pair.
1562   // Existing classloaders will call define_instance_class with the
1563   // classloader lock held
1564   // Parallel classloaders will call find_or_define_instance_class
1565   // which will require a token to perform the define class
1566   Symbol*  name_h = k->name();
1567   Dictionary* dictionary = loader_data->dictionary();
1568   unsigned int d_hash = dictionary->compute_hash(name_h);
1569   check_constraints(d_hash, k, class_loader_h, true, CHECK);
1570 
1571   // Register class just loaded with class loader (placed in Vector)
1572   // Note we do this before updating the dictionary, as this can
1573   // fail with an OutOfMemoryError (if it does, we will *not* put this
1574   // class in the dictionary and will not update the class hierarchy).
1575   // JVMTI FollowReferences needs to find the classes this way.
1576   if (k->class_loader() != NULL) {
1577     methodHandle m(THREAD, Universe::loader_addClass_method());
1578     JavaValue result(T_VOID);
1579     JavaCallArguments args(class_loader_h);
1580     args.push_oop(Handle(THREAD, k->java_mirror()));
1581     JavaCalls::call(&result, m, &args, CHECK);
1582   }
1583 
1584   // Add the new class. We need recompile lock during update of CHA.
1585   {
1586     unsigned int p_hash = placeholders()->compute_hash(name_h);
1587     int p_index = placeholders()->hash_to_index(p_hash);
1588 
1589     MutexLocker mu_r(Compile_lock, THREAD);
1590 
1591     // Add to class hierarchy, initialize vtables, and do possible
1592     // deoptimizations.
1593     add_to_hierarchy(k, CHECK); // No exception, but can block
1594 
1595     // Add to systemDictionary - so other classes can see it.
1596     // Grabs and releases SystemDictionary_lock
1597     update_dictionary(d_hash, p_index, p_hash,
1598                       k, class_loader_h, THREAD);
1599   }
1600   k->eager_initialize(THREAD);
1601 
1602   // notify jvmti
1603   if (JvmtiExport::should_post_class_load()) {
1604       assert(THREAD->is_Java_thread(), "thread->is_Java_thread()");
1605       JvmtiExport::post_class_load((JavaThread *) THREAD, k);
1606 
1607   }
1608   post_class_define_event(k, loader_data);
1609 }
1610 
1611 // Support parallel classloading
1612 // All parallel class loaders, including bootstrap classloader
1613 // lock a placeholder entry for this class/class_loader pair
1614 // to allow parallel defines of different classes for this class loader
1615 // With AllowParallelDefine flag==true, in case they do not synchronize around
1616 // FindLoadedClass/DefineClass, calls, we check for parallel
1617 // loading for them, wait if a defineClass is in progress
1618 // and return the initial requestor's results
1619 // This flag does not apply to the bootstrap classloader.
1620 // With AllowParallelDefine flag==false, call through to define_instance_class
1621 // which will throw LinkageError: duplicate class definition.
1622 // False is the requested default.
1623 // For better performance, the class loaders should synchronize
1624 // findClass(), i.e. FindLoadedClass/DefineClassIfAbsent or they
1625 // potentially waste time reading and parsing the bytestream.
1626 // Note: VM callers should ensure consistency of k/class_name,class_loader
1627 // Be careful when modifying this code: once you have run
1628 // placeholders()->find_and_add(PlaceholderTable::DEFINE_CLASS),
1629 // you need to find_and_remove it before returning.
1630 // So be careful to not exit with a CHECK_ macro betweeen these calls.
1631 InstanceKlass* SystemDictionary::find_or_define_instance_class(Symbol* class_name, Handle class_loader,
1632                                                                InstanceKlass* k, TRAPS) {
1633 
1634   Symbol*  name_h = k->name(); // passed in class_name may be null
1635   ClassLoaderData* loader_data = class_loader_data(class_loader);
1636   Dictionary* dictionary = loader_data->dictionary();
1637 
1638   unsigned int d_hash = dictionary->compute_hash(name_h);
1639 
1640   // Hold SD lock around find_class and placeholder creation for DEFINE_CLASS
1641   unsigned int p_hash = placeholders()->compute_hash(name_h);
1642   int p_index = placeholders()->hash_to_index(p_hash);
1643   PlaceholderEntry* probe;
1644 
1645   {
1646     MutexLocker mu(SystemDictionary_lock, THREAD);
1647     // First check if class already defined
1648     if (is_parallelDefine(class_loader)) {
1649       InstanceKlass* check = find_class(d_hash, name_h, dictionary);
1650       if (check != NULL) {
1651         return check;
1652       }
1653     }
1654 
1655     // Acquire define token for this class/classloader
1656     probe = placeholders()->find_and_add(p_index, p_hash, name_h, loader_data, PlaceholderTable::DEFINE_CLASS, NULL, THREAD);
1657     // Wait if another thread defining in parallel
1658     // All threads wait - even those that will throw duplicate class: otherwise
1659     // caller is surprised by LinkageError: duplicate, but findLoadedClass fails
1660     // if other thread has not finished updating dictionary
1661     while (probe->definer() != NULL) {
1662       SystemDictionary_lock->wait();
1663     }
1664     // Only special cases allow parallel defines and can use other thread's results
1665     // Other cases fall through, and may run into duplicate defines
1666     // caught by finding an entry in the SystemDictionary
1667     if (is_parallelDefine(class_loader) && (probe->instance_klass() != NULL)) {
1668         placeholders()->find_and_remove(p_index, p_hash, name_h, loader_data, PlaceholderTable::DEFINE_CLASS, THREAD);
1669         SystemDictionary_lock->notify_all();
1670 #ifdef ASSERT
1671         InstanceKlass* check = find_class(d_hash, name_h, dictionary);
1672         assert(check != NULL, "definer missed recording success");
1673 #endif
1674         return probe->instance_klass();
1675     } else {
1676       // This thread will define the class (even if earlier thread tried and had an error)
1677       probe->set_definer(THREAD);
1678     }
1679   }
1680 
1681   define_instance_class(k, THREAD);
1682 
1683   Handle linkage_exception = Handle(); // null handle
1684 
1685   // definer must notify any waiting threads
1686   {
1687     MutexLocker mu(SystemDictionary_lock, THREAD);
1688     PlaceholderEntry* probe = placeholders()->get_entry(p_index, p_hash, name_h, loader_data);
1689     assert(probe != NULL, "DEFINE_CLASS placeholder lost?");
1690     if (probe != NULL) {
1691       if (HAS_PENDING_EXCEPTION) {
1692         linkage_exception = Handle(THREAD,PENDING_EXCEPTION);
1693         CLEAR_PENDING_EXCEPTION;
1694       } else {
1695         probe->set_instance_klass(k);
1696       }
1697       probe->set_definer(NULL);
1698       placeholders()->find_and_remove(p_index, p_hash, name_h, loader_data, PlaceholderTable::DEFINE_CLASS, THREAD);
1699       SystemDictionary_lock->notify_all();
1700     }
1701   }
1702 
1703   // Can't throw exception while holding lock due to rank ordering
1704   if (linkage_exception() != NULL) {
1705     THROW_OOP_(linkage_exception(), NULL); // throws exception and returns
1706   }
1707 
1708   return k;
1709 }
1710 
1711 Handle SystemDictionary::compute_loader_lock_object(Handle class_loader, TRAPS) {
1712   // If class_loader is NULL we synchronize on _system_loader_lock_obj
1713   if (class_loader.is_null()) {
1714     return Handle(THREAD, _system_loader_lock_obj);
1715   } else {
1716     return class_loader;
1717   }
1718 }
1719 
1720 // This method is added to check how often we have to wait to grab loader
1721 // lock. The results are being recorded in the performance counters defined in
1722 // ClassLoader::_sync_systemLoaderLockContentionRate and
1723 // ClassLoader::_sync_nonSystemLoaderLockConteionRate.
1724 void SystemDictionary::check_loader_lock_contention(Handle loader_lock, TRAPS) {
1725   if (!UsePerfData) {
1726     return;
1727   }
1728 
1729   assert(!loader_lock.is_null(), "NULL lock object");
1730 
1731   if (ObjectSynchronizer::query_lock_ownership((JavaThread*)THREAD, loader_lock)
1732       == ObjectSynchronizer::owner_other) {
1733     // contention will likely happen, so increment the corresponding
1734     // contention counter.
1735     if (oopDesc::equals(loader_lock(), _system_loader_lock_obj)) {
1736       ClassLoader::sync_systemLoaderLockContentionRate()->inc();
1737     } else {
1738       ClassLoader::sync_nonSystemLoaderLockContentionRate()->inc();
1739     }
1740   }
1741 }
1742 
1743 // ----------------------------------------------------------------------------
1744 // Lookup
1745 
1746 InstanceKlass* SystemDictionary::find_class(unsigned int hash,
1747                                             Symbol* class_name,
1748                                             Dictionary* dictionary) {
1749   assert_locked_or_safepoint(SystemDictionary_lock);
1750   int index = dictionary->hash_to_index(hash);
1751   return dictionary->find_class(index, hash, class_name);
1752 }
1753 
1754 
1755 // Basic find on classes in the midst of being loaded
1756 Symbol* SystemDictionary::find_placeholder(Symbol* class_name,
1757                                            ClassLoaderData* loader_data) {
1758   assert_locked_or_safepoint(SystemDictionary_lock);
1759   unsigned int p_hash = placeholders()->compute_hash(class_name);
1760   int p_index = placeholders()->hash_to_index(p_hash);
1761   return placeholders()->find_entry(p_index, p_hash, class_name, loader_data);
1762 }
1763 
1764 
1765 // Used for assertions and verification only
1766 // Precalculating the hash and index is an optimization because there are many lookups
1767 // before adding the class.
1768 InstanceKlass* SystemDictionary::find_class(Symbol* class_name, ClassLoaderData* loader_data) {
1769   assert_locked_or_safepoint(SystemDictionary_lock);
1770   #ifndef ASSERT
1771   guarantee(VerifyBeforeGC      ||
1772             VerifyDuringGC      ||
1773             VerifyBeforeExit    ||
1774             VerifyDuringStartup ||
1775             VerifyAfterGC, "too expensive");
1776   #endif
1777 
1778   Dictionary* dictionary = loader_data->dictionary();
1779   unsigned int d_hash = dictionary->compute_hash(class_name);
1780   return find_class(d_hash, class_name, dictionary);
1781 }
1782 
1783 
1784 // ----------------------------------------------------------------------------
1785 // Update hierachy. This is done before the new klass has been added to the SystemDictionary. The Recompile_lock
1786 // is held, to ensure that the compiler is not using the class hierachy, and that deoptimization will kick in
1787 // before a new class is used.
1788 
1789 void SystemDictionary::add_to_hierarchy(InstanceKlass* k, TRAPS) {
1790   assert(k != NULL, "just checking");
1791   assert_locked_or_safepoint(Compile_lock);
1792 
1793   k->set_init_state(InstanceKlass::loaded);
1794   // make sure init_state store is already done.
1795   // The compiler reads the hierarchy outside of the Compile_lock.
1796   // Access ordering is used to add to hierarchy.
1797 
1798   // Link into hierachy.
1799   k->append_to_sibling_list();                    // add to superklass/sibling list
1800   k->process_interfaces(THREAD);                  // handle all "implements" declarations
1801 
1802   // Now flush all code that depended on old class hierarchy.
1803   // Note: must be done *after* linking k into the hierarchy (was bug 12/9/97)
1804   CodeCache::flush_dependents_on(k);
1805 }
1806 
1807 // ----------------------------------------------------------------------------
1808 // GC support
1809 
1810 // Assumes classes in the SystemDictionary are only unloaded at a safepoint
1811 // Note: anonymous classes are not in the SD.
1812 bool SystemDictionary::do_unloading(GCTimer* gc_timer) {
1813 
1814   bool unloading_occurred;
1815   bool is_concurrent = !SafepointSynchronize::is_at_safepoint();
1816   {
1817     GCTraceTime(Debug, gc, phases) t("ClassLoaderData", gc_timer);
1818     assert_locked_or_safepoint(ClassLoaderDataGraph_lock);  // caller locks.
1819     // First, mark for unload all ClassLoaderData referencing a dead class loader.
1820     unloading_occurred = ClassLoaderDataGraph::do_unloading();
1821     if (unloading_occurred) {
1822       MutexLocker ml2(is_concurrent ? Module_lock : NULL);
1823       JFR_ONLY(Jfr::on_unloading_classes();)
1824 
1825       MutexLocker ml1(is_concurrent ? SystemDictionary_lock : NULL);
1826       ClassLoaderDataGraph::clean_module_and_package_info();
1827       constraints()->purge_loader_constraints();
1828       resolution_errors()->purge_resolution_errors();
1829     }
1830   }
1831 
1832   GCTraceTime(Debug, gc, phases) t("Trigger cleanups", gc_timer);
1833 
1834   if (unloading_occurred) {
1835     SymbolTable::trigger_cleanup();
1836 
1837     // Oops referenced by the protection domain cache table may get unreachable independently
1838     // of the class loader (eg. cached protection domain oops). So we need to
1839     // explicitly unlink them here.
1840     // All protection domain oops are linked to the caller class, so if nothing
1841     // unloads, this is not needed.
1842     _pd_cache_table->trigger_cleanup();
1843   }
1844 
1845   return unloading_occurred;
1846 }
1847 
1848 void SystemDictionary::oops_do(OopClosure* f, bool include_handles) {
1849   f->do_oop(&_java_system_loader);
1850   f->do_oop(&_java_platform_loader);
1851   f->do_oop(&_system_loader_lock_obj);
1852   CDS_ONLY(SystemDictionaryShared::oops_do(f);)
1853 
1854   // Visit extra methods
1855   invoke_method_table()->oops_do(f);
1856 
1857   if (include_handles) {
1858     vm_global_oop_storage()->oops_do(f);
1859   }
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   _loader_constraints  = new LoaderConstraintTable(_loader_constraint_size);
1884   _resolution_errors   = new ResolutionErrorTable(_resolution_error_size);
1885   _invoke_method_table = new SymbolPropertyTable(_invoke_method_size);
1886   _pd_cache_table = new ProtectionDomainCacheTable(defaultProtectionDomainCacheSize);
1887 
1888   // Allocate private object used as system class loader lock
1889   _system_loader_lock_obj = oopFactory::new_intArray(0, CHECK);
1890   // Initialize basic classes
1891   resolve_well_known_classes(CHECK);
1892 }
1893 
1894 // Compact table of directions on the initialization of klasses:
1895 static const short wk_init_info[] = {
1896   #define WK_KLASS_INIT_INFO(name, symbol) \
1897     ((short)vmSymbols::VM_SYMBOL_ENUM_NAME(symbol)),
1898 
1899   WK_KLASSES_DO(WK_KLASS_INIT_INFO)
1900   #undef WK_KLASS_INIT_INFO
1901   0
1902 };
1903 
1904 #ifdef ASSERT
1905 bool SystemDictionary::is_well_known_klass(Symbol* class_name) {
1906   int sid;
1907   for (int i = 0; (sid = wk_init_info[i]) != 0; i++) {
1908     Symbol* symbol = vmSymbols::symbol_at((vmSymbols::SID)sid);
1909     if (class_name == symbol) {
1910       return true;
1911     }
1912   }
1913   return false;
1914 }
1915 #endif
1916 
1917 bool SystemDictionary::resolve_wk_klass(WKID id, TRAPS) {
1918   assert(id >= (int)FIRST_WKID && id < (int)WKID_LIMIT, "oob");
1919   int sid = wk_init_info[id - FIRST_WKID];
1920   Symbol* symbol = vmSymbols::symbol_at((vmSymbols::SID)sid);
1921   InstanceKlass** klassp = &_well_known_klasses[id];
1922 
1923   if ((*klassp) == NULL) {
1924     Klass* k = resolve_or_fail(symbol, true, CHECK_0);
1925     (*klassp) = InstanceKlass::cast(k);
1926   }
1927   return ((*klassp) != NULL);
1928 }
1929 
1930 void SystemDictionary::resolve_wk_klasses_until(WKID limit_id, WKID &start_id, TRAPS) {
1931   assert((int)start_id <= (int)limit_id, "IDs are out of order!");
1932   for (int id = (int)start_id; id < (int)limit_id; id++) {
1933     assert(id >= (int)FIRST_WKID && id < (int)WKID_LIMIT, "oob");
1934     resolve_wk_klass((WKID)id, CHECK);
1935   }
1936 
1937   // move the starting value forward to the limit:
1938   start_id = limit_id;
1939 }
1940 
1941 void SystemDictionary::resolve_well_known_classes(TRAPS) {
1942   assert(WK_KLASS(Object_klass) == NULL, "well-known classes should only be initialized once");
1943 
1944   // Create the ModuleEntry for java.base.  This call needs to be done here,
1945   // after vmSymbols::initialize() is called but before any classes are pre-loaded.
1946   ClassLoader::classLoader_init2(CHECK);
1947 
1948   // Preload commonly used klasses
1949   WKID scan = FIRST_WKID;
1950   // first do Object, then String, Class
1951 #if INCLUDE_CDS
1952   if (UseSharedSpaces) {
1953     resolve_wk_klasses_through(WK_KLASS_ENUM_NAME(Object_klass), scan, CHECK);
1954 
1955     // It's unsafe to access the archived heap regions before they
1956     // are fixed up, so we must do the fixup as early as possible
1957     // before the archived java objects are accessed by functions
1958     // such as java_lang_Class::restore_archived_mirror and
1959     // ConstantPool::restore_unshareable_info (restores the archived
1960     // resolved_references array object).
1961     //
1962     // HeapShared::fixup_mapped_heap_regions() fills the empty
1963     // spaces in the archived heap regions and may use
1964     // SystemDictionary::Object_klass(), so we can do this only after
1965     // Object_klass is resolved. See the above resolve_wk_klasses_through()
1966     // call. No mirror objects are accessed/restored in the above call.
1967     // Mirrors are restored after java.lang.Class is loaded.
1968     HeapShared::fixup_mapped_heap_regions();
1969 
1970     // Initialize the constant pool for the Object_class
1971     assert(Object_klass()->is_shared(), "must be");
1972     Object_klass()->constants()->restore_unshareable_info(CHECK);
1973     resolve_wk_klasses_through(WK_KLASS_ENUM_NAME(Class_klass), scan, CHECK);
1974   } else
1975 #endif
1976   {
1977     resolve_wk_klasses_through(WK_KLASS_ENUM_NAME(Class_klass), scan, CHECK);
1978   }
1979 
1980   // Calculate offsets for String and Class classes since they are loaded and
1981   // can be used after this point.
1982   java_lang_String::compute_offsets();
1983   java_lang_Class::compute_offsets();
1984 
1985   // Fixup mirrors for classes loaded before java.lang.Class.
1986   // These calls iterate over the objects currently in the perm gen
1987   // so calling them at this point is matters (not before when there
1988   // are fewer objects and not later after there are more objects
1989   // in the perm gen.
1990   Universe::initialize_basic_type_mirrors(CHECK);
1991   Universe::fixup_mirrors(CHECK);
1992 
1993   // do a bunch more:
1994   resolve_wk_klasses_through(WK_KLASS_ENUM_NAME(Reference_klass), scan, CHECK);
1995 
1996   // Preload ref klasses and set reference types
1997   InstanceKlass::cast(WK_KLASS(Reference_klass))->set_reference_type(REF_OTHER);
1998   InstanceRefKlass::update_nonstatic_oop_maps(WK_KLASS(Reference_klass));
1999 
2000   resolve_wk_klasses_through(WK_KLASS_ENUM_NAME(PhantomReference_klass), scan, CHECK);
2001   InstanceKlass::cast(WK_KLASS(SoftReference_klass))->set_reference_type(REF_SOFT);
2002   InstanceKlass::cast(WK_KLASS(WeakReference_klass))->set_reference_type(REF_WEAK);
2003   InstanceKlass::cast(WK_KLASS(FinalReference_klass))->set_reference_type(REF_FINAL);
2004   InstanceKlass::cast(WK_KLASS(PhantomReference_klass))->set_reference_type(REF_PHANTOM);
2005 
2006   // JSR 292 classes
2007   WKID jsr292_group_start = WK_KLASS_ENUM_NAME(MethodHandle_klass);
2008   WKID jsr292_group_end   = WK_KLASS_ENUM_NAME(VolatileCallSite_klass);
2009   resolve_wk_klasses_until(jsr292_group_start, scan, CHECK);
2010   resolve_wk_klasses_through(jsr292_group_end, scan, CHECK);
2011   WKID last = WKID_LIMIT;
2012   resolve_wk_klasses_until(last, scan, CHECK);
2013 
2014   _box_klasses[T_BOOLEAN] = WK_KLASS(Boolean_klass);
2015   _box_klasses[T_CHAR]    = WK_KLASS(Character_klass);
2016   _box_klasses[T_FLOAT]   = WK_KLASS(Float_klass);
2017   _box_klasses[T_DOUBLE]  = WK_KLASS(Double_klass);
2018   _box_klasses[T_BYTE]    = WK_KLASS(Byte_klass);
2019   _box_klasses[T_SHORT]   = WK_KLASS(Short_klass);
2020   _box_klasses[T_INT]     = WK_KLASS(Integer_klass);
2021   _box_klasses[T_LONG]    = WK_KLASS(Long_klass);
2022   //_box_klasses[T_OBJECT]  = WK_KLASS(object_klass);
2023   //_box_klasses[T_ARRAY]   = WK_KLASS(object_klass);
2024 
2025   { // Compute whether we should use checkPackageAccess or NOT
2026     Method* method = InstanceKlass::cast(ClassLoader_klass())->find_method(vmSymbols::checkPackageAccess_name(), vmSymbols::class_protectiondomain_signature());
2027     _has_checkPackageAccess = (method != NULL);
2028   }
2029 
2030 #ifdef ASSERT
2031   if (UseSharedSpaces) {
2032     assert(JvmtiExport::is_early_phase(),
2033            "All well known classes must be resolved in JVMTI early phase");
2034     for (int i = FIRST_WKID; i < last; i++) {
2035       InstanceKlass* k = _well_known_klasses[i];
2036       assert(k->is_shared(), "must not be replaced by JVMTI class file load hook");
2037     }
2038   }
2039 #endif
2040 }
2041 
2042 // Tells if a given klass is a box (wrapper class, such as java.lang.Integer).
2043 // If so, returns the basic type it holds.  If not, returns T_OBJECT.
2044 BasicType SystemDictionary::box_klass_type(Klass* k) {
2045   assert(k != NULL, "");
2046   for (int i = T_BOOLEAN; i < T_VOID+1; i++) {
2047     if (_box_klasses[i] == k)
2048       return (BasicType)i;
2049   }
2050   return T_OBJECT;
2051 }
2052 
2053 // Constraints on class loaders. The details of the algorithm can be
2054 // found in the OOPSLA'98 paper "Dynamic Class Loading in the Java
2055 // Virtual Machine" by Sheng Liang and Gilad Bracha.  The basic idea is
2056 // that the dictionary needs to maintain a set of contraints that
2057 // must be satisfied by all classes in the dictionary.
2058 // if defining is true, then LinkageError if already in dictionary
2059 // if initiating loader, then ok if InstanceKlass matches existing entry
2060 
2061 void SystemDictionary::check_constraints(unsigned int d_hash,
2062                                          InstanceKlass* k,
2063                                          Handle class_loader,
2064                                          bool defining,
2065                                          TRAPS) {
2066   ResourceMark rm(THREAD);
2067   stringStream ss;
2068   bool throwException = false;
2069 
2070   {
2071     Symbol *name = k->name();
2072     ClassLoaderData *loader_data = class_loader_data(class_loader);
2073 
2074     MutexLocker mu(SystemDictionary_lock, THREAD);
2075 
2076     InstanceKlass* check = find_class(d_hash, name, loader_data->dictionary());
2077     if (check != NULL) {
2078       // If different InstanceKlass - duplicate class definition,
2079       // else - ok, class loaded by a different thread in parallel.
2080       // We should only have found it if it was done loading and ok to use.
2081       // The dictionary only holds instance classes, placeholders
2082       // also hold array classes.
2083 
2084       assert(check->is_instance_klass(), "noninstance in systemdictionary");
2085       if ((defining == true) || (k != check)) {
2086         throwException = true;
2087         ss.print("loader %s", loader_data->loader_name_and_id());
2088         ss.print(" attempted duplicate %s definition for %s. (%s)",
2089                  k->external_kind(), k->external_name(), k->class_in_module_of_loader(false, true));
2090       } else {
2091         return;
2092       }
2093     }
2094 
2095 #ifdef ASSERT
2096     Symbol* ph_check = find_placeholder(name, loader_data);
2097     assert(ph_check == NULL || ph_check == name, "invalid symbol");
2098 #endif
2099 
2100     if (throwException == false) {
2101       if (constraints()->check_or_update(k, class_loader, name) == false) {
2102         throwException = true;
2103         ss.print("loader constraint violation: loader %s", loader_data->loader_name_and_id());
2104         ss.print(" wants to load %s %s.",
2105                  k->external_kind(), k->external_name());
2106         Klass *existing_klass = constraints()->find_constrained_klass(name, class_loader);
2107         if (existing_klass != NULL && existing_klass->class_loader() != class_loader()) {
2108           ss.print(" A different %s with the same name was previously loaded by %s. (%s)",
2109                    existing_klass->external_kind(),
2110                    existing_klass->class_loader_data()->loader_name_and_id(),
2111                    existing_klass->class_in_module_of_loader(false, true));
2112         } else {
2113           ss.print(" (%s)", k->class_in_module_of_loader(false, true));
2114         }
2115       }
2116     }
2117   }
2118 
2119   // Throw error now if needed (cannot throw while holding
2120   // SystemDictionary_lock because of rank ordering)
2121   if (throwException == true) {
2122     THROW_MSG(vmSymbols::java_lang_LinkageError(), ss.as_string());
2123   }
2124 }
2125 
2126 // Update class loader data dictionary - done after check_constraint and add_to_hierachy
2127 // have been called.
2128 void SystemDictionary::update_dictionary(unsigned int d_hash,
2129                                          int p_index, unsigned int p_hash,
2130                                          InstanceKlass* k,
2131                                          Handle class_loader,
2132                                          TRAPS) {
2133   // Compile_lock prevents systemDictionary updates during compilations
2134   assert_locked_or_safepoint(Compile_lock);
2135   Symbol*  name  = k->name();
2136   ClassLoaderData *loader_data = class_loader_data(class_loader);
2137 
2138   {
2139     MutexLocker mu1(SystemDictionary_lock, THREAD);
2140 
2141     // See whether biased locking is enabled and if so set it for this
2142     // klass.
2143     // Note that this must be done past the last potential blocking
2144     // point / safepoint. We might enable biased locking lazily using a
2145     // VM_Operation to iterate the SystemDictionary and installing the
2146     // biasable mark word into each InstanceKlass's prototype header.
2147     // To avoid race conditions where we accidentally miss enabling the
2148     // optimization for one class in the process of being added to the
2149     // dictionary, we must not safepoint after the test of
2150     // BiasedLocking::enabled().
2151     if (UseBiasedLocking && BiasedLocking::enabled()) {
2152       // Set biased locking bit for all loaded classes; it will be
2153       // cleared if revocation occurs too often for this type
2154       // NOTE that we must only do this when the class is initally
2155       // defined, not each time it is referenced from a new class loader
2156       if (oopDesc::equals(k->class_loader(), class_loader())) {
2157         k->set_prototype_header(markOopDesc::biased_locking_prototype());
2158       }
2159     }
2160 
2161     // Make a new dictionary entry.
2162     Dictionary* dictionary = loader_data->dictionary();
2163     InstanceKlass* sd_check = find_class(d_hash, name, dictionary);
2164     if (sd_check == NULL) {
2165       dictionary->add_klass(d_hash, name, k);
2166     }
2167   #ifdef ASSERT
2168     sd_check = find_class(d_hash, name, dictionary);
2169     assert (sd_check != NULL, "should have entry in dictionary");
2170     // Note: there may be a placeholder entry: for circularity testing
2171     // or for parallel defines
2172   #endif
2173     SystemDictionary_lock->notify_all();
2174   }
2175 }
2176 
2177 
2178 // Try to find a class name using the loader constraints.  The
2179 // loader constraints might know about a class that isn't fully loaded
2180 // yet and these will be ignored.
2181 Klass* SystemDictionary::find_constrained_instance_or_array_klass(
2182                     Symbol* class_name, Handle class_loader, TRAPS) {
2183 
2184   // First see if it has been loaded directly.
2185   // Force the protection domain to be null.  (This removes protection checks.)
2186   Handle no_protection_domain;
2187   Klass* klass = find_instance_or_array_klass(class_name, class_loader,
2188                                               no_protection_domain, CHECK_NULL);
2189   if (klass != NULL)
2190     return klass;
2191 
2192   // Now look to see if it has been loaded elsewhere, and is subject to
2193   // a loader constraint that would require this loader to return the
2194   // klass that is already loaded.
2195   if (FieldType::is_array(class_name)) {
2196     // For array classes, their Klass*s are not kept in the
2197     // constraint table. The element Klass*s are.
2198     FieldArrayInfo fd;
2199     BasicType t = FieldType::get_array_info(class_name, fd, CHECK_(NULL));
2200     if (t != T_OBJECT) {
2201       klass = Universe::typeArrayKlassObj(t);
2202     } else {
2203       MutexLocker mu(SystemDictionary_lock, THREAD);
2204       klass = constraints()->find_constrained_klass(fd.object_key(), class_loader);
2205     }
2206     // If element class already loaded, allocate array klass
2207     if (klass != NULL) {
2208       klass = klass->array_klass_or_null(fd.dimension());
2209     }
2210   } else {
2211     MutexLocker mu(SystemDictionary_lock, THREAD);
2212     // Non-array classes are easy: simply check the constraint table.
2213     klass = constraints()->find_constrained_klass(class_name, class_loader);
2214   }
2215 
2216   return klass;
2217 }
2218 
2219 
2220 bool SystemDictionary::add_loader_constraint(Symbol* class_name,
2221                                              Handle class_loader1,
2222                                              Handle class_loader2,
2223                                              Thread* THREAD) {
2224   ClassLoaderData* loader_data1 = class_loader_data(class_loader1);
2225   ClassLoaderData* loader_data2 = class_loader_data(class_loader2);
2226 
2227   Symbol* constraint_name = NULL;
2228   // Needs to be in same scope as constraint_name in case a Symbol is created and
2229   // assigned to constraint_name.
2230   FieldArrayInfo fd;
2231   if (!FieldType::is_array(class_name)) {
2232     constraint_name = class_name;
2233   } else {
2234     // For array classes, their Klass*s are not kept in the
2235     // constraint table. The element classes are.
2236     BasicType t = FieldType::get_array_info(class_name, fd, CHECK_(false));
2237     // primitive types always pass
2238     if (t != T_OBJECT) {
2239       return true;
2240     } else {
2241       constraint_name = fd.object_key();
2242     }
2243   }
2244 
2245   Dictionary* dictionary1 = loader_data1->dictionary();
2246   unsigned int d_hash1 = dictionary1->compute_hash(constraint_name);
2247 
2248   Dictionary* dictionary2 = loader_data2->dictionary();
2249   unsigned int d_hash2 = dictionary2->compute_hash(constraint_name);
2250 
2251   {
2252     MutexLocker mu_s(SystemDictionary_lock, THREAD);
2253     InstanceKlass* klass1 = find_class(d_hash1, constraint_name, dictionary1);
2254     InstanceKlass* klass2 = find_class(d_hash2, constraint_name, dictionary2);
2255     return constraints()->add_entry(constraint_name, klass1, class_loader1,
2256                                     klass2, class_loader2);
2257   }
2258 }
2259 
2260 // Add entry to resolution error table to record the error when the first
2261 // attempt to resolve a reference to a class has failed.
2262 void SystemDictionary::add_resolution_error(const constantPoolHandle& pool, int which,
2263                                             Symbol* error, Symbol* message) {
2264   unsigned int hash = resolution_errors()->compute_hash(pool, which);
2265   int index = resolution_errors()->hash_to_index(hash);
2266   {
2267     MutexLocker ml(SystemDictionary_lock, Thread::current());
2268     resolution_errors()->add_entry(index, hash, pool, which, error, message);
2269   }
2270 }
2271 
2272 // Delete a resolution error for RedefineClasses for a constant pool is going away
2273 void SystemDictionary::delete_resolution_error(ConstantPool* pool) {
2274   resolution_errors()->delete_entry(pool);
2275 }
2276 
2277 // Lookup resolution error table. Returns error if found, otherwise NULL.
2278 Symbol* SystemDictionary::find_resolution_error(const constantPoolHandle& pool, int which,
2279                                                 Symbol** message) {
2280   unsigned int hash = resolution_errors()->compute_hash(pool, which);
2281   int index = resolution_errors()->hash_to_index(hash);
2282   {
2283     MutexLocker ml(SystemDictionary_lock, Thread::current());
2284     ResolutionErrorEntry* entry = resolution_errors()->find_entry(index, hash, pool, which);
2285     if (entry != NULL) {
2286       *message = entry->message();
2287       return entry->error();
2288     } else {
2289       return NULL;
2290     }
2291   }
2292 }
2293 
2294 
2295 // Signature constraints ensure that callers and callees agree about
2296 // the meaning of type names in their signatures.  This routine is the
2297 // intake for constraints.  It collects them from several places:
2298 //
2299 //  * LinkResolver::resolve_method (if check_access is true) requires
2300 //    that the resolving class (the caller) and the defining class of
2301 //    the resolved method (the callee) agree on each type in the
2302 //    method's signature.
2303 //
2304 //  * LinkResolver::resolve_interface_method performs exactly the same
2305 //    checks.
2306 //
2307 //  * LinkResolver::resolve_field requires that the constant pool
2308 //    attempting to link to a field agree with the field's defining
2309 //    class about the type of the field signature.
2310 //
2311 //  * klassVtable::initialize_vtable requires that, when a class
2312 //    overrides a vtable entry allocated by a superclass, that the
2313 //    overriding method (i.e., the callee) agree with the superclass
2314 //    on each type in the method's signature.
2315 //
2316 //  * klassItable::initialize_itable requires that, when a class fills
2317 //    in its itables, for each non-abstract method installed in an
2318 //    itable, the method (i.e., the callee) agree with the interface
2319 //    on each type in the method's signature.
2320 //
2321 // All those methods have a boolean (check_access, checkconstraints)
2322 // which turns off the checks.  This is used from specialized contexts
2323 // such as bootstrapping, dumping, and debugging.
2324 //
2325 // No direct constraint is placed between the class and its
2326 // supertypes.  Constraints are only placed along linked relations
2327 // between callers and callees.  When a method overrides or implements
2328 // an abstract method in a supertype (superclass or interface), the
2329 // constraints are placed as if the supertype were the caller to the
2330 // overriding method.  (This works well, since callers to the
2331 // supertype have already established agreement between themselves and
2332 // the supertype.)  As a result of all this, a class can disagree with
2333 // its supertype about the meaning of a type name, as long as that
2334 // class neither calls a relevant method of the supertype, nor is
2335 // called (perhaps via an override) from the supertype.
2336 //
2337 //
2338 // SystemDictionary::check_signature_loaders(sig, l1, l2)
2339 //
2340 // Make sure all class components (including arrays) in the given
2341 // signature will be resolved to the same class in both loaders.
2342 // Returns the name of the type that failed a loader constraint check, or
2343 // NULL if no constraint failed.  No exception except OOME is thrown.
2344 // Arrays are not added to the loader constraint table, their elements are.
2345 Symbol* SystemDictionary::check_signature_loaders(Symbol* signature,
2346                                                Handle loader1, Handle loader2,
2347                                                bool is_method, TRAPS)  {
2348   // Nothing to do if loaders are the same.
2349   if (oopDesc::equals(loader1(), loader2())) {
2350     return NULL;
2351   }
2352 
2353   SignatureStream sig_strm(signature, is_method);
2354   while (!sig_strm.is_done()) {
2355     if (sig_strm.is_object()) {
2356       Symbol* sig = sig_strm.as_symbol();
2357       if (!add_loader_constraint(sig, loader1, loader2, THREAD)) {
2358         return sig;
2359       }
2360     }
2361     sig_strm.next();
2362   }
2363   return NULL;
2364 }
2365 
2366 
2367 methodHandle SystemDictionary::find_method_handle_intrinsic(vmIntrinsics::ID iid,
2368                                                             Symbol* signature,
2369                                                             TRAPS) {
2370   methodHandle empty;
2371   assert(MethodHandles::is_signature_polymorphic(iid) &&
2372          MethodHandles::is_signature_polymorphic_intrinsic(iid) &&
2373          iid != vmIntrinsics::_invokeGeneric,
2374          "must be a known MH intrinsic iid=%d: %s", iid, vmIntrinsics::name_at(iid));
2375 
2376   unsigned int hash  = invoke_method_table()->compute_hash(signature, iid);
2377   int          index = invoke_method_table()->hash_to_index(hash);
2378   SymbolPropertyEntry* spe = invoke_method_table()->find_entry(index, hash, signature, iid);
2379   methodHandle m;
2380   if (spe == NULL || spe->method() == NULL) {
2381     spe = NULL;
2382     // Must create lots of stuff here, but outside of the SystemDictionary lock.
2383     m = Method::make_method_handle_intrinsic(iid, signature, CHECK_(empty));
2384     if (!Arguments::is_interpreter_only()) {
2385       // Generate a compiled form of the MH intrinsic.
2386       AdapterHandlerLibrary::create_native_wrapper(m);
2387       // Check if have the compiled code.
2388       if (!m->has_compiled_code()) {
2389         THROW_MSG_(vmSymbols::java_lang_VirtualMachineError(),
2390                    "Out of space in CodeCache for method handle intrinsic", empty);
2391       }
2392     }
2393     // Now grab the lock.  We might have to throw away the new method,
2394     // if a racing thread has managed to install one at the same time.
2395     {
2396       MutexLocker ml(SystemDictionary_lock, THREAD);
2397       spe = invoke_method_table()->find_entry(index, hash, signature, iid);
2398       if (spe == NULL)
2399         spe = invoke_method_table()->add_entry(index, hash, signature, iid);
2400       if (spe->method() == NULL)
2401         spe->set_method(m());
2402     }
2403   }
2404 
2405   assert(spe != NULL && spe->method() != NULL, "");
2406   assert(Arguments::is_interpreter_only() || (spe->method()->has_compiled_code() &&
2407          spe->method()->code()->entry_point() == spe->method()->from_compiled_entry()),
2408          "MH intrinsic invariant");
2409   return spe->method();
2410 }
2411 
2412 // Helper for unpacking the return value from linkMethod and linkCallSite.
2413 static methodHandle unpack_method_and_appendix(Handle mname,
2414                                                Klass* accessing_klass,
2415                                                objArrayHandle appendix_box,
2416                                                Handle* appendix_result,
2417                                                TRAPS) {
2418   methodHandle empty;
2419   if (mname.not_null()) {
2420     Method* m = java_lang_invoke_MemberName::vmtarget(mname());
2421     if (m != NULL) {
2422       oop appendix = appendix_box->obj_at(0);
2423       if (TraceMethodHandles) {
2424     #ifndef PRODUCT
2425         ttyLocker ttyl;
2426         tty->print("Linked method=" INTPTR_FORMAT ": ", p2i(m));
2427         m->print();
2428         if (appendix != NULL) { tty->print("appendix = "); appendix->print(); }
2429         tty->cr();
2430     #endif //PRODUCT
2431       }
2432       (*appendix_result) = Handle(THREAD, appendix);
2433       // the target is stored in the cpCache and if a reference to this
2434       // MemberName is dropped we need a way to make sure the
2435       // class_loader containing this method is kept alive.
2436       ClassLoaderData* this_key = accessing_klass->class_loader_data();
2437       this_key->record_dependency(m->method_holder());
2438       return methodHandle(THREAD, m);
2439     }
2440   }
2441   THROW_MSG_(vmSymbols::java_lang_LinkageError(), "bad value from MethodHandleNatives", empty);
2442   return empty;
2443 }
2444 
2445 methodHandle SystemDictionary::find_method_handle_invoker(Klass* klass,
2446                                                           Symbol* name,
2447                                                           Symbol* signature,
2448                                                           Klass* accessing_klass,
2449                                                           Handle *appendix_result,
2450                                                           TRAPS) {
2451   methodHandle empty;
2452   assert(THREAD->can_call_java() ,"");
2453   Handle method_type =
2454     SystemDictionary::find_method_handle_type(signature, accessing_klass, CHECK_(empty));
2455 
2456   int ref_kind = JVM_REF_invokeVirtual;
2457   oop name_oop = StringTable::intern(name, CHECK_(empty));
2458   Handle name_str (THREAD, name_oop);
2459   objArrayHandle appendix_box = oopFactory::new_objArray_handle(SystemDictionary::Object_klass(), 1, CHECK_(empty));
2460   assert(appendix_box->obj_at(0) == NULL, "");
2461 
2462   // This should not happen.  JDK code should take care of that.
2463   if (accessing_klass == NULL || method_type.is_null()) {
2464     THROW_MSG_(vmSymbols::java_lang_InternalError(), "bad invokehandle", empty);
2465   }
2466 
2467   // call java.lang.invoke.MethodHandleNatives::linkMethod(... String, MethodType) -> MemberName
2468   JavaCallArguments args;
2469   args.push_oop(Handle(THREAD, accessing_klass->java_mirror()));
2470   args.push_int(ref_kind);
2471   args.push_oop(Handle(THREAD, klass->java_mirror()));
2472   args.push_oop(name_str);
2473   args.push_oop(method_type);
2474   args.push_oop(appendix_box);
2475   JavaValue result(T_OBJECT);
2476   JavaCalls::call_static(&result,
2477                          SystemDictionary::MethodHandleNatives_klass(),
2478                          vmSymbols::linkMethod_name(),
2479                          vmSymbols::linkMethod_signature(),
2480                          &args, CHECK_(empty));
2481   Handle mname(THREAD, (oop) result.get_jobject());
2482   return unpack_method_and_appendix(mname, accessing_klass, appendix_box, appendix_result, THREAD);
2483 }
2484 
2485 // Decide if we can globally cache a lookup of this class, to be returned to any client that asks.
2486 // We must ensure that all class loaders everywhere will reach this class, for any client.
2487 // This is a safe bet for public classes in java.lang, such as Object and String.
2488 // We also include public classes in java.lang.invoke, because they appear frequently in system-level method types.
2489 // Out of an abundance of caution, we do not include any other classes, not even for packages like java.util.
2490 static bool is_always_visible_class(oop mirror) {
2491   Klass* klass = java_lang_Class::as_Klass(mirror);
2492   if (klass->is_objArray_klass()) {
2493     klass = ObjArrayKlass::cast(klass)->bottom_klass(); // check element type
2494   }
2495   if (klass->is_typeArray_klass()) {
2496     return true; // primitive array
2497   }
2498   assert(klass->is_instance_klass(), "%s", klass->external_name());
2499   return klass->is_public() &&
2500          (InstanceKlass::cast(klass)->is_same_class_package(SystemDictionary::Object_klass()) ||       // java.lang
2501           InstanceKlass::cast(klass)->is_same_class_package(SystemDictionary::MethodHandle_klass()));  // java.lang.invoke
2502 }
2503 
2504 
2505 // Return the Java mirror (java.lang.Class instance) for a single-character
2506 // descriptor.  This result, when available, is the same as produced by the
2507 // heavier API point of the same name that takes a Symbol.
2508 oop SystemDictionary::find_java_mirror_for_type(char signature_char) {
2509   return java_lang_Class::primitive_mirror(char2type(signature_char));
2510 }
2511 
2512 // Find or construct the Java mirror (java.lang.Class instance) for a
2513 // for the given field type signature, as interpreted relative to the
2514 // given class loader.  Handles primitives, void, references, arrays,
2515 // and all other reflectable types, except method types.
2516 // N.B.  Code in reflection should use this entry point.
2517 Handle SystemDictionary::find_java_mirror_for_type(Symbol* signature,
2518                                                    Klass* accessing_klass,
2519                                                    Handle class_loader,
2520                                                    Handle protection_domain,
2521                                                    SignatureStream::FailureMode failure_mode,
2522                                                    TRAPS) {
2523   Handle empty;
2524 
2525   assert(accessing_klass == NULL || (class_loader.is_null() && protection_domain.is_null()),
2526          "one or the other, or perhaps neither");
2527 
2528   Symbol* type = signature;
2529 
2530   // What we have here must be a valid field descriptor,
2531   // and all valid field descriptors are supported.
2532   // Produce the same java.lang.Class that reflection reports.
2533   if (type->utf8_length() == 1) {
2534 
2535     // It's a primitive.  (Void has a primitive mirror too.)
2536     char ch = type->char_at(0);
2537     assert(is_java_primitive(char2type(ch)) || ch == 'V', "");
2538     return Handle(THREAD, find_java_mirror_for_type(ch));
2539 
2540   } else if (FieldType::is_obj(type) || FieldType::is_array(type)) {
2541 
2542     // It's a reference type.
2543     if (accessing_klass != NULL) {
2544       class_loader      = Handle(THREAD, accessing_klass->class_loader());
2545       protection_domain = Handle(THREAD, accessing_klass->protection_domain());
2546     }
2547     Klass* constant_type_klass;
2548     if (failure_mode == SignatureStream::ReturnNull) {
2549       constant_type_klass = resolve_or_null(type, class_loader, protection_domain,
2550                                             CHECK_(empty));
2551     } else {
2552       bool throw_error = (failure_mode == SignatureStream::NCDFError);
2553       constant_type_klass = resolve_or_fail(type, class_loader, protection_domain,
2554                                             throw_error, CHECK_(empty));
2555     }
2556     if (constant_type_klass == NULL) {
2557       return Handle();  // report failure this way
2558     }
2559     Handle mirror(THREAD, constant_type_klass->java_mirror());
2560 
2561     // Check accessibility, emulating ConstantPool::verify_constant_pool_resolve.
2562     if (accessing_klass != NULL) {
2563       Klass* sel_klass = constant_type_klass;
2564       bool fold_type_to_class = true;
2565       LinkResolver::check_klass_accessability(accessing_klass, sel_klass,
2566                                               fold_type_to_class, CHECK_(empty));
2567     }
2568 
2569     return mirror;
2570 
2571   }
2572 
2573   // Fall through to an error.
2574   assert(false, "unsupported mirror syntax");
2575   THROW_MSG_(vmSymbols::java_lang_InternalError(), "unsupported mirror syntax", empty);
2576 }
2577 
2578 
2579 // Ask Java code to find or construct a java.lang.invoke.MethodType for the given
2580 // signature, as interpreted relative to the given class loader.
2581 // Because of class loader constraints, all method handle usage must be
2582 // consistent with this loader.
2583 Handle SystemDictionary::find_method_handle_type(Symbol* signature,
2584                                                  Klass* accessing_klass,
2585                                                  TRAPS) {
2586   Handle empty;
2587   vmIntrinsics::ID null_iid = vmIntrinsics::_none;  // distinct from all method handle invoker intrinsics
2588   unsigned int hash  = invoke_method_table()->compute_hash(signature, null_iid);
2589   int          index = invoke_method_table()->hash_to_index(hash);
2590   SymbolPropertyEntry* spe = invoke_method_table()->find_entry(index, hash, signature, null_iid);
2591   if (spe != NULL && spe->method_type() != NULL) {
2592     assert(java_lang_invoke_MethodType::is_instance(spe->method_type()), "");
2593     return Handle(THREAD, spe->method_type());
2594   } else if (!THREAD->can_call_java()) {
2595     warning("SystemDictionary::find_method_handle_type called from compiler thread");  // FIXME
2596     return Handle();  // do not attempt from within compiler, unless it was cached
2597   }
2598 
2599   Handle class_loader, protection_domain;
2600   if (accessing_klass != NULL) {
2601     class_loader      = Handle(THREAD, accessing_klass->class_loader());
2602     protection_domain = Handle(THREAD, accessing_klass->protection_domain());
2603   }
2604   bool can_be_cached = true;
2605   int npts = ArgumentCount(signature).size();
2606   objArrayHandle pts = oopFactory::new_objArray_handle(SystemDictionary::Class_klass(), npts, CHECK_(empty));
2607   int arg = 0;
2608   Handle rt; // the return type from the signature
2609   ResourceMark rm(THREAD);
2610   for (SignatureStream ss(signature); !ss.is_done(); ss.next()) {
2611     oop mirror = NULL;
2612     if (can_be_cached) {
2613       // Use neutral class loader to lookup candidate classes to be placed in the cache.
2614       mirror = ss.as_java_mirror(Handle(), Handle(),
2615                                  SignatureStream::ReturnNull, CHECK_(empty));
2616       if (mirror == NULL || (ss.is_object() && !is_always_visible_class(mirror))) {
2617         // Fall back to accessing_klass context.
2618         can_be_cached = false;
2619       }
2620     }
2621     if (!can_be_cached) {
2622       // Resolve, throwing a real error if it doesn't work.
2623       mirror = ss.as_java_mirror(class_loader, protection_domain,
2624                                  SignatureStream::NCDFError, CHECK_(empty));
2625     }
2626     assert(mirror != NULL, "%s", ss.as_symbol()->as_C_string());
2627     if (ss.at_return_type())
2628       rt = Handle(THREAD, mirror);
2629     else
2630       pts->obj_at_put(arg++, mirror);
2631 
2632     // Check accessibility.
2633     if (!java_lang_Class::is_primitive(mirror) && accessing_klass != NULL) {
2634       Klass* sel_klass = java_lang_Class::as_Klass(mirror);
2635       mirror = NULL;  // safety
2636       // Emulate ConstantPool::verify_constant_pool_resolve.
2637       bool fold_type_to_class = true;
2638       LinkResolver::check_klass_accessability(accessing_klass, sel_klass,
2639                                               fold_type_to_class, CHECK_(empty));
2640     }
2641   }
2642   assert(arg == npts, "");
2643 
2644   // call java.lang.invoke.MethodHandleNatives::findMethodHandleType(Class rt, Class[] pts) -> MethodType
2645   JavaCallArguments args(Handle(THREAD, rt()));
2646   args.push_oop(pts);
2647   JavaValue result(T_OBJECT);
2648   JavaCalls::call_static(&result,
2649                          SystemDictionary::MethodHandleNatives_klass(),
2650                          vmSymbols::findMethodHandleType_name(),
2651                          vmSymbols::findMethodHandleType_signature(),
2652                          &args, CHECK_(empty));
2653   Handle method_type(THREAD, (oop) result.get_jobject());
2654 
2655   if (can_be_cached) {
2656     // We can cache this MethodType inside the JVM.
2657     MutexLocker ml(SystemDictionary_lock, THREAD);
2658     spe = invoke_method_table()->find_entry(index, hash, signature, null_iid);
2659     if (spe == NULL)
2660       spe = invoke_method_table()->add_entry(index, hash, signature, null_iid);
2661     if (spe->method_type() == NULL) {
2662       spe->set_method_type(method_type());
2663     }
2664   }
2665 
2666   // report back to the caller with the MethodType
2667   return method_type;
2668 }
2669 
2670 Handle SystemDictionary::find_field_handle_type(Symbol* signature,
2671                                                 Klass* accessing_klass,
2672                                                 TRAPS) {
2673   Handle empty;
2674   ResourceMark rm(THREAD);
2675   SignatureStream ss(signature, /*is_method=*/ false);
2676   if (!ss.is_done()) {
2677     Handle class_loader, protection_domain;
2678     if (accessing_klass != NULL) {
2679       class_loader      = Handle(THREAD, accessing_klass->class_loader());
2680       protection_domain = Handle(THREAD, accessing_klass->protection_domain());
2681     }
2682     oop mirror = ss.as_java_mirror(class_loader, protection_domain, SignatureStream::NCDFError, CHECK_(empty));
2683     ss.next();
2684     if (ss.is_done()) {
2685       return Handle(THREAD, mirror);
2686     }
2687   }
2688   return empty;
2689 }
2690 
2691 // Ask Java code to find or construct a method handle constant.
2692 Handle SystemDictionary::link_method_handle_constant(Klass* caller,
2693                                                      int ref_kind, //e.g., JVM_REF_invokeVirtual
2694                                                      Klass* callee,
2695                                                      Symbol* name,
2696                                                      Symbol* signature,
2697                                                      TRAPS) {
2698   Handle empty;
2699   if (caller == NULL) {
2700     THROW_MSG_(vmSymbols::java_lang_InternalError(), "bad MH constant", empty);
2701   }
2702   Handle name_str      = java_lang_String::create_from_symbol(name,      CHECK_(empty));
2703   Handle signature_str = java_lang_String::create_from_symbol(signature, CHECK_(empty));
2704 
2705   // Put symbolic info from the MH constant into freshly created MemberName and resolve it.
2706   Handle mname = MemberName_klass()->allocate_instance_handle(CHECK_(empty));
2707   java_lang_invoke_MemberName::set_clazz(mname(), callee->java_mirror());
2708   java_lang_invoke_MemberName::set_name (mname(), name_str());
2709   java_lang_invoke_MemberName::set_type (mname(), signature_str());
2710   java_lang_invoke_MemberName::set_flags(mname(), MethodHandles::ref_kind_to_flags(ref_kind));
2711 
2712   if (ref_kind == JVM_REF_invokeVirtual &&
2713       MethodHandles::is_signature_polymorphic_public_name(callee, name)) {
2714     // Skip resolution for public signature polymorphic methods such as
2715     // j.l.i.MethodHandle.invoke()/invokeExact() and those on VarHandle
2716     // They require appendix argument which MemberName resolution doesn't handle.
2717     // There's special logic on JDK side to handle them
2718     // (see MethodHandles.linkMethodHandleConstant() and MethodHandles.findVirtualForMH()).
2719   } else {
2720     MethodHandles::resolve_MemberName(mname, caller, /*speculative_resolve*/false, CHECK_(empty));
2721   }
2722 
2723   // After method/field resolution succeeded, it's safe to resolve MH signature as well.
2724   Handle type = MethodHandles::resolve_MemberName_type(mname, caller, CHECK_(empty));
2725 
2726   // call java.lang.invoke.MethodHandleNatives::linkMethodHandleConstant(Class caller, int refKind, Class callee, String name, Object type) -> MethodHandle
2727   JavaCallArguments args;
2728   args.push_oop(Handle(THREAD, caller->java_mirror()));  // the referring class
2729   args.push_int(ref_kind);
2730   args.push_oop(Handle(THREAD, callee->java_mirror()));  // the target class
2731   args.push_oop(name_str);
2732   args.push_oop(type);
2733   JavaValue result(T_OBJECT);
2734   JavaCalls::call_static(&result,
2735                          SystemDictionary::MethodHandleNatives_klass(),
2736                          vmSymbols::linkMethodHandleConstant_name(),
2737                          vmSymbols::linkMethodHandleConstant_signature(),
2738                          &args, CHECK_(empty));
2739   return Handle(THREAD, (oop) result.get_jobject());
2740 }
2741 
2742 // Ask Java to run a bootstrap method, in order to create a dynamic call site
2743 // while linking an invokedynamic op, or compute a constant for Dynamic_info CP entry
2744 // with linkage results being stored back into the bootstrap specifier.
2745 void SystemDictionary::invoke_bootstrap_method(BootstrapInfo& bootstrap_specifier, TRAPS) {
2746   // Resolve the bootstrap specifier, its name, type, and static arguments
2747   bootstrap_specifier.resolve_bsm(CHECK);
2748 
2749   // This should not happen.  JDK code should take care of that.
2750   if (bootstrap_specifier.caller() == NULL || bootstrap_specifier.type_arg().is_null()) {
2751     THROW_MSG(vmSymbols::java_lang_InternalError(), "Invalid bootstrap method invocation with no caller or type argument");
2752   }
2753 
2754   bool is_indy = bootstrap_specifier.is_method_call();
2755   objArrayHandle appendix_box;
2756   if (is_indy) {
2757     // Some method calls may require an appendix argument.  Arrange to receive it.
2758     appendix_box = oopFactory::new_objArray_handle(SystemDictionary::Object_klass(), 1, CHECK);
2759     assert(appendix_box->obj_at(0) == NULL, "");
2760   }
2761 
2762   // call condy: java.lang.invoke.MethodHandleNatives::linkDynamicConstant(caller, condy_index, bsm, type, info)
2763   //       indy: java.lang.invoke.MethodHandleNatives::linkCallSite(caller, indy_index, bsm, name, mtype, info, &appendix)
2764   JavaCallArguments args;
2765   args.push_oop(Handle(THREAD, bootstrap_specifier.caller_mirror()));
2766   args.push_int(bootstrap_specifier.bss_index());
2767   args.push_oop(bootstrap_specifier.bsm());
2768   args.push_oop(bootstrap_specifier.name_arg());
2769   args.push_oop(bootstrap_specifier.type_arg());
2770   args.push_oop(bootstrap_specifier.arg_values());
2771   if (is_indy) {
2772     args.push_oop(appendix_box);
2773   }
2774   JavaValue result(T_OBJECT);
2775   JavaCalls::call_static(&result,
2776                          SystemDictionary::MethodHandleNatives_klass(),
2777                          is_indy ? vmSymbols::linkCallSite_name() : vmSymbols::linkDynamicConstant_name(),
2778                          is_indy ? vmSymbols::linkCallSite_signature() : vmSymbols::linkDynamicConstant_signature(),
2779                          &args, CHECK);
2780 
2781   Handle value(THREAD, (oop) result.get_jobject());
2782   if (is_indy) {
2783     Handle appendix;
2784     methodHandle method = unpack_method_and_appendix(value,
2785                                                      bootstrap_specifier.caller(),
2786                                                      appendix_box,
2787                                                      &appendix, CHECK);
2788     bootstrap_specifier.set_resolved_method(method, appendix);
2789   } else {
2790     bootstrap_specifier.set_resolved_value(value);
2791   }
2792 
2793   // sanity check
2794   assert(bootstrap_specifier.is_resolved() ||
2795          (bootstrap_specifier.is_method_call() &&
2796           bootstrap_specifier.resolved_method().not_null()), "bootstrap method call failed");
2797 }
2798 
2799 // Protection domain cache table handling
2800 
2801 ProtectionDomainCacheEntry* SystemDictionary::cache_get(Handle protection_domain) {
2802   return _pd_cache_table->get(protection_domain);
2803 }
2804 
2805 // ----------------------------------------------------------------------------
2806 
2807 void SystemDictionary::print_on(outputStream *st) {
2808   CDS_ONLY(SystemDictionaryShared::print_on(st));
2809   GCMutexLocker mu(SystemDictionary_lock);
2810 
2811   ClassLoaderDataGraph::print_dictionary(st);
2812 
2813   // Placeholders
2814   placeholders()->print_on(st);
2815   st->cr();
2816 
2817   // loader constraints - print under SD_lock
2818   constraints()->print_on(st);
2819   st->cr();
2820 
2821   _pd_cache_table->print_on(st);
2822   st->cr();
2823 }
2824 
2825 void SystemDictionary::print() { print_on(tty); }
2826 
2827 void SystemDictionary::verify() {
2828   guarantee(constraints() != NULL,
2829             "Verify of loader constraints failed");
2830   guarantee(placeholders()->number_of_entries() >= 0,
2831             "Verify of placeholders failed");
2832 
2833   GCMutexLocker mu(SystemDictionary_lock);
2834 
2835   // Verify dictionary
2836   ClassLoaderDataGraph::verify_dictionary();
2837 
2838   placeholders()->verify();
2839 
2840   // Verify constraint table
2841   guarantee(constraints() != NULL, "Verify of loader constraints failed");
2842   constraints()->verify(placeholders());
2843 
2844   _pd_cache_table->verify();
2845 }
2846 
2847 void SystemDictionary::dump(outputStream *st, bool verbose) {
2848   assert_locked_or_safepoint(SystemDictionary_lock);
2849   if (verbose) {
2850     print_on(st);
2851   } else {
2852     CDS_ONLY(SystemDictionaryShared::print_table_statistics(st));
2853     ClassLoaderDataGraph::print_table_statistics(st);
2854     placeholders()->print_table_statistics(st, "Placeholder Table");
2855     constraints()->print_table_statistics(st, "LoaderConstraints Table");
2856     pd_cache_table()->print_table_statistics(st, "ProtectionDomainCache Table");
2857   }
2858 }
2859 
2860 TableStatistics SystemDictionary::placeholders_statistics() {
2861   MutexLocker ml(SystemDictionary_lock);
2862   return placeholders()->statistics_calculate();
2863 }
2864 
2865 TableStatistics SystemDictionary::loader_constraints_statistics() {
2866   MutexLocker ml(SystemDictionary_lock);
2867   return constraints()->statistics_calculate();
2868 }
2869 
2870 TableStatistics SystemDictionary::protection_domain_cache_statistics() {
2871   MutexLocker ml(SystemDictionary_lock);
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_global_oop_storage =
2902     new OopStorage("VM Global Oop Handles",
2903                    VMGlobalAlloc_lock,
2904                    VMGlobalActive_lock);
2905 
2906   _vm_weak_oop_storage =
2907     new OopStorage("VM Weak Oop Handles",
2908                    VMWeakAlloc_lock,
2909                    VMWeakActive_lock);
2910 }
2911 
2912 OopStorage* SystemDictionary::vm_global_oop_storage() {
2913   assert(_vm_global_oop_storage != NULL, "Uninitialized");
2914   return _vm_global_oop_storage;
2915 }
2916 
2917 OopStorage* SystemDictionary::vm_weak_oop_storage() {
2918   assert(_vm_weak_oop_storage != NULL, "Uninitialized");
2919   return _vm_weak_oop_storage;
2920 }