src/share/vm/classfile/systemDictionary.cpp

Fri, 12 Nov 2010 09:37:13 -0500

author
zgu
date
Fri, 12 Nov 2010 09:37:13 -0500
changeset 2299
9752a6549f2e
parent 2268
3b2dea75431e
child 2314
f95d63e2154a
permissions
-rw-r--r--

Merge

     1 /*
     2  * Copyright (c) 1997, 2010, Oracle and/or its affiliates. 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 Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
    20  * or visit www.oracle.com if you need additional information or have any
    21  * 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;
    34 SymbolPropertyTable*   SystemDictionary::_invoke_method_table = NULL;
    37 int         SystemDictionary::_number_of_modifications = 0;
    39 oop         SystemDictionary::_system_loader_lock_obj     =  NULL;
    41 klassOop    SystemDictionary::_well_known_klasses[SystemDictionary::WKID_LIMIT]
    42                                                           =  { NULL /*, NULL...*/ };
    44 klassOop    SystemDictionary::_box_klasses[T_VOID+1]      =  { NULL /*, NULL...*/ };
    46 oop         SystemDictionary::_java_system_loader         =  NULL;
    48 bool        SystemDictionary::_has_loadClassInternal      =  false;
    49 bool        SystemDictionary::_has_checkPackageAccess     =  false;
    51 // lazily initialized klass variables
    52 volatile klassOop    SystemDictionary::_abstract_ownable_synchronizer_klass = NULL;
    55 // ----------------------------------------------------------------------------
    56 // Java-level SystemLoader
    58 oop SystemDictionary::java_system_loader() {
    59   return _java_system_loader;
    60 }
    62 void SystemDictionary::compute_java_system_loader(TRAPS) {
    63   KlassHandle system_klass(THREAD, WK_KLASS(ClassLoader_klass));
    64   JavaValue result(T_OBJECT);
    65   JavaCalls::call_static(&result,
    66                          KlassHandle(THREAD, WK_KLASS(ClassLoader_klass)),
    67                          vmSymbolHandles::getSystemClassLoader_name(),
    68                          vmSymbolHandles::void_classloader_signature(),
    69                          CHECK);
    71   _java_system_loader = (oop)result.get_jobject();
    72 }
    75 // ----------------------------------------------------------------------------
    76 // debugging
    78 #ifdef ASSERT
    80 // return true if class_name contains no '.' (internal format is '/')
    81 bool SystemDictionary::is_internal_format(symbolHandle class_name) {
    82   if (class_name.not_null()) {
    83     ResourceMark rm;
    84     char* name = class_name->as_C_string();
    85     return strchr(name, '.') == NULL;
    86   } else {
    87     return true;
    88   }
    89 }
    91 #endif
    93 // ----------------------------------------------------------------------------
    94 // Parallel class loading check
    96 bool SystemDictionary::is_parallelCapable(Handle class_loader) {
    97   if (UnsyncloadClass || class_loader.is_null()) return true;
    98   if (AlwaysLockClassLoader) return false;
    99   return java_lang_Class::parallelCapable(class_loader());
   100 }
   101 // ----------------------------------------------------------------------------
   102 // ParallelDefineClass flag does not apply to bootclass loader
   103 bool SystemDictionary::is_parallelDefine(Handle class_loader) {
   104    if (class_loader.is_null()) return false;
   105    if (AllowParallelDefineClass && java_lang_Class::parallelCapable(class_loader())) {
   106      return true;
   107    }
   108    return false;
   109 }
   110 // ----------------------------------------------------------------------------
   111 // Resolving of classes
   113 // Forwards to resolve_or_null
   115 klassOop SystemDictionary::resolve_or_fail(symbolHandle class_name, Handle class_loader, Handle protection_domain, bool throw_error, TRAPS) {
   116   klassOop klass = resolve_or_null(class_name, class_loader, protection_domain, THREAD);
   117   if (HAS_PENDING_EXCEPTION || klass == NULL) {
   118     KlassHandle k_h(THREAD, klass);
   119     // can return a null klass
   120     klass = handle_resolution_exception(class_name, class_loader, protection_domain, throw_error, k_h, THREAD);
   121   }
   122   return klass;
   123 }
   125 klassOop SystemDictionary::handle_resolution_exception(symbolHandle class_name, Handle class_loader, Handle protection_domain, bool throw_error, KlassHandle klass_h, TRAPS) {
   126   if (HAS_PENDING_EXCEPTION) {
   127     // If we have a pending exception we forward it to the caller, unless throw_error is true,
   128     // in which case we have to check whether the pending exception is a ClassNotFoundException,
   129     // and if so convert it to a NoClassDefFoundError
   130     // And chain the original ClassNotFoundException
   131     if (throw_error && PENDING_EXCEPTION->is_a(SystemDictionary::ClassNotFoundException_klass())) {
   132       ResourceMark rm(THREAD);
   133       assert(klass_h() == NULL, "Should not have result with exception pending");
   134       Handle e(THREAD, PENDING_EXCEPTION);
   135       CLEAR_PENDING_EXCEPTION;
   136       THROW_MSG_CAUSE_0(vmSymbols::java_lang_NoClassDefFoundError(), class_name->as_C_string(), e);
   137     } else {
   138       return NULL;
   139     }
   140   }
   141   // Class not found, throw appropriate error or exception depending on value of throw_error
   142   if (klass_h() == NULL) {
   143     ResourceMark rm(THREAD);
   144     if (throw_error) {
   145       THROW_MSG_0(vmSymbols::java_lang_NoClassDefFoundError(), class_name->as_C_string());
   146     } else {
   147       THROW_MSG_0(vmSymbols::java_lang_ClassNotFoundException(), class_name->as_C_string());
   148     }
   149   }
   150   return (klassOop)klass_h();
   151 }
   154 klassOop SystemDictionary::resolve_or_fail(symbolHandle class_name,
   155                                            bool throw_error, TRAPS)
   156 {
   157   return resolve_or_fail(class_name, Handle(), Handle(), throw_error, THREAD);
   158 }
   161 // Forwards to resolve_instance_class_or_null
   163 klassOop SystemDictionary::resolve_or_null(symbolHandle class_name, Handle class_loader, Handle protection_domain, TRAPS) {
   164   assert(!THREAD->is_Compiler_thread(), "Can not load classes with the Compiler thread");
   165   if (FieldType::is_array(class_name())) {
   166     return resolve_array_class_or_null(class_name, class_loader, protection_domain, CHECK_NULL);
   167   } else {
   168     return resolve_instance_class_or_null(class_name, class_loader, protection_domain, CHECK_NULL);
   169   }
   170 }
   172 klassOop SystemDictionary::resolve_or_null(symbolHandle class_name, TRAPS) {
   173   return resolve_or_null(class_name, Handle(), Handle(), THREAD);
   174 }
   176 // Forwards to resolve_instance_class_or_null
   178 klassOop SystemDictionary::resolve_array_class_or_null(symbolHandle class_name,
   179                                                        Handle class_loader,
   180                                                        Handle protection_domain,
   181                                                        TRAPS) {
   182   assert(FieldType::is_array(class_name()), "must be array");
   183   jint dimension;
   184   symbolOop object_key;
   185   klassOop k = NULL;
   186   // dimension and object_key are assigned as a side-effect of this call
   187   BasicType t = FieldType::get_array_info(class_name(),
   188                                           &dimension,
   189                                           &object_key,
   190                                           CHECK_NULL);
   192   if (t == T_OBJECT) {
   193     symbolHandle h_key(THREAD, object_key);
   194     // naked oop "k" is OK here -- we assign back into it
   195     k = SystemDictionary::resolve_instance_class_or_null(h_key,
   196                                                          class_loader,
   197                                                          protection_domain,
   198                                                          CHECK_NULL);
   199     if (k != NULL) {
   200       k = Klass::cast(k)->array_klass(dimension, CHECK_NULL);
   201     }
   202   } else {
   203     k = Universe::typeArrayKlassObj(t);
   204     k = typeArrayKlass::cast(k)->array_klass(dimension, CHECK_NULL);
   205   }
   206   return k;
   207 }
   210 // Must be called for any super-class or super-interface resolution
   211 // during class definition to allow class circularity checking
   212 // super-interface callers:
   213 //    parse_interfaces - for defineClass & jvmtiRedefineClasses
   214 // super-class callers:
   215 //   ClassFileParser - for defineClass & jvmtiRedefineClasses
   216 //   load_shared_class - while loading a class from shared archive
   217 //   resolve_instance_class_or_null:
   218 //     via: handle_parallel_super_load
   219 //      when resolving a class that has an existing placeholder with
   220 //      a saved superclass [i.e. a defineClass is currently in progress]
   221 //      if another thread is trying to resolve the class, it must do
   222 //      super-class checks on its own thread to catch class circularity
   223 // This last call is critical in class circularity checking for cases
   224 // where classloading is delegated to different threads and the
   225 // classloader lock is released.
   226 // Take the case: Base->Super->Base
   227 //   1. If thread T1 tries to do a defineClass of class Base
   228 //    resolve_super_or_fail creates placeholder: T1, Base (super Super)
   229 //   2. resolve_instance_class_or_null does not find SD or placeholder for Super
   230 //    so it tries to load Super
   231 //   3. If we load the class internally, or user classloader uses same thread
   232 //      loadClassFromxxx or defineClass via parseClassFile Super ...
   233 //      3.1 resolve_super_or_fail creates placeholder: T1, Super (super Base)
   234 //      3.3 resolve_instance_class_or_null Base, finds placeholder for Base
   235 //      3.4 calls resolve_super_or_fail Base
   236 //      3.5 finds T1,Base -> throws class circularity
   237 //OR 4. If T2 tries to resolve Super via defineClass Super ...
   238 //      4.1 resolve_super_or_fail creates placeholder: T2, Super (super Base)
   239 //      4.2 resolve_instance_class_or_null Base, finds placeholder for Base (super Super)
   240 //      4.3 calls resolve_super_or_fail Super in parallel on own thread T2
   241 //      4.4 finds T2, Super -> throws class circularity
   242 // Must be called, even if superclass is null, since this is
   243 // where the placeholder entry is created which claims this
   244 // thread is loading this class/classloader.
   245 klassOop SystemDictionary::resolve_super_or_fail(symbolHandle child_name,
   246                                                  symbolHandle class_name,
   247                                                  Handle class_loader,
   248                                                  Handle protection_domain,
   249                                                  bool is_superclass,
   250                                                  TRAPS) {
   252   // Try to get one of the well-known klasses.
   253   // They are trusted, and do not participate in circularities.
   254   if (LinkWellKnownClasses) {
   255     klassOop k = find_well_known_klass(class_name());
   256     if (k != NULL) {
   257       return k;
   258     }
   259   }
   261   // Double-check, if child class is already loaded, just return super-class,interface
   262   // Don't add a placedholder if already loaded, i.e. already in system dictionary
   263   // Make sure there's a placeholder for the *child* before resolving.
   264   // Used as a claim that this thread is currently loading superclass/classloader
   265   // Used here for ClassCircularity checks and also for heap verification
   266   // (every instanceKlass in the heap needs to be in the system dictionary
   267   // or have a placeholder).
   268   // Must check ClassCircularity before checking if super class is already loaded
   269   //
   270   // We might not already have a placeholder if this child_name was
   271   // first seen via resolve_from_stream (jni_DefineClass or JVM_DefineClass);
   272   // the name of the class might not be known until the stream is actually
   273   // parsed.
   274   // Bugs 4643874, 4715493
   275   // compute_hash can have a safepoint
   277   unsigned int d_hash = dictionary()->compute_hash(child_name, class_loader);
   278   int d_index = dictionary()->hash_to_index(d_hash);
   279   unsigned int p_hash = placeholders()->compute_hash(child_name, class_loader);
   280   int p_index = placeholders()->hash_to_index(p_hash);
   281   // can't throw error holding a lock
   282   bool child_already_loaded = false;
   283   bool throw_circularity_error = false;
   284   {
   285     MutexLocker mu(SystemDictionary_lock, THREAD);
   286     klassOop childk = find_class(d_index, d_hash, child_name, class_loader);
   287     klassOop quicksuperk;
   288     // to support // loading: if child done loading, just return superclass
   289     // if class_name, & class_loader don't match:
   290     // if initial define, SD update will give LinkageError
   291     // if redefine: compare_class_versions will give HIERARCHY_CHANGED
   292     // so we don't throw an exception here.
   293     // see: nsk redefclass014 & java.lang.instrument Instrument032
   294     if ((childk != NULL ) && (is_superclass) &&
   295        ((quicksuperk = instanceKlass::cast(childk)->super()) != NULL) &&
   297          ((Klass::cast(quicksuperk)->name() == class_name()) &&
   298             (Klass::cast(quicksuperk)->class_loader()  == class_loader()))) {
   299            return quicksuperk;
   300     } else {
   301       PlaceholderEntry* probe = placeholders()->get_entry(p_index, p_hash, child_name, class_loader);
   302       if (probe && probe->check_seen_thread(THREAD, PlaceholderTable::LOAD_SUPER)) {
   303           throw_circularity_error = true;
   304       }
   305     }
   306     if (!throw_circularity_error) {
   307       PlaceholderEntry* newprobe = placeholders()->find_and_add(p_index, p_hash, child_name, class_loader, PlaceholderTable::LOAD_SUPER, class_name, THREAD);
   308     }
   309   }
   310   if (throw_circularity_error) {
   311       ResourceMark rm(THREAD);
   312       THROW_MSG_0(vmSymbols::java_lang_ClassCircularityError(), child_name->as_C_string());
   313   }
   315 // java.lang.Object should have been found above
   316   assert(class_name() != NULL, "null super class for resolving");
   317   // Resolve the super class or interface, check results on return
   318   klassOop superk = NULL;
   319   superk = SystemDictionary::resolve_or_null(class_name,
   320                                                  class_loader,
   321                                                  protection_domain,
   322                                                  THREAD);
   324   KlassHandle superk_h(THREAD, superk);
   326   // Note: clean up of placeholders currently in callers of
   327   // resolve_super_or_fail - either at update_dictionary time
   328   // or on error
   329   {
   330   MutexLocker mu(SystemDictionary_lock, THREAD);
   331    PlaceholderEntry* probe = placeholders()->get_entry(p_index, p_hash, child_name, class_loader);
   332    if (probe != NULL) {
   333       probe->remove_seen_thread(THREAD, PlaceholderTable::LOAD_SUPER);
   334    }
   335   }
   336   if (HAS_PENDING_EXCEPTION || superk_h() == NULL) {
   337     // can null superk
   338     superk_h = KlassHandle(THREAD, handle_resolution_exception(class_name, class_loader, protection_domain, true, superk_h, THREAD));
   339   }
   341   return superk_h();
   342 }
   344 void SystemDictionary::validate_protection_domain(instanceKlassHandle klass,
   345                                                   Handle class_loader,
   346                                                   Handle protection_domain,
   347                                                   TRAPS) {
   348   if(!has_checkPackageAccess()) return;
   350   // Now we have to call back to java to check if the initating class has access
   351   JavaValue result(T_VOID);
   352   if (TraceProtectionDomainVerification) {
   353     // Print out trace information
   354     tty->print_cr("Checking package access");
   355     tty->print(" - class loader:      "); class_loader()->print_value_on(tty);      tty->cr();
   356     tty->print(" - protection domain: "); protection_domain()->print_value_on(tty); tty->cr();
   357     tty->print(" - loading:           "); klass()->print_value_on(tty);             tty->cr();
   358   }
   360   assert(class_loader() != NULL, "should not have non-null protection domain for null classloader");
   362   KlassHandle system_loader(THREAD, SystemDictionary::ClassLoader_klass());
   363   JavaCalls::call_special(&result,
   364                          class_loader,
   365                          system_loader,
   366                          vmSymbolHandles::checkPackageAccess_name(),
   367                          vmSymbolHandles::class_protectiondomain_signature(),
   368                          Handle(THREAD, klass->java_mirror()),
   369                          protection_domain,
   370                          THREAD);
   372   if (TraceProtectionDomainVerification) {
   373     if (HAS_PENDING_EXCEPTION) {
   374       tty->print_cr(" -> DENIED !!!!!!!!!!!!!!!!!!!!!");
   375     } else {
   376      tty->print_cr(" -> granted");
   377     }
   378     tty->cr();
   379   }
   381   if (HAS_PENDING_EXCEPTION) return;
   383   // If no exception has been thrown, we have validated the protection domain
   384   // Insert the protection domain of the initiating class into the set.
   385   {
   386     // We recalculate the entry here -- we've called out to java since
   387     // the last time it was calculated.
   388     symbolHandle kn(THREAD, klass->name());
   389     unsigned int d_hash = dictionary()->compute_hash(kn, class_loader);
   390     int d_index = dictionary()->hash_to_index(d_hash);
   392     MutexLocker mu(SystemDictionary_lock, THREAD);
   393     {
   394       // Note that we have an entry, and entries can be deleted only during GC,
   395       // so we cannot allow GC to occur while we're holding this entry.
   397       // We're using a No_Safepoint_Verifier to catch any place where we
   398       // might potentially do a GC at all.
   399       // SystemDictionary::do_unloading() asserts that classes are only
   400       // unloaded at a safepoint.
   401       No_Safepoint_Verifier nosafepoint;
   402       dictionary()->add_protection_domain(d_index, d_hash, klass, class_loader,
   403                                           protection_domain, THREAD);
   404     }
   405   }
   406 }
   408 // We only get here if this thread finds that another thread
   409 // has already claimed the placeholder token for the current operation,
   410 // but that other thread either never owned or gave up the
   411 // object lock
   412 // Waits on SystemDictionary_lock to indicate placeholder table updated
   413 // On return, caller must recheck placeholder table state
   414 //
   415 // We only get here if
   416 //  1) custom classLoader, i.e. not bootstrap classloader
   417 //  2) UnsyncloadClass not set
   418 //  3) custom classLoader has broken the class loader objectLock
   419 //     so another thread got here in parallel
   420 //
   421 // lockObject must be held.
   422 // Complicated dance due to lock ordering:
   423 // Must first release the classloader object lock to
   424 // allow initial definer to complete the class definition
   425 // and to avoid deadlock
   426 // Reclaim classloader lock object with same original recursion count
   427 // Must release SystemDictionary_lock after notify, since
   428 // class loader lock must be claimed before SystemDictionary_lock
   429 // to prevent deadlocks
   430 //
   431 // The notify allows applications that did an untimed wait() on
   432 // the classloader object lock to not hang.
   433 void SystemDictionary::double_lock_wait(Handle lockObject, TRAPS) {
   434   assert_lock_strong(SystemDictionary_lock);
   436   bool calledholdinglock
   437       = ObjectSynchronizer::current_thread_holds_lock((JavaThread*)THREAD, lockObject);
   438   assert(calledholdinglock,"must hold lock for notify");
   439   assert((!(lockObject() == _system_loader_lock_obj) && !is_parallelCapable(lockObject)), "unexpected double_lock_wait");
   440   ObjectSynchronizer::notifyall(lockObject, THREAD);
   441   intptr_t recursions =  ObjectSynchronizer::complete_exit(lockObject, THREAD);
   442   SystemDictionary_lock->wait();
   443   SystemDictionary_lock->unlock();
   444   ObjectSynchronizer::reenter(lockObject, recursions, THREAD);
   445   SystemDictionary_lock->lock();
   446 }
   448 // If the class in is in the placeholder table, class loading is in progress
   449 // For cases where the application changes threads to load classes, it
   450 // is critical to ClassCircularity detection that we try loading
   451 // the superclass on the same thread internally, so we do parallel
   452 // super class loading here.
   453 // This also is critical in cases where the original thread gets stalled
   454 // even in non-circularity situations.
   455 // Note: only one thread can define the class, but multiple can resolve
   456 // Note: must call resolve_super_or_fail even if null super -
   457 // to force placeholder entry creation for this class for circularity detection
   458 // Caller must check for pending exception
   459 // Returns non-null klassOop if other thread has completed load
   460 // and we are done,
   461 // If return null klassOop and no pending exception, the caller must load the class
   462 instanceKlassHandle SystemDictionary::handle_parallel_super_load(
   463     symbolHandle name, symbolHandle superclassname, Handle class_loader,
   464     Handle protection_domain, Handle lockObject, TRAPS) {
   466   instanceKlassHandle nh = instanceKlassHandle(); // null Handle
   467   unsigned int d_hash = dictionary()->compute_hash(name, class_loader);
   468   int d_index = dictionary()->hash_to_index(d_hash);
   469   unsigned int p_hash = placeholders()->compute_hash(name, class_loader);
   470   int p_index = placeholders()->hash_to_index(p_hash);
   472   // superk is not used, resolve_super called for circularity check only
   473   // This code is reached in two situations. One if this thread
   474   // is loading the same class twice (e.g. ClassCircularity, or
   475   // java.lang.instrument).
   476   // The second is if another thread started the resolve_super first
   477   // and has not yet finished.
   478   // In both cases the original caller will clean up the placeholder
   479   // entry on error.
   480   klassOop superk = SystemDictionary::resolve_super_or_fail(name,
   481                                                           superclassname,
   482                                                           class_loader,
   483                                                           protection_domain,
   484                                                           true,
   485                                                           CHECK_(nh));
   486   // We don't redefine the class, so we just need to clean up if there
   487   // was not an error (don't want to modify any system dictionary
   488   // data structures).
   489   {
   490     MutexLocker mu(SystemDictionary_lock, THREAD);
   491     placeholders()->find_and_remove(p_index, p_hash, name, class_loader, THREAD);
   492     SystemDictionary_lock->notify_all();
   493   }
   495   // parallelCapable class loaders do NOT wait for parallel superclass loads to complete
   496   // Serial class loaders and bootstrap classloader do wait for superclass loads
   497  if (!class_loader.is_null() && is_parallelCapable(class_loader)) {
   498     MutexLocker mu(SystemDictionary_lock, THREAD);
   499     // Check if classloading completed while we were loading superclass or waiting
   500     klassOop check = find_class(d_index, d_hash, name, class_loader);
   501     if (check != NULL) {
   502       // Klass is already loaded, so just return it
   503       return(instanceKlassHandle(THREAD, check));
   504     } else {
   505       return nh;
   506     }
   507   }
   509   // must loop to both handle other placeholder updates
   510   // and spurious notifications
   511   bool super_load_in_progress = true;
   512   PlaceholderEntry* placeholder;
   513   while (super_load_in_progress) {
   514     MutexLocker mu(SystemDictionary_lock, THREAD);
   515     // Check if classloading completed while we were loading superclass or waiting
   516     klassOop check = find_class(d_index, d_hash, name, class_loader);
   517     if (check != NULL) {
   518       // Klass is already loaded, so just return it
   519       return(instanceKlassHandle(THREAD, check));
   520     } else {
   521       placeholder = placeholders()->get_entry(p_index, p_hash, name, class_loader);
   522       if (placeholder && placeholder->super_load_in_progress() ){
   523         // Before UnsyncloadClass:
   524         // We only get here if the application has released the
   525         // classloader lock when another thread was in the middle of loading a
   526         // superclass/superinterface for this class, and now
   527         // this thread is also trying to load this class.
   528         // To minimize surprises, the first thread that started to
   529         // load a class should be the one to complete the loading
   530         // with the classfile it initially expected.
   531         // This logic has the current thread wait once it has done
   532         // all the superclass/superinterface loading it can, until
   533         // the original thread completes the class loading or fails
   534         // If it completes we will use the resulting instanceKlass
   535         // which we will find below in the systemDictionary.
   536         // We also get here for parallel bootstrap classloader
   537         if (class_loader.is_null()) {
   538           SystemDictionary_lock->wait();
   539         } else {
   540           double_lock_wait(lockObject, THREAD);
   541         }
   542       } else {
   543         // If not in SD and not in PH, other thread's load must have failed
   544         super_load_in_progress = false;
   545       }
   546     }
   547   }
   548   return (nh);
   549 }
   552 klassOop SystemDictionary::resolve_instance_class_or_null(symbolHandle class_name, Handle class_loader, Handle protection_domain, TRAPS) {
   553   assert(class_name.not_null() && !FieldType::is_array(class_name()), "invalid class name");
   554   // First check to see if we should remove wrapping L and ;
   555   symbolHandle name;
   556   if (FieldType::is_obj(class_name())) {
   557     ResourceMark rm(THREAD);
   558     // Ignore wrapping L and ;.
   559     name = oopFactory::new_symbol_handle(class_name()->as_C_string() + 1, class_name()->utf8_length() - 2, CHECK_NULL);
   560   } else {
   561     name = class_name;
   562   }
   564   // UseNewReflection
   565   // Fix for 4474172; see evaluation for more details
   566   class_loader = Handle(THREAD, java_lang_ClassLoader::non_reflection_class_loader(class_loader()));
   568   // Do lookup to see if class already exist and the protection domain
   569   // has the right access
   570   unsigned int d_hash = dictionary()->compute_hash(name, class_loader);
   571   int d_index = dictionary()->hash_to_index(d_hash);
   572   klassOop probe = dictionary()->find(d_index, d_hash, name, class_loader,
   573                                       protection_domain, THREAD);
   574   if (probe != NULL) return probe;
   577   // Non-bootstrap class loaders will call out to class loader and
   578   // define via jvm/jni_DefineClass which will acquire the
   579   // class loader object lock to protect against multiple threads
   580   // defining the class in parallel by accident.
   581   // This lock must be acquired here so the waiter will find
   582   // any successful result in the SystemDictionary and not attempt
   583   // the define
   584   // ParallelCapable Classloaders and the bootstrap classloader,
   585   // or all classloaders with UnsyncloadClass do not acquire lock here
   586   bool DoObjectLock = true;
   587   if (is_parallelCapable(class_loader)) {
   588     DoObjectLock = false;
   589   }
   591   unsigned int p_hash = placeholders()->compute_hash(name, class_loader);
   592   int p_index = placeholders()->hash_to_index(p_hash);
   594   // Class is not in SystemDictionary so we have to do loading.
   595   // Make sure we are synchronized on the class loader before we proceed
   596   Handle lockObject = compute_loader_lock_object(class_loader, THREAD);
   597   check_loader_lock_contention(lockObject, THREAD);
   598   ObjectLocker ol(lockObject, THREAD, DoObjectLock);
   600   // Check again (after locking) if class already exist in SystemDictionary
   601   bool class_has_been_loaded   = false;
   602   bool super_load_in_progress  = false;
   603   bool havesupername = false;
   604   instanceKlassHandle k;
   605   PlaceholderEntry* placeholder;
   606   symbolHandle superclassname;
   608   {
   609     MutexLocker mu(SystemDictionary_lock, THREAD);
   610     klassOop check = find_class(d_index, d_hash, name, class_loader);
   611     if (check != NULL) {
   612       // Klass is already loaded, so just return it
   613       class_has_been_loaded = true;
   614       k = instanceKlassHandle(THREAD, check);
   615     } else {
   616       placeholder = placeholders()->get_entry(p_index, p_hash, name, class_loader);
   617       if (placeholder && placeholder->super_load_in_progress()) {
   618          super_load_in_progress = true;
   619          if (placeholder->havesupername() == true) {
   620            superclassname = symbolHandle(THREAD, placeholder->supername());
   621            havesupername = true;
   622          }
   623       }
   624     }
   625   }
   627   // If the class in is in the placeholder table, class loading is in progress
   628   if (super_load_in_progress && havesupername==true) {
   629     k = SystemDictionary::handle_parallel_super_load(name, superclassname,
   630         class_loader, protection_domain, lockObject, THREAD);
   631     if (HAS_PENDING_EXCEPTION) {
   632       return NULL;
   633     }
   634     if (!k.is_null()) {
   635       class_has_been_loaded = true;
   636     }
   637   }
   639   if (!class_has_been_loaded) {
   641     // add placeholder entry to record loading instance class
   642     // Five cases:
   643     // All cases need to prevent modifying bootclasssearchpath
   644     // in parallel with a classload of same classname
   645     // Redefineclasses uses existence of the placeholder for the duration
   646     // of the class load to prevent concurrent redefinition of not completely
   647     // defined classes.
   648     // case 1. traditional classloaders that rely on the classloader object lock
   649     //   - no other need for LOAD_INSTANCE
   650     // case 2. traditional classloaders that break the classloader object lock
   651     //    as a deadlock workaround. Detection of this case requires that
   652     //    this check is done while holding the classloader object lock,
   653     //    and that lock is still held when calling classloader's loadClass.
   654     //    For these classloaders, we ensure that the first requestor
   655     //    completes the load and other requestors wait for completion.
   656     // case 3. UnsyncloadClass - don't use objectLocker
   657     //    With this flag, we allow parallel classloading of a
   658     //    class/classloader pair
   659     // case4. Bootstrap classloader - don't own objectLocker
   660     //    This classloader supports parallelism at the classloader level,
   661     //    but only allows a single load of a class/classloader pair.
   662     //    No performance benefit and no deadlock issues.
   663     // case 5. parallelCapable user level classloaders - without objectLocker
   664     //    Allow parallel classloading of a class/classloader pair
   665     symbolHandle nullsymbolHandle;
   666     bool throw_circularity_error = false;
   667     {
   668       MutexLocker mu(SystemDictionary_lock, THREAD);
   669       if (class_loader.is_null() || !is_parallelCapable(class_loader)) {
   670         PlaceholderEntry* oldprobe = placeholders()->get_entry(p_index, p_hash, name, class_loader);
   671         if (oldprobe) {
   672           // only need check_seen_thread once, not on each loop
   673           // 6341374 java/lang/Instrument with -Xcomp
   674           if (oldprobe->check_seen_thread(THREAD, PlaceholderTable::LOAD_INSTANCE)) {
   675             throw_circularity_error = true;
   676           } else {
   677             // case 1: traditional: should never see load_in_progress.
   678             while (!class_has_been_loaded && oldprobe && oldprobe->instance_load_in_progress()) {
   680               // case 4: bootstrap classloader: prevent futile classloading,
   681               // wait on first requestor
   682               if (class_loader.is_null()) {
   683                 SystemDictionary_lock->wait();
   684               } else {
   685               // case 2: traditional with broken classloader lock. wait on first
   686               // requestor.
   687                 double_lock_wait(lockObject, THREAD);
   688               }
   689               // Check if classloading completed while we were waiting
   690               klassOop check = find_class(d_index, d_hash, name, class_loader);
   691               if (check != NULL) {
   692                 // Klass is already loaded, so just return it
   693                 k = instanceKlassHandle(THREAD, check);
   694                 class_has_been_loaded = true;
   695               }
   696               // check if other thread failed to load and cleaned up
   697               oldprobe = placeholders()->get_entry(p_index, p_hash, name, class_loader);
   698             }
   699           }
   700         }
   701       }
   702       // All cases: add LOAD_INSTANCE
   703       // case 3: UnsyncloadClass || case 5: parallelCapable: allow competing threads to try
   704       // LOAD_INSTANCE in parallel
   705       // add placeholder entry even if error - callers will remove on error
   706       if (!throw_circularity_error && !class_has_been_loaded) {
   707         PlaceholderEntry* newprobe = placeholders()->find_and_add(p_index, p_hash, name, class_loader, PlaceholderTable::LOAD_INSTANCE, nullsymbolHandle, THREAD);
   708         // For class loaders that do not acquire the classloader object lock,
   709         // if they did not catch another thread holding LOAD_INSTANCE,
   710         // need a check analogous to the acquire ObjectLocker/find_class
   711         // i.e. now that we hold the LOAD_INSTANCE token on loading this class/CL
   712         // one final check if the load has already completed
   713         // class loaders holding the ObjectLock shouldn't find the class here
   714         klassOop check = find_class(d_index, d_hash, name, class_loader);
   715         if (check != NULL) {
   716         // Klass is already loaded, so just return it
   717           k = instanceKlassHandle(THREAD, check);
   718           class_has_been_loaded = true;
   719           newprobe->remove_seen_thread(THREAD, PlaceholderTable::LOAD_INSTANCE);
   720           placeholders()->find_and_remove(p_index, p_hash, name, class_loader, THREAD);
   721           SystemDictionary_lock->notify_all();
   722         }
   723       }
   724     }
   725     // must throw error outside of owning lock
   726     if (throw_circularity_error) {
   727       ResourceMark rm(THREAD);
   728       THROW_MSG_0(vmSymbols::java_lang_ClassCircularityError(), name->as_C_string());
   729     }
   731     if (!class_has_been_loaded) {
   733       // Do actual loading
   734       k = load_instance_class(name, class_loader, THREAD);
   736       // For UnsyncloadClass only
   737       // If they got a linkageError, check if a parallel class load succeeded.
   738       // If it did, then for bytecode resolution the specification requires
   739       // that we return the same result we did for the other thread, i.e. the
   740       // successfully loaded instanceKlass
   741       // Should not get here for classloaders that support parallelism
   742       // with the new cleaner mechanism, even with AllowParallelDefineClass
   743       // Bootstrap goes through here to allow for an extra guarantee check
   744       if (UnsyncloadClass || (class_loader.is_null())) {
   745         if (k.is_null() && HAS_PENDING_EXCEPTION
   746           && PENDING_EXCEPTION->is_a(SystemDictionary::LinkageError_klass())) {
   747           MutexLocker mu(SystemDictionary_lock, THREAD);
   748           klassOop check = find_class(d_index, d_hash, name, class_loader);
   749           if (check != NULL) {
   750             // Klass is already loaded, so just use it
   751             k = instanceKlassHandle(THREAD, check);
   752             CLEAR_PENDING_EXCEPTION;
   753             guarantee((!class_loader.is_null()), "dup definition for bootstrap loader?");
   754           }
   755         }
   756       }
   758       // clean up placeholder entries for success or error
   759       // This cleans up LOAD_INSTANCE entries
   760       // It also cleans up LOAD_SUPER entries on errors from
   761       // calling load_instance_class
   762       {
   763         MutexLocker mu(SystemDictionary_lock, THREAD);
   764         PlaceholderEntry* probe = placeholders()->get_entry(p_index, p_hash, name, class_loader);
   765         if (probe != NULL) {
   766           probe->remove_seen_thread(THREAD, PlaceholderTable::LOAD_INSTANCE);
   767           placeholders()->find_and_remove(p_index, p_hash, name, class_loader, THREAD);
   768           SystemDictionary_lock->notify_all();
   769         }
   770       }
   772       // If everything was OK (no exceptions, no null return value), and
   773       // class_loader is NOT the defining loader, do a little more bookkeeping.
   774       if (!HAS_PENDING_EXCEPTION && !k.is_null() &&
   775         k->class_loader() != class_loader()) {
   777         check_constraints(d_index, d_hash, k, class_loader, false, THREAD);
   779         // Need to check for a PENDING_EXCEPTION again; check_constraints
   780         // can throw and doesn't use the CHECK macro.
   781         if (!HAS_PENDING_EXCEPTION) {
   782           { // Grabbing the Compile_lock prevents systemDictionary updates
   783             // during compilations.
   784             MutexLocker mu(Compile_lock, THREAD);
   785             update_dictionary(d_index, d_hash, p_index, p_hash,
   786                             k, class_loader, THREAD);
   787           }
   788           if (JvmtiExport::should_post_class_load()) {
   789             Thread *thread = THREAD;
   790             assert(thread->is_Java_thread(), "thread->is_Java_thread()");
   791             JvmtiExport::post_class_load((JavaThread *) thread, k());
   792           }
   793         }
   794       }
   795       if (HAS_PENDING_EXCEPTION || k.is_null()) {
   796         // On error, clean up placeholders
   797         {
   798           MutexLocker mu(SystemDictionary_lock, THREAD);
   799           placeholders()->find_and_remove(p_index, p_hash, name, class_loader, THREAD);
   800           SystemDictionary_lock->notify_all();
   801         }
   802         return NULL;
   803       }
   804     }
   805   }
   807 #ifdef ASSERT
   808   {
   809     Handle loader (THREAD, k->class_loader());
   810     MutexLocker mu(SystemDictionary_lock, THREAD);
   811     oop kk = find_class_or_placeholder(name, loader);
   812     assert(kk == k(), "should be present in dictionary");
   813   }
   814 #endif
   816   // return if the protection domain in NULL
   817   if (protection_domain() == NULL) return k();
   819   // Check the protection domain has the right access
   820   {
   821     MutexLocker mu(SystemDictionary_lock, THREAD);
   822     // Note that we have an entry, and entries can be deleted only during GC,
   823     // so we cannot allow GC to occur while we're holding this entry.
   824     // We're using a No_Safepoint_Verifier to catch any place where we
   825     // might potentially do a GC at all.
   826     // SystemDictionary::do_unloading() asserts that classes are only
   827     // unloaded at a safepoint.
   828     No_Safepoint_Verifier nosafepoint;
   829     if (dictionary()->is_valid_protection_domain(d_index, d_hash, name,
   830                                                  class_loader,
   831                                                  protection_domain)) {
   832       return k();
   833     }
   834   }
   836   // Verify protection domain. If it fails an exception is thrown
   837   validate_protection_domain(k, class_loader, protection_domain, CHECK_(klassOop(NULL)));
   839   return k();
   840 }
   843 // This routine does not lock the system dictionary.
   844 //
   845 // Since readers don't hold a lock, we must make sure that system
   846 // dictionary entries are only removed at a safepoint (when only one
   847 // thread is running), and are added to in a safe way (all links must
   848 // be updated in an MT-safe manner).
   849 //
   850 // Callers should be aware that an entry could be added just after
   851 // _dictionary->bucket(index) is read here, so the caller will not see
   852 // the new entry.
   854 klassOop SystemDictionary::find(symbolHandle class_name,
   855                                 Handle class_loader,
   856                                 Handle protection_domain,
   857                                 TRAPS) {
   859   // UseNewReflection
   860   // The result of this call should be consistent with the result
   861   // of the call to resolve_instance_class_or_null().
   862   // See evaluation 6790209 and 4474172 for more details.
   863   class_loader = Handle(THREAD, java_lang_ClassLoader::non_reflection_class_loader(class_loader()));
   865   unsigned int d_hash = dictionary()->compute_hash(class_name, class_loader);
   866   int d_index = dictionary()->hash_to_index(d_hash);
   868   {
   869     // Note that we have an entry, and entries can be deleted only during GC,
   870     // so we cannot allow GC to occur while we're holding this entry.
   871     // We're using a No_Safepoint_Verifier to catch any place where we
   872     // might potentially do a GC at all.
   873     // SystemDictionary::do_unloading() asserts that classes are only
   874     // unloaded at a safepoint.
   875     No_Safepoint_Verifier nosafepoint;
   876     return dictionary()->find(d_index, d_hash, class_name, class_loader,
   877                               protection_domain, THREAD);
   878   }
   879 }
   882 // Look for a loaded instance or array klass by name.  Do not do any loading.
   883 // return NULL in case of error.
   884 klassOop SystemDictionary::find_instance_or_array_klass(symbolHandle class_name,
   885                                                         Handle class_loader,
   886                                                         Handle protection_domain,
   887                                                         TRAPS) {
   888   klassOop k = NULL;
   889   assert(class_name() != NULL, "class name must be non NULL");
   891   // Try to get one of the well-known klasses.
   892   if (LinkWellKnownClasses) {
   893     k = find_well_known_klass(class_name());
   894     if (k != NULL) {
   895       return k;
   896     }
   897   }
   899   if (FieldType::is_array(class_name())) {
   900     // The name refers to an array.  Parse the name.
   901     jint dimension;
   902     symbolOop object_key;
   904     // dimension and object_key are assigned as a side-effect of this call
   905     BasicType t = FieldType::get_array_info(class_name(), &dimension,
   906                                             &object_key, CHECK_(NULL));
   907     if (t != T_OBJECT) {
   908       k = Universe::typeArrayKlassObj(t);
   909     } else {
   910       symbolHandle h_key(THREAD, object_key);
   911       k = SystemDictionary::find(h_key, class_loader, protection_domain, THREAD);
   912     }
   913     if (k != NULL) {
   914       k = Klass::cast(k)->array_klass_or_null(dimension);
   915     }
   916   } else {
   917     k = find(class_name, class_loader, protection_domain, THREAD);
   918   }
   919   return k;
   920 }
   922 // Quick range check for names of well-known classes:
   923 static symbolOop wk_klass_name_limits[2] = {NULL, NULL};
   925 #ifndef PRODUCT
   926 static int find_wkk_calls, find_wkk_probes, find_wkk_wins;
   927 // counts for "hello world": 3983, 1616, 1075
   928 //  => 60% hit after limit guard, 25% total win rate
   929 #endif
   931 klassOop SystemDictionary::find_well_known_klass(symbolOop class_name) {
   932   // A bounds-check on class_name will quickly get a negative result.
   933   NOT_PRODUCT(find_wkk_calls++);
   934   if (class_name >= wk_klass_name_limits[0] &&
   935       class_name <= wk_klass_name_limits[1]) {
   936     NOT_PRODUCT(find_wkk_probes++);
   937     vmSymbols::SID sid = vmSymbols::find_sid(class_name);
   938     if (sid != vmSymbols::NO_SID) {
   939       klassOop k = NULL;
   940       switch (sid) {
   941         #define WK_KLASS_CASE(name, symbol, ignore_option) \
   942         case vmSymbols::VM_SYMBOL_ENUM_NAME(symbol): \
   943           k = WK_KLASS(name); break;
   944         WK_KLASSES_DO(WK_KLASS_CASE)
   945         #undef WK_KLASS_CASE
   946       }
   947       NOT_PRODUCT(if (k != NULL)  find_wkk_wins++);
   948       return k;
   949     }
   950   }
   951   return NULL;
   952 }
   954 // Note: this method is much like resolve_from_stream, but
   955 // updates no supplemental data structures.
   956 // TODO consolidate the two methods with a helper routine?
   957 klassOop SystemDictionary::parse_stream(symbolHandle class_name,
   958                                         Handle class_loader,
   959                                         Handle protection_domain,
   960                                         ClassFileStream* st,
   961                                         KlassHandle host_klass,
   962                                         GrowableArray<Handle>* cp_patches,
   963                                         TRAPS) {
   964   symbolHandle parsed_name;
   966   // Parse the stream. Note that we do this even though this klass might
   967   // already be present in the SystemDictionary, otherwise we would not
   968   // throw potential ClassFormatErrors.
   969   //
   970   // Note: "name" is updated.
   971   // Further note:  a placeholder will be added for this class when
   972   //   super classes are loaded (resolve_super_or_fail). We expect this
   973   //   to be called for all classes but java.lang.Object; and we preload
   974   //   java.lang.Object through resolve_or_fail, not this path.
   976   instanceKlassHandle k = ClassFileParser(st).parseClassFile(class_name,
   977                                                              class_loader,
   978                                                              protection_domain,
   979                                                              host_klass,
   980                                                              cp_patches,
   981                                                              parsed_name,
   982                                                              true,
   983                                                              THREAD);
   986   // We don't redefine the class, so we just need to clean up whether there
   987   // was an error or not (don't want to modify any system dictionary
   988   // data structures).
   989   // Parsed name could be null if we threw an error before we got far
   990   // enough along to parse it -- in that case, there is nothing to clean up.
   991   if (!parsed_name.is_null()) {
   992     unsigned int p_hash = placeholders()->compute_hash(parsed_name,
   993                                                        class_loader);
   994     int p_index = placeholders()->hash_to_index(p_hash);
   995     {
   996     MutexLocker mu(SystemDictionary_lock, THREAD);
   997     placeholders()->find_and_remove(p_index, p_hash, parsed_name, class_loader, THREAD);
   998     SystemDictionary_lock->notify_all();
   999     }
  1002   if (host_klass.not_null() && k.not_null()) {
  1003     assert(AnonymousClasses, "");
  1004     // If it's anonymous, initialize it now, since nobody else will.
  1005     k->set_host_klass(host_klass());
  1008       MutexLocker mu_r(Compile_lock, THREAD);
  1010       // Add to class hierarchy, initialize vtables, and do possible
  1011       // deoptimizations.
  1012       add_to_hierarchy(k, CHECK_NULL); // No exception, but can block
  1014       // But, do not add to system dictionary.
  1017     k->eager_initialize(THREAD);
  1019     // notify jvmti
  1020     if (JvmtiExport::should_post_class_load()) {
  1021         assert(THREAD->is_Java_thread(), "thread->is_Java_thread()");
  1022         JvmtiExport::post_class_load((JavaThread *) THREAD, k());
  1026   return k();
  1029 // Add a klass to the system from a stream (called by jni_DefineClass and
  1030 // JVM_DefineClass).
  1031 // Note: class_name can be NULL. In that case we do not know the name of
  1032 // the class until we have parsed the stream.
  1034 klassOop SystemDictionary::resolve_from_stream(symbolHandle class_name,
  1035                                                Handle class_loader,
  1036                                                Handle protection_domain,
  1037                                                ClassFileStream* st,
  1038                                                bool verify,
  1039                                                TRAPS) {
  1041   // Classloaders that support parallelism, e.g. bootstrap classloader,
  1042   // or all classloaders with UnsyncloadClass do not acquire lock here
  1043   bool DoObjectLock = true;
  1044   if (is_parallelCapable(class_loader)) {
  1045     DoObjectLock = false;
  1048   // Make sure we are synchronized on the class loader before we proceed
  1049   Handle lockObject = compute_loader_lock_object(class_loader, THREAD);
  1050   check_loader_lock_contention(lockObject, THREAD);
  1051   ObjectLocker ol(lockObject, THREAD, DoObjectLock);
  1053   symbolHandle parsed_name;
  1055   // Parse the stream. Note that we do this even though this klass might
  1056   // already be present in the SystemDictionary, otherwise we would not
  1057   // throw potential ClassFormatErrors.
  1058   //
  1059   // Note: "name" is updated.
  1060   // Further note:  a placeholder will be added for this class when
  1061   //   super classes are loaded (resolve_super_or_fail). We expect this
  1062   //   to be called for all classes but java.lang.Object; and we preload
  1063   //   java.lang.Object through resolve_or_fail, not this path.
  1065   instanceKlassHandle k = ClassFileParser(st).parseClassFile(class_name,
  1066                                                              class_loader,
  1067                                                              protection_domain,
  1068                                                              parsed_name,
  1069                                                              verify,
  1070                                                              THREAD);
  1072   const char* pkg = "java/";
  1073   if (!HAS_PENDING_EXCEPTION &&
  1074       !class_loader.is_null() &&
  1075       !parsed_name.is_null() &&
  1076       !strncmp((const char*)parsed_name->bytes(), pkg, strlen(pkg))) {
  1077     // It is illegal to define classes in the "java." package from
  1078     // JVM_DefineClass or jni_DefineClass unless you're the bootclassloader
  1079     ResourceMark rm(THREAD);
  1080     char* name = parsed_name->as_C_string();
  1081     char* index = strrchr(name, '/');
  1082     *index = '\0'; // chop to just the package name
  1083     while ((index = strchr(name, '/')) != NULL) {
  1084       *index = '.'; // replace '/' with '.' in package name
  1086     const char* fmt = "Prohibited package name: %s";
  1087     size_t len = strlen(fmt) + strlen(name);
  1088     char* message = NEW_RESOURCE_ARRAY(char, len);
  1089     jio_snprintf(message, len, fmt, name);
  1090     Exceptions::_throw_msg(THREAD_AND_LOCATION,
  1091       vmSymbols::java_lang_SecurityException(), message);
  1094   if (!HAS_PENDING_EXCEPTION) {
  1095     assert(!parsed_name.is_null(), "Sanity");
  1096     assert(class_name.is_null() || class_name() == parsed_name(),
  1097            "name mismatch");
  1098     // Verification prevents us from creating names with dots in them, this
  1099     // asserts that that's the case.
  1100     assert(is_internal_format(parsed_name),
  1101            "external class name format used internally");
  1103     // Add class just loaded
  1104     // If a class loader supports parallel classloading handle parallel define requests
  1105     // find_or_define_instance_class may return a different instanceKlass
  1106     if (is_parallelCapable(class_loader)) {
  1107       k = find_or_define_instance_class(class_name, class_loader, k, THREAD);
  1108     } else {
  1109       define_instance_class(k, THREAD);
  1113   // If parsing the class file or define_instance_class failed, we
  1114   // need to remove the placeholder added on our behalf. But we
  1115   // must make sure parsed_name is valid first (it won't be if we had
  1116   // a format error before the class was parsed far enough to
  1117   // find the name).
  1118   if (HAS_PENDING_EXCEPTION && !parsed_name.is_null()) {
  1119     unsigned int p_hash = placeholders()->compute_hash(parsed_name,
  1120                                                        class_loader);
  1121     int p_index = placeholders()->hash_to_index(p_hash);
  1123     MutexLocker mu(SystemDictionary_lock, THREAD);
  1124     placeholders()->find_and_remove(p_index, p_hash, parsed_name, class_loader, THREAD);
  1125     SystemDictionary_lock->notify_all();
  1127     return NULL;
  1130   // Make sure that we didn't leave a place holder in the
  1131   // SystemDictionary; this is only done on success
  1132   debug_only( {
  1133     if (!HAS_PENDING_EXCEPTION) {
  1134       assert(!parsed_name.is_null(), "parsed_name is still null?");
  1135       symbolHandle h_name   (THREAD, k->name());
  1136       Handle h_loader (THREAD, k->class_loader());
  1138       MutexLocker mu(SystemDictionary_lock, THREAD);
  1140       oop check = find_class_or_placeholder(parsed_name, class_loader);
  1141       assert(check == k(), "should be present in the dictionary");
  1143       oop check2 = find_class_or_placeholder(h_name, h_loader);
  1144       assert(check == check2, "name inconsistancy in SystemDictionary");
  1146   } );
  1148   return k();
  1152 void SystemDictionary::set_shared_dictionary(HashtableBucket* t, int length,
  1153                                              int number_of_entries) {
  1154   assert(length == _nof_buckets * sizeof(HashtableBucket),
  1155          "bad shared dictionary size.");
  1156   _shared_dictionary = new Dictionary(_nof_buckets, t, number_of_entries);
  1160 // If there is a shared dictionary, then find the entry for the
  1161 // given shared system class, if any.
  1163 klassOop SystemDictionary::find_shared_class(symbolHandle class_name) {
  1164   if (shared_dictionary() != NULL) {
  1165     unsigned int d_hash = dictionary()->compute_hash(class_name, Handle());
  1166     int d_index = dictionary()->hash_to_index(d_hash);
  1167     return shared_dictionary()->find_shared_class(d_index, d_hash, class_name);
  1168   } else {
  1169     return NULL;
  1174 // Load a class from the shared spaces (found through the shared system
  1175 // dictionary).  Force the superclass and all interfaces to be loaded.
  1176 // Update the class definition to include sibling classes and no
  1177 // subclasses (yet).  [Classes in the shared space are not part of the
  1178 // object hierarchy until loaded.]
  1180 instanceKlassHandle SystemDictionary::load_shared_class(
  1181                  symbolHandle class_name, Handle class_loader, TRAPS) {
  1182   instanceKlassHandle ik (THREAD, find_shared_class(class_name));
  1183   return load_shared_class(ik, class_loader, THREAD);
  1186 // Note well!  Changes to this method may affect oop access order
  1187 // in the shared archive.  Please take care to not make changes that
  1188 // adversely affect cold start time by changing the oop access order
  1189 // that is specified in dump.cpp MarkAndMoveOrderedReadOnly and
  1190 // MarkAndMoveOrderedReadWrite closures.
  1191 instanceKlassHandle SystemDictionary::load_shared_class(
  1192                  instanceKlassHandle ik, Handle class_loader, TRAPS) {
  1193   assert(class_loader.is_null(), "non-null classloader for shared class?");
  1194   if (ik.not_null()) {
  1195     instanceKlassHandle nh = instanceKlassHandle(); // null Handle
  1196     symbolHandle class_name(THREAD, ik->name());
  1198     // Found the class, now load the superclass and interfaces.  If they
  1199     // are shared, add them to the main system dictionary and reset
  1200     // their hierarchy references (supers, subs, and interfaces).
  1202     if (ik->super() != NULL) {
  1203       symbolHandle cn(THREAD, ik->super()->klass_part()->name());
  1204       resolve_super_or_fail(class_name, cn,
  1205                             class_loader, Handle(), true, CHECK_(nh));
  1208     objArrayHandle interfaces (THREAD, ik->local_interfaces());
  1209     int num_interfaces = interfaces->length();
  1210     for (int index = 0; index < num_interfaces; index++) {
  1211       klassOop k = klassOop(interfaces->obj_at(index));
  1213       // Note: can not use instanceKlass::cast here because
  1214       // interfaces' instanceKlass's C++ vtbls haven't been
  1215       // reinitialized yet (they will be once the interface classes
  1216       // are loaded)
  1217       symbolHandle name (THREAD, k->klass_part()->name());
  1218       resolve_super_or_fail(class_name, name, class_loader, Handle(), false, CHECK_(nh));
  1221     // Adjust methods to recover missing data.  They need addresses for
  1222     // interpreter entry points and their default native method address
  1223     // must be reset.
  1225     // Updating methods must be done under a lock so multiple
  1226     // threads don't update these in parallel
  1227     // Shared classes are all currently loaded by the bootstrap
  1228     // classloader, so this will never cause a deadlock on
  1229     // a custom class loader lock.
  1232       Handle lockObject = compute_loader_lock_object(class_loader, THREAD);
  1233       check_loader_lock_contention(lockObject, THREAD);
  1234       ObjectLocker ol(lockObject, THREAD, true);
  1236       objArrayHandle methods (THREAD, ik->methods());
  1237       int num_methods = methods->length();
  1238       for (int index2 = 0; index2 < num_methods; ++index2) {
  1239         methodHandle m(THREAD, methodOop(methods->obj_at(index2)));
  1240         m()->link_method(m, CHECK_(nh));
  1244     if (TraceClassLoading) {
  1245       ResourceMark rm;
  1246       tty->print("[Loaded %s", ik->external_name());
  1247       tty->print(" from shared objects file");
  1248       tty->print_cr("]");
  1250     // notify a class loaded from shared object
  1251     ClassLoadingService::notify_class_loaded(instanceKlass::cast(ik()),
  1252                                              true /* shared class */);
  1254   return ik;
  1257 #ifdef KERNEL
  1258 // Some classes on the bootstrap class path haven't been installed on the
  1259 // system yet.  Call the DownloadManager method to make them appear in the
  1260 // bootstrap class path and try again to load the named class.
  1261 // Note that with delegation class loaders all classes in another loader will
  1262 // first try to call this so it'd better be fast!!
  1263 static instanceKlassHandle download_and_retry_class_load(
  1264                                                     symbolHandle class_name,
  1265                                                     TRAPS) {
  1267   klassOop dlm = SystemDictionary::sun_jkernel_DownloadManager_klass();
  1268   instanceKlassHandle nk;
  1270   // If download manager class isn't loaded just return.
  1271   if (dlm == NULL) return nk;
  1273   { HandleMark hm(THREAD);
  1274     ResourceMark rm(THREAD);
  1275     Handle s = java_lang_String::create_from_symbol(class_name, CHECK_(nk));
  1276     Handle class_string = java_lang_String::externalize_classname(s, CHECK_(nk));
  1278     // return value
  1279     JavaValue result(T_OBJECT);
  1281     // Call the DownloadManager.  We assume that it has a lock because
  1282     // multiple classes could be not found and downloaded at the same time.
  1283     // class sun.misc.DownloadManager;
  1284     // public static String getBootClassPathEntryForClass(String className);
  1285     JavaCalls::call_static(&result,
  1286                        KlassHandle(THREAD, dlm),
  1287                        vmSymbolHandles::getBootClassPathEntryForClass_name(),
  1288                        vmSymbolHandles::string_string_signature(),
  1289                        class_string,
  1290                        CHECK_(nk));
  1292     // Get result.string and add to bootclasspath
  1293     assert(result.get_type() == T_OBJECT, "just checking");
  1294     oop obj = (oop) result.get_jobject();
  1295     if (obj == NULL) { return nk; }
  1297     Handle h_obj(THREAD, obj);
  1298     char* new_class_name = java_lang_String::as_platform_dependent_str(h_obj,
  1299                                                                   CHECK_(nk));
  1301     // lock the loader
  1302     // we use this lock because JVMTI does.
  1303     Handle loader_lock(THREAD, SystemDictionary::system_loader_lock());
  1305     ObjectLocker ol(loader_lock, THREAD);
  1306     // add the file to the bootclasspath
  1307     ClassLoader::update_class_path_entry_list(new_class_name, true);
  1308   } // end HandleMark
  1310   if (TraceClassLoading) {
  1311     ClassLoader::print_bootclasspath();
  1313   return ClassLoader::load_classfile(class_name, CHECK_(nk));
  1315 #endif // KERNEL
  1318 instanceKlassHandle SystemDictionary::load_instance_class(symbolHandle class_name, Handle class_loader, TRAPS) {
  1319   instanceKlassHandle nh = instanceKlassHandle(); // null Handle
  1320   if (class_loader.is_null()) {
  1322     // Search the shared system dictionary for classes preloaded into the
  1323     // shared spaces.
  1324     instanceKlassHandle k;
  1326       PerfTraceTime vmtimer(ClassLoader::perf_shared_classload_time());
  1327       k = load_shared_class(class_name, class_loader, THREAD);
  1330     if (k.is_null()) {
  1331       // Use VM class loader
  1332       PerfTraceTime vmtimer(ClassLoader::perf_sys_classload_time());
  1333       k = ClassLoader::load_classfile(class_name, CHECK_(nh));
  1336 #ifdef KERNEL
  1337     // If the VM class loader has failed to load the class, call the
  1338     // DownloadManager class to make it magically appear on the classpath
  1339     // and try again.  This is only configured with the Kernel VM.
  1340     if (k.is_null()) {
  1341       k = download_and_retry_class_load(class_name, CHECK_(nh));
  1343 #endif // KERNEL
  1345     // find_or_define_instance_class may return a different instanceKlass
  1346     if (!k.is_null()) {
  1347       k = find_or_define_instance_class(class_name, class_loader, k, CHECK_(nh));
  1349     return k;
  1350   } else {
  1351     // Use user specified class loader to load class. Call loadClass operation on class_loader.
  1352     ResourceMark rm(THREAD);
  1354     assert(THREAD->is_Java_thread(), "must be a JavaThread");
  1355     JavaThread* jt = (JavaThread*) THREAD;
  1357     PerfClassTraceTime vmtimer(ClassLoader::perf_app_classload_time(),
  1358                                ClassLoader::perf_app_classload_selftime(),
  1359                                ClassLoader::perf_app_classload_count(),
  1360                                jt->get_thread_stat()->perf_recursion_counts_addr(),
  1361                                jt->get_thread_stat()->perf_timers_addr(),
  1362                                PerfClassTraceTime::CLASS_LOAD);
  1364     Handle s = java_lang_String::create_from_symbol(class_name, CHECK_(nh));
  1365     // Translate to external class name format, i.e., convert '/' chars to '.'
  1366     Handle string = java_lang_String::externalize_classname(s, CHECK_(nh));
  1368     JavaValue result(T_OBJECT);
  1370     KlassHandle spec_klass (THREAD, SystemDictionary::ClassLoader_klass());
  1372     // Call public unsynchronized loadClass(String) directly for all class loaders
  1373     // for parallelCapable class loaders. JDK >=7, loadClass(String, boolean) will
  1374     // acquire a class-name based lock rather than the class loader object lock.
  1375     // JDK < 7 already acquire the class loader lock in loadClass(String, boolean),
  1376     // so the call to loadClassInternal() was not required.
  1377     //
  1378     // UnsyncloadClass flag means both call loadClass(String) and do
  1379     // not acquire the class loader lock even for class loaders that are
  1380     // not parallelCapable. This was a risky transitional
  1381     // flag for diagnostic purposes only. It is risky to call
  1382     // custom class loaders without synchronization.
  1383     // WARNING If a custom class loader does NOT synchronizer findClass, or callers of
  1384     // findClass, the UnsyncloadClass flag risks unexpected timing bugs in the field.
  1385     // Do NOT assume this will be supported in future releases.
  1386     //
  1387     // Added MustCallLoadClassInternal in case we discover in the field
  1388     // a customer that counts on this call
  1389     if (MustCallLoadClassInternal && has_loadClassInternal()) {
  1390       JavaCalls::call_special(&result,
  1391                               class_loader,
  1392                               spec_klass,
  1393                               vmSymbolHandles::loadClassInternal_name(),
  1394                               vmSymbolHandles::string_class_signature(),
  1395                               string,
  1396                               CHECK_(nh));
  1397     } else {
  1398       JavaCalls::call_virtual(&result,
  1399                               class_loader,
  1400                               spec_klass,
  1401                               vmSymbolHandles::loadClass_name(),
  1402                               vmSymbolHandles::string_class_signature(),
  1403                               string,
  1404                               CHECK_(nh));
  1407     assert(result.get_type() == T_OBJECT, "just checking");
  1408     oop obj = (oop) result.get_jobject();
  1410     // Primitive classes return null since forName() can not be
  1411     // used to obtain any of the Class objects representing primitives or void
  1412     if ((obj != NULL) && !(java_lang_Class::is_primitive(obj))) {
  1413       instanceKlassHandle k =
  1414                 instanceKlassHandle(THREAD, java_lang_Class::as_klassOop(obj));
  1415       // For user defined Java class loaders, check that the name returned is
  1416       // the same as that requested.  This check is done for the bootstrap
  1417       // loader when parsing the class file.
  1418       if (class_name() == k->name()) {
  1419         return k;
  1422     // Class is not found or has the wrong name, return NULL
  1423     return nh;
  1427 void SystemDictionary::define_instance_class(instanceKlassHandle k, TRAPS) {
  1429   Handle class_loader_h(THREAD, k->class_loader());
  1431  // for bootstrap and other parallel classloaders don't acquire lock,
  1432  // use placeholder token
  1433  // If a parallelCapable class loader calls define_instance_class instead of
  1434  // find_or_define_instance_class to get here, we have a timing
  1435  // hole with systemDictionary updates and check_constraints
  1436  if (!class_loader_h.is_null() && !is_parallelCapable(class_loader_h)) {
  1437     assert(ObjectSynchronizer::current_thread_holds_lock((JavaThread*)THREAD,
  1438          compute_loader_lock_object(class_loader_h, THREAD)),
  1439          "define called without lock");
  1442   // Check class-loading constraints. Throw exception if violation is detected.
  1443   // Grabs and releases SystemDictionary_lock
  1444   // The check_constraints/find_class call and update_dictionary sequence
  1445   // must be "atomic" for a specific class/classloader pair so we never
  1446   // define two different instanceKlasses for that class/classloader pair.
  1447   // Existing classloaders will call define_instance_class with the
  1448   // classloader lock held
  1449   // Parallel classloaders will call find_or_define_instance_class
  1450   // which will require a token to perform the define class
  1451   symbolHandle name_h(THREAD, k->name());
  1452   unsigned int d_hash = dictionary()->compute_hash(name_h, class_loader_h);
  1453   int d_index = dictionary()->hash_to_index(d_hash);
  1454   check_constraints(d_index, d_hash, k, class_loader_h, true, CHECK);
  1456   // Register class just loaded with class loader (placed in Vector)
  1457   // Note we do this before updating the dictionary, as this can
  1458   // fail with an OutOfMemoryError (if it does, we will *not* put this
  1459   // class in the dictionary and will not update the class hierarchy).
  1460   if (k->class_loader() != NULL) {
  1461     methodHandle m(THREAD, Universe::loader_addClass_method());
  1462     JavaValue result(T_VOID);
  1463     JavaCallArguments args(class_loader_h);
  1464     args.push_oop(Handle(THREAD, k->java_mirror()));
  1465     JavaCalls::call(&result, m, &args, CHECK);
  1468   // Add the new class. We need recompile lock during update of CHA.
  1470     unsigned int p_hash = placeholders()->compute_hash(name_h, class_loader_h);
  1471     int p_index = placeholders()->hash_to_index(p_hash);
  1473     MutexLocker mu_r(Compile_lock, THREAD);
  1475     // Add to class hierarchy, initialize vtables, and do possible
  1476     // deoptimizations.
  1477     add_to_hierarchy(k, CHECK); // No exception, but can block
  1479     // Add to systemDictionary - so other classes can see it.
  1480     // Grabs and releases SystemDictionary_lock
  1481     update_dictionary(d_index, d_hash, p_index, p_hash,
  1482                       k, class_loader_h, THREAD);
  1484   k->eager_initialize(THREAD);
  1486   // notify jvmti
  1487   if (JvmtiExport::should_post_class_load()) {
  1488       assert(THREAD->is_Java_thread(), "thread->is_Java_thread()");
  1489       JvmtiExport::post_class_load((JavaThread *) THREAD, k());
  1494 // Support parallel classloading
  1495 // All parallel class loaders, including bootstrap classloader
  1496 // lock a placeholder entry for this class/class_loader pair
  1497 // to allow parallel defines of different classes for this class loader
  1498 // With AllowParallelDefine flag==true, in case they do not synchronize around
  1499 // FindLoadedClass/DefineClass, calls, we check for parallel
  1500 // loading for them, wait if a defineClass is in progress
  1501 // and return the initial requestor's results
  1502 // This flag does not apply to the bootstrap classloader.
  1503 // With AllowParallelDefine flag==false, call through to define_instance_class
  1504 // which will throw LinkageError: duplicate class definition.
  1505 // False is the requested default.
  1506 // For better performance, the class loaders should synchronize
  1507 // findClass(), i.e. FindLoadedClass/DefineClassIfAbsent or they
  1508 // potentially waste time reading and parsing the bytestream.
  1509 // Note: VM callers should ensure consistency of k/class_name,class_loader
  1510 instanceKlassHandle SystemDictionary::find_or_define_instance_class(symbolHandle class_name, Handle class_loader, instanceKlassHandle k, TRAPS) {
  1512   instanceKlassHandle nh = instanceKlassHandle(); // null Handle
  1513   symbolHandle name_h(THREAD, k->name()); // passed in class_name may be null
  1515   unsigned int d_hash = dictionary()->compute_hash(name_h, class_loader);
  1516   int d_index = dictionary()->hash_to_index(d_hash);
  1518 // Hold SD lock around find_class and placeholder creation for DEFINE_CLASS
  1519   unsigned int p_hash = placeholders()->compute_hash(name_h, class_loader);
  1520   int p_index = placeholders()->hash_to_index(p_hash);
  1521   PlaceholderEntry* probe;
  1524     MutexLocker mu(SystemDictionary_lock, THREAD);
  1525     // First check if class already defined
  1526     if (UnsyncloadClass || (is_parallelDefine(class_loader))) {
  1527       klassOop check = find_class(d_index, d_hash, name_h, class_loader);
  1528       if (check != NULL) {
  1529         return(instanceKlassHandle(THREAD, check));
  1533     // Acquire define token for this class/classloader
  1534     symbolHandle nullsymbolHandle;
  1535     probe = placeholders()->find_and_add(p_index, p_hash, name_h, class_loader, PlaceholderTable::DEFINE_CLASS, nullsymbolHandle, THREAD);
  1536     // Wait if another thread defining in parallel
  1537     // All threads wait - even those that will throw duplicate class: otherwise
  1538     // caller is surprised by LinkageError: duplicate, but findLoadedClass fails
  1539     // if other thread has not finished updating dictionary
  1540     while (probe->definer() != NULL) {
  1541       SystemDictionary_lock->wait();
  1543     // Only special cases allow parallel defines and can use other thread's results
  1544     // Other cases fall through, and may run into duplicate defines
  1545     // caught by finding an entry in the SystemDictionary
  1546     if ((UnsyncloadClass || is_parallelDefine(class_loader)) && (probe->instanceKlass() != NULL)) {
  1547         probe->remove_seen_thread(THREAD, PlaceholderTable::DEFINE_CLASS);
  1548         placeholders()->find_and_remove(p_index, p_hash, name_h, class_loader, THREAD);
  1549         SystemDictionary_lock->notify_all();
  1550 #ifdef ASSERT
  1551         klassOop check = find_class(d_index, d_hash, name_h, class_loader);
  1552         assert(check != NULL, "definer missed recording success");
  1553 #endif
  1554         return(instanceKlassHandle(THREAD, probe->instanceKlass()));
  1555     } else {
  1556       // This thread will define the class (even if earlier thread tried and had an error)
  1557       probe->set_definer(THREAD);
  1561   define_instance_class(k, THREAD);
  1563   Handle linkage_exception = Handle(); // null handle
  1565   // definer must notify any waiting threads
  1567     MutexLocker mu(SystemDictionary_lock, THREAD);
  1568     PlaceholderEntry* probe = placeholders()->get_entry(p_index, p_hash, name_h, class_loader);
  1569     assert(probe != NULL, "DEFINE_CLASS placeholder lost?");
  1570     if (probe != NULL) {
  1571       if (HAS_PENDING_EXCEPTION) {
  1572         linkage_exception = Handle(THREAD,PENDING_EXCEPTION);
  1573         CLEAR_PENDING_EXCEPTION;
  1574       } else {
  1575         probe->set_instanceKlass(k());
  1577       probe->set_definer(NULL);
  1578       probe->remove_seen_thread(THREAD, PlaceholderTable::DEFINE_CLASS);
  1579       placeholders()->find_and_remove(p_index, p_hash, name_h, class_loader, THREAD);
  1580       SystemDictionary_lock->notify_all();
  1584   // Can't throw exception while holding lock due to rank ordering
  1585   if (linkage_exception() != NULL) {
  1586     THROW_OOP_(linkage_exception(), nh); // throws exception and returns
  1589   return k;
  1591 Handle SystemDictionary::compute_loader_lock_object(Handle class_loader, TRAPS) {
  1592   // If class_loader is NULL we synchronize on _system_loader_lock_obj
  1593   if (class_loader.is_null()) {
  1594     return Handle(THREAD, _system_loader_lock_obj);
  1595   } else {
  1596     return class_loader;
  1600 // This method is added to check how often we have to wait to grab loader
  1601 // lock. The results are being recorded in the performance counters defined in
  1602 // ClassLoader::_sync_systemLoaderLockContentionRate and
  1603 // ClassLoader::_sync_nonSystemLoaderLockConteionRate.
  1604 void SystemDictionary::check_loader_lock_contention(Handle loader_lock, TRAPS) {
  1605   if (!UsePerfData) {
  1606     return;
  1609   assert(!loader_lock.is_null(), "NULL lock object");
  1611   if (ObjectSynchronizer::query_lock_ownership((JavaThread*)THREAD, loader_lock)
  1612       == ObjectSynchronizer::owner_other) {
  1613     // contention will likely happen, so increment the corresponding
  1614     // contention counter.
  1615     if (loader_lock() == _system_loader_lock_obj) {
  1616       ClassLoader::sync_systemLoaderLockContentionRate()->inc();
  1617     } else {
  1618       ClassLoader::sync_nonSystemLoaderLockContentionRate()->inc();
  1623 // ----------------------------------------------------------------------------
  1624 // Lookup
  1626 klassOop SystemDictionary::find_class(int index, unsigned int hash,
  1627                                       symbolHandle class_name,
  1628                                       Handle class_loader) {
  1629   assert_locked_or_safepoint(SystemDictionary_lock);
  1630   assert (index == dictionary()->index_for(class_name, class_loader),
  1631           "incorrect index?");
  1633   klassOop k = dictionary()->find_class(index, hash, class_name, class_loader);
  1634   return k;
  1638 // Basic find on classes in the midst of being loaded
  1639 symbolOop SystemDictionary::find_placeholder(int index, unsigned int hash,
  1640                                              symbolHandle class_name,
  1641                                              Handle class_loader) {
  1642   assert_locked_or_safepoint(SystemDictionary_lock);
  1644   return placeholders()->find_entry(index, hash, class_name, class_loader);
  1648 // Used for assertions and verification only
  1649 oop SystemDictionary::find_class_or_placeholder(symbolHandle class_name,
  1650                                                 Handle class_loader) {
  1651   #ifndef ASSERT
  1652   guarantee(VerifyBeforeGC   ||
  1653             VerifyDuringGC   ||
  1654             VerifyBeforeExit ||
  1655             VerifyAfterGC, "too expensive");
  1656   #endif
  1657   assert_locked_or_safepoint(SystemDictionary_lock);
  1658   symbolOop class_name_ = class_name();
  1659   oop class_loader_ = class_loader();
  1661   // First look in the loaded class array
  1662   unsigned int d_hash = dictionary()->compute_hash(class_name, class_loader);
  1663   int d_index = dictionary()->hash_to_index(d_hash);
  1664   oop lookup = find_class(d_index, d_hash, class_name, class_loader);
  1666   if (lookup == NULL) {
  1667     // Next try the placeholders
  1668     unsigned int p_hash = placeholders()->compute_hash(class_name,class_loader);
  1669     int p_index = placeholders()->hash_to_index(p_hash);
  1670     lookup = find_placeholder(p_index, p_hash, class_name, class_loader);
  1673   return lookup;
  1677 // Get the next class in the diictionary.
  1678 klassOop SystemDictionary::try_get_next_class() {
  1679   return dictionary()->try_get_next_class();
  1683 // ----------------------------------------------------------------------------
  1684 // Update hierachy. This is done before the new klass has been added to the SystemDictionary. The Recompile_lock
  1685 // is held, to ensure that the compiler is not using the class hierachy, and that deoptimization will kick in
  1686 // before a new class is used.
  1688 void SystemDictionary::add_to_hierarchy(instanceKlassHandle k, TRAPS) {
  1689   assert(k.not_null(), "just checking");
  1690   // Link into hierachy. Make sure the vtables are initialized before linking into
  1691   k->append_to_sibling_list();                    // add to superklass/sibling list
  1692   k->process_interfaces(THREAD);                  // handle all "implements" declarations
  1693   k->set_init_state(instanceKlass::loaded);
  1694   // Now flush all code that depended on old class hierarchy.
  1695   // Note: must be done *after* linking k into the hierarchy (was bug 12/9/97)
  1696   // Also, first reinitialize vtable because it may have gotten out of synch
  1697   // while the new class wasn't connected to the class hierarchy.
  1698   Universe::flush_dependents_on(k);
  1702 // ----------------------------------------------------------------------------
  1703 // GC support
  1705 // Following roots during mark-sweep is separated in two phases.
  1706 //
  1707 // The first phase follows preloaded classes and all other system
  1708 // classes, since these will never get unloaded anyway.
  1709 //
  1710 // The second phase removes (unloads) unreachable classes from the
  1711 // system dictionary and follows the remaining classes' contents.
  1713 void SystemDictionary::always_strong_oops_do(OopClosure* blk) {
  1714   // Follow preloaded classes/mirrors and system loader object
  1715   blk->do_oop(&_java_system_loader);
  1716   preloaded_oops_do(blk);
  1717   always_strong_classes_do(blk);
  1721 void SystemDictionary::always_strong_classes_do(OopClosure* blk) {
  1722   // Follow all system classes and temporary placeholders in dictionary
  1723   dictionary()->always_strong_classes_do(blk);
  1725   // Placeholders. These are *always* strong roots, as they
  1726   // represent classes we're actively loading.
  1727   placeholders_do(blk);
  1729   // Visit extra methods
  1730   invoke_method_table()->oops_do(blk);
  1732   // Loader constraints. We must keep the symbolOop used in the name alive.
  1733   constraints()->always_strong_classes_do(blk);
  1735   // Resolution errors keep the symbolOop for the error alive
  1736   resolution_errors()->always_strong_classes_do(blk);
  1740 void SystemDictionary::placeholders_do(OopClosure* blk) {
  1741   placeholders()->oops_do(blk);
  1745 bool SystemDictionary::do_unloading(BoolObjectClosure* is_alive) {
  1746   bool result = dictionary()->do_unloading(is_alive);
  1747   constraints()->purge_loader_constraints(is_alive);
  1748   resolution_errors()->purge_resolution_errors(is_alive);
  1749   return result;
  1753 // The mirrors are scanned by shared_oops_do() which is
  1754 // not called by oops_do().  In order to process oops in
  1755 // a necessary order, shared_oops_do() is call by
  1756 // Universe::oops_do().
  1757 void SystemDictionary::oops_do(OopClosure* f) {
  1758   // Adjust preloaded classes and system loader object
  1759   f->do_oop(&_java_system_loader);
  1760   preloaded_oops_do(f);
  1762   lazily_loaded_oops_do(f);
  1764   // Adjust dictionary
  1765   dictionary()->oops_do(f);
  1767   // Visit extra methods
  1768   invoke_method_table()->oops_do(f);
  1770   // Partially loaded classes
  1771   placeholders()->oops_do(f);
  1773   // Adjust constraint table
  1774   constraints()->oops_do(f);
  1776   // Adjust resolution error table
  1777   resolution_errors()->oops_do(f);
  1781 void SystemDictionary::preloaded_oops_do(OopClosure* f) {
  1782   f->do_oop((oop*) &wk_klass_name_limits[0]);
  1783   f->do_oop((oop*) &wk_klass_name_limits[1]);
  1785   for (int k = (int)FIRST_WKID; k < (int)WKID_LIMIT; k++) {
  1786     f->do_oop((oop*) &_well_known_klasses[k]);
  1790     for (int i = 0; i < T_VOID+1; i++) {
  1791       if (_box_klasses[i] != NULL) {
  1792         assert(i >= T_BOOLEAN, "checking");
  1793         f->do_oop((oop*) &_box_klasses[i]);
  1798   // The basic type mirrors would have already been processed in
  1799   // Universe::oops_do(), via a call to shared_oops_do(), so should
  1800   // not be processed again.
  1802   f->do_oop((oop*) &_system_loader_lock_obj);
  1803   FilteredFieldsMap::klasses_oops_do(f);
  1806 void SystemDictionary::lazily_loaded_oops_do(OopClosure* f) {
  1807   f->do_oop((oop*) &_abstract_ownable_synchronizer_klass);
  1810 // Just the classes from defining class loaders
  1811 // Don't iterate over placeholders
  1812 void SystemDictionary::classes_do(void f(klassOop)) {
  1813   dictionary()->classes_do(f);
  1816 // Added for initialize_itable_for_klass
  1817 //   Just the classes from defining class loaders
  1818 // Don't iterate over placeholders
  1819 void SystemDictionary::classes_do(void f(klassOop, TRAPS), TRAPS) {
  1820   dictionary()->classes_do(f, CHECK);
  1823 //   All classes, and their class loaders
  1824 // Don't iterate over placeholders
  1825 void SystemDictionary::classes_do(void f(klassOop, oop)) {
  1826   dictionary()->classes_do(f);
  1829 //   All classes, and their class loaders
  1830 //   (added for helpers that use HandleMarks and ResourceMarks)
  1831 // Don't iterate over placeholders
  1832 void SystemDictionary::classes_do(void f(klassOop, oop, TRAPS), TRAPS) {
  1833   dictionary()->classes_do(f, CHECK);
  1836 void SystemDictionary::placeholders_do(void f(symbolOop, oop)) {
  1837   placeholders()->entries_do(f);
  1840 void SystemDictionary::methods_do(void f(methodOop)) {
  1841   dictionary()->methods_do(f);
  1842   invoke_method_table()->methods_do(f);
  1845 // ----------------------------------------------------------------------------
  1846 // Lazily load klasses
  1848 void SystemDictionary::load_abstract_ownable_synchronizer_klass(TRAPS) {
  1849   assert(JDK_Version::is_gte_jdk16x_version(), "Must be JDK 1.6 or later");
  1851   // if multiple threads calling this function, only one thread will load
  1852   // the class.  The other threads will find the loaded version once the
  1853   // class is loaded.
  1854   klassOop aos = _abstract_ownable_synchronizer_klass;
  1855   if (aos == NULL) {
  1856     klassOop k = resolve_or_fail(vmSymbolHandles::java_util_concurrent_locks_AbstractOwnableSynchronizer(), true, CHECK);
  1857     // Force a fence to prevent any read before the write completes
  1858     OrderAccess::fence();
  1859     _abstract_ownable_synchronizer_klass = k;
  1863 // ----------------------------------------------------------------------------
  1864 // Initialization
  1866 void SystemDictionary::initialize(TRAPS) {
  1867   // Allocate arrays
  1868   assert(dictionary() == NULL,
  1869          "SystemDictionary should only be initialized once");
  1870   _dictionary          = new Dictionary(_nof_buckets);
  1871   _placeholders        = new PlaceholderTable(_nof_buckets);
  1872   _number_of_modifications = 0;
  1873   _loader_constraints  = new LoaderConstraintTable(_loader_constraint_size);
  1874   _resolution_errors   = new ResolutionErrorTable(_resolution_error_size);
  1875   _invoke_method_table = new SymbolPropertyTable(_invoke_method_size);
  1877   // Allocate private object used as system class loader lock
  1878   _system_loader_lock_obj = oopFactory::new_system_objArray(0, CHECK);
  1879   // Initialize basic classes
  1880   initialize_preloaded_classes(CHECK);
  1883 // Compact table of directions on the initialization of klasses:
  1884 static const short wk_init_info[] = {
  1885   #define WK_KLASS_INIT_INFO(name, symbol, option) \
  1886     ( ((int)vmSymbols::VM_SYMBOL_ENUM_NAME(symbol) \
  1887           << SystemDictionary::CEIL_LG_OPTION_LIMIT) \
  1888       | (int)SystemDictionary::option ),
  1889   WK_KLASSES_DO(WK_KLASS_INIT_INFO)
  1890   #undef WK_KLASS_INIT_INFO
  1892 };
  1894 bool SystemDictionary::initialize_wk_klass(WKID id, int init_opt, TRAPS) {
  1895   assert(id >= (int)FIRST_WKID && id < (int)WKID_LIMIT, "oob");
  1896   int  info = wk_init_info[id - FIRST_WKID];
  1897   int  sid  = (info >> CEIL_LG_OPTION_LIMIT);
  1898   symbolHandle symbol = vmSymbolHandles::symbol_handle_at((vmSymbols::SID)sid);
  1899   klassOop*    klassp = &_well_known_klasses[id];
  1900   bool must_load = (init_opt < SystemDictionary::Opt);
  1901   bool try_load  = true;
  1902   if (init_opt == SystemDictionary::Opt_Kernel) {
  1903 #ifndef KERNEL
  1904     try_load = false;
  1905 #endif //KERNEL
  1907   if ((*klassp) == NULL && try_load) {
  1908     if (must_load) {
  1909       (*klassp) = resolve_or_fail(symbol, true, CHECK_0); // load required class
  1910     } else {
  1911       (*klassp) = resolve_or_null(symbol,       CHECK_0); // load optional klass
  1914   return ((*klassp) != NULL);
  1917 void SystemDictionary::initialize_wk_klasses_until(WKID limit_id, WKID &start_id, TRAPS) {
  1918   assert((int)start_id <= (int)limit_id, "IDs are out of order!");
  1919   for (int id = (int)start_id; id < (int)limit_id; id++) {
  1920     assert(id >= (int)FIRST_WKID && id < (int)WKID_LIMIT, "oob");
  1921     int info = wk_init_info[id - FIRST_WKID];
  1922     int sid  = (info >> CEIL_LG_OPTION_LIMIT);
  1923     int opt  = (info & right_n_bits(CEIL_LG_OPTION_LIMIT));
  1925     initialize_wk_klass((WKID)id, opt, CHECK);
  1927     // Update limits, so find_well_known_klass can be very fast:
  1928     symbolOop s = vmSymbols::symbol_at((vmSymbols::SID)sid);
  1929     if (wk_klass_name_limits[1] == NULL) {
  1930       wk_klass_name_limits[0] = wk_klass_name_limits[1] = s;
  1931     } else if (wk_klass_name_limits[1] < s) {
  1932       wk_klass_name_limits[1] = s;
  1933     } else if (wk_klass_name_limits[0] > s) {
  1934       wk_klass_name_limits[0] = s;
  1938   // move the starting value forward to the limit:
  1939   start_id = limit_id;
  1943 void SystemDictionary::initialize_preloaded_classes(TRAPS) {
  1944   assert(WK_KLASS(Object_klass) == NULL, "preloaded classes should only be initialized once");
  1945   // Preload commonly used klasses
  1946   WKID scan = FIRST_WKID;
  1947   // first do Object, String, Class
  1948   initialize_wk_klasses_through(WK_KLASS_ENUM_NAME(Class_klass), scan, CHECK);
  1950   debug_only(instanceKlass::verify_class_klass_nonstatic_oop_maps(WK_KLASS(Class_klass)));
  1952   // Fixup mirrors for classes loaded before java.lang.Class.
  1953   // These calls iterate over the objects currently in the perm gen
  1954   // so calling them at this point is matters (not before when there
  1955   // are fewer objects and not later after there are more objects
  1956   // in the perm gen.
  1957   Universe::initialize_basic_type_mirrors(CHECK);
  1958   Universe::fixup_mirrors(CHECK);
  1960   // do a bunch more:
  1961   initialize_wk_klasses_through(WK_KLASS_ENUM_NAME(Reference_klass), scan, CHECK);
  1963   // Preload ref klasses and set reference types
  1964   instanceKlass::cast(WK_KLASS(Reference_klass))->set_reference_type(REF_OTHER);
  1965   instanceRefKlass::update_nonstatic_oop_maps(WK_KLASS(Reference_klass));
  1967   initialize_wk_klasses_through(WK_KLASS_ENUM_NAME(PhantomReference_klass), scan, CHECK);
  1968   instanceKlass::cast(WK_KLASS(SoftReference_klass))->set_reference_type(REF_SOFT);
  1969   instanceKlass::cast(WK_KLASS(WeakReference_klass))->set_reference_type(REF_WEAK);
  1970   instanceKlass::cast(WK_KLASS(FinalReference_klass))->set_reference_type(REF_FINAL);
  1971   instanceKlass::cast(WK_KLASS(PhantomReference_klass))->set_reference_type(REF_PHANTOM);
  1973   WKID meth_group_start = WK_KLASS_ENUM_NAME(MethodHandle_klass);
  1974   WKID meth_group_end   = WK_KLASS_ENUM_NAME(WrongMethodTypeException_klass);
  1975   initialize_wk_klasses_until(meth_group_start, scan, CHECK);
  1976   if (EnableMethodHandles) {
  1977     initialize_wk_klasses_through(meth_group_end, scan, CHECK);
  1979   if (_well_known_klasses[meth_group_start] == NULL) {
  1980     // Skip the rest of the method handle classes, if MethodHandle is not loaded.
  1981     scan = WKID(meth_group_end+1);
  1983   WKID indy_group_start = WK_KLASS_ENUM_NAME(Linkage_klass);
  1984   WKID indy_group_end   = WK_KLASS_ENUM_NAME(InvokeDynamic_klass);
  1985   initialize_wk_klasses_until(indy_group_start, scan, CHECK);
  1986   if (EnableInvokeDynamic) {
  1987     initialize_wk_klasses_through(indy_group_end, scan, CHECK);
  1989   if (_well_known_klasses[indy_group_start] == NULL) {
  1990     // Skip the rest of the dynamic typing classes, if Linkage is not loaded.
  1991     scan = WKID(indy_group_end+1);
  1994   initialize_wk_klasses_until(WKID_LIMIT, scan, CHECK);
  1996   _box_klasses[T_BOOLEAN] = WK_KLASS(Boolean_klass);
  1997   _box_klasses[T_CHAR]    = WK_KLASS(Character_klass);
  1998   _box_klasses[T_FLOAT]   = WK_KLASS(Float_klass);
  1999   _box_klasses[T_DOUBLE]  = WK_KLASS(Double_klass);
  2000   _box_klasses[T_BYTE]    = WK_KLASS(Byte_klass);
  2001   _box_klasses[T_SHORT]   = WK_KLASS(Short_klass);
  2002   _box_klasses[T_INT]     = WK_KLASS(Integer_klass);
  2003   _box_klasses[T_LONG]    = WK_KLASS(Long_klass);
  2004   //_box_klasses[T_OBJECT]  = WK_KLASS(object_klass);
  2005   //_box_klasses[T_ARRAY]   = WK_KLASS(object_klass);
  2007 #ifdef KERNEL
  2008   if (sun_jkernel_DownloadManager_klass() == NULL) {
  2009     warning("Cannot find sun/jkernel/DownloadManager");
  2011 #endif // KERNEL
  2013   { // Compute whether we should use loadClass or loadClassInternal when loading classes.
  2014     methodOop method = instanceKlass::cast(ClassLoader_klass())->find_method(vmSymbols::loadClassInternal_name(), vmSymbols::string_class_signature());
  2015     _has_loadClassInternal = (method != NULL);
  2017   { // Compute whether we should use checkPackageAccess or NOT
  2018     methodOop method = instanceKlass::cast(ClassLoader_klass())->find_method(vmSymbols::checkPackageAccess_name(), vmSymbols::class_protectiondomain_signature());
  2019     _has_checkPackageAccess = (method != NULL);
  2023 // Tells if a given klass is a box (wrapper class, such as java.lang.Integer).
  2024 // If so, returns the basic type it holds.  If not, returns T_OBJECT.
  2025 BasicType SystemDictionary::box_klass_type(klassOop k) {
  2026   assert(k != NULL, "");
  2027   for (int i = T_BOOLEAN; i < T_VOID+1; i++) {
  2028     if (_box_klasses[i] == k)
  2029       return (BasicType)i;
  2031   return T_OBJECT;
  2034 KlassHandle SystemDictionaryHandles::box_klass(BasicType t) {
  2035   if (t >= T_BOOLEAN && t <= T_VOID)
  2036     return KlassHandle(&SystemDictionary::_box_klasses[t], true);
  2037   else
  2038     return KlassHandle();
  2041 // Constraints on class loaders. The details of the algorithm can be
  2042 // found in the OOPSLA'98 paper "Dynamic Class Loading in the Java
  2043 // Virtual Machine" by Sheng Liang and Gilad Bracha.  The basic idea is
  2044 // that the system dictionary needs to maintain a set of contraints that
  2045 // must be satisfied by all classes in the dictionary.
  2046 // if defining is true, then LinkageError if already in systemDictionary
  2047 // if initiating loader, then ok if instanceKlass matches existing entry
  2049 void SystemDictionary::check_constraints(int d_index, unsigned int d_hash,
  2050                                          instanceKlassHandle k,
  2051                                          Handle class_loader, bool defining,
  2052                                          TRAPS) {
  2053   const char *linkage_error = NULL;
  2055     symbolHandle name (THREAD, k->name());
  2056     MutexLocker mu(SystemDictionary_lock, THREAD);
  2058     klassOop check = find_class(d_index, d_hash, name, class_loader);
  2059     if (check != (klassOop)NULL) {
  2060       // if different instanceKlass - duplicate class definition,
  2061       // else - ok, class loaded by a different thread in parallel,
  2062       // we should only have found it if it was done loading and ok to use
  2063       // system dictionary only holds instance classes, placeholders
  2064       // also holds array classes
  2066       assert(check->klass_part()->oop_is_instance(), "noninstance in systemdictionary");
  2067       if ((defining == true) || (k() != check)) {
  2068         linkage_error = "loader (instance of  %s): attempted  duplicate class "
  2069           "definition for name: \"%s\"";
  2070       } else {
  2071         return;
  2075 #ifdef ASSERT
  2076     unsigned int p_hash = placeholders()->compute_hash(name, class_loader);
  2077     int p_index = placeholders()->hash_to_index(p_hash);
  2078     symbolOop ph_check = find_placeholder(p_index, p_hash, name, class_loader);
  2079     assert(ph_check == NULL || ph_check == name(), "invalid symbol");
  2080 #endif
  2082     if (linkage_error == NULL) {
  2083       if (constraints()->check_or_update(k, class_loader, name) == false) {
  2084         linkage_error = "loader constraint violation: loader (instance of %s)"
  2085           " previously initiated loading for a different type with name \"%s\"";
  2090   // Throw error now if needed (cannot throw while holding
  2091   // SystemDictionary_lock because of rank ordering)
  2093   if (linkage_error) {
  2094     ResourceMark rm(THREAD);
  2095     const char* class_loader_name = loader_name(class_loader());
  2096     char* type_name = k->name()->as_C_string();
  2097     size_t buflen = strlen(linkage_error) + strlen(class_loader_name) +
  2098       strlen(type_name);
  2099     char* buf = NEW_RESOURCE_ARRAY_IN_THREAD(THREAD, char, buflen);
  2100     jio_snprintf(buf, buflen, linkage_error, class_loader_name, type_name);
  2101     THROW_MSG(vmSymbols::java_lang_LinkageError(), buf);
  2106 // Update system dictionary - done after check_constraint and add_to_hierachy
  2107 // have been called.
  2108 void SystemDictionary::update_dictionary(int d_index, unsigned int d_hash,
  2109                                          int p_index, unsigned int p_hash,
  2110                                          instanceKlassHandle k,
  2111                                          Handle class_loader,
  2112                                          TRAPS) {
  2113   // Compile_lock prevents systemDictionary updates during compilations
  2114   assert_locked_or_safepoint(Compile_lock);
  2115   symbolHandle name (THREAD, k->name());
  2118   MutexLocker mu1(SystemDictionary_lock, THREAD);
  2120   // See whether biased locking is enabled and if so set it for this
  2121   // klass.
  2122   // Note that this must be done past the last potential blocking
  2123   // point / safepoint. We enable biased locking lazily using a
  2124   // VM_Operation to iterate the SystemDictionary and installing the
  2125   // biasable mark word into each instanceKlass's prototype header.
  2126   // To avoid race conditions where we accidentally miss enabling the
  2127   // optimization for one class in the process of being added to the
  2128   // dictionary, we must not safepoint after the test of
  2129   // BiasedLocking::enabled().
  2130   if (UseBiasedLocking && BiasedLocking::enabled()) {
  2131     // Set biased locking bit for all loaded classes; it will be
  2132     // cleared if revocation occurs too often for this type
  2133     // NOTE that we must only do this when the class is initally
  2134     // defined, not each time it is referenced from a new class loader
  2135     if (k->class_loader() == class_loader()) {
  2136       k->set_prototype_header(markOopDesc::biased_locking_prototype());
  2140   // Check for a placeholder. If there, remove it and make a
  2141   // new system dictionary entry.
  2142   placeholders()->find_and_remove(p_index, p_hash, name, class_loader, THREAD);
  2143   klassOop sd_check = find_class(d_index, d_hash, name, class_loader);
  2144   if (sd_check == NULL) {
  2145     dictionary()->add_klass(name, class_loader, k);
  2146     notice_modification();
  2148 #ifdef ASSERT
  2149   sd_check = find_class(d_index, d_hash, name, class_loader);
  2150   assert (sd_check != NULL, "should have entry in system dictionary");
  2151 // Changed to allow PH to remain to complete class circularity checking
  2152 // while only one thread can define a class at one time, multiple
  2153 // classes can resolve the superclass for a class at one time,
  2154 // and the placeholder is used to track that
  2155 //  symbolOop ph_check = find_placeholder(p_index, p_hash, name, class_loader);
  2156 //  assert (ph_check == NULL, "should not have a placeholder entry");
  2157 #endif
  2158     SystemDictionary_lock->notify_all();
  2163 klassOop SystemDictionary::find_constrained_instance_or_array_klass(
  2164                     symbolHandle class_name, Handle class_loader, TRAPS) {
  2166   // First see if it has been loaded directly.
  2167   // Force the protection domain to be null.  (This removes protection checks.)
  2168   Handle no_protection_domain;
  2169   klassOop klass = find_instance_or_array_klass(class_name, class_loader,
  2170                                                 no_protection_domain, CHECK_NULL);
  2171   if (klass != NULL)
  2172     return klass;
  2174   // Now look to see if it has been loaded elsewhere, and is subject to
  2175   // a loader constraint that would require this loader to return the
  2176   // klass that is already loaded.
  2177   if (FieldType::is_array(class_name())) {
  2178     // For array classes, their klassOops are not kept in the
  2179     // constraint table. The element klassOops are.
  2180     jint dimension;
  2181     symbolOop object_key;
  2182     BasicType t = FieldType::get_array_info(class_name(), &dimension,
  2183                                             &object_key, CHECK_(NULL));
  2184     if (t != T_OBJECT) {
  2185       klass = Universe::typeArrayKlassObj(t);
  2186     } else {
  2187       symbolHandle elem_name(THREAD, object_key);
  2188       MutexLocker mu(SystemDictionary_lock, THREAD);
  2189       klass = constraints()->find_constrained_klass(elem_name, class_loader);
  2191     // If element class already loaded, allocate array klass
  2192     if (klass != NULL) {
  2193       klass = Klass::cast(klass)->array_klass_or_null(dimension);
  2195   } else {
  2196     MutexLocker mu(SystemDictionary_lock, THREAD);
  2197     // Non-array classes are easy: simply check the constraint table.
  2198     klass = constraints()->find_constrained_klass(class_name, class_loader);
  2201   return klass;
  2205 bool SystemDictionary::add_loader_constraint(symbolHandle class_name,
  2206                                              Handle class_loader1,
  2207                                              Handle class_loader2,
  2208                                              Thread* THREAD) {
  2209   symbolHandle constraint_name;
  2210   if (!FieldType::is_array(class_name())) {
  2211     constraint_name = class_name;
  2212   } else {
  2213     // For array classes, their klassOops are not kept in the
  2214     // constraint table. The element classes are.
  2215     jint dimension;
  2216     symbolOop object_key;
  2217     BasicType t = FieldType::get_array_info(class_name(), &dimension,
  2218                                             &object_key, CHECK_(false));
  2219     // primitive types always pass
  2220     if (t != T_OBJECT) {
  2221       return true;
  2222     } else {
  2223       constraint_name = symbolHandle(THREAD, object_key);
  2226   unsigned int d_hash1 = dictionary()->compute_hash(constraint_name, class_loader1);
  2227   int d_index1 = dictionary()->hash_to_index(d_hash1);
  2229   unsigned int d_hash2 = dictionary()->compute_hash(constraint_name, class_loader2);
  2230   int d_index2 = dictionary()->hash_to_index(d_hash2);
  2232   MutexLocker mu_s(SystemDictionary_lock, THREAD);
  2234   // Better never do a GC while we're holding these oops
  2235   No_Safepoint_Verifier nosafepoint;
  2237   klassOop klass1 = find_class(d_index1, d_hash1, constraint_name, class_loader1);
  2238   klassOop klass2 = find_class(d_index2, d_hash2, constraint_name, class_loader2);
  2239   return constraints()->add_entry(constraint_name, klass1, class_loader1,
  2240                                   klass2, class_loader2);
  2244 // Add entry to resolution error table to record the error when the first
  2245 // attempt to resolve a reference to a class has failed.
  2246 void SystemDictionary::add_resolution_error(constantPoolHandle pool, int which, symbolHandle error) {
  2247   unsigned int hash = resolution_errors()->compute_hash(pool, which);
  2248   int index = resolution_errors()->hash_to_index(hash);
  2250     MutexLocker ml(SystemDictionary_lock, Thread::current());
  2251     resolution_errors()->add_entry(index, hash, pool, which, error);
  2255 // Lookup resolution error table. Returns error if found, otherwise NULL.
  2256 symbolOop SystemDictionary::find_resolution_error(constantPoolHandle pool, int which) {
  2257   unsigned int hash = resolution_errors()->compute_hash(pool, which);
  2258   int index = resolution_errors()->hash_to_index(hash);
  2260     MutexLocker ml(SystemDictionary_lock, Thread::current());
  2261     ResolutionErrorEntry* entry = resolution_errors()->find_entry(index, hash, pool, which);
  2262     return (entry != NULL) ? entry->error() : (symbolOop)NULL;
  2267 // Signature constraints ensure that callers and callees agree about
  2268 // the meaning of type names in their signatures.  This routine is the
  2269 // intake for constraints.  It collects them from several places:
  2270 //
  2271 //  * LinkResolver::resolve_method (if check_access is true) requires
  2272 //    that the resolving class (the caller) and the defining class of
  2273 //    the resolved method (the callee) agree on each type in the
  2274 //    method's signature.
  2275 //
  2276 //  * LinkResolver::resolve_interface_method performs exactly the same
  2277 //    checks.
  2278 //
  2279 //  * LinkResolver::resolve_field requires that the constant pool
  2280 //    attempting to link to a field agree with the field's defining
  2281 //    class about the type of the field signature.
  2282 //
  2283 //  * klassVtable::initialize_vtable requires that, when a class
  2284 //    overrides a vtable entry allocated by a superclass, that the
  2285 //    overriding method (i.e., the callee) agree with the superclass
  2286 //    on each type in the method's signature.
  2287 //
  2288 //  * klassItable::initialize_itable requires that, when a class fills
  2289 //    in its itables, for each non-abstract method installed in an
  2290 //    itable, the method (i.e., the callee) agree with the interface
  2291 //    on each type in the method's signature.
  2292 //
  2293 // All those methods have a boolean (check_access, checkconstraints)
  2294 // which turns off the checks.  This is used from specialized contexts
  2295 // such as bootstrapping, dumping, and debugging.
  2296 //
  2297 // No direct constraint is placed between the class and its
  2298 // supertypes.  Constraints are only placed along linked relations
  2299 // between callers and callees.  When a method overrides or implements
  2300 // an abstract method in a supertype (superclass or interface), the
  2301 // constraints are placed as if the supertype were the caller to the
  2302 // overriding method.  (This works well, since callers to the
  2303 // supertype have already established agreement between themselves and
  2304 // the supertype.)  As a result of all this, a class can disagree with
  2305 // its supertype about the meaning of a type name, as long as that
  2306 // class neither calls a relevant method of the supertype, nor is
  2307 // called (perhaps via an override) from the supertype.
  2308 //
  2309 //
  2310 // SystemDictionary::check_signature_loaders(sig, l1, l2)
  2311 //
  2312 // Make sure all class components (including arrays) in the given
  2313 // signature will be resolved to the same class in both loaders.
  2314 // Returns the name of the type that failed a loader constraint check, or
  2315 // NULL if no constraint failed. The returned C string needs cleaning up
  2316 // with a ResourceMark in the caller.  No exception except OOME is thrown.
  2317 // Arrays are not added to the loader constraint table, their elements are.
  2318 char* SystemDictionary::check_signature_loaders(symbolHandle signature,
  2319                                                Handle loader1, Handle loader2,
  2320                                                bool is_method, TRAPS)  {
  2321   // Nothing to do if loaders are the same.
  2322   if (loader1() == loader2()) {
  2323     return NULL;
  2326   SignatureStream sig_strm(signature, is_method);
  2327   while (!sig_strm.is_done()) {
  2328     if (sig_strm.is_object()) {
  2329       symbolOop s = sig_strm.as_symbol(CHECK_NULL);
  2330       symbolHandle sig (THREAD, s);
  2331       if (!add_loader_constraint(sig, loader1, loader2, THREAD)) {
  2332         return sig()->as_C_string();
  2335     sig_strm.next();
  2337   return NULL;
  2341 methodOop SystemDictionary::find_method_handle_invoke(symbolHandle name,
  2342                                                       symbolHandle signature,
  2343                                                       KlassHandle accessing_klass,
  2344                                                       TRAPS) {
  2345   if (!EnableMethodHandles)  return NULL;
  2346   vmSymbols::SID name_id = vmSymbols::find_sid(name());
  2347   assert(name_id != vmSymbols::NO_SID, "must be a known name");
  2348   unsigned int hash  = invoke_method_table()->compute_hash(signature, name_id);
  2349   int          index = invoke_method_table()->hash_to_index(hash);
  2350   SymbolPropertyEntry* spe = invoke_method_table()->find_entry(index, hash, signature, name_id);
  2351   methodHandle non_cached_result;
  2352   if (spe == NULL || spe->property_oop() == NULL) {
  2353     spe = NULL;
  2354     // Must create lots of stuff here, but outside of the SystemDictionary lock.
  2355     if (THREAD->is_Compiler_thread())
  2356       return NULL;              // do not attempt from within compiler
  2357     bool for_invokeGeneric = (name_id == vmSymbols::VM_SYMBOL_ENUM_NAME(invokeGeneric_name));
  2358     bool found_on_bcp = false;
  2359     Handle mt = find_method_handle_type(signature(), accessing_klass,
  2360                                         for_invokeGeneric,
  2361                                         found_on_bcp, CHECK_NULL);
  2362     KlassHandle  mh_klass = SystemDictionaryHandles::MethodHandle_klass();
  2363     methodHandle m = methodOopDesc::make_invoke_method(mh_klass, name, signature,
  2364                                                        mt, CHECK_NULL);
  2365     // Now grab the lock.  We might have to throw away the new method,
  2366     // if a racing thread has managed to install one at the same time.
  2367     if (found_on_bcp) {
  2368       MutexLocker ml(SystemDictionary_lock, Thread::current());
  2369       spe = invoke_method_table()->find_entry(index, hash, signature, name_id);
  2370       if (spe == NULL)
  2371         spe = invoke_method_table()->add_entry(index, hash, signature, name_id);
  2372       if (spe->property_oop() == NULL)
  2373         spe->set_property_oop(m());
  2374     } else {
  2375       non_cached_result = m;
  2378   if (spe != NULL && spe->property_oop() != NULL) {
  2379     assert(spe->property_oop()->is_method(), "");
  2380     return (methodOop) spe->property_oop();
  2381   } else {
  2382     return non_cached_result();
  2386 // Ask Java code to find or construct a java.dyn.MethodType for the given
  2387 // signature, as interpreted relative to the given class loader.
  2388 // Because of class loader constraints, all method handle usage must be
  2389 // consistent with this loader.
  2390 Handle SystemDictionary::find_method_handle_type(symbolHandle signature,
  2391                                                  KlassHandle accessing_klass,
  2392                                                  bool for_invokeGeneric,
  2393                                                  bool& return_bcp_flag,
  2394                                                  TRAPS) {
  2395   Handle class_loader, protection_domain;
  2396   bool is_on_bcp = true;  // keep this true as long as we can materialize from the boot classloader
  2397   Handle empty;
  2398   int npts = ArgumentCount(signature()).size();
  2399   objArrayHandle pts = oopFactory::new_objArray(SystemDictionary::Class_klass(), npts, CHECK_(empty));
  2400   int arg = 0;
  2401   Handle rt;                            // the return type from the signature
  2402   for (SignatureStream ss(signature()); !ss.is_done(); ss.next()) {
  2403     oop mirror = NULL;
  2404     if (is_on_bcp) {
  2405       mirror = ss.as_java_mirror(class_loader, protection_domain,
  2406                                  SignatureStream::ReturnNull, CHECK_(empty));
  2407       if (mirror == NULL) {
  2408         // fall back from BCP to accessing_klass
  2409         if (accessing_klass.not_null()) {
  2410           class_loader      = Handle(THREAD, instanceKlass::cast(accessing_klass())->class_loader());
  2411           protection_domain = Handle(THREAD, instanceKlass::cast(accessing_klass())->protection_domain());
  2413         is_on_bcp = false;
  2416     if (!is_on_bcp) {
  2417       // Resolve, throwing a real error if it doesn't work.
  2418       mirror = ss.as_java_mirror(class_loader, protection_domain,
  2419                                  SignatureStream::NCDFError, CHECK_(empty));
  2421     if (ss.at_return_type())
  2422       rt = Handle(THREAD, mirror);
  2423     else
  2424       pts->obj_at_put(arg++, mirror);
  2425     // Check accessibility.
  2426     if (ss.is_object() && accessing_klass.not_null()) {
  2427       klassOop sel_klass = java_lang_Class::as_klassOop(mirror);
  2428       // Emulate constantPoolOopDesc::verify_constant_pool_resolve.
  2429       if (Klass::cast(sel_klass)->oop_is_objArray())
  2430         sel_klass = objArrayKlass::cast(sel_klass)->bottom_klass();
  2431       if (Klass::cast(sel_klass)->oop_is_instance()) {
  2432         KlassHandle sel_kh(THREAD, sel_klass);
  2433         LinkResolver::check_klass_accessability(accessing_klass, sel_kh, CHECK_(empty));
  2437   assert(arg == npts, "");
  2439   // call sun.dyn.MethodHandleNatives::findMethodType(Class rt, Class[] pts) -> MethodType
  2440   JavaCallArguments args(Handle(THREAD, rt()));
  2441   args.push_oop(pts());
  2442   JavaValue result(T_OBJECT);
  2443   JavaCalls::call_static(&result,
  2444                          SystemDictionary::MethodHandleNatives_klass(),
  2445                          vmSymbols::findMethodHandleType_name(),
  2446                          vmSymbols::findMethodHandleType_signature(),
  2447                          &args, CHECK_(empty));
  2448   Handle method_type(THREAD, (oop) result.get_jobject());
  2450   if (for_invokeGeneric) {
  2451     // call sun.dyn.MethodHandleNatives::notifyGenericMethodType(MethodType) -> void
  2452     JavaCallArguments args(Handle(THREAD, method_type()));
  2453     JavaValue no_result(T_VOID);
  2454     JavaCalls::call_static(&no_result,
  2455                            SystemDictionary::MethodHandleNatives_klass(),
  2456                            vmSymbols::notifyGenericMethodType_name(),
  2457                            vmSymbols::notifyGenericMethodType_signature(),
  2458                            &args, THREAD);
  2459     if (HAS_PENDING_EXCEPTION) {
  2460       // If the notification fails, just kill it.
  2461       CLEAR_PENDING_EXCEPTION;
  2465   // report back to the caller with the MethodType and the "on_bcp" flag
  2466   return_bcp_flag = is_on_bcp;
  2467   return method_type;
  2470 // Ask Java code to find or construct a method handle constant.
  2471 Handle SystemDictionary::link_method_handle_constant(KlassHandle caller,
  2472                                                      int ref_kind, //e.g., JVM_REF_invokeVirtual
  2473                                                      KlassHandle callee,
  2474                                                      symbolHandle name_sym,
  2475                                                      symbolHandle signature,
  2476                                                      TRAPS) {
  2477   Handle empty;
  2478   Handle name = java_lang_String::create_from_symbol(name_sym(), CHECK_(empty));
  2479   Handle type;
  2480   if (signature->utf8_length() > 0 && signature->byte_at(0) == '(') {
  2481     bool ignore_is_on_bcp = false;
  2482     type = find_method_handle_type(signature, caller, false, ignore_is_on_bcp, CHECK_(empty));
  2483   } else {
  2484     SignatureStream ss(signature(), false);
  2485     if (!ss.is_done()) {
  2486       oop mirror = ss.as_java_mirror(caller->class_loader(), caller->protection_domain(),
  2487                                      SignatureStream::NCDFError, CHECK_(empty));
  2488       type = Handle(THREAD, mirror);
  2489       ss.next();
  2490       if (!ss.is_done())  type = Handle();  // error!
  2493   if (type.is_null()) {
  2494     THROW_MSG_(vmSymbols::java_lang_LinkageError(), "bad signature", empty);
  2497   // call sun.dyn.MethodHandleNatives::linkMethodHandleConstant(Class caller, int refKind, Class callee, String name, Object type) -> MethodHandle
  2498   JavaCallArguments args;
  2499   args.push_oop(caller->java_mirror());  // the referring class
  2500   args.push_int(ref_kind);
  2501   args.push_oop(callee->java_mirror());  // the target class
  2502   args.push_oop(name());
  2503   args.push_oop(type());
  2504   JavaValue result(T_OBJECT);
  2505   JavaCalls::call_static(&result,
  2506                          SystemDictionary::MethodHandleNatives_klass(),
  2507                          vmSymbols::linkMethodHandleConstant_name(),
  2508                          vmSymbols::linkMethodHandleConstant_signature(),
  2509                          &args, CHECK_(empty));
  2510   return Handle(THREAD, (oop) result.get_jobject());
  2513 // Ask Java code to find or construct a java.dyn.CallSite for the given
  2514 // name and signature, as interpreted relative to the given class loader.
  2515 Handle SystemDictionary::make_dynamic_call_site(Handle bootstrap_method,
  2516                                                 symbolHandle name,
  2517                                                 methodHandle signature_invoker,
  2518                                                 Handle info,
  2519                                                 methodHandle caller_method,
  2520                                                 int caller_bci,
  2521                                                 TRAPS) {
  2522   Handle empty;
  2523   guarantee(bootstrap_method.not_null() &&
  2524             java_dyn_MethodHandle::is_instance(bootstrap_method()),
  2525             "caller must supply a valid BSM");
  2527   Handle caller_mname = MethodHandles::new_MemberName(CHECK_(empty));
  2528   MethodHandles::init_MemberName(caller_mname(), caller_method());
  2530   // call sun.dyn.MethodHandleNatives::makeDynamicCallSite(bootm, name, mtype, info, caller_mname, caller_pos)
  2531   oop name_str_oop = StringTable::intern(name(), CHECK_(empty)); // not a handle!
  2532   JavaCallArguments args(Handle(THREAD, bootstrap_method()));
  2533   args.push_oop(name_str_oop);
  2534   args.push_oop(signature_invoker->method_handle_type());
  2535   args.push_oop(info());
  2536   args.push_oop(caller_mname());
  2537   args.push_int(caller_bci);
  2538   JavaValue result(T_OBJECT);
  2539   JavaCalls::call_static(&result,
  2540                          SystemDictionary::MethodHandleNatives_klass(),
  2541                          vmSymbols::makeDynamicCallSite_name(),
  2542                          vmSymbols::makeDynamicCallSite_signature(),
  2543                          &args, CHECK_(empty));
  2544   oop call_site_oop = (oop) result.get_jobject();
  2545   assert(call_site_oop->is_oop()
  2546          /*&& java_dyn_CallSite::is_instance(call_site_oop)*/, "must be sane");
  2547   if (TraceMethodHandles) {
  2548 #ifndef PRODUCT
  2549     tty->print_cr("Linked invokedynamic bci=%d site="INTPTR_FORMAT":", caller_bci, call_site_oop);
  2550     call_site_oop->print();
  2551     tty->cr();
  2552 #endif //PRODUCT
  2554   return call_site_oop;
  2557 Handle SystemDictionary::find_bootstrap_method(methodHandle caller_method, int caller_bci,
  2558                                                int cache_index,
  2559                                                Handle& argument_info_result,
  2560                                                TRAPS) {
  2561   Handle empty;
  2563   constantPoolHandle pool;
  2565     klassOop caller = caller_method->method_holder();
  2566     if (!Klass::cast(caller)->oop_is_instance())  return empty;
  2567     pool = constantPoolHandle(THREAD, instanceKlass::cast(caller)->constants());
  2570   int constant_pool_index = pool->cache()->entry_at(cache_index)->constant_pool_index();
  2571   constantTag tag = pool->tag_at(constant_pool_index);
  2573   if (tag.is_invoke_dynamic()) {
  2574     // JVM_CONSTANT_InvokeDynamic is an ordered pair of [bootm, name&type], plus optional arguments
  2575     // The bootm, being a JVM_CONSTANT_MethodHandle, has its own cache entry.
  2576     int bsm_index = pool->invoke_dynamic_bootstrap_method_ref_index_at(constant_pool_index);
  2577     if (bsm_index != 0) {
  2578       int bsm_index_in_cache = pool->cache()->entry_at(cache_index)->bootstrap_method_index_in_cache();
  2579       DEBUG_ONLY(int bsm_index_2 = pool->cache()->entry_at(bsm_index_in_cache)->constant_pool_index());
  2580       assert(bsm_index == bsm_index_2, "BSM constant lifted to cache");
  2581       if (TraceMethodHandles) {
  2582         tty->print_cr("resolving bootstrap method for "PTR_FORMAT" at %d at cache[%d]CP[%d]...",
  2583                       (intptr_t) caller_method(), caller_bci, cache_index, constant_pool_index);
  2585       oop bsm_oop = pool->resolve_cached_constant_at(bsm_index_in_cache, CHECK_(empty));
  2586       if (TraceMethodHandles) {
  2587         tty->print_cr("bootstrap method for "PTR_FORMAT" at %d retrieved as "PTR_FORMAT":",
  2588                       (intptr_t) caller_method(), caller_bci, (intptr_t) bsm_oop);
  2590       assert(bsm_oop->is_oop(), "must be sane");
  2591       // caller must verify that it is of type MethodHandle
  2592       Handle bsm(THREAD, bsm_oop);
  2593       bsm_oop = NULL;  // safety
  2595       // Extract the optional static arguments.
  2596       Handle argument_info;  // either null, or one arg, or Object[]{arg...}
  2597       int argc = pool->invoke_dynamic_argument_count_at(constant_pool_index);
  2598       if (TraceInvokeDynamic) {
  2599         tty->print_cr("find_bootstrap_method: [%d/%d] CONSTANT_InvokeDynamic: %d[%d]",
  2600                       constant_pool_index, cache_index, bsm_index, argc);
  2602       if (argc > 0) {
  2603         objArrayHandle arg_array;
  2604         if (argc > 1) {
  2605           objArrayOop arg_array_oop = oopFactory::new_objArray(SystemDictionary::Object_klass(), argc, CHECK_(empty));
  2606           arg_array = objArrayHandle(THREAD, arg_array_oop);
  2607           argument_info = arg_array;
  2609         for (int arg_i = 0; arg_i < argc; arg_i++) {
  2610           int arg_index = pool->invoke_dynamic_argument_index_at(constant_pool_index, arg_i);
  2611           oop arg_oop = pool->resolve_possibly_cached_constant_at(arg_index, CHECK_(empty));
  2612           if (arg_array.is_null()) {
  2613             argument_info = Handle(THREAD, arg_oop);
  2614           } else {
  2615             arg_array->obj_at_put(arg_i, arg_oop);
  2620       argument_info_result = argument_info;  // return argument_info to caller
  2621       return bsm;
  2623     // else null BSM; fall through
  2624   } else if (tag.is_name_and_type()) {
  2625     // JSR 292 EDR does not have JVM_CONSTANT_InvokeDynamic
  2626     // a bare name&type defaults its BSM to null, so fall through...
  2627   } else {
  2628     ShouldNotReachHere();  // verifier does not allow this
  2631   // Fall through to pick up the per-class bootstrap method.
  2632   // This mechanism may go away in the PFD.
  2633   assert(AllowTransitionalJSR292, "else the verifier should have stopped us already");
  2634   argument_info_result = empty;  // return no argument_info to caller
  2635   oop bsm_oop = instanceKlass::cast(caller_method->method_holder())->bootstrap_method();
  2636   if (bsm_oop != NULL) {
  2637     if (TraceMethodHandles) {
  2638       tty->print_cr("bootstrap method for "PTR_FORMAT" registered as "PTR_FORMAT":",
  2639                     (intptr_t) caller_method(), (intptr_t) bsm_oop);
  2641     assert(bsm_oop->is_oop(), "must be sane");
  2642     return Handle(THREAD, bsm_oop);
  2645   return empty;
  2648 // Since the identity hash code for symbols changes when the symbols are
  2649 // moved from the regular perm gen (hash in the mark word) to the shared
  2650 // spaces (hash is the address), the classes loaded into the dictionary
  2651 // may be in the wrong buckets.
  2653 void SystemDictionary::reorder_dictionary() {
  2654   dictionary()->reorder_dictionary();
  2658 void SystemDictionary::copy_buckets(char** top, char* end) {
  2659   dictionary()->copy_buckets(top, end);
  2663 void SystemDictionary::copy_table(char** top, char* end) {
  2664   dictionary()->copy_table(top, end);
  2668 void SystemDictionary::reverse() {
  2669   dictionary()->reverse();
  2672 int SystemDictionary::number_of_classes() {
  2673   return dictionary()->number_of_entries();
  2677 // ----------------------------------------------------------------------------
  2678 #ifndef PRODUCT
  2680 void SystemDictionary::print() {
  2681   dictionary()->print();
  2683   // Placeholders
  2684   GCMutexLocker mu(SystemDictionary_lock);
  2685   placeholders()->print();
  2687   // loader constraints - print under SD_lock
  2688   constraints()->print();
  2691 #endif
  2693 void SystemDictionary::verify() {
  2694   guarantee(dictionary() != NULL, "Verify of system dictionary failed");
  2695   guarantee(constraints() != NULL,
  2696             "Verify of loader constraints failed");
  2697   guarantee(dictionary()->number_of_entries() >= 0 &&
  2698             placeholders()->number_of_entries() >= 0,
  2699             "Verify of system dictionary failed");
  2701   // Verify dictionary
  2702   dictionary()->verify();
  2704   GCMutexLocker mu(SystemDictionary_lock);
  2705   placeholders()->verify();
  2707   // Verify constraint table
  2708   guarantee(constraints() != NULL, "Verify of loader constraints failed");
  2709   constraints()->verify(dictionary(), placeholders());
  2713 void SystemDictionary::verify_obj_klass_present(Handle obj,
  2714                                                 symbolHandle class_name,
  2715                                                 Handle class_loader) {
  2716   GCMutexLocker mu(SystemDictionary_lock);
  2717   oop probe = find_class_or_placeholder(class_name, class_loader);
  2718   if (probe == NULL) {
  2719     probe = SystemDictionary::find_shared_class(class_name);
  2721   guarantee(probe != NULL &&
  2722             (!probe->is_klass() || probe == obj()),
  2723                      "Loaded klasses should be in SystemDictionary");
  2726 #ifndef PRODUCT
  2728 // statistics code
  2729 class ClassStatistics: AllStatic {
  2730  private:
  2731   static int nclasses;        // number of classes
  2732   static int nmethods;        // number of methods
  2733   static int nmethoddata;     // number of methodData
  2734   static int class_size;      // size of class objects in words
  2735   static int method_size;     // size of method objects in words
  2736   static int debug_size;      // size of debug info in methods
  2737   static int methoddata_size; // size of methodData objects in words
  2739   static void do_class(klassOop k) {
  2740     nclasses++;
  2741     class_size += k->size();
  2742     if (k->klass_part()->oop_is_instance()) {
  2743       instanceKlass* ik = (instanceKlass*)k->klass_part();
  2744       class_size += ik->methods()->size();
  2745       class_size += ik->constants()->size();
  2746       class_size += ik->local_interfaces()->size();
  2747       class_size += ik->transitive_interfaces()->size();
  2748       // We do not have to count implementors, since we only store one!
  2749       class_size += ik->fields()->size();
  2753   static void do_method(methodOop m) {
  2754     nmethods++;
  2755     method_size += m->size();
  2756     // class loader uses same objArray for empty vectors, so don't count these
  2757     if (m->exception_table()->length() != 0)   method_size += m->exception_table()->size();
  2758     if (m->has_stackmap_table()) {
  2759       method_size += m->stackmap_data()->size();
  2762     methodDataOop mdo = m->method_data();
  2763     if (mdo != NULL) {
  2764       nmethoddata++;
  2765       methoddata_size += mdo->size();
  2769  public:
  2770   static void print() {
  2771     SystemDictionary::classes_do(do_class);
  2772     SystemDictionary::methods_do(do_method);
  2773     tty->print_cr("Class statistics:");
  2774     tty->print_cr("%d classes (%d bytes)", nclasses, class_size * oopSize);
  2775     tty->print_cr("%d methods (%d bytes = %d base + %d debug info)", nmethods,
  2776                   (method_size + debug_size) * oopSize, method_size * oopSize, debug_size * oopSize);
  2777     tty->print_cr("%d methoddata (%d bytes)", nmethoddata, methoddata_size * oopSize);
  2779 };
  2782 int ClassStatistics::nclasses        = 0;
  2783 int ClassStatistics::nmethods        = 0;
  2784 int ClassStatistics::nmethoddata     = 0;
  2785 int ClassStatistics::class_size      = 0;
  2786 int ClassStatistics::method_size     = 0;
  2787 int ClassStatistics::debug_size      = 0;
  2788 int ClassStatistics::methoddata_size = 0;
  2790 void SystemDictionary::print_class_statistics() {
  2791   ResourceMark rm;
  2792   ClassStatistics::print();
  2796 class MethodStatistics: AllStatic {
  2797  public:
  2798   enum {
  2799     max_parameter_size = 10
  2800   };
  2801  private:
  2803   static int _number_of_methods;
  2804   static int _number_of_final_methods;
  2805   static int _number_of_static_methods;
  2806   static int _number_of_native_methods;
  2807   static int _number_of_synchronized_methods;
  2808   static int _number_of_profiled_methods;
  2809   static int _number_of_bytecodes;
  2810   static int _parameter_size_profile[max_parameter_size];
  2811   static int _bytecodes_profile[Bytecodes::number_of_java_codes];
  2813   static void initialize() {
  2814     _number_of_methods        = 0;
  2815     _number_of_final_methods  = 0;
  2816     _number_of_static_methods = 0;
  2817     _number_of_native_methods = 0;
  2818     _number_of_synchronized_methods = 0;
  2819     _number_of_profiled_methods = 0;
  2820     _number_of_bytecodes      = 0;
  2821     for (int i = 0; i < max_parameter_size             ; i++) _parameter_size_profile[i] = 0;
  2822     for (int j = 0; j < Bytecodes::number_of_java_codes; j++) _bytecodes_profile     [j] = 0;
  2823   };
  2825   static void do_method(methodOop m) {
  2826     _number_of_methods++;
  2827     // collect flag info
  2828     if (m->is_final()       ) _number_of_final_methods++;
  2829     if (m->is_static()      ) _number_of_static_methods++;
  2830     if (m->is_native()      ) _number_of_native_methods++;
  2831     if (m->is_synchronized()) _number_of_synchronized_methods++;
  2832     if (m->method_data() != NULL) _number_of_profiled_methods++;
  2833     // collect parameter size info (add one for receiver, if any)
  2834     _parameter_size_profile[MIN2(m->size_of_parameters() + (m->is_static() ? 0 : 1), max_parameter_size - 1)]++;
  2835     // collect bytecodes info
  2837       Thread *thread = Thread::current();
  2838       HandleMark hm(thread);
  2839       BytecodeStream s(methodHandle(thread, m));
  2840       Bytecodes::Code c;
  2841       while ((c = s.next()) >= 0) {
  2842         _number_of_bytecodes++;
  2843         _bytecodes_profile[c]++;
  2848  public:
  2849   static void print() {
  2850     initialize();
  2851     SystemDictionary::methods_do(do_method);
  2852     // generate output
  2853     tty->cr();
  2854     tty->print_cr("Method statistics (static):");
  2855     // flag distribution
  2856     tty->cr();
  2857     tty->print_cr("%6d final        methods  %6.1f%%", _number_of_final_methods       , _number_of_final_methods        * 100.0F / _number_of_methods);
  2858     tty->print_cr("%6d static       methods  %6.1f%%", _number_of_static_methods      , _number_of_static_methods       * 100.0F / _number_of_methods);
  2859     tty->print_cr("%6d native       methods  %6.1f%%", _number_of_native_methods      , _number_of_native_methods       * 100.0F / _number_of_methods);
  2860     tty->print_cr("%6d synchronized methods  %6.1f%%", _number_of_synchronized_methods, _number_of_synchronized_methods * 100.0F / _number_of_methods);
  2861     tty->print_cr("%6d profiled     methods  %6.1f%%", _number_of_profiled_methods, _number_of_profiled_methods * 100.0F / _number_of_methods);
  2862     // parameter size profile
  2863     tty->cr();
  2864     { int tot = 0;
  2865       int avg = 0;
  2866       for (int i = 0; i < max_parameter_size; i++) {
  2867         int n = _parameter_size_profile[i];
  2868         tot += n;
  2869         avg += n*i;
  2870         tty->print_cr("parameter size = %1d: %6d methods  %5.1f%%", i, n, n * 100.0F / _number_of_methods);
  2872       assert(tot == _number_of_methods, "should be the same");
  2873       tty->print_cr("                    %6d methods  100.0%%", _number_of_methods);
  2874       tty->print_cr("(average parameter size = %3.1f including receiver, if any)", (float)avg / _number_of_methods);
  2876     // bytecodes profile
  2877     tty->cr();
  2878     { int tot = 0;
  2879       for (int i = 0; i < Bytecodes::number_of_java_codes; i++) {
  2880         if (Bytecodes::is_defined(i)) {
  2881           Bytecodes::Code c = Bytecodes::cast(i);
  2882           int n = _bytecodes_profile[c];
  2883           tot += n;
  2884           tty->print_cr("%9d  %7.3f%%  %s", n, n * 100.0F / _number_of_bytecodes, Bytecodes::name(c));
  2887       assert(tot == _number_of_bytecodes, "should be the same");
  2888       tty->print_cr("%9d  100.000%%", _number_of_bytecodes);
  2890     tty->cr();
  2892 };
  2894 int MethodStatistics::_number_of_methods;
  2895 int MethodStatistics::_number_of_final_methods;
  2896 int MethodStatistics::_number_of_static_methods;
  2897 int MethodStatistics::_number_of_native_methods;
  2898 int MethodStatistics::_number_of_synchronized_methods;
  2899 int MethodStatistics::_number_of_profiled_methods;
  2900 int MethodStatistics::_number_of_bytecodes;
  2901 int MethodStatistics::_parameter_size_profile[MethodStatistics::max_parameter_size];
  2902 int MethodStatistics::_bytecodes_profile[Bytecodes::number_of_java_codes];
  2905 void SystemDictionary::print_method_statistics() {
  2906   MethodStatistics::print();
  2909 #endif // PRODUCT

mercurial