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