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