src/share/vm/classfile/systemDictionary.cpp

Wed, 09 Apr 2008 15:10:22 -0700

author
rasbold
date
Wed, 09 Apr 2008 15:10:22 -0700
changeset 544
9f4457a14b58
parent 457
90f5ddc7297b
child 567
60b728ec77c1
permissions
-rw-r--r--

Merge

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

mercurial