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