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