1 #ifdef USE_PRAGMA_IDENT_SRC
   2 #pragma ident "@(#)systemDictionary.cpp 1.367 08/01/17 09:41:11 JVM"
   3 #endif
   4 /*
   5  * Copyright 1997-2007 Sun Microsystems, Inc.  All Rights Reserved.
   6  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   7  *
   8  * This code is free software; you can redistribute it and/or modify it
   9  * under the terms of the GNU General Public License version 2 only, as
  10  * published by the Free Software Foundation.
  11  *
  12  * This code is distributed in the hope that it will be useful, but WITHOUT
  13  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  14  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  15  * version 2 for more details (a copy is included in the LICENSE file that
  16  * accompanied this code).
  17  *
  18  * You should have received a copy of the GNU General Public License version
  19  * 2 along with this work; if not, write to the Free Software Foundation,
  20  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  21  *
  22  * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
  23  * CA 95054 USA or visit www.sun.com if you need additional information or
  24  * have any questions.
  25  *  
  26  */
  27 
  28 # include "incls/_precompiled.incl"
  29 # include "incls/_systemDictionary.cpp.incl"
  30 
  31 
  32 Dictionary*       SystemDictionary::_dictionary = NULL;
  33 PlaceholderTable* SystemDictionary::_placeholders = NULL;
  34 Dictionary*       SystemDictionary::_shared_dictionary = NULL;
  35 LoaderConstraintTable* SystemDictionary::_loader_constraints = NULL;
  36 ResolutionErrorTable* SystemDictionary::_resolution_errors = NULL;
  37 
  38 
  39 int         SystemDictionary::_number_of_modifications = 0;
  40 
  41 oop         SystemDictionary::_system_loader_lock_obj     =  NULL;
  42 
  43 klassOop    SystemDictionary::_object_klass               =  NULL;
  44 klassOop    SystemDictionary::_string_klass               =  NULL;
  45 klassOop    SystemDictionary::_class_klass                =  NULL;
  46 klassOop    SystemDictionary::_cloneable_klass            =  NULL;
  47 klassOop    SystemDictionary::_classloader_klass          =  NULL;
  48 klassOop    SystemDictionary::_serializable_klass         =  NULL;
  49 klassOop    SystemDictionary::_system_klass               =  NULL;
  50 
  51 klassOop    SystemDictionary::_throwable_klass            =  NULL;
  52 klassOop    SystemDictionary::_error_klass                =  NULL;
  53 klassOop    SystemDictionary::_threaddeath_klass          =  NULL;
  54 klassOop    SystemDictionary::_exception_klass            =  NULL;
  55 klassOop    SystemDictionary::_runtime_exception_klass    =  NULL;
  56 klassOop    SystemDictionary::_classNotFoundException_klass = NULL;
  57 klassOop    SystemDictionary::_noClassDefFoundError_klass = NULL;
  58 klassOop    SystemDictionary::_linkageError_klass         = NULL;
  59 klassOop    SystemDictionary::_classCastException_klass   =  NULL;
  60 klassOop    SystemDictionary::_arrayStoreException_klass  =  NULL;
  61 klassOop    SystemDictionary::_virtualMachineError_klass  =  NULL;
  62 klassOop    SystemDictionary::_outOfMemoryError_klass     =  NULL;
  63 klassOop    SystemDictionary::_StackOverflowError_klass   =  NULL;
  64 klassOop    SystemDictionary::_illegalMonitorStateException_klass   =  NULL;
  65 klassOop    SystemDictionary::_protectionDomain_klass     =  NULL;
  66 klassOop    SystemDictionary::_AccessControlContext_klass = NULL;
  67 
  68 klassOop    SystemDictionary::_reference_klass            =  NULL;
  69 klassOop    SystemDictionary::_soft_reference_klass       =  NULL;
  70 klassOop    SystemDictionary::_weak_reference_klass       =  NULL;
  71 klassOop    SystemDictionary::_final_reference_klass      =  NULL;
  72 klassOop    SystemDictionary::_phantom_reference_klass    =  NULL;
  73 klassOop    SystemDictionary::_finalizer_klass            =  NULL;
  74 
  75 klassOop    SystemDictionary::_thread_klass               =  NULL;
  76 klassOop    SystemDictionary::_threadGroup_klass          =  NULL;
  77 klassOop    SystemDictionary::_properties_klass           =  NULL;
  78 klassOop    SystemDictionary::_reflect_accessible_object_klass =  NULL;
  79 klassOop    SystemDictionary::_reflect_field_klass        =  NULL;
  80 klassOop    SystemDictionary::_reflect_method_klass       =  NULL;
  81 klassOop    SystemDictionary::_reflect_constructor_klass  =  NULL;
  82 klassOop    SystemDictionary::_reflect_magic_klass        =  NULL;
  83 klassOop    SystemDictionary::_reflect_method_accessor_klass = NULL;
  84 klassOop    SystemDictionary::_reflect_constructor_accessor_klass = NULL;
  85 klassOop    SystemDictionary::_reflect_delegating_classloader_klass = NULL;
  86 klassOop    SystemDictionary::_reflect_constant_pool_klass =  NULL;
  87 klassOop    SystemDictionary::_reflect_unsafe_static_field_accessor_impl_klass = NULL;
  88 
  89 klassOop    SystemDictionary::_vector_klass               =  NULL;
  90 klassOop    SystemDictionary::_hashtable_klass            =  NULL;
  91 klassOop    SystemDictionary::_stringBuffer_klass         =  NULL;
  92 
  93 klassOop    SystemDictionary::_stackTraceElement_klass    =  NULL;
  94 
  95 klassOop    SystemDictionary::_java_nio_Buffer_klass      =  NULL;
  96 
  97 klassOop    SystemDictionary::_sun_misc_AtomicLongCSImpl_klass = NULL;
  98 klassOop    SystemDictionary::_sun_jkernel_DownloadManager_klass  = NULL;
  99 
 100 klassOop    SystemDictionary::_boolean_klass              =  NULL;
 101 klassOop    SystemDictionary::_char_klass                 =  NULL;
 102 klassOop    SystemDictionary::_float_klass                =  NULL;
 103 klassOop    SystemDictionary::_double_klass               =  NULL;
 104 klassOop    SystemDictionary::_byte_klass                 =  NULL;
 105 klassOop    SystemDictionary::_short_klass                =  NULL;
 106 klassOop    SystemDictionary::_int_klass                  =  NULL;
 107 klassOop    SystemDictionary::_long_klass                 =  NULL;
 108 klassOop    SystemDictionary::_box_klasses[T_VOID+1]      =  { NULL /*, NULL...*/ };
 109 
 110 oop         SystemDictionary::_java_system_loader         =  NULL;
 111 
 112 bool        SystemDictionary::_has_loadClassInternal      =  false;
 113 bool        SystemDictionary::_has_checkPackageAccess     =  false;
 114 
 115 // lazily initialized klass variables
 116 volatile klassOop    SystemDictionary::_abstract_ownable_synchronizer_klass = NULL;
 117 
 118 
 119 // ----------------------------------------------------------------------------
 120 // Java-level SystemLoader
 121 
 122 oop SystemDictionary::java_system_loader() {
 123   return _java_system_loader;
 124 }
 125 
 126 void SystemDictionary::compute_java_system_loader(TRAPS) {
 127   KlassHandle system_klass(THREAD, _classloader_klass);    
 128   JavaValue result(T_OBJECT);
 129   JavaCalls::call_static(&result, 
 130                          KlassHandle(THREAD, _classloader_klass),
 131                          vmSymbolHandles::getSystemClassLoader_name(),
 132                          vmSymbolHandles::void_classloader_signature(),
 133                          CHECK);
 134     
 135   _java_system_loader = (oop)result.get_jobject();    
 136 }
 137 
 138 
 139 // ----------------------------------------------------------------------------
 140 // debugging
 141 
 142 #ifdef ASSERT
 143 
 144 // return true if class_name contains no '.' (internal format is '/')
 145 bool SystemDictionary::is_internal_format(symbolHandle class_name) {
 146   if (class_name.not_null()) {
 147     ResourceMark rm;
 148     char* name = class_name->as_C_string();
 149     return strchr(name, '.') == NULL;
 150   } else {
 151     return true;
 152   }
 153 }
 154 
 155 #endif
 156 
 157 // ----------------------------------------------------------------------------
 158 // Resolving of classes
 159 
 160 // Forwards to resolve_or_null
 161 
 162 klassOop SystemDictionary::resolve_or_fail(symbolHandle class_name, Handle class_loader, Handle protection_domain, bool throw_error, TRAPS) {  
 163   klassOop klass = resolve_or_null(class_name, class_loader, protection_domain, THREAD);
 164   if (HAS_PENDING_EXCEPTION || klass == NULL) {
 165     KlassHandle k_h(THREAD, klass);
 166     // can return a null klass
 167     klass = handle_resolution_exception(class_name, class_loader, protection_domain, throw_error, k_h, THREAD);
 168   }
 169   return klass;
 170 }
 171 
 172 klassOop SystemDictionary::handle_resolution_exception(symbolHandle class_name, Handle class_loader, Handle protection_domain, bool throw_error, KlassHandle klass_h, TRAPS) {
 173   if (HAS_PENDING_EXCEPTION) {
 174     // If we have a pending exception we forward it to the caller, unless throw_error is true,
 175     // in which case we have to check whether the pending exception is a ClassNotFoundException,
 176     // and if so convert it to a NoClassDefFoundError
 177     // And chain the original ClassNotFoundException
 178     if (throw_error && PENDING_EXCEPTION->is_a(SystemDictionary::classNotFoundException_klass())) {
 179       ResourceMark rm(THREAD);
 180       assert(klass_h() == NULL, "Should not have result with exception pending");
 181       Handle e(THREAD, PENDING_EXCEPTION);
 182       CLEAR_PENDING_EXCEPTION;
 183       THROW_MSG_CAUSE_0(vmSymbols::java_lang_NoClassDefFoundError(), class_name->as_C_string(), e);
 184     } else {
 185       return NULL; 
 186     }
 187   }
 188   // Class not found, throw appropriate error or exception depending on value of throw_error
 189   if (klass_h() == NULL) {
 190     ResourceMark rm(THREAD);
 191     if (throw_error) {
 192       THROW_MSG_0(vmSymbols::java_lang_NoClassDefFoundError(), class_name->as_C_string());
 193     } else {      
 194       THROW_MSG_0(vmSymbols::java_lang_ClassNotFoundException(), class_name->as_C_string());      
 195     }
 196   }
 197   return (klassOop)klass_h(); 
 198 }
 199 
 200 
 201 klassOop SystemDictionary::resolve_or_fail(symbolHandle class_name,
 202                                            bool throw_error, TRAPS)
 203 {
 204   return resolve_or_fail(class_name, Handle(), Handle(), throw_error, THREAD);
 205 }
 206 
 207 
 208 // Forwards to resolve_instance_class_or_null
 209 
 210 klassOop SystemDictionary::resolve_or_null(symbolHandle class_name, Handle class_loader, Handle protection_domain, TRAPS) {  
 211   assert(!THREAD->is_Compiler_thread(), "Can not load classes with the Compiler thread");
 212   if (FieldType::is_array(class_name())) {
 213     return resolve_array_class_or_null(class_name, class_loader, protection_domain, CHECK_NULL);
 214   } else {
 215     return resolve_instance_class_or_null(class_name, class_loader, protection_domain, CHECK_NULL);
 216   }
 217 }
 218 
 219 klassOop SystemDictionary::resolve_or_null(symbolHandle class_name, TRAPS) {  
 220   return resolve_or_null(class_name, Handle(), Handle(), THREAD);
 221 }
 222 
 223 // Forwards to resolve_instance_class_or_null
 224 
 225 klassOop SystemDictionary::resolve_array_class_or_null(symbolHandle class_name,
 226                                                        Handle class_loader, 
 227                                                        Handle protection_domain,
 228                                                        TRAPS) {  
 229   assert(FieldType::is_array(class_name()), "must be array");
 230   jint dimension;
 231   symbolOop object_key;
 232   klassOop k = NULL;  
 233   // dimension and object_key are assigned as a side-effect of this call
 234   BasicType t = FieldType::get_array_info(class_name(), 
 235                                           &dimension, 
 236                                           &object_key, 
 237                                           CHECK_NULL);
 238 
 239   if (t == T_OBJECT) {
 240     symbolHandle h_key(THREAD, object_key);
 241     // naked oop "k" is OK here -- we assign back into it
 242     k = SystemDictionary::resolve_instance_class_or_null(h_key, 
 243                                                          class_loader, 
 244                                                          protection_domain, 
 245                                                          CHECK_NULL);
 246     if (k != NULL) {
 247       k = Klass::cast(k)->array_klass(dimension, CHECK_NULL);
 248     }
 249   } else {
 250     k = Universe::typeArrayKlassObj(t);
 251     k = typeArrayKlass::cast(k)->array_klass(dimension, CHECK_NULL);
 252   }
 253   return k;
 254 }
 255 
 256 
 257 // Must be called for any super-class or super-interface resolution
 258 // during class definition to allow class circularity checking
 259 // super-interface callers: 
 260 //    parse_interfaces - for defineClass & jvmtiRedefineClasses
 261 // super-class callers:
 262 //   ClassFileParser - for defineClass & jvmtiRedefineClasses
 263 //   load_shared_class - while loading a class from shared archive
 264 //   resolve_instance_class_or_fail:
 265 //      when resolving a class that has an existing placeholder with
 266 //      a saved superclass [i.e. a defineClass is currently in progress]
 267 //      if another thread is trying to resolve the class, it must do
 268 //      super-class checks on its own thread to catch class circularity
 269 // This last call is critical in class circularity checking for cases
 270 // where classloading is delegated to different threads and the
 271 // classloader lock is released.
 272 // Take the case: Base->Super->Base
 273 //   1. If thread T1 tries to do a defineClass of class Base
 274 //    resolve_super_or_fail creates placeholder: T1, Base (super Super)
 275 //   2. resolve_instance_class_or_null does not find SD or placeholder for Super
 276 //    so it tries to load Super
 277 //   3. If we load the class internally, or user classloader uses same thread
 278 //      loadClassFromxxx or defineClass via parseClassFile Super ...
 279 //      3.1 resolve_super_or_fail creates placeholder: T1, Super (super Base) 
 280 //      3.3 resolve_instance_class_or_null Base, finds placeholder for Base
 281 //      3.4 calls resolve_super_or_fail Base
 282 //      3.5 finds T1,Base -> throws class circularity
 283 //OR 4. If T2 tries to resolve Super via defineClass Super ...
 284 //      4.1 resolve_super_or_fail creates placeholder: T2, Super (super Base) 
 285 //      4.2 resolve_instance_class_or_null Base, finds placeholder for Base (super Super)
 286 //      4.3 calls resolve_super_or_fail Super in parallel on own thread T2
 287 //      4.4 finds T2, Super -> throws class circularity
 288 // Must be called, even if superclass is null, since this is
 289 // where the placeholder entry is created which claims this
 290 // thread is loading this class/classloader.
 291 klassOop SystemDictionary::resolve_super_or_fail(symbolHandle child_name,
 292                                                  symbolHandle class_name,
 293                                                  Handle class_loader,
 294                                                  Handle protection_domain,
 295                                                  bool is_superclass,
 296                                                  TRAPS) {
 297 
 298   // Double-check, if child class is already loaded, just return super-class,interface
 299   // Don't add a placedholder if already loaded, i.e. already in system dictionary
 300   // Make sure there's a placeholder for the *child* before resolving.
 301   // Used as a claim that this thread is currently loading superclass/classloader
 302   // Used here for ClassCircularity checks and also for heap verification
 303   // (every instanceKlass in the heap needs to be in the system dictionary
 304   // or have a placeholder).
 305   // Must check ClassCircularity before checking if super class is already loaded
 306   //
 307   // We might not already have a placeholder if this child_name was
 308   // first seen via resolve_from_stream (jni_DefineClass or JVM_DefineClass);
 309   // the name of the class might not be known until the stream is actually
 310   // parsed.
 311   // Bugs 4643874, 4715493
 312   // compute_hash can have a safepoint
 313 
 314   unsigned int d_hash = dictionary()->compute_hash(child_name, class_loader);
 315   int d_index = dictionary()->hash_to_index(d_hash);
 316   unsigned int p_hash = placeholders()->compute_hash(child_name, class_loader);
 317   int p_index = placeholders()->hash_to_index(p_hash);
 318   // can't throw error holding a lock
 319   bool child_already_loaded = false;
 320   bool throw_circularity_error = false;
 321   {
 322     MutexLocker mu(SystemDictionary_lock, THREAD);
 323     klassOop childk = find_class(d_index, d_hash, child_name, class_loader);
 324     klassOop quicksuperk;
 325     // to support // loading: if child done loading, just return superclass
 326     // if class_name, & class_loader don't match:
 327     // if initial define, SD update will give LinkageError
 328     // if redefine: compare_class_versions will give HIERARCHY_CHANGED
 329     // so we don't throw an exception here.
 330     // see: nsk redefclass014 & java.lang.instrument Instrument032
 331     if ((childk != NULL ) && (is_superclass) &&
 332        ((quicksuperk = instanceKlass::cast(childk)->super()) != NULL) &&
 333       
 334          ((Klass::cast(quicksuperk)->name() == class_name()) && 
 335             (Klass::cast(quicksuperk)->class_loader()  == class_loader()))) {
 336            return quicksuperk;
 337     } else {
 338       PlaceholderEntry* probe = placeholders()->get_entry(p_index, p_hash, child_name, class_loader);
 339       if (probe && probe->check_seen_thread(THREAD, PlaceholderTable::LOAD_SUPER)) {
 340           throw_circularity_error = true;
 341       } 
 342 
 343       // add placeholder entry even if error - callers will remove on error
 344       PlaceholderEntry* newprobe = placeholders()->find_and_add(p_index, p_hash, child_name, class_loader, PlaceholderTable::LOAD_SUPER, class_name, THREAD); 
 345       if (throw_circularity_error) {
 346          newprobe->remove_seen_thread(THREAD, PlaceholderTable::LOAD_SUPER);
 347       }
 348     }
 349   }
 350   if (throw_circularity_error) {
 351       ResourceMark rm(THREAD);
 352       THROW_MSG_0(vmSymbols::java_lang_ClassCircularityError(), child_name->as_C_string());
 353   }
 354 
 355 // java.lang.Object should have been found above
 356   assert(class_name() != NULL, "null super class for resolving");
 357   // Resolve the super class or interface, check results on return
 358   klassOop superk = NULL;
 359   superk = SystemDictionary::resolve_or_null(class_name,
 360                                                  class_loader,
 361                                                  protection_domain,
 362                                                  THREAD);
 363   
 364   KlassHandle superk_h(THREAD, superk);
 365   
 366   // Note: clean up of placeholders currently in callers of
 367   // resolve_super_or_fail - either at update_dictionary time
 368   // or on error 
 369   {
 370   MutexLocker mu(SystemDictionary_lock, THREAD);
 371    PlaceholderEntry* probe = placeholders()->get_entry(p_index, p_hash, child_name, class_loader);
 372    if (probe != NULL) {
 373       probe->remove_seen_thread(THREAD, PlaceholderTable::LOAD_SUPER);
 374    }
 375   }
 376   if (HAS_PENDING_EXCEPTION || superk_h() == NULL) {
 377     // can null superk
 378     superk_h = KlassHandle(THREAD, handle_resolution_exception(class_name, class_loader, protection_domain, true, superk_h, THREAD));
 379   }
 380 
 381   return superk_h();
 382 }
 383 
 384 
 385 void SystemDictionary::validate_protection_domain(instanceKlassHandle klass,
 386                                                   Handle class_loader,
 387                                                   Handle protection_domain,
 388                                                   TRAPS) {
 389   if(!has_checkPackageAccess()) return;
 390 
 391   // Now we have to call back to java to check if the initating class has access
 392   JavaValue result(T_VOID);
 393   if (TraceProtectionDomainVerification) {
 394     // Print out trace information
 395     tty->print_cr("Checking package access");
 396     tty->print(" - class loader:      "); class_loader()->print_value_on(tty);      tty->cr();
 397     tty->print(" - protection domain: "); protection_domain()->print_value_on(tty); tty->cr();
 398     tty->print(" - loading:           "); klass()->print_value_on(tty);             tty->cr();
 399   }
 400   
 401   assert(class_loader() != NULL, "should not have non-null protection domain for null classloader");
 402 
 403   KlassHandle system_loader(THREAD, SystemDictionary::classloader_klass());
 404   JavaCalls::call_special(&result,
 405                          class_loader,
 406                          system_loader,
 407                          vmSymbolHandles::checkPackageAccess_name(),
 408                          vmSymbolHandles::class_protectiondomain_signature(), 
 409                          Handle(THREAD, klass->java_mirror()),
 410                          protection_domain,
 411                          THREAD);
 412 
 413   if (TraceProtectionDomainVerification) {
 414     if (HAS_PENDING_EXCEPTION) {
 415       tty->print_cr(" -> DENIED !!!!!!!!!!!!!!!!!!!!!");
 416     } else {
 417      tty->print_cr(" -> granted");
 418     }
 419     tty->cr();
 420   }
 421 
 422   if (HAS_PENDING_EXCEPTION) return; 
 423     
 424   // If no exception has been thrown, we have validated the protection domain
 425   // Insert the protection domain of the initiating class into the set.
 426   {
 427     // We recalculate the entry here -- we've called out to java since
 428     // the last time it was calculated.
 429     symbolHandle kn(THREAD, klass->name());
 430     unsigned int d_hash = dictionary()->compute_hash(kn, class_loader);
 431     int d_index = dictionary()->hash_to_index(d_hash);
 432 
 433     MutexLocker mu(SystemDictionary_lock, THREAD);
 434     { 
 435       // Note that we have an entry, and entries can be deleted only during GC,
 436       // so we cannot allow GC to occur while we're holding this entry.
 437 
 438       // We're using a No_Safepoint_Verifier to catch any place where we
 439       // might potentially do a GC at all.
 440       // SystemDictionary::do_unloading() asserts that classes are only
 441       // unloaded at a safepoint.
 442       No_Safepoint_Verifier nosafepoint;
 443       dictionary()->add_protection_domain(d_index, d_hash, klass, class_loader,
 444                                           protection_domain, THREAD);
 445     }
 446   }
 447 }
 448 
 449 // We only get here if this thread finds that another thread
 450 // has already claimed the placeholder token for the current operation,
 451 // but that other thread either never owned or gave up the
 452 // object lock
 453 // Waits on SystemDictionary_lock to indicate placeholder table updated
 454 // On return, caller must recheck placeholder table state
 455 //
 456 // We only get here if 
 457 //  1) custom classLoader, i.e. not bootstrap classloader
 458 //  2) UnsyncloadClass not set
 459 //  3) custom classLoader has broken the class loader objectLock
 460 //     so another thread got here in parallel
 461 //
 462 // lockObject must be held. 
 463 // Complicated dance due to lock ordering:
 464 // Must first release the classloader object lock to
 465 // allow initial definer to complete the class definition
 466 // and to avoid deadlock
 467 // Reclaim classloader lock object with same original recursion count
 468 // Must release SystemDictionary_lock after notify, since
 469 // class loader lock must be claimed before SystemDictionary_lock
 470 // to prevent deadlocks
 471 //
 472 // The notify allows applications that did an untimed wait() on
 473 // the classloader object lock to not hang.
 474 void SystemDictionary::double_lock_wait(Handle lockObject, TRAPS) {
 475   assert_lock_strong(SystemDictionary_lock);
 476 
 477   bool calledholdinglock 
 478       = ObjectSynchronizer::current_thread_holds_lock((JavaThread*)THREAD, lockObject);
 479   assert(calledholdinglock,"must hold lock for notify");
 480   assert(!UnsyncloadClass, "unexpected double_lock_wait");
 481   ObjectSynchronizer::notifyall(lockObject, THREAD);
 482   intptr_t recursions =  ObjectSynchronizer::complete_exit(lockObject, THREAD);
 483   SystemDictionary_lock->wait();
 484   SystemDictionary_lock->unlock();
 485   ObjectSynchronizer::reenter(lockObject, recursions, THREAD);
 486   SystemDictionary_lock->lock();
 487 }
 488 
 489 // If the class in is in the placeholder table, class loading is in progress
 490 // For cases where the application changes threads to load classes, it
 491 // is critical to ClassCircularity detection that we try loading
 492 // the superclass on the same thread internally, so we do parallel
 493 // super class loading here.
 494 // This also is critical in cases where the original thread gets stalled
 495 // even in non-circularity situations.
 496 // Note: only one thread can define the class, but multiple can resolve
 497 // Note: must call resolve_super_or_fail even if null super -
 498 // to force placeholder entry creation for this class
 499 // Caller must check for pending exception
 500 // Returns non-null klassOop if other thread has completed load
 501 // and we are done, 
 502 // If return null klassOop and no pending exception, the caller must load the class
 503 instanceKlassHandle SystemDictionary::handle_parallel_super_load(
 504     symbolHandle name, symbolHandle superclassname, Handle class_loader, 
 505     Handle protection_domain, Handle lockObject, TRAPS) {
 506 
 507   instanceKlassHandle nh = instanceKlassHandle(); // null Handle
 508   unsigned int d_hash = dictionary()->compute_hash(name, class_loader);
 509   int d_index = dictionary()->hash_to_index(d_hash);
 510   unsigned int p_hash = placeholders()->compute_hash(name, class_loader);
 511   int p_index = placeholders()->hash_to_index(p_hash);
 512 
 513   // superk is not used, resolve_super called for circularity check only
 514   // This code is reached in two situations. One if this thread
 515   // is loading the same class twice (e.g. ClassCircularity, or 
 516   // java.lang.instrument).
 517   // The second is if another thread started the resolve_super first
 518   // and has not yet finished. 
 519   // In both cases the original caller will clean up the placeholder
 520   // entry on error.
 521   klassOop superk = SystemDictionary::resolve_super_or_fail(name,
 522                                                           superclassname,
 523                                                           class_loader,
 524                                                           protection_domain,
 525                                                           true,
 526                                                           CHECK_(nh));
 527   // We don't redefine the class, so we just need to clean up if there
 528   // was not an error (don't want to modify any system dictionary
 529   // data structures).
 530   {
 531     MutexLocker mu(SystemDictionary_lock, THREAD);
 532     placeholders()->find_and_remove(p_index, p_hash, name, class_loader, THREAD);
 533     SystemDictionary_lock->notify_all();
 534   }
 535 
 536   // UnsyncloadClass does NOT wait for parallel superclass loads to complete
 537   // Bootstrap classloader does wait for parallel superclass loads
 538  if (UnsyncloadClass) {
 539     MutexLocker mu(SystemDictionary_lock, THREAD);
 540     // Check if classloading completed while we were loading superclass or waiting
 541     klassOop check = find_class(d_index, d_hash, name, class_loader);
 542     if (check != NULL) {
 543       // Klass is already loaded, so just return it
 544       return(instanceKlassHandle(THREAD, check));
 545     } else {
 546       return nh;
 547     }
 548   } 
 549 
 550   // must loop to both handle other placeholder updates
 551   // and spurious notifications
 552   bool super_load_in_progress = true;
 553   PlaceholderEntry* placeholder;
 554   while (super_load_in_progress) {
 555     MutexLocker mu(SystemDictionary_lock, THREAD);
 556     // Check if classloading completed while we were loading superclass or waiting
 557     klassOop check = find_class(d_index, d_hash, name, class_loader);
 558     if (check != NULL) {
 559       // Klass is already loaded, so just return it
 560       return(instanceKlassHandle(THREAD, check));
 561     } else {
 562       placeholder = placeholders()->get_entry(p_index, p_hash, name, class_loader);
 563       if (placeholder && placeholder->super_load_in_progress() ){
 564         // Before UnsyncloadClass:
 565         // We only get here if the application has released the
 566         // classloader lock when another thread was in the middle of loading a
 567         // superclass/superinterface for this class, and now
 568         // this thread is also trying to load this class.
 569         // To minimize surprises, the first thread that started to
 570         // load a class should be the one to complete the loading
 571         // with the classfile it initially expected.
 572         // This logic has the current thread wait once it has done
 573         // all the superclass/superinterface loading it can, until
 574         // the original thread completes the class loading or fails
 575         // If it completes we will use the resulting instanceKlass
 576         // which we will find below in the systemDictionary.
 577         // We also get here for parallel bootstrap classloader
 578         if (class_loader.is_null()) {
 579           SystemDictionary_lock->wait();
 580         } else {
 581           double_lock_wait(lockObject, THREAD);
 582         }
 583       } else {
 584         // If not in SD and not in PH, other thread's load must have failed
 585         super_load_in_progress = false;
 586       }
 587     }
 588   }
 589   return (nh);
 590 }
 591 
 592 
 593 klassOop SystemDictionary::resolve_instance_class_or_null(symbolHandle class_name, Handle class_loader, Handle protection_domain, TRAPS) {
 594   assert(class_name.not_null() && !FieldType::is_array(class_name()), "invalid class name");
 595   // First check to see if we should remove wrapping L and ;
 596   symbolHandle name;    
 597   if (FieldType::is_obj(class_name())) {
 598     ResourceMark rm(THREAD);
 599     // Ignore wrapping L and ;.
 600     name = oopFactory::new_symbol_handle(class_name()->as_C_string() + 1, class_name()->utf8_length() - 2, CHECK_NULL);    
 601   } else {
 602     name = class_name;
 603   }
 604 
 605   // UseNewReflection
 606   // Fix for 4474172; see evaluation for more details
 607   class_loader = Handle(THREAD, java_lang_ClassLoader::non_reflection_class_loader(class_loader()));
 608 
 609   // Do lookup to see if class already exist and the protection domain
 610   // has the right access
 611   unsigned int d_hash = dictionary()->compute_hash(name, class_loader);
 612   int d_index = dictionary()->hash_to_index(d_hash);
 613   klassOop probe = dictionary()->find(d_index, d_hash, name, class_loader,
 614                                       protection_domain, THREAD);
 615   if (probe != NULL) return probe;
 616 
 617 
 618   // Non-bootstrap class loaders will call out to class loader and
 619   // define via jvm/jni_DefineClass which will acquire the
 620   // class loader object lock to protect against multiple threads
 621   // defining the class in parallel by accident.
 622   // This lock must be acquired here so the waiter will find
 623   // any successful result in the SystemDictionary and not attempt
 624   // the define
 625   // Classloaders that support parallelism, e.g. bootstrap classloader,
 626   // or all classloaders with UnsyncloadClass do not acquire lock here
 627   bool DoObjectLock = true;
 628   if (UnsyncloadClass || (class_loader.is_null())) {
 629     DoObjectLock = false;
 630   }
 631 
 632   unsigned int p_hash = placeholders()->compute_hash(name, class_loader);
 633   int p_index = placeholders()->hash_to_index(p_hash);
 634 
 635   // Class is not in SystemDictionary so we have to do loading.
 636   // Make sure we are synchronized on the class loader before we proceed
 637   Handle lockObject = compute_loader_lock_object(class_loader, THREAD);
 638   check_loader_lock_contention(lockObject, THREAD);
 639   ObjectLocker ol(lockObject, THREAD, DoObjectLock);
 640 
 641   // Check again (after locking) if class already exist in SystemDictionary
 642   bool class_has_been_loaded   = false;
 643   bool super_load_in_progress  = false;
 644   bool havesupername = false;
 645   instanceKlassHandle k;
 646   PlaceholderEntry* placeholder;
 647   symbolHandle superclassname;
 648 
 649   {           
 650     MutexLocker mu(SystemDictionary_lock, THREAD);  
 651     klassOop check = find_class(d_index, d_hash, name, class_loader);
 652     if (check != NULL) {
 653       // Klass is already loaded, so just return it
 654       class_has_been_loaded = true;
 655       k = instanceKlassHandle(THREAD, check);
 656     } else {
 657       placeholder = placeholders()->get_entry(p_index, p_hash, name, class_loader);
 658       if (placeholder && placeholder->super_load_in_progress()) {
 659          super_load_in_progress = true;
 660          if (placeholder->havesupername() == true) {
 661            superclassname = symbolHandle(THREAD, placeholder->supername());
 662            havesupername = true;
 663          }
 664       } 
 665     }
 666   }
 667 
 668   // If the class in is in the placeholder table, class loading is in progress
 669   if (super_load_in_progress && havesupername==true) {
 670     k = SystemDictionary::handle_parallel_super_load(name, superclassname, 
 671         class_loader, protection_domain, lockObject, THREAD);
 672     if (HAS_PENDING_EXCEPTION) {
 673       return NULL;
 674     }
 675     if (!k.is_null()) {
 676       class_has_been_loaded = true;
 677     }
 678   }
 679 
 680   if (!class_has_been_loaded) {
 681   
 682     // add placeholder entry to record loading instance class
 683     // Five cases:
 684     // All cases need to prevent modifying bootclasssearchpath
 685     // in parallel with a classload of same classname
 686     // case 1. traditional classloaders that rely on the classloader object lock
 687     //   - no other need for LOAD_INSTANCE
 688     // case 2. traditional classloaders that break the classloader object lock 
 689     //    as a deadlock workaround. Detection of this case requires that
 690     //    this check is done while holding the classloader object lock,
 691     //    and that lock is still held when calling classloader's loadClass.
 692     //    For these classloaders, we ensure that the first requestor
 693     //    completes the load and other requestors wait for completion.
 694     // case 3. UnsyncloadClass - don't use objectLocker
 695     //    With this flag, we allow parallel classloading of a
 696     //    class/classloader pair
 697     // case4. Bootstrap classloader - don't own objectLocker
 698     //    This classloader supports parallelism at the classloader level,
 699     //    but only allows a single load of a class/classloader pair.
 700     //    No performance benefit and no deadlock issues.
 701     // case 5. Future: parallel user level classloaders - without objectLocker
 702     symbolHandle nullsymbolHandle;
 703     bool throw_circularity_error = false;
 704     {
 705       MutexLocker mu(SystemDictionary_lock, THREAD);
 706       if (!UnsyncloadClass) {
 707         PlaceholderEntry* oldprobe = placeholders()->get_entry(p_index, p_hash, name, class_loader);
 708         if (oldprobe) {
 709           // only need check_seen_thread once, not on each loop
 710           // 6341374 java/lang/Instrument with -Xcomp
 711           if (oldprobe->check_seen_thread(THREAD, PlaceholderTable::LOAD_INSTANCE)) {
 712             throw_circularity_error = true;
 713           } else {
 714             // case 1: traditional: should never see load_in_progress.
 715             while (!class_has_been_loaded && oldprobe && oldprobe->instance_load_in_progress()) {
 716      
 717               // case 4: bootstrap classloader: prevent futile classloading,
 718               // wait on first requestor
 719               if (class_loader.is_null()) {
 720                 SystemDictionary_lock->wait();
 721               } else {
 722               // case 2: traditional with broken classloader lock. wait on first
 723               // requestor.
 724                 double_lock_wait(lockObject, THREAD);
 725               }
 726               // Check if classloading completed while we were waiting
 727               klassOop check = find_class(d_index, d_hash, name, class_loader);
 728               if (check != NULL) {
 729                 // Klass is already loaded, so just return it
 730                 k = instanceKlassHandle(THREAD, check);
 731                 class_has_been_loaded = true;
 732               }
 733               // check if other thread failed to load and cleaned up
 734               oldprobe = placeholders()->get_entry(p_index, p_hash, name, class_loader);
 735             } 
 736           } 
 737         }
 738       }
 739       // All cases: add LOAD_INSTANCE 
 740       // case 3: UnsyncloadClass: allow competing threads to try
 741       // LOAD_INSTANCE in parallel
 742       // add placeholder entry even if error - callers will remove on error
 743       if (!class_has_been_loaded) {
 744         PlaceholderEntry* newprobe = placeholders()->find_and_add(p_index, p_hash, name, class_loader, PlaceholderTable::LOAD_INSTANCE, nullsymbolHandle, THREAD); 
 745         if (throw_circularity_error) {
 746           newprobe->remove_seen_thread(THREAD, PlaceholderTable::LOAD_INSTANCE);
 747         }
 748         // For class loaders that do not acquire the classloader object lock,
 749         // if they did not catch another thread holding LOAD_INSTANCE,
 750         // need a check analogous to the acquire ObjectLocker/find_class 
 751         // i.e. now that we hold the LOAD_INSTANCE token on loading this class/CL
 752         // one final check if the load has already completed
 753         klassOop check = find_class(d_index, d_hash, name, class_loader);
 754         if (check != NULL) {
 755         // Klass is already loaded, so just return it
 756           k = instanceKlassHandle(THREAD, check);
 757           class_has_been_loaded = true;
 758           newprobe->remove_seen_thread(THREAD, PlaceholderTable::LOAD_INSTANCE); 
 759         }
 760       }
 761     }
 762     // must throw error outside of owning lock
 763     if (throw_circularity_error) {
 764       ResourceMark rm(THREAD);
 765       THROW_MSG_0(vmSymbols::java_lang_ClassCircularityError(), name->as_C_string());
 766     }
 767 
 768     if (!class_has_been_loaded) {
 769 
 770       // Do actual loading
 771       k = load_instance_class(name, class_loader, THREAD);
 772 
 773       // In custom class loaders, the usual findClass calls
 774       // findLoadedClass, which directly searches  the SystemDictionary, then
 775       // defineClass. If these are not atomic with respect to other threads,
 776       // the findLoadedClass can fail, but the defineClass can get a 
 777       // LinkageError:: duplicate class definition.
 778       // If they got a linkageError, check if a parallel class load succeeded.
 779       // If it did, then for bytecode resolution the specification requires
 780       // that we return the same result we did for the other thread, i.e. the
 781       // successfully loaded instanceKlass
 782       // Note: Class can not be unloaded as long as any classloader refs exist
 783       // Should not get here for classloaders that support parallelism
 784       // with the new cleaner mechanism, e.g. bootstrap classloader
 785       if (UnsyncloadClass || (class_loader.is_null())) {
 786         if (k.is_null() && HAS_PENDING_EXCEPTION 
 787           && PENDING_EXCEPTION->is_a(SystemDictionary::linkageError_klass())) {
 788           MutexLocker mu(SystemDictionary_lock, THREAD);
 789           klassOop check = find_class(d_index, d_hash, name, class_loader);
 790           if (check != NULL) {
 791             // Klass is already loaded, so just use it
 792             k = instanceKlassHandle(THREAD, check);
 793             CLEAR_PENDING_EXCEPTION;
 794             guarantee((!class_loader.is_null()), "dup definition for bootstrap loader?");
 795           }
 796         }
 797       }
 798 
 799       // clean up placeholder entries for success or error
 800       // This cleans up LOAD_INSTANCE entries
 801       // It also cleans up LOAD_SUPER entries on errors from 
 802       // calling load_instance_class
 803       { 
 804         MutexLocker mu(SystemDictionary_lock, THREAD);
 805         PlaceholderEntry* probe = placeholders()->get_entry(p_index, p_hash, name, class_loader);
 806         if (probe != NULL) {
 807           probe->remove_seen_thread(THREAD, PlaceholderTable::LOAD_INSTANCE);
 808           placeholders()->find_and_remove(p_index, p_hash, name, class_loader, THREAD);
 809           SystemDictionary_lock->notify_all();
 810         }
 811       }
 812 
 813       // If everything was OK (no exceptions, no null return value), and
 814       // class_loader is NOT the defining loader, do a little more bookkeeping.
 815       if (!HAS_PENDING_EXCEPTION && !k.is_null() && 
 816         k->class_loader() != class_loader()) {
 817 
 818         check_constraints(d_index, d_hash, k, class_loader, false, THREAD);
 819 
 820         // Need to check for a PENDING_EXCEPTION again; check_constraints
 821         // can throw and doesn't use the CHECK macro.
 822         if (!HAS_PENDING_EXCEPTION) {
 823           { // Grabbing the Compile_lock prevents systemDictionary updates
 824             // during compilations. 
 825             MutexLocker mu(Compile_lock, THREAD);      
 826             update_dictionary(d_index, d_hash, p_index, p_hash,
 827                             k, class_loader, THREAD);
 828           }
 829           if (JvmtiExport::should_post_class_load()) {
 830             Thread *thread = THREAD;
 831             assert(thread->is_Java_thread(), "thread->is_Java_thread()");
 832             JvmtiExport::post_class_load((JavaThread *) thread, k());
 833           }
 834         }
 835       }
 836       if (HAS_PENDING_EXCEPTION || k.is_null()) {
 837         // On error, clean up placeholders
 838         {
 839           MutexLocker mu(SystemDictionary_lock, THREAD);
 840           placeholders()->find_and_remove(p_index, p_hash, name, class_loader, THREAD);
 841           SystemDictionary_lock->notify_all();
 842         }
 843         return NULL;
 844       }
 845     }
 846   }
 847 
 848 #ifdef ASSERT
 849   {
 850     Handle loader (THREAD, k->class_loader());
 851     MutexLocker mu(SystemDictionary_lock, THREAD);  
 852     oop kk = find_class_or_placeholder(name, loader);
 853     assert(kk == k(), "should be present in dictionary");
 854   }
 855 #endif
 856 
 857   // return if the protection domain in NULL
 858   if (protection_domain() == NULL) return k();
 859 
 860   // Check the protection domain has the right access 
 861   {
 862     MutexLocker mu(SystemDictionary_lock, THREAD);  
 863     // Note that we have an entry, and entries can be deleted only during GC,
 864     // so we cannot allow GC to occur while we're holding this entry.
 865     // We're using a No_Safepoint_Verifier to catch any place where we
 866     // might potentially do a GC at all.
 867     // SystemDictionary::do_unloading() asserts that classes are only
 868     // unloaded at a safepoint.
 869     No_Safepoint_Verifier nosafepoint;
 870     if (dictionary()->is_valid_protection_domain(d_index, d_hash, name,
 871                                                  class_loader,
 872                                                  protection_domain)) {
 873       return k();
 874     }
 875   }
 876 
 877   // Verify protection domain. If it fails an exception is thrown
 878   validate_protection_domain(k, class_loader, protection_domain, CHECK_(klassOop(NULL)));
 879 
 880   return k();
 881 }
 882 
 883 
 884 // This routine does not lock the system dictionary.
 885 //
 886 // Since readers don't hold a lock, we must make sure that system
 887 // dictionary entries are only removed at a safepoint (when only one
 888 // thread is running), and are added to in a safe way (all links must
 889 // be updated in an MT-safe manner).
 890 //
 891 // Callers should be aware that an entry could be added just after
 892 // _dictionary->bucket(index) is read here, so the caller will not see
 893 // the new entry.
 894 
 895 klassOop SystemDictionary::find(symbolHandle class_name,
 896                                 Handle class_loader, 
 897                                 Handle protection_domain,
 898                                 TRAPS) {
 899 
 900   unsigned int d_hash = dictionary()->compute_hash(class_name, class_loader);
 901   int d_index = dictionary()->hash_to_index(d_hash);
 902 
 903   {
 904     // Note that we have an entry, and entries can be deleted only during GC,
 905     // so we cannot allow GC to occur while we're holding this entry.
 906     // We're using a No_Safepoint_Verifier to catch any place where we
 907     // might potentially do a GC at all.
 908     // SystemDictionary::do_unloading() asserts that classes are only
 909     // unloaded at a safepoint.
 910     No_Safepoint_Verifier nosafepoint;
 911     return dictionary()->find(d_index, d_hash, class_name, class_loader,
 912                               protection_domain, THREAD);
 913   }
 914 }
 915 
 916 
 917 // Look for a loaded instance or array klass by name.  Do not do any loading.
 918 // return NULL in case of error.
 919 klassOop SystemDictionary::find_instance_or_array_klass(symbolHandle class_name,
 920                                                         Handle class_loader,
 921                                                         Handle protection_domain,
 922                                                         TRAPS) {
 923   klassOop k = NULL;
 924   assert(class_name() != NULL, "class name must be non NULL");
 925   if (FieldType::is_array(class_name())) {
 926     // The name refers to an array.  Parse the name.
 927     jint dimension;
 928     symbolOop object_key;
 929 
 930     // dimension and object_key are assigned as a side-effect of this call
 931     BasicType t = FieldType::get_array_info(class_name(), &dimension,
 932                                             &object_key, CHECK_(NULL));
 933     if (t != T_OBJECT) {
 934       k = Universe::typeArrayKlassObj(t);
 935     } else {
 936       symbolHandle h_key(THREAD, object_key);
 937       k = SystemDictionary::find(h_key, class_loader, protection_domain, THREAD);
 938     }
 939     if (k != NULL) {
 940       k = Klass::cast(k)->array_klass_or_null(dimension);
 941     }
 942   } else {
 943     k = find(class_name, class_loader, protection_domain, THREAD);
 944   }
 945   return k;
 946 }
 947 
 948 // Note: this method is much like resolve_from_stream, but
 949 // updates no supplemental data structures.
 950 // TODO consolidate the two methods with a helper routine?
 951 klassOop SystemDictionary::parse_stream(symbolHandle class_name,
 952                                         Handle class_loader,
 953                                         Handle protection_domain,
 954                                         ClassFileStream* st,
 955                                         TRAPS) {
 956   symbolHandle parsed_name;
 957 
 958   // Parse the stream. Note that we do this even though this klass might
 959   // already be present in the SystemDictionary, otherwise we would not
 960   // throw potential ClassFormatErrors.
 961   //
 962   // Note: "name" is updated.
 963   // Further note:  a placeholder will be added for this class when
 964   //   super classes are loaded (resolve_super_or_fail). We expect this
 965   //   to be called for all classes but java.lang.Object; and we preload
 966   //   java.lang.Object through resolve_or_fail, not this path.
 967 
 968   instanceKlassHandle k = ClassFileParser(st).parseClassFile(class_name,
 969                                                              class_loader,
 970                                                              protection_domain,
 971                                                              parsed_name,
 972                                                              THREAD);
 973 
 974 
 975   // We don't redefine the class, so we just need to clean up whether there
 976   // was an error or not (don't want to modify any system dictionary
 977   // data structures).
 978   // Parsed name could be null if we threw an error before we got far
 979   // enough along to parse it -- in that case, there is nothing to clean up.
 980   if (!parsed_name.is_null()) {
 981     unsigned int p_hash = placeholders()->compute_hash(parsed_name, 
 982                                                        class_loader);
 983     int p_index = placeholders()->hash_to_index(p_hash);
 984     {
 985     MutexLocker mu(SystemDictionary_lock, THREAD);
 986     placeholders()->find_and_remove(p_index, p_hash, parsed_name, class_loader, THREAD);
 987     SystemDictionary_lock->notify_all();
 988     }
 989   }
 990 
 991   return k();
 992 }
 993 
 994 // Add a klass to the system from a stream (called by jni_DefineClass and
 995 // JVM_DefineClass).
 996 // Note: class_name can be NULL. In that case we do not know the name of 
 997 // the class until we have parsed the stream.
 998 
 999 klassOop SystemDictionary::resolve_from_stream(symbolHandle class_name, 
1000                                                Handle class_loader, 
1001                                                Handle protection_domain, 
1002                                                ClassFileStream* st, 
1003                                                TRAPS) {
1004 
1005   // Make sure we are synchronized on the class loader before we initiate 
1006   // loading.
1007   Handle lockObject = compute_loader_lock_object(class_loader, THREAD); 
1008   check_loader_lock_contention(lockObject, THREAD);
1009   ObjectLocker ol(lockObject, THREAD);
1010 
1011   symbolHandle parsed_name;
1012 
1013   // Parse the stream. Note that we do this even though this klass might 
1014   // already be present in the SystemDictionary, otherwise we would not 
1015   // throw potential ClassFormatErrors.
1016   //
1017   // Note: "name" is updated.
1018   // Further note:  a placeholder will be added for this class when
1019   //   super classes are loaded (resolve_super_or_fail). We expect this
1020   //   to be called for all classes but java.lang.Object; and we preload
1021   //   java.lang.Object through resolve_or_fail, not this path.
1022 
1023   instanceKlassHandle k = ClassFileParser(st).parseClassFile(class_name, 
1024                                                              class_loader, 
1025                                                              protection_domain,
1026                                                              parsed_name,
1027                                                              THREAD);
1028 
1029   const char* pkg = "java/";
1030   if (!HAS_PENDING_EXCEPTION && 
1031       !class_loader.is_null() && 
1032       !parsed_name.is_null() && 
1033       !strncmp((const char*)parsed_name->bytes(), pkg, strlen(pkg))) {
1034     // It is illegal to define classes in the "java." package from
1035     // JVM_DefineClass or jni_DefineClass unless you're the bootclassloader
1036     ResourceMark rm(THREAD);
1037     char* name = parsed_name->as_C_string();
1038     char* index = strrchr(name, '/');
1039     *index = '\0'; // chop to just the package name
1040     while ((index = strchr(name, '/')) != NULL) {
1041       *index = '.'; // replace '/' with '.' in package name
1042     }
1043     const char* fmt = "Prohibited package name: %s";
1044     size_t len = strlen(fmt) + strlen(name);
1045     char* message = NEW_RESOURCE_ARRAY(char, len);
1046     jio_snprintf(message, len, fmt, name);
1047     Exceptions::_throw_msg(THREAD_AND_LOCATION, 
1048       vmSymbols::java_lang_SecurityException(), message);
1049   }
1050 
1051   if (!HAS_PENDING_EXCEPTION) {
1052     assert(!parsed_name.is_null(), "Sanity");
1053     assert(class_name.is_null() || class_name() == parsed_name(), 
1054            "name mismatch");
1055     // Verification prevents us from creating names with dots in them, this
1056     // asserts that that's the case.
1057     assert(is_internal_format(parsed_name),
1058            "external class name format used internally");
1059 
1060     // Add class just loaded
1061     define_instance_class(k, THREAD);
1062   }
1063 
1064   // If parsing the class file or define_instance_class failed, we
1065   // need to remove the placeholder added on our behalf. But we
1066   // must make sure parsed_name is valid first (it won't be if we had
1067   // a format error before the class was parsed far enough to
1068   // find the name).
1069   if (HAS_PENDING_EXCEPTION && !parsed_name.is_null()) {
1070     unsigned int p_hash = placeholders()->compute_hash(parsed_name, 
1071                                                        class_loader);
1072     int p_index = placeholders()->hash_to_index(p_hash);
1073     {
1074     MutexLocker mu(SystemDictionary_lock, THREAD);
1075     placeholders()->find_and_remove(p_index, p_hash, parsed_name, class_loader, THREAD);
1076     SystemDictionary_lock->notify_all();
1077     }
1078     return NULL;
1079   }
1080 
1081   // Make sure that we didn't leave a place holder in the
1082   // SystemDictionary; this is only done on success
1083   debug_only( {
1084     if (!HAS_PENDING_EXCEPTION) {
1085       assert(!parsed_name.is_null(), "parsed_name is still null?");
1086       symbolHandle h_name   (THREAD, k->name());
1087       Handle h_loader (THREAD, k->class_loader());
1088 
1089       MutexLocker mu(SystemDictionary_lock, THREAD);
1090 
1091       oop check = find_class_or_placeholder(parsed_name, class_loader);
1092       assert(check == k(), "should be present in the dictionary");
1093 
1094       oop check2 = find_class_or_placeholder(h_name, h_loader);
1095       assert(check == check2, "name inconsistancy in SystemDictionary");
1096     }
1097   } );
1098 
1099   return k();
1100 }
1101 
1102 
1103 void SystemDictionary::set_shared_dictionary(HashtableBucket* t, int length,
1104                                              int number_of_entries) {
1105   assert(length == _nof_buckets * sizeof(HashtableBucket),
1106          "bad shared dictionary size.");
1107   _shared_dictionary = new Dictionary(_nof_buckets, t, number_of_entries);
1108 }
1109 
1110 
1111 // If there is a shared dictionary, then find the entry for the
1112 // given shared system class, if any.
1113 
1114 klassOop SystemDictionary::find_shared_class(symbolHandle class_name) {
1115   if (shared_dictionary() != NULL) {
1116     unsigned int d_hash = dictionary()->compute_hash(class_name, Handle());
1117     int d_index = dictionary()->hash_to_index(d_hash);
1118     return shared_dictionary()->find_shared_class(d_index, d_hash, class_name);
1119   } else {
1120     return NULL;
1121   }
1122 }
1123 
1124 
1125 // Load a class from the shared spaces (found through the shared system
1126 // dictionary).  Force the superclass and all interfaces to be loaded.
1127 // Update the class definition to include sibling classes and no
1128 // subclasses (yet).  [Classes in the shared space are not part of the
1129 // object hierarchy until loaded.]
1130 
1131 instanceKlassHandle SystemDictionary::load_shared_class(
1132                  symbolHandle class_name, Handle class_loader, TRAPS) {
1133   instanceKlassHandle ik (THREAD, find_shared_class(class_name));
1134   return load_shared_class(ik, class_loader, THREAD);
1135 }
1136 
1137 // Note well!  Changes to this method may affect oop access order
1138 // in the shared archive.  Please take care to not make changes that
1139 // adversely affect cold start time by changing the oop access order
1140 // that is specified in dump.cpp MarkAndMoveOrderedReadOnly and
1141 // MarkAndMoveOrderedReadWrite closures.
1142 instanceKlassHandle SystemDictionary::load_shared_class(
1143                  instanceKlassHandle ik, Handle class_loader, TRAPS) {
1144   assert(class_loader.is_null(), "non-null classloader for shared class?");
1145   if (ik.not_null()) {
1146     instanceKlassHandle nh = instanceKlassHandle(); // null Handle
1147     symbolHandle class_name(THREAD, ik->name());
1148 
1149     // Found the class, now load the superclass and interfaces.  If they
1150     // are shared, add them to the main system dictionary and reset
1151     // their hierarchy references (supers, subs, and interfaces).
1152 
1153     if (ik->super() != NULL) {
1154       symbolHandle cn(THREAD, ik->super()->klass_part()->name());
1155       resolve_super_or_fail(class_name, cn,
1156                             class_loader, Handle(), true, CHECK_(nh));
1157     }
1158 
1159     objArrayHandle interfaces (THREAD, ik->local_interfaces());
1160     int num_interfaces = interfaces->length();
1161     for (int index = 0; index < num_interfaces; index++) {
1162       klassOop k = klassOop(interfaces->obj_at(index));
1163 
1164       // Note: can not use instanceKlass::cast here because
1165       // interfaces' instanceKlass's C++ vtbls haven't been
1166       // reinitialized yet (they will be once the interface classes
1167       // are loaded)
1168       symbolHandle name (THREAD, k->klass_part()->name());
1169       resolve_super_or_fail(class_name, name, class_loader, Handle(), false, CHECK_(nh));
1170     }
1171 
1172     // Adjust methods to recover missing data.  They need addresses for
1173     // interpreter entry points and their default native method address
1174     // must be reset.
1175 
1176     // Updating methods must be done under a lock so multiple
1177     // threads don't update these in parallel
1178     // Shared classes are all currently loaded by the bootstrap
1179     // classloader, so this will never cause a deadlock on
1180     // a custom class loader lock.
1181 
1182     {
1183       Handle lockObject = compute_loader_lock_object(class_loader, THREAD);
1184       check_loader_lock_contention(lockObject, THREAD);
1185       ObjectLocker ol(lockObject, THREAD, true);
1186 
1187       objArrayHandle methods (THREAD, ik->methods());
1188       int num_methods = methods->length();
1189       for (int index2 = 0; index2 < num_methods; ++index2) {
1190         methodHandle m(THREAD, methodOop(methods->obj_at(index2)));
1191         m()->link_method(m, CHECK_(nh));
1192       }
1193     }
1194 
1195     if (TraceClassLoading) {
1196       ResourceMark rm;
1197       tty->print("[Loaded %s", ik->external_name());
1198       tty->print(" from shared objects file");
1199       tty->print_cr("]");
1200     }
1201     // notify a class loaded from shared object
1202     ClassLoadingService::notify_class_loaded(instanceKlass::cast(ik()), 
1203                                              true /* shared class */);
1204   }
1205   return ik;
1206 }
1207 
1208 #ifdef KERNEL
1209 // Some classes on the bootstrap class path haven't been installed on the
1210 // system yet.  Call the DownloadManager method to make them appear in the
1211 // bootstrap class path and try again to load the named class.
1212 // Note that with delegation class loaders all classes in another loader will
1213 // first try to call this so it'd better be fast!!
1214 static instanceKlassHandle download_and_retry_class_load(
1215                                                     symbolHandle class_name,
1216                                                     TRAPS) {
1217 
1218   klassOop dlm = SystemDictionary::sun_jkernel_DownloadManager_klass();
1219   instanceKlassHandle nk;
1220 
1221   // If download manager class isn't loaded just return.
1222   if (dlm == NULL) return nk;
1223 
1224   { HandleMark hm(THREAD);
1225     ResourceMark rm(THREAD);
1226     Handle s = java_lang_String::create_from_symbol(class_name, CHECK_(nk));
1227     Handle class_string = java_lang_String::externalize_classname(s, CHECK_(nk));
1228 
1229     // return value
1230     JavaValue result(T_OBJECT);
1231 
1232     // Call the DownloadManager.  We assume that it has a lock because
1233     // multiple classes could be not found and downloaded at the same time.
1234     // class sun.misc.DownloadManager;
1235     // public static String getBootClassPathEntryForClass(String className);
1236     JavaCalls::call_static(&result,
1237                        KlassHandle(THREAD, dlm),
1238                        vmSymbolHandles::getBootClassPathEntryForClass_name(),
1239                        vmSymbolHandles::string_string_signature(),
1240                        class_string,
1241                        CHECK_(nk));
1242 
1243     // Get result.string and add to bootclasspath
1244     assert(result.get_type() == T_OBJECT, "just checking");
1245     oop obj = (oop) result.get_jobject();
1246     if (obj == NULL) { return nk; }
1247 
1248     Handle h_obj(THREAD, obj);
1249     char* new_class_name = java_lang_String::as_platform_dependent_str(h_obj, 
1250                                                                   CHECK_(nk));
1251 
1252     // lock the loader 
1253     // we use this lock because JVMTI does.
1254     Handle loader_lock(THREAD, SystemDictionary::system_loader_lock());
1255 
1256     ObjectLocker ol(loader_lock, THREAD);
1257     // add the file to the bootclasspath
1258     ClassLoader::update_class_path_entry_list(new_class_name, true);
1259   } // end HandleMark
1260 
1261   if (TraceClassLoading) {
1262     ClassLoader::print_bootclasspath();
1263   }
1264   return ClassLoader::load_classfile(class_name, CHECK_(nk));
1265 }
1266 #endif // KERNEL
1267 
1268 
1269 instanceKlassHandle SystemDictionary::load_instance_class(symbolHandle class_name, Handle class_loader, TRAPS) {
1270   instanceKlassHandle nh = instanceKlassHandle(); // null Handle
1271   if (class_loader.is_null()) {
1272     // Search the shared system dictionary for classes preloaded into the
1273     // shared spaces.
1274     instanceKlassHandle k;
1275     k = load_shared_class(class_name, class_loader, THREAD);
1276 
1277     if (k.is_null()) {
1278       // Use VM class loader
1279       k = ClassLoader::load_classfile(class_name, CHECK_(nh));
1280     }
1281 
1282 #ifdef KERNEL
1283     // If the VM class loader has failed to load the class, call the
1284     // DownloadManager class to make it magically appear on the classpath
1285     // and try again.  This is only configured with the Kernel VM.
1286     if (k.is_null()) {
1287       k = download_and_retry_class_load(class_name, CHECK_(nh));
1288     }
1289 #endif // KERNEL
1290 
1291     // find_or_define_instance_class may return a different k
1292     if (!k.is_null()) {
1293       k = find_or_define_instance_class(class_name, class_loader, k, CHECK_(nh));
1294     }
1295     return k;
1296   } else {
1297     // Use user specified class loader to load class. Call loadClass operation on class_loader.
1298     ResourceMark rm(THREAD);
1299       
1300     Handle s = java_lang_String::create_from_symbol(class_name, CHECK_(nh));
1301     // Translate to external class name format, i.e., convert '/' chars to '.'
1302     Handle string = java_lang_String::externalize_classname(s, CHECK_(nh));
1303 
1304     JavaValue result(T_OBJECT);
1305 
1306     KlassHandle spec_klass (THREAD, SystemDictionary::classloader_klass());
1307 
1308     // UnsyncloadClass option means don't synchronize loadClass() calls.
1309     // loadClassInternal() is synchronized and public loadClass(String) is not.
1310     // This flag is for diagnostic purposes only. It is risky to call
1311     // custom class loaders without synchronization.
1312     // WARNING If a custom class loader does NOT synchronizer findClass, or callers of
1313     // findClass, this flag risks unexpected timing bugs in the field.
1314     // Do NOT assume this will be supported in future releases.
1315     if (!UnsyncloadClass && has_loadClassInternal()) {
1316       JavaCalls::call_special(&result, 
1317                               class_loader, 
1318                               spec_klass,
1319                               vmSymbolHandles::loadClassInternal_name(),
1320                               vmSymbolHandles::string_class_signature(), 
1321                               string,
1322                               CHECK_(nh));
1323     } else {
1324       JavaCalls::call_virtual(&result, 
1325                               class_loader, 
1326                               spec_klass,
1327                               vmSymbolHandles::loadClass_name(),
1328                               vmSymbolHandles::string_class_signature(), 
1329                               string,
1330                               CHECK_(nh));
1331     }
1332 
1333     assert(result.get_type() == T_OBJECT, "just checking");
1334     oop obj = (oop) result.get_jobject();
1335 
1336     // Primitive classes return null since forName() can not be
1337     // used to obtain any of the Class objects representing primitives or void
1338     if ((obj != NULL) && !(java_lang_Class::is_primitive(obj))) {      
1339       instanceKlassHandle k = 
1340                 instanceKlassHandle(THREAD, java_lang_Class::as_klassOop(obj));
1341       // For user defined Java class loaders, check that the name returned is
1342       // the same as that requested.  This check is done for the bootstrap
1343       // loader when parsing the class file.
1344       if (class_name() == k->name()) {
1345         return k;
1346       }
1347     }
1348     // Class is not found or has the wrong name, return NULL
1349     return nh;
1350   }
1351 }
1352 
1353 void SystemDictionary::define_instance_class(instanceKlassHandle k, TRAPS) {
1354 
1355   Handle class_loader_h(THREAD, k->class_loader());
1356 
1357   // for bootstrap classloader don't acquire lock
1358   if (!class_loader_h.is_null()) {
1359     assert(ObjectSynchronizer::current_thread_holds_lock((JavaThread*)THREAD, 
1360          compute_loader_lock_object(class_loader_h, THREAD)),
1361          "define called without lock");
1362   }
1363 
1364 
1365   // Check class-loading constraints. Throw exception if violation is detected.
1366   // Grabs and releases SystemDictionary_lock
1367   // The check_constraints/find_class call and update_dictionary sequence
1368   // must be "atomic" for a specific class/classloader pair so we never
1369   // define two different instanceKlasses for that class/classloader pair.
1370   // Existing classloaders will call define_instance_class with the
1371   // classloader lock held
1372   // Parallel classloaders will call find_or_define_instance_class
1373   // which will require a token to perform the define class
1374   symbolHandle name_h(THREAD, k->name());
1375   unsigned int d_hash = dictionary()->compute_hash(name_h, class_loader_h);
1376   int d_index = dictionary()->hash_to_index(d_hash);
1377   check_constraints(d_index, d_hash, k, class_loader_h, true, CHECK);
1378 
1379   // Register class just loaded with class loader (placed in Vector)
1380   // Note we do this before updating the dictionary, as this can
1381   // fail with an OutOfMemoryError (if it does, we will *not* put this
1382   // class in the dictionary and will not update the class hierarchy).
1383   if (k->class_loader() != NULL) {
1384     methodHandle m(THREAD, Universe::loader_addClass_method());
1385     JavaValue result(T_VOID);
1386     JavaCallArguments args(class_loader_h);
1387     args.push_oop(Handle(THREAD, k->java_mirror()));
1388     JavaCalls::call(&result, m, &args, CHECK);
1389   }
1390 
1391   // Add the new class. We need recompile lock during update of CHA.
1392   {
1393     unsigned int p_hash = placeholders()->compute_hash(name_h, class_loader_h);
1394     int p_index = placeholders()->hash_to_index(p_hash);
1395 
1396     MutexLocker mu_r(Compile_lock, THREAD);                    
1397 
1398     // Add to class hierarchy, initialize vtables, and do possible
1399     // deoptimizations.
1400     add_to_hierarchy(k, CHECK); // No exception, but can block
1401 
1402     // Add to systemDictionary - so other classes can see it.
1403     // Grabs and releases SystemDictionary_lock
1404     update_dictionary(d_index, d_hash, p_index, p_hash,
1405                       k, class_loader_h, THREAD);
1406   }
1407   k->eager_initialize(THREAD);
1408 
1409   // notify jvmti
1410   if (JvmtiExport::should_post_class_load()) {
1411       assert(THREAD->is_Java_thread(), "thread->is_Java_thread()");
1412       JvmtiExport::post_class_load((JavaThread *) THREAD, k());
1413 
1414   }
1415 }
1416 
1417 // Support parallel classloading
1418 // Initial implementation for bootstrap classloader
1419 // For future:
1420 // For custom class loaders that support parallel classloading,
1421 // in case they do not synchronize around
1422 // FindLoadedClass/DefineClass calls, we check for parallel
1423 // loading for them, wait if a defineClass is in progress
1424 // and return the initial requestor's results
1425 // For better performance, the class loaders should synchronize
1426 // findClass(), i.e. FindLoadedClass/DefineClass or they
1427 // potentially waste time reading and parsing the bytestream.
1428 // Note: VM callers should ensure consistency of k/class_name,class_loader
1429 instanceKlassHandle SystemDictionary::find_or_define_instance_class(symbolHandle class_name, Handle class_loader, instanceKlassHandle k, TRAPS) {
1430 
1431   instanceKlassHandle nh = instanceKlassHandle(); // null Handle
1432 
1433   unsigned int d_hash = dictionary()->compute_hash(class_name, class_loader);
1434   int d_index = dictionary()->hash_to_index(d_hash);
1435 
1436 // Hold SD lock around find_class and placeholder creation for DEFINE_CLASS
1437   unsigned int p_hash = placeholders()->compute_hash(class_name, class_loader);
1438   int p_index = placeholders()->hash_to_index(p_hash);
1439   PlaceholderEntry* probe;
1440 
1441   { 
1442     MutexLocker mu(SystemDictionary_lock, THREAD);
1443     // First check if class already defined
1444     klassOop check = find_class(d_index, d_hash, class_name, class_loader);
1445     if (check != NULL) {
1446       return(instanceKlassHandle(THREAD, check));
1447     }
1448 
1449     // Acquire define token for this class/classloader
1450     symbolHandle nullsymbolHandle;
1451     probe = placeholders()->find_and_add(p_index, p_hash, class_name, class_loader, PlaceholderTable::DEFINE_CLASS, nullsymbolHandle, THREAD); 
1452     // Check if another thread defining in parallel
1453     if (probe->definer() == NULL) {
1454       // Thread will define the class
1455       probe->set_definer(THREAD);
1456     } else {
1457       // Wait for defining thread to finish and return results
1458       while (probe->definer() != NULL) {
1459         SystemDictionary_lock->wait();
1460       }
1461       if (probe->instanceKlass() != NULL) {
1462         probe->remove_seen_thread(THREAD, PlaceholderTable::DEFINE_CLASS);
1463         return(instanceKlassHandle(THREAD, probe->instanceKlass()));
1464       } else {
1465         // If definer had an error, try again as any new thread would
1466         probe->set_definer(THREAD);
1467 #ifdef ASSERT
1468         klassOop check = find_class(d_index, d_hash, class_name, class_loader);
1469         assert(check == NULL, "definer missed recording success");
1470 #endif
1471       }
1472     }
1473   }
1474 
1475   define_instance_class(k, THREAD);
1476 
1477   Handle linkage_exception = Handle(); // null handle
1478 
1479   // definer must notify any waiting threads
1480   {
1481     MutexLocker mu(SystemDictionary_lock, THREAD);
1482     PlaceholderEntry* probe = placeholders()->get_entry(p_index, p_hash, class_name, class_loader);
1483     assert(probe != NULL, "DEFINE_CLASS placeholder lost?");
1484     if (probe != NULL) {
1485       if (HAS_PENDING_EXCEPTION) {
1486         linkage_exception = Handle(THREAD,PENDING_EXCEPTION);
1487         CLEAR_PENDING_EXCEPTION;
1488       } else {
1489         probe->set_instanceKlass(k());
1490       }
1491       probe->set_definer(NULL);
1492       probe->remove_seen_thread(THREAD, PlaceholderTable::DEFINE_CLASS);
1493       SystemDictionary_lock->notify_all();
1494     }
1495   }
1496 
1497   // Can't throw exception while holding lock due to rank ordering
1498   if (linkage_exception() != NULL) {
1499     THROW_OOP_(linkage_exception(), nh); // throws exception and returns
1500   }
1501 
1502   return k;
1503 }
1504 
1505 Handle SystemDictionary::compute_loader_lock_object(Handle class_loader, TRAPS) {
1506   // If class_loader is NULL we synchronize on _system_loader_lock_obj
1507   if (class_loader.is_null()) {
1508     return Handle(THREAD, _system_loader_lock_obj);
1509   } else {
1510     return class_loader;
1511   }
1512 }
1513 
1514 // This method is added to check how often we have to wait to grab loader
1515 // lock. The results are being recorded in the performance counters defined in
1516 // ClassLoader::_sync_systemLoaderLockContentionRate and
1517 // ClassLoader::_sync_nonSystemLoaderLockConteionRate. 
1518 void SystemDictionary::check_loader_lock_contention(Handle loader_lock, TRAPS) {
1519   if (!UsePerfData) {
1520     return;
1521   }
1522 
1523   assert(!loader_lock.is_null(), "NULL lock object");
1524 
1525   if (ObjectSynchronizer::query_lock_ownership((JavaThread*)THREAD, loader_lock)
1526       == ObjectSynchronizer::owner_other) {
1527     // contention will likely happen, so increment the corresponding 
1528     // contention counter.
1529     if (loader_lock() == _system_loader_lock_obj) {
1530       ClassLoader::sync_systemLoaderLockContentionRate()->inc();
1531     } else {
1532       ClassLoader::sync_nonSystemLoaderLockContentionRate()->inc();
1533     }
1534   }
1535 } 
1536   
1537 // ----------------------------------------------------------------------------
1538 // Lookup
1539 
1540 klassOop SystemDictionary::find_class(int index, unsigned int hash,
1541                                       symbolHandle class_name,
1542                                       Handle class_loader) {
1543   assert_locked_or_safepoint(SystemDictionary_lock);
1544   assert (index == dictionary()->index_for(class_name, class_loader),
1545           "incorrect index?");
1546 
1547   klassOop k = dictionary()->find_class(index, hash, class_name, class_loader);
1548   return k;
1549 }
1550 
1551 
1552 // Basic find on classes in the midst of being loaded
1553 symbolOop SystemDictionary::find_placeholder(int index, unsigned int hash,
1554                                              symbolHandle class_name,
1555                                              Handle class_loader) {
1556   assert_locked_or_safepoint(SystemDictionary_lock);
1557 
1558   return placeholders()->find_entry(index, hash, class_name, class_loader);
1559 }
1560 
1561 
1562 // Used for assertions and verification only
1563 oop SystemDictionary::find_class_or_placeholder(symbolHandle class_name, 
1564                                                 Handle class_loader) {
1565   #ifndef ASSERT
1566   guarantee(VerifyBeforeGC   || 
1567             VerifyDuringGC   || 
1568             VerifyBeforeExit ||
1569             VerifyAfterGC, "too expensive"); 
1570   #endif
1571   assert_locked_or_safepoint(SystemDictionary_lock);
1572   symbolOop class_name_ = class_name();
1573   oop class_loader_ = class_loader();
1574 
1575   // First look in the loaded class array
1576   unsigned int d_hash = dictionary()->compute_hash(class_name, class_loader);
1577   int d_index = dictionary()->hash_to_index(d_hash);
1578   oop lookup = find_class(d_index, d_hash, class_name, class_loader);
1579 
1580   if (lookup == NULL) {
1581     // Next try the placeholders
1582     unsigned int p_hash = placeholders()->compute_hash(class_name,class_loader);
1583     int p_index = placeholders()->hash_to_index(p_hash);
1584     lookup = find_placeholder(p_index, p_hash, class_name, class_loader);
1585   }
1586 
1587   return lookup;
1588 }
1589 
1590 
1591 // Get the next class in the diictionary.
1592 klassOop SystemDictionary::try_get_next_class() {
1593   return dictionary()->try_get_next_class();
1594 }
1595 
1596 
1597 // ----------------------------------------------------------------------------
1598 // Update hierachy. This is done before the new klass has been added to the SystemDictionary. The Recompile_lock
1599 // is held, to ensure that the compiler is not using the class hierachy, and that deoptimization will kick in
1600 // before a new class is used.
1601 
1602 void SystemDictionary::add_to_hierarchy(instanceKlassHandle k, TRAPS) {
1603   assert(k.not_null(), "just checking");
1604   // Link into hierachy. Make sure the vtables are initialized before linking into 
1605   k->append_to_sibling_list();                    // add to superklass/sibling list
1606   k->process_interfaces(THREAD);                  // handle all "implements" declarations  
1607   k->set_init_state(instanceKlass::loaded);
1608   // Now flush all code that depended on old class hierarchy.
1609   // Note: must be done *after* linking k into the hierarchy (was bug 12/9/97)
1610   // Also, first reinitialize vtable because it may have gotten out of synch 
1611   // while the new class wasn't connected to the class hierarchy.     
1612   Universe::flush_dependents_on(k);
1613 }
1614 
1615 
1616 // ----------------------------------------------------------------------------
1617 // GC support
1618 
1619 // Following roots during mark-sweep is separated in two phases. 
1620 //
1621 // The first phase follows preloaded classes and all other system 
1622 // classes, since these will never get unloaded anyway.
1623 //
1624 // The second phase removes (unloads) unreachable classes from the
1625 // system dictionary and follows the remaining classes' contents.
1626 
1627 void SystemDictionary::always_strong_oops_do(OopClosure* blk) {
1628   // Follow preloaded classes/mirrors and system loader object
1629   blk->do_oop(&_java_system_loader);
1630   preloaded_oops_do(blk);
1631   always_strong_classes_do(blk);
1632 }
1633 
1634 
1635 void SystemDictionary::always_strong_classes_do(OopClosure* blk) {
1636   // Follow all system classes and temporary placeholders in dictionary
1637   dictionary()->always_strong_classes_do(blk);
1638   
1639   // Placeholders. These are *always* strong roots, as they
1640   // represent classes we're actively loading.
1641   placeholders_do(blk);  
1642 
1643   // Loader constraints. We must keep the symbolOop used in the name alive.
1644   constraints()->always_strong_classes_do(blk);
1645 
1646   // Resolution errors keep the symbolOop for the error alive
1647   resolution_errors()->always_strong_classes_do(blk);
1648 }
1649 
1650 
1651 void SystemDictionary::placeholders_do(OopClosure* blk) {
1652   placeholders()->oops_do(blk);
1653 }
1654 
1655 
1656 bool SystemDictionary::do_unloading(BoolObjectClosure* is_alive) {
1657   bool result = dictionary()->do_unloading(is_alive);
1658   constraints()->purge_loader_constraints(is_alive);
1659   resolution_errors()->purge_resolution_errors(is_alive);
1660   return result;
1661 }
1662 
1663 
1664 // The mirrors are scanned by shared_oops_do() which is
1665 // not called by oops_do().  In order to process oops in
1666 // a necessary order, shared_oops_do() is call by
1667 // Universe::oops_do().
1668 void SystemDictionary::oops_do(OopClosure* f) {
1669   // Adjust preloaded classes and system loader object
1670   f->do_oop(&_java_system_loader);
1671   preloaded_oops_do(f);
1672 
1673   lazily_loaded_oops_do(f);
1674 
1675   // Adjust dictionary
1676   dictionary()->oops_do(f);
1677 
1678   // Partially loaded classes
1679   placeholders()->oops_do(f);
1680 
1681   // Adjust constraint table
1682   constraints()->oops_do(f);
1683 
1684   // Adjust resolution error table
1685   resolution_errors()->oops_do(f);
1686 }
1687 
1688 
1689 void SystemDictionary::preloaded_oops_do(OopClosure* f) {
1690   f->do_oop((oop*) &_string_klass);
1691   f->do_oop((oop*) &_object_klass);
1692   f->do_oop((oop*) &_class_klass);
1693   f->do_oop((oop*) &_cloneable_klass);
1694   f->do_oop((oop*) &_classloader_klass);
1695   f->do_oop((oop*) &_serializable_klass);
1696   f->do_oop((oop*) &_system_klass);
1697 
1698   f->do_oop((oop*) &_throwable_klass);
1699   f->do_oop((oop*) &_error_klass);
1700   f->do_oop((oop*) &_threaddeath_klass);
1701   f->do_oop((oop*) &_exception_klass);
1702   f->do_oop((oop*) &_runtime_exception_klass);
1703   f->do_oop((oop*) &_classNotFoundException_klass);
1704   f->do_oop((oop*) &_noClassDefFoundError_klass);
1705   f->do_oop((oop*) &_linkageError_klass);
1706   f->do_oop((oop*) &_classCastException_klass);
1707   f->do_oop((oop*) &_arrayStoreException_klass);
1708   f->do_oop((oop*) &_virtualMachineError_klass);
1709   f->do_oop((oop*) &_outOfMemoryError_klass);
1710   f->do_oop((oop*) &_StackOverflowError_klass);
1711   f->do_oop((oop*) &_illegalMonitorStateException_klass);
1712   f->do_oop((oop*) &_protectionDomain_klass);
1713   f->do_oop((oop*) &_AccessControlContext_klass);
1714 
1715   f->do_oop((oop*) &_reference_klass);
1716   f->do_oop((oop*) &_soft_reference_klass);
1717   f->do_oop((oop*) &_weak_reference_klass);
1718   f->do_oop((oop*) &_final_reference_klass);
1719   f->do_oop((oop*) &_phantom_reference_klass);
1720   f->do_oop((oop*) &_finalizer_klass);
1721   
1722   f->do_oop((oop*) &_thread_klass);
1723   f->do_oop((oop*) &_threadGroup_klass);
1724   f->do_oop((oop*) &_properties_klass);      
1725   f->do_oop((oop*) &_reflect_accessible_object_klass);      
1726   f->do_oop((oop*) &_reflect_field_klass);      
1727   f->do_oop((oop*) &_reflect_method_klass);      
1728   f->do_oop((oop*) &_reflect_constructor_klass);      
1729   f->do_oop((oop*) &_reflect_magic_klass);
1730   f->do_oop((oop*) &_reflect_method_accessor_klass);
1731   f->do_oop((oop*) &_reflect_constructor_accessor_klass);
1732   f->do_oop((oop*) &_reflect_delegating_classloader_klass);
1733   f->do_oop((oop*) &_reflect_constant_pool_klass);
1734   f->do_oop((oop*) &_reflect_unsafe_static_field_accessor_impl_klass);
1735 
1736   f->do_oop((oop*) &_stringBuffer_klass);
1737   f->do_oop((oop*) &_vector_klass);
1738   f->do_oop((oop*) &_hashtable_klass);
1739 
1740   f->do_oop((oop*) &_stackTraceElement_klass);
1741 
1742   f->do_oop((oop*) &_java_nio_Buffer_klass);
1743 
1744   f->do_oop((oop*) &_sun_misc_AtomicLongCSImpl_klass);
1745   f->do_oop((oop*) &_sun_jkernel_DownloadManager_klass);
1746 
1747   f->do_oop((oop*) &_boolean_klass);
1748   f->do_oop((oop*) &_char_klass);
1749   f->do_oop((oop*) &_float_klass);
1750   f->do_oop((oop*) &_double_klass);
1751   f->do_oop((oop*) &_byte_klass);
1752   f->do_oop((oop*) &_short_klass);
1753   f->do_oop((oop*) &_int_klass);
1754   f->do_oop((oop*) &_long_klass);
1755   {
1756     for (int i = 0; i < T_VOID+1; i++) {
1757       if (_box_klasses[i] != NULL) {
1758         assert(i >= T_BOOLEAN, "checking");
1759         f->do_oop((oop*) &_box_klasses[i]);
1760       }
1761     }
1762   }
1763 
1764   // The basic type mirrors would have already been processed in
1765   // Universe::oops_do(), via a call to shared_oops_do(), so should
1766   // not be processed again.
1767 
1768   f->do_oop((oop*) &_system_loader_lock_obj); 
1769   FilteredFieldsMap::klasses_oops_do(f); 
1770 }
1771 
1772 void SystemDictionary::lazily_loaded_oops_do(OopClosure* f) {
1773   f->do_oop((oop*) &_abstract_ownable_synchronizer_klass);
1774 }
1775 
1776 // Just the classes from defining class loaders
1777 // Don't iterate over placeholders
1778 void SystemDictionary::classes_do(void f(klassOop)) {
1779   dictionary()->classes_do(f);
1780 }
1781 
1782 // Added for initialize_itable_for_klass
1783 //   Just the classes from defining class loaders
1784 // Don't iterate over placeholders
1785 void SystemDictionary::classes_do(void f(klassOop, TRAPS), TRAPS) {
1786   dictionary()->classes_do(f, CHECK);
1787 }
1788 
1789 //   All classes, and their class loaders
1790 // Don't iterate over placeholders
1791 void SystemDictionary::classes_do(void f(klassOop, oop)) {
1792   dictionary()->classes_do(f);
1793 }
1794 
1795 //   All classes, and their class loaders
1796 //   (added for helpers that use HandleMarks and ResourceMarks)
1797 // Don't iterate over placeholders
1798 void SystemDictionary::classes_do(void f(klassOop, oop, TRAPS), TRAPS) {
1799   dictionary()->classes_do(f, CHECK);
1800 }
1801 
1802 void SystemDictionary::placeholders_do(void f(symbolOop, oop)) {
1803   placeholders()->entries_do(f);
1804 }
1805 
1806 void SystemDictionary::methods_do(void f(methodOop)) {
1807   dictionary()->methods_do(f);
1808 }
1809 
1810 // ----------------------------------------------------------------------------
1811 // Lazily load klasses
1812 
1813 void SystemDictionary::load_abstract_ownable_synchronizer_klass(TRAPS) {
1814   assert(JDK_Version::is_gte_jdk16x_version(), "Must be JDK 1.6 or later");
1815 
1816   // if multiple threads calling this function, only one thread will load
1817   // the class.  The other threads will find the loaded version once the
1818   // class is loaded.
1819   klassOop aos = _abstract_ownable_synchronizer_klass;
1820   if (aos == NULL) {
1821     klassOop k = resolve_or_fail(vmSymbolHandles::java_util_concurrent_locks_AbstractOwnableSynchronizer(), true, CHECK);
1822     // Force a fence to prevent any read before the write completes
1823     OrderAccess::fence();
1824     _abstract_ownable_synchronizer_klass = k;
1825   }
1826 }
1827 
1828 // ----------------------------------------------------------------------------
1829 // Initialization
1830 
1831 void SystemDictionary::initialize(TRAPS) {
1832   // Allocate arrays
1833   assert(dictionary() == NULL,
1834          "SystemDictionary should only be initialized once");
1835   _dictionary = new Dictionary(_nof_buckets);
1836   _placeholders = new PlaceholderTable(_nof_buckets);
1837   _number_of_modifications = 0;
1838   _loader_constraints = new LoaderConstraintTable(_loader_constraint_size);
1839   _resolution_errors = new ResolutionErrorTable(_resolution_error_size);
1840 
1841   // Allocate private object used as system class loader lock
1842   _system_loader_lock_obj = oopFactory::new_system_objArray(0, CHECK);
1843   // Initialize basic classes
1844   initialize_preloaded_classes(CHECK);
1845 }
1846 
1847 
1848 void SystemDictionary::initialize_preloaded_classes(TRAPS) {
1849   assert(_object_klass == NULL, "preloaded classes should only be initialized once");
1850   // Preload commonly used klasses
1851   _object_klass            = resolve_or_fail(vmSymbolHandles::java_lang_Object(),                true, CHECK);
1852   _string_klass            = resolve_or_fail(vmSymbolHandles::java_lang_String(),                true, CHECK);  
1853   _class_klass             = resolve_or_fail(vmSymbolHandles::java_lang_Class(),                 true, CHECK);
1854   debug_only(instanceKlass::verify_class_klass_nonstatic_oop_maps(_class_klass));
1855   // Fixup mirrors for classes loaded before java.lang.Class.
1856   // These calls iterate over the objects currently in the perm gen
1857   // so calling them at this point is matters (not before when there
1858   // are fewer objects and not later after there are more objects
1859   // in the perm gen.
1860   Universe::initialize_basic_type_mirrors(CHECK);
1861   Universe::fixup_mirrors(CHECK);
1862 
1863   _cloneable_klass         = resolve_or_fail(vmSymbolHandles::java_lang_Cloneable(),             true, CHECK);
1864   _classloader_klass       = resolve_or_fail(vmSymbolHandles::java_lang_ClassLoader(),           true, CHECK);
1865   _serializable_klass      = resolve_or_fail(vmSymbolHandles::java_io_Serializable(),            true, CHECK);
1866   _system_klass            = resolve_or_fail(vmSymbolHandles::java_lang_System(),                true, CHECK);  
1867 
1868   _throwable_klass         = resolve_or_fail(vmSymbolHandles::java_lang_Throwable(),             true, CHECK);
1869   _error_klass             = resolve_or_fail(vmSymbolHandles::java_lang_Error(),                 true, CHECK);
1870   _threaddeath_klass       = resolve_or_fail(vmSymbolHandles::java_lang_ThreadDeath(),           true, CHECK);
1871   _exception_klass         = resolve_or_fail(vmSymbolHandles::java_lang_Exception(),             true, CHECK);
1872   _runtime_exception_klass = resolve_or_fail(vmSymbolHandles::java_lang_RuntimeException(),      true, CHECK);
1873   _protectionDomain_klass  = resolve_or_fail(vmSymbolHandles::java_security_ProtectionDomain(),  true, CHECK);
1874   _AccessControlContext_klass = resolve_or_fail(vmSymbolHandles::java_security_AccessControlContext(),  true, CHECK);
1875   _classNotFoundException_klass = resolve_or_fail(vmSymbolHandles::java_lang_ClassNotFoundException(),  true, CHECK);
1876   _noClassDefFoundError_klass   = resolve_or_fail(vmSymbolHandles::java_lang_NoClassDefFoundError(),  true, CHECK);  
1877   _linkageError_klass   = resolve_or_fail(vmSymbolHandles::java_lang_LinkageError(),  true, CHECK);  
1878   _classCastException_klass = resolve_or_fail(vmSymbolHandles::java_lang_ClassCastException(),   true, CHECK);  
1879   _arrayStoreException_klass = resolve_or_fail(vmSymbolHandles::java_lang_ArrayStoreException(),   true, CHECK);  
1880   _virtualMachineError_klass = resolve_or_fail(vmSymbolHandles::java_lang_VirtualMachineError(),   true, CHECK);  
1881   _outOfMemoryError_klass  = resolve_or_fail(vmSymbolHandles::java_lang_OutOfMemoryError(),      true, CHECK);  
1882   _StackOverflowError_klass = resolve_or_fail(vmSymbolHandles::java_lang_StackOverflowError(),   true, CHECK);  
1883   _illegalMonitorStateException_klass = resolve_or_fail(vmSymbolHandles::java_lang_IllegalMonitorStateException(),   true, CHECK);  
1884 
1885   // Preload ref klasses and set reference types
1886   _reference_klass         = resolve_or_fail(vmSymbolHandles::java_lang_ref_Reference(),         true, CHECK);
1887   instanceKlass::cast(_reference_klass)->set_reference_type(REF_OTHER);
1888   instanceRefKlass::update_nonstatic_oop_maps(_reference_klass);
1889 
1890   _soft_reference_klass    = resolve_or_fail(vmSymbolHandles::java_lang_ref_SoftReference(),     true, CHECK);
1891   instanceKlass::cast(_soft_reference_klass)->set_reference_type(REF_SOFT);
1892   _weak_reference_klass    = resolve_or_fail(vmSymbolHandles::java_lang_ref_WeakReference(),     true, CHECK);
1893   instanceKlass::cast(_weak_reference_klass)->set_reference_type(REF_WEAK);
1894   _final_reference_klass   = resolve_or_fail(vmSymbolHandles::java_lang_ref_FinalReference(),    true, CHECK);
1895   instanceKlass::cast(_final_reference_klass)->set_reference_type(REF_FINAL);
1896   _phantom_reference_klass = resolve_or_fail(vmSymbolHandles::java_lang_ref_PhantomReference(),  true, CHECK);
1897   instanceKlass::cast(_phantom_reference_klass)->set_reference_type(REF_PHANTOM);
1898   _finalizer_klass         = resolve_or_fail(vmSymbolHandles::java_lang_ref_Finalizer(),         true, CHECK);
1899 
1900   _thread_klass           = resolve_or_fail(vmSymbolHandles::java_lang_Thread(),                true, CHECK);
1901   _threadGroup_klass      = resolve_or_fail(vmSymbolHandles::java_lang_ThreadGroup(),           true, CHECK);
1902   _properties_klass       = resolve_or_fail(vmSymbolHandles::java_util_Properties(),            true, CHECK);  
1903   _reflect_accessible_object_klass = resolve_or_fail(vmSymbolHandles::java_lang_reflect_AccessibleObject(),  true, CHECK);  
1904   _reflect_field_klass    = resolve_or_fail(vmSymbolHandles::java_lang_reflect_Field(),         true, CHECK);  
1905   _reflect_method_klass   = resolve_or_fail(vmSymbolHandles::java_lang_reflect_Method(),        true, CHECK);  
1906   _reflect_constructor_klass = resolve_or_fail(vmSymbolHandles::java_lang_reflect_Constructor(),   true, CHECK);  
1907   // Universe::is_gte_jdk14x_version() is not set up by this point.
1908   // It's okay if these turn out to be NULL in non-1.4 JDKs.
1909   _reflect_magic_klass    = resolve_or_null(vmSymbolHandles::sun_reflect_MagicAccessorImpl(),         CHECK);
1910   _reflect_method_accessor_klass = resolve_or_null(vmSymbolHandles::sun_reflect_MethodAccessorImpl(),     CHECK);
1911   _reflect_constructor_accessor_klass = resolve_or_null(vmSymbolHandles::sun_reflect_ConstructorAccessorImpl(),     CHECK);
1912   _reflect_delegating_classloader_klass = resolve_or_null(vmSymbolHandles::sun_reflect_DelegatingClassLoader(),     CHECK);
1913   _reflect_constant_pool_klass = resolve_or_null(vmSymbolHandles::sun_reflect_ConstantPool(),         CHECK);
1914   _reflect_unsafe_static_field_accessor_impl_klass = resolve_or_null(vmSymbolHandles::sun_reflect_UnsafeStaticFieldAccessorImpl(), CHECK);
1915 
1916   _vector_klass           = resolve_or_fail(vmSymbolHandles::java_util_Vector(),                true, CHECK);  
1917   _hashtable_klass        = resolve_or_fail(vmSymbolHandles::java_util_Hashtable(),             true, CHECK);  
1918   _stringBuffer_klass     = resolve_or_fail(vmSymbolHandles::java_lang_StringBuffer(),          true, CHECK);  
1919 
1920   // It's NULL in non-1.4 JDKs.
1921   _stackTraceElement_klass = resolve_or_null(vmSymbolHandles::java_lang_StackTraceElement(),          CHECK);
1922 
1923   // Universe::is_gte_jdk14x_version() is not set up by this point.
1924   // It's okay if this turns out to be NULL in non-1.4 JDKs.
1925   _java_nio_Buffer_klass   = resolve_or_null(vmSymbolHandles::java_nio_Buffer(),                 CHECK);
1926 
1927   // If this class isn't present, it won't be referenced.
1928   _sun_misc_AtomicLongCSImpl_klass = resolve_or_null(vmSymbolHandles::sun_misc_AtomicLongCSImpl(),     CHECK);
1929 #ifdef KERNEL
1930   _sun_jkernel_DownloadManager_klass = resolve_or_null(vmSymbolHandles::sun_jkernel_DownloadManager(),     CHECK);
1931   if (_sun_jkernel_DownloadManager_klass == NULL) {
1932     warning("Cannot find sun/jkernel/DownloadManager");
1933   }
1934 #endif // KERNEL
1935 
1936   // Preload boxing klasses
1937   _boolean_klass           = resolve_or_fail(vmSymbolHandles::java_lang_Boolean(),               true, CHECK);
1938   _char_klass              = resolve_or_fail(vmSymbolHandles::java_lang_Character(),             true, CHECK);
1939   _float_klass             = resolve_or_fail(vmSymbolHandles::java_lang_Float(),                 true, CHECK);
1940   _double_klass            = resolve_or_fail(vmSymbolHandles::java_lang_Double(),                true, CHECK);
1941   _byte_klass              = resolve_or_fail(vmSymbolHandles::java_lang_Byte(),                  true, CHECK);
1942   _short_klass             = resolve_or_fail(vmSymbolHandles::java_lang_Short(),                 true, CHECK);
1943   _int_klass               = resolve_or_fail(vmSymbolHandles::java_lang_Integer(),               true, CHECK);
1944   _long_klass              = resolve_or_fail(vmSymbolHandles::java_lang_Long(),                  true, CHECK);
1945 
1946   _box_klasses[T_BOOLEAN] = _boolean_klass;
1947   _box_klasses[T_CHAR]    = _char_klass;
1948   _box_klasses[T_FLOAT]   = _float_klass;
1949   _box_klasses[T_DOUBLE]  = _double_klass;
1950   _box_klasses[T_BYTE]    = _byte_klass;
1951   _box_klasses[T_SHORT]   = _short_klass;
1952   _box_klasses[T_INT]     = _int_klass;
1953   _box_klasses[T_LONG]    = _long_klass;
1954   //_box_klasses[T_OBJECT]  = _object_klass;
1955   //_box_klasses[T_ARRAY]   = _object_klass;
1956 
1957   { // Compute whether we should use loadClass or loadClassInternal when loading classes.
1958     methodOop method = instanceKlass::cast(classloader_klass())->find_method(vmSymbols::loadClassInternal_name(), vmSymbols::string_class_signature());
1959     _has_loadClassInternal = (method != NULL);
1960   }
1961 
1962   { // Compute whether we should use checkPackageAccess or NOT
1963     methodOop method = instanceKlass::cast(classloader_klass())->find_method(vmSymbols::checkPackageAccess_name(), vmSymbols::class_protectiondomain_signature());
1964     _has_checkPackageAccess = (method != NULL); 
1965   }
1966 }
1967 
1968 // Tells if a given klass is a box (wrapper class, such as java.lang.Integer).
1969 // If so, returns the basic type it holds.  If not, returns T_OBJECT.
1970 BasicType SystemDictionary::box_klass_type(klassOop k) {
1971   assert(k != NULL, "");
1972   for (int i = T_BOOLEAN; i < T_VOID+1; i++) {
1973     if (_box_klasses[i] == k)
1974       return (BasicType)i;
1975   }
1976   return T_OBJECT;
1977 }
1978 
1979 // Constraints on class loaders. The details of the algorithm can be
1980 // found in the OOPSLA'98 paper "Dynamic Class Loading in the Java
1981 // Virtual Machine" by Sheng Liang and Gilad Bracha.  The basic idea is
1982 // that the system dictionary needs to maintain a set of contraints that
1983 // must be satisfied by all classes in the dictionary.
1984 // if defining is true, then LinkageError if already in systemDictionary
1985 // if initiating loader, then ok if instanceKlass matches existing entry
1986 
1987 void SystemDictionary::check_constraints(int d_index, unsigned int d_hash,
1988                                          instanceKlassHandle k,
1989                                          Handle class_loader, bool defining, 
1990                                          TRAPS) {
1991   const char *linkage_error = NULL;
1992   {
1993     symbolHandle name (THREAD, k->name());
1994     MutexLocker mu(SystemDictionary_lock, THREAD);         
1995 
1996     klassOop check = find_class(d_index, d_hash, name, class_loader);
1997     if (check != (klassOop)NULL) { 
1998       // if different instanceKlass - duplicate class definition,
1999       // else - ok, class loaded by a different thread in parallel,
2000       // we should only have found it if it was done loading and ok to use 
2001       // system dictionary only holds instance classes, placeholders
2002       // also holds array classes
2003       
2004       assert(check->klass_part()->oop_is_instance(), "noninstance in systemdictionary");
2005       if ((defining == true) || (k() != check)) {
2006         linkage_error = "loader (instance of  %s): attempted  duplicate class "
2007           "definition for name: \"%s\"";
2008       } else {
2009         return;
2010       }
2011     }
2012 
2013 #ifdef ASSERT
2014     unsigned int p_hash = placeholders()->compute_hash(name, class_loader);
2015     int p_index = placeholders()->hash_to_index(p_hash);
2016     symbolOop ph_check = find_placeholder(p_index, p_hash, name, class_loader);
2017     assert(ph_check == NULL || ph_check == name(), "invalid symbol");
2018 #endif
2019 
2020     if (linkage_error == NULL) {
2021       if (constraints()->check_or_update(k, class_loader, name) == false) {
2022         linkage_error = "loader constraint violation: loader (instance of %s)"
2023           " previously initiated loading for a different type with name \"%s\"";
2024       }
2025     }
2026   }
2027 
2028   // Throw error now if needed (cannot throw while holding 
2029   // SystemDictionary_lock because of rank ordering)
2030 
2031   if (linkage_error) {
2032     ResourceMark rm(THREAD);
2033     const char* class_loader_name = loader_name(class_loader());
2034     char* type_name = k->name()->as_C_string();
2035     size_t buflen = strlen(linkage_error) + strlen(class_loader_name) +
2036       strlen(type_name);
2037     char* buf = NEW_RESOURCE_ARRAY_IN_THREAD(THREAD, char, buflen);
2038     jio_snprintf(buf, buflen, linkage_error, class_loader_name, type_name);
2039     THROW_MSG(vmSymbols::java_lang_LinkageError(), buf);
2040   }
2041 }
2042 
2043 
2044 // Update system dictionary - done after check_constraint and add_to_hierachy 
2045 // have been called.
2046 void SystemDictionary::update_dictionary(int d_index, unsigned int d_hash,
2047                                          int p_index, unsigned int p_hash,
2048                                          instanceKlassHandle k, 
2049                                          Handle class_loader, 
2050                                          TRAPS) {
2051   // Compile_lock prevents systemDictionary updates during compilations
2052   assert_locked_or_safepoint(Compile_lock);
2053   symbolHandle name (THREAD, k->name());
2054 
2055   {
2056   MutexLocker mu1(SystemDictionary_lock, THREAD);           
2057 
2058   // See whether biased locking is enabled and if so set it for this
2059   // klass.
2060   // Note that this must be done past the last potential blocking
2061   // point / safepoint. We enable biased locking lazily using a
2062   // VM_Operation to iterate the SystemDictionary and installing the
2063   // biasable mark word into each instanceKlass's prototype header.
2064   // To avoid race conditions where we accidentally miss enabling the
2065   // optimization for one class in the process of being added to the
2066   // dictionary, we must not safepoint after the test of
2067   // BiasedLocking::enabled().
2068   if (UseBiasedLocking && BiasedLocking::enabled()) {
2069     // Set biased locking bit for all loaded classes; it will be
2070     // cleared if revocation occurs too often for this type
2071     // NOTE that we must only do this when the class is initally
2072     // defined, not each time it is referenced from a new class loader
2073     if (k->class_loader() == class_loader()) {
2074       k->set_prototype_header(markOopDesc::biased_locking_prototype());
2075     }
2076   }
2077 
2078   // Check for a placeholder. If there, remove it and make a
2079   // new system dictionary entry.
2080   placeholders()->find_and_remove(p_index, p_hash, name, class_loader, THREAD);
2081   klassOop sd_check = find_class(d_index, d_hash, name, class_loader);
2082   if (sd_check == NULL) {
2083     dictionary()->add_klass(name, class_loader, k);
2084     notice_modification();
2085   }
2086 #ifdef ASSERT
2087   sd_check = find_class(d_index, d_hash, name, class_loader);
2088   assert (sd_check != NULL, "should have entry in system dictionary");
2089 // Changed to allow PH to remain to complete class circularity checking
2090 // while only one thread can define a class at one time, multiple
2091 // classes can resolve the superclass for a class at one time, 
2092 // and the placeholder is used to track that
2093 //  symbolOop ph_check = find_placeholder(p_index, p_hash, name, class_loader);
2094 //  assert (ph_check == NULL, "should not have a placeholder entry");
2095 #endif
2096     SystemDictionary_lock->notify_all();
2097   }
2098 }
2099 
2100 
2101 klassOop SystemDictionary::find_constrained_instance_or_array_klass(
2102                     symbolHandle class_name, Handle class_loader, TRAPS) {
2103 
2104   // First see if it has been loaded directly.
2105   // Force the protection domain to be null.  (This removes protection checks.)
2106   Handle no_protection_domain;
2107   klassOop klass = find_instance_or_array_klass(class_name, class_loader,
2108                                                 no_protection_domain, CHECK_NULL);
2109   if (klass != NULL)
2110     return klass;
2111 
2112   // Now look to see if it has been loaded elsewhere, and is subject to
2113   // a loader constraint that would require this loader to return the
2114   // klass that is already loaded.
2115   if (FieldType::is_array(class_name())) {
2116     // Array classes are hard because their klassOops are not kept in the
2117     // constraint table. The array klass may be constrained, but the elem class
2118     // may not be. 
2119     jint dimension;
2120     symbolOop object_key;
2121     BasicType t = FieldType::get_array_info(class_name(), &dimension,
2122                                             &object_key, CHECK_(NULL));
2123     if (t != T_OBJECT) {
2124       klass = Universe::typeArrayKlassObj(t);
2125     } else {
2126       symbolHandle elem_name(THREAD, object_key);
2127       MutexLocker mu(SystemDictionary_lock, THREAD);
2128       klass = constraints()->find_constrained_elem_klass(class_name, elem_name, class_loader, THREAD);
2129     }
2130     if (klass != NULL) {
2131       klass = Klass::cast(klass)->array_klass_or_null(dimension);
2132     }
2133   } else {
2134     MutexLocker mu(SystemDictionary_lock, THREAD);
2135     // Non-array classes are easy: simply check the constraint table.
2136     klass = constraints()->find_constrained_klass(class_name, class_loader);
2137   }
2138       
2139   return klass;
2140 }
2141 
2142 
2143 bool SystemDictionary::add_loader_constraint(symbolHandle class_name,
2144                                              Handle class_loader1,
2145                                              Handle class_loader2, 
2146                                              Thread* THREAD) {
2147   unsigned int d_hash1 = dictionary()->compute_hash(class_name, class_loader1);
2148   int d_index1 = dictionary()->hash_to_index(d_hash1);
2149 
2150   unsigned int d_hash2 = dictionary()->compute_hash(class_name, class_loader2);
2151   int d_index2 = dictionary()->hash_to_index(d_hash2);
2152 
2153   {
2154     MutexLocker mu_s(SystemDictionary_lock, THREAD);
2155 
2156     // Better never do a GC while we're holding these oops
2157     No_Safepoint_Verifier nosafepoint;
2158 
2159     klassOop klass1 = find_class(d_index1, d_hash1, class_name, class_loader1);
2160     klassOop klass2 = find_class(d_index2, d_hash2, class_name, class_loader2);
2161     return constraints()->add_entry(class_name, klass1, class_loader1,
2162                                     klass2, class_loader2);
2163   }
2164 }
2165 
2166 // Add entry to resolution error table to record the error when the first
2167 // attempt to resolve a reference to a class has failed.
2168 void SystemDictionary::add_resolution_error(constantPoolHandle pool, int which, symbolHandle error) {
2169   unsigned int hash = resolution_errors()->compute_hash(pool, which);
2170   int index = resolution_errors()->hash_to_index(hash);
2171   { 
2172     MutexLocker ml(SystemDictionary_lock, Thread::current());
2173     resolution_errors()->add_entry(index, hash, pool, which, error);
2174   }
2175 }
2176 
2177 // Lookup resolution error table. Returns error if found, otherwise NULL.
2178 symbolOop SystemDictionary::find_resolution_error(constantPoolHandle pool, int which) {
2179   unsigned int hash = resolution_errors()->compute_hash(pool, which);
2180   int index = resolution_errors()->hash_to_index(hash);
2181   { 
2182     MutexLocker ml(SystemDictionary_lock, Thread::current());
2183     ResolutionErrorEntry* entry = resolution_errors()->find_entry(index, hash, pool, which);
2184     return (entry != NULL) ? entry->error() : (symbolOop)NULL;
2185   }
2186 }
2187 
2188 
2189 // Make sure all class components (including arrays) in the given
2190 // signature will be resolved to the same class in both loaders.
2191 // Returns the name of the type that failed a loader constraint check, or
2192 // NULL if no constraint failed. The returned C string needs cleaning up
2193 // with a ResourceMark in the caller
2194 char* SystemDictionary::check_signature_loaders(symbolHandle signature,
2195                                                Handle loader1, Handle loader2,
2196                                                bool is_method, TRAPS)  {
2197   // Nothing to do if loaders are the same. 
2198   if (loader1() == loader2()) {
2199     return NULL;
2200   }
2201   
2202   SignatureStream sig_strm(signature, is_method);
2203   while (!sig_strm.is_done()) {
2204     if (sig_strm.is_object()) {
2205       symbolOop s = sig_strm.as_symbol(CHECK_NULL);
2206       symbolHandle sig (THREAD, s);
2207       if (!add_loader_constraint(sig, loader1, loader2, THREAD)) {
2208         return sig()->as_C_string();
2209       }
2210     }
2211     sig_strm.next();
2212   }
2213   return NULL;
2214 }
2215 
2216 
2217 // Since the identity hash code for symbols changes when the symbols are
2218 // moved from the regular perm gen (hash in the mark word) to the shared
2219 // spaces (hash is the address), the classes loaded into the dictionary
2220 // may be in the wrong buckets.
2221 
2222 void SystemDictionary::reorder_dictionary() {
2223   dictionary()->reorder_dictionary();
2224 }
2225 
2226 
2227 void SystemDictionary::copy_buckets(char** top, char* end) {
2228   dictionary()->copy_buckets(top, end);
2229 }
2230 
2231 
2232 void SystemDictionary::copy_table(char** top, char* end) {
2233   dictionary()->copy_table(top, end);
2234 }
2235 
2236 
2237 void SystemDictionary::reverse() {
2238   dictionary()->reverse();
2239 }
2240 
2241 int SystemDictionary::number_of_classes() {
2242   return dictionary()->number_of_entries();
2243 }
2244 
2245 
2246 // ----------------------------------------------------------------------------
2247 #ifndef PRODUCT
2248 
2249 void SystemDictionary::print() {
2250   dictionary()->print();
2251 
2252   // Placeholders
2253   GCMutexLocker mu(SystemDictionary_lock);
2254   placeholders()->print();
2255 
2256   // loader constraints - print under SD_lock
2257   constraints()->print();
2258 }
2259 
2260 #endif
2261 
2262 void SystemDictionary::verify() {
2263   guarantee(dictionary() != NULL, "Verify of system dictionary failed");
2264   guarantee(constraints() != NULL,
2265             "Verify of loader constraints failed");
2266   guarantee(dictionary()->number_of_entries() >= 0 &&
2267             placeholders()->number_of_entries() >= 0,
2268             "Verify of system dictionary failed");
2269 
2270   // Verify dictionary
2271   dictionary()->verify();
2272 
2273   GCMutexLocker mu(SystemDictionary_lock);
2274   placeholders()->verify();
2275 
2276   // Verify constraint table
2277   guarantee(constraints() != NULL, "Verify of loader constraints failed");
2278   constraints()->verify(dictionary());
2279 }
2280 
2281 
2282 void SystemDictionary::verify_obj_klass_present(Handle obj,
2283                                                 symbolHandle class_name,
2284                                                 Handle class_loader) {
2285   GCMutexLocker mu(SystemDictionary_lock);
2286   oop probe = find_class_or_placeholder(class_name, class_loader);
2287   if (probe == NULL) {
2288     probe = SystemDictionary::find_shared_class(class_name);
2289   }
2290   guarantee(probe != NULL && 
2291             (!probe->is_klass() || probe == obj()), 
2292                      "Loaded klasses should be in SystemDictionary");
2293 }
2294 
2295 #ifndef PRODUCT
2296 
2297 // statistics code
2298 class ClassStatistics: AllStatic {
2299  private:
2300   static int nclasses;        // number of classes
2301   static int nmethods;        // number of methods
2302   static int nmethoddata;     // number of methodData    
2303   static int class_size;      // size of class objects in words
2304   static int method_size;     // size of method objects in words
2305   static int debug_size;      // size of debug info in methods
2306   static int methoddata_size; // size of methodData objects in words
2307 
2308   static void do_class(klassOop k) {
2309     nclasses++;
2310     class_size += k->size();
2311     if (k->klass_part()->oop_is_instance()) {
2312       instanceKlass* ik = (instanceKlass*)k->klass_part();
2313       class_size += ik->methods()->size();
2314       class_size += ik->constants()->size();
2315       class_size += ik->local_interfaces()->size();
2316       class_size += ik->transitive_interfaces()->size();
2317       // We do not have to count implementors, since we only store one!      
2318       class_size += ik->fields()->size();
2319     }
2320   }
2321 
2322   static void do_method(methodOop m) {
2323     nmethods++;
2324     method_size += m->size();
2325     // class loader uses same objArray for empty vectors, so don't count these
2326     if (m->exception_table()->length() != 0)   method_size += m->exception_table()->size();
2327     if (m->has_stackmap_table()) {
2328       method_size += m->stackmap_data()->size();
2329     }
2330 
2331     methodDataOop mdo = m->method_data();
2332     if (mdo != NULL) {
2333       nmethoddata++;
2334       methoddata_size += mdo->size();
2335     }
2336   }
2337 
2338  public:
2339   static void print() {
2340     SystemDictionary::classes_do(do_class);
2341     SystemDictionary::methods_do(do_method);
2342     tty->print_cr("Class statistics:");
2343     tty->print_cr("%d classes (%d bytes)", nclasses, class_size * oopSize);
2344     tty->print_cr("%d methods (%d bytes = %d base + %d debug info)", nmethods, 
2345                   (method_size + debug_size) * oopSize, method_size * oopSize, debug_size * oopSize);
2346     tty->print_cr("%d methoddata (%d bytes)", nmethoddata, methoddata_size * oopSize);
2347   }
2348 };
2349 
2350 
2351 int ClassStatistics::nclasses        = 0;  
2352 int ClassStatistics::nmethods        = 0;
2353 int ClassStatistics::nmethoddata     = 0;
2354 int ClassStatistics::class_size      = 0;
2355 int ClassStatistics::method_size     = 0; 
2356 int ClassStatistics::debug_size      = 0;
2357 int ClassStatistics::methoddata_size = 0;
2358 
2359 void SystemDictionary::print_class_statistics() {
2360   ResourceMark rm;
2361   ClassStatistics::print();
2362 }
2363 
2364 
2365 class MethodStatistics: AllStatic {
2366  public:
2367   enum {
2368     max_parameter_size = 10
2369   };
2370  private:
2371 
2372   static int _number_of_methods;
2373   static int _number_of_final_methods;
2374   static int _number_of_static_methods;
2375   static int _number_of_native_methods;
2376   static int _number_of_synchronized_methods;
2377   static int _number_of_profiled_methods;
2378   static int _number_of_bytecodes;
2379   static int _parameter_size_profile[max_parameter_size];
2380   static int _bytecodes_profile[Bytecodes::number_of_java_codes];
2381 
2382   static void initialize() {
2383     _number_of_methods        = 0;
2384     _number_of_final_methods  = 0;
2385     _number_of_static_methods = 0;
2386     _number_of_native_methods = 0;
2387     _number_of_synchronized_methods = 0;
2388     _number_of_profiled_methods = 0;
2389     _number_of_bytecodes      = 0;
2390     for (int i = 0; i < max_parameter_size             ; i++) _parameter_size_profile[i] = 0;
2391     for (int j = 0; j < Bytecodes::number_of_java_codes; j++) _bytecodes_profile     [j] = 0;
2392   };
2393 
2394   static void do_method(methodOop m) {
2395     _number_of_methods++;
2396     // collect flag info
2397     if (m->is_final()       ) _number_of_final_methods++;
2398     if (m->is_static()      ) _number_of_static_methods++;
2399     if (m->is_native()      ) _number_of_native_methods++;
2400     if (m->is_synchronized()) _number_of_synchronized_methods++;
2401     if (m->method_data() != NULL) _number_of_profiled_methods++;
2402     // collect parameter size info (add one for receiver, if any)
2403     _parameter_size_profile[MIN2(m->size_of_parameters() + (m->is_static() ? 0 : 1), max_parameter_size - 1)]++;
2404     // collect bytecodes info
2405     { 
2406       Thread *thread = Thread::current();
2407       HandleMark hm(thread);
2408       BytecodeStream s(methodHandle(thread, m));
2409       Bytecodes::Code c;
2410       while ((c = s.next()) >= 0) {
2411         _number_of_bytecodes++;
2412         _bytecodes_profile[c]++;
2413       }
2414     }
2415   }
2416 
2417  public:
2418   static void print() {
2419     initialize();
2420     SystemDictionary::methods_do(do_method);
2421     // generate output
2422     tty->cr();
2423     tty->print_cr("Method statistics (static):");
2424     // flag distribution
2425     tty->cr();
2426     tty->print_cr("%6d final        methods  %6.1f%%", _number_of_final_methods       , _number_of_final_methods        * 100.0F / _number_of_methods);
2427     tty->print_cr("%6d static       methods  %6.1f%%", _number_of_static_methods      , _number_of_static_methods       * 100.0F / _number_of_methods);
2428     tty->print_cr("%6d native       methods  %6.1f%%", _number_of_native_methods      , _number_of_native_methods       * 100.0F / _number_of_methods);
2429     tty->print_cr("%6d synchronized methods  %6.1f%%", _number_of_synchronized_methods, _number_of_synchronized_methods * 100.0F / _number_of_methods);
2430     tty->print_cr("%6d profiled     methods  %6.1f%%", _number_of_profiled_methods, _number_of_profiled_methods * 100.0F / _number_of_methods);
2431     // parameter size profile
2432     tty->cr();
2433     { int tot = 0;
2434       int avg = 0;
2435       for (int i = 0; i < max_parameter_size; i++) {
2436         int n = _parameter_size_profile[i];
2437         tot += n;
2438         avg += n*i;
2439         tty->print_cr("parameter size = %1d: %6d methods  %5.1f%%", i, n, n * 100.0F / _number_of_methods);
2440       }
2441       assert(tot == _number_of_methods, "should be the same");
2442       tty->print_cr("                    %6d methods  100.0%%", _number_of_methods);
2443       tty->print_cr("(average parameter size = %3.1f including receiver, if any)", (float)avg / _number_of_methods);
2444     }
2445     // bytecodes profile
2446     tty->cr();
2447     { int tot = 0;
2448       for (int i = 0; i < Bytecodes::number_of_java_codes; i++) {
2449         if (Bytecodes::is_defined(i)) {
2450           Bytecodes::Code c = Bytecodes::cast(i);
2451           int n = _bytecodes_profile[c];
2452           tot += n;
2453           tty->print_cr("%9d  %7.3f%%  %s", n, n * 100.0F / _number_of_bytecodes, Bytecodes::name(c));
2454         }
2455       }
2456       assert(tot == _number_of_bytecodes, "should be the same");
2457       tty->print_cr("%9d  100.000%%", _number_of_bytecodes);
2458     }
2459     tty->cr();
2460   }
2461 };
2462 
2463 int MethodStatistics::_number_of_methods;
2464 int MethodStatistics::_number_of_final_methods;
2465 int MethodStatistics::_number_of_static_methods;
2466 int MethodStatistics::_number_of_native_methods;
2467 int MethodStatistics::_number_of_synchronized_methods;
2468 int MethodStatistics::_number_of_profiled_methods;
2469 int MethodStatistics::_number_of_bytecodes;
2470 int MethodStatistics::_parameter_size_profile[MethodStatistics::max_parameter_size];
2471 int MethodStatistics::_bytecodes_profile[Bytecodes::number_of_java_codes];
2472 
2473 
2474 void SystemDictionary::print_method_statistics() {
2475   MethodStatistics::print();
2476 }
2477 
2478 #endif // PRODUCT