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   assert(!ModuleEntryTable::javabase_moduleEntry()->is_patched(),
1226          "Cannot use sharing if java.base is patched");
1227   ResourceMark rm;
1228   int path_index = ik->shared_classpath_index();
1229   SharedClassPathEntry* ent =
1230             (SharedClassPathEntry*)FileMapInfo::shared_classpath(path_index);
1231   if (!Universe::is_module_initialized()) {
1232     assert(ent != NULL && ent->is_jrt(),
1233            "Loading non-bootstrap classes before the module system is initialized");
1234     assert(class_loader.is_null(), "sanity");
1235     return true;
1236   }
1237   // Get the pkg_entry from the classloader
1238   TempNewSymbol pkg_name = NULL;
1239   PackageEntry* pkg_entry = NULL;
1240   ModuleEntry* mod_entry = NULL;
1241   const char* pkg_string = NULL;
1242   ClassLoaderData* loader_data = class_loader_data(class_loader);
1243   pkg_name = InstanceKlass::package_from_name(class_name, CHECK_false);
1244   if (pkg_name != NULL) {
1245     pkg_string = pkg_name->as_C_string();
1246     if (loader_data != NULL) {
1247       pkg_entry = loader_data->packages()->lookup_only(pkg_name);
1248     }
1249     if (pkg_entry != NULL) {
1250       mod_entry = pkg_entry->module();
1251     }
1252   }
1253 
1254   // If the archived class is from a module that has been patched at runtime,
1255   // the class cannot be loaded from the archive.
1256   if (mod_entry != NULL && mod_entry->is_patched()) {
1257     return false;
1258   }
1259 
1260   if (class_loader.is_null()) {
1261     assert(ent != NULL, "Shared class for NULL classloader must have valid SharedClassPathEntry");
1262     // The NULL classloader can load archived class originated from the
1263     // "modules" jimage and the -Xbootclasspath/a. For class from the
1264     // "modules" jimage, the PackageEntry/ModuleEntry must be defined
1265     // by the NULL classloader.
1266     if (mod_entry != NULL) {
1267       // PackageEntry/ModuleEntry is found in the classloader. Check if the
1268       // ModuleEntry's location agrees with the archived class' origination.
1269       if (ent->is_jrt() && mod_entry->location()->starts_with("jrt:")) {
1270         return true; // Module class from the "module" jimage
1271       }
1272     }
1273 
1274     // If the archived class is not from the "module" jimage, the class can be
1275     // loaded by the NULL classloader if
1276     //
1277     // 1. the class is from the unamed package
1278     // 2. or, the class is not from a module defined in the NULL classloader
1279     // 3. or, the class is from an unamed module
1280     if (!ent->is_jrt() && ik->is_shared_boot_class()) {
1281       // the class is from the -Xbootclasspath/a
1282       if (pkg_string == NULL ||
1283           pkg_entry == NULL ||
1284           pkg_entry->in_unnamed_module()) {
1285         assert(mod_entry == NULL ||
1286                mod_entry == loader_data->modules()->unnamed_module(),
1287                "the unnamed module is not defined in the classloader");
1288         return true;
1289       }
1290     }
1291     return false;
1292   } else {
1293     bool res = SystemDictionaryShared::is_shared_class_visible_for_classloader(
1294               ik, class_loader, pkg_string, pkg_name,
1295               pkg_entry, mod_entry, CHECK_(false));
1296     return res;
1297   }
1298 }
1299 
1300 instanceKlassHandle SystemDictionary::load_shared_class(instanceKlassHandle ik,
1301                                                         Handle class_loader,
1302                                                         Handle protection_domain, TRAPS) {
1303   instanceKlassHandle nh = instanceKlassHandle(); // null Handle
1304 
1305   if (ik.not_null()) {
1306     Symbol* class_name = ik->name();
1307 
1308     bool visible = is_shared_class_visible(
1309                             class_name, ik, class_loader, CHECK_(nh));
1310     if (!visible) {
1311       return nh;
1312     }
1313 
1314     // Resolve the superclass and interfaces. They must be the same
1315     // as in dump time, because the layout of <ik> depends on
1316     // the specific layout of ik->super() and ik->local_interfaces().
1317     //
1318     // If unexpected superclass or interfaces are found, we cannot
1319     // load <ik> from the shared archive.
1320 
1321     if (ik->super() != NULL) {
1322       Symbol*  cn = ik->super()->name();
1323       Klass *s = resolve_super_or_fail(class_name, cn,
1324                                        class_loader, protection_domain, true, CHECK_(nh));
1325       if (s != ik->super()) {
1326         // The dynamically resolved super class is not the same as the one we used during dump time,
1327         // so we cannot use ik.
1328         return nh;
1329       } else {
1330         assert(s->is_shared(), "must be");
1331       }
1332     }
1333 
1334     Array<Klass*>* interfaces = ik->local_interfaces();
1335     int num_interfaces = interfaces->length();
1336     for (int index = 0; index < num_interfaces; index++) {
1337       Klass* k = interfaces->at(index);
1338 
1339       // Note: can not use InstanceKlass::cast here because
1340       // interfaces' InstanceKlass's C++ vtbls haven't been
1341       // reinitialized yet (they will be once the interface classes
1342       // are loaded)
1343       Symbol*  name  = k->name();
1344       Klass* i = resolve_super_or_fail(class_name, name, class_loader, protection_domain, false, CHECK_(nh));
1345       if (k != i) {
1346         // The dynamically resolved interface class is not the same as the one we used during dump time,
1347         // so we cannot use ik.
1348         return nh;
1349       } else {
1350         assert(i->is_shared(), "must be");
1351       }
1352     }
1353 
1354     instanceKlassHandle new_ik = KlassFactory::check_shared_class_file_load_hook(
1355         ik, class_name, class_loader, protection_domain, CHECK_(nh));
1356     if (new_ik.not_null()) {
1357       // The class is changed by CFLH. Return the new class. The shared class is
1358       // not used.
1359       return new_ik;
1360     }
1361 
1362     // Adjust methods to recover missing data.  They need addresses for
1363     // interpreter entry points and their default native method address
1364     // must be reset.
1365 
1366     // Updating methods must be done under a lock so multiple
1367     // threads don't update these in parallel
1368     //
1369     // Shared classes are all currently loaded by either the bootstrap or
1370     // internal parallel class loaders, so this will never cause a deadlock
1371     // on a custom class loader lock.
1372 
1373     ClassLoaderData* loader_data = ClassLoaderData::class_loader_data(class_loader());
1374     {
1375       Handle lockObject = compute_loader_lock_object(class_loader, THREAD);
1376       check_loader_lock_contention(lockObject, THREAD);
1377       ObjectLocker ol(lockObject, THREAD, true);
1378       // prohibited package check assumes all classes loaded from archive call
1379       // restore_unshareable_info which calls ik->set_package()
1380       ik->restore_unshareable_info(loader_data, protection_domain, CHECK_(nh));
1381     }
1382 
1383     if (log_is_enabled(Info, class, load)) {
1384       ik()->print_loading_log(LogLevel::Info, loader_data, NULL, NULL);
1385     }
1386     // No 'else' here as logging levels are not mutually exclusive
1387 
1388     if (log_is_enabled(Debug, class, load)) {
1389       ik()->print_loading_log(LogLevel::Debug, loader_data, NULL, NULL);
1390     }
1391 
1392     // For boot loader, ensure that GetSystemPackage knows that a class in this
1393     // package was loaded.
1394     if (class_loader.is_null()) {
1395       int path_index = ik->shared_classpath_index();
1396       ResourceMark rm;
1397       ClassLoader::add_package(ik->name()->as_C_string(), path_index, THREAD);
1398     }
1399 
1400     if (DumpLoadedClassList != NULL && classlist_file->is_open()) {
1401       // Only dump the classes that can be stored into CDS archive
1402       if (SystemDictionaryShared::is_sharing_possible(loader_data)) {
1403         ResourceMark rm(THREAD);
1404         classlist_file->print_cr("%s", ik->name()->as_C_string());
1405         classlist_file->flush();
1406       }
1407     }
1408 
1409     // notify a class loaded from shared object
1410     ClassLoadingService::notify_class_loaded(ik(), true /* shared class */);
1411   }
1412   return ik;
1413 }
1414 #endif // INCLUDE_CDS
1415 
1416 instanceKlassHandle SystemDictionary::load_instance_class(Symbol* class_name, Handle class_loader, TRAPS) {
1417   instanceKlassHandle nh = instanceKlassHandle(); // null Handle
1418 
1419   if (class_loader.is_null()) {
1420     ResourceMark rm;
1421     PackageEntry* pkg_entry = NULL;
1422     bool search_only_bootloader_append = false;
1423     ClassLoaderData *loader_data = class_loader_data(class_loader);
1424 
1425     // Find the package in the boot loader's package entry table.
1426     TempNewSymbol pkg_name = InstanceKlass::package_from_name(class_name, CHECK_NULL);
1427     if (pkg_name != NULL) {
1428       pkg_entry = loader_data->packages()->lookup_only(pkg_name);
1429     }
1430 
1431     // Prior to attempting to load the class, enforce the boot loader's
1432     // visibility boundaries.
1433     if (!Universe::is_module_initialized()) {
1434       // During bootstrapping, prior to module initialization, any
1435       // class attempting to be loaded must be checked against the
1436       // java.base packages in the boot loader's PackageEntryTable.
1437       // No class outside of java.base is allowed to be loaded during
1438       // this bootstrapping window.
1439       if (!DumpSharedSpaces) {
1440         if (pkg_entry == NULL || pkg_entry->in_unnamed_module()) {
1441           // Class is either in the unnamed package or in
1442           // a named package within the unnamed module.  Either
1443           // case is outside of java.base, do not attempt to
1444           // load the class post java.base definition.  If
1445           // java.base has not been defined, let the class load
1446           // and its package will be checked later by
1447           // ModuleEntryTable::verify_javabase_packages.
1448           if (ModuleEntryTable::javabase_defined()) {
1449             return nh;
1450           }
1451         } else {
1452           // Check that the class' package is defined within java.base.
1453           ModuleEntry* mod_entry = pkg_entry->module();
1454           Symbol* mod_entry_name = mod_entry->name();
1455           if (mod_entry_name->fast_compare(vmSymbols::java_base()) != 0) {
1456             return nh;
1457           }
1458         }
1459       }
1460     } else {
1461       assert(!DumpSharedSpaces, "Archive dumped after module system initialization");
1462       // After the module system has been initialized, check if the class'
1463       // package is in a module defined to the boot loader.
1464       if (pkg_name == NULL || pkg_entry == NULL || pkg_entry->in_unnamed_module()) {
1465         // Class is either in the unnamed package, in a named package
1466         // within a module not defined to the boot loader or in a
1467         // a named package within the unnamed module.  In all cases,
1468         // limit visibility to search for the class only in the boot
1469         // loader's append path.
1470         search_only_bootloader_append = true;
1471       }
1472     }
1473 
1474     // Prior to bootstrapping's module initialization, never load a class outside
1475     // of the boot loader's module path
1476     assert(Universe::is_module_initialized() || DumpSharedSpaces ||
1477            !search_only_bootloader_append,
1478            "Attempt to load a class outside of boot loader's module path");
1479 
1480     // Search the shared system dictionary for classes preloaded into the
1481     // shared spaces.
1482     instanceKlassHandle k;
1483     {
1484 #if INCLUDE_CDS
1485       PerfTraceTime vmtimer(ClassLoader::perf_shared_classload_time());
1486       k = load_shared_class(class_name, class_loader, THREAD);
1487 #endif
1488     }
1489 
1490     if (k.is_null()) {
1491       // Use VM class loader
1492       PerfTraceTime vmtimer(ClassLoader::perf_sys_classload_time());
1493       k = ClassLoader::load_class(class_name, search_only_bootloader_append, CHECK_(nh));
1494     }
1495 
1496     // find_or_define_instance_class may return a different InstanceKlass
1497     if (!k.is_null()) {
1498       k = find_or_define_instance_class(class_name, class_loader, k, CHECK_(nh));
1499     }
1500     return k;
1501   } else {
1502     // Use user specified class loader to load class. Call loadClass operation on class_loader.
1503     ResourceMark rm(THREAD);
1504 
1505     assert(THREAD->is_Java_thread(), "must be a JavaThread");
1506     JavaThread* jt = (JavaThread*) THREAD;
1507 
1508     PerfClassTraceTime vmtimer(ClassLoader::perf_app_classload_time(),
1509                                ClassLoader::perf_app_classload_selftime(),
1510                                ClassLoader::perf_app_classload_count(),
1511                                jt->get_thread_stat()->perf_recursion_counts_addr(),
1512                                jt->get_thread_stat()->perf_timers_addr(),
1513                                PerfClassTraceTime::CLASS_LOAD);
1514 
1515     Handle s = java_lang_String::create_from_symbol(class_name, CHECK_(nh));
1516     // Translate to external class name format, i.e., convert '/' chars to '.'
1517     Handle string = java_lang_String::externalize_classname(s, CHECK_(nh));
1518 
1519     JavaValue result(T_OBJECT);
1520 
1521     KlassHandle spec_klass (THREAD, SystemDictionary::ClassLoader_klass());
1522 
1523     // Call public unsynchronized loadClass(String) directly for all class loaders
1524     // for parallelCapable class loaders. JDK >=7, loadClass(String, boolean) will
1525     // acquire a class-name based lock rather than the class loader object lock.
1526     // JDK < 7 already acquire the class loader lock in loadClass(String, boolean),
1527     // so the call to loadClassInternal() was not required.
1528     //
1529     // UnsyncloadClass flag means both call loadClass(String) and do
1530     // not acquire the class loader lock even for class loaders that are
1531     // not parallelCapable. This was a risky transitional
1532     // flag for diagnostic purposes only. It is risky to call
1533     // custom class loaders without synchronization.
1534     // WARNING If a custom class loader does NOT synchronizer findClass, or callers of
1535     // findClass, the UnsyncloadClass flag risks unexpected timing bugs in the field.
1536     // Do NOT assume this will be supported in future releases.
1537     //
1538     // Added MustCallLoadClassInternal in case we discover in the field
1539     // a customer that counts on this call
1540     if (MustCallLoadClassInternal && has_loadClassInternal()) {
1541       JavaCalls::call_special(&result,
1542                               class_loader,
1543                               spec_klass,
1544                               vmSymbols::loadClassInternal_name(),
1545                               vmSymbols::string_class_signature(),
1546                               string,
1547                               CHECK_(nh));
1548     } else {
1549       JavaCalls::call_virtual(&result,
1550                               class_loader,
1551                               spec_klass,
1552                               vmSymbols::loadClass_name(),
1553                               vmSymbols::string_class_signature(),
1554                               string,
1555                               CHECK_(nh));
1556     }
1557 
1558     assert(result.get_type() == T_OBJECT, "just checking");
1559     oop obj = (oop) result.get_jobject();
1560 
1561     // Primitive classes return null since forName() can not be
1562     // used to obtain any of the Class objects representing primitives or void
1563     if ((obj != NULL) && !(java_lang_Class::is_primitive(obj))) {
1564       instanceKlassHandle k =
1565                 instanceKlassHandle(THREAD, java_lang_Class::as_Klass(obj));
1566       // For user defined Java class loaders, check that the name returned is
1567       // the same as that requested.  This check is done for the bootstrap
1568       // loader when parsing the class file.
1569       if (class_name == k->name()) {
1570         return k;
1571       }
1572     }
1573     // Class is not found or has the wrong name, return NULL
1574     return nh;
1575   }
1576 }
1577 
1578 void SystemDictionary::define_instance_class(instanceKlassHandle k, TRAPS) {
1579 
1580   ClassLoaderData* loader_data = k->class_loader_data();
1581   Handle class_loader_h(THREAD, loader_data->class_loader());
1582 
1583  // for bootstrap and other parallel classloaders don't acquire lock,
1584  // use placeholder token
1585  // If a parallelCapable class loader calls define_instance_class instead of
1586  // find_or_define_instance_class to get here, we have a timing
1587  // hole with systemDictionary updates and check_constraints
1588  if (!class_loader_h.is_null() && !is_parallelCapable(class_loader_h)) {
1589     assert(ObjectSynchronizer::current_thread_holds_lock((JavaThread*)THREAD,
1590          compute_loader_lock_object(class_loader_h, THREAD)),
1591          "define called without lock");
1592   }
1593 
1594   // Check class-loading constraints. Throw exception if violation is detected.
1595   // Grabs and releases SystemDictionary_lock
1596   // The check_constraints/find_class call and update_dictionary sequence
1597   // must be "atomic" for a specific class/classloader pair so we never
1598   // define two different instanceKlasses for that class/classloader pair.
1599   // Existing classloaders will call define_instance_class with the
1600   // classloader lock held
1601   // Parallel classloaders will call find_or_define_instance_class
1602   // which will require a token to perform the define class
1603   Symbol*  name_h = k->name();
1604   unsigned int d_hash = dictionary()->compute_hash(name_h, loader_data);
1605   int d_index = dictionary()->hash_to_index(d_hash);
1606   check_constraints(d_index, d_hash, k, class_loader_h, true, CHECK);
1607 
1608   // Register class just loaded with class loader (placed in Vector)
1609   // Note we do this before updating the dictionary, as this can
1610   // fail with an OutOfMemoryError (if it does, we will *not* put this
1611   // class in the dictionary and will not update the class hierarchy).
1612   // JVMTI FollowReferences needs to find the classes this way.
1613   if (k->class_loader() != NULL) {
1614     methodHandle m(THREAD, Universe::loader_addClass_method());
1615     JavaValue result(T_VOID);
1616     JavaCallArguments args(class_loader_h);
1617     args.push_oop(Handle(THREAD, k->java_mirror()));
1618     JavaCalls::call(&result, m, &args, CHECK);
1619   }
1620 
1621   // Add the new class. We need recompile lock during update of CHA.
1622   {
1623     unsigned int p_hash = placeholders()->compute_hash(name_h, loader_data);
1624     int p_index = placeholders()->hash_to_index(p_hash);
1625 
1626     MutexLocker mu_r(Compile_lock, THREAD);
1627 
1628     // Add to class hierarchy, initialize vtables, and do possible
1629     // deoptimizations.
1630     add_to_hierarchy(k, CHECK); // No exception, but can block
1631 
1632     // Add to systemDictionary - so other classes can see it.
1633     // Grabs and releases SystemDictionary_lock
1634     update_dictionary(d_index, d_hash, p_index, p_hash,
1635                       k, class_loader_h, THREAD);
1636   }
1637   k->eager_initialize(THREAD);
1638 
1639   // notify jvmti
1640   if (JvmtiExport::should_post_class_load()) {
1641       assert(THREAD->is_Java_thread(), "thread->is_Java_thread()");
1642       JvmtiExport::post_class_load((JavaThread *) THREAD, k());
1643 
1644   }
1645   class_define_event(k, loader_data);
1646 }
1647 
1648 // Support parallel classloading
1649 // All parallel class loaders, including bootstrap classloader
1650 // lock a placeholder entry for this class/class_loader pair
1651 // to allow parallel defines of different classes for this class loader
1652 // With AllowParallelDefine flag==true, in case they do not synchronize around
1653 // FindLoadedClass/DefineClass, calls, we check for parallel
1654 // loading for them, wait if a defineClass is in progress
1655 // and return the initial requestor's results
1656 // This flag does not apply to the bootstrap classloader.
1657 // With AllowParallelDefine flag==false, call through to define_instance_class
1658 // which will throw LinkageError: duplicate class definition.
1659 // False is the requested default.
1660 // For better performance, the class loaders should synchronize
1661 // findClass(), i.e. FindLoadedClass/DefineClassIfAbsent or they
1662 // potentially waste time reading and parsing the bytestream.
1663 // Note: VM callers should ensure consistency of k/class_name,class_loader
1664 // Be careful when modifying this code: once you have run
1665 // placeholders()->find_and_add(PlaceholderTable::DEFINE_CLASS),
1666 // you need to find_and_remove it before returning.
1667 // So be careful to not exit with a CHECK_ macro betweeen these calls.
1668 instanceKlassHandle SystemDictionary::find_or_define_instance_class(Symbol* class_name, Handle class_loader, instanceKlassHandle k, TRAPS) {
1669 
1670   instanceKlassHandle nh = instanceKlassHandle(); // null Handle
1671   Symbol*  name_h = k->name(); // passed in class_name may be null
1672   ClassLoaderData* loader_data = class_loader_data(class_loader);
1673 
1674   unsigned int d_hash = dictionary()->compute_hash(name_h, loader_data);
1675   int d_index = dictionary()->hash_to_index(d_hash);
1676 
1677 // Hold SD lock around find_class and placeholder creation for DEFINE_CLASS
1678   unsigned int p_hash = placeholders()->compute_hash(name_h, loader_data);
1679   int p_index = placeholders()->hash_to_index(p_hash);
1680   PlaceholderEntry* probe;
1681 
1682   {
1683     MutexLocker mu(SystemDictionary_lock, THREAD);
1684     // First check if class already defined
1685     if (UnsyncloadClass || (is_parallelDefine(class_loader))) {
1686       Klass* check = find_class(d_index, d_hash, name_h, loader_data);
1687       if (check != NULL) {
1688         return(instanceKlassHandle(THREAD, check));
1689       }
1690     }
1691 
1692     // Acquire define token for this class/classloader
1693     probe = placeholders()->find_and_add(p_index, p_hash, name_h, loader_data, PlaceholderTable::DEFINE_CLASS, NULL, THREAD);
1694     // Wait if another thread defining in parallel
1695     // All threads wait - even those that will throw duplicate class: otherwise
1696     // caller is surprised by LinkageError: duplicate, but findLoadedClass fails
1697     // if other thread has not finished updating dictionary
1698     while (probe->definer() != NULL) {
1699       SystemDictionary_lock->wait();
1700     }
1701     // Only special cases allow parallel defines and can use other thread's results
1702     // Other cases fall through, and may run into duplicate defines
1703     // caught by finding an entry in the SystemDictionary
1704     if ((UnsyncloadClass || is_parallelDefine(class_loader)) && (probe->instance_klass() != NULL)) {
1705         placeholders()->find_and_remove(p_index, p_hash, name_h, loader_data, PlaceholderTable::DEFINE_CLASS, THREAD);
1706         SystemDictionary_lock->notify_all();
1707 #ifdef ASSERT
1708         Klass* check = find_class(d_index, d_hash, name_h, loader_data);
1709         assert(check != NULL, "definer missed recording success");
1710 #endif
1711         return(instanceKlassHandle(THREAD, probe->instance_klass()));
1712     } else {
1713       // This thread will define the class (even if earlier thread tried and had an error)
1714       probe->set_definer(THREAD);
1715     }
1716   }
1717 
1718   define_instance_class(k, THREAD);
1719 
1720   Handle linkage_exception = Handle(); // null handle
1721 
1722   // definer must notify any waiting threads
1723   {
1724     MutexLocker mu(SystemDictionary_lock, THREAD);
1725     PlaceholderEntry* probe = placeholders()->get_entry(p_index, p_hash, name_h, loader_data);
1726     assert(probe != NULL, "DEFINE_CLASS placeholder lost?");
1727     if (probe != NULL) {
1728       if (HAS_PENDING_EXCEPTION) {
1729         linkage_exception = Handle(THREAD,PENDING_EXCEPTION);
1730         CLEAR_PENDING_EXCEPTION;
1731       } else {
1732         probe->set_instance_klass(k());
1733       }
1734       probe->set_definer(NULL);
1735       placeholders()->find_and_remove(p_index, p_hash, name_h, loader_data, PlaceholderTable::DEFINE_CLASS, THREAD);
1736       SystemDictionary_lock->notify_all();
1737     }
1738   }
1739 
1740   // Can't throw exception while holding lock due to rank ordering
1741   if (linkage_exception() != NULL) {
1742     THROW_OOP_(linkage_exception(), nh); // throws exception and returns
1743   }
1744 
1745   return k;
1746 }
1747 Handle SystemDictionary::compute_loader_lock_object(Handle class_loader, TRAPS) {
1748   // If class_loader is NULL we synchronize on _system_loader_lock_obj
1749   if (class_loader.is_null()) {
1750     return Handle(THREAD, _system_loader_lock_obj);
1751   } else {
1752     return class_loader;
1753   }
1754 }
1755 
1756 // This method is added to check how often we have to wait to grab loader
1757 // lock. The results are being recorded in the performance counters defined in
1758 // ClassLoader::_sync_systemLoaderLockContentionRate and
1759 // ClassLoader::_sync_nonSystemLoaderLockConteionRate.
1760 void SystemDictionary::check_loader_lock_contention(Handle loader_lock, TRAPS) {
1761   if (!UsePerfData) {
1762     return;
1763   }
1764 
1765   assert(!loader_lock.is_null(), "NULL lock object");
1766 
1767   if (ObjectSynchronizer::query_lock_ownership((JavaThread*)THREAD, loader_lock)
1768       == ObjectSynchronizer::owner_other) {
1769     // contention will likely happen, so increment the corresponding
1770     // contention counter.
1771     if (loader_lock() == _system_loader_lock_obj) {
1772       ClassLoader::sync_systemLoaderLockContentionRate()->inc();
1773     } else {
1774       ClassLoader::sync_nonSystemLoaderLockContentionRate()->inc();
1775     }
1776   }
1777 }
1778 
1779 // ----------------------------------------------------------------------------
1780 // Lookup
1781 
1782 Klass* SystemDictionary::find_class(int index, unsigned int hash,
1783                                       Symbol* class_name,
1784                                       ClassLoaderData* loader_data) {
1785   assert_locked_or_safepoint(SystemDictionary_lock);
1786   assert (index == dictionary()->index_for(class_name, loader_data),
1787           "incorrect index?");
1788 
1789   Klass* k = dictionary()->find_class(index, hash, class_name, loader_data);
1790   return k;
1791 }
1792 
1793 
1794 // Basic find on classes in the midst of being loaded
1795 Symbol* SystemDictionary::find_placeholder(Symbol* class_name,
1796                                            ClassLoaderData* loader_data) {
1797   assert_locked_or_safepoint(SystemDictionary_lock);
1798   unsigned int p_hash = placeholders()->compute_hash(class_name, loader_data);
1799   int p_index = placeholders()->hash_to_index(p_hash);
1800   return placeholders()->find_entry(p_index, p_hash, class_name, loader_data);
1801 }
1802 
1803 
1804 // Used for assertions and verification only
1805 Klass* SystemDictionary::find_class(Symbol* class_name, ClassLoaderData* loader_data) {
1806   #ifndef ASSERT
1807   guarantee(VerifyBeforeGC      ||
1808             VerifyDuringGC      ||
1809             VerifyBeforeExit    ||
1810             VerifyDuringStartup ||
1811             VerifyAfterGC, "too expensive");
1812   #endif
1813   assert_locked_or_safepoint(SystemDictionary_lock);
1814 
1815   // First look in the loaded class array
1816   unsigned int d_hash = dictionary()->compute_hash(class_name, loader_data);
1817   int d_index = dictionary()->hash_to_index(d_hash);
1818   return find_class(d_index, d_hash, class_name, loader_data);
1819 }
1820 
1821 
1822 // Get the next class in the dictionary.
1823 Klass* SystemDictionary::try_get_next_class() {
1824   return dictionary()->try_get_next_class();
1825 }
1826 
1827 
1828 // ----------------------------------------------------------------------------
1829 // Update hierachy. This is done before the new klass has been added to the SystemDictionary. The Recompile_lock
1830 // is held, to ensure that the compiler is not using the class hierachy, and that deoptimization will kick in
1831 // before a new class is used.
1832 
1833 void SystemDictionary::add_to_hierarchy(instanceKlassHandle k, TRAPS) {
1834   assert(k.not_null(), "just checking");
1835   assert_locked_or_safepoint(Compile_lock);
1836 
1837   // Link into hierachy. Make sure the vtables are initialized before linking into
1838   k->append_to_sibling_list();                    // add to superklass/sibling list
1839   k->process_interfaces(THREAD);                  // handle all "implements" declarations
1840   k->set_init_state(InstanceKlass::loaded);
1841   // Now flush all code that depended on old class hierarchy.
1842   // Note: must be done *after* linking k into the hierarchy (was bug 12/9/97)
1843   // Also, first reinitialize vtable because it may have gotten out of synch
1844   // while the new class wasn't connected to the class hierarchy.
1845   CodeCache::flush_dependents_on(k);
1846 }
1847 
1848 // ----------------------------------------------------------------------------
1849 // GC support
1850 
1851 // Following roots during mark-sweep is separated in two phases.
1852 //
1853 // The first phase follows preloaded classes and all other system
1854 // classes, since these will never get unloaded anyway.
1855 //
1856 // The second phase removes (unloads) unreachable classes from the
1857 // system dictionary and follows the remaining classes' contents.
1858 
1859 void SystemDictionary::always_strong_oops_do(OopClosure* blk) {
1860   roots_oops_do(blk, NULL);
1861 }
1862 
1863 void SystemDictionary::always_strong_classes_do(KlassClosure* closure) {
1864   // Follow all system classes and temporary placeholders in dictionary
1865   dictionary()->always_strong_classes_do(closure);
1866 
1867   // Placeholders. These represent classes we're actively loading.
1868   placeholders()->classes_do(closure);
1869 }
1870 
1871 // Calculate a "good" systemdictionary size based
1872 // on predicted or current loaded classes count
1873 int SystemDictionary::calculate_systemdictionary_size(int classcount) {
1874   int newsize = _old_default_sdsize;
1875   if ((classcount > 0)  && !DumpSharedSpaces) {
1876     int desiredsize = classcount/_average_depth_goal;
1877     for (newsize = _primelist[_sdgeneration]; _sdgeneration < _prime_array_size -1;
1878          newsize = _primelist[++_sdgeneration]) {
1879       if (desiredsize <=  newsize) {
1880         break;
1881       }
1882     }
1883   }
1884   return newsize;
1885 }
1886 
1887 #ifdef ASSERT
1888 class VerifySDReachableAndLiveClosure : public OopClosure {
1889 private:
1890   BoolObjectClosure* _is_alive;
1891 
1892   template <class T> void do_oop_work(T* p) {
1893     oop obj = oopDesc::load_decode_heap_oop(p);
1894     guarantee(_is_alive->do_object_b(obj), "Oop in system dictionary must be live");
1895   }
1896 
1897 public:
1898   VerifySDReachableAndLiveClosure(BoolObjectClosure* is_alive) : OopClosure(), _is_alive(is_alive) { }
1899 
1900   virtual void do_oop(oop* p)       { do_oop_work(p); }
1901   virtual void do_oop(narrowOop* p) { do_oop_work(p); }
1902 };
1903 #endif
1904 
1905 // Assumes classes in the SystemDictionary are only unloaded at a safepoint
1906 // Note: anonymous classes are not in the SD.
1907 bool SystemDictionary::do_unloading(BoolObjectClosure* is_alive,
1908                                     bool clean_previous_versions) {
1909   // First, mark for unload all ClassLoaderData referencing a dead class loader.
1910   bool unloading_occurred = ClassLoaderDataGraph::do_unloading(is_alive,
1911                                                                clean_previous_versions);
1912   if (unloading_occurred) {
1913     dictionary()->do_unloading();
1914     constraints()->purge_loader_constraints();
1915     resolution_errors()->purge_resolution_errors();
1916   }
1917   // Oops referenced by the system dictionary may get unreachable independently
1918   // of the class loader (eg. cached protection domain oops). So we need to
1919   // explicitly unlink them here instead of in Dictionary::do_unloading.
1920   dictionary()->unlink(is_alive);
1921 #ifdef ASSERT
1922   VerifySDReachableAndLiveClosure cl(is_alive);
1923   dictionary()->oops_do(&cl);
1924 #endif
1925   return unloading_occurred;
1926 }
1927 
1928 void SystemDictionary::roots_oops_do(OopClosure* strong, OopClosure* weak) {
1929   strong->do_oop(&_java_system_loader);
1930   strong->do_oop(&_system_loader_lock_obj);
1931   CDS_ONLY(SystemDictionaryShared::roots_oops_do(strong);)
1932 
1933   // Adjust dictionary
1934   dictionary()->roots_oops_do(strong, weak);
1935 
1936   // Visit extra methods
1937   invoke_method_table()->oops_do(strong);
1938 }
1939 
1940 void SystemDictionary::oops_do(OopClosure* f) {
1941   f->do_oop(&_java_system_loader);
1942   f->do_oop(&_system_loader_lock_obj);
1943   CDS_ONLY(SystemDictionaryShared::oops_do(f);)
1944 
1945   // Adjust dictionary
1946   dictionary()->oops_do(f);
1947 
1948   // Visit extra methods
1949   invoke_method_table()->oops_do(f);
1950 }
1951 
1952 // Extended Class redefinition support.
1953 // If one of these classes is replaced, we need to replace it in these places.
1954 // KlassClosure::do_klass should take the address of a class but we can
1955 // change that later.
1956 void SystemDictionary::preloaded_classes_do(KlassClosure* f) {
1957   for (int k = (int)FIRST_WKID; k < (int)WKID_LIMIT; k++) {
1958     f->do_klass(_well_known_klasses[k]);
1959   }
1960 
1961   {
1962     for (int i = 0; i < T_VOID+1; i++) {
1963       if (_box_klasses[i] != NULL) {
1964         assert(i >= T_BOOLEAN, "checking");
1965         f->do_klass(_box_klasses[i]);
1966       }
1967     }
1968   }
1969 
1970   FilteredFieldsMap::classes_do(f);
1971 }
1972 
1973 void SystemDictionary::lazily_loaded_classes_do(KlassClosure* f) {
1974   f->do_klass(_abstract_ownable_synchronizer_klass);
1975 }
1976 
1977 // Just the classes from defining class loaders
1978 // Don't iterate over placeholders
1979 void SystemDictionary::classes_do(void f(Klass*)) {
1980   dictionary()->classes_do(f);
1981 }
1982 
1983 // Added for initialize_itable_for_klass
1984 //   Just the classes from defining class loaders
1985 // Don't iterate over placeholders
1986 void SystemDictionary::classes_do(void f(Klass*, TRAPS), TRAPS) {
1987   dictionary()->classes_do(f, CHECK);
1988 }
1989 
1990 //   All classes, and their class loaders
1991 // Don't iterate over placeholders
1992 void SystemDictionary::classes_do(void f(Klass*, ClassLoaderData*)) {
1993   dictionary()->classes_do(f);
1994 }
1995 
1996 void SystemDictionary::placeholders_do(void f(Symbol*)) {
1997   placeholders()->entries_do(f);
1998 }
1999 
2000 void SystemDictionary::methods_do(void f(Method*)) {
2001   dictionary()->methods_do(f);
2002   invoke_method_table()->methods_do(f);
2003 }
2004 
2005 void SystemDictionary::remove_classes_in_error_state() {
2006   dictionary()->remove_classes_in_error_state();
2007 }
2008 
2009 // ----------------------------------------------------------------------------
2010 // Lazily load klasses
2011 
2012 void SystemDictionary::load_abstract_ownable_synchronizer_klass(TRAPS) {
2013   // if multiple threads calling this function, only one thread will load
2014   // the class.  The other threads will find the loaded version once the
2015   // class is loaded.
2016   Klass* aos = _abstract_ownable_synchronizer_klass;
2017   if (aos == NULL) {
2018     Klass* k = resolve_or_fail(vmSymbols::java_util_concurrent_locks_AbstractOwnableSynchronizer(), true, CHECK);
2019     // Force a fence to prevent any read before the write completes
2020     OrderAccess::fence();
2021     _abstract_ownable_synchronizer_klass = InstanceKlass::cast(k);
2022   }
2023 }
2024 
2025 // ----------------------------------------------------------------------------
2026 // Initialization
2027 
2028 void SystemDictionary::initialize(TRAPS) {
2029   // Allocate arrays
2030   assert(dictionary() == NULL,
2031          "SystemDictionary should only be initialized once");
2032   _sdgeneration        = 0;
2033   _dictionary          = new Dictionary(calculate_systemdictionary_size(PredictedLoadedClassCount));
2034   _placeholders        = new PlaceholderTable(_nof_buckets);
2035   _number_of_modifications = 0;
2036   _loader_constraints  = new LoaderConstraintTable(_loader_constraint_size);
2037   _resolution_errors   = new ResolutionErrorTable(_resolution_error_size);
2038   _invoke_method_table = new SymbolPropertyTable(_invoke_method_size);
2039 
2040   // Allocate private object used as system class loader lock
2041   _system_loader_lock_obj = oopFactory::new_intArray(0, CHECK);
2042   // Initialize basic classes
2043   initialize_preloaded_classes(CHECK);
2044 }
2045 
2046 // Compact table of directions on the initialization of klasses:
2047 static const short wk_init_info[] = {
2048   #define WK_KLASS_INIT_INFO(name, symbol, option) \
2049     ( ((int)vmSymbols::VM_SYMBOL_ENUM_NAME(symbol) \
2050           << SystemDictionary::CEIL_LG_OPTION_LIMIT) \
2051       | (int)SystemDictionary::option ),
2052   WK_KLASSES_DO(WK_KLASS_INIT_INFO)
2053   #undef WK_KLASS_INIT_INFO
2054   0
2055 };
2056 
2057 bool SystemDictionary::initialize_wk_klass(WKID id, int init_opt, TRAPS) {
2058   assert(id >= (int)FIRST_WKID && id < (int)WKID_LIMIT, "oob");
2059   int  info = wk_init_info[id - FIRST_WKID];
2060   int  sid  = (info >> CEIL_LG_OPTION_LIMIT);
2061   Symbol* symbol = vmSymbols::symbol_at((vmSymbols::SID)sid);
2062   InstanceKlass** klassp = &_well_known_klasses[id];
2063 
2064   bool must_load;
2065 #if INCLUDE_JVMCI
2066   if (EnableJVMCI) {
2067     // If JVMCI is enabled we require its classes to be found.
2068     must_load = (init_opt < SystemDictionary::Opt) || (init_opt == SystemDictionary::Jvmci);
2069   } else
2070 #endif
2071   {
2072     must_load = (init_opt < SystemDictionary::Opt);
2073   }
2074 
2075   if ((*klassp) == NULL) {
2076     Klass* k;
2077     if (must_load) {
2078       k = resolve_or_fail(symbol, true, CHECK_0); // load required class
2079     } else {
2080       k = resolve_or_null(symbol,       CHECK_0); // load optional klass
2081     }
2082     (*klassp) = (k == NULL) ? NULL : InstanceKlass::cast(k);
2083   }
2084   return ((*klassp) != NULL);
2085 }
2086 
2087 void SystemDictionary::initialize_wk_klasses_until(WKID limit_id, WKID &start_id, TRAPS) {
2088   assert((int)start_id <= (int)limit_id, "IDs are out of order!");
2089   for (int id = (int)start_id; id < (int)limit_id; id++) {
2090     assert(id >= (int)FIRST_WKID && id < (int)WKID_LIMIT, "oob");
2091     int info = wk_init_info[id - FIRST_WKID];
2092     int sid  = (info >> CEIL_LG_OPTION_LIMIT);
2093     int opt  = (info & right_n_bits(CEIL_LG_OPTION_LIMIT));
2094 
2095     initialize_wk_klass((WKID)id, opt, CHECK);
2096   }
2097 
2098   // move the starting value forward to the limit:
2099   start_id = limit_id;
2100 }
2101 
2102 void SystemDictionary::initialize_preloaded_classes(TRAPS) {
2103   assert(WK_KLASS(Object_klass) == NULL, "preloaded classes should only be initialized once");
2104 
2105   // Create the ModuleEntry for java.base.  This call needs to be done here,
2106   // after vmSymbols::initialize() is called but before any classes are pre-loaded.
2107   ClassLoader::classLoader_init2(CHECK);
2108 
2109   // Preload commonly used klasses
2110   WKID scan = FIRST_WKID;
2111   // first do Object, then String, Class
2112   if (UseSharedSpaces) {
2113     initialize_wk_klasses_through(WK_KLASS_ENUM_NAME(Object_klass), scan, CHECK);
2114     // Initialize the constant pool for the Object_class
2115     InstanceKlass* ik = InstanceKlass::cast(Object_klass());
2116     ik->constants()->restore_unshareable_info(CHECK);
2117     initialize_wk_klasses_through(WK_KLASS_ENUM_NAME(Class_klass), scan, CHECK);
2118   } else {
2119     initialize_wk_klasses_through(WK_KLASS_ENUM_NAME(Class_klass), scan, CHECK);
2120   }
2121 
2122   // Calculate offsets for String and Class classes since they are loaded and
2123   // can be used after this point.
2124   java_lang_String::compute_offsets();
2125   java_lang_Class::compute_offsets();
2126 
2127   // Fixup mirrors for classes loaded before java.lang.Class.
2128   // These calls iterate over the objects currently in the perm gen
2129   // so calling them at this point is matters (not before when there
2130   // are fewer objects and not later after there are more objects
2131   // in the perm gen.
2132   Universe::initialize_basic_type_mirrors(CHECK);
2133   Universe::fixup_mirrors(CHECK);
2134 
2135   // do a bunch more:
2136   initialize_wk_klasses_through(WK_KLASS_ENUM_NAME(Reference_klass), scan, CHECK);
2137 
2138   // Preload ref klasses and set reference types
2139   InstanceKlass::cast(WK_KLASS(Reference_klass))->set_reference_type(REF_OTHER);
2140   InstanceRefKlass::update_nonstatic_oop_maps(WK_KLASS(Reference_klass));
2141 
2142   initialize_wk_klasses_through(WK_KLASS_ENUM_NAME(PhantomReference_klass), scan, CHECK);
2143   InstanceKlass::cast(WK_KLASS(SoftReference_klass))->set_reference_type(REF_SOFT);
2144   InstanceKlass::cast(WK_KLASS(WeakReference_klass))->set_reference_type(REF_WEAK);
2145   InstanceKlass::cast(WK_KLASS(FinalReference_klass))->set_reference_type(REF_FINAL);
2146   InstanceKlass::cast(WK_KLASS(PhantomReference_klass))->set_reference_type(REF_PHANTOM);
2147 
2148   // JSR 292 classes
2149   WKID jsr292_group_start = WK_KLASS_ENUM_NAME(MethodHandle_klass);
2150   WKID jsr292_group_end   = WK_KLASS_ENUM_NAME(VolatileCallSite_klass);
2151   initialize_wk_klasses_until(jsr292_group_start, scan, CHECK);
2152   initialize_wk_klasses_through(jsr292_group_end, scan, CHECK);
2153   initialize_wk_klasses_until(NOT_JVMCI(WKID_LIMIT) JVMCI_ONLY(FIRST_JVMCI_WKID), scan, CHECK);
2154 
2155   _box_klasses[T_BOOLEAN] = WK_KLASS(Boolean_klass);
2156   _box_klasses[T_CHAR]    = WK_KLASS(Character_klass);
2157   _box_klasses[T_FLOAT]   = WK_KLASS(Float_klass);
2158   _box_klasses[T_DOUBLE]  = WK_KLASS(Double_klass);
2159   _box_klasses[T_BYTE]    = WK_KLASS(Byte_klass);
2160   _box_klasses[T_SHORT]   = WK_KLASS(Short_klass);
2161   _box_klasses[T_INT]     = WK_KLASS(Integer_klass);
2162   _box_klasses[T_LONG]    = WK_KLASS(Long_klass);
2163   //_box_klasses[T_OBJECT]  = WK_KLASS(object_klass);
2164   //_box_klasses[T_ARRAY]   = WK_KLASS(object_klass);
2165 
2166   { // Compute whether we should use loadClass or loadClassInternal when loading classes.
2167     Method* method = InstanceKlass::cast(ClassLoader_klass())->find_method(vmSymbols::loadClassInternal_name(), vmSymbols::string_class_signature());
2168     _has_loadClassInternal = (method != NULL);
2169   }
2170   { // Compute whether we should use checkPackageAccess or NOT
2171     Method* method = InstanceKlass::cast(ClassLoader_klass())->find_method(vmSymbols::checkPackageAccess_name(), vmSymbols::class_protectiondomain_signature());
2172     _has_checkPackageAccess = (method != NULL);
2173   }
2174 }
2175 
2176 // Tells if a given klass is a box (wrapper class, such as java.lang.Integer).
2177 // If so, returns the basic type it holds.  If not, returns T_OBJECT.
2178 BasicType SystemDictionary::box_klass_type(Klass* k) {
2179   assert(k != NULL, "");
2180   for (int i = T_BOOLEAN; i < T_VOID+1; i++) {
2181     if (_box_klasses[i] == k)
2182       return (BasicType)i;
2183   }
2184   return T_OBJECT;
2185 }
2186 
2187 // Constraints on class loaders. The details of the algorithm can be
2188 // found in the OOPSLA'98 paper "Dynamic Class Loading in the Java
2189 // Virtual Machine" by Sheng Liang and Gilad Bracha.  The basic idea is
2190 // that the system dictionary needs to maintain a set of contraints that
2191 // must be satisfied by all classes in the dictionary.
2192 // if defining is true, then LinkageError if already in systemDictionary
2193 // if initiating loader, then ok if InstanceKlass matches existing entry
2194 
2195 void SystemDictionary::check_constraints(int d_index, unsigned int d_hash,
2196                                          instanceKlassHandle k,
2197                                          Handle class_loader, bool defining,
2198                                          TRAPS) {
2199   const char *linkage_error1 = NULL;
2200   const char *linkage_error2 = NULL;
2201   {
2202     Symbol*  name  = k->name();
2203     ClassLoaderData *loader_data = class_loader_data(class_loader);
2204 
2205     MutexLocker mu(SystemDictionary_lock, THREAD);
2206 
2207     Klass* check = find_class(d_index, d_hash, name, loader_data);
2208     if (check != (Klass*)NULL) {
2209       // if different InstanceKlass - duplicate class definition,
2210       // else - ok, class loaded by a different thread in parallel,
2211       // we should only have found it if it was done loading and ok to use
2212       // system dictionary only holds instance classes, placeholders
2213       // also holds array classes
2214 
2215       assert(check->is_instance_klass(), "noninstance in systemdictionary");
2216       if ((defining == true) || (k() != check)) {
2217         linkage_error1 = "loader (instance of  ";
2218         linkage_error2 = "): attempted  duplicate class definition for name: \"";
2219       } else {
2220         return;
2221       }
2222     }
2223 
2224 #ifdef ASSERT
2225     Symbol* ph_check = find_placeholder(name, loader_data);
2226     assert(ph_check == NULL || ph_check == name, "invalid symbol");
2227 #endif
2228 
2229     if (linkage_error1 == NULL) {
2230       if (constraints()->check_or_update(k, class_loader, name) == false) {
2231         linkage_error1 = "loader constraint violation: loader (instance of ";
2232         linkage_error2 = ") previously initiated loading for a different type with name \"";
2233       }
2234     }
2235   }
2236 
2237   // Throw error now if needed (cannot throw while holding
2238   // SystemDictionary_lock because of rank ordering)
2239 
2240   if (linkage_error1) {
2241     ResourceMark rm(THREAD);
2242     const char* class_loader_name = loader_name(class_loader());
2243     char* type_name = k->name()->as_C_string();
2244     size_t buflen = strlen(linkage_error1) + strlen(class_loader_name) +
2245       strlen(linkage_error2) + strlen(type_name) + 2; // +2 for '"' and null byte.
2246     char* buf = NEW_RESOURCE_ARRAY_IN_THREAD(THREAD, char, buflen);
2247     jio_snprintf(buf, buflen, "%s%s%s%s\"", linkage_error1, class_loader_name, linkage_error2, type_name);
2248     THROW_MSG(vmSymbols::java_lang_LinkageError(), buf);
2249   }
2250 }
2251 
2252 
2253 // Update system dictionary - done after check_constraint and add_to_hierachy
2254 // have been called.
2255 void SystemDictionary::update_dictionary(int d_index, unsigned int d_hash,
2256                                          int p_index, unsigned int p_hash,
2257                                          instanceKlassHandle k,
2258                                          Handle class_loader,
2259                                          TRAPS) {
2260   // Compile_lock prevents systemDictionary updates during compilations
2261   assert_locked_or_safepoint(Compile_lock);
2262   Symbol*  name  = k->name();
2263   ClassLoaderData *loader_data = class_loader_data(class_loader);
2264 
2265   {
2266   MutexLocker mu1(SystemDictionary_lock, THREAD);
2267 
2268   // See whether biased locking is enabled and if so set it for this
2269   // klass.
2270   // Note that this must be done past the last potential blocking
2271   // point / safepoint. We enable biased locking lazily using a
2272   // VM_Operation to iterate the SystemDictionary and installing the
2273   // biasable mark word into each InstanceKlass's prototype header.
2274   // To avoid race conditions where we accidentally miss enabling the
2275   // optimization for one class in the process of being added to the
2276   // dictionary, we must not safepoint after the test of
2277   // BiasedLocking::enabled().
2278   if (UseBiasedLocking && BiasedLocking::enabled()) {
2279     // Set biased locking bit for all loaded classes; it will be
2280     // cleared if revocation occurs too often for this type
2281     // NOTE that we must only do this when the class is initally
2282     // defined, not each time it is referenced from a new class loader
2283     if (k->class_loader() == class_loader()) {
2284       k->set_prototype_header(markOopDesc::biased_locking_prototype());
2285     }
2286   }
2287 
2288   // Make a new system dictionary entry.
2289   Klass* sd_check = find_class(d_index, d_hash, name, loader_data);
2290   if (sd_check == NULL) {
2291     dictionary()->add_klass(name, loader_data, k);
2292     notice_modification();
2293   }
2294 #ifdef ASSERT
2295   sd_check = find_class(d_index, d_hash, name, loader_data);
2296   assert (sd_check != NULL, "should have entry in system dictionary");
2297   // Note: there may be a placeholder entry: for circularity testing
2298   // or for parallel defines
2299 #endif
2300     SystemDictionary_lock->notify_all();
2301   }
2302 }
2303 
2304 
2305 // Try to find a class name using the loader constraints.  The
2306 // loader constraints might know about a class that isn't fully loaded
2307 // yet and these will be ignored.
2308 Klass* SystemDictionary::find_constrained_instance_or_array_klass(
2309                     Symbol* class_name, Handle class_loader, TRAPS) {
2310 
2311   // First see if it has been loaded directly.
2312   // Force the protection domain to be null.  (This removes protection checks.)
2313   Handle no_protection_domain;
2314   Klass* klass = find_instance_or_array_klass(class_name, class_loader,
2315                                               no_protection_domain, CHECK_NULL);
2316   if (klass != NULL)
2317     return klass;
2318 
2319   // Now look to see if it has been loaded elsewhere, and is subject to
2320   // a loader constraint that would require this loader to return the
2321   // klass that is already loaded.
2322   if (FieldType::is_array(class_name)) {
2323     // For array classes, their Klass*s are not kept in the
2324     // constraint table. The element Klass*s are.
2325     FieldArrayInfo fd;
2326     BasicType t = FieldType::get_array_info(class_name, fd, CHECK_(NULL));
2327     if (t != T_OBJECT) {
2328       klass = Universe::typeArrayKlassObj(t);
2329     } else {
2330       MutexLocker mu(SystemDictionary_lock, THREAD);
2331       klass = constraints()->find_constrained_klass(fd.object_key(), class_loader);
2332     }
2333     // If element class already loaded, allocate array klass
2334     if (klass != NULL) {
2335       klass = klass->array_klass_or_null(fd.dimension());
2336     }
2337   } else {
2338     MutexLocker mu(SystemDictionary_lock, THREAD);
2339     // Non-array classes are easy: simply check the constraint table.
2340     klass = constraints()->find_constrained_klass(class_name, class_loader);
2341   }
2342 
2343   return klass;
2344 }
2345 
2346 
2347 bool SystemDictionary::add_loader_constraint(Symbol* class_name,
2348                                              Handle class_loader1,
2349                                              Handle class_loader2,
2350                                              Thread* THREAD) {
2351   ClassLoaderData* loader_data1 = class_loader_data(class_loader1);
2352   ClassLoaderData* loader_data2 = class_loader_data(class_loader2);
2353 
2354   Symbol* constraint_name = NULL;
2355   if (!FieldType::is_array(class_name)) {
2356     constraint_name = class_name;
2357   } else {
2358     // For array classes, their Klass*s are not kept in the
2359     // constraint table. The element classes are.
2360     FieldArrayInfo fd;
2361     BasicType t = FieldType::get_array_info(class_name, fd, CHECK_(false));
2362     // primitive types always pass
2363     if (t != T_OBJECT) {
2364       return true;
2365     } else {
2366       constraint_name = fd.object_key();
2367     }
2368   }
2369   unsigned int d_hash1 = dictionary()->compute_hash(constraint_name, loader_data1);
2370   int d_index1 = dictionary()->hash_to_index(d_hash1);
2371 
2372   unsigned int d_hash2 = dictionary()->compute_hash(constraint_name, loader_data2);
2373   int d_index2 = dictionary()->hash_to_index(d_hash2);
2374   {
2375   MutexLocker mu_s(SystemDictionary_lock, THREAD);
2376 
2377   // Better never do a GC while we're holding these oops
2378   NoSafepointVerifier nosafepoint;
2379 
2380   Klass* klass1 = find_class(d_index1, d_hash1, constraint_name, loader_data1);
2381   Klass* klass2 = find_class(d_index2, d_hash2, constraint_name, loader_data2);
2382   return constraints()->add_entry(constraint_name, klass1, class_loader1,
2383                                   klass2, class_loader2);
2384   }
2385 }
2386 
2387 // Add entry to resolution error table to record the error when the first
2388 // attempt to resolve a reference to a class has failed.
2389 void SystemDictionary::add_resolution_error(const constantPoolHandle& pool, int which,
2390                                             Symbol* error, Symbol* message) {
2391   unsigned int hash = resolution_errors()->compute_hash(pool, which);
2392   int index = resolution_errors()->hash_to_index(hash);
2393   {
2394     MutexLocker ml(SystemDictionary_lock, Thread::current());
2395     resolution_errors()->add_entry(index, hash, pool, which, error, message);
2396   }
2397 }
2398 
2399 // Delete a resolution error for RedefineClasses for a constant pool is going away
2400 void SystemDictionary::delete_resolution_error(ConstantPool* pool) {
2401   resolution_errors()->delete_entry(pool);
2402 }
2403 
2404 // Lookup resolution error table. Returns error if found, otherwise NULL.
2405 Symbol* SystemDictionary::find_resolution_error(const constantPoolHandle& pool, int which,
2406                                                 Symbol** message) {
2407   unsigned int hash = resolution_errors()->compute_hash(pool, which);
2408   int index = resolution_errors()->hash_to_index(hash);
2409   {
2410     MutexLocker ml(SystemDictionary_lock, Thread::current());
2411     ResolutionErrorEntry* entry = resolution_errors()->find_entry(index, hash, pool, which);
2412     if (entry != NULL) {
2413       *message = entry->message();
2414       return entry->error();
2415     } else {
2416       return NULL;
2417     }
2418   }
2419 }
2420 
2421 
2422 // Signature constraints ensure that callers and callees agree about
2423 // the meaning of type names in their signatures.  This routine is the
2424 // intake for constraints.  It collects them from several places:
2425 //
2426 //  * LinkResolver::resolve_method (if check_access is true) requires
2427 //    that the resolving class (the caller) and the defining class of
2428 //    the resolved method (the callee) agree on each type in the
2429 //    method's signature.
2430 //
2431 //  * LinkResolver::resolve_interface_method performs exactly the same
2432 //    checks.
2433 //
2434 //  * LinkResolver::resolve_field requires that the constant pool
2435 //    attempting to link to a field agree with the field's defining
2436 //    class about the type of the field signature.
2437 //
2438 //  * klassVtable::initialize_vtable requires that, when a class
2439 //    overrides a vtable entry allocated by a superclass, that the
2440 //    overriding method (i.e., the callee) agree with the superclass
2441 //    on each type in the method's signature.
2442 //
2443 //  * klassItable::initialize_itable requires that, when a class fills
2444 //    in its itables, for each non-abstract method installed in an
2445 //    itable, the method (i.e., the callee) agree with the interface
2446 //    on each type in the method's signature.
2447 //
2448 // All those methods have a boolean (check_access, checkconstraints)
2449 // which turns off the checks.  This is used from specialized contexts
2450 // such as bootstrapping, dumping, and debugging.
2451 //
2452 // No direct constraint is placed between the class and its
2453 // supertypes.  Constraints are only placed along linked relations
2454 // between callers and callees.  When a method overrides or implements
2455 // an abstract method in a supertype (superclass or interface), the
2456 // constraints are placed as if the supertype were the caller to the
2457 // overriding method.  (This works well, since callers to the
2458 // supertype have already established agreement between themselves and
2459 // the supertype.)  As a result of all this, a class can disagree with
2460 // its supertype about the meaning of a type name, as long as that
2461 // class neither calls a relevant method of the supertype, nor is
2462 // called (perhaps via an override) from the supertype.
2463 //
2464 //
2465 // SystemDictionary::check_signature_loaders(sig, l1, l2)
2466 //
2467 // Make sure all class components (including arrays) in the given
2468 // signature will be resolved to the same class in both loaders.
2469 // Returns the name of the type that failed a loader constraint check, or
2470 // NULL if no constraint failed.  No exception except OOME is thrown.
2471 // Arrays are not added to the loader constraint table, their elements are.
2472 Symbol* SystemDictionary::check_signature_loaders(Symbol* signature,
2473                                                Handle loader1, Handle loader2,
2474                                                bool is_method, TRAPS)  {
2475   // Nothing to do if loaders are the same.
2476   if (loader1() == loader2()) {
2477     return NULL;
2478   }
2479 
2480   SignatureStream sig_strm(signature, is_method);
2481   while (!sig_strm.is_done()) {
2482     if (sig_strm.is_object()) {
2483       Symbol* sig = sig_strm.as_symbol(CHECK_NULL);
2484       if (!add_loader_constraint(sig, loader1, loader2, THREAD)) {
2485         return sig;
2486       }
2487     }
2488     sig_strm.next();
2489   }
2490   return NULL;
2491 }
2492 
2493 
2494 methodHandle SystemDictionary::find_method_handle_intrinsic(vmIntrinsics::ID iid,
2495                                                             Symbol* signature,
2496                                                             TRAPS) {
2497   methodHandle empty;
2498   assert(MethodHandles::is_signature_polymorphic(iid) &&
2499          MethodHandles::is_signature_polymorphic_intrinsic(iid) &&
2500          iid != vmIntrinsics::_invokeGeneric,
2501          "must be a known MH intrinsic iid=%d: %s", iid, vmIntrinsics::name_at(iid));
2502 
2503   unsigned int hash  = invoke_method_table()->compute_hash(signature, iid);
2504   int          index = invoke_method_table()->hash_to_index(hash);
2505   SymbolPropertyEntry* spe = invoke_method_table()->find_entry(index, hash, signature, iid);
2506   methodHandle m;
2507   if (spe == NULL || spe->method() == NULL) {
2508     spe = NULL;
2509     // Must create lots of stuff here, but outside of the SystemDictionary lock.
2510     m = Method::make_method_handle_intrinsic(iid, signature, CHECK_(empty));
2511     if (!Arguments::is_interpreter_only()) {
2512       // Generate a compiled form of the MH intrinsic.
2513       AdapterHandlerLibrary::create_native_wrapper(m);
2514       // Check if have the compiled code.
2515       if (!m->has_compiled_code()) {
2516         THROW_MSG_(vmSymbols::java_lang_VirtualMachineError(),
2517                    "Out of space in CodeCache for method handle intrinsic", empty);
2518       }
2519     }
2520     // Now grab the lock.  We might have to throw away the new method,
2521     // if a racing thread has managed to install one at the same time.
2522     {
2523       MutexLocker ml(SystemDictionary_lock, THREAD);
2524       spe = invoke_method_table()->find_entry(index, hash, signature, iid);
2525       if (spe == NULL)
2526         spe = invoke_method_table()->add_entry(index, hash, signature, iid);
2527       if (spe->method() == NULL)
2528         spe->set_method(m());
2529     }
2530   }
2531 
2532   assert(spe != NULL && spe->method() != NULL, "");
2533   assert(Arguments::is_interpreter_only() || (spe->method()->has_compiled_code() &&
2534          spe->method()->code()->entry_point() == spe->method()->from_compiled_entry()),
2535          "MH intrinsic invariant");
2536   return spe->method();
2537 }
2538 
2539 // Helper for unpacking the return value from linkMethod and linkCallSite.
2540 static methodHandle unpack_method_and_appendix(Handle mname,
2541                                                KlassHandle accessing_klass,
2542                                                objArrayHandle appendix_box,
2543                                                Handle* appendix_result,
2544                                                TRAPS) {
2545   methodHandle empty;
2546   if (mname.not_null()) {
2547     Metadata* vmtarget = java_lang_invoke_MemberName::vmtarget(mname());
2548     if (vmtarget != NULL && vmtarget->is_method()) {
2549       Method* m = (Method*)vmtarget;
2550       oop appendix = appendix_box->obj_at(0);
2551       if (TraceMethodHandles) {
2552     #ifndef PRODUCT
2553         ttyLocker ttyl;
2554         tty->print("Linked method=" INTPTR_FORMAT ": ", p2i(m));
2555         m->print();
2556         if (appendix != NULL) { tty->print("appendix = "); appendix->print(); }
2557         tty->cr();
2558     #endif //PRODUCT
2559       }
2560       (*appendix_result) = Handle(THREAD, appendix);
2561       // the target is stored in the cpCache and if a reference to this
2562       // MethodName is dropped we need a way to make sure the
2563       // class_loader containing this method is kept alive.
2564       // FIXME: the appendix might also preserve this dependency.
2565       ClassLoaderData* this_key = InstanceKlass::cast(accessing_klass())->class_loader_data();
2566       this_key->record_dependency(m->method_holder(), CHECK_NULL); // Can throw OOM
2567       return methodHandle(THREAD, m);
2568     }
2569   }
2570   THROW_MSG_(vmSymbols::java_lang_LinkageError(), "bad value from MethodHandleNatives", empty);
2571   return empty;
2572 }
2573 
2574 methodHandle SystemDictionary::find_method_handle_invoker(KlassHandle klass,
2575                                                           Symbol* name,
2576                                                           Symbol* signature,
2577                                                           KlassHandle accessing_klass,
2578                                                           Handle *appendix_result,
2579                                                           Handle *method_type_result,
2580                                                           TRAPS) {
2581   methodHandle empty;
2582   assert(THREAD->can_call_java() ,"");
2583   Handle method_type =
2584     SystemDictionary::find_method_handle_type(signature, accessing_klass, CHECK_(empty));
2585 
2586   int ref_kind = JVM_REF_invokeVirtual;
2587   Handle name_str = StringTable::intern(name, CHECK_(empty));
2588   objArrayHandle appendix_box = oopFactory::new_objArray(SystemDictionary::Object_klass(), 1, CHECK_(empty));
2589   assert(appendix_box->obj_at(0) == NULL, "");
2590 
2591   // This should not happen.  JDK code should take care of that.
2592   if (accessing_klass.is_null() || method_type.is_null()) {
2593     THROW_MSG_(vmSymbols::java_lang_InternalError(), "bad invokehandle", empty);
2594   }
2595 
2596   // call java.lang.invoke.MethodHandleNatives::linkMethod(... String, MethodType) -> MemberName
2597   JavaCallArguments args;
2598   args.push_oop(accessing_klass()->java_mirror());
2599   args.push_int(ref_kind);
2600   args.push_oop(klass()->java_mirror());
2601   args.push_oop(name_str());
2602   args.push_oop(method_type());
2603   args.push_oop(appendix_box());
2604   JavaValue result(T_OBJECT);
2605   JavaCalls::call_static(&result,
2606                          SystemDictionary::MethodHandleNatives_klass(),
2607                          vmSymbols::linkMethod_name(),
2608                          vmSymbols::linkMethod_signature(),
2609                          &args, CHECK_(empty));
2610   Handle mname(THREAD, (oop) result.get_jobject());
2611   (*method_type_result) = method_type;
2612   return unpack_method_and_appendix(mname, accessing_klass, appendix_box, appendix_result, THREAD);
2613 }
2614 
2615 // Decide if we can globally cache a lookup of this class, to be returned to any client that asks.
2616 // We must ensure that all class loaders everywhere will reach this class, for any client.
2617 // This is a safe bet for public classes in java.lang, such as Object and String.
2618 // We also include public classes in java.lang.invoke, because they appear frequently in system-level method types.
2619 // Out of an abundance of caution, we do not include any other classes, not even for packages like java.util.
2620 static bool is_always_visible_class(oop mirror) {
2621   Klass* klass = java_lang_Class::as_Klass(mirror);
2622   if (klass->is_objArray_klass()) {
2623     klass = ObjArrayKlass::cast(klass)->bottom_klass(); // check element type
2624   }
2625   if (klass->is_typeArray_klass()) {
2626     return true; // primitive array
2627   }
2628   assert(klass->is_instance_klass(), "%s", klass->external_name());
2629   return klass->is_public() &&
2630          (InstanceKlass::cast(klass)->is_same_class_package(SystemDictionary::Object_klass()) ||       // java.lang
2631           InstanceKlass::cast(klass)->is_same_class_package(SystemDictionary::MethodHandle_klass()));  // java.lang.invoke
2632 }
2633 
2634 // Ask Java code to find or construct a java.lang.invoke.MethodType for the given
2635 // signature, as interpreted relative to the given class loader.
2636 // Because of class loader constraints, all method handle usage must be
2637 // consistent with this loader.
2638 Handle SystemDictionary::find_method_handle_type(Symbol* signature,
2639                                                  KlassHandle accessing_klass,
2640                                                  TRAPS) {
2641   Handle empty;
2642   vmIntrinsics::ID null_iid = vmIntrinsics::_none;  // distinct from all method handle invoker intrinsics
2643   unsigned int hash  = invoke_method_table()->compute_hash(signature, null_iid);
2644   int          index = invoke_method_table()->hash_to_index(hash);
2645   SymbolPropertyEntry* spe = invoke_method_table()->find_entry(index, hash, signature, null_iid);
2646   if (spe != NULL && spe->method_type() != NULL) {
2647     assert(java_lang_invoke_MethodType::is_instance(spe->method_type()), "");
2648     return Handle(THREAD, spe->method_type());
2649   } else if (!THREAD->can_call_java()) {
2650     warning("SystemDictionary::find_method_handle_type called from compiler thread");  // FIXME
2651     return Handle();  // do not attempt from within compiler, unless it was cached
2652   }
2653 
2654   Handle class_loader, protection_domain;
2655   if (accessing_klass.not_null()) {
2656     class_loader      = Handle(THREAD, InstanceKlass::cast(accessing_klass())->class_loader());
2657     protection_domain = Handle(THREAD, InstanceKlass::cast(accessing_klass())->protection_domain());
2658   }
2659   bool can_be_cached = true;
2660   int npts = ArgumentCount(signature).size();
2661   objArrayHandle pts = oopFactory::new_objArray(SystemDictionary::Class_klass(), npts, CHECK_(empty));
2662   int arg = 0;
2663   Handle rt; // the return type from the signature
2664   ResourceMark rm(THREAD);
2665   for (SignatureStream ss(signature); !ss.is_done(); ss.next()) {
2666     oop mirror = NULL;
2667     if (can_be_cached) {
2668       // Use neutral class loader to lookup candidate classes to be placed in the cache.
2669       mirror = ss.as_java_mirror(Handle(), Handle(),
2670                                  SignatureStream::ReturnNull, CHECK_(empty));
2671       if (mirror == NULL || (ss.is_object() && !is_always_visible_class(mirror))) {
2672         // Fall back to accessing_klass context.
2673         can_be_cached = false;
2674       }
2675     }
2676     if (!can_be_cached) {
2677       // Resolve, throwing a real error if it doesn't work.
2678       mirror = ss.as_java_mirror(class_loader, protection_domain,
2679                                  SignatureStream::NCDFError, CHECK_(empty));
2680     }
2681     assert(!oopDesc::is_null(mirror), "%s", ss.as_symbol(THREAD)->as_C_string());
2682     if (ss.at_return_type())
2683       rt = Handle(THREAD, mirror);
2684     else
2685       pts->obj_at_put(arg++, mirror);
2686 
2687     // Check accessibility.
2688     if (ss.is_object() && accessing_klass.not_null()) {
2689       Klass* sel_klass = java_lang_Class::as_Klass(mirror);
2690       mirror = NULL;  // safety
2691       // Emulate ConstantPool::verify_constant_pool_resolve.
2692       if (sel_klass->is_objArray_klass())
2693         sel_klass = ObjArrayKlass::cast(sel_klass)->bottom_klass();
2694       if (sel_klass->is_instance_klass()) {
2695         KlassHandle sel_kh(THREAD, sel_klass);
2696         LinkResolver::check_klass_accessability(accessing_klass, sel_kh, CHECK_(empty));
2697       }
2698     }
2699   }
2700   assert(arg == npts, "");
2701 
2702   // call java.lang.invoke.MethodHandleNatives::findMethodHandleType(Class rt, Class[] pts) -> MethodType
2703   JavaCallArguments args(Handle(THREAD, rt()));
2704   args.push_oop(pts());
2705   JavaValue result(T_OBJECT);
2706   JavaCalls::call_static(&result,
2707                          SystemDictionary::MethodHandleNatives_klass(),
2708                          vmSymbols::findMethodHandleType_name(),
2709                          vmSymbols::findMethodHandleType_signature(),
2710                          &args, CHECK_(empty));
2711   Handle method_type(THREAD, (oop) result.get_jobject());
2712 
2713   if (can_be_cached) {
2714     // We can cache this MethodType inside the JVM.
2715     MutexLocker ml(SystemDictionary_lock, THREAD);
2716     spe = invoke_method_table()->find_entry(index, hash, signature, null_iid);
2717     if (spe == NULL)
2718       spe = invoke_method_table()->add_entry(index, hash, signature, null_iid);
2719     if (spe->method_type() == NULL) {
2720       spe->set_method_type(method_type());
2721     }
2722   }
2723 
2724   // report back to the caller with the MethodType
2725   return method_type;
2726 }
2727 
2728 // Ask Java code to find or construct a method handle constant.
2729 Handle SystemDictionary::link_method_handle_constant(KlassHandle caller,
2730                                                      int ref_kind, //e.g., JVM_REF_invokeVirtual
2731                                                      KlassHandle callee,
2732                                                      Symbol* name_sym,
2733                                                      Symbol* signature,
2734                                                      TRAPS) {
2735   Handle empty;
2736   Handle name = java_lang_String::create_from_symbol(name_sym, CHECK_(empty));
2737   Handle type;
2738   if (signature->utf8_length() > 0 && signature->byte_at(0) == '(') {
2739     type = find_method_handle_type(signature, caller, CHECK_(empty));
2740   } else if (caller.is_null()) {
2741     // This should not happen.  JDK code should take care of that.
2742     THROW_MSG_(vmSymbols::java_lang_InternalError(), "bad MH constant", empty);
2743   } else {
2744     ResourceMark rm(THREAD);
2745     SignatureStream ss(signature, false);
2746     if (!ss.is_done()) {
2747       oop mirror = ss.as_java_mirror(caller->class_loader(), caller->protection_domain(),
2748                                      SignatureStream::NCDFError, CHECK_(empty));
2749       type = Handle(THREAD, mirror);
2750       ss.next();
2751       if (!ss.is_done())  type = Handle();  // error!
2752     }
2753   }
2754   if (type.is_null()) {
2755     THROW_MSG_(vmSymbols::java_lang_LinkageError(), "bad signature", empty);
2756   }
2757 
2758   // call java.lang.invoke.MethodHandleNatives::linkMethodHandleConstant(Class caller, int refKind, Class callee, String name, Object type) -> MethodHandle
2759   JavaCallArguments args;
2760   args.push_oop(caller->java_mirror());  // the referring class
2761   args.push_int(ref_kind);
2762   args.push_oop(callee->java_mirror());  // the target class
2763   args.push_oop(name());
2764   args.push_oop(type());
2765   JavaValue result(T_OBJECT);
2766   JavaCalls::call_static(&result,
2767                          SystemDictionary::MethodHandleNatives_klass(),
2768                          vmSymbols::linkMethodHandleConstant_name(),
2769                          vmSymbols::linkMethodHandleConstant_signature(),
2770                          &args, CHECK_(empty));
2771   return Handle(THREAD, (oop) result.get_jobject());
2772 }
2773 
2774 // Ask Java code to find or construct a java.lang.invoke.CallSite for the given
2775 // name and signature, as interpreted relative to the given class loader.
2776 methodHandle SystemDictionary::find_dynamic_call_site_invoker(KlassHandle caller,
2777                                                               Handle bootstrap_specifier,
2778                                                               Symbol* name,
2779                                                               Symbol* type,
2780                                                               Handle *appendix_result,
2781                                                               Handle *method_type_result,
2782                                                               TRAPS) {
2783   methodHandle empty;
2784   Handle bsm, info;
2785   if (java_lang_invoke_MethodHandle::is_instance(bootstrap_specifier())) {
2786     bsm = bootstrap_specifier;
2787   } else {
2788     assert(bootstrap_specifier->is_objArray(), "");
2789     objArrayHandle args(THREAD, (objArrayOop) bootstrap_specifier());
2790     int len = args->length();
2791     assert(len >= 1, "");
2792     bsm = Handle(THREAD, args->obj_at(0));
2793     if (len > 1) {
2794       objArrayOop args1 = oopFactory::new_objArray(SystemDictionary::Object_klass(), len-1, CHECK_(empty));
2795       for (int i = 1; i < len; i++)
2796         args1->obj_at_put(i-1, args->obj_at(i));
2797       info = Handle(THREAD, args1);
2798     }
2799   }
2800   guarantee(java_lang_invoke_MethodHandle::is_instance(bsm()),
2801             "caller must supply a valid BSM");
2802 
2803   Handle method_name = java_lang_String::create_from_symbol(name, CHECK_(empty));
2804   Handle method_type = find_method_handle_type(type, caller, CHECK_(empty));
2805 
2806   // This should not happen.  JDK code should take care of that.
2807   if (caller.is_null() || method_type.is_null()) {
2808     THROW_MSG_(vmSymbols::java_lang_InternalError(), "bad invokedynamic", empty);
2809   }
2810 
2811   objArrayHandle appendix_box = oopFactory::new_objArray(SystemDictionary::Object_klass(), 1, CHECK_(empty));
2812   assert(appendix_box->obj_at(0) == NULL, "");
2813 
2814   // call java.lang.invoke.MethodHandleNatives::linkCallSite(caller, bsm, name, mtype, info, &appendix)
2815   JavaCallArguments args;
2816   args.push_oop(caller->java_mirror());
2817   args.push_oop(bsm());
2818   args.push_oop(method_name());
2819   args.push_oop(method_type());
2820   args.push_oop(info());
2821   args.push_oop(appendix_box);
2822   JavaValue result(T_OBJECT);
2823   JavaCalls::call_static(&result,
2824                          SystemDictionary::MethodHandleNatives_klass(),
2825                          vmSymbols::linkCallSite_name(),
2826                          vmSymbols::linkCallSite_signature(),
2827                          &args, CHECK_(empty));
2828   Handle mname(THREAD, (oop) result.get_jobject());
2829   (*method_type_result) = method_type;
2830   return unpack_method_and_appendix(mname, caller, appendix_box, appendix_result, THREAD);
2831 }
2832 
2833 // Since the identity hash code for symbols changes when the symbols are
2834 // moved from the regular perm gen (hash in the mark word) to the shared
2835 // spaces (hash is the address), the classes loaded into the dictionary
2836 // may be in the wrong buckets.
2837 
2838 void SystemDictionary::reorder_dictionary() {
2839   dictionary()->reorder_dictionary();
2840 }
2841 
2842 
2843 void SystemDictionary::copy_buckets(char** top, char* end) {
2844   dictionary()->copy_buckets(top, end);
2845 }
2846 
2847 
2848 void SystemDictionary::copy_table(char** top, char* end) {
2849   dictionary()->copy_table(top, end);
2850 }
2851 
2852 
2853 void SystemDictionary::reverse() {
2854   dictionary()->reverse();
2855 }
2856 
2857 int SystemDictionary::number_of_classes() {
2858   return dictionary()->number_of_entries();
2859 }
2860 
2861 
2862 // ----------------------------------------------------------------------------
2863 void SystemDictionary::print_shared(bool details) {
2864   shared_dictionary()->print(details);
2865 }
2866 
2867 void SystemDictionary::print(bool details) {
2868   dictionary()->print(details);
2869 
2870   // Placeholders
2871   GCMutexLocker mu(SystemDictionary_lock);
2872   placeholders()->print();
2873 
2874   // loader constraints - print under SD_lock
2875   constraints()->print();
2876 }
2877 
2878 
2879 void SystemDictionary::verify() {
2880   guarantee(dictionary() != NULL, "Verify of system dictionary failed");
2881   guarantee(constraints() != NULL,
2882             "Verify of loader constraints failed");
2883   guarantee(dictionary()->number_of_entries() >= 0 &&
2884             placeholders()->number_of_entries() >= 0,
2885             "Verify of system dictionary failed");
2886 
2887   // Verify dictionary
2888   dictionary()->verify();
2889 
2890   GCMutexLocker mu(SystemDictionary_lock);
2891   placeholders()->verify();
2892 
2893   // Verify constraint table
2894   guarantee(constraints() != NULL, "Verify of loader constraints failed");
2895   constraints()->verify(dictionary(), placeholders());
2896 }
2897 
2898 // caller needs ResourceMark
2899 const char* SystemDictionary::loader_name(const oop loader) {
2900   return ((loader) == NULL ? "<bootloader>" :
2901           InstanceKlass::cast((loader)->klass())->name()->as_C_string());
2902 }
2903 
2904 // caller needs ResourceMark
2905 const char* SystemDictionary::loader_name(const ClassLoaderData* loader_data) {
2906   return (loader_data->class_loader() == NULL ? "<bootloader>" :
2907           SystemDictionary::loader_name(loader_data->class_loader()));
2908 }