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