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