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                                         KlassHandle host_klass,
 941                                         GrowableArray<Handle>* cp_patches,
 942                                         TRAPS) {
 943   symbolHandle parsed_name;
 944 
 945   // Parse the stream. Note that we do this even though this klass might
 946   // already be present in the SystemDictionary, otherwise we would not
 947   // throw potential ClassFormatErrors.
 948   //
 949   // Note: "name" is updated.
 950   // Further note:  a placeholder will be added for this class when
 951   //   super classes are loaded (resolve_super_or_fail). We expect this
 952   //   to be called for all classes but java.lang.Object; and we preload
 953   //   java.lang.Object through resolve_or_fail, not this path.
 954 
 955   instanceKlassHandle k = ClassFileParser(st).parseClassFile(class_name,
 956                                                              class_loader,
 957                                                              protection_domain,
 958                                                              cp_patches,
 959                                                              parsed_name,
 960                                                              THREAD);
 961 
 962   // We don't redefine the class, so we just need to clean up whether there
 963   // was an error or not (don't want to modify any system dictionary
 964   // data structures).
 965   // Parsed name could be null if we threw an error before we got far
 966   // enough along to parse it -- in that case, there is nothing to clean up.
 967   if (!parsed_name.is_null()) {
 968     unsigned int p_hash = placeholders()->compute_hash(parsed_name,
 969                                                        class_loader);
 970     int p_index = placeholders()->hash_to_index(p_hash);
 971     {
 972     MutexLocker mu(SystemDictionary_lock, THREAD);
 973     placeholders()->find_and_remove(p_index, p_hash, parsed_name, class_loader, THREAD);
 974     SystemDictionary_lock->notify_all();
 975     }
 976   }
 977 
 978   if (host_klass.not_null() && k.not_null()) {
 979     assert(AnonymousClasses, "");
 980     // If it's anonymous, initialize it now, since nobody else will.
 981     k->set_host_klass(host_klass());
 982 
 983     {
 984       MutexLocker mu_r(Compile_lock, THREAD);
 985 
 986       // Add to class hierarchy, initialize vtables, and do possible
 987       // deoptimizations.
 988       add_to_hierarchy(k, CHECK_NULL); // No exception, but can block
 989 
 990       // But, do not add to system dictionary.
 991     }
 992 
 993     k->eager_initialize(THREAD);
 994 
 995     // notify jvmti
 996     if (JvmtiExport::should_post_class_load()) {
 997         assert(THREAD->is_Java_thread(), "thread->is_Java_thread()");
 998         JvmtiExport::post_class_load((JavaThread *) THREAD, k());
 999     }
1000   }
1001 
1002   return k();
1003 }
1004 
1005 // Add a klass to the system from a stream (called by jni_DefineClass and
1006 // JVM_DefineClass).
1007 // Note: class_name can be NULL. In that case we do not know the name of
1008 // the class until we have parsed the stream.
1009 
1010 klassOop SystemDictionary::resolve_from_stream(symbolHandle class_name,
1011                                                Handle class_loader,
1012                                                Handle protection_domain,
1013                                                ClassFileStream* st,
1014                                                TRAPS) {
1015 
1016   // Make sure we are synchronized on the class loader before we initiate
1017   // loading.
1018   Handle lockObject = compute_loader_lock_object(class_loader, THREAD);
1019   check_loader_lock_contention(lockObject, THREAD);
1020   ObjectLocker ol(lockObject, THREAD);
1021 
1022   symbolHandle parsed_name;
1023 
1024   // Parse the stream. Note that we do this even though this klass might
1025   // already be present in the SystemDictionary, otherwise we would not
1026   // throw potential ClassFormatErrors.
1027   //
1028   // Note: "name" is updated.
1029   // Further note:  a placeholder will be added for this class when
1030   //   super classes are loaded (resolve_super_or_fail). We expect this
1031   //   to be called for all classes but java.lang.Object; and we preload
1032   //   java.lang.Object through resolve_or_fail, not this path.
1033 
1034   instanceKlassHandle k = ClassFileParser(st).parseClassFile(class_name,
1035                                                              class_loader,
1036                                                              protection_domain,
1037                                                              parsed_name,
1038                                                              THREAD);
1039 
1040   const char* pkg = "java/";
1041   if (!HAS_PENDING_EXCEPTION &&
1042       !class_loader.is_null() &&
1043       !parsed_name.is_null() &&
1044       !strncmp((const char*)parsed_name->bytes(), pkg, strlen(pkg))) {
1045     // It is illegal to define classes in the "java." package from
1046     // JVM_DefineClass or jni_DefineClass unless you're the bootclassloader
1047     ResourceMark rm(THREAD);
1048     char* name = parsed_name->as_C_string();
1049     char* index = strrchr(name, '/');
1050     *index = '\0'; // chop to just the package name
1051     while ((index = strchr(name, '/')) != NULL) {
1052       *index = '.'; // replace '/' with '.' in package name
1053     }
1054     const char* fmt = "Prohibited package name: %s";
1055     size_t len = strlen(fmt) + strlen(name);
1056     char* message = NEW_RESOURCE_ARRAY(char, len);
1057     jio_snprintf(message, len, fmt, name);
1058     Exceptions::_throw_msg(THREAD_AND_LOCATION,
1059       vmSymbols::java_lang_SecurityException(), message);
1060   }
1061 
1062   if (!HAS_PENDING_EXCEPTION) {
1063     assert(!parsed_name.is_null(), "Sanity");
1064     assert(class_name.is_null() || class_name() == parsed_name(),
1065            "name mismatch");
1066     // Verification prevents us from creating names with dots in them, this
1067     // asserts that that's the case.
1068     assert(is_internal_format(parsed_name),
1069            "external class name format used internally");
1070 
1071     // Add class just loaded
1072     define_instance_class(k, THREAD);
1073   }
1074 
1075   // If parsing the class file or define_instance_class failed, we
1076   // need to remove the placeholder added on our behalf. But we
1077   // must make sure parsed_name is valid first (it won't be if we had
1078   // a format error before the class was parsed far enough to
1079   // find the name).
1080   if (HAS_PENDING_EXCEPTION && !parsed_name.is_null()) {
1081     unsigned int p_hash = placeholders()->compute_hash(parsed_name,
1082                                                        class_loader);
1083     int p_index = placeholders()->hash_to_index(p_hash);
1084     {
1085     MutexLocker mu(SystemDictionary_lock, THREAD);
1086     placeholders()->find_and_remove(p_index, p_hash, parsed_name, class_loader, THREAD);
1087     SystemDictionary_lock->notify_all();
1088     }
1089     return NULL;
1090   }
1091 
1092   // Make sure that we didn't leave a place holder in the
1093   // SystemDictionary; this is only done on success
1094   debug_only( {
1095     if (!HAS_PENDING_EXCEPTION) {
1096       assert(!parsed_name.is_null(), "parsed_name is still null?");
1097       symbolHandle h_name   (THREAD, k->name());
1098       Handle h_loader (THREAD, k->class_loader());
1099 
1100       MutexLocker mu(SystemDictionary_lock, THREAD);
1101 
1102       oop check = find_class_or_placeholder(parsed_name, class_loader);
1103       assert(check == k(), "should be present in the dictionary");
1104 
1105       oop check2 = find_class_or_placeholder(h_name, h_loader);
1106       assert(check == check2, "name inconsistancy in SystemDictionary");
1107     }
1108   } );
1109 
1110   return k();
1111 }
1112 
1113 
1114 void SystemDictionary::set_shared_dictionary(HashtableBucket* t, int length,
1115                                              int number_of_entries) {
1116   assert(length == _nof_buckets * sizeof(HashtableBucket),
1117          "bad shared dictionary size.");
1118   _shared_dictionary = new Dictionary(_nof_buckets, t, number_of_entries);
1119 }
1120 
1121 
1122 // If there is a shared dictionary, then find the entry for the
1123 // given shared system class, if any.
1124 
1125 klassOop SystemDictionary::find_shared_class(symbolHandle class_name) {
1126   if (shared_dictionary() != NULL) {
1127     unsigned int d_hash = dictionary()->compute_hash(class_name, Handle());
1128     int d_index = dictionary()->hash_to_index(d_hash);
1129     return shared_dictionary()->find_shared_class(d_index, d_hash, class_name);
1130   } else {
1131     return NULL;
1132   }
1133 }
1134 
1135 
1136 // Load a class from the shared spaces (found through the shared system
1137 // dictionary).  Force the superclass and all interfaces to be loaded.
1138 // Update the class definition to include sibling classes and no
1139 // subclasses (yet).  [Classes in the shared space are not part of the
1140 // object hierarchy until loaded.]
1141 
1142 instanceKlassHandle SystemDictionary::load_shared_class(
1143                  symbolHandle class_name, Handle class_loader, TRAPS) {
1144   instanceKlassHandle ik (THREAD, find_shared_class(class_name));
1145   return load_shared_class(ik, class_loader, THREAD);
1146 }
1147 
1148 // Note well!  Changes to this method may affect oop access order
1149 // in the shared archive.  Please take care to not make changes that
1150 // adversely affect cold start time by changing the oop access order
1151 // that is specified in dump.cpp MarkAndMoveOrderedReadOnly and
1152 // MarkAndMoveOrderedReadWrite closures.
1153 instanceKlassHandle SystemDictionary::load_shared_class(
1154                  instanceKlassHandle ik, Handle class_loader, TRAPS) {
1155   assert(class_loader.is_null(), "non-null classloader for shared class?");
1156   if (ik.not_null()) {
1157     instanceKlassHandle nh = instanceKlassHandle(); // null Handle
1158     symbolHandle class_name(THREAD, ik->name());
1159 
1160     // Found the class, now load the superclass and interfaces.  If they
1161     // are shared, add them to the main system dictionary and reset
1162     // their hierarchy references (supers, subs, and interfaces).
1163 
1164     if (ik->super() != NULL) {
1165       symbolHandle cn(THREAD, ik->super()->klass_part()->name());
1166       resolve_super_or_fail(class_name, cn,
1167                             class_loader, Handle(), true, CHECK_(nh));
1168     }
1169 
1170     objArrayHandle interfaces (THREAD, ik->local_interfaces());
1171     int num_interfaces = interfaces->length();
1172     for (int index = 0; index < num_interfaces; index++) {
1173       klassOop k = klassOop(interfaces->obj_at(index));
1174 
1175       // Note: can not use instanceKlass::cast here because
1176       // interfaces' instanceKlass's C++ vtbls haven't been
1177       // reinitialized yet (they will be once the interface classes
1178       // are loaded)
1179       symbolHandle name (THREAD, k->klass_part()->name());
1180       resolve_super_or_fail(class_name, name, class_loader, Handle(), false, CHECK_(nh));
1181     }
1182 
1183     // Adjust methods to recover missing data.  They need addresses for
1184     // interpreter entry points and their default native method address
1185     // must be reset.
1186 
1187     // Updating methods must be done under a lock so multiple
1188     // threads don't update these in parallel
1189     // Shared classes are all currently loaded by the bootstrap
1190     // classloader, so this will never cause a deadlock on
1191     // a custom class loader lock.
1192 
1193     {
1194       Handle lockObject = compute_loader_lock_object(class_loader, THREAD);
1195       check_loader_lock_contention(lockObject, THREAD);
1196       ObjectLocker ol(lockObject, THREAD, true);
1197 
1198       objArrayHandle methods (THREAD, ik->methods());
1199       int num_methods = methods->length();
1200       for (int index2 = 0; index2 < num_methods; ++index2) {
1201         methodHandle m(THREAD, methodOop(methods->obj_at(index2)));
1202         m()->link_method(m, CHECK_(nh));
1203       }
1204     }
1205 
1206     if (TraceClassLoading) {
1207       ResourceMark rm;
1208       tty->print("[Loaded %s", ik->external_name());
1209       tty->print(" from shared objects file");
1210       tty->print_cr("]");
1211     }
1212     // notify a class loaded from shared object
1213     ClassLoadingService::notify_class_loaded(instanceKlass::cast(ik()),
1214                                              true /* shared class */);
1215   }
1216   return ik;
1217 }
1218 
1219 #ifdef KERNEL
1220 // Some classes on the bootstrap class path haven't been installed on the
1221 // system yet.  Call the DownloadManager method to make them appear in the
1222 // bootstrap class path and try again to load the named class.
1223 // Note that with delegation class loaders all classes in another loader will
1224 // first try to call this so it'd better be fast!!
1225 static instanceKlassHandle download_and_retry_class_load(
1226                                                     symbolHandle class_name,
1227                                                     TRAPS) {
1228 
1229   klassOop dlm = SystemDictionary::sun_jkernel_DownloadManager_klass();
1230   instanceKlassHandle nk;
1231 
1232   // If download manager class isn't loaded just return.
1233   if (dlm == NULL) return nk;
1234 
1235   { HandleMark hm(THREAD);
1236     ResourceMark rm(THREAD);
1237     Handle s = java_lang_String::create_from_symbol(class_name, CHECK_(nk));
1238     Handle class_string = java_lang_String::externalize_classname(s, CHECK_(nk));
1239 
1240     // return value
1241     JavaValue result(T_OBJECT);
1242 
1243     // Call the DownloadManager.  We assume that it has a lock because
1244     // multiple classes could be not found and downloaded at the same time.
1245     // class sun.misc.DownloadManager;
1246     // public static String getBootClassPathEntryForClass(String className);
1247     JavaCalls::call_static(&result,
1248                        KlassHandle(THREAD, dlm),
1249                        vmSymbolHandles::getBootClassPathEntryForClass_name(),
1250                        vmSymbolHandles::string_string_signature(),
1251                        class_string,
1252                        CHECK_(nk));
1253 
1254     // Get result.string and add to bootclasspath
1255     assert(result.get_type() == T_OBJECT, "just checking");
1256     oop obj = (oop) result.get_jobject();
1257     if (obj == NULL) { return nk; }
1258 
1259     Handle h_obj(THREAD, obj);
1260     char* new_class_name = java_lang_String::as_platform_dependent_str(h_obj,
1261                                                                   CHECK_(nk));
1262 
1263     // lock the loader
1264     // we use this lock because JVMTI does.
1265     Handle loader_lock(THREAD, SystemDictionary::system_loader_lock());
1266 
1267     ObjectLocker ol(loader_lock, THREAD);
1268     // add the file to the bootclasspath
1269     ClassLoader::update_class_path_entry_list(new_class_name, true);
1270   } // end HandleMark
1271 
1272   if (TraceClassLoading) {
1273     ClassLoader::print_bootclasspath();
1274   }
1275   return ClassLoader::load_classfile(class_name, CHECK_(nk));
1276 }
1277 #endif // KERNEL
1278 
1279 
1280 instanceKlassHandle SystemDictionary::load_instance_class(symbolHandle class_name, Handle class_loader, TRAPS) {
1281   instanceKlassHandle nh = instanceKlassHandle(); // null Handle
1282   if (class_loader.is_null()) {
1283     // Search the shared system dictionary for classes preloaded into the
1284     // shared spaces.
1285     instanceKlassHandle k;
1286     k = load_shared_class(class_name, class_loader, THREAD);
1287 
1288     if (k.is_null()) {
1289       // Use VM class loader
1290       k = ClassLoader::load_classfile(class_name, CHECK_(nh));
1291     }
1292 
1293 #ifdef KERNEL
1294     // If the VM class loader has failed to load the class, call the
1295     // DownloadManager class to make it magically appear on the classpath
1296     // and try again.  This is only configured with the Kernel VM.
1297     if (k.is_null()) {
1298       k = download_and_retry_class_load(class_name, CHECK_(nh));
1299     }
1300 #endif // KERNEL
1301 
1302     // find_or_define_instance_class may return a different k
1303     if (!k.is_null()) {
1304       k = find_or_define_instance_class(class_name, class_loader, k, CHECK_(nh));
1305     }
1306     return k;
1307   } else {
1308     // Use user specified class loader to load class. Call loadClass operation on class_loader.
1309     ResourceMark rm(THREAD);
1310 
1311     Handle s = java_lang_String::create_from_symbol(class_name, CHECK_(nh));
1312     // Translate to external class name format, i.e., convert '/' chars to '.'
1313     Handle string = java_lang_String::externalize_classname(s, CHECK_(nh));
1314 
1315     JavaValue result(T_OBJECT);
1316 
1317     KlassHandle spec_klass (THREAD, SystemDictionary::classloader_klass());
1318 
1319     // UnsyncloadClass option means don't synchronize loadClass() calls.
1320     // loadClassInternal() is synchronized and public loadClass(String) is not.
1321     // This flag is for diagnostic purposes only. It is risky to call
1322     // custom class loaders without synchronization.
1323     // WARNING If a custom class loader does NOT synchronizer findClass, or callers of
1324     // findClass, this flag risks unexpected timing bugs in the field.
1325     // Do NOT assume this will be supported in future releases.
1326     if (!UnsyncloadClass && has_loadClassInternal()) {
1327       JavaCalls::call_special(&result,
1328                               class_loader,
1329                               spec_klass,
1330                               vmSymbolHandles::loadClassInternal_name(),
1331                               vmSymbolHandles::string_class_signature(),
1332                               string,
1333                               CHECK_(nh));
1334     } else {
1335       JavaCalls::call_virtual(&result,
1336                               class_loader,
1337                               spec_klass,
1338                               vmSymbolHandles::loadClass_name(),
1339                               vmSymbolHandles::string_class_signature(),
1340                               string,
1341                               CHECK_(nh));
1342     }
1343 
1344     assert(result.get_type() == T_OBJECT, "just checking");
1345     oop obj = (oop) result.get_jobject();
1346 
1347     // Primitive classes return null since forName() can not be
1348     // used to obtain any of the Class objects representing primitives or void
1349     if ((obj != NULL) && !(java_lang_Class::is_primitive(obj))) {
1350       instanceKlassHandle k =
1351                 instanceKlassHandle(THREAD, java_lang_Class::as_klassOop(obj));
1352       // For user defined Java class loaders, check that the name returned is
1353       // the same as that requested.  This check is done for the bootstrap
1354       // loader when parsing the class file.
1355       if (class_name() == k->name()) {
1356         return k;
1357       }
1358     }
1359     // Class is not found or has the wrong name, return NULL
1360     return nh;
1361   }
1362 }
1363 
1364 void SystemDictionary::define_instance_class(instanceKlassHandle k, TRAPS) {
1365 
1366   Handle class_loader_h(THREAD, k->class_loader());
1367 
1368   // for bootstrap classloader don't acquire lock
1369   if (!class_loader_h.is_null()) {
1370     assert(ObjectSynchronizer::current_thread_holds_lock((JavaThread*)THREAD,
1371          compute_loader_lock_object(class_loader_h, THREAD)),
1372          "define called without lock");
1373   }
1374 
1375 
1376   // Check class-loading constraints. Throw exception if violation is detected.
1377   // Grabs and releases SystemDictionary_lock
1378   // The check_constraints/find_class call and update_dictionary sequence
1379   // must be "atomic" for a specific class/classloader pair so we never
1380   // define two different instanceKlasses for that class/classloader pair.
1381   // Existing classloaders will call define_instance_class with the
1382   // classloader lock held
1383   // Parallel classloaders will call find_or_define_instance_class
1384   // which will require a token to perform the define class
1385   symbolHandle name_h(THREAD, k->name());
1386   unsigned int d_hash = dictionary()->compute_hash(name_h, class_loader_h);
1387   int d_index = dictionary()->hash_to_index(d_hash);
1388   check_constraints(d_index, d_hash, k, class_loader_h, true, CHECK);
1389 
1390   // Register class just loaded with class loader (placed in Vector)
1391   // Note we do this before updating the dictionary, as this can
1392   // fail with an OutOfMemoryError (if it does, we will *not* put this
1393   // class in the dictionary and will not update the class hierarchy).
1394   if (k->class_loader() != NULL) {
1395     methodHandle m(THREAD, Universe::loader_addClass_method());
1396     JavaValue result(T_VOID);
1397     JavaCallArguments args(class_loader_h);
1398     args.push_oop(Handle(THREAD, k->java_mirror()));
1399     JavaCalls::call(&result, m, &args, CHECK);
1400   }
1401 
1402   // Add the new class. We need recompile lock during update of CHA.
1403   {
1404     unsigned int p_hash = placeholders()->compute_hash(name_h, class_loader_h);
1405     int p_index = placeholders()->hash_to_index(p_hash);
1406 
1407     MutexLocker mu_r(Compile_lock, THREAD);
1408 
1409     // Add to class hierarchy, initialize vtables, and do possible
1410     // deoptimizations.
1411     add_to_hierarchy(k, CHECK); // No exception, but can block
1412 
1413     // Add to systemDictionary - so other classes can see it.
1414     // Grabs and releases SystemDictionary_lock
1415     update_dictionary(d_index, d_hash, p_index, p_hash,
1416                       k, class_loader_h, THREAD);
1417   }
1418   k->eager_initialize(THREAD);
1419 
1420   // notify jvmti
1421   if (JvmtiExport::should_post_class_load()) {
1422       assert(THREAD->is_Java_thread(), "thread->is_Java_thread()");
1423       JvmtiExport::post_class_load((JavaThread *) THREAD, k());
1424 
1425   }
1426 }
1427 
1428 // Support parallel classloading
1429 // Initial implementation for bootstrap classloader
1430 // For future:
1431 // For custom class loaders that support parallel classloading,
1432 // in case they do not synchronize around
1433 // FindLoadedClass/DefineClass calls, we check for parallel
1434 // loading for them, wait if a defineClass is in progress
1435 // and return the initial requestor's results
1436 // For better performance, the class loaders should synchronize
1437 // findClass(), i.e. FindLoadedClass/DefineClass or they
1438 // potentially waste time reading and parsing the bytestream.
1439 // Note: VM callers should ensure consistency of k/class_name,class_loader
1440 instanceKlassHandle SystemDictionary::find_or_define_instance_class(symbolHandle class_name, Handle class_loader, instanceKlassHandle k, TRAPS) {
1441 
1442   instanceKlassHandle nh = instanceKlassHandle(); // null Handle
1443 
1444   unsigned int d_hash = dictionary()->compute_hash(class_name, class_loader);
1445   int d_index = dictionary()->hash_to_index(d_hash);
1446 
1447 // Hold SD lock around find_class and placeholder creation for DEFINE_CLASS
1448   unsigned int p_hash = placeholders()->compute_hash(class_name, class_loader);
1449   int p_index = placeholders()->hash_to_index(p_hash);
1450   PlaceholderEntry* probe;
1451 
1452   {
1453     MutexLocker mu(SystemDictionary_lock, THREAD);
1454     // First check if class already defined
1455     klassOop check = find_class(d_index, d_hash, class_name, class_loader);
1456     if (check != NULL) {
1457       return(instanceKlassHandle(THREAD, check));
1458     }
1459 
1460     // Acquire define token for this class/classloader
1461     symbolHandle nullsymbolHandle;
1462     probe = placeholders()->find_and_add(p_index, p_hash, class_name, class_loader, PlaceholderTable::DEFINE_CLASS, nullsymbolHandle, THREAD);
1463     // Check if another thread defining in parallel
1464     if (probe->definer() == NULL) {
1465       // Thread will define the class
1466       probe->set_definer(THREAD);
1467     } else {
1468       // Wait for defining thread to finish and return results
1469       while (probe->definer() != NULL) {
1470         SystemDictionary_lock->wait();
1471       }
1472       if (probe->instanceKlass() != NULL) {
1473         probe->remove_seen_thread(THREAD, PlaceholderTable::DEFINE_CLASS);
1474         return(instanceKlassHandle(THREAD, probe->instanceKlass()));
1475       } else {
1476         // If definer had an error, try again as any new thread would
1477         probe->set_definer(THREAD);
1478 #ifdef ASSERT
1479         klassOop check = find_class(d_index, d_hash, class_name, class_loader);
1480         assert(check == NULL, "definer missed recording success");
1481 #endif
1482       }
1483     }
1484   }
1485 
1486   define_instance_class(k, THREAD);
1487 
1488   Handle linkage_exception = Handle(); // null handle
1489 
1490   // definer must notify any waiting threads
1491   {
1492     MutexLocker mu(SystemDictionary_lock, THREAD);
1493     PlaceholderEntry* probe = placeholders()->get_entry(p_index, p_hash, class_name, class_loader);
1494     assert(probe != NULL, "DEFINE_CLASS placeholder lost?");
1495     if (probe != NULL) {
1496       if (HAS_PENDING_EXCEPTION) {
1497         linkage_exception = Handle(THREAD,PENDING_EXCEPTION);
1498         CLEAR_PENDING_EXCEPTION;
1499       } else {
1500         probe->set_instanceKlass(k());
1501       }
1502       probe->set_definer(NULL);
1503       probe->remove_seen_thread(THREAD, PlaceholderTable::DEFINE_CLASS);
1504       SystemDictionary_lock->notify_all();
1505     }
1506   }
1507 
1508   // Can't throw exception while holding lock due to rank ordering
1509   if (linkage_exception() != NULL) {
1510     THROW_OOP_(linkage_exception(), nh); // throws exception and returns
1511   }
1512 
1513   return k;
1514 }
1515 
1516 Handle SystemDictionary::compute_loader_lock_object(Handle class_loader, TRAPS) {
1517   // If class_loader is NULL we synchronize on _system_loader_lock_obj
1518   if (class_loader.is_null()) {
1519     return Handle(THREAD, _system_loader_lock_obj);
1520   } else {
1521     return class_loader;
1522   }
1523 }
1524 
1525 // This method is added to check how often we have to wait to grab loader
1526 // lock. The results are being recorded in the performance counters defined in
1527 // ClassLoader::_sync_systemLoaderLockContentionRate and
1528 // ClassLoader::_sync_nonSystemLoaderLockConteionRate.
1529 void SystemDictionary::check_loader_lock_contention(Handle loader_lock, TRAPS) {
1530   if (!UsePerfData) {
1531     return;
1532   }
1533 
1534   assert(!loader_lock.is_null(), "NULL lock object");
1535 
1536   if (ObjectSynchronizer::query_lock_ownership((JavaThread*)THREAD, loader_lock)
1537       == ObjectSynchronizer::owner_other) {
1538     // contention will likely happen, so increment the corresponding
1539     // contention counter.
1540     if (loader_lock() == _system_loader_lock_obj) {
1541       ClassLoader::sync_systemLoaderLockContentionRate()->inc();
1542     } else {
1543       ClassLoader::sync_nonSystemLoaderLockContentionRate()->inc();
1544     }
1545   }
1546 }
1547 
1548 // ----------------------------------------------------------------------------
1549 // Lookup
1550 
1551 klassOop SystemDictionary::find_class(int index, unsigned int hash,
1552                                       symbolHandle class_name,
1553                                       Handle class_loader) {
1554   assert_locked_or_safepoint(SystemDictionary_lock);
1555   assert (index == dictionary()->index_for(class_name, class_loader),
1556           "incorrect index?");
1557 
1558   klassOop k = dictionary()->find_class(index, hash, class_name, class_loader);
1559   return k;
1560 }
1561 
1562 
1563 // Basic find on classes in the midst of being loaded
1564 symbolOop SystemDictionary::find_placeholder(int index, unsigned int hash,
1565                                              symbolHandle class_name,
1566                                              Handle class_loader) {
1567   assert_locked_or_safepoint(SystemDictionary_lock);
1568 
1569   return placeholders()->find_entry(index, hash, class_name, class_loader);
1570 }
1571 
1572 
1573 // Used for assertions and verification only
1574 oop SystemDictionary::find_class_or_placeholder(symbolHandle class_name,
1575                                                 Handle class_loader) {
1576   #ifndef ASSERT
1577   guarantee(VerifyBeforeGC   ||
1578             VerifyDuringGC   ||
1579             VerifyBeforeExit ||
1580             VerifyAfterGC, "too expensive");
1581   #endif
1582   assert_locked_or_safepoint(SystemDictionary_lock);
1583   symbolOop class_name_ = class_name();
1584   oop class_loader_ = class_loader();
1585 
1586   // First look in the loaded class array
1587   unsigned int d_hash = dictionary()->compute_hash(class_name, class_loader);
1588   int d_index = dictionary()->hash_to_index(d_hash);
1589   oop lookup = find_class(d_index, d_hash, class_name, class_loader);
1590 
1591   if (lookup == NULL) {
1592     // Next try the placeholders
1593     unsigned int p_hash = placeholders()->compute_hash(class_name,class_loader);
1594     int p_index = placeholders()->hash_to_index(p_hash);
1595     lookup = find_placeholder(p_index, p_hash, class_name, class_loader);
1596   }
1597 
1598   return lookup;
1599 }
1600 
1601 
1602 // Get the next class in the diictionary.
1603 klassOop SystemDictionary::try_get_next_class() {
1604   return dictionary()->try_get_next_class();
1605 }
1606 
1607 
1608 // ----------------------------------------------------------------------------
1609 // Update hierachy. This is done before the new klass has been added to the SystemDictionary. The Recompile_lock
1610 // is held, to ensure that the compiler is not using the class hierachy, and that deoptimization will kick in
1611 // before a new class is used.
1612 
1613 void SystemDictionary::add_to_hierarchy(instanceKlassHandle k, TRAPS) {
1614   assert(k.not_null(), "just checking");
1615   // Link into hierachy. Make sure the vtables are initialized before linking into
1616   k->append_to_sibling_list();                    // add to superklass/sibling list
1617   k->process_interfaces(THREAD);                  // handle all "implements" declarations
1618   k->set_init_state(instanceKlass::loaded);
1619   // Now flush all code that depended on old class hierarchy.
1620   // Note: must be done *after* linking k into the hierarchy (was bug 12/9/97)
1621   // Also, first reinitialize vtable because it may have gotten out of synch
1622   // while the new class wasn't connected to the class hierarchy.
1623   Universe::flush_dependents_on(k);
1624 }
1625 
1626 
1627 // ----------------------------------------------------------------------------
1628 // GC support
1629 
1630 // Following roots during mark-sweep is separated in two phases.
1631 //
1632 // The first phase follows preloaded classes and all other system
1633 // classes, since these will never get unloaded anyway.
1634 //
1635 // The second phase removes (unloads) unreachable classes from the
1636 // system dictionary and follows the remaining classes' contents.
1637 
1638 void SystemDictionary::always_strong_oops_do(OopClosure* blk) {
1639   // Follow preloaded classes/mirrors and system loader object
1640   blk->do_oop(&_java_system_loader);
1641   preloaded_oops_do(blk);
1642   always_strong_classes_do(blk);
1643 }
1644 
1645 
1646 void SystemDictionary::always_strong_classes_do(OopClosure* blk) {
1647   // Follow all system classes and temporary placeholders in dictionary
1648   dictionary()->always_strong_classes_do(blk);
1649 
1650   // Placeholders. These are *always* strong roots, as they
1651   // represent classes we're actively loading.
1652   placeholders_do(blk);
1653 
1654   // Loader constraints. We must keep the symbolOop used in the name alive.
1655   constraints()->always_strong_classes_do(blk);
1656 
1657   // Resolution errors keep the symbolOop for the error alive
1658   resolution_errors()->always_strong_classes_do(blk);
1659 }
1660 
1661 
1662 void SystemDictionary::placeholders_do(OopClosure* blk) {
1663   placeholders()->oops_do(blk);
1664 }
1665 
1666 
1667 bool SystemDictionary::do_unloading(BoolObjectClosure* is_alive) {
1668   bool result = dictionary()->do_unloading(is_alive);
1669   constraints()->purge_loader_constraints(is_alive);
1670   resolution_errors()->purge_resolution_errors(is_alive);
1671   return result;
1672 }
1673 
1674 
1675 // The mirrors are scanned by shared_oops_do() which is
1676 // not called by oops_do().  In order to process oops in
1677 // a necessary order, shared_oops_do() is call by
1678 // Universe::oops_do().
1679 void SystemDictionary::oops_do(OopClosure* f) {
1680   // Adjust preloaded classes and system loader object
1681   f->do_oop(&_java_system_loader);
1682   preloaded_oops_do(f);
1683 
1684   lazily_loaded_oops_do(f);
1685 
1686   // Adjust dictionary
1687   dictionary()->oops_do(f);
1688 
1689   // Partially loaded classes
1690   placeholders()->oops_do(f);
1691 
1692   // Adjust constraint table
1693   constraints()->oops_do(f);
1694 
1695   // Adjust resolution error table
1696   resolution_errors()->oops_do(f);
1697 }
1698 
1699 
1700 void SystemDictionary::preloaded_oops_do(OopClosure* f) {
1701   f->do_oop((oop*) &wk_klass_name_limits[0]);
1702   f->do_oop((oop*) &wk_klass_name_limits[1]);
1703 
1704   for (int k = (int)FIRST_WKID; k < (int)WKID_LIMIT; k++) {
1705     f->do_oop((oop*) &_well_known_klasses[k]);
1706   }
1707 
1708   {
1709     for (int i = 0; i < T_VOID+1; i++) {
1710       if (_box_klasses[i] != NULL) {
1711         assert(i >= T_BOOLEAN, "checking");
1712         f->do_oop((oop*) &_box_klasses[i]);
1713       }
1714     }
1715   }
1716 
1717   // The basic type mirrors would have already been processed in
1718   // Universe::oops_do(), via a call to shared_oops_do(), so should
1719   // not be processed again.
1720 
1721   f->do_oop((oop*) &_system_loader_lock_obj);
1722   FilteredFieldsMap::klasses_oops_do(f);
1723 }
1724 
1725 void SystemDictionary::lazily_loaded_oops_do(OopClosure* f) {
1726   f->do_oop((oop*) &_abstract_ownable_synchronizer_klass);
1727 }
1728 
1729 // Just the classes from defining class loaders
1730 // Don't iterate over placeholders
1731 void SystemDictionary::classes_do(void f(klassOop)) {
1732   dictionary()->classes_do(f);
1733 }
1734 
1735 // Added for initialize_itable_for_klass
1736 //   Just the classes from defining class loaders
1737 // Don't iterate over placeholders
1738 void SystemDictionary::classes_do(void f(klassOop, TRAPS), TRAPS) {
1739   dictionary()->classes_do(f, CHECK);
1740 }
1741 
1742 //   All classes, and their class loaders
1743 // Don't iterate over placeholders
1744 void SystemDictionary::classes_do(void f(klassOop, oop)) {
1745   dictionary()->classes_do(f);
1746 }
1747 
1748 //   All classes, and their class loaders
1749 //   (added for helpers that use HandleMarks and ResourceMarks)
1750 // Don't iterate over placeholders
1751 void SystemDictionary::classes_do(void f(klassOop, oop, TRAPS), TRAPS) {
1752   dictionary()->classes_do(f, CHECK);
1753 }
1754 
1755 void SystemDictionary::placeholders_do(void f(symbolOop, oop)) {
1756   placeholders()->entries_do(f);
1757 }
1758 
1759 void SystemDictionary::methods_do(void f(methodOop)) {
1760   dictionary()->methods_do(f);
1761 }
1762 
1763 // ----------------------------------------------------------------------------
1764 // Lazily load klasses
1765 
1766 void SystemDictionary::load_abstract_ownable_synchronizer_klass(TRAPS) {
1767   assert(JDK_Version::is_gte_jdk16x_version(), "Must be JDK 1.6 or later");
1768 
1769   // if multiple threads calling this function, only one thread will load
1770   // the class.  The other threads will find the loaded version once the
1771   // class is loaded.
1772   klassOop aos = _abstract_ownable_synchronizer_klass;
1773   if (aos == NULL) {
1774     klassOop k = resolve_or_fail(vmSymbolHandles::java_util_concurrent_locks_AbstractOwnableSynchronizer(), true, CHECK);
1775     // Force a fence to prevent any read before the write completes
1776     OrderAccess::fence();
1777     _abstract_ownable_synchronizer_klass = k;
1778   }
1779 }
1780 
1781 // ----------------------------------------------------------------------------
1782 // Initialization
1783 
1784 void SystemDictionary::initialize(TRAPS) {
1785   // Allocate arrays
1786   assert(dictionary() == NULL,
1787          "SystemDictionary should only be initialized once");
1788   _dictionary = new Dictionary(_nof_buckets);
1789   _placeholders = new PlaceholderTable(_nof_buckets);
1790   _number_of_modifications = 0;
1791   _loader_constraints = new LoaderConstraintTable(_loader_constraint_size);
1792   _resolution_errors = new ResolutionErrorTable(_resolution_error_size);
1793 
1794   // Allocate private object used as system class loader lock
1795   _system_loader_lock_obj = oopFactory::new_system_objArray(0, CHECK);
1796   // Initialize basic classes
1797   initialize_preloaded_classes(CHECK);
1798 }
1799 
1800 // Compact table of directions on the initialization of klasses:
1801 static const short wk_init_info[] = {
1802   #define WK_KLASS_INIT_INFO(name, symbol, option) \
1803     ( ((int)vmSymbols::VM_SYMBOL_ENUM_NAME(symbol) \
1804           << SystemDictionary::CEIL_LG_OPTION_LIMIT) \
1805       | (int)SystemDictionary::option ),
1806   WK_KLASSES_DO(WK_KLASS_INIT_INFO)
1807   #undef WK_KLASS_INIT_INFO
1808   0
1809 };
1810 
1811 bool SystemDictionary::initialize_wk_klass(WKID id, int init_opt, TRAPS) {
1812   assert(id >= (int)FIRST_WKID && id < (int)WKID_LIMIT, "oob");
1813   int  info = wk_init_info[id - FIRST_WKID];
1814   int  sid  = (info >> CEIL_LG_OPTION_LIMIT);
1815   symbolHandle symbol = vmSymbolHandles::symbol_handle_at((vmSymbols::SID)sid);
1816   klassOop*    klassp = &_well_known_klasses[id];
1817   bool must_load = (init_opt < SystemDictionary::Opt);
1818   bool try_load  = true;
1819   if (init_opt == SystemDictionary::Opt_Kernel) {
1820 #ifndef KERNEL
1821     try_load = false;
1822 #endif //KERNEL
1823   }
1824   if ((*klassp) == NULL && try_load) {
1825     if (must_load) {
1826       (*klassp) = resolve_or_fail(symbol, true, CHECK_0); // load required class
1827     } else {
1828       (*klassp) = resolve_or_null(symbol,       CHECK_0); // load optional klass
1829     }
1830   }
1831   return ((*klassp) != NULL);
1832 }
1833 
1834 void SystemDictionary::initialize_wk_klasses_until(WKID limit_id, WKID &start_id, TRAPS) {
1835   assert((int)start_id <= (int)limit_id, "IDs are out of order!");
1836   for (int id = (int)start_id; id < (int)limit_id; id++) {
1837     assert(id >= (int)FIRST_WKID && id < (int)WKID_LIMIT, "oob");
1838     int info = wk_init_info[id - FIRST_WKID];
1839     int sid  = (info >> CEIL_LG_OPTION_LIMIT);
1840     int opt  = (info & right_n_bits(CEIL_LG_OPTION_LIMIT));
1841 
1842     initialize_wk_klass((WKID)id, opt, CHECK);
1843 
1844     // Update limits, so find_well_known_klass can be very fast:
1845     symbolOop s = vmSymbols::symbol_at((vmSymbols::SID)sid);
1846     if (wk_klass_name_limits[1] == NULL) {
1847       wk_klass_name_limits[0] = wk_klass_name_limits[1] = s;
1848     } else if (wk_klass_name_limits[1] < s) {
1849       wk_klass_name_limits[1] = s;
1850     } else if (wk_klass_name_limits[0] > s) {
1851       wk_klass_name_limits[0] = s;
1852     }
1853   }
1854 }
1855 
1856 
1857 void SystemDictionary::initialize_preloaded_classes(TRAPS) {
1858   assert(WK_KLASS(object_klass) == NULL, "preloaded classes should only be initialized once");
1859   // Preload commonly used klasses
1860   WKID scan = FIRST_WKID;
1861   // first do Object, String, Class
1862   initialize_wk_klasses_through(WK_KLASS_ENUM_NAME(class_klass), scan, CHECK);
1863 
1864   debug_only(instanceKlass::verify_class_klass_nonstatic_oop_maps(WK_KLASS(class_klass)));
1865 
1866   // Fixup mirrors for classes loaded before java.lang.Class.
1867   // These calls iterate over the objects currently in the perm gen
1868   // so calling them at this point is matters (not before when there
1869   // are fewer objects and not later after there are more objects
1870   // in the perm gen.
1871   Universe::initialize_basic_type_mirrors(CHECK);
1872   Universe::fixup_mirrors(CHECK);
1873 
1874   // do a bunch more:
1875   initialize_wk_klasses_through(WK_KLASS_ENUM_NAME(reference_klass), scan, CHECK);
1876 
1877   // Preload ref klasses and set reference types
1878   instanceKlass::cast(WK_KLASS(reference_klass))->set_reference_type(REF_OTHER);
1879   instanceRefKlass::update_nonstatic_oop_maps(WK_KLASS(reference_klass));
1880 
1881   initialize_wk_klasses_through(WK_KLASS_ENUM_NAME(phantom_reference_klass), scan, CHECK);
1882   instanceKlass::cast(WK_KLASS(soft_reference_klass))->set_reference_type(REF_SOFT);
1883   instanceKlass::cast(WK_KLASS(weak_reference_klass))->set_reference_type(REF_WEAK);
1884   instanceKlass::cast(WK_KLASS(final_reference_klass))->set_reference_type(REF_FINAL);
1885   instanceKlass::cast(WK_KLASS(phantom_reference_klass))->set_reference_type(REF_PHANTOM);
1886 
1887   initialize_wk_klasses_until(WKID_LIMIT, scan, CHECK);
1888 
1889   _box_klasses[T_BOOLEAN] = WK_KLASS(boolean_klass);
1890   _box_klasses[T_CHAR]    = WK_KLASS(char_klass);
1891   _box_klasses[T_FLOAT]   = WK_KLASS(float_klass);
1892   _box_klasses[T_DOUBLE]  = WK_KLASS(double_klass);
1893   _box_klasses[T_BYTE]    = WK_KLASS(byte_klass);
1894   _box_klasses[T_SHORT]   = WK_KLASS(short_klass);
1895   _box_klasses[T_INT]     = WK_KLASS(int_klass);
1896   _box_klasses[T_LONG]    = WK_KLASS(long_klass);
1897   //_box_klasses[T_OBJECT]  = WK_KLASS(object_klass);
1898   //_box_klasses[T_ARRAY]   = WK_KLASS(object_klass);
1899 
1900 #ifdef KERNEL
1901   if (sun_jkernel_DownloadManager_klass() == NULL) {
1902     warning("Cannot find sun/jkernel/DownloadManager");
1903   }
1904 #endif // KERNEL
1905   { // Compute whether we should use loadClass or loadClassInternal when loading classes.
1906     methodOop method = instanceKlass::cast(classloader_klass())->find_method(vmSymbols::loadClassInternal_name(), vmSymbols::string_class_signature());
1907     _has_loadClassInternal = (method != NULL);
1908   }
1909 
1910   { // Compute whether we should use checkPackageAccess or NOT
1911     methodOop method = instanceKlass::cast(classloader_klass())->find_method(vmSymbols::checkPackageAccess_name(), vmSymbols::class_protectiondomain_signature());
1912     _has_checkPackageAccess = (method != NULL);
1913   }
1914 }
1915 
1916 // Tells if a given klass is a box (wrapper class, such as java.lang.Integer).
1917 // If so, returns the basic type it holds.  If not, returns T_OBJECT.
1918 BasicType SystemDictionary::box_klass_type(klassOop k) {
1919   assert(k != NULL, "");
1920   for (int i = T_BOOLEAN; i < T_VOID+1; i++) {
1921     if (_box_klasses[i] == k)
1922       return (BasicType)i;
1923   }
1924   return T_OBJECT;
1925 }
1926 
1927 // Constraints on class loaders. The details of the algorithm can be
1928 // found in the OOPSLA'98 paper "Dynamic Class Loading in the Java
1929 // Virtual Machine" by Sheng Liang and Gilad Bracha.  The basic idea is
1930 // that the system dictionary needs to maintain a set of contraints that
1931 // must be satisfied by all classes in the dictionary.
1932 // if defining is true, then LinkageError if already in systemDictionary
1933 // if initiating loader, then ok if instanceKlass matches existing entry
1934 
1935 void SystemDictionary::check_constraints(int d_index, unsigned int d_hash,
1936                                          instanceKlassHandle k,
1937                                          Handle class_loader, bool defining,
1938                                          TRAPS) {
1939   const char *linkage_error = NULL;
1940   {
1941     symbolHandle name (THREAD, k->name());
1942     MutexLocker mu(SystemDictionary_lock, THREAD);
1943 
1944     klassOop check = find_class(d_index, d_hash, name, class_loader);
1945     if (check != (klassOop)NULL) {
1946       // if different instanceKlass - duplicate class definition,
1947       // else - ok, class loaded by a different thread in parallel,
1948       // we should only have found it if it was done loading and ok to use
1949       // system dictionary only holds instance classes, placeholders
1950       // also holds array classes
1951 
1952       assert(check->klass_part()->oop_is_instance(), "noninstance in systemdictionary");
1953       if ((defining == true) || (k() != check)) {
1954         linkage_error = "loader (instance of  %s): attempted  duplicate class "
1955           "definition for name: \"%s\"";
1956       } else {
1957         return;
1958       }
1959     }
1960 
1961 #ifdef ASSERT
1962     unsigned int p_hash = placeholders()->compute_hash(name, class_loader);
1963     int p_index = placeholders()->hash_to_index(p_hash);
1964     symbolOop ph_check = find_placeholder(p_index, p_hash, name, class_loader);
1965     assert(ph_check == NULL || ph_check == name(), "invalid symbol");
1966 #endif
1967 
1968     if (linkage_error == NULL) {
1969       if (constraints()->check_or_update(k, class_loader, name) == false) {
1970         linkage_error = "loader constraint violation: loader (instance of %s)"
1971           " previously initiated loading for a different type with name \"%s\"";
1972       }
1973     }
1974   }
1975 
1976   // Throw error now if needed (cannot throw while holding
1977   // SystemDictionary_lock because of rank ordering)
1978 
1979   if (linkage_error) {
1980     ResourceMark rm(THREAD);
1981     const char* class_loader_name = loader_name(class_loader());
1982     char* type_name = k->name()->as_C_string();
1983     size_t buflen = strlen(linkage_error) + strlen(class_loader_name) +
1984       strlen(type_name);
1985     char* buf = NEW_RESOURCE_ARRAY_IN_THREAD(THREAD, char, buflen);
1986     jio_snprintf(buf, buflen, linkage_error, class_loader_name, type_name);
1987     THROW_MSG(vmSymbols::java_lang_LinkageError(), buf);
1988   }
1989 }
1990 
1991 
1992 // Update system dictionary - done after check_constraint and add_to_hierachy
1993 // have been called.
1994 void SystemDictionary::update_dictionary(int d_index, unsigned int d_hash,
1995                                          int p_index, unsigned int p_hash,
1996                                          instanceKlassHandle k,
1997                                          Handle class_loader,
1998                                          TRAPS) {
1999   // Compile_lock prevents systemDictionary updates during compilations
2000   assert_locked_or_safepoint(Compile_lock);
2001   symbolHandle name (THREAD, k->name());
2002 
2003   {
2004   MutexLocker mu1(SystemDictionary_lock, THREAD);
2005 
2006   // See whether biased locking is enabled and if so set it for this
2007   // klass.
2008   // Note that this must be done past the last potential blocking
2009   // point / safepoint. We enable biased locking lazily using a
2010   // VM_Operation to iterate the SystemDictionary and installing the
2011   // biasable mark word into each instanceKlass's prototype header.
2012   // To avoid race conditions where we accidentally miss enabling the
2013   // optimization for one class in the process of being added to the
2014   // dictionary, we must not safepoint after the test of
2015   // BiasedLocking::enabled().
2016   if (UseBiasedLocking && BiasedLocking::enabled()) {
2017     // Set biased locking bit for all loaded classes; it will be
2018     // cleared if revocation occurs too often for this type
2019     // NOTE that we must only do this when the class is initally
2020     // defined, not each time it is referenced from a new class loader
2021     if (k->class_loader() == class_loader()) {
2022       k->set_prototype_header(markOopDesc::biased_locking_prototype());
2023     }
2024   }
2025 
2026   // Check for a placeholder. If there, remove it and make a
2027   // new system dictionary entry.
2028   placeholders()->find_and_remove(p_index, p_hash, name, class_loader, THREAD);
2029   klassOop sd_check = find_class(d_index, d_hash, name, class_loader);
2030   if (sd_check == NULL) {
2031     dictionary()->add_klass(name, class_loader, k);
2032     notice_modification();
2033   }
2034 #ifdef ASSERT
2035   sd_check = find_class(d_index, d_hash, name, class_loader);
2036   assert (sd_check != NULL, "should have entry in system dictionary");
2037 // Changed to allow PH to remain to complete class circularity checking
2038 // while only one thread can define a class at one time, multiple
2039 // classes can resolve the superclass for a class at one time,
2040 // and the placeholder is used to track that
2041 //  symbolOop ph_check = find_placeholder(p_index, p_hash, name, class_loader);
2042 //  assert (ph_check == NULL, "should not have a placeholder entry");
2043 #endif
2044     SystemDictionary_lock->notify_all();
2045   }
2046 }
2047 
2048 
2049 klassOop SystemDictionary::find_constrained_instance_or_array_klass(
2050                     symbolHandle class_name, Handle class_loader, TRAPS) {
2051 
2052   // First see if it has been loaded directly.
2053   // Force the protection domain to be null.  (This removes protection checks.)
2054   Handle no_protection_domain;
2055   klassOop klass = find_instance_or_array_klass(class_name, class_loader,
2056                                                 no_protection_domain, CHECK_NULL);
2057   if (klass != NULL)
2058     return klass;
2059 
2060   // Now look to see if it has been loaded elsewhere, and is subject to
2061   // a loader constraint that would require this loader to return the
2062   // klass that is already loaded.
2063   if (FieldType::is_array(class_name())) {
2064     // Array classes are hard because their klassOops are not kept in the
2065     // constraint table. The array klass may be constrained, but the elem class
2066     // may not be.
2067     jint dimension;
2068     symbolOop object_key;
2069     BasicType t = FieldType::get_array_info(class_name(), &dimension,
2070                                             &object_key, CHECK_(NULL));
2071     if (t != T_OBJECT) {
2072       klass = Universe::typeArrayKlassObj(t);
2073     } else {
2074       symbolHandle elem_name(THREAD, object_key);
2075       MutexLocker mu(SystemDictionary_lock, THREAD);
2076       klass = constraints()->find_constrained_elem_klass(class_name, elem_name, class_loader, THREAD);
2077     }
2078     if (klass != NULL) {
2079       klass = Klass::cast(klass)->array_klass_or_null(dimension);
2080     }
2081   } else {
2082     MutexLocker mu(SystemDictionary_lock, THREAD);
2083     // Non-array classes are easy: simply check the constraint table.
2084     klass = constraints()->find_constrained_klass(class_name, class_loader);
2085   }
2086 
2087   return klass;
2088 }
2089 
2090 
2091 bool SystemDictionary::add_loader_constraint(symbolHandle class_name,
2092                                              Handle class_loader1,
2093                                              Handle class_loader2,
2094                                              Thread* THREAD) {
2095   unsigned int d_hash1 = dictionary()->compute_hash(class_name, class_loader1);
2096   int d_index1 = dictionary()->hash_to_index(d_hash1);
2097 
2098   unsigned int d_hash2 = dictionary()->compute_hash(class_name, class_loader2);
2099   int d_index2 = dictionary()->hash_to_index(d_hash2);
2100 
2101   {
2102     MutexLocker mu_s(SystemDictionary_lock, THREAD);
2103 
2104     // Better never do a GC while we're holding these oops
2105     No_Safepoint_Verifier nosafepoint;
2106 
2107     klassOop klass1 = find_class(d_index1, d_hash1, class_name, class_loader1);
2108     klassOop klass2 = find_class(d_index2, d_hash2, class_name, class_loader2);
2109     return constraints()->add_entry(class_name, klass1, class_loader1,
2110                                     klass2, class_loader2);
2111   }
2112 }
2113 
2114 // Add entry to resolution error table to record the error when the first
2115 // attempt to resolve a reference to a class has failed.
2116 void SystemDictionary::add_resolution_error(constantPoolHandle pool, int which, symbolHandle error) {
2117   unsigned int hash = resolution_errors()->compute_hash(pool, which);
2118   int index = resolution_errors()->hash_to_index(hash);
2119   {
2120     MutexLocker ml(SystemDictionary_lock, Thread::current());
2121     resolution_errors()->add_entry(index, hash, pool, which, error);
2122   }
2123 }
2124 
2125 // Lookup resolution error table. Returns error if found, otherwise NULL.
2126 symbolOop SystemDictionary::find_resolution_error(constantPoolHandle pool, int which) {
2127   unsigned int hash = resolution_errors()->compute_hash(pool, which);
2128   int index = resolution_errors()->hash_to_index(hash);
2129   {
2130     MutexLocker ml(SystemDictionary_lock, Thread::current());
2131     ResolutionErrorEntry* entry = resolution_errors()->find_entry(index, hash, pool, which);
2132     return (entry != NULL) ? entry->error() : (symbolOop)NULL;
2133   }
2134 }
2135 
2136 
2137 // Make sure all class components (including arrays) in the given
2138 // signature will be resolved to the same class in both loaders.
2139 // Returns the name of the type that failed a loader constraint check, or
2140 // NULL if no constraint failed. The returned C string needs cleaning up
2141 // with a ResourceMark in the caller
2142 char* SystemDictionary::check_signature_loaders(symbolHandle signature,
2143                                                Handle loader1, Handle loader2,
2144                                                bool is_method, TRAPS)  {
2145   // Nothing to do if loaders are the same.
2146   if (loader1() == loader2()) {
2147     return NULL;
2148   }
2149 
2150   SignatureStream sig_strm(signature, is_method);
2151   while (!sig_strm.is_done()) {
2152     if (sig_strm.is_object()) {
2153       symbolOop s = sig_strm.as_symbol(CHECK_NULL);
2154       symbolHandle sig (THREAD, s);
2155       if (!add_loader_constraint(sig, loader1, loader2, THREAD)) {
2156         return sig()->as_C_string();
2157       }
2158     }
2159     sig_strm.next();
2160   }
2161   return NULL;
2162 }
2163 
2164 
2165 // Since the identity hash code for symbols changes when the symbols are
2166 // moved from the regular perm gen (hash in the mark word) to the shared
2167 // spaces (hash is the address), the classes loaded into the dictionary
2168 // may be in the wrong buckets.
2169 
2170 void SystemDictionary::reorder_dictionary() {
2171   dictionary()->reorder_dictionary();
2172 }
2173 
2174 
2175 void SystemDictionary::copy_buckets(char** top, char* end) {
2176   dictionary()->copy_buckets(top, end);
2177 }
2178 
2179 
2180 void SystemDictionary::copy_table(char** top, char* end) {
2181   dictionary()->copy_table(top, end);
2182 }
2183 
2184 
2185 void SystemDictionary::reverse() {
2186   dictionary()->reverse();
2187 }
2188 
2189 int SystemDictionary::number_of_classes() {
2190   return dictionary()->number_of_entries();
2191 }
2192 
2193 
2194 // ----------------------------------------------------------------------------
2195 #ifndef PRODUCT
2196 
2197 void SystemDictionary::print() {
2198   dictionary()->print();
2199 
2200   // Placeholders
2201   GCMutexLocker mu(SystemDictionary_lock);
2202   placeholders()->print();
2203 
2204   // loader constraints - print under SD_lock
2205   constraints()->print();
2206 }
2207 
2208 #endif
2209 
2210 void SystemDictionary::verify() {
2211   guarantee(dictionary() != NULL, "Verify of system dictionary failed");
2212   guarantee(constraints() != NULL,
2213             "Verify of loader constraints failed");
2214   guarantee(dictionary()->number_of_entries() >= 0 &&
2215             placeholders()->number_of_entries() >= 0,
2216             "Verify of system dictionary failed");
2217 
2218   // Verify dictionary
2219   dictionary()->verify();
2220 
2221   GCMutexLocker mu(SystemDictionary_lock);
2222   placeholders()->verify();
2223 
2224   // Verify constraint table
2225   guarantee(constraints() != NULL, "Verify of loader constraints failed");
2226   constraints()->verify(dictionary());
2227 }
2228 
2229 
2230 void SystemDictionary::verify_obj_klass_present(Handle obj,
2231                                                 symbolHandle class_name,
2232                                                 Handle class_loader) {
2233   GCMutexLocker mu(SystemDictionary_lock);
2234   oop probe = find_class_or_placeholder(class_name, class_loader);
2235   if (probe == NULL) {
2236     probe = SystemDictionary::find_shared_class(class_name);
2237   }
2238   guarantee(probe != NULL &&
2239             (!probe->is_klass() || probe == obj()),
2240                      "Loaded klasses should be in SystemDictionary");
2241 }
2242 
2243 #ifndef PRODUCT
2244 
2245 // statistics code
2246 class ClassStatistics: AllStatic {
2247  private:
2248   static int nclasses;        // number of classes
2249   static int nmethods;        // number of methods
2250   static int nmethoddata;     // number of methodData
2251   static int class_size;      // size of class objects in words
2252   static int method_size;     // size of method objects in words
2253   static int debug_size;      // size of debug info in methods
2254   static int methoddata_size; // size of methodData objects in words
2255 
2256   static void do_class(klassOop k) {
2257     nclasses++;
2258     class_size += k->size();
2259     if (k->klass_part()->oop_is_instance()) {
2260       instanceKlass* ik = (instanceKlass*)k->klass_part();
2261       class_size += ik->methods()->size();
2262       class_size += ik->constants()->size();
2263       class_size += ik->local_interfaces()->size();
2264       class_size += ik->transitive_interfaces()->size();
2265       // We do not have to count implementors, since we only store one!
2266       class_size += ik->fields()->size();
2267     }
2268   }
2269 
2270   static void do_method(methodOop m) {
2271     nmethods++;
2272     method_size += m->size();
2273     // class loader uses same objArray for empty vectors, so don't count these
2274     if (m->exception_table()->length() != 0)   method_size += m->exception_table()->size();
2275     if (m->has_stackmap_table()) {
2276       method_size += m->stackmap_data()->size();
2277     }
2278 
2279     methodDataOop mdo = m->method_data();
2280     if (mdo != NULL) {
2281       nmethoddata++;
2282       methoddata_size += mdo->size();
2283     }
2284   }
2285 
2286  public:
2287   static void print() {
2288     SystemDictionary::classes_do(do_class);
2289     SystemDictionary::methods_do(do_method);
2290     tty->print_cr("Class statistics:");
2291     tty->print_cr("%d classes (%d bytes)", nclasses, class_size * oopSize);
2292     tty->print_cr("%d methods (%d bytes = %d base + %d debug info)", nmethods,
2293                   (method_size + debug_size) * oopSize, method_size * oopSize, debug_size * oopSize);
2294     tty->print_cr("%d methoddata (%d bytes)", nmethoddata, methoddata_size * oopSize);
2295   }
2296 };
2297 
2298 
2299 int ClassStatistics::nclasses        = 0;
2300 int ClassStatistics::nmethods        = 0;
2301 int ClassStatistics::nmethoddata     = 0;
2302 int ClassStatistics::class_size      = 0;
2303 int ClassStatistics::method_size     = 0;
2304 int ClassStatistics::debug_size      = 0;
2305 int ClassStatistics::methoddata_size = 0;
2306 
2307 void SystemDictionary::print_class_statistics() {
2308   ResourceMark rm;
2309   ClassStatistics::print();
2310 }
2311 
2312 
2313 class MethodStatistics: AllStatic {
2314  public:
2315   enum {
2316     max_parameter_size = 10
2317   };
2318  private:
2319 
2320   static int _number_of_methods;
2321   static int _number_of_final_methods;
2322   static int _number_of_static_methods;
2323   static int _number_of_native_methods;
2324   static int _number_of_synchronized_methods;
2325   static int _number_of_profiled_methods;
2326   static int _number_of_bytecodes;
2327   static int _parameter_size_profile[max_parameter_size];
2328   static int _bytecodes_profile[Bytecodes::number_of_java_codes];
2329 
2330   static void initialize() {
2331     _number_of_methods        = 0;
2332     _number_of_final_methods  = 0;
2333     _number_of_static_methods = 0;
2334     _number_of_native_methods = 0;
2335     _number_of_synchronized_methods = 0;
2336     _number_of_profiled_methods = 0;
2337     _number_of_bytecodes      = 0;
2338     for (int i = 0; i < max_parameter_size             ; i++) _parameter_size_profile[i] = 0;
2339     for (int j = 0; j < Bytecodes::number_of_java_codes; j++) _bytecodes_profile     [j] = 0;
2340   };
2341 
2342   static void do_method(methodOop m) {
2343     _number_of_methods++;
2344     // collect flag info
2345     if (m->is_final()       ) _number_of_final_methods++;
2346     if (m->is_static()      ) _number_of_static_methods++;
2347     if (m->is_native()      ) _number_of_native_methods++;
2348     if (m->is_synchronized()) _number_of_synchronized_methods++;
2349     if (m->method_data() != NULL) _number_of_profiled_methods++;
2350     // collect parameter size info (add one for receiver, if any)
2351     _parameter_size_profile[MIN2(m->size_of_parameters() + (m->is_static() ? 0 : 1), max_parameter_size - 1)]++;
2352     // collect bytecodes info
2353     {
2354       Thread *thread = Thread::current();
2355       HandleMark hm(thread);
2356       BytecodeStream s(methodHandle(thread, m));
2357       Bytecodes::Code c;
2358       while ((c = s.next()) >= 0) {
2359         _number_of_bytecodes++;
2360         _bytecodes_profile[c]++;
2361       }
2362     }
2363   }
2364 
2365  public:
2366   static void print() {
2367     initialize();
2368     SystemDictionary::methods_do(do_method);
2369     // generate output
2370     tty->cr();
2371     tty->print_cr("Method statistics (static):");
2372     // flag distribution
2373     tty->cr();
2374     tty->print_cr("%6d final        methods  %6.1f%%", _number_of_final_methods       , _number_of_final_methods        * 100.0F / _number_of_methods);
2375     tty->print_cr("%6d static       methods  %6.1f%%", _number_of_static_methods      , _number_of_static_methods       * 100.0F / _number_of_methods);
2376     tty->print_cr("%6d native       methods  %6.1f%%", _number_of_native_methods      , _number_of_native_methods       * 100.0F / _number_of_methods);
2377     tty->print_cr("%6d synchronized methods  %6.1f%%", _number_of_synchronized_methods, _number_of_synchronized_methods * 100.0F / _number_of_methods);
2378     tty->print_cr("%6d profiled     methods  %6.1f%%", _number_of_profiled_methods, _number_of_profiled_methods * 100.0F / _number_of_methods);
2379     // parameter size profile
2380     tty->cr();
2381     { int tot = 0;
2382       int avg = 0;
2383       for (int i = 0; i < max_parameter_size; i++) {
2384         int n = _parameter_size_profile[i];
2385         tot += n;
2386         avg += n*i;
2387         tty->print_cr("parameter size = %1d: %6d methods  %5.1f%%", i, n, n * 100.0F / _number_of_methods);
2388       }
2389       assert(tot == _number_of_methods, "should be the same");
2390       tty->print_cr("                    %6d methods  100.0%%", _number_of_methods);
2391       tty->print_cr("(average parameter size = %3.1f including receiver, if any)", (float)avg / _number_of_methods);
2392     }
2393     // bytecodes profile
2394     tty->cr();
2395     { int tot = 0;
2396       for (int i = 0; i < Bytecodes::number_of_java_codes; i++) {
2397         if (Bytecodes::is_defined(i)) {
2398           Bytecodes::Code c = Bytecodes::cast(i);
2399           int n = _bytecodes_profile[c];
2400           tot += n;
2401           tty->print_cr("%9d  %7.3f%%  %s", n, n * 100.0F / _number_of_bytecodes, Bytecodes::name(c));
2402         }
2403       }
2404       assert(tot == _number_of_bytecodes, "should be the same");
2405       tty->print_cr("%9d  100.000%%", _number_of_bytecodes);
2406     }
2407     tty->cr();
2408   }
2409 };
2410 
2411 int MethodStatistics::_number_of_methods;
2412 int MethodStatistics::_number_of_final_methods;
2413 int MethodStatistics::_number_of_static_methods;
2414 int MethodStatistics::_number_of_native_methods;
2415 int MethodStatistics::_number_of_synchronized_methods;
2416 int MethodStatistics::_number_of_profiled_methods;
2417 int MethodStatistics::_number_of_bytecodes;
2418 int MethodStatistics::_parameter_size_profile[MethodStatistics::max_parameter_size];
2419 int MethodStatistics::_bytecodes_profile[Bytecodes::number_of_java_codes];
2420 
2421 
2422 void SystemDictionary::print_method_statistics() {
2423   MethodStatistics::print();
2424 }
2425 
2426 #endif // PRODUCT