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