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