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