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