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