src/share/vm/classfile/systemDictionary.cpp

Wed, 23 Sep 2009 23:56:15 -0700

author
jrose
date
Wed, 23 Sep 2009 23:56:15 -0700
changeset 1428
54b3b351d6f9
parent 1424
148e5441d916
parent 1408
ad6585fd4087
child 1474
987e948ebbc8
permissions
-rw-r--r--

Merge

     1 /*
     2  * Copyright 1997-2009 Sun Microsystems, Inc.  All Rights Reserved.
     3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
     4  *
     5  * This code is free software; you can redistribute it and/or modify it
     6  * under the terms of the GNU General Public License version 2 only, as
     7  * published by the Free Software Foundation.
     8  *
     9  * This code is distributed in the hope that it will be useful, but WITHOUT
    10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
    12  * version 2 for more details (a copy is included in the LICENSE file that
    13  * accompanied this code).
    14  *
    15  * You should have received a copy of the GNU General Public License version
    16  * 2 along with this work; if not, write to the Free Software Foundation,
    17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
    18  *
    19  * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
    20  * CA 95054 USA or visit www.sun.com if you need additional information or
    21  * have any questions.
    22  *
    23  */
    25 # include "incls/_precompiled.incl"
    26 # include "incls/_systemDictionary.cpp.incl"
    29 Dictionary*       SystemDictionary::_dictionary = NULL;
    30 PlaceholderTable* SystemDictionary::_placeholders = NULL;
    31 Dictionary*       SystemDictionary::_shared_dictionary = NULL;
    32 LoaderConstraintTable* SystemDictionary::_loader_constraints = NULL;
    33 ResolutionErrorTable* SystemDictionary::_resolution_errors = NULL;
    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 // Resolving of classes
   104 // Forwards to resolve_or_null
   106 klassOop SystemDictionary::resolve_or_fail(symbolHandle class_name, Handle class_loader, Handle protection_domain, bool throw_error, TRAPS) {
   107   klassOop klass = resolve_or_null(class_name, class_loader, protection_domain, THREAD);
   108   if (HAS_PENDING_EXCEPTION || klass == NULL) {
   109     KlassHandle k_h(THREAD, klass);
   110     // can return a null klass
   111     klass = handle_resolution_exception(class_name, class_loader, protection_domain, throw_error, k_h, THREAD);
   112   }
   113   return klass;
   114 }
   116 klassOop SystemDictionary::handle_resolution_exception(symbolHandle class_name, Handle class_loader, Handle protection_domain, bool throw_error, KlassHandle klass_h, TRAPS) {
   117   if (HAS_PENDING_EXCEPTION) {
   118     // If we have a pending exception we forward it to the caller, unless throw_error is true,
   119     // in which case we have to check whether the pending exception is a ClassNotFoundException,
   120     // and if so convert it to a NoClassDefFoundError
   121     // And chain the original ClassNotFoundException
   122     if (throw_error && PENDING_EXCEPTION->is_a(SystemDictionary::classNotFoundException_klass())) {
   123       ResourceMark rm(THREAD);
   124       assert(klass_h() == NULL, "Should not have result with exception pending");
   125       Handle e(THREAD, PENDING_EXCEPTION);
   126       CLEAR_PENDING_EXCEPTION;
   127       THROW_MSG_CAUSE_0(vmSymbols::java_lang_NoClassDefFoundError(), class_name->as_C_string(), e);
   128     } else {
   129       return NULL;
   130     }
   131   }
   132   // Class not found, throw appropriate error or exception depending on value of throw_error
   133   if (klass_h() == NULL) {
   134     ResourceMark rm(THREAD);
   135     if (throw_error) {
   136       THROW_MSG_0(vmSymbols::java_lang_NoClassDefFoundError(), class_name->as_C_string());
   137     } else {
   138       THROW_MSG_0(vmSymbols::java_lang_ClassNotFoundException(), class_name->as_C_string());
   139     }
   140   }
   141   return (klassOop)klass_h();
   142 }
   145 klassOop SystemDictionary::resolve_or_fail(symbolHandle class_name,
   146                                            bool throw_error, TRAPS)
   147 {
   148   return resolve_or_fail(class_name, Handle(), Handle(), throw_error, THREAD);
   149 }
   152 // Forwards to resolve_instance_class_or_null
   154 klassOop SystemDictionary::resolve_or_null(symbolHandle class_name, Handle class_loader, Handle protection_domain, TRAPS) {
   155   assert(!THREAD->is_Compiler_thread(), "Can not load classes with the Compiler thread");
   156   if (FieldType::is_array(class_name())) {
   157     return resolve_array_class_or_null(class_name, class_loader, protection_domain, CHECK_NULL);
   158   } else {
   159     return resolve_instance_class_or_null(class_name, class_loader, protection_domain, CHECK_NULL);
   160   }
   161 }
   163 klassOop SystemDictionary::resolve_or_null(symbolHandle class_name, TRAPS) {
   164   return resolve_or_null(class_name, Handle(), Handle(), THREAD);
   165 }
   167 // Forwards to resolve_instance_class_or_null
   169 klassOop SystemDictionary::resolve_array_class_or_null(symbolHandle class_name,
   170                                                        Handle class_loader,
   171                                                        Handle protection_domain,
   172                                                        TRAPS) {
   173   assert(FieldType::is_array(class_name()), "must be array");
   174   jint dimension;
   175   symbolOop object_key;
   176   klassOop k = NULL;
   177   // dimension and object_key are assigned as a side-effect of this call
   178   BasicType t = FieldType::get_array_info(class_name(),
   179                                           &dimension,
   180                                           &object_key,
   181                                           CHECK_NULL);
   183   if (t == T_OBJECT) {
   184     symbolHandle h_key(THREAD, object_key);
   185     // naked oop "k" is OK here -- we assign back into it
   186     k = SystemDictionary::resolve_instance_class_or_null(h_key,
   187                                                          class_loader,
   188                                                          protection_domain,
   189                                                          CHECK_NULL);
   190     if (k != NULL) {
   191       k = Klass::cast(k)->array_klass(dimension, CHECK_NULL);
   192     }
   193   } else {
   194     k = Universe::typeArrayKlassObj(t);
   195     k = typeArrayKlass::cast(k)->array_klass(dimension, CHECK_NULL);
   196   }
   197   return k;
   198 }
   201 // Must be called for any super-class or super-interface resolution
   202 // during class definition to allow class circularity checking
   203 // super-interface callers:
   204 //    parse_interfaces - for defineClass & jvmtiRedefineClasses
   205 // super-class callers:
   206 //   ClassFileParser - for defineClass & jvmtiRedefineClasses
   207 //   load_shared_class - while loading a class from shared archive
   208 //   resolve_instance_class_or_null:
   209 //     via: handle_parallel_super_load
   210 //      when resolving a class that has an existing placeholder with
   211 //      a saved superclass [i.e. a defineClass is currently in progress]
   212 //      if another thread is trying to resolve the class, it must do
   213 //      super-class checks on its own thread to catch class circularity
   214 // This last call is critical in class circularity checking for cases
   215 // where classloading is delegated to different threads and the
   216 // classloader lock is released.
   217 // Take the case: Base->Super->Base
   218 //   1. If thread T1 tries to do a defineClass of class Base
   219 //    resolve_super_or_fail creates placeholder: T1, Base (super Super)
   220 //   2. resolve_instance_class_or_null does not find SD or placeholder for Super
   221 //    so it tries to load Super
   222 //   3. If we load the class internally, or user classloader uses same thread
   223 //      loadClassFromxxx or defineClass via parseClassFile Super ...
   224 //      3.1 resolve_super_or_fail creates placeholder: T1, Super (super Base)
   225 //      3.3 resolve_instance_class_or_null Base, finds placeholder for Base
   226 //      3.4 calls resolve_super_or_fail Base
   227 //      3.5 finds T1,Base -> throws class circularity
   228 //OR 4. If T2 tries to resolve Super via defineClass Super ...
   229 //      4.1 resolve_super_or_fail creates placeholder: T2, Super (super Base)
   230 //      4.2 resolve_instance_class_or_null Base, finds placeholder for Base (super Super)
   231 //      4.3 calls resolve_super_or_fail Super in parallel on own thread T2
   232 //      4.4 finds T2, Super -> throws class circularity
   233 // Must be called, even if superclass is null, since this is
   234 // where the placeholder entry is created which claims this
   235 // thread is loading this class/classloader.
   236 klassOop SystemDictionary::resolve_super_or_fail(symbolHandle child_name,
   237                                                  symbolHandle class_name,
   238                                                  Handle class_loader,
   239                                                  Handle protection_domain,
   240                                                  bool is_superclass,
   241                                                  TRAPS) {
   243   // Try to get one of the well-known klasses.
   244   // They are trusted, and do not participate in circularities.
   245   if (LinkWellKnownClasses) {
   246     klassOop k = find_well_known_klass(class_name());
   247     if (k != NULL) {
   248       return k;
   249     }
   250   }
   252   // Double-check, if child class is already loaded, just return super-class,interface
   253   // Don't add a placedholder if already loaded, i.e. already in system dictionary
   254   // Make sure there's a placeholder for the *child* before resolving.
   255   // Used as a claim that this thread is currently loading superclass/classloader
   256   // Used here for ClassCircularity checks and also for heap verification
   257   // (every instanceKlass in the heap needs to be in the system dictionary
   258   // or have a placeholder).
   259   // Must check ClassCircularity before checking if super class is already loaded
   260   //
   261   // We might not already have a placeholder if this child_name was
   262   // first seen via resolve_from_stream (jni_DefineClass or JVM_DefineClass);
   263   // the name of the class might not be known until the stream is actually
   264   // parsed.
   265   // Bugs 4643874, 4715493
   266   // compute_hash can have a safepoint
   268   unsigned int d_hash = dictionary()->compute_hash(child_name, class_loader);
   269   int d_index = dictionary()->hash_to_index(d_hash);
   270   unsigned int p_hash = placeholders()->compute_hash(child_name, class_loader);
   271   int p_index = placeholders()->hash_to_index(p_hash);
   272   // can't throw error holding a lock
   273   bool child_already_loaded = false;
   274   bool throw_circularity_error = false;
   275   {
   276     MutexLocker mu(SystemDictionary_lock, THREAD);
   277     klassOop childk = find_class(d_index, d_hash, child_name, class_loader);
   278     klassOop quicksuperk;
   279     // to support // loading: if child done loading, just return superclass
   280     // if class_name, & class_loader don't match:
   281     // if initial define, SD update will give LinkageError
   282     // if redefine: compare_class_versions will give HIERARCHY_CHANGED
   283     // so we don't throw an exception here.
   284     // see: nsk redefclass014 & java.lang.instrument Instrument032
   285     if ((childk != NULL ) && (is_superclass) &&
   286        ((quicksuperk = instanceKlass::cast(childk)->super()) != NULL) &&
   288          ((Klass::cast(quicksuperk)->name() == class_name()) &&
   289             (Klass::cast(quicksuperk)->class_loader()  == class_loader()))) {
   290            return quicksuperk;
   291     } else {
   292       PlaceholderEntry* probe = placeholders()->get_entry(p_index, p_hash, child_name, class_loader);
   293       if (probe && probe->check_seen_thread(THREAD, PlaceholderTable::LOAD_SUPER)) {
   294           throw_circularity_error = true;
   295       }
   296     }
   297     if (!throw_circularity_error) {
   298       PlaceholderEntry* newprobe = placeholders()->find_and_add(p_index, p_hash, child_name, class_loader, PlaceholderTable::LOAD_SUPER, class_name, THREAD);
   299     }
   300   }
   301   if (throw_circularity_error) {
   302       ResourceMark rm(THREAD);
   303       THROW_MSG_0(vmSymbols::java_lang_ClassCircularityError(), child_name->as_C_string());
   304   }
   306 // java.lang.Object should have been found above
   307   assert(class_name() != NULL, "null super class for resolving");
   308   // Resolve the super class or interface, check results on return
   309   klassOop superk = NULL;
   310   superk = SystemDictionary::resolve_or_null(class_name,
   311                                                  class_loader,
   312                                                  protection_domain,
   313                                                  THREAD);
   315   KlassHandle superk_h(THREAD, superk);
   317   // Note: clean up of placeholders currently in callers of
   318   // resolve_super_or_fail - either at update_dictionary time
   319   // or on error
   320   {
   321   MutexLocker mu(SystemDictionary_lock, THREAD);
   322    PlaceholderEntry* probe = placeholders()->get_entry(p_index, p_hash, child_name, class_loader);
   323    if (probe != NULL) {
   324       probe->remove_seen_thread(THREAD, PlaceholderTable::LOAD_SUPER);
   325    }
   326   }
   327   if (HAS_PENDING_EXCEPTION || superk_h() == NULL) {
   328     // can null superk
   329     superk_h = KlassHandle(THREAD, handle_resolution_exception(class_name, class_loader, protection_domain, true, superk_h, THREAD));
   330   }
   332   return superk_h();
   333 }
   335 void SystemDictionary::validate_protection_domain(instanceKlassHandle klass,
   336                                                   Handle class_loader,
   337                                                   Handle protection_domain,
   338                                                   TRAPS) {
   339   if(!has_checkPackageAccess()) return;
   341   // Now we have to call back to java to check if the initating class has access
   342   JavaValue result(T_VOID);
   343   if (TraceProtectionDomainVerification) {
   344     // Print out trace information
   345     tty->print_cr("Checking package access");
   346     tty->print(" - class loader:      "); class_loader()->print_value_on(tty);      tty->cr();
   347     tty->print(" - protection domain: "); protection_domain()->print_value_on(tty); tty->cr();
   348     tty->print(" - loading:           "); klass()->print_value_on(tty);             tty->cr();
   349   }
   351   assert(class_loader() != NULL, "should not have non-null protection domain for null classloader");
   353   KlassHandle system_loader(THREAD, SystemDictionary::classloader_klass());
   354   JavaCalls::call_special(&result,
   355                          class_loader,
   356                          system_loader,
   357                          vmSymbolHandles::checkPackageAccess_name(),
   358                          vmSymbolHandles::class_protectiondomain_signature(),
   359                          Handle(THREAD, klass->java_mirror()),
   360                          protection_domain,
   361                          THREAD);
   363   if (TraceProtectionDomainVerification) {
   364     if (HAS_PENDING_EXCEPTION) {
   365       tty->print_cr(" -> DENIED !!!!!!!!!!!!!!!!!!!!!");
   366     } else {
   367      tty->print_cr(" -> granted");
   368     }
   369     tty->cr();
   370   }
   372   if (HAS_PENDING_EXCEPTION) return;
   374   // If no exception has been thrown, we have validated the protection domain
   375   // Insert the protection domain of the initiating class into the set.
   376   {
   377     // We recalculate the entry here -- we've called out to java since
   378     // the last time it was calculated.
   379     symbolHandle kn(THREAD, klass->name());
   380     unsigned int d_hash = dictionary()->compute_hash(kn, class_loader);
   381     int d_index = dictionary()->hash_to_index(d_hash);
   383     MutexLocker mu(SystemDictionary_lock, THREAD);
   384     {
   385       // Note that we have an entry, and entries can be deleted only during GC,
   386       // so we cannot allow GC to occur while we're holding this entry.
   388       // We're using a No_Safepoint_Verifier to catch any place where we
   389       // might potentially do a GC at all.
   390       // SystemDictionary::do_unloading() asserts that classes are only
   391       // unloaded at a safepoint.
   392       No_Safepoint_Verifier nosafepoint;
   393       dictionary()->add_protection_domain(d_index, d_hash, klass, class_loader,
   394                                           protection_domain, THREAD);
   395     }
   396   }
   397 }
   399 // We only get here if this thread finds that another thread
   400 // has already claimed the placeholder token for the current operation,
   401 // but that other thread either never owned or gave up the
   402 // object lock
   403 // Waits on SystemDictionary_lock to indicate placeholder table updated
   404 // On return, caller must recheck placeholder table state
   405 //
   406 // We only get here if
   407 //  1) custom classLoader, i.e. not bootstrap classloader
   408 //  2) UnsyncloadClass not set
   409 //  3) custom classLoader has broken the class loader objectLock
   410 //     so another thread got here in parallel
   411 //
   412 // lockObject must be held.
   413 // Complicated dance due to lock ordering:
   414 // Must first release the classloader object lock to
   415 // allow initial definer to complete the class definition
   416 // and to avoid deadlock
   417 // Reclaim classloader lock object with same original recursion count
   418 // Must release SystemDictionary_lock after notify, since
   419 // class loader lock must be claimed before SystemDictionary_lock
   420 // to prevent deadlocks
   421 //
   422 // The notify allows applications that did an untimed wait() on
   423 // the classloader object lock to not hang.
   424 void SystemDictionary::double_lock_wait(Handle lockObject, TRAPS) {
   425   assert_lock_strong(SystemDictionary_lock);
   427   bool calledholdinglock
   428       = ObjectSynchronizer::current_thread_holds_lock((JavaThread*)THREAD, lockObject);
   429   assert(calledholdinglock,"must hold lock for notify");
   430   assert((!(lockObject() == _system_loader_lock_obj) && !is_parallelCapable(lockObject)), "unexpected double_lock_wait");
   431   ObjectSynchronizer::notifyall(lockObject, THREAD);
   432   intptr_t recursions =  ObjectSynchronizer::complete_exit(lockObject, THREAD);
   433   SystemDictionary_lock->wait();
   434   SystemDictionary_lock->unlock();
   435   ObjectSynchronizer::reenter(lockObject, recursions, THREAD);
   436   SystemDictionary_lock->lock();
   437 }
   439 // If the class in is in the placeholder table, class loading is in progress
   440 // For cases where the application changes threads to load classes, it
   441 // is critical to ClassCircularity detection that we try loading
   442 // the superclass on the same thread internally, so we do parallel
   443 // super class loading here.
   444 // This also is critical in cases where the original thread gets stalled
   445 // even in non-circularity situations.
   446 // Note: only one thread can define the class, but multiple can resolve
   447 // Note: must call resolve_super_or_fail even if null super -
   448 // to force placeholder entry creation for this class for circularity detection
   449 // Caller must check for pending exception
   450 // Returns non-null klassOop if other thread has completed load
   451 // and we are done,
   452 // If return null klassOop and no pending exception, the caller must load the class
   453 instanceKlassHandle SystemDictionary::handle_parallel_super_load(
   454     symbolHandle name, symbolHandle superclassname, Handle class_loader,
   455     Handle protection_domain, Handle lockObject, TRAPS) {
   457   instanceKlassHandle nh = instanceKlassHandle(); // null Handle
   458   unsigned int d_hash = dictionary()->compute_hash(name, class_loader);
   459   int d_index = dictionary()->hash_to_index(d_hash);
   460   unsigned int p_hash = placeholders()->compute_hash(name, class_loader);
   461   int p_index = placeholders()->hash_to_index(p_hash);
   463   // superk is not used, resolve_super called for circularity check only
   464   // This code is reached in two situations. One if this thread
   465   // is loading the same class twice (e.g. ClassCircularity, or
   466   // java.lang.instrument).
   467   // The second is if another thread started the resolve_super first
   468   // and has not yet finished.
   469   // In both cases the original caller will clean up the placeholder
   470   // entry on error.
   471   klassOop superk = SystemDictionary::resolve_super_or_fail(name,
   472                                                           superclassname,
   473                                                           class_loader,
   474                                                           protection_domain,
   475                                                           true,
   476                                                           CHECK_(nh));
   477   // We don't redefine the class, so we just need to clean up if there
   478   // was not an error (don't want to modify any system dictionary
   479   // data structures).
   480   {
   481     MutexLocker mu(SystemDictionary_lock, THREAD);
   482     placeholders()->find_and_remove(p_index, p_hash, name, class_loader, THREAD);
   483     SystemDictionary_lock->notify_all();
   484   }
   486   // parallelCapable class loaders do NOT wait for parallel superclass loads to complete
   487   // Serial class loaders and bootstrap classloader do wait for superclass loads
   488  if (!class_loader.is_null() && is_parallelCapable(class_loader)) {
   489     MutexLocker mu(SystemDictionary_lock, THREAD);
   490     // Check if classloading completed while we were loading superclass or waiting
   491     klassOop check = find_class(d_index, d_hash, name, class_loader);
   492     if (check != NULL) {
   493       // Klass is already loaded, so just return it
   494       return(instanceKlassHandle(THREAD, check));
   495     } else {
   496       return nh;
   497     }
   498   }
   500   // must loop to both handle other placeholder updates
   501   // and spurious notifications
   502   bool super_load_in_progress = true;
   503   PlaceholderEntry* placeholder;
   504   while (super_load_in_progress) {
   505     MutexLocker mu(SystemDictionary_lock, THREAD);
   506     // Check if classloading completed while we were loading superclass or waiting
   507     klassOop check = find_class(d_index, d_hash, name, class_loader);
   508     if (check != NULL) {
   509       // Klass is already loaded, so just return it
   510       return(instanceKlassHandle(THREAD, check));
   511     } else {
   512       placeholder = placeholders()->get_entry(p_index, p_hash, name, class_loader);
   513       if (placeholder && placeholder->super_load_in_progress() ){
   514         // Before UnsyncloadClass:
   515         // We only get here if the application has released the
   516         // classloader lock when another thread was in the middle of loading a
   517         // superclass/superinterface for this class, and now
   518         // this thread is also trying to load this class.
   519         // To minimize surprises, the first thread that started to
   520         // load a class should be the one to complete the loading
   521         // with the classfile it initially expected.
   522         // This logic has the current thread wait once it has done
   523         // all the superclass/superinterface loading it can, until
   524         // the original thread completes the class loading or fails
   525         // If it completes we will use the resulting instanceKlass
   526         // which we will find below in the systemDictionary.
   527         // We also get here for parallel bootstrap classloader
   528         if (class_loader.is_null()) {
   529           SystemDictionary_lock->wait();
   530         } else {
   531           double_lock_wait(lockObject, THREAD);
   532         }
   533       } else {
   534         // If not in SD and not in PH, other thread's load must have failed
   535         super_load_in_progress = false;
   536       }
   537     }
   538   }
   539   return (nh);
   540 }
   543 klassOop SystemDictionary::resolve_instance_class_or_null(symbolHandle class_name, Handle class_loader, Handle protection_domain, TRAPS) {
   544   assert(class_name.not_null() && !FieldType::is_array(class_name()), "invalid class name");
   545   // First check to see if we should remove wrapping L and ;
   546   symbolHandle name;
   547   if (FieldType::is_obj(class_name())) {
   548     ResourceMark rm(THREAD);
   549     // Ignore wrapping L and ;.
   550     name = oopFactory::new_symbol_handle(class_name()->as_C_string() + 1, class_name()->utf8_length() - 2, CHECK_NULL);
   551   } else {
   552     name = class_name;
   553   }
   555   // UseNewReflection
   556   // Fix for 4474172; see evaluation for more details
   557   class_loader = Handle(THREAD, java_lang_ClassLoader::non_reflection_class_loader(class_loader()));
   559   // Do lookup to see if class already exist and the protection domain
   560   // has the right access
   561   unsigned int d_hash = dictionary()->compute_hash(name, class_loader);
   562   int d_index = dictionary()->hash_to_index(d_hash);
   563   klassOop probe = dictionary()->find(d_index, d_hash, name, class_loader,
   564                                       protection_domain, THREAD);
   565   if (probe != NULL) return probe;
   568   // Non-bootstrap class loaders will call out to class loader and
   569   // define via jvm/jni_DefineClass which will acquire the
   570   // class loader object lock to protect against multiple threads
   571   // defining the class in parallel by accident.
   572   // This lock must be acquired here so the waiter will find
   573   // any successful result in the SystemDictionary and not attempt
   574   // the define
   575   // ParallelCapable Classloaders and the bootstrap classloader,
   576   // or all classloaders with UnsyncloadClass do not acquire lock here
   577   bool DoObjectLock = true;
   578   if (is_parallelCapable(class_loader)) {
   579     DoObjectLock = false;
   580   }
   582   unsigned int p_hash = placeholders()->compute_hash(name, class_loader);
   583   int p_index = placeholders()->hash_to_index(p_hash);
   585   // Class is not in SystemDictionary so we have to do loading.
   586   // Make sure we are synchronized on the class loader before we proceed
   587   Handle lockObject = compute_loader_lock_object(class_loader, THREAD);
   588   check_loader_lock_contention(lockObject, THREAD);
   589   ObjectLocker ol(lockObject, THREAD, DoObjectLock);
   591   // Check again (after locking) if class already exist in SystemDictionary
   592   bool class_has_been_loaded   = false;
   593   bool super_load_in_progress  = false;
   594   bool havesupername = false;
   595   instanceKlassHandle k;
   596   PlaceholderEntry* placeholder;
   597   symbolHandle superclassname;
   599   {
   600     MutexLocker mu(SystemDictionary_lock, THREAD);
   601     klassOop check = find_class(d_index, d_hash, name, class_loader);
   602     if (check != NULL) {
   603       // Klass is already loaded, so just return it
   604       class_has_been_loaded = true;
   605       k = instanceKlassHandle(THREAD, check);
   606     } else {
   607       placeholder = placeholders()->get_entry(p_index, p_hash, name, class_loader);
   608       if (placeholder && placeholder->super_load_in_progress()) {
   609          super_load_in_progress = true;
   610          if (placeholder->havesupername() == true) {
   611            superclassname = symbolHandle(THREAD, placeholder->supername());
   612            havesupername = true;
   613          }
   614       }
   615     }
   616   }
   618   // If the class in is in the placeholder table, class loading is in progress
   619   if (super_load_in_progress && havesupername==true) {
   620     k = SystemDictionary::handle_parallel_super_load(name, superclassname,
   621         class_loader, protection_domain, lockObject, THREAD);
   622     if (HAS_PENDING_EXCEPTION) {
   623       return NULL;
   624     }
   625     if (!k.is_null()) {
   626       class_has_been_loaded = true;
   627     }
   628   }
   630   if (!class_has_been_loaded) {
   632     // add placeholder entry to record loading instance class
   633     // Five cases:
   634     // All cases need to prevent modifying bootclasssearchpath
   635     // in parallel with a classload of same classname
   636     // Redefineclasses uses existence of the placeholder for the duration
   637     // of the class load to prevent concurrent redefinition of not completely
   638     // defined classes.
   639     // case 1. traditional classloaders that rely on the classloader object lock
   640     //   - no other need for LOAD_INSTANCE
   641     // case 2. traditional classloaders that break the classloader object lock
   642     //    as a deadlock workaround. Detection of this case requires that
   643     //    this check is done while holding the classloader object lock,
   644     //    and that lock is still held when calling classloader's loadClass.
   645     //    For these classloaders, we ensure that the first requestor
   646     //    completes the load and other requestors wait for completion.
   647     // case 3. UnsyncloadClass - don't use objectLocker
   648     //    With this flag, we allow parallel classloading of a
   649     //    class/classloader pair
   650     // case4. Bootstrap classloader - don't own objectLocker
   651     //    This classloader supports parallelism at the classloader level,
   652     //    but only allows a single load of a class/classloader pair.
   653     //    No performance benefit and no deadlock issues.
   654     // case 5. parallelCapable user level classloaders - without objectLocker
   655     //    Allow parallel classloading of a class/classloader pair
   656     symbolHandle nullsymbolHandle;
   657     bool throw_circularity_error = false;
   658     {
   659       MutexLocker mu(SystemDictionary_lock, THREAD);
   660       if (class_loader.is_null() || !is_parallelCapable(class_loader)) {
   661         PlaceholderEntry* oldprobe = placeholders()->get_entry(p_index, p_hash, name, class_loader);
   662         if (oldprobe) {
   663           // only need check_seen_thread once, not on each loop
   664           // 6341374 java/lang/Instrument with -Xcomp
   665           if (oldprobe->check_seen_thread(THREAD, PlaceholderTable::LOAD_INSTANCE)) {
   666             throw_circularity_error = true;
   667           } else {
   668             // case 1: traditional: should never see load_in_progress.
   669             while (!class_has_been_loaded && oldprobe && oldprobe->instance_load_in_progress()) {
   671               // case 4: bootstrap classloader: prevent futile classloading,
   672               // wait on first requestor
   673               if (class_loader.is_null()) {
   674                 SystemDictionary_lock->wait();
   675               } else {
   676               // case 2: traditional with broken classloader lock. wait on first
   677               // requestor.
   678                 double_lock_wait(lockObject, THREAD);
   679               }
   680               // Check if classloading completed while we were waiting
   681               klassOop check = find_class(d_index, d_hash, name, class_loader);
   682               if (check != NULL) {
   683                 // Klass is already loaded, so just return it
   684                 k = instanceKlassHandle(THREAD, check);
   685                 class_has_been_loaded = true;
   686               }
   687               // check if other thread failed to load and cleaned up
   688               oldprobe = placeholders()->get_entry(p_index, p_hash, name, class_loader);
   689             }
   690           }
   691         }
   692       }
   693       // All cases: add LOAD_INSTANCE
   694       // case 3: UnsyncloadClass || case 5: parallelCapable: allow competing threads to try
   695       // LOAD_INSTANCE in parallel
   696       // add placeholder entry even if error - callers will remove on error
   697       if (!throw_circularity_error && !class_has_been_loaded) {
   698         PlaceholderEntry* newprobe = placeholders()->find_and_add(p_index, p_hash, name, class_loader, PlaceholderTable::LOAD_INSTANCE, nullsymbolHandle, THREAD);
   699         // For class loaders that do not acquire the classloader object lock,
   700         // if they did not catch another thread holding LOAD_INSTANCE,
   701         // need a check analogous to the acquire ObjectLocker/find_class
   702         // i.e. now that we hold the LOAD_INSTANCE token on loading this class/CL
   703         // one final check if the load has already completed
   704         // class loaders holding the ObjectLock shouldn't find the class here
   705         klassOop check = find_class(d_index, d_hash, name, class_loader);
   706         if (check != NULL) {
   707         // Klass is already loaded, so just return it
   708           k = instanceKlassHandle(THREAD, check);
   709           class_has_been_loaded = true;
   710           newprobe->remove_seen_thread(THREAD, PlaceholderTable::LOAD_INSTANCE);
   711           placeholders()->find_and_remove(p_index, p_hash, name, class_loader, THREAD);
   712           SystemDictionary_lock->notify_all();
   713         }
   714       }
   715     }
   716     // must throw error outside of owning lock
   717     if (throw_circularity_error) {
   718       ResourceMark rm(THREAD);
   719       THROW_MSG_0(vmSymbols::java_lang_ClassCircularityError(), name->as_C_string());
   720     }
   722     if (!class_has_been_loaded) {
   724       // Do actual loading
   725       k = load_instance_class(name, class_loader, THREAD);
   727       // For UnsyncloadClass and AllowParallelDefineClass only:
   728       // If they got a linkageError, check if a parallel class load succeeded.
   729       // If it did, then for bytecode resolution the specification requires
   730       // that we return the same result we did for the other thread, i.e. the
   731       // successfully loaded instanceKlass
   732       // Should not get here for classloaders that support parallelism
   733       // with the new cleaner mechanism
   734       // Bootstrap goes through here to allow for an extra guarantee check
   735       if (UnsyncloadClass || (class_loader.is_null())) {
   736         if (k.is_null() && HAS_PENDING_EXCEPTION
   737           && PENDING_EXCEPTION->is_a(SystemDictionary::linkageError_klass())) {
   738           MutexLocker mu(SystemDictionary_lock, THREAD);
   739           klassOop check = find_class(d_index, d_hash, name, class_loader);
   740           if (check != NULL) {
   741             // Klass is already loaded, so just use it
   742             k = instanceKlassHandle(THREAD, check);
   743             CLEAR_PENDING_EXCEPTION;
   744             guarantee((!class_loader.is_null()), "dup definition for bootstrap loader?");
   745           }
   746         }
   747       }
   749       // clean up placeholder entries for success or error
   750       // This cleans up LOAD_INSTANCE entries
   751       // It also cleans up LOAD_SUPER entries on errors from
   752       // calling load_instance_class
   753       {
   754         MutexLocker mu(SystemDictionary_lock, THREAD);
   755         PlaceholderEntry* probe = placeholders()->get_entry(p_index, p_hash, name, class_loader);
   756         if (probe != NULL) {
   757           probe->remove_seen_thread(THREAD, PlaceholderTable::LOAD_INSTANCE);
   758           placeholders()->find_and_remove(p_index, p_hash, name, class_loader, THREAD);
   759           SystemDictionary_lock->notify_all();
   760         }
   761       }
   763       // If everything was OK (no exceptions, no null return value), and
   764       // class_loader is NOT the defining loader, do a little more bookkeeping.
   765       if (!HAS_PENDING_EXCEPTION && !k.is_null() &&
   766         k->class_loader() != class_loader()) {
   768         check_constraints(d_index, d_hash, k, class_loader, false, THREAD);
   770         // Need to check for a PENDING_EXCEPTION again; check_constraints
   771         // can throw and doesn't use the CHECK macro.
   772         if (!HAS_PENDING_EXCEPTION) {
   773           { // Grabbing the Compile_lock prevents systemDictionary updates
   774             // during compilations.
   775             MutexLocker mu(Compile_lock, THREAD);
   776             update_dictionary(d_index, d_hash, p_index, p_hash,
   777                             k, class_loader, THREAD);
   778           }
   779           if (JvmtiExport::should_post_class_load()) {
   780             Thread *thread = THREAD;
   781             assert(thread->is_Java_thread(), "thread->is_Java_thread()");
   782             JvmtiExport::post_class_load((JavaThread *) thread, k());
   783           }
   784         }
   785       }
   786       if (HAS_PENDING_EXCEPTION || k.is_null()) {
   787         // On error, clean up placeholders
   788         {
   789           MutexLocker mu(SystemDictionary_lock, THREAD);
   790           placeholders()->find_and_remove(p_index, p_hash, name, class_loader, THREAD);
   791           SystemDictionary_lock->notify_all();
   792         }
   793         return NULL;
   794       }
   795     }
   796   }
   798 #ifdef ASSERT
   799   {
   800     Handle loader (THREAD, k->class_loader());
   801     MutexLocker mu(SystemDictionary_lock, THREAD);
   802     oop kk = find_class_or_placeholder(name, loader);
   803     assert(kk == k(), "should be present in dictionary");
   804   }
   805 #endif
   807   // return if the protection domain in NULL
   808   if (protection_domain() == NULL) return k();
   810   // Check the protection domain has the right access
   811   {
   812     MutexLocker mu(SystemDictionary_lock, THREAD);
   813     // Note that we have an entry, and entries can be deleted only during GC,
   814     // so we cannot allow GC to occur while we're holding this entry.
   815     // We're using a No_Safepoint_Verifier to catch any place where we
   816     // might potentially do a GC at all.
   817     // SystemDictionary::do_unloading() asserts that classes are only
   818     // unloaded at a safepoint.
   819     No_Safepoint_Verifier nosafepoint;
   820     if (dictionary()->is_valid_protection_domain(d_index, d_hash, name,
   821                                                  class_loader,
   822                                                  protection_domain)) {
   823       return k();
   824     }
   825   }
   827   // Verify protection domain. If it fails an exception is thrown
   828   validate_protection_domain(k, class_loader, protection_domain, CHECK_(klassOop(NULL)));
   830   return k();
   831 }
   834 // This routine does not lock the system dictionary.
   835 //
   836 // Since readers don't hold a lock, we must make sure that system
   837 // dictionary entries are only removed at a safepoint (when only one
   838 // thread is running), and are added to in a safe way (all links must
   839 // be updated in an MT-safe manner).
   840 //
   841 // Callers should be aware that an entry could be added just after
   842 // _dictionary->bucket(index) is read here, so the caller will not see
   843 // the new entry.
   845 klassOop SystemDictionary::find(symbolHandle class_name,
   846                                 Handle class_loader,
   847                                 Handle protection_domain,
   848                                 TRAPS) {
   850   // UseNewReflection
   851   // The result of this call should be consistent with the result
   852   // of the call to resolve_instance_class_or_null().
   853   // See evaluation 6790209 and 4474172 for more details.
   854   class_loader = Handle(THREAD, java_lang_ClassLoader::non_reflection_class_loader(class_loader()));
   856   unsigned int d_hash = dictionary()->compute_hash(class_name, class_loader);
   857   int d_index = dictionary()->hash_to_index(d_hash);
   859   {
   860     // Note that we have an entry, and entries can be deleted only during GC,
   861     // so we cannot allow GC to occur while we're holding this entry.
   862     // We're using a No_Safepoint_Verifier to catch any place where we
   863     // might potentially do a GC at all.
   864     // SystemDictionary::do_unloading() asserts that classes are only
   865     // unloaded at a safepoint.
   866     No_Safepoint_Verifier nosafepoint;
   867     return dictionary()->find(d_index, d_hash, class_name, class_loader,
   868                               protection_domain, THREAD);
   869   }
   870 }
   873 // Look for a loaded instance or array klass by name.  Do not do any loading.
   874 // return NULL in case of error.
   875 klassOop SystemDictionary::find_instance_or_array_klass(symbolHandle class_name,
   876                                                         Handle class_loader,
   877                                                         Handle protection_domain,
   878                                                         TRAPS) {
   879   klassOop k = NULL;
   880   assert(class_name() != NULL, "class name must be non NULL");
   882   // Try to get one of the well-known klasses.
   883   if (LinkWellKnownClasses) {
   884     k = find_well_known_klass(class_name());
   885     if (k != NULL) {
   886       return k;
   887     }
   888   }
   890   if (FieldType::is_array(class_name())) {
   891     // The name refers to an array.  Parse the name.
   892     jint dimension;
   893     symbolOop object_key;
   895     // dimension and object_key are assigned as a side-effect of this call
   896     BasicType t = FieldType::get_array_info(class_name(), &dimension,
   897                                             &object_key, CHECK_(NULL));
   898     if (t != T_OBJECT) {
   899       k = Universe::typeArrayKlassObj(t);
   900     } else {
   901       symbolHandle h_key(THREAD, object_key);
   902       k = SystemDictionary::find(h_key, class_loader, protection_domain, THREAD);
   903     }
   904     if (k != NULL) {
   905       k = Klass::cast(k)->array_klass_or_null(dimension);
   906     }
   907   } else {
   908     k = find(class_name, class_loader, protection_domain, THREAD);
   909   }
   910   return k;
   911 }
   913 // Quick range check for names of well-known classes:
   914 static symbolOop wk_klass_name_limits[2] = {NULL, NULL};
   916 #ifndef PRODUCT
   917 static int find_wkk_calls, find_wkk_probes, find_wkk_wins;
   918 // counts for "hello world": 3983, 1616, 1075
   919 //  => 60% hit after limit guard, 25% total win rate
   920 #endif
   922 klassOop SystemDictionary::find_well_known_klass(symbolOop class_name) {
   923   // A bounds-check on class_name will quickly get a negative result.
   924   NOT_PRODUCT(find_wkk_calls++);
   925   if (class_name >= wk_klass_name_limits[0] &&
   926       class_name <= wk_klass_name_limits[1]) {
   927     NOT_PRODUCT(find_wkk_probes++);
   928     vmSymbols::SID sid = vmSymbols::find_sid(class_name);
   929     if (sid != vmSymbols::NO_SID) {
   930       klassOop k = NULL;
   931       switch (sid) {
   932         #define WK_KLASS_CASE(name, symbol, ignore_option) \
   933         case vmSymbols::VM_SYMBOL_ENUM_NAME(symbol): \
   934           k = WK_KLASS(name); break;
   935         WK_KLASSES_DO(WK_KLASS_CASE)
   936         #undef WK_KLASS_CASE
   937       }
   938       NOT_PRODUCT(if (k != NULL)  find_wkk_wins++);
   939       return k;
   940     }
   941   }
   942   return NULL;
   943 }
   945 // Note: this method is much like resolve_from_stream, but
   946 // updates no supplemental data structures.
   947 // TODO consolidate the two methods with a helper routine?
   948 klassOop SystemDictionary::parse_stream(symbolHandle class_name,
   949                                         Handle class_loader,
   950                                         Handle protection_domain,
   951                                         ClassFileStream* st,
   952                                         KlassHandle host_klass,
   953                                         GrowableArray<Handle>* cp_patches,
   954                                         TRAPS) {
   955   symbolHandle parsed_name;
   957   // Parse the stream. Note that we do this even though this klass might
   958   // already be present in the SystemDictionary, otherwise we would not
   959   // throw potential ClassFormatErrors.
   960   //
   961   // Note: "name" is updated.
   962   // Further note:  a placeholder will be added for this class when
   963   //   super classes are loaded (resolve_super_or_fail). We expect this
   964   //   to be called for all classes but java.lang.Object; and we preload
   965   //   java.lang.Object through resolve_or_fail, not this path.
   967   instanceKlassHandle k = ClassFileParser(st).parseClassFile(class_name,
   968                                                              class_loader,
   969                                                              protection_domain,
   970                                                              host_klass,
   971                                                              cp_patches,
   972                                                              parsed_name,
   973                                                              true,
   974                                                              THREAD);
   977   // We don't redefine the class, so we just need to clean up whether there
   978   // was an error or not (don't want to modify any system dictionary
   979   // data structures).
   980   // Parsed name could be null if we threw an error before we got far
   981   // enough along to parse it -- in that case, there is nothing to clean up.
   982   if (!parsed_name.is_null()) {
   983     unsigned int p_hash = placeholders()->compute_hash(parsed_name,
   984                                                        class_loader);
   985     int p_index = placeholders()->hash_to_index(p_hash);
   986     {
   987     MutexLocker mu(SystemDictionary_lock, THREAD);
   988     placeholders()->find_and_remove(p_index, p_hash, parsed_name, class_loader, THREAD);
   989     SystemDictionary_lock->notify_all();
   990     }
   991   }
   993   if (host_klass.not_null() && k.not_null()) {
   994     assert(AnonymousClasses, "");
   995     // If it's anonymous, initialize it now, since nobody else will.
   996     k->set_host_klass(host_klass());
   998     {
   999       MutexLocker mu_r(Compile_lock, THREAD);
  1001       // Add to class hierarchy, initialize vtables, and do possible
  1002       // deoptimizations.
  1003       add_to_hierarchy(k, CHECK_NULL); // No exception, but can block
  1005       // But, do not add to system dictionary.
  1008     k->eager_initialize(THREAD);
  1010     // notify jvmti
  1011     if (JvmtiExport::should_post_class_load()) {
  1012         assert(THREAD->is_Java_thread(), "thread->is_Java_thread()");
  1013         JvmtiExport::post_class_load((JavaThread *) THREAD, k());
  1017   return k();
  1020 // Add a klass to the system from a stream (called by jni_DefineClass and
  1021 // JVM_DefineClass).
  1022 // Note: class_name can be NULL. In that case we do not know the name of
  1023 // the class until we have parsed the stream.
  1025 klassOop SystemDictionary::resolve_from_stream(symbolHandle class_name,
  1026                                                Handle class_loader,
  1027                                                Handle protection_domain,
  1028                                                ClassFileStream* st,
  1029                                                bool verify,
  1030                                                TRAPS) {
  1032   // Classloaders that support parallelism, e.g. bootstrap classloader,
  1033   // or all classloaders with UnsyncloadClass do not acquire lock here
  1034   bool DoObjectLock = true;
  1035   if (is_parallelCapable(class_loader)) {
  1036     DoObjectLock = false;
  1039   // Make sure we are synchronized on the class loader before we proceed
  1040   Handle lockObject = compute_loader_lock_object(class_loader, THREAD);
  1041   check_loader_lock_contention(lockObject, THREAD);
  1042   ObjectLocker ol(lockObject, THREAD, DoObjectLock);
  1044   symbolHandle parsed_name;
  1046   // Parse the stream. Note that we do this even though this klass might
  1047   // already be present in the SystemDictionary, otherwise we would not
  1048   // throw potential ClassFormatErrors.
  1049   //
  1050   // Note: "name" is updated.
  1051   // Further note:  a placeholder will be added for this class when
  1052   //   super classes are loaded (resolve_super_or_fail). We expect this
  1053   //   to be called for all classes but java.lang.Object; and we preload
  1054   //   java.lang.Object through resolve_or_fail, not this path.
  1056   instanceKlassHandle k = ClassFileParser(st).parseClassFile(class_name,
  1057                                                              class_loader,
  1058                                                              protection_domain,
  1059                                                              parsed_name,
  1060                                                              verify,
  1061                                                              THREAD);
  1063   const char* pkg = "java/";
  1064   if (!HAS_PENDING_EXCEPTION &&
  1065       !class_loader.is_null() &&
  1066       !parsed_name.is_null() &&
  1067       !strncmp((const char*)parsed_name->bytes(), pkg, strlen(pkg))) {
  1068     // It is illegal to define classes in the "java." package from
  1069     // JVM_DefineClass or jni_DefineClass unless you're the bootclassloader
  1070     ResourceMark rm(THREAD);
  1071     char* name = parsed_name->as_C_string();
  1072     char* index = strrchr(name, '/');
  1073     *index = '\0'; // chop to just the package name
  1074     while ((index = strchr(name, '/')) != NULL) {
  1075       *index = '.'; // replace '/' with '.' in package name
  1077     const char* fmt = "Prohibited package name: %s";
  1078     size_t len = strlen(fmt) + strlen(name);
  1079     char* message = NEW_RESOURCE_ARRAY(char, len);
  1080     jio_snprintf(message, len, fmt, name);
  1081     Exceptions::_throw_msg(THREAD_AND_LOCATION,
  1082       vmSymbols::java_lang_SecurityException(), message);
  1085   if (!HAS_PENDING_EXCEPTION) {
  1086     assert(!parsed_name.is_null(), "Sanity");
  1087     assert(class_name.is_null() || class_name() == parsed_name(),
  1088            "name mismatch");
  1089     // Verification prevents us from creating names with dots in them, this
  1090     // asserts that that's the case.
  1091     assert(is_internal_format(parsed_name),
  1092            "external class name format used internally");
  1094     // Add class just loaded
  1095     // If a class loader supports parallel classloading handle parallel define requests
  1096     // find_or_define_instance_class may return a different instanceKlass
  1097     if (is_parallelCapable(class_loader)) {
  1098       k = find_or_define_instance_class(class_name, class_loader, k, THREAD);
  1099     } else {
  1100       define_instance_class(k, THREAD);
  1104   // If parsing the class file or define_instance_class failed, we
  1105   // need to remove the placeholder added on our behalf. But we
  1106   // must make sure parsed_name is valid first (it won't be if we had
  1107   // a format error before the class was parsed far enough to
  1108   // find the name).
  1109   if (HAS_PENDING_EXCEPTION && !parsed_name.is_null()) {
  1110     unsigned int p_hash = placeholders()->compute_hash(parsed_name,
  1111                                                        class_loader);
  1112     int p_index = placeholders()->hash_to_index(p_hash);
  1114     MutexLocker mu(SystemDictionary_lock, THREAD);
  1115     placeholders()->find_and_remove(p_index, p_hash, parsed_name, class_loader, THREAD);
  1116     SystemDictionary_lock->notify_all();
  1118     return NULL;
  1121   // Make sure that we didn't leave a place holder in the
  1122   // SystemDictionary; this is only done on success
  1123   debug_only( {
  1124     if (!HAS_PENDING_EXCEPTION) {
  1125       assert(!parsed_name.is_null(), "parsed_name is still null?");
  1126       symbolHandle h_name   (THREAD, k->name());
  1127       Handle h_loader (THREAD, k->class_loader());
  1129       MutexLocker mu(SystemDictionary_lock, THREAD);
  1131       oop check = find_class_or_placeholder(parsed_name, class_loader);
  1132       assert(check == k(), "should be present in the dictionary");
  1134       oop check2 = find_class_or_placeholder(h_name, h_loader);
  1135       assert(check == check2, "name inconsistancy in SystemDictionary");
  1137   } );
  1139   return k();
  1143 void SystemDictionary::set_shared_dictionary(HashtableBucket* t, int length,
  1144                                              int number_of_entries) {
  1145   assert(length == _nof_buckets * sizeof(HashtableBucket),
  1146          "bad shared dictionary size.");
  1147   _shared_dictionary = new Dictionary(_nof_buckets, t, number_of_entries);
  1151 // If there is a shared dictionary, then find the entry for the
  1152 // given shared system class, if any.
  1154 klassOop SystemDictionary::find_shared_class(symbolHandle class_name) {
  1155   if (shared_dictionary() != NULL) {
  1156     unsigned int d_hash = dictionary()->compute_hash(class_name, Handle());
  1157     int d_index = dictionary()->hash_to_index(d_hash);
  1158     return shared_dictionary()->find_shared_class(d_index, d_hash, class_name);
  1159   } else {
  1160     return NULL;
  1165 // Load a class from the shared spaces (found through the shared system
  1166 // dictionary).  Force the superclass and all interfaces to be loaded.
  1167 // Update the class definition to include sibling classes and no
  1168 // subclasses (yet).  [Classes in the shared space are not part of the
  1169 // object hierarchy until loaded.]
  1171 instanceKlassHandle SystemDictionary::load_shared_class(
  1172                  symbolHandle class_name, Handle class_loader, TRAPS) {
  1173   instanceKlassHandle ik (THREAD, find_shared_class(class_name));
  1174   return load_shared_class(ik, class_loader, THREAD);
  1177 // Note well!  Changes to this method may affect oop access order
  1178 // in the shared archive.  Please take care to not make changes that
  1179 // adversely affect cold start time by changing the oop access order
  1180 // that is specified in dump.cpp MarkAndMoveOrderedReadOnly and
  1181 // MarkAndMoveOrderedReadWrite closures.
  1182 instanceKlassHandle SystemDictionary::load_shared_class(
  1183                  instanceKlassHandle ik, Handle class_loader, TRAPS) {
  1184   assert(class_loader.is_null(), "non-null classloader for shared class?");
  1185   if (ik.not_null()) {
  1186     instanceKlassHandle nh = instanceKlassHandle(); // null Handle
  1187     symbolHandle class_name(THREAD, ik->name());
  1189     // Found the class, now load the superclass and interfaces.  If they
  1190     // are shared, add them to the main system dictionary and reset
  1191     // their hierarchy references (supers, subs, and interfaces).
  1193     if (ik->super() != NULL) {
  1194       symbolHandle cn(THREAD, ik->super()->klass_part()->name());
  1195       resolve_super_or_fail(class_name, cn,
  1196                             class_loader, Handle(), true, CHECK_(nh));
  1199     objArrayHandle interfaces (THREAD, ik->local_interfaces());
  1200     int num_interfaces = interfaces->length();
  1201     for (int index = 0; index < num_interfaces; index++) {
  1202       klassOop k = klassOop(interfaces->obj_at(index));
  1204       // Note: can not use instanceKlass::cast here because
  1205       // interfaces' instanceKlass's C++ vtbls haven't been
  1206       // reinitialized yet (they will be once the interface classes
  1207       // are loaded)
  1208       symbolHandle name (THREAD, k->klass_part()->name());
  1209       resolve_super_or_fail(class_name, name, class_loader, Handle(), false, CHECK_(nh));
  1212     // Adjust methods to recover missing data.  They need addresses for
  1213     // interpreter entry points and their default native method address
  1214     // must be reset.
  1216     // Updating methods must be done under a lock so multiple
  1217     // threads don't update these in parallel
  1218     // Shared classes are all currently loaded by the bootstrap
  1219     // classloader, so this will never cause a deadlock on
  1220     // a custom class loader lock.
  1223       Handle lockObject = compute_loader_lock_object(class_loader, THREAD);
  1224       check_loader_lock_contention(lockObject, THREAD);
  1225       ObjectLocker ol(lockObject, THREAD, true);
  1227       objArrayHandle methods (THREAD, ik->methods());
  1228       int num_methods = methods->length();
  1229       for (int index2 = 0; index2 < num_methods; ++index2) {
  1230         methodHandle m(THREAD, methodOop(methods->obj_at(index2)));
  1231         m()->link_method(m, CHECK_(nh));
  1235     if (TraceClassLoading) {
  1236       ResourceMark rm;
  1237       tty->print("[Loaded %s", ik->external_name());
  1238       tty->print(" from shared objects file");
  1239       tty->print_cr("]");
  1241     // notify a class loaded from shared object
  1242     ClassLoadingService::notify_class_loaded(instanceKlass::cast(ik()),
  1243                                              true /* shared class */);
  1245   return ik;
  1248 #ifdef KERNEL
  1249 // Some classes on the bootstrap class path haven't been installed on the
  1250 // system yet.  Call the DownloadManager method to make them appear in the
  1251 // bootstrap class path and try again to load the named class.
  1252 // Note that with delegation class loaders all classes in another loader will
  1253 // first try to call this so it'd better be fast!!
  1254 static instanceKlassHandle download_and_retry_class_load(
  1255                                                     symbolHandle class_name,
  1256                                                     TRAPS) {
  1258   klassOop dlm = SystemDictionary::sun_jkernel_DownloadManager_klass();
  1259   instanceKlassHandle nk;
  1261   // If download manager class isn't loaded just return.
  1262   if (dlm == NULL) return nk;
  1264   { HandleMark hm(THREAD);
  1265     ResourceMark rm(THREAD);
  1266     Handle s = java_lang_String::create_from_symbol(class_name, CHECK_(nk));
  1267     Handle class_string = java_lang_String::externalize_classname(s, CHECK_(nk));
  1269     // return value
  1270     JavaValue result(T_OBJECT);
  1272     // Call the DownloadManager.  We assume that it has a lock because
  1273     // multiple classes could be not found and downloaded at the same time.
  1274     // class sun.misc.DownloadManager;
  1275     // public static String getBootClassPathEntryForClass(String className);
  1276     JavaCalls::call_static(&result,
  1277                        KlassHandle(THREAD, dlm),
  1278                        vmSymbolHandles::getBootClassPathEntryForClass_name(),
  1279                        vmSymbolHandles::string_string_signature(),
  1280                        class_string,
  1281                        CHECK_(nk));
  1283     // Get result.string and add to bootclasspath
  1284     assert(result.get_type() == T_OBJECT, "just checking");
  1285     oop obj = (oop) result.get_jobject();
  1286     if (obj == NULL) { return nk; }
  1288     Handle h_obj(THREAD, obj);
  1289     char* new_class_name = java_lang_String::as_platform_dependent_str(h_obj,
  1290                                                                   CHECK_(nk));
  1292     // lock the loader
  1293     // we use this lock because JVMTI does.
  1294     Handle loader_lock(THREAD, SystemDictionary::system_loader_lock());
  1296     ObjectLocker ol(loader_lock, THREAD);
  1297     // add the file to the bootclasspath
  1298     ClassLoader::update_class_path_entry_list(new_class_name, true);
  1299   } // end HandleMark
  1301   if (TraceClassLoading) {
  1302     ClassLoader::print_bootclasspath();
  1304   return ClassLoader::load_classfile(class_name, CHECK_(nk));
  1306 #endif // KERNEL
  1309 instanceKlassHandle SystemDictionary::load_instance_class(symbolHandle class_name, Handle class_loader, TRAPS) {
  1310   instanceKlassHandle nh = instanceKlassHandle(); // null Handle
  1311   if (class_loader.is_null()) {
  1313     // Search the shared system dictionary for classes preloaded into the
  1314     // shared spaces.
  1315     instanceKlassHandle k;
  1317       PerfTraceTime vmtimer(ClassLoader::perf_shared_classload_time());
  1318       k = load_shared_class(class_name, class_loader, THREAD);
  1321     if (k.is_null()) {
  1322       // Use VM class loader
  1323       PerfTraceTime vmtimer(ClassLoader::perf_sys_classload_time());
  1324       k = ClassLoader::load_classfile(class_name, CHECK_(nh));
  1327 #ifdef KERNEL
  1328     // If the VM class loader has failed to load the class, call the
  1329     // DownloadManager class to make it magically appear on the classpath
  1330     // and try again.  This is only configured with the Kernel VM.
  1331     if (k.is_null()) {
  1332       k = download_and_retry_class_load(class_name, CHECK_(nh));
  1334 #endif // KERNEL
  1336     // find_or_define_instance_class may return a different instanceKlass
  1337     if (!k.is_null()) {
  1338       k = find_or_define_instance_class(class_name, class_loader, k, CHECK_(nh));
  1340     return k;
  1341   } else {
  1342     // Use user specified class loader to load class. Call loadClass operation on class_loader.
  1343     ResourceMark rm(THREAD);
  1345     assert(THREAD->is_Java_thread(), "must be a JavaThread");
  1346     JavaThread* jt = (JavaThread*) THREAD;
  1348     PerfClassTraceTime vmtimer(ClassLoader::perf_app_classload_time(),
  1349                                ClassLoader::perf_app_classload_selftime(),
  1350                                ClassLoader::perf_app_classload_count(),
  1351                                jt->get_thread_stat()->perf_recursion_counts_addr(),
  1352                                jt->get_thread_stat()->perf_timers_addr(),
  1353                                PerfClassTraceTime::CLASS_LOAD);
  1355     Handle s = java_lang_String::create_from_symbol(class_name, CHECK_(nh));
  1356     // Translate to external class name format, i.e., convert '/' chars to '.'
  1357     Handle string = java_lang_String::externalize_classname(s, CHECK_(nh));
  1359     JavaValue result(T_OBJECT);
  1361     KlassHandle spec_klass (THREAD, SystemDictionary::classloader_klass());
  1363     // Call public unsynchronized loadClass(String) directly for all class loaders
  1364     // for parallelCapable class loaders. JDK >=7, loadClass(String, boolean) will
  1365     // acquire a class-name based lock rather than the class loader object lock.
  1366     // JDK < 7 already acquire the class loader lock in loadClass(String, boolean),
  1367     // so the call to loadClassInternal() was not required.
  1368     //
  1369     // UnsyncloadClass flag means both call loadClass(String) and do
  1370     // not acquire the class loader lock even for class loaders that are
  1371     // not parallelCapable. This was a risky transitional
  1372     // flag for diagnostic purposes only. It is risky to call
  1373     // custom class loaders without synchronization.
  1374     // WARNING If a custom class loader does NOT synchronizer findClass, or callers of
  1375     // findClass, the UnsyncloadClass flag risks unexpected timing bugs in the field.
  1376     // Do NOT assume this will be supported in future releases.
  1377     //
  1378     // Added MustCallLoadClassInternal in case we discover in the field
  1379     // a customer that counts on this call
  1380     if (MustCallLoadClassInternal && has_loadClassInternal()) {
  1381       JavaCalls::call_special(&result,
  1382                               class_loader,
  1383                               spec_klass,
  1384                               vmSymbolHandles::loadClassInternal_name(),
  1385                               vmSymbolHandles::string_class_signature(),
  1386                               string,
  1387                               CHECK_(nh));
  1388     } else {
  1389       JavaCalls::call_virtual(&result,
  1390                               class_loader,
  1391                               spec_klass,
  1392                               vmSymbolHandles::loadClass_name(),
  1393                               vmSymbolHandles::string_class_signature(),
  1394                               string,
  1395                               CHECK_(nh));
  1398     assert(result.get_type() == T_OBJECT, "just checking");
  1399     oop obj = (oop) result.get_jobject();
  1401     // Primitive classes return null since forName() can not be
  1402     // used to obtain any of the Class objects representing primitives or void
  1403     if ((obj != NULL) && !(java_lang_Class::is_primitive(obj))) {
  1404       instanceKlassHandle k =
  1405                 instanceKlassHandle(THREAD, java_lang_Class::as_klassOop(obj));
  1406       // For user defined Java class loaders, check that the name returned is
  1407       // the same as that requested.  This check is done for the bootstrap
  1408       // loader when parsing the class file.
  1409       if (class_name() == k->name()) {
  1410         return k;
  1413     // Class is not found or has the wrong name, return NULL
  1414     return nh;
  1418 void SystemDictionary::define_instance_class(instanceKlassHandle k, TRAPS) {
  1420   Handle class_loader_h(THREAD, k->class_loader());
  1422  // for bootstrap and other parallel classloaders don't acquire lock,
  1423  // use placeholder token
  1424  // If a parallelCapable class loader calls define_instance_class instead of
  1425  // find_or_define_instance_class to get here, we have a timing
  1426  // hole with systemDictionary updates and check_constraints
  1427  if (!class_loader_h.is_null() && !is_parallelCapable(class_loader_h)) {
  1428     assert(ObjectSynchronizer::current_thread_holds_lock((JavaThread*)THREAD,
  1429          compute_loader_lock_object(class_loader_h, THREAD)),
  1430          "define called without lock");
  1433   // Check class-loading constraints. Throw exception if violation is detected.
  1434   // Grabs and releases SystemDictionary_lock
  1435   // The check_constraints/find_class call and update_dictionary sequence
  1436   // must be "atomic" for a specific class/classloader pair so we never
  1437   // define two different instanceKlasses for that class/classloader pair.
  1438   // Existing classloaders will call define_instance_class with the
  1439   // classloader lock held
  1440   // Parallel classloaders will call find_or_define_instance_class
  1441   // which will require a token to perform the define class
  1442   symbolHandle name_h(THREAD, k->name());
  1443   unsigned int d_hash = dictionary()->compute_hash(name_h, class_loader_h);
  1444   int d_index = dictionary()->hash_to_index(d_hash);
  1445   check_constraints(d_index, d_hash, k, class_loader_h, true, CHECK);
  1447   // Register class just loaded with class loader (placed in Vector)
  1448   // Note we do this before updating the dictionary, as this can
  1449   // fail with an OutOfMemoryError (if it does, we will *not* put this
  1450   // class in the dictionary and will not update the class hierarchy).
  1451   if (k->class_loader() != NULL) {
  1452     methodHandle m(THREAD, Universe::loader_addClass_method());
  1453     JavaValue result(T_VOID);
  1454     JavaCallArguments args(class_loader_h);
  1455     args.push_oop(Handle(THREAD, k->java_mirror()));
  1456     JavaCalls::call(&result, m, &args, CHECK);
  1459   // Add the new class. We need recompile lock during update of CHA.
  1461     unsigned int p_hash = placeholders()->compute_hash(name_h, class_loader_h);
  1462     int p_index = placeholders()->hash_to_index(p_hash);
  1464     MutexLocker mu_r(Compile_lock, THREAD);
  1466     // Add to class hierarchy, initialize vtables, and do possible
  1467     // deoptimizations.
  1468     add_to_hierarchy(k, CHECK); // No exception, but can block
  1470     // Add to systemDictionary - so other classes can see it.
  1471     // Grabs and releases SystemDictionary_lock
  1472     update_dictionary(d_index, d_hash, p_index, p_hash,
  1473                       k, class_loader_h, THREAD);
  1475   k->eager_initialize(THREAD);
  1477   // notify jvmti
  1478   if (JvmtiExport::should_post_class_load()) {
  1479       assert(THREAD->is_Java_thread(), "thread->is_Java_thread()");
  1480       JvmtiExport::post_class_load((JavaThread *) THREAD, k());
  1485 // Support parallel classloading
  1486 // Initial implementation for bootstrap classloader
  1487 // For custom class loaders that support parallel classloading,
  1488 // With AllowParallelDefine flag==true, in case they do not synchronize around
  1489 // FindLoadedClass/DefineClass, calls, we check for parallel
  1490 // loading for them, wait if a defineClass is in progress
  1491 // and return the initial requestor's results
  1492 // With AllowParallelDefine flag==false, call through to define_instance_class
  1493 // which will throw LinkageError: duplicate class definition.
  1494 // For better performance, the class loaders should synchronize
  1495 // findClass(), i.e. FindLoadedClass/DefineClassIfAbsent or they
  1496 // potentially waste time reading and parsing the bytestream.
  1497 // Note: VM callers should ensure consistency of k/class_name,class_loader
  1498 instanceKlassHandle SystemDictionary::find_or_define_instance_class(symbolHandle class_name, Handle class_loader, instanceKlassHandle k, TRAPS) {
  1500   instanceKlassHandle nh = instanceKlassHandle(); // null Handle
  1501   symbolHandle name_h(THREAD, k->name()); // passed in class_name may be null
  1503   unsigned int d_hash = dictionary()->compute_hash(name_h, class_loader);
  1504   int d_index = dictionary()->hash_to_index(d_hash);
  1506 // Hold SD lock around find_class and placeholder creation for DEFINE_CLASS
  1507   unsigned int p_hash = placeholders()->compute_hash(name_h, class_loader);
  1508   int p_index = placeholders()->hash_to_index(p_hash);
  1509   PlaceholderEntry* probe;
  1512     MutexLocker mu(SystemDictionary_lock, THREAD);
  1513     // First check if class already defined
  1514     klassOop check = find_class(d_index, d_hash, name_h, class_loader);
  1515     if (check != NULL) {
  1516       return(instanceKlassHandle(THREAD, check));
  1519     // Acquire define token for this class/classloader
  1520     symbolHandle nullsymbolHandle;
  1521     probe = placeholders()->find_and_add(p_index, p_hash, name_h, class_loader, PlaceholderTable::DEFINE_CLASS, nullsymbolHandle, THREAD);
  1522     // Wait if another thread defining in parallel
  1523     // All threads wait - even those that will throw duplicate class: otherwise
  1524     // caller is surprised by LinkageError: duplicate, but findLoadedClass fails
  1525     // if other thread has not finished updating dictionary
  1526     while (probe->definer() != NULL) {
  1527       SystemDictionary_lock->wait();
  1529     // Only special cases allow parallel defines and can use other thread's results
  1530     // Other cases fall through, and may run into duplicate defines
  1531     // caught by finding an entry in the SystemDictionary
  1532     if ((UnsyncloadClass || AllowParallelDefineClass) && (probe->instanceKlass() != NULL)) {
  1533         probe->remove_seen_thread(THREAD, PlaceholderTable::DEFINE_CLASS);
  1534         placeholders()->find_and_remove(p_index, p_hash, name_h, class_loader, THREAD);
  1535         SystemDictionary_lock->notify_all();
  1536 #ifdef ASSERT
  1537         klassOop check = find_class(d_index, d_hash, name_h, class_loader);
  1538         assert(check != NULL, "definer missed recording success");
  1539 #endif
  1540         return(instanceKlassHandle(THREAD, probe->instanceKlass()));
  1541     } else {
  1542       // This thread will define the class (even if earlier thread tried and had an error)
  1543       probe->set_definer(THREAD);
  1547   define_instance_class(k, THREAD);
  1549   Handle linkage_exception = Handle(); // null handle
  1551   // definer must notify any waiting threads
  1553     MutexLocker mu(SystemDictionary_lock, THREAD);
  1554     PlaceholderEntry* probe = placeholders()->get_entry(p_index, p_hash, name_h, class_loader);
  1555     assert(probe != NULL, "DEFINE_CLASS placeholder lost?");
  1556     if (probe != NULL) {
  1557       if (HAS_PENDING_EXCEPTION) {
  1558         linkage_exception = Handle(THREAD,PENDING_EXCEPTION);
  1559         CLEAR_PENDING_EXCEPTION;
  1560       } else {
  1561         probe->set_instanceKlass(k());
  1563       probe->set_definer(NULL);
  1564       probe->remove_seen_thread(THREAD, PlaceholderTable::DEFINE_CLASS);
  1565       placeholders()->find_and_remove(p_index, p_hash, name_h, class_loader, THREAD);
  1566       SystemDictionary_lock->notify_all();
  1570   // Can't throw exception while holding lock due to rank ordering
  1571   if (linkage_exception() != NULL) {
  1572     THROW_OOP_(linkage_exception(), nh); // throws exception and returns
  1575   return k;
  1577 Handle SystemDictionary::compute_loader_lock_object(Handle class_loader, TRAPS) {
  1578   // If class_loader is NULL we synchronize on _system_loader_lock_obj
  1579   if (class_loader.is_null()) {
  1580     return Handle(THREAD, _system_loader_lock_obj);
  1581   } else {
  1582     return class_loader;
  1586 // This method is added to check how often we have to wait to grab loader
  1587 // lock. The results are being recorded in the performance counters defined in
  1588 // ClassLoader::_sync_systemLoaderLockContentionRate and
  1589 // ClassLoader::_sync_nonSystemLoaderLockConteionRate.
  1590 void SystemDictionary::check_loader_lock_contention(Handle loader_lock, TRAPS) {
  1591   if (!UsePerfData) {
  1592     return;
  1595   assert(!loader_lock.is_null(), "NULL lock object");
  1597   if (ObjectSynchronizer::query_lock_ownership((JavaThread*)THREAD, loader_lock)
  1598       == ObjectSynchronizer::owner_other) {
  1599     // contention will likely happen, so increment the corresponding
  1600     // contention counter.
  1601     if (loader_lock() == _system_loader_lock_obj) {
  1602       ClassLoader::sync_systemLoaderLockContentionRate()->inc();
  1603     } else {
  1604       ClassLoader::sync_nonSystemLoaderLockContentionRate()->inc();
  1609 // ----------------------------------------------------------------------------
  1610 // Lookup
  1612 klassOop SystemDictionary::find_class(int index, unsigned int hash,
  1613                                       symbolHandle class_name,
  1614                                       Handle class_loader) {
  1615   assert_locked_or_safepoint(SystemDictionary_lock);
  1616   assert (index == dictionary()->index_for(class_name, class_loader),
  1617           "incorrect index?");
  1619   klassOop k = dictionary()->find_class(index, hash, class_name, class_loader);
  1620   return k;
  1624 // Basic find on classes in the midst of being loaded
  1625 symbolOop SystemDictionary::find_placeholder(int index, unsigned int hash,
  1626                                              symbolHandle class_name,
  1627                                              Handle class_loader) {
  1628   assert_locked_or_safepoint(SystemDictionary_lock);
  1630   return placeholders()->find_entry(index, hash, class_name, class_loader);
  1634 // Used for assertions and verification only
  1635 oop SystemDictionary::find_class_or_placeholder(symbolHandle class_name,
  1636                                                 Handle class_loader) {
  1637   #ifndef ASSERT
  1638   guarantee(VerifyBeforeGC   ||
  1639             VerifyDuringGC   ||
  1640             VerifyBeforeExit ||
  1641             VerifyAfterGC, "too expensive");
  1642   #endif
  1643   assert_locked_or_safepoint(SystemDictionary_lock);
  1644   symbolOop class_name_ = class_name();
  1645   oop class_loader_ = class_loader();
  1647   // First look in the loaded class array
  1648   unsigned int d_hash = dictionary()->compute_hash(class_name, class_loader);
  1649   int d_index = dictionary()->hash_to_index(d_hash);
  1650   oop lookup = find_class(d_index, d_hash, class_name, class_loader);
  1652   if (lookup == NULL) {
  1653     // Next try the placeholders
  1654     unsigned int p_hash = placeholders()->compute_hash(class_name,class_loader);
  1655     int p_index = placeholders()->hash_to_index(p_hash);
  1656     lookup = find_placeholder(p_index, p_hash, class_name, class_loader);
  1659   return lookup;
  1663 // Get the next class in the diictionary.
  1664 klassOop SystemDictionary::try_get_next_class() {
  1665   return dictionary()->try_get_next_class();
  1669 // ----------------------------------------------------------------------------
  1670 // Update hierachy. This is done before the new klass has been added to the SystemDictionary. The Recompile_lock
  1671 // is held, to ensure that the compiler is not using the class hierachy, and that deoptimization will kick in
  1672 // before a new class is used.
  1674 void SystemDictionary::add_to_hierarchy(instanceKlassHandle k, TRAPS) {
  1675   assert(k.not_null(), "just checking");
  1676   // Link into hierachy. Make sure the vtables are initialized before linking into
  1677   k->append_to_sibling_list();                    // add to superklass/sibling list
  1678   k->process_interfaces(THREAD);                  // handle all "implements" declarations
  1679   k->set_init_state(instanceKlass::loaded);
  1680   // Now flush all code that depended on old class hierarchy.
  1681   // Note: must be done *after* linking k into the hierarchy (was bug 12/9/97)
  1682   // Also, first reinitialize vtable because it may have gotten out of synch
  1683   // while the new class wasn't connected to the class hierarchy.
  1684   Universe::flush_dependents_on(k);
  1688 // ----------------------------------------------------------------------------
  1689 // GC support
  1691 // Following roots during mark-sweep is separated in two phases.
  1692 //
  1693 // The first phase follows preloaded classes and all other system
  1694 // classes, since these will never get unloaded anyway.
  1695 //
  1696 // The second phase removes (unloads) unreachable classes from the
  1697 // system dictionary and follows the remaining classes' contents.
  1699 void SystemDictionary::always_strong_oops_do(OopClosure* blk) {
  1700   // Follow preloaded classes/mirrors and system loader object
  1701   blk->do_oop(&_java_system_loader);
  1702   preloaded_oops_do(blk);
  1703   always_strong_classes_do(blk);
  1707 void SystemDictionary::always_strong_classes_do(OopClosure* blk) {
  1708   // Follow all system classes and temporary placeholders in dictionary
  1709   dictionary()->always_strong_classes_do(blk);
  1711   // Placeholders. These are *always* strong roots, as they
  1712   // represent classes we're actively loading.
  1713   placeholders_do(blk);
  1715   // Visit extra methods
  1716   if (invoke_method_table() != NULL)
  1717     invoke_method_table()->oops_do(blk);
  1719   // Loader constraints. We must keep the symbolOop used in the name alive.
  1720   constraints()->always_strong_classes_do(blk);
  1722   // Resolution errors keep the symbolOop for the error alive
  1723   resolution_errors()->always_strong_classes_do(blk);
  1727 void SystemDictionary::placeholders_do(OopClosure* blk) {
  1728   placeholders()->oops_do(blk);
  1732 bool SystemDictionary::do_unloading(BoolObjectClosure* is_alive) {
  1733   bool result = dictionary()->do_unloading(is_alive);
  1734   constraints()->purge_loader_constraints(is_alive);
  1735   resolution_errors()->purge_resolution_errors(is_alive);
  1736   return result;
  1740 // The mirrors are scanned by shared_oops_do() which is
  1741 // not called by oops_do().  In order to process oops in
  1742 // a necessary order, shared_oops_do() is call by
  1743 // Universe::oops_do().
  1744 void SystemDictionary::oops_do(OopClosure* f) {
  1745   // Adjust preloaded classes and system loader object
  1746   f->do_oop(&_java_system_loader);
  1747   preloaded_oops_do(f);
  1749   lazily_loaded_oops_do(f);
  1751   // Adjust dictionary
  1752   dictionary()->oops_do(f);
  1754   // Visit extra methods
  1755   if (invoke_method_table() != NULL)
  1756     invoke_method_table()->oops_do(f);
  1758   // Partially loaded classes
  1759   placeholders()->oops_do(f);
  1761   // Adjust constraint table
  1762   constraints()->oops_do(f);
  1764   // Adjust resolution error table
  1765   resolution_errors()->oops_do(f);
  1769 void SystemDictionary::preloaded_oops_do(OopClosure* f) {
  1770   f->do_oop((oop*) &wk_klass_name_limits[0]);
  1771   f->do_oop((oop*) &wk_klass_name_limits[1]);
  1773   for (int k = (int)FIRST_WKID; k < (int)WKID_LIMIT; k++) {
  1774     f->do_oop((oop*) &_well_known_klasses[k]);
  1778     for (int i = 0; i < T_VOID+1; i++) {
  1779       if (_box_klasses[i] != NULL) {
  1780         assert(i >= T_BOOLEAN, "checking");
  1781         f->do_oop((oop*) &_box_klasses[i]);
  1786   // The basic type mirrors would have already been processed in
  1787   // Universe::oops_do(), via a call to shared_oops_do(), so should
  1788   // not be processed again.
  1790   f->do_oop((oop*) &_system_loader_lock_obj);
  1791   FilteredFieldsMap::klasses_oops_do(f);
  1794 void SystemDictionary::lazily_loaded_oops_do(OopClosure* f) {
  1795   f->do_oop((oop*) &_abstract_ownable_synchronizer_klass);
  1798 // Just the classes from defining class loaders
  1799 // Don't iterate over placeholders
  1800 void SystemDictionary::classes_do(void f(klassOop)) {
  1801   dictionary()->classes_do(f);
  1804 // Added for initialize_itable_for_klass
  1805 //   Just the classes from defining class loaders
  1806 // Don't iterate over placeholders
  1807 void SystemDictionary::classes_do(void f(klassOop, TRAPS), TRAPS) {
  1808   dictionary()->classes_do(f, CHECK);
  1811 //   All classes, and their class loaders
  1812 // Don't iterate over placeholders
  1813 void SystemDictionary::classes_do(void f(klassOop, oop)) {
  1814   dictionary()->classes_do(f);
  1817 //   All classes, and their class loaders
  1818 //   (added for helpers that use HandleMarks and ResourceMarks)
  1819 // Don't iterate over placeholders
  1820 void SystemDictionary::classes_do(void f(klassOop, oop, TRAPS), TRAPS) {
  1821   dictionary()->classes_do(f, CHECK);
  1824 void SystemDictionary::placeholders_do(void f(symbolOop, oop)) {
  1825   placeholders()->entries_do(f);
  1828 void SystemDictionary::methods_do(void f(methodOop)) {
  1829   dictionary()->methods_do(f);
  1830   if (invoke_method_table() != NULL)
  1831     invoke_method_table()->methods_do(f);
  1834 // ----------------------------------------------------------------------------
  1835 // Lazily load klasses
  1837 void SystemDictionary::load_abstract_ownable_synchronizer_klass(TRAPS) {
  1838   assert(JDK_Version::is_gte_jdk16x_version(), "Must be JDK 1.6 or later");
  1840   // if multiple threads calling this function, only one thread will load
  1841   // the class.  The other threads will find the loaded version once the
  1842   // class is loaded.
  1843   klassOop aos = _abstract_ownable_synchronizer_klass;
  1844   if (aos == NULL) {
  1845     klassOop k = resolve_or_fail(vmSymbolHandles::java_util_concurrent_locks_AbstractOwnableSynchronizer(), true, CHECK);
  1846     // Force a fence to prevent any read before the write completes
  1847     OrderAccess::fence();
  1848     _abstract_ownable_synchronizer_klass = k;
  1852 // ----------------------------------------------------------------------------
  1853 // Initialization
  1855 void SystemDictionary::initialize(TRAPS) {
  1856   // Allocate arrays
  1857   assert(dictionary() == NULL,
  1858          "SystemDictionary should only be initialized once");
  1859   _dictionary = new Dictionary(_nof_buckets);
  1860   _placeholders = new PlaceholderTable(_nof_buckets);
  1861   _number_of_modifications = 0;
  1862   _loader_constraints = new LoaderConstraintTable(_loader_constraint_size);
  1863   _resolution_errors = new ResolutionErrorTable(_resolution_error_size);
  1864   // _invoke_method_table is allocated lazily in find_method_handle_invoke()
  1866   // Allocate private object used as system class loader lock
  1867   _system_loader_lock_obj = oopFactory::new_system_objArray(0, CHECK);
  1868   // Initialize basic classes
  1869   initialize_preloaded_classes(CHECK);
  1872 // Compact table of directions on the initialization of klasses:
  1873 static const short wk_init_info[] = {
  1874   #define WK_KLASS_INIT_INFO(name, symbol, option) \
  1875     ( ((int)vmSymbols::VM_SYMBOL_ENUM_NAME(symbol) \
  1876           << SystemDictionary::CEIL_LG_OPTION_LIMIT) \
  1877       | (int)SystemDictionary::option ),
  1878   WK_KLASSES_DO(WK_KLASS_INIT_INFO)
  1879   #undef WK_KLASS_INIT_INFO
  1881 };
  1883 bool SystemDictionary::initialize_wk_klass(WKID id, int init_opt, TRAPS) {
  1884   assert(id >= (int)FIRST_WKID && id < (int)WKID_LIMIT, "oob");
  1885   int  info = wk_init_info[id - FIRST_WKID];
  1886   int  sid  = (info >> CEIL_LG_OPTION_LIMIT);
  1887   symbolHandle symbol = vmSymbolHandles::symbol_handle_at((vmSymbols::SID)sid);
  1888   klassOop*    klassp = &_well_known_klasses[id];
  1889   bool must_load = (init_opt < SystemDictionary::Opt);
  1890   bool try_load  = true;
  1891   if (init_opt == SystemDictionary::Opt_Kernel) {
  1892 #ifndef KERNEL
  1893     try_load = false;
  1894 #endif //KERNEL
  1896   if ((*klassp) == NULL && try_load) {
  1897     if (must_load) {
  1898       (*klassp) = resolve_or_fail(symbol, true, CHECK_0); // load required class
  1899     } else {
  1900       (*klassp) = resolve_or_null(symbol,       CHECK_0); // load optional klass
  1903   return ((*klassp) != NULL);
  1906 void SystemDictionary::initialize_wk_klasses_until(WKID limit_id, WKID &start_id, TRAPS) {
  1907   assert((int)start_id <= (int)limit_id, "IDs are out of order!");
  1908   for (int id = (int)start_id; id < (int)limit_id; id++) {
  1909     assert(id >= (int)FIRST_WKID && id < (int)WKID_LIMIT, "oob");
  1910     int info = wk_init_info[id - FIRST_WKID];
  1911     int sid  = (info >> CEIL_LG_OPTION_LIMIT);
  1912     int opt  = (info & right_n_bits(CEIL_LG_OPTION_LIMIT));
  1914     initialize_wk_klass((WKID)id, opt, CHECK);
  1916     // Update limits, so find_well_known_klass can be very fast:
  1917     symbolOop s = vmSymbols::symbol_at((vmSymbols::SID)sid);
  1918     if (wk_klass_name_limits[1] == NULL) {
  1919       wk_klass_name_limits[0] = wk_klass_name_limits[1] = s;
  1920     } else if (wk_klass_name_limits[1] < s) {
  1921       wk_klass_name_limits[1] = s;
  1922     } else if (wk_klass_name_limits[0] > s) {
  1923       wk_klass_name_limits[0] = s;
  1927   // move the starting value forward to the limit:
  1928   start_id = limit_id;
  1932 void SystemDictionary::initialize_preloaded_classes(TRAPS) {
  1933   assert(WK_KLASS(object_klass) == NULL, "preloaded classes should only be initialized once");
  1934   // Preload commonly used klasses
  1935   WKID scan = FIRST_WKID;
  1936   // first do Object, String, Class
  1937   initialize_wk_klasses_through(WK_KLASS_ENUM_NAME(class_klass), scan, CHECK);
  1939   debug_only(instanceKlass::verify_class_klass_nonstatic_oop_maps(WK_KLASS(class_klass)));
  1941   // Fixup mirrors for classes loaded before java.lang.Class.
  1942   // These calls iterate over the objects currently in the perm gen
  1943   // so calling them at this point is matters (not before when there
  1944   // are fewer objects and not later after there are more objects
  1945   // in the perm gen.
  1946   Universe::initialize_basic_type_mirrors(CHECK);
  1947   Universe::fixup_mirrors(CHECK);
  1949   // do a bunch more:
  1950   initialize_wk_klasses_through(WK_KLASS_ENUM_NAME(reference_klass), scan, CHECK);
  1952   // Preload ref klasses and set reference types
  1953   instanceKlass::cast(WK_KLASS(reference_klass))->set_reference_type(REF_OTHER);
  1954   instanceRefKlass::update_nonstatic_oop_maps(WK_KLASS(reference_klass));
  1956   initialize_wk_klasses_through(WK_KLASS_ENUM_NAME(phantom_reference_klass), scan, CHECK);
  1957   instanceKlass::cast(WK_KLASS(soft_reference_klass))->set_reference_type(REF_SOFT);
  1958   instanceKlass::cast(WK_KLASS(weak_reference_klass))->set_reference_type(REF_WEAK);
  1959   instanceKlass::cast(WK_KLASS(final_reference_klass))->set_reference_type(REF_FINAL);
  1960   instanceKlass::cast(WK_KLASS(phantom_reference_klass))->set_reference_type(REF_PHANTOM);
  1962   WKID meth_group_start = WK_KLASS_ENUM_NAME(MethodHandle_klass);
  1963   WKID meth_group_end   = WK_KLASS_ENUM_NAME(WrongMethodTypeException_klass);
  1964   initialize_wk_klasses_until(meth_group_start, scan, CHECK);
  1965   if (EnableMethodHandles) {
  1966     initialize_wk_klasses_through(meth_group_start, scan, CHECK);
  1968   if (_well_known_klasses[meth_group_start] == NULL) {
  1969     // Skip the rest of the method handle classes, if MethodHandle is not loaded.
  1970     scan = WKID(meth_group_end+1);
  1972   WKID indy_group_start = WK_KLASS_ENUM_NAME(Linkage_klass);
  1973   WKID indy_group_end   = WK_KLASS_ENUM_NAME(Dynamic_klass);
  1974   initialize_wk_klasses_until(indy_group_start, scan, CHECK);
  1975   if (EnableInvokeDynamic) {
  1976     initialize_wk_klasses_through(indy_group_start, scan, CHECK);
  1978   if (_well_known_klasses[indy_group_start] == NULL) {
  1979     // Skip the rest of the dynamic typing classes, if Linkage is not loaded.
  1980     scan = WKID(indy_group_end+1);
  1983   initialize_wk_klasses_until(WKID_LIMIT, scan, CHECK);
  1985   _box_klasses[T_BOOLEAN] = WK_KLASS(boolean_klass);
  1986   _box_klasses[T_CHAR]    = WK_KLASS(char_klass);
  1987   _box_klasses[T_FLOAT]   = WK_KLASS(float_klass);
  1988   _box_klasses[T_DOUBLE]  = WK_KLASS(double_klass);
  1989   _box_klasses[T_BYTE]    = WK_KLASS(byte_klass);
  1990   _box_klasses[T_SHORT]   = WK_KLASS(short_klass);
  1991   _box_klasses[T_INT]     = WK_KLASS(int_klass);
  1992   _box_klasses[T_LONG]    = WK_KLASS(long_klass);
  1993   //_box_klasses[T_OBJECT]  = WK_KLASS(object_klass);
  1994   //_box_klasses[T_ARRAY]   = WK_KLASS(object_klass);
  1996 #ifdef KERNEL
  1997   if (sun_jkernel_DownloadManager_klass() == NULL) {
  1998     warning("Cannot find sun/jkernel/DownloadManager");
  2000 #endif // KERNEL
  2002   { // Compute whether we should use loadClass or loadClassInternal when loading classes.
  2003     methodOop method = instanceKlass::cast(classloader_klass())->find_method(vmSymbols::loadClassInternal_name(), vmSymbols::string_class_signature());
  2004     _has_loadClassInternal = (method != NULL);
  2006   { // Compute whether we should use checkPackageAccess or NOT
  2007     methodOop method = instanceKlass::cast(classloader_klass())->find_method(vmSymbols::checkPackageAccess_name(), vmSymbols::class_protectiondomain_signature());
  2008     _has_checkPackageAccess = (method != NULL);
  2012 // Tells if a given klass is a box (wrapper class, such as java.lang.Integer).
  2013 // If so, returns the basic type it holds.  If not, returns T_OBJECT.
  2014 BasicType SystemDictionary::box_klass_type(klassOop k) {
  2015   assert(k != NULL, "");
  2016   for (int i = T_BOOLEAN; i < T_VOID+1; i++) {
  2017     if (_box_klasses[i] == k)
  2018       return (BasicType)i;
  2020   return T_OBJECT;
  2023 KlassHandle SystemDictionaryHandles::box_klass(BasicType t) {
  2024   if (t >= T_BOOLEAN && t <= T_VOID)
  2025     return KlassHandle(&SystemDictionary::_box_klasses[t], true);
  2026   else
  2027     return KlassHandle();
  2030 // Constraints on class loaders. The details of the algorithm can be
  2031 // found in the OOPSLA'98 paper "Dynamic Class Loading in the Java
  2032 // Virtual Machine" by Sheng Liang and Gilad Bracha.  The basic idea is
  2033 // that the system dictionary needs to maintain a set of contraints that
  2034 // must be satisfied by all classes in the dictionary.
  2035 // if defining is true, then LinkageError if already in systemDictionary
  2036 // if initiating loader, then ok if instanceKlass matches existing entry
  2038 void SystemDictionary::check_constraints(int d_index, unsigned int d_hash,
  2039                                          instanceKlassHandle k,
  2040                                          Handle class_loader, bool defining,
  2041                                          TRAPS) {
  2042   const char *linkage_error = NULL;
  2044     symbolHandle name (THREAD, k->name());
  2045     MutexLocker mu(SystemDictionary_lock, THREAD);
  2047     klassOop check = find_class(d_index, d_hash, name, class_loader);
  2048     if (check != (klassOop)NULL) {
  2049       // if different instanceKlass - duplicate class definition,
  2050       // else - ok, class loaded by a different thread in parallel,
  2051       // we should only have found it if it was done loading and ok to use
  2052       // system dictionary only holds instance classes, placeholders
  2053       // also holds array classes
  2055       assert(check->klass_part()->oop_is_instance(), "noninstance in systemdictionary");
  2056       if ((defining == true) || (k() != check)) {
  2057         linkage_error = "loader (instance of  %s): attempted  duplicate class "
  2058           "definition for name: \"%s\"";
  2059       } else {
  2060         return;
  2064 #ifdef ASSERT
  2065     unsigned int p_hash = placeholders()->compute_hash(name, class_loader);
  2066     int p_index = placeholders()->hash_to_index(p_hash);
  2067     symbolOop ph_check = find_placeholder(p_index, p_hash, name, class_loader);
  2068     assert(ph_check == NULL || ph_check == name(), "invalid symbol");
  2069 #endif
  2071     if (linkage_error == NULL) {
  2072       if (constraints()->check_or_update(k, class_loader, name) == false) {
  2073         linkage_error = "loader constraint violation: loader (instance of %s)"
  2074           " previously initiated loading for a different type with name \"%s\"";
  2079   // Throw error now if needed (cannot throw while holding
  2080   // SystemDictionary_lock because of rank ordering)
  2082   if (linkage_error) {
  2083     ResourceMark rm(THREAD);
  2084     const char* class_loader_name = loader_name(class_loader());
  2085     char* type_name = k->name()->as_C_string();
  2086     size_t buflen = strlen(linkage_error) + strlen(class_loader_name) +
  2087       strlen(type_name);
  2088     char* buf = NEW_RESOURCE_ARRAY_IN_THREAD(THREAD, char, buflen);
  2089     jio_snprintf(buf, buflen, linkage_error, class_loader_name, type_name);
  2090     THROW_MSG(vmSymbols::java_lang_LinkageError(), buf);
  2095 // Update system dictionary - done after check_constraint and add_to_hierachy
  2096 // have been called.
  2097 void SystemDictionary::update_dictionary(int d_index, unsigned int d_hash,
  2098                                          int p_index, unsigned int p_hash,
  2099                                          instanceKlassHandle k,
  2100                                          Handle class_loader,
  2101                                          TRAPS) {
  2102   // Compile_lock prevents systemDictionary updates during compilations
  2103   assert_locked_or_safepoint(Compile_lock);
  2104   symbolHandle name (THREAD, k->name());
  2107   MutexLocker mu1(SystemDictionary_lock, THREAD);
  2109   // See whether biased locking is enabled and if so set it for this
  2110   // klass.
  2111   // Note that this must be done past the last potential blocking
  2112   // point / safepoint. We enable biased locking lazily using a
  2113   // VM_Operation to iterate the SystemDictionary and installing the
  2114   // biasable mark word into each instanceKlass's prototype header.
  2115   // To avoid race conditions where we accidentally miss enabling the
  2116   // optimization for one class in the process of being added to the
  2117   // dictionary, we must not safepoint after the test of
  2118   // BiasedLocking::enabled().
  2119   if (UseBiasedLocking && BiasedLocking::enabled()) {
  2120     // Set biased locking bit for all loaded classes; it will be
  2121     // cleared if revocation occurs too often for this type
  2122     // NOTE that we must only do this when the class is initally
  2123     // defined, not each time it is referenced from a new class loader
  2124     if (k->class_loader() == class_loader()) {
  2125       k->set_prototype_header(markOopDesc::biased_locking_prototype());
  2129   // Check for a placeholder. If there, remove it and make a
  2130   // new system dictionary entry.
  2131   placeholders()->find_and_remove(p_index, p_hash, name, class_loader, THREAD);
  2132   klassOop sd_check = find_class(d_index, d_hash, name, class_loader);
  2133   if (sd_check == NULL) {
  2134     dictionary()->add_klass(name, class_loader, k);
  2135     notice_modification();
  2137 #ifdef ASSERT
  2138   sd_check = find_class(d_index, d_hash, name, class_loader);
  2139   assert (sd_check != NULL, "should have entry in system dictionary");
  2140 // Changed to allow PH to remain to complete class circularity checking
  2141 // while only one thread can define a class at one time, multiple
  2142 // classes can resolve the superclass for a class at one time,
  2143 // and the placeholder is used to track that
  2144 //  symbolOop ph_check = find_placeholder(p_index, p_hash, name, class_loader);
  2145 //  assert (ph_check == NULL, "should not have a placeholder entry");
  2146 #endif
  2147     SystemDictionary_lock->notify_all();
  2152 klassOop SystemDictionary::find_constrained_instance_or_array_klass(
  2153                     symbolHandle class_name, Handle class_loader, TRAPS) {
  2155   // First see if it has been loaded directly.
  2156   // Force the protection domain to be null.  (This removes protection checks.)
  2157   Handle no_protection_domain;
  2158   klassOop klass = find_instance_or_array_klass(class_name, class_loader,
  2159                                                 no_protection_domain, CHECK_NULL);
  2160   if (klass != NULL)
  2161     return klass;
  2163   // Now look to see if it has been loaded elsewhere, and is subject to
  2164   // a loader constraint that would require this loader to return the
  2165   // klass that is already loaded.
  2166   if (FieldType::is_array(class_name())) {
  2167     // Array classes are hard because their klassOops are not kept in the
  2168     // constraint table. The array klass may be constrained, but the elem class
  2169     // may not be.
  2170     jint dimension;
  2171     symbolOop object_key;
  2172     BasicType t = FieldType::get_array_info(class_name(), &dimension,
  2173                                             &object_key, CHECK_(NULL));
  2174     if (t != T_OBJECT) {
  2175       klass = Universe::typeArrayKlassObj(t);
  2176     } else {
  2177       symbolHandle elem_name(THREAD, object_key);
  2178       MutexLocker mu(SystemDictionary_lock, THREAD);
  2179       klass = constraints()->find_constrained_elem_klass(class_name, elem_name, class_loader, THREAD);
  2181     if (klass != NULL) {
  2182       klass = Klass::cast(klass)->array_klass_or_null(dimension);
  2184   } else {
  2185     MutexLocker mu(SystemDictionary_lock, THREAD);
  2186     // Non-array classes are easy: simply check the constraint table.
  2187     klass = constraints()->find_constrained_klass(class_name, class_loader);
  2190   return klass;
  2194 bool SystemDictionary::add_loader_constraint(symbolHandle class_name,
  2195                                              Handle class_loader1,
  2196                                              Handle class_loader2,
  2197                                              Thread* THREAD) {
  2198   unsigned int d_hash1 = dictionary()->compute_hash(class_name, class_loader1);
  2199   int d_index1 = dictionary()->hash_to_index(d_hash1);
  2201   unsigned int d_hash2 = dictionary()->compute_hash(class_name, class_loader2);
  2202   int d_index2 = dictionary()->hash_to_index(d_hash2);
  2205     MutexLocker mu_s(SystemDictionary_lock, THREAD);
  2207     // Better never do a GC while we're holding these oops
  2208     No_Safepoint_Verifier nosafepoint;
  2210     klassOop klass1 = find_class(d_index1, d_hash1, class_name, class_loader1);
  2211     klassOop klass2 = find_class(d_index2, d_hash2, class_name, class_loader2);
  2212     return constraints()->add_entry(class_name, klass1, class_loader1,
  2213                                     klass2, class_loader2);
  2217 // Add entry to resolution error table to record the error when the first
  2218 // attempt to resolve a reference to a class has failed.
  2219 void SystemDictionary::add_resolution_error(constantPoolHandle pool, int which, symbolHandle error) {
  2220   unsigned int hash = resolution_errors()->compute_hash(pool, which);
  2221   int index = resolution_errors()->hash_to_index(hash);
  2223     MutexLocker ml(SystemDictionary_lock, Thread::current());
  2224     resolution_errors()->add_entry(index, hash, pool, which, error);
  2228 // Lookup resolution error table. Returns error if found, otherwise NULL.
  2229 symbolOop SystemDictionary::find_resolution_error(constantPoolHandle pool, int which) {
  2230   unsigned int hash = resolution_errors()->compute_hash(pool, which);
  2231   int index = resolution_errors()->hash_to_index(hash);
  2233     MutexLocker ml(SystemDictionary_lock, Thread::current());
  2234     ResolutionErrorEntry* entry = resolution_errors()->find_entry(index, hash, pool, which);
  2235     return (entry != NULL) ? entry->error() : (symbolOop)NULL;
  2240 // Signature constraints ensure that callers and callees agree about
  2241 // the meaning of type names in their signatures.  This routine is the
  2242 // intake for constraints.  It collects them from several places:
  2243 //
  2244 //  * LinkResolver::resolve_method (if check_access is true) requires
  2245 //    that the resolving class (the caller) and the defining class of
  2246 //    the resolved method (the callee) agree on each type in the
  2247 //    method's signature.
  2248 //
  2249 //  * LinkResolver::resolve_interface_method performs exactly the same
  2250 //    checks.
  2251 //
  2252 //  * LinkResolver::resolve_field requires that the constant pool
  2253 //    attempting to link to a field agree with the field's defining
  2254 //    class about the type of the field signature.
  2255 //
  2256 //  * klassVtable::initialize_vtable requires that, when a class
  2257 //    overrides a vtable entry allocated by a superclass, that the
  2258 //    overriding method (i.e., the callee) agree with the superclass
  2259 //    on each type in the method's signature.
  2260 //
  2261 //  * klassItable::initialize_itable requires that, when a class fills
  2262 //    in its itables, for each non-abstract method installed in an
  2263 //    itable, the method (i.e., the callee) agree with the interface
  2264 //    on each type in the method's signature.
  2265 //
  2266 // All those methods have a boolean (check_access, checkconstraints)
  2267 // which turns off the checks.  This is used from specialized contexts
  2268 // such as bootstrapping, dumping, and debugging.
  2269 //
  2270 // No direct constraint is placed between the class and its
  2271 // supertypes.  Constraints are only placed along linked relations
  2272 // between callers and callees.  When a method overrides or implements
  2273 // an abstract method in a supertype (superclass or interface), the
  2274 // constraints are placed as if the supertype were the caller to the
  2275 // overriding method.  (This works well, since callers to the
  2276 // supertype have already established agreement between themselves and
  2277 // the supertype.)  As a result of all this, a class can disagree with
  2278 // its supertype about the meaning of a type name, as long as that
  2279 // class neither calls a relevant method of the supertype, nor is
  2280 // called (perhaps via an override) from the supertype.
  2281 //
  2282 //
  2283 // SystemDictionary::check_signature_loaders(sig, l1, l2)
  2284 //
  2285 // Make sure all class components (including arrays) in the given
  2286 // signature will be resolved to the same class in both loaders.
  2287 // Returns the name of the type that failed a loader constraint check, or
  2288 // NULL if no constraint failed. The returned C string needs cleaning up
  2289 // with a ResourceMark in the caller.  No exception except OOME is thrown.
  2290 char* SystemDictionary::check_signature_loaders(symbolHandle signature,
  2291                                                Handle loader1, Handle loader2,
  2292                                                bool is_method, TRAPS)  {
  2293   // Nothing to do if loaders are the same.
  2294   if (loader1() == loader2()) {
  2295     return NULL;
  2298   SignatureStream sig_strm(signature, is_method);
  2299   while (!sig_strm.is_done()) {
  2300     if (sig_strm.is_object()) {
  2301       symbolOop s = sig_strm.as_symbol(CHECK_NULL);
  2302       symbolHandle sig (THREAD, s);
  2303       if (!add_loader_constraint(sig, loader1, loader2, THREAD)) {
  2304         return sig()->as_C_string();
  2307     sig_strm.next();
  2309   return NULL;
  2313 methodOop SystemDictionary::find_method_handle_invoke(symbolHandle signature,
  2314                                                       Handle class_loader,
  2315                                                       Handle protection_domain,
  2316                                                       TRAPS) {
  2317   if (!EnableMethodHandles)  return NULL;
  2318   assert(class_loader.is_null() && protection_domain.is_null(),
  2319          "cannot load specialized versions of MethodHandle.invoke");
  2320   if (invoke_method_table() == NULL) {
  2321     // create this side table lazily
  2322     _invoke_method_table = new SymbolPropertyTable(_invoke_method_size);
  2324   unsigned int hash  = invoke_method_table()->compute_hash(signature);
  2325   int          index = invoke_method_table()->hash_to_index(hash);
  2326   SymbolPropertyEntry* spe = invoke_method_table()->find_entry(index, hash, signature);
  2327   if (spe == NULL || spe->property_oop() == NULL) {
  2328     // Must create lots of stuff here, but outside of the SystemDictionary lock.
  2329     Handle mt = compute_method_handle_type(signature(),
  2330                                            class_loader, protection_domain,
  2331                                            CHECK_NULL);
  2332     KlassHandle  mh_klass = SystemDictionaryHandles::MethodHandle_klass();
  2333     methodHandle m = methodOopDesc::make_invoke_method(mh_klass, signature,
  2334                                                        mt, CHECK_NULL);
  2335     // Now grab the lock.  We might have to throw away the new method,
  2336     // if a racing thread has managed to install one at the same time.
  2338       MutexLocker ml(SystemDictionary_lock, Thread::current());
  2339       spe = invoke_method_table()->find_entry(index, hash, signature);
  2340       if (spe == NULL)
  2341         spe = invoke_method_table()->add_entry(index, hash, signature);
  2342       if (spe->property_oop() == NULL)
  2343         spe->set_property_oop(m());
  2346   methodOop m = (methodOop) spe->property_oop();
  2347   assert(m->is_method(), "");
  2348   return m;
  2351 // Ask Java code to find or construct a java.dyn.MethodType for the given
  2352 // signature, as interpreted relative to the given class loader.
  2353 // Because of class loader constraints, all method handle usage must be
  2354 // consistent with this loader.
  2355 Handle SystemDictionary::compute_method_handle_type(symbolHandle signature,
  2356                                                     Handle class_loader,
  2357                                                     Handle protection_domain,
  2358                                                     TRAPS) {
  2359   Handle empty;
  2360   int npts = ArgumentCount(signature()).size();
  2361   objArrayHandle pts = oopFactory::new_objArray(SystemDictionary::class_klass(), npts, CHECK_(empty));
  2362   int arg = 0;
  2363   Handle rt;                            // the return type from the signature
  2364   for (SignatureStream ss(signature()); !ss.is_done(); ss.next()) {
  2365     oop mirror;
  2366     if (!ss.is_object()) {
  2367       mirror = Universe::java_mirror(ss.type());
  2368     } else {
  2369       symbolOop    name_oop = ss.as_symbol(CHECK_(empty));
  2370       symbolHandle name(THREAD, name_oop);
  2371       klassOop klass = resolve_or_fail(name,
  2372                                        class_loader, protection_domain,
  2373                                        true, CHECK_(empty));
  2374       mirror = Klass::cast(klass)->java_mirror();
  2376     if (ss.at_return_type())
  2377       rt = Handle(THREAD, mirror);
  2378     else
  2379       pts->obj_at_put(arg++, mirror);
  2381   assert(arg == npts, "");
  2383   // call MethodType java.dyn.MethodType::makeImpl(Class rt, Class[] pts, false, true)
  2384   bool varargs = false, trusted = true;
  2385   JavaCallArguments args(Handle(THREAD, rt()));
  2386   args.push_oop(pts());
  2387   args.push_int(false);
  2388   args.push_int(trusted);
  2389   JavaValue result(T_OBJECT);
  2390   JavaCalls::call_static(&result,
  2391                          SystemDictionary::MethodType_klass(),
  2392                          vmSymbols::makeImpl_name(), vmSymbols::makeImpl_signature(),
  2393                          &args, CHECK_(empty));
  2394   return Handle(THREAD, (oop) result.get_jobject());
  2398 // Ask Java code to find or construct a java.dyn.CallSite for the given
  2399 // name and signature, as interpreted relative to the given class loader.
  2400 Handle SystemDictionary::make_dynamic_call_site(KlassHandle caller,
  2401                                                 int caller_method_idnum,
  2402                                                 int caller_bci,
  2403                                                 symbolHandle name,
  2404                                                 methodHandle mh_invdyn,
  2405                                                 TRAPS) {
  2406   Handle empty;
  2407   // call sun.dyn.CallSiteImpl::makeSite(caller, name, mtype, cmid, cbci)
  2408   oop name_str_oop = StringTable::intern(name(), CHECK_(empty)); // not a handle!
  2409   JavaCallArguments args(Handle(THREAD, caller->java_mirror()));
  2410   args.push_oop(name_str_oop);
  2411   args.push_oop(mh_invdyn->method_handle_type());
  2412   args.push_int(caller_method_idnum);
  2413   args.push_int(caller_bci);
  2414   JavaValue result(T_OBJECT);
  2415   JavaCalls::call_static(&result,
  2416                          SystemDictionary::CallSiteImpl_klass(),
  2417                          vmSymbols::makeSite_name(), vmSymbols::makeSite_signature(),
  2418                          &args, CHECK_(empty));
  2419   oop call_site_oop = (oop) result.get_jobject();
  2420   assert(call_site_oop->is_oop()
  2421          /*&& sun_dyn_CallSiteImpl::is_instance(call_site_oop)*/, "must be sane");
  2422   sun_dyn_CallSiteImpl::set_vmmethod(call_site_oop, mh_invdyn());
  2423   if (TraceMethodHandles) {
  2424     tty->print_cr("Linked invokedynamic bci=%d site="INTPTR_FORMAT":", caller_bci, call_site_oop);
  2425     call_site_oop->print();
  2426     tty->cr();
  2428   return call_site_oop;
  2431 Handle SystemDictionary::find_bootstrap_method(KlassHandle caller,
  2432                                                KlassHandle search_bootstrap_klass,
  2433                                                TRAPS) {
  2434   Handle empty;
  2435   if (!caller->oop_is_instance())  return empty;
  2437   instanceKlassHandle ik(THREAD, caller());
  2439   if (ik->bootstrap_method() != NULL) {
  2440     return Handle(THREAD, ik->bootstrap_method());
  2443   // call java.dyn.Linkage::findBootstrapMethod(caller, sbk)
  2444   JavaCallArguments args(Handle(THREAD, ik->java_mirror()));
  2445   if (search_bootstrap_klass.is_null())
  2446     args.push_oop(Handle());
  2447   else
  2448     args.push_oop(search_bootstrap_klass->java_mirror());
  2449   JavaValue result(T_OBJECT);
  2450   JavaCalls::call_static(&result,
  2451                          SystemDictionary::Linkage_klass(),
  2452                          vmSymbols::findBootstrapMethod_name(),
  2453                          vmSymbols::findBootstrapMethod_signature(),
  2454                          &args, CHECK_(empty));
  2455   oop boot_method_oop = (oop) result.get_jobject();
  2457   if (boot_method_oop != NULL) {
  2458     assert(boot_method_oop->is_oop()
  2459            && java_dyn_MethodHandle::is_instance(boot_method_oop), "must be sane");
  2460     // probably no race conditions, but let's be careful:
  2461     if (Atomic::cmpxchg_ptr(boot_method_oop, ik->adr_bootstrap_method(), NULL) == NULL)
  2462       ik->set_bootstrap_method(boot_method_oop);
  2463     else
  2464       boot_method_oop = ik->bootstrap_method();
  2465   } else {
  2466     boot_method_oop = ik->bootstrap_method();
  2469   return Handle(THREAD, boot_method_oop);
  2472 // Since the identity hash code for symbols changes when the symbols are
  2473 // moved from the regular perm gen (hash in the mark word) to the shared
  2474 // spaces (hash is the address), the classes loaded into the dictionary
  2475 // may be in the wrong buckets.
  2477 void SystemDictionary::reorder_dictionary() {
  2478   dictionary()->reorder_dictionary();
  2482 void SystemDictionary::copy_buckets(char** top, char* end) {
  2483   dictionary()->copy_buckets(top, end);
  2487 void SystemDictionary::copy_table(char** top, char* end) {
  2488   dictionary()->copy_table(top, end);
  2492 void SystemDictionary::reverse() {
  2493   dictionary()->reverse();
  2496 int SystemDictionary::number_of_classes() {
  2497   return dictionary()->number_of_entries();
  2501 // ----------------------------------------------------------------------------
  2502 #ifndef PRODUCT
  2504 void SystemDictionary::print() {
  2505   dictionary()->print();
  2507   // Placeholders
  2508   GCMutexLocker mu(SystemDictionary_lock);
  2509   placeholders()->print();
  2511   // loader constraints - print under SD_lock
  2512   constraints()->print();
  2515 #endif
  2517 void SystemDictionary::verify() {
  2518   guarantee(dictionary() != NULL, "Verify of system dictionary failed");
  2519   guarantee(constraints() != NULL,
  2520             "Verify of loader constraints failed");
  2521   guarantee(dictionary()->number_of_entries() >= 0 &&
  2522             placeholders()->number_of_entries() >= 0,
  2523             "Verify of system dictionary failed");
  2525   // Verify dictionary
  2526   dictionary()->verify();
  2528   GCMutexLocker mu(SystemDictionary_lock);
  2529   placeholders()->verify();
  2531   // Verify constraint table
  2532   guarantee(constraints() != NULL, "Verify of loader constraints failed");
  2533   constraints()->verify(dictionary());
  2537 void SystemDictionary::verify_obj_klass_present(Handle obj,
  2538                                                 symbolHandle class_name,
  2539                                                 Handle class_loader) {
  2540   GCMutexLocker mu(SystemDictionary_lock);
  2541   oop probe = find_class_or_placeholder(class_name, class_loader);
  2542   if (probe == NULL) {
  2543     probe = SystemDictionary::find_shared_class(class_name);
  2545   guarantee(probe != NULL &&
  2546             (!probe->is_klass() || probe == obj()),
  2547                      "Loaded klasses should be in SystemDictionary");
  2550 #ifndef PRODUCT
  2552 // statistics code
  2553 class ClassStatistics: AllStatic {
  2554  private:
  2555   static int nclasses;        // number of classes
  2556   static int nmethods;        // number of methods
  2557   static int nmethoddata;     // number of methodData
  2558   static int class_size;      // size of class objects in words
  2559   static int method_size;     // size of method objects in words
  2560   static int debug_size;      // size of debug info in methods
  2561   static int methoddata_size; // size of methodData objects in words
  2563   static void do_class(klassOop k) {
  2564     nclasses++;
  2565     class_size += k->size();
  2566     if (k->klass_part()->oop_is_instance()) {
  2567       instanceKlass* ik = (instanceKlass*)k->klass_part();
  2568       class_size += ik->methods()->size();
  2569       class_size += ik->constants()->size();
  2570       class_size += ik->local_interfaces()->size();
  2571       class_size += ik->transitive_interfaces()->size();
  2572       // We do not have to count implementors, since we only store one!
  2573       class_size += ik->fields()->size();
  2577   static void do_method(methodOop m) {
  2578     nmethods++;
  2579     method_size += m->size();
  2580     // class loader uses same objArray for empty vectors, so don't count these
  2581     if (m->exception_table()->length() != 0)   method_size += m->exception_table()->size();
  2582     if (m->has_stackmap_table()) {
  2583       method_size += m->stackmap_data()->size();
  2586     methodDataOop mdo = m->method_data();
  2587     if (mdo != NULL) {
  2588       nmethoddata++;
  2589       methoddata_size += mdo->size();
  2593  public:
  2594   static void print() {
  2595     SystemDictionary::classes_do(do_class);
  2596     SystemDictionary::methods_do(do_method);
  2597     tty->print_cr("Class statistics:");
  2598     tty->print_cr("%d classes (%d bytes)", nclasses, class_size * oopSize);
  2599     tty->print_cr("%d methods (%d bytes = %d base + %d debug info)", nmethods,
  2600                   (method_size + debug_size) * oopSize, method_size * oopSize, debug_size * oopSize);
  2601     tty->print_cr("%d methoddata (%d bytes)", nmethoddata, methoddata_size * oopSize);
  2603 };
  2606 int ClassStatistics::nclasses        = 0;
  2607 int ClassStatistics::nmethods        = 0;
  2608 int ClassStatistics::nmethoddata     = 0;
  2609 int ClassStatistics::class_size      = 0;
  2610 int ClassStatistics::method_size     = 0;
  2611 int ClassStatistics::debug_size      = 0;
  2612 int ClassStatistics::methoddata_size = 0;
  2614 void SystemDictionary::print_class_statistics() {
  2615   ResourceMark rm;
  2616   ClassStatistics::print();
  2620 class MethodStatistics: AllStatic {
  2621  public:
  2622   enum {
  2623     max_parameter_size = 10
  2624   };
  2625  private:
  2627   static int _number_of_methods;
  2628   static int _number_of_final_methods;
  2629   static int _number_of_static_methods;
  2630   static int _number_of_native_methods;
  2631   static int _number_of_synchronized_methods;
  2632   static int _number_of_profiled_methods;
  2633   static int _number_of_bytecodes;
  2634   static int _parameter_size_profile[max_parameter_size];
  2635   static int _bytecodes_profile[Bytecodes::number_of_java_codes];
  2637   static void initialize() {
  2638     _number_of_methods        = 0;
  2639     _number_of_final_methods  = 0;
  2640     _number_of_static_methods = 0;
  2641     _number_of_native_methods = 0;
  2642     _number_of_synchronized_methods = 0;
  2643     _number_of_profiled_methods = 0;
  2644     _number_of_bytecodes      = 0;
  2645     for (int i = 0; i < max_parameter_size             ; i++) _parameter_size_profile[i] = 0;
  2646     for (int j = 0; j < Bytecodes::number_of_java_codes; j++) _bytecodes_profile     [j] = 0;
  2647   };
  2649   static void do_method(methodOop m) {
  2650     _number_of_methods++;
  2651     // collect flag info
  2652     if (m->is_final()       ) _number_of_final_methods++;
  2653     if (m->is_static()      ) _number_of_static_methods++;
  2654     if (m->is_native()      ) _number_of_native_methods++;
  2655     if (m->is_synchronized()) _number_of_synchronized_methods++;
  2656     if (m->method_data() != NULL) _number_of_profiled_methods++;
  2657     // collect parameter size info (add one for receiver, if any)
  2658     _parameter_size_profile[MIN2(m->size_of_parameters() + (m->is_static() ? 0 : 1), max_parameter_size - 1)]++;
  2659     // collect bytecodes info
  2661       Thread *thread = Thread::current();
  2662       HandleMark hm(thread);
  2663       BytecodeStream s(methodHandle(thread, m));
  2664       Bytecodes::Code c;
  2665       while ((c = s.next()) >= 0) {
  2666         _number_of_bytecodes++;
  2667         _bytecodes_profile[c]++;
  2672  public:
  2673   static void print() {
  2674     initialize();
  2675     SystemDictionary::methods_do(do_method);
  2676     // generate output
  2677     tty->cr();
  2678     tty->print_cr("Method statistics (static):");
  2679     // flag distribution
  2680     tty->cr();
  2681     tty->print_cr("%6d final        methods  %6.1f%%", _number_of_final_methods       , _number_of_final_methods        * 100.0F / _number_of_methods);
  2682     tty->print_cr("%6d static       methods  %6.1f%%", _number_of_static_methods      , _number_of_static_methods       * 100.0F / _number_of_methods);
  2683     tty->print_cr("%6d native       methods  %6.1f%%", _number_of_native_methods      , _number_of_native_methods       * 100.0F / _number_of_methods);
  2684     tty->print_cr("%6d synchronized methods  %6.1f%%", _number_of_synchronized_methods, _number_of_synchronized_methods * 100.0F / _number_of_methods);
  2685     tty->print_cr("%6d profiled     methods  %6.1f%%", _number_of_profiled_methods, _number_of_profiled_methods * 100.0F / _number_of_methods);
  2686     // parameter size profile
  2687     tty->cr();
  2688     { int tot = 0;
  2689       int avg = 0;
  2690       for (int i = 0; i < max_parameter_size; i++) {
  2691         int n = _parameter_size_profile[i];
  2692         tot += n;
  2693         avg += n*i;
  2694         tty->print_cr("parameter size = %1d: %6d methods  %5.1f%%", i, n, n * 100.0F / _number_of_methods);
  2696       assert(tot == _number_of_methods, "should be the same");
  2697       tty->print_cr("                    %6d methods  100.0%%", _number_of_methods);
  2698       tty->print_cr("(average parameter size = %3.1f including receiver, if any)", (float)avg / _number_of_methods);
  2700     // bytecodes profile
  2701     tty->cr();
  2702     { int tot = 0;
  2703       for (int i = 0; i < Bytecodes::number_of_java_codes; i++) {
  2704         if (Bytecodes::is_defined(i)) {
  2705           Bytecodes::Code c = Bytecodes::cast(i);
  2706           int n = _bytecodes_profile[c];
  2707           tot += n;
  2708           tty->print_cr("%9d  %7.3f%%  %s", n, n * 100.0F / _number_of_bytecodes, Bytecodes::name(c));
  2711       assert(tot == _number_of_bytecodes, "should be the same");
  2712       tty->print_cr("%9d  100.000%%", _number_of_bytecodes);
  2714     tty->cr();
  2716 };
  2718 int MethodStatistics::_number_of_methods;
  2719 int MethodStatistics::_number_of_final_methods;
  2720 int MethodStatistics::_number_of_static_methods;
  2721 int MethodStatistics::_number_of_native_methods;
  2722 int MethodStatistics::_number_of_synchronized_methods;
  2723 int MethodStatistics::_number_of_profiled_methods;
  2724 int MethodStatistics::_number_of_bytecodes;
  2725 int MethodStatistics::_parameter_size_profile[MethodStatistics::max_parameter_size];
  2726 int MethodStatistics::_bytecodes_profile[Bytecodes::number_of_java_codes];
  2729 void SystemDictionary::print_method_statistics() {
  2730   MethodStatistics::print();
  2733 #endif // PRODUCT

mercurial