src/share/vm/classfile/systemDictionary.cpp

Wed, 24 Oct 2012 14:33:22 -0700

author
kvn
date
Wed, 24 Oct 2012 14:33:22 -0700
changeset 4205
a3ecd773a7b9
parent 4164
d804e148cff8
child 4177
633ba56cb013
permissions
-rw-r--r--

7184394: add intrinsics to use AES instructions
Summary: Use new x86 AES instructions for AESCrypt.
Reviewed-by: twisti, kvn, roland
Contributed-by: tom.deneau@amd.com

     1 /*
     2  * Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved.
     3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
     4  *
     5  * This code is free software; you can redistribute it and/or modify it
     6  * under the terms of the GNU General Public License version 2 only, as
     7  * published by the Free Software Foundation.
     8  *
     9  * This code is distributed in the hope that it will be useful, but WITHOUT
    10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
    12  * version 2 for more details (a copy is included in the LICENSE file that
    13  * accompanied this code).
    14  *
    15  * You should have received a copy of the GNU General Public License version
    16  * 2 along with this work; if not, write to the Free Software Foundation,
    17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
    18  *
    19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
    20  * or visit www.oracle.com if you need additional information or have any
    21  * questions.
    22  *
    23  */
    25 #include "precompiled.hpp"
    26 #include "classfile/classLoaderData.inline.hpp"
    27 #include "classfile/dictionary.hpp"
    28 #include "classfile/javaClasses.hpp"
    29 #include "classfile/loaderConstraints.hpp"
    30 #include "classfile/placeholders.hpp"
    31 #include "classfile/resolutionErrors.hpp"
    32 #include "classfile/systemDictionary.hpp"
    33 #include "classfile/vmSymbols.hpp"
    34 #include "compiler/compileBroker.hpp"
    35 #include "interpreter/bytecodeStream.hpp"
    36 #include "interpreter/interpreter.hpp"
    37 #include "memory/gcLocker.hpp"
    38 #include "memory/oopFactory.hpp"
    39 #include "oops/instanceKlass.hpp"
    40 #include "oops/instanceRefKlass.hpp"
    41 #include "oops/klass.inline.hpp"
    42 #include "oops/methodData.hpp"
    43 #include "oops/objArrayKlass.hpp"
    44 #include "oops/oop.inline.hpp"
    45 #include "oops/oop.inline2.hpp"
    46 #include "oops/typeArrayKlass.hpp"
    47 #include "prims/jvmtiEnvBase.hpp"
    48 #include "prims/methodHandles.hpp"
    49 #include "runtime/biasedLocking.hpp"
    50 #include "runtime/fieldType.hpp"
    51 #include "runtime/handles.inline.hpp"
    52 #include "runtime/java.hpp"
    53 #include "runtime/javaCalls.hpp"
    54 #include "runtime/mutexLocker.hpp"
    55 #include "runtime/signature.hpp"
    56 #include "services/classLoadingService.hpp"
    57 #include "services/threadService.hpp"
    60 Dictionary*            SystemDictionary::_dictionary          = NULL;
    61 PlaceholderTable*      SystemDictionary::_placeholders        = NULL;
    62 Dictionary*            SystemDictionary::_shared_dictionary   = NULL;
    63 LoaderConstraintTable* SystemDictionary::_loader_constraints  = NULL;
    64 ResolutionErrorTable*  SystemDictionary::_resolution_errors   = NULL;
    65 SymbolPropertyTable*   SystemDictionary::_invoke_method_table = NULL;
    68 int         SystemDictionary::_number_of_modifications = 0;
    69 int         SystemDictionary::_sdgeneration               = 0;
    70 const int   SystemDictionary::_primelist[_prime_array_size] = {1009,2017,4049,5051,10103,
    71               20201,40423,99991};
    73 oop         SystemDictionary::_system_loader_lock_obj     =  NULL;
    75 Klass*      SystemDictionary::_well_known_klasses[SystemDictionary::WKID_LIMIT]
    76                                                           =  { NULL /*, NULL...*/ };
    78 Klass*      SystemDictionary::_box_klasses[T_VOID+1]      =  { NULL /*, NULL...*/ };
    80 oop         SystemDictionary::_java_system_loader         =  NULL;
    82 bool        SystemDictionary::_has_loadClassInternal      =  false;
    83 bool        SystemDictionary::_has_checkPackageAccess     =  false;
    85 // lazily initialized klass variables
    86 Klass* volatile SystemDictionary::_abstract_ownable_synchronizer_klass = NULL;
    89 // ----------------------------------------------------------------------------
    90 // Java-level SystemLoader
    92 oop SystemDictionary::java_system_loader() {
    93   return _java_system_loader;
    94 }
    96 void SystemDictionary::compute_java_system_loader(TRAPS) {
    97   KlassHandle system_klass(THREAD, WK_KLASS(ClassLoader_klass));
    98   JavaValue result(T_OBJECT);
    99   JavaCalls::call_static(&result,
   100                          KlassHandle(THREAD, WK_KLASS(ClassLoader_klass)),
   101                          vmSymbols::getSystemClassLoader_name(),
   102                          vmSymbols::void_classloader_signature(),
   103                          CHECK);
   105   _java_system_loader = (oop)result.get_jobject();
   106 }
   109 ClassLoaderData* SystemDictionary::register_loader(Handle class_loader) {
   110   if (class_loader() == NULL) return ClassLoaderData::the_null_class_loader_data();
   111   return ClassLoaderDataGraph::find_or_create(class_loader);
   112 }
   114 // ----------------------------------------------------------------------------
   115 // debugging
   117 #ifdef ASSERT
   119 // return true if class_name contains no '.' (internal format is '/')
   120 bool SystemDictionary::is_internal_format(Symbol* class_name) {
   121   if (class_name != NULL) {
   122     ResourceMark rm;
   123     char* name = class_name->as_C_string();
   124     return strchr(name, '.') == NULL;
   125   } else {
   126     return true;
   127   }
   128 }
   130 #endif
   132 // ----------------------------------------------------------------------------
   133 // Parallel class loading check
   135 bool SystemDictionary::is_parallelCapable(Handle class_loader) {
   136   if (UnsyncloadClass || class_loader.is_null()) return true;
   137   if (AlwaysLockClassLoader) return false;
   138   return java_lang_ClassLoader::parallelCapable(class_loader());
   139 }
   140 // ----------------------------------------------------------------------------
   141 // ParallelDefineClass flag does not apply to bootclass loader
   142 bool SystemDictionary::is_parallelDefine(Handle class_loader) {
   143    if (class_loader.is_null()) return false;
   144    if (AllowParallelDefineClass && java_lang_ClassLoader::parallelCapable(class_loader())) {
   145      return true;
   146    }
   147    return false;
   148 }
   149 // ----------------------------------------------------------------------------
   150 // Resolving of classes
   152 // Forwards to resolve_or_null
   154 Klass* SystemDictionary::resolve_or_fail(Symbol* class_name, Handle class_loader, Handle protection_domain, bool throw_error, TRAPS) {
   155   Klass* klass = resolve_or_null(class_name, class_loader, protection_domain, THREAD);
   156   if (HAS_PENDING_EXCEPTION || klass == NULL) {
   157     KlassHandle k_h(THREAD, klass);
   158     // can return a null klass
   159     klass = handle_resolution_exception(class_name, class_loader, protection_domain, throw_error, k_h, THREAD);
   160   }
   161   return klass;
   162 }
   164 Klass* SystemDictionary::handle_resolution_exception(Symbol* class_name, Handle class_loader, Handle protection_domain, bool throw_error, KlassHandle klass_h, TRAPS) {
   165   if (HAS_PENDING_EXCEPTION) {
   166     // If we have a pending exception we forward it to the caller, unless throw_error is true,
   167     // in which case we have to check whether the pending exception is a ClassNotFoundException,
   168     // and if so convert it to a NoClassDefFoundError
   169     // And chain the original ClassNotFoundException
   170     if (throw_error && PENDING_EXCEPTION->is_a(SystemDictionary::ClassNotFoundException_klass())) {
   171       ResourceMark rm(THREAD);
   172       assert(klass_h() == NULL, "Should not have result with exception pending");
   173       Handle e(THREAD, PENDING_EXCEPTION);
   174       CLEAR_PENDING_EXCEPTION;
   175       THROW_MSG_CAUSE_0(vmSymbols::java_lang_NoClassDefFoundError(), class_name->as_C_string(), e);
   176     } else {
   177       return NULL;
   178     }
   179   }
   180   // Class not found, throw appropriate error or exception depending on value of throw_error
   181   if (klass_h() == NULL) {
   182     ResourceMark rm(THREAD);
   183     if (throw_error) {
   184       THROW_MSG_0(vmSymbols::java_lang_NoClassDefFoundError(), class_name->as_C_string());
   185     } else {
   186       THROW_MSG_0(vmSymbols::java_lang_ClassNotFoundException(), class_name->as_C_string());
   187     }
   188   }
   189   return (Klass*)klass_h();
   190 }
   193 Klass* SystemDictionary::resolve_or_fail(Symbol* class_name,
   194                                            bool throw_error, TRAPS)
   195 {
   196   return resolve_or_fail(class_name, Handle(), Handle(), throw_error, THREAD);
   197 }
   200 // Forwards to resolve_instance_class_or_null
   202 Klass* SystemDictionary::resolve_or_null(Symbol* class_name, Handle class_loader, Handle protection_domain, TRAPS) {
   203   assert(!THREAD->is_Compiler_thread(),
   204          err_msg("can not load classes with compiler thread: class=%s, classloader=%s",
   205                  class_name->as_C_string(),
   206                  class_loader.is_null() ? "null" : class_loader->klass()->name()->as_C_string()));
   207   if (FieldType::is_array(class_name)) {
   208     return resolve_array_class_or_null(class_name, class_loader, protection_domain, CHECK_NULL);
   209   } else if (FieldType::is_obj(class_name)) {
   210     ResourceMark rm(THREAD);
   211     // Ignore wrapping L and ;.
   212     TempNewSymbol name = SymbolTable::new_symbol(class_name->as_C_string() + 1,
   213                                    class_name->utf8_length() - 2, CHECK_NULL);
   214     return resolve_instance_class_or_null(name, class_loader, protection_domain, CHECK_NULL);
   215   } else {
   216     return resolve_instance_class_or_null(class_name, class_loader, protection_domain, CHECK_NULL);
   217   }
   218 }
   220 Klass* SystemDictionary::resolve_or_null(Symbol* class_name, TRAPS) {
   221   return resolve_or_null(class_name, Handle(), Handle(), THREAD);
   222 }
   224 // Forwards to resolve_instance_class_or_null
   226 Klass* SystemDictionary::resolve_array_class_or_null(Symbol* class_name,
   227                                                        Handle class_loader,
   228                                                        Handle protection_domain,
   229                                                        TRAPS) {
   230   assert(FieldType::is_array(class_name), "must be array");
   231   Klass* k = NULL;
   232   FieldArrayInfo fd;
   233   // dimension and object_key in FieldArrayInfo are assigned as a side-effect
   234   // of this call
   235   BasicType t = FieldType::get_array_info(class_name, fd, CHECK_NULL);
   236   if (t == T_OBJECT) {
   237     // naked oop "k" is OK here -- we assign back into it
   238     k = SystemDictionary::resolve_instance_class_or_null(fd.object_key(),
   239                                                          class_loader,
   240                                                          protection_domain,
   241                                                          CHECK_NULL);
   242     if (k != NULL) {
   243       k = Klass::cast(k)->array_klass(fd.dimension(), CHECK_NULL);
   244     }
   245   } else {
   246     k = Universe::typeArrayKlassObj(t);
   247     k = TypeArrayKlass::cast(k)->array_klass(fd.dimension(), CHECK_NULL);
   248   }
   249   return k;
   250 }
   253 // Must be called for any super-class or super-interface resolution
   254 // during class definition to allow class circularity checking
   255 // super-interface callers:
   256 //    parse_interfaces - for defineClass & jvmtiRedefineClasses
   257 // super-class callers:
   258 //   ClassFileParser - for defineClass & jvmtiRedefineClasses
   259 //   load_shared_class - while loading a class from shared archive
   260 //   resolve_instance_class_or_null:
   261 //     via: handle_parallel_super_load
   262 //      when resolving a class that has an existing placeholder with
   263 //      a saved superclass [i.e. a defineClass is currently in progress]
   264 //      if another thread is trying to resolve the class, it must do
   265 //      super-class checks on its own thread to catch class circularity
   266 // This last call is critical in class circularity checking for cases
   267 // where classloading is delegated to different threads and the
   268 // classloader lock is released.
   269 // Take the case: Base->Super->Base
   270 //   1. If thread T1 tries to do a defineClass of class Base
   271 //    resolve_super_or_fail creates placeholder: T1, Base (super Super)
   272 //   2. resolve_instance_class_or_null does not find SD or placeholder for Super
   273 //    so it tries to load Super
   274 //   3. If we load the class internally, or user classloader uses same thread
   275 //      loadClassFromxxx or defineClass via parseClassFile Super ...
   276 //      3.1 resolve_super_or_fail creates placeholder: T1, Super (super Base)
   277 //      3.3 resolve_instance_class_or_null Base, finds placeholder for Base
   278 //      3.4 calls resolve_super_or_fail Base
   279 //      3.5 finds T1,Base -> throws class circularity
   280 //OR 4. If T2 tries to resolve Super via defineClass Super ...
   281 //      4.1 resolve_super_or_fail creates placeholder: T2, Super (super Base)
   282 //      4.2 resolve_instance_class_or_null Base, finds placeholder for Base (super Super)
   283 //      4.3 calls resolve_super_or_fail Super in parallel on own thread T2
   284 //      4.4 finds T2, Super -> throws class circularity
   285 // Must be called, even if superclass is null, since this is
   286 // where the placeholder entry is created which claims this
   287 // thread is loading this class/classloader.
   288 Klass* SystemDictionary::resolve_super_or_fail(Symbol* child_name,
   289                                                  Symbol* class_name,
   290                                                  Handle class_loader,
   291                                                  Handle protection_domain,
   292                                                  bool is_superclass,
   293                                                  TRAPS) {
   294   // Double-check, if child class is already loaded, just return super-class,interface
   295   // Don't add a placedholder if already loaded, i.e. already in system dictionary
   296   // Make sure there's a placeholder for the *child* before resolving.
   297   // Used as a claim that this thread is currently loading superclass/classloader
   298   // Used here for ClassCircularity checks and also for heap verification
   299   // (every InstanceKlass in the heap needs to be in the system dictionary
   300   // or have a placeholder).
   301   // Must check ClassCircularity before checking if super class is already loaded
   302   //
   303   // We might not already have a placeholder if this child_name was
   304   // first seen via resolve_from_stream (jni_DefineClass or JVM_DefineClass);
   305   // the name of the class might not be known until the stream is actually
   306   // parsed.
   307   // Bugs 4643874, 4715493
   308   // compute_hash can have a safepoint
   310   ClassLoaderData* loader_data = class_loader_data(class_loader);
   311   unsigned int d_hash = dictionary()->compute_hash(child_name, loader_data);
   312   int d_index = dictionary()->hash_to_index(d_hash);
   313   unsigned int p_hash = placeholders()->compute_hash(child_name, loader_data);
   314   int p_index = placeholders()->hash_to_index(p_hash);
   315   // can't throw error holding a lock
   316   bool child_already_loaded = false;
   317   bool throw_circularity_error = false;
   318   {
   319     MutexLocker mu(SystemDictionary_lock, THREAD);
   320     Klass* childk = find_class(d_index, d_hash, child_name, loader_data);
   321     Klass* quicksuperk;
   322     // to support // loading: if child done loading, just return superclass
   323     // if class_name, & class_loader don't match:
   324     // if initial define, SD update will give LinkageError
   325     // if redefine: compare_class_versions will give HIERARCHY_CHANGED
   326     // so we don't throw an exception here.
   327     // see: nsk redefclass014 & java.lang.instrument Instrument032
   328     if ((childk != NULL ) && (is_superclass) &&
   329        ((quicksuperk = InstanceKlass::cast(childk)->super()) != NULL) &&
   331          ((Klass::cast(quicksuperk)->name() == class_name) &&
   332             (Klass::cast(quicksuperk)->class_loader()  == class_loader()))) {
   333            return quicksuperk;
   334     } else {
   335       PlaceholderEntry* probe = placeholders()->get_entry(p_index, p_hash, child_name, loader_data);
   336       if (probe && probe->check_seen_thread(THREAD, PlaceholderTable::LOAD_SUPER)) {
   337           throw_circularity_error = true;
   338       }
   339     }
   340     if (!throw_circularity_error) {
   341       PlaceholderEntry* newprobe = placeholders()->find_and_add(p_index, p_hash, child_name, loader_data, PlaceholderTable::LOAD_SUPER, class_name, THREAD);
   342     }
   343   }
   344   if (throw_circularity_error) {
   345       ResourceMark rm(THREAD);
   346       THROW_MSG_0(vmSymbols::java_lang_ClassCircularityError(), child_name->as_C_string());
   347   }
   349 // java.lang.Object should have been found above
   350   assert(class_name != NULL, "null super class for resolving");
   351   // Resolve the super class or interface, check results on return
   352   Klass* superk = NULL;
   353   superk = SystemDictionary::resolve_or_null(class_name,
   354                                                  class_loader,
   355                                                  protection_domain,
   356                                                  THREAD);
   358   KlassHandle superk_h(THREAD, superk);
   360   // Note: clean up of placeholders currently in callers of
   361   // resolve_super_or_fail - either at update_dictionary time
   362   // or on error
   363   {
   364   MutexLocker mu(SystemDictionary_lock, THREAD);
   365    PlaceholderEntry* probe = placeholders()->get_entry(p_index, p_hash, child_name, loader_data);
   366    if (probe != NULL) {
   367       probe->remove_seen_thread(THREAD, PlaceholderTable::LOAD_SUPER);
   368    }
   369   }
   370   if (HAS_PENDING_EXCEPTION || superk_h() == NULL) {
   371     // can null superk
   372     superk_h = KlassHandle(THREAD, handle_resolution_exception(class_name, class_loader, protection_domain, true, superk_h, THREAD));
   373   }
   375   return superk_h();
   376 }
   378 void SystemDictionary::validate_protection_domain(instanceKlassHandle klass,
   379                                                   Handle class_loader,
   380                                                   Handle protection_domain,
   381                                                   TRAPS) {
   382   if(!has_checkPackageAccess()) return;
   384   // Now we have to call back to java to check if the initating class has access
   385   JavaValue result(T_VOID);
   386   if (TraceProtectionDomainVerification) {
   387     // Print out trace information
   388     tty->print_cr("Checking package access");
   389     tty->print(" - class loader:      "); class_loader()->print_value_on(tty);      tty->cr();
   390     tty->print(" - protection domain: "); protection_domain()->print_value_on(tty); tty->cr();
   391     tty->print(" - loading:           "); klass()->print_value_on(tty);             tty->cr();
   392   }
   394   KlassHandle system_loader(THREAD, SystemDictionary::ClassLoader_klass());
   395   JavaCalls::call_special(&result,
   396                          class_loader,
   397                          system_loader,
   398                          vmSymbols::checkPackageAccess_name(),
   399                          vmSymbols::class_protectiondomain_signature(),
   400                          Handle(THREAD, klass->java_mirror()),
   401                          protection_domain,
   402                          THREAD);
   404   if (TraceProtectionDomainVerification) {
   405     if (HAS_PENDING_EXCEPTION) {
   406       tty->print_cr(" -> DENIED !!!!!!!!!!!!!!!!!!!!!");
   407     } else {
   408      tty->print_cr(" -> granted");
   409     }
   410     tty->cr();
   411   }
   413   if (HAS_PENDING_EXCEPTION) return;
   415   // If no exception has been thrown, we have validated the protection domain
   416   // Insert the protection domain of the initiating class into the set.
   417   {
   418     // We recalculate the entry here -- we've called out to java since
   419     // the last time it was calculated.
   420     ClassLoaderData* loader_data = class_loader_data(class_loader);
   422     Symbol*  kn = klass->name();
   423     unsigned int d_hash = dictionary()->compute_hash(kn, loader_data);
   424     int d_index = dictionary()->hash_to_index(d_hash);
   426     MutexLocker mu(SystemDictionary_lock, THREAD);
   427     {
   428       // Note that we have an entry, and entries can be deleted only during GC,
   429       // so we cannot allow GC to occur while we're holding this entry.
   431       // We're using a No_Safepoint_Verifier to catch any place where we
   432       // might potentially do a GC at all.
   433       // SystemDictionary::do_unloading() asserts that classes are only
   434       // unloaded at a safepoint.
   435       No_Safepoint_Verifier nosafepoint;
   436       dictionary()->add_protection_domain(d_index, d_hash, klass, loader_data,
   437                                           protection_domain, THREAD);
   438     }
   439   }
   440 }
   442 // We only get here if this thread finds that another thread
   443 // has already claimed the placeholder token for the current operation,
   444 // but that other thread either never owned or gave up the
   445 // object lock
   446 // Waits on SystemDictionary_lock to indicate placeholder table updated
   447 // On return, caller must recheck placeholder table state
   448 //
   449 // We only get here if
   450 //  1) custom classLoader, i.e. not bootstrap classloader
   451 //  2) UnsyncloadClass not set
   452 //  3) custom classLoader has broken the class loader objectLock
   453 //     so another thread got here in parallel
   454 //
   455 // lockObject must be held.
   456 // Complicated dance due to lock ordering:
   457 // Must first release the classloader object lock to
   458 // allow initial definer to complete the class definition
   459 // and to avoid deadlock
   460 // Reclaim classloader lock object with same original recursion count
   461 // Must release SystemDictionary_lock after notify, since
   462 // class loader lock must be claimed before SystemDictionary_lock
   463 // to prevent deadlocks
   464 //
   465 // The notify allows applications that did an untimed wait() on
   466 // the classloader object lock to not hang.
   467 void SystemDictionary::double_lock_wait(Handle lockObject, TRAPS) {
   468   assert_lock_strong(SystemDictionary_lock);
   470   bool calledholdinglock
   471       = ObjectSynchronizer::current_thread_holds_lock((JavaThread*)THREAD, lockObject);
   472   assert(calledholdinglock,"must hold lock for notify");
   473   assert((!(lockObject() == _system_loader_lock_obj) && !is_parallelCapable(lockObject)), "unexpected double_lock_wait");
   474   ObjectSynchronizer::notifyall(lockObject, THREAD);
   475   intptr_t recursions =  ObjectSynchronizer::complete_exit(lockObject, THREAD);
   476   SystemDictionary_lock->wait();
   477   SystemDictionary_lock->unlock();
   478   ObjectSynchronizer::reenter(lockObject, recursions, THREAD);
   479   SystemDictionary_lock->lock();
   480 }
   482 // If the class in is in the placeholder table, class loading is in progress
   483 // For cases where the application changes threads to load classes, it
   484 // is critical to ClassCircularity detection that we try loading
   485 // the superclass on the same thread internally, so we do parallel
   486 // super class loading here.
   487 // This also is critical in cases where the original thread gets stalled
   488 // even in non-circularity situations.
   489 // Note: only one thread can define the class, but multiple can resolve
   490 // Note: must call resolve_super_or_fail even if null super -
   491 // to force placeholder entry creation for this class for circularity detection
   492 // Caller must check for pending exception
   493 // Returns non-null Klass* if other thread has completed load
   494 // and we are done,
   495 // If return null Klass* and no pending exception, the caller must load the class
   496 instanceKlassHandle SystemDictionary::handle_parallel_super_load(
   497     Symbol* name, Symbol* superclassname, Handle class_loader,
   498     Handle protection_domain, Handle lockObject, TRAPS) {
   500   instanceKlassHandle nh = instanceKlassHandle(); // null Handle
   501   ClassLoaderData* loader_data = class_loader_data(class_loader);
   502   unsigned int d_hash = dictionary()->compute_hash(name, loader_data);
   503   int d_index = dictionary()->hash_to_index(d_hash);
   504   unsigned int p_hash = placeholders()->compute_hash(name, loader_data);
   505   int p_index = placeholders()->hash_to_index(p_hash);
   507   // superk is not used, resolve_super called for circularity check only
   508   // This code is reached in two situations. One if this thread
   509   // is loading the same class twice (e.g. ClassCircularity, or
   510   // java.lang.instrument).
   511   // The second is if another thread started the resolve_super first
   512   // and has not yet finished.
   513   // In both cases the original caller will clean up the placeholder
   514   // entry on error.
   515   Klass* superk = SystemDictionary::resolve_super_or_fail(name,
   516                                                           superclassname,
   517                                                           class_loader,
   518                                                           protection_domain,
   519                                                           true,
   520                                                           CHECK_(nh));
   521   // We don't redefine the class, so we just need to clean up if there
   522   // was not an error (don't want to modify any system dictionary
   523   // data structures).
   524   {
   525     MutexLocker mu(SystemDictionary_lock, THREAD);
   526     placeholders()->find_and_remove(p_index, p_hash, name, loader_data, THREAD);
   527     SystemDictionary_lock->notify_all();
   528   }
   530   // parallelCapable class loaders do NOT wait for parallel superclass loads to complete
   531   // Serial class loaders and bootstrap classloader do wait for superclass loads
   532  if (!class_loader.is_null() && is_parallelCapable(class_loader)) {
   533     MutexLocker mu(SystemDictionary_lock, THREAD);
   534     // Check if classloading completed while we were loading superclass or waiting
   535     Klass* check = find_class(d_index, d_hash, name, loader_data);
   536     if (check != NULL) {
   537       // Klass is already loaded, so just return it
   538       return(instanceKlassHandle(THREAD, check));
   539     } else {
   540       return nh;
   541     }
   542   }
   544   // must loop to both handle other placeholder updates
   545   // and spurious notifications
   546   bool super_load_in_progress = true;
   547   PlaceholderEntry* placeholder;
   548   while (super_load_in_progress) {
   549     MutexLocker mu(SystemDictionary_lock, THREAD);
   550     // Check if classloading completed while we were loading superclass or waiting
   551     Klass* check = find_class(d_index, d_hash, name, loader_data);
   552     if (check != NULL) {
   553       // Klass is already loaded, so just return it
   554       return(instanceKlassHandle(THREAD, check));
   555     } else {
   556       placeholder = placeholders()->get_entry(p_index, p_hash, name, loader_data);
   557       if (placeholder && placeholder->super_load_in_progress() ){
   558         // Before UnsyncloadClass:
   559         // We only get here if the application has released the
   560         // classloader lock when another thread was in the middle of loading a
   561         // superclass/superinterface for this class, and now
   562         // this thread is also trying to load this class.
   563         // To minimize surprises, the first thread that started to
   564         // load a class should be the one to complete the loading
   565         // with the classfile it initially expected.
   566         // This logic has the current thread wait once it has done
   567         // all the superclass/superinterface loading it can, until
   568         // the original thread completes the class loading or fails
   569         // If it completes we will use the resulting InstanceKlass
   570         // which we will find below in the systemDictionary.
   571         // We also get here for parallel bootstrap classloader
   572         if (class_loader.is_null()) {
   573           SystemDictionary_lock->wait();
   574         } else {
   575           double_lock_wait(lockObject, THREAD);
   576         }
   577       } else {
   578         // If not in SD and not in PH, other thread's load must have failed
   579         super_load_in_progress = false;
   580       }
   581     }
   582   }
   583   return (nh);
   584 }
   587 Klass* SystemDictionary::resolve_instance_class_or_null(Symbol* name, Handle class_loader, Handle protection_domain, TRAPS) {
   588   assert(name != NULL && !FieldType::is_array(name) &&
   589          !FieldType::is_obj(name), "invalid class name");
   591   // UseNewReflection
   592   // Fix for 4474172; see evaluation for more details
   593   class_loader = Handle(THREAD, java_lang_ClassLoader::non_reflection_class_loader(class_loader()));
   594   ClassLoaderData *loader_data = register_loader(class_loader);
   596   // Do lookup to see if class already exist and the protection domain
   597   // has the right access
   598   unsigned int d_hash = dictionary()->compute_hash(name, loader_data);
   599   int d_index = dictionary()->hash_to_index(d_hash);
   600   Klass* probe = dictionary()->find(d_index, d_hash, name, loader_data,
   601                                       protection_domain, THREAD);
   602   if (probe != NULL) return probe;
   605   // Non-bootstrap class loaders will call out to class loader and
   606   // define via jvm/jni_DefineClass which will acquire the
   607   // class loader object lock to protect against multiple threads
   608   // defining the class in parallel by accident.
   609   // This lock must be acquired here so the waiter will find
   610   // any successful result in the SystemDictionary and not attempt
   611   // the define
   612   // ParallelCapable Classloaders and the bootstrap classloader,
   613   // or all classloaders with UnsyncloadClass do not acquire lock here
   614   bool DoObjectLock = true;
   615   if (is_parallelCapable(class_loader)) {
   616     DoObjectLock = false;
   617   }
   619   unsigned int p_hash = placeholders()->compute_hash(name, loader_data);
   620   int p_index = placeholders()->hash_to_index(p_hash);
   622   // Class is not in SystemDictionary so we have to do loading.
   623   // Make sure we are synchronized on the class loader before we proceed
   624   Handle lockObject = compute_loader_lock_object(class_loader, THREAD);
   625   check_loader_lock_contention(lockObject, THREAD);
   626   ObjectLocker ol(lockObject, THREAD, DoObjectLock);
   628   // Check again (after locking) if class already exist in SystemDictionary
   629   bool class_has_been_loaded   = false;
   630   bool super_load_in_progress  = false;
   631   bool havesupername = false;
   632   instanceKlassHandle k;
   633   PlaceholderEntry* placeholder;
   634   Symbol* superclassname = NULL;
   636   {
   637     MutexLocker mu(SystemDictionary_lock, THREAD);
   638     Klass* check = find_class(d_index, d_hash, name, loader_data);
   639     if (check != NULL) {
   640       // Klass is already loaded, so just return it
   641       class_has_been_loaded = true;
   642       k = instanceKlassHandle(THREAD, check);
   643     } else {
   644       placeholder = placeholders()->get_entry(p_index, p_hash, name, loader_data);
   645       if (placeholder && placeholder->super_load_in_progress()) {
   646          super_load_in_progress = true;
   647          if (placeholder->havesupername() == true) {
   648            superclassname = placeholder->supername();
   649            havesupername = true;
   650          }
   651       }
   652     }
   653   }
   655   // If the class in is in the placeholder table, class loading is in progress
   656   if (super_load_in_progress && havesupername==true) {
   657     k = SystemDictionary::handle_parallel_super_load(name, superclassname,
   658         class_loader, protection_domain, lockObject, THREAD);
   659     if (HAS_PENDING_EXCEPTION) {
   660       return NULL;
   661     }
   662     if (!k.is_null()) {
   663       class_has_been_loaded = true;
   664     }
   665   }
   667   if (!class_has_been_loaded) {
   669     // add placeholder entry to record loading instance class
   670     // Five cases:
   671     // All cases need to prevent modifying bootclasssearchpath
   672     // in parallel with a classload of same classname
   673     // Redefineclasses uses existence of the placeholder for the duration
   674     // of the class load to prevent concurrent redefinition of not completely
   675     // defined classes.
   676     // case 1. traditional classloaders that rely on the classloader object lock
   677     //   - no other need for LOAD_INSTANCE
   678     // case 2. traditional classloaders that break the classloader object lock
   679     //    as a deadlock workaround. Detection of this case requires that
   680     //    this check is done while holding the classloader object lock,
   681     //    and that lock is still held when calling classloader's loadClass.
   682     //    For these classloaders, we ensure that the first requestor
   683     //    completes the load and other requestors wait for completion.
   684     // case 3. UnsyncloadClass - don't use objectLocker
   685     //    With this flag, we allow parallel classloading of a
   686     //    class/classloader pair
   687     // case4. Bootstrap classloader - don't own objectLocker
   688     //    This classloader supports parallelism at the classloader level,
   689     //    but only allows a single load of a class/classloader pair.
   690     //    No performance benefit and no deadlock issues.
   691     // case 5. parallelCapable user level classloaders - without objectLocker
   692     //    Allow parallel classloading of a class/classloader pair
   693     bool throw_circularity_error = false;
   694     {
   695       MutexLocker mu(SystemDictionary_lock, THREAD);
   696       if (class_loader.is_null() || !is_parallelCapable(class_loader)) {
   697         PlaceholderEntry* oldprobe = placeholders()->get_entry(p_index, p_hash, name, loader_data);
   698         if (oldprobe) {
   699           // only need check_seen_thread once, not on each loop
   700           // 6341374 java/lang/Instrument with -Xcomp
   701           if (oldprobe->check_seen_thread(THREAD, PlaceholderTable::LOAD_INSTANCE)) {
   702             throw_circularity_error = true;
   703           } else {
   704             // case 1: traditional: should never see load_in_progress.
   705             while (!class_has_been_loaded && oldprobe && oldprobe->instance_load_in_progress()) {
   707               // case 4: bootstrap classloader: prevent futile classloading,
   708               // wait on first requestor
   709               if (class_loader.is_null()) {
   710                 SystemDictionary_lock->wait();
   711               } else {
   712               // case 2: traditional with broken classloader lock. wait on first
   713               // requestor.
   714                 double_lock_wait(lockObject, THREAD);
   715               }
   716               // Check if classloading completed while we were waiting
   717               Klass* check = find_class(d_index, d_hash, name, loader_data);
   718               if (check != NULL) {
   719                 // Klass is already loaded, so just return it
   720                 k = instanceKlassHandle(THREAD, check);
   721                 class_has_been_loaded = true;
   722               }
   723               // check if other thread failed to load and cleaned up
   724               oldprobe = placeholders()->get_entry(p_index, p_hash, name, loader_data);
   725             }
   726           }
   727         }
   728       }
   729       // All cases: add LOAD_INSTANCE
   730       // case 3: UnsyncloadClass || case 5: parallelCapable: allow competing threads to try
   731       // LOAD_INSTANCE in parallel
   732       // add placeholder entry even if error - callers will remove on error
   733       if (!throw_circularity_error && !class_has_been_loaded) {
   734         PlaceholderEntry* newprobe = placeholders()->find_and_add(p_index, p_hash, name, loader_data, PlaceholderTable::LOAD_INSTANCE, NULL, THREAD);
   735         // For class loaders that do not acquire the classloader object lock,
   736         // if they did not catch another thread holding LOAD_INSTANCE,
   737         // need a check analogous to the acquire ObjectLocker/find_class
   738         // i.e. now that we hold the LOAD_INSTANCE token on loading this class/CL
   739         // one final check if the load has already completed
   740         // class loaders holding the ObjectLock shouldn't find the class here
   741         Klass* check = find_class(d_index, d_hash, name, loader_data);
   742         if (check != NULL) {
   743         // Klass is already loaded, so just return it
   744           k = instanceKlassHandle(THREAD, check);
   745           class_has_been_loaded = true;
   746           newprobe->remove_seen_thread(THREAD, PlaceholderTable::LOAD_INSTANCE);
   747           placeholders()->find_and_remove(p_index, p_hash, name, loader_data, THREAD);
   748           SystemDictionary_lock->notify_all();
   749         }
   750       }
   751     }
   752     // must throw error outside of owning lock
   753     if (throw_circularity_error) {
   754       ResourceMark rm(THREAD);
   755       THROW_MSG_0(vmSymbols::java_lang_ClassCircularityError(), name->as_C_string());
   756     }
   758     if (!class_has_been_loaded) {
   760       // Do actual loading
   761       k = load_instance_class(name, class_loader, THREAD);
   763       // For UnsyncloadClass only
   764       // If they got a linkageError, check if a parallel class load succeeded.
   765       // If it did, then for bytecode resolution the specification requires
   766       // that we return the same result we did for the other thread, i.e. the
   767       // successfully loaded InstanceKlass
   768       // Should not get here for classloaders that support parallelism
   769       // with the new cleaner mechanism, even with AllowParallelDefineClass
   770       // Bootstrap goes through here to allow for an extra guarantee check
   771       if (UnsyncloadClass || (class_loader.is_null())) {
   772         if (k.is_null() && HAS_PENDING_EXCEPTION
   773           && PENDING_EXCEPTION->is_a(SystemDictionary::LinkageError_klass())) {
   774           MutexLocker mu(SystemDictionary_lock, THREAD);
   775           Klass* check = find_class(d_index, d_hash, name, loader_data);
   776           if (check != NULL) {
   777             // Klass is already loaded, so just use it
   778             k = instanceKlassHandle(THREAD, check);
   779             CLEAR_PENDING_EXCEPTION;
   780             guarantee((!class_loader.is_null()), "dup definition for bootstrap loader?");
   781           }
   782         }
   783       }
   785       // clean up placeholder entries for success or error
   786       // This cleans up LOAD_INSTANCE entries
   787       // It also cleans up LOAD_SUPER entries on errors from
   788       // calling load_instance_class
   789       {
   790         MutexLocker mu(SystemDictionary_lock, THREAD);
   791         PlaceholderEntry* probe = placeholders()->get_entry(p_index, p_hash, name, loader_data);
   792         if (probe != NULL) {
   793           probe->remove_seen_thread(THREAD, PlaceholderTable::LOAD_INSTANCE);
   794           placeholders()->find_and_remove(p_index, p_hash, name, loader_data, THREAD);
   795           SystemDictionary_lock->notify_all();
   796         }
   797       }
   799       // If everything was OK (no exceptions, no null return value), and
   800       // class_loader is NOT the defining loader, do a little more bookkeeping.
   801       if (!HAS_PENDING_EXCEPTION && !k.is_null() &&
   802         k->class_loader() != class_loader()) {
   804         check_constraints(d_index, d_hash, k, class_loader, false, THREAD);
   806         // Need to check for a PENDING_EXCEPTION again; check_constraints
   807         // can throw and doesn't use the CHECK macro.
   808         if (!HAS_PENDING_EXCEPTION) {
   809           { // Grabbing the Compile_lock prevents systemDictionary updates
   810             // during compilations.
   811             MutexLocker mu(Compile_lock, THREAD);
   812             update_dictionary(d_index, d_hash, p_index, p_hash,
   813                             k, class_loader, THREAD);
   814           }
   815           if (JvmtiExport::should_post_class_load()) {
   816             Thread *thread = THREAD;
   817             assert(thread->is_Java_thread(), "thread->is_Java_thread()");
   818             JvmtiExport::post_class_load((JavaThread *) thread, k());
   819           }
   820         }
   821       }
   822       if (HAS_PENDING_EXCEPTION || k.is_null()) {
   823         // On error, clean up placeholders
   824         {
   825           MutexLocker mu(SystemDictionary_lock, THREAD);
   826           placeholders()->find_and_remove(p_index, p_hash, name, loader_data, THREAD);
   827           SystemDictionary_lock->notify_all();
   828         }
   829         return NULL;
   830       }
   831     }
   832   }
   834 #ifdef ASSERT
   835   {
   836     ClassLoaderData* loader_data = k->class_loader_data();
   837     MutexLocker mu(SystemDictionary_lock, THREAD);
   838     Klass* kk = find_class(name, loader_data);
   839     assert(kk == k(), "should be present in dictionary");
   840   }
   841 #endif
   843   // return if the protection domain in NULL
   844   if (protection_domain() == NULL) return k();
   846   // Check the protection domain has the right access
   847   {
   848     MutexLocker mu(SystemDictionary_lock, THREAD);
   849     // Note that we have an entry, and entries can be deleted only during GC,
   850     // so we cannot allow GC to occur while we're holding this entry.
   851     // We're using a No_Safepoint_Verifier to catch any place where we
   852     // might potentially do a GC at all.
   853     // SystemDictionary::do_unloading() asserts that classes are only
   854     // unloaded at a safepoint.
   855     No_Safepoint_Verifier nosafepoint;
   856     if (dictionary()->is_valid_protection_domain(d_index, d_hash, name,
   857                                                  loader_data,
   858                                                  protection_domain)) {
   859       return k();
   860     }
   861   }
   863   // Verify protection domain. If it fails an exception is thrown
   864   validate_protection_domain(k, class_loader, protection_domain, CHECK_NULL);
   866   return k();
   867 }
   870 // This routine does not lock the system dictionary.
   871 //
   872 // Since readers don't hold a lock, we must make sure that system
   873 // dictionary entries are only removed at a safepoint (when only one
   874 // thread is running), and are added to in a safe way (all links must
   875 // be updated in an MT-safe manner).
   876 //
   877 // Callers should be aware that an entry could be added just after
   878 // _dictionary->bucket(index) is read here, so the caller will not see
   879 // the new entry.
   881 Klass* SystemDictionary::find(Symbol* class_name,
   882                                 Handle class_loader,
   883                                 Handle protection_domain,
   884                                 TRAPS) {
   886   // UseNewReflection
   887   // The result of this call should be consistent with the result
   888   // of the call to resolve_instance_class_or_null().
   889   // See evaluation 6790209 and 4474172 for more details.
   890   class_loader = Handle(THREAD, java_lang_ClassLoader::non_reflection_class_loader(class_loader()));
   891   ClassLoaderData* loader_data = register_loader(class_loader);
   893   unsigned int d_hash = dictionary()->compute_hash(class_name, loader_data);
   894   int d_index = dictionary()->hash_to_index(d_hash);
   896   {
   897     // Note that we have an entry, and entries can be deleted only during GC,
   898     // so we cannot allow GC to occur while we're holding this entry.
   899     // We're using a No_Safepoint_Verifier to catch any place where we
   900     // might potentially do a GC at all.
   901     // SystemDictionary::do_unloading() asserts that classes are only
   902     // unloaded at a safepoint.
   903     No_Safepoint_Verifier nosafepoint;
   904     return dictionary()->find(d_index, d_hash, class_name, loader_data,
   905                               protection_domain, THREAD);
   906   }
   907 }
   910 // Look for a loaded instance or array klass by name.  Do not do any loading.
   911 // return NULL in case of error.
   912 Klass* SystemDictionary::find_instance_or_array_klass(Symbol* class_name,
   913                                                       Handle class_loader,
   914                                                       Handle protection_domain,
   915                                                       TRAPS) {
   916   Klass* k = NULL;
   917   assert(class_name != NULL, "class name must be non NULL");
   919   if (FieldType::is_array(class_name)) {
   920     // The name refers to an array.  Parse the name.
   921     // dimension and object_key in FieldArrayInfo are assigned as a
   922     // side-effect of this call
   923     FieldArrayInfo fd;
   924     BasicType t = FieldType::get_array_info(class_name, fd, CHECK_(NULL));
   925     if (t != T_OBJECT) {
   926       k = Universe::typeArrayKlassObj(t);
   927     } else {
   928       k = SystemDictionary::find(fd.object_key(), class_loader, protection_domain, THREAD);
   929     }
   930     if (k != NULL) {
   931       k = Klass::cast(k)->array_klass_or_null(fd.dimension());
   932     }
   933   } else {
   934     k = find(class_name, class_loader, protection_domain, THREAD);
   935   }
   936   return k;
   937 }
   939 // Note: this method is much like resolve_from_stream, but
   940 // updates no supplemental data structures.
   941 // TODO consolidate the two methods with a helper routine?
   942 Klass* SystemDictionary::parse_stream(Symbol* class_name,
   943                                       Handle class_loader,
   944                                       Handle protection_domain,
   945                                       ClassFileStream* st,
   946                                       KlassHandle host_klass,
   947                                       GrowableArray<Handle>* cp_patches,
   948                                       TRAPS) {
   949   TempNewSymbol parsed_name = NULL;
   951   // Parse the stream. Note that we do this even though this klass might
   952   // already be present in the SystemDictionary, otherwise we would not
   953   // throw potential ClassFormatErrors.
   954   //
   955   // Note: "name" is updated.
   956   // Further note:  a placeholder will be added for this class when
   957   //   super classes are loaded (resolve_super_or_fail). We expect this
   958   //   to be called for all classes but java.lang.Object; and we preload
   959   //   java.lang.Object through resolve_or_fail, not this path.
   961   instanceKlassHandle k = ClassFileParser(st).parseClassFile(class_name,
   962                                                              class_loader,
   963                                                              protection_domain,
   964                                                              host_klass,
   965                                                              cp_patches,
   966                                                              parsed_name,
   967                                                              true,
   968                                                              THREAD);
   970   // We don't redefine the class, so we just need to clean up whether there
   971   // was an error or not (don't want to modify any system dictionary
   972   // data structures).
   973   // Parsed name could be null if we threw an error before we got far
   974   // enough along to parse it -- in that case, there is nothing to clean up.
   975   if (parsed_name != NULL) {
   976     ClassLoaderData* loader_data = class_loader_data(class_loader);
   978     unsigned int p_hash = placeholders()->compute_hash(parsed_name,
   979                                                        loader_data);
   980     int p_index = placeholders()->hash_to_index(p_hash);
   981     {
   982     MutexLocker mu(SystemDictionary_lock, THREAD);
   983     placeholders()->find_and_remove(p_index, p_hash, parsed_name, loader_data, THREAD);
   984     SystemDictionary_lock->notify_all();
   985     }
   986   }
   988   if (host_klass.not_null() && k.not_null()) {
   989     assert(EnableInvokeDynamic, "");
   990     // If it's anonymous, initialize it now, since nobody else will.
   991     k->class_loader_data()->record_dependency(host_klass(), CHECK_NULL);
   992     k->set_host_klass(host_klass());
   994     {
   995       MutexLocker mu_r(Compile_lock, THREAD);
   997       // Add to class hierarchy, initialize vtables, and do possible
   998       // deoptimizations.
   999       add_to_hierarchy(k, CHECK_NULL); // No exception, but can block
  1001       // But, do not add to system dictionary.
  1004     // Rewrite and patch constant pool here.
  1005     k->link_class(THREAD);
  1006     if (cp_patches != NULL) {
  1007       k->constants()->patch_resolved_references(cp_patches);
  1009     k->eager_initialize(THREAD);
  1011     // notify jvmti
  1012     if (JvmtiExport::should_post_class_load()) {
  1013         assert(THREAD->is_Java_thread(), "thread->is_Java_thread()");
  1014         JvmtiExport::post_class_load((JavaThread *) THREAD, k());
  1017   assert(host_klass.not_null() || cp_patches == NULL,
  1018          "cp_patches only found with host_klass");
  1020   return k();
  1023 // Add a klass to the system from a stream (called by jni_DefineClass and
  1024 // JVM_DefineClass).
  1025 // Note: class_name can be NULL. In that case we do not know the name of
  1026 // the class until we have parsed the stream.
  1028 Klass* SystemDictionary::resolve_from_stream(Symbol* class_name,
  1029                                              Handle class_loader,
  1030                                              Handle protection_domain,
  1031                                              ClassFileStream* st,
  1032                                              bool verify,
  1033                                              TRAPS) {
  1035   // Classloaders that support parallelism, e.g. bootstrap classloader,
  1036   // or all classloaders with UnsyncloadClass do not acquire lock here
  1037   bool DoObjectLock = true;
  1038   if (is_parallelCapable(class_loader)) {
  1039     DoObjectLock = false;
  1042   ClassLoaderData* loader_data = register_loader(class_loader);
  1044   // Make sure we are synchronized on the class loader before we proceed
  1045   Handle lockObject = compute_loader_lock_object(class_loader, THREAD);
  1046   check_loader_lock_contention(lockObject, THREAD);
  1047   ObjectLocker ol(lockObject, THREAD, DoObjectLock);
  1049   TempNewSymbol parsed_name = NULL;
  1051   // Parse the stream. Note that we do this even though this klass might
  1052   // already be present in the SystemDictionary, otherwise we would not
  1053   // throw potential ClassFormatErrors.
  1054   //
  1055   // Note: "name" is updated.
  1056   // Further note:  a placeholder will be added for this class when
  1057   //   super classes are loaded (resolve_super_or_fail). We expect this
  1058   //   to be called for all classes but java.lang.Object; and we preload
  1059   //   java.lang.Object through resolve_or_fail, not this path.
  1061   instanceKlassHandle k = ClassFileParser(st).parseClassFile(class_name,
  1062                                                              class_loader,
  1063                                                              protection_domain,
  1064                                                              parsed_name,
  1065                                                              verify,
  1066                                                              THREAD);
  1068   const char* pkg = "java/";
  1069   if (!HAS_PENDING_EXCEPTION &&
  1070       !class_loader.is_null() &&
  1071       parsed_name != NULL &&
  1072       !strncmp((const char*)parsed_name->bytes(), pkg, strlen(pkg))) {
  1073     // It is illegal to define classes in the "java." package from
  1074     // JVM_DefineClass or jni_DefineClass unless you're the bootclassloader
  1075     ResourceMark rm(THREAD);
  1076     char* name = parsed_name->as_C_string();
  1077     char* index = strrchr(name, '/');
  1078     *index = '\0'; // chop to just the package name
  1079     while ((index = strchr(name, '/')) != NULL) {
  1080       *index = '.'; // replace '/' with '.' in package name
  1082     const char* fmt = "Prohibited package name: %s";
  1083     size_t len = strlen(fmt) + strlen(name);
  1084     char* message = NEW_RESOURCE_ARRAY(char, len);
  1085     jio_snprintf(message, len, fmt, name);
  1086     Exceptions::_throw_msg(THREAD_AND_LOCATION,
  1087       vmSymbols::java_lang_SecurityException(), message);
  1090   if (!HAS_PENDING_EXCEPTION) {
  1091     assert(parsed_name != NULL, "Sanity");
  1092     assert(class_name == NULL || class_name == parsed_name, "name mismatch");
  1093     // Verification prevents us from creating names with dots in them, this
  1094     // asserts that that's the case.
  1095     assert(is_internal_format(parsed_name),
  1096            "external class name format used internally");
  1098     // Add class just loaded
  1099     // If a class loader supports parallel classloading handle parallel define requests
  1100     // find_or_define_instance_class may return a different InstanceKlass
  1101     if (is_parallelCapable(class_loader)) {
  1102       k = find_or_define_instance_class(class_name, class_loader, k, THREAD);
  1103     } else {
  1104       define_instance_class(k, THREAD);
  1108   // If parsing the class file or define_instance_class failed, we
  1109   // need to remove the placeholder added on our behalf. But we
  1110   // must make sure parsed_name is valid first (it won't be if we had
  1111   // a format error before the class was parsed far enough to
  1112   // find the name).
  1113   if (HAS_PENDING_EXCEPTION && parsed_name != NULL) {
  1114     unsigned int p_hash = placeholders()->compute_hash(parsed_name,
  1115                                                        loader_data);
  1116     int p_index = placeholders()->hash_to_index(p_hash);
  1118     MutexLocker mu(SystemDictionary_lock, THREAD);
  1119     placeholders()->find_and_remove(p_index, p_hash, parsed_name, loader_data, THREAD);
  1120     SystemDictionary_lock->notify_all();
  1122     return NULL;
  1125   // Make sure that we didn't leave a place holder in the
  1126   // SystemDictionary; this is only done on success
  1127   debug_only( {
  1128     if (!HAS_PENDING_EXCEPTION) {
  1129       assert(parsed_name != NULL, "parsed_name is still null?");
  1130       Symbol*  h_name    = k->name();
  1131       ClassLoaderData *defining_loader_data = k->class_loader_data();
  1133       MutexLocker mu(SystemDictionary_lock, THREAD);
  1135       Klass* check = find_class(parsed_name, loader_data);
  1136       assert(check == k(), "should be present in the dictionary");
  1138       Klass* check2 = find_class(h_name, defining_loader_data);
  1139       assert(check == check2, "name inconsistancy in SystemDictionary");
  1141   } );
  1143   return k();
  1147 void SystemDictionary::set_shared_dictionary(HashtableBucket<mtClass>* t, int length,
  1148                                              int number_of_entries) {
  1149   assert(length == _nof_buckets * sizeof(HashtableBucket<mtClass>),
  1150          "bad shared dictionary size.");
  1151   _shared_dictionary = new Dictionary(_nof_buckets, t, number_of_entries);
  1155 // If there is a shared dictionary, then find the entry for the
  1156 // given shared system class, if any.
  1158 Klass* SystemDictionary::find_shared_class(Symbol* class_name) {
  1159   if (shared_dictionary() != NULL) {
  1160     unsigned int d_hash = shared_dictionary()->compute_hash(class_name, NULL);
  1161     int d_index = shared_dictionary()->hash_to_index(d_hash);
  1163     return shared_dictionary()->find_shared_class(d_index, d_hash, class_name);
  1164   } else {
  1165     return NULL;
  1170 // Load a class from the shared spaces (found through the shared system
  1171 // dictionary).  Force the superclass and all interfaces to be loaded.
  1172 // Update the class definition to include sibling classes and no
  1173 // subclasses (yet).  [Classes in the shared space are not part of the
  1174 // object hierarchy until loaded.]
  1176 instanceKlassHandle SystemDictionary::load_shared_class(
  1177                  Symbol* class_name, Handle class_loader, TRAPS) {
  1178   instanceKlassHandle ik (THREAD, find_shared_class(class_name));
  1179   return load_shared_class(ik, class_loader, THREAD);
  1182 // Note well!  Changes to this method may affect oop access order
  1183 // in the shared archive.  Please take care to not make changes that
  1184 // adversely affect cold start time by changing the oop access order
  1185 // that is specified in dump.cpp MarkAndMoveOrderedReadOnly and
  1186 // MarkAndMoveOrderedReadWrite closures.
  1187 instanceKlassHandle SystemDictionary::load_shared_class(
  1188                  instanceKlassHandle ik, Handle class_loader, TRAPS) {
  1189   assert(class_loader.is_null(), "non-null classloader for shared class?");
  1190   if (ik.not_null()) {
  1191     instanceKlassHandle nh = instanceKlassHandle(); // null Handle
  1192     Symbol*  class_name = ik->name();
  1194     // Found the class, now load the superclass and interfaces.  If they
  1195     // are shared, add them to the main system dictionary and reset
  1196     // their hierarchy references (supers, subs, and interfaces).
  1198     if (ik->super() != NULL) {
  1199       Symbol*  cn = ik->super()->name();
  1200       resolve_super_or_fail(class_name, cn,
  1201                             class_loader, Handle(), true, CHECK_(nh));
  1204     Array<Klass*>* interfaces = ik->local_interfaces();
  1205     int num_interfaces = interfaces->length();
  1206     for (int index = 0; index < num_interfaces; index++) {
  1207       Klass* k = interfaces->at(index);
  1209       // Note: can not use InstanceKlass::cast here because
  1210       // interfaces' InstanceKlass's C++ vtbls haven't been
  1211       // reinitialized yet (they will be once the interface classes
  1212       // are loaded)
  1213       Symbol*  name  = k->name();
  1214       resolve_super_or_fail(class_name, name, class_loader, Handle(), false, CHECK_(nh));
  1217     // Adjust methods to recover missing data.  They need addresses for
  1218     // interpreter entry points and their default native method address
  1219     // must be reset.
  1221     // Updating methods must be done under a lock so multiple
  1222     // threads don't update these in parallel
  1223     // Shared classes are all currently loaded by the bootstrap
  1224     // classloader, so this will never cause a deadlock on
  1225     // a custom class loader lock.
  1228       Handle lockObject = compute_loader_lock_object(class_loader, THREAD);
  1229       check_loader_lock_contention(lockObject, THREAD);
  1230       ObjectLocker ol(lockObject, THREAD, true);
  1231       ik->restore_unshareable_info(CHECK_(nh));
  1234     if (TraceClassLoading) {
  1235       ResourceMark rm;
  1236       tty->print("[Loaded %s", ik->external_name());
  1237       tty->print(" from shared objects file");
  1238       tty->print_cr("]");
  1240     // notify a class loaded from shared object
  1241     ClassLoadingService::notify_class_loaded(InstanceKlass::cast(ik()),
  1242                                              true /* shared class */);
  1244   return ik;
  1247 #ifdef KERNEL
  1248 // Some classes on the bootstrap class path haven't been installed on the
  1249 // system yet.  Call the DownloadManager method to make them appear in the
  1250 // bootstrap class path and try again to load the named class.
  1251 // Note that with delegation class loaders all classes in another loader will
  1252 // first try to call this so it'd better be fast!!
  1253 static instanceKlassHandle download_and_retry_class_load(
  1254                                                     Symbol* class_name,
  1255                                                     TRAPS) {
  1257   Klass* dlm = SystemDictionary::DownloadManager_klass();
  1258   instanceKlassHandle nk;
  1260   // If download manager class isn't loaded just return.
  1261   if (dlm == NULL) return nk;
  1263   { HandleMark hm(THREAD);
  1264     ResourceMark rm(THREAD);
  1265     Handle s = java_lang_String::create_from_symbol(class_name, CHECK_(nk));
  1266     Handle class_string = java_lang_String::externalize_classname(s, CHECK_(nk));
  1268     // return value
  1269     JavaValue result(T_OBJECT);
  1271     // Call the DownloadManager.  We assume that it has a lock because
  1272     // multiple classes could be not found and downloaded at the same time.
  1273     // class sun.misc.DownloadManager;
  1274     // public static String getBootClassPathEntryForClass(String className);
  1275     JavaCalls::call_static(&result,
  1276                        KlassHandle(THREAD, dlm),
  1277                        vmSymbols::getBootClassPathEntryForClass_name(),
  1278                        vmSymbols::string_string_signature(),
  1279                        class_string,
  1280                        CHECK_(nk));
  1282     // Get result.string and add to bootclasspath
  1283     assert(result.get_type() == T_OBJECT, "just checking");
  1284     oop obj = (oop) result.get_jobject();
  1285     if (obj == NULL) { return nk; }
  1287     Handle h_obj(THREAD, obj);
  1288     char* new_class_name = java_lang_String::as_platform_dependent_str(h_obj,
  1289                                                                   CHECK_(nk));
  1291     // lock the loader
  1292     // we use this lock because JVMTI does.
  1293     Handle loader_lock(THREAD, SystemDictionary::system_loader_lock());
  1295     ObjectLocker ol(loader_lock, THREAD);
  1296     // add the file to the bootclasspath
  1297     ClassLoader::update_class_path_entry_list(new_class_name, true);
  1298   } // end HandleMark
  1300   if (TraceClassLoading) {
  1301     ClassLoader::print_bootclasspath();
  1303   return ClassLoader::load_classfile(class_name, CHECK_(nk));
  1305 #endif // KERNEL
  1308 instanceKlassHandle SystemDictionary::load_instance_class(Symbol* class_name, Handle class_loader, TRAPS) {
  1309   instanceKlassHandle nh = instanceKlassHandle(); // null Handle
  1310   if (class_loader.is_null()) {
  1312     // Search the shared system dictionary for classes preloaded into the
  1313     // shared spaces.
  1314     instanceKlassHandle k;
  1316       PerfTraceTime vmtimer(ClassLoader::perf_shared_classload_time());
  1317       k = load_shared_class(class_name, class_loader, THREAD);
  1320     if (k.is_null()) {
  1321       // Use VM class loader
  1322       PerfTraceTime vmtimer(ClassLoader::perf_sys_classload_time());
  1323       k = ClassLoader::load_classfile(class_name, CHECK_(nh));
  1326 #ifdef KERNEL
  1327     // If the VM class loader has failed to load the class, call the
  1328     // DownloadManager class to make it magically appear on the classpath
  1329     // and try again.  This is only configured with the Kernel VM.
  1330     if (k.is_null()) {
  1331       k = download_and_retry_class_load(class_name, CHECK_(nh));
  1333 #endif // KERNEL
  1335     // find_or_define_instance_class may return a different InstanceKlass
  1336     if (!k.is_null()) {
  1337       k = find_or_define_instance_class(class_name, class_loader, k, CHECK_(nh));
  1339     return k;
  1340   } else {
  1341     // Use user specified class loader to load class. Call loadClass operation on class_loader.
  1342     ResourceMark rm(THREAD);
  1344     assert(THREAD->is_Java_thread(), "must be a JavaThread");
  1345     JavaThread* jt = (JavaThread*) THREAD;
  1347     PerfClassTraceTime vmtimer(ClassLoader::perf_app_classload_time(),
  1348                                ClassLoader::perf_app_classload_selftime(),
  1349                                ClassLoader::perf_app_classload_count(),
  1350                                jt->get_thread_stat()->perf_recursion_counts_addr(),
  1351                                jt->get_thread_stat()->perf_timers_addr(),
  1352                                PerfClassTraceTime::CLASS_LOAD);
  1354     Handle s = java_lang_String::create_from_symbol(class_name, CHECK_(nh));
  1355     // Translate to external class name format, i.e., convert '/' chars to '.'
  1356     Handle string = java_lang_String::externalize_classname(s, CHECK_(nh));
  1358     JavaValue result(T_OBJECT);
  1360     KlassHandle spec_klass (THREAD, SystemDictionary::ClassLoader_klass());
  1362     // Call public unsynchronized loadClass(String) directly for all class loaders
  1363     // for parallelCapable class loaders. JDK >=7, loadClass(String, boolean) will
  1364     // acquire a class-name based lock rather than the class loader object lock.
  1365     // JDK < 7 already acquire the class loader lock in loadClass(String, boolean),
  1366     // so the call to loadClassInternal() was not required.
  1367     //
  1368     // UnsyncloadClass flag means both call loadClass(String) and do
  1369     // not acquire the class loader lock even for class loaders that are
  1370     // not parallelCapable. This was a risky transitional
  1371     // flag for diagnostic purposes only. It is risky to call
  1372     // custom class loaders without synchronization.
  1373     // WARNING If a custom class loader does NOT synchronizer findClass, or callers of
  1374     // findClass, the UnsyncloadClass flag risks unexpected timing bugs in the field.
  1375     // Do NOT assume this will be supported in future releases.
  1376     //
  1377     // Added MustCallLoadClassInternal in case we discover in the field
  1378     // a customer that counts on this call
  1379     if (MustCallLoadClassInternal && has_loadClassInternal()) {
  1380       JavaCalls::call_special(&result,
  1381                               class_loader,
  1382                               spec_klass,
  1383                               vmSymbols::loadClassInternal_name(),
  1384                               vmSymbols::string_class_signature(),
  1385                               string,
  1386                               CHECK_(nh));
  1387     } else {
  1388       JavaCalls::call_virtual(&result,
  1389                               class_loader,
  1390                               spec_klass,
  1391                               vmSymbols::loadClass_name(),
  1392                               vmSymbols::string_class_signature(),
  1393                               string,
  1394                               CHECK_(nh));
  1397     assert(result.get_type() == T_OBJECT, "just checking");
  1398     oop obj = (oop) result.get_jobject();
  1400     // Primitive classes return null since forName() can not be
  1401     // used to obtain any of the Class objects representing primitives or void
  1402     if ((obj != NULL) && !(java_lang_Class::is_primitive(obj))) {
  1403       instanceKlassHandle k =
  1404                 instanceKlassHandle(THREAD, java_lang_Class::as_Klass(obj));
  1405       // For user defined Java class loaders, check that the name returned is
  1406       // the same as that requested.  This check is done for the bootstrap
  1407       // loader when parsing the class file.
  1408       if (class_name == k->name()) {
  1409         return k;
  1412     // Class is not found or has the wrong name, return NULL
  1413     return nh;
  1417 void SystemDictionary::define_instance_class(instanceKlassHandle k, TRAPS) {
  1419   ClassLoaderData* loader_data = k->class_loader_data();
  1420   Handle class_loader_h(THREAD, loader_data->class_loader());
  1422   for (uintx it = 0; it < GCExpandToAllocateDelayMillis; it++){}
  1424  // for bootstrap and other parallel classloaders don't acquire lock,
  1425  // use placeholder token
  1426  // If a parallelCapable class loader calls define_instance_class instead of
  1427  // find_or_define_instance_class to get here, we have a timing
  1428  // hole with systemDictionary updates and check_constraints
  1429  if (!class_loader_h.is_null() && !is_parallelCapable(class_loader_h)) {
  1430     assert(ObjectSynchronizer::current_thread_holds_lock((JavaThread*)THREAD,
  1431          compute_loader_lock_object(class_loader_h, THREAD)),
  1432          "define called without lock");
  1435   // Check class-loading constraints. Throw exception if violation is detected.
  1436   // Grabs and releases SystemDictionary_lock
  1437   // The check_constraints/find_class call and update_dictionary sequence
  1438   // must be "atomic" for a specific class/classloader pair so we never
  1439   // define two different instanceKlasses for that class/classloader pair.
  1440   // Existing classloaders will call define_instance_class with the
  1441   // classloader lock held
  1442   // Parallel classloaders will call find_or_define_instance_class
  1443   // which will require a token to perform the define class
  1444   Symbol*  name_h = k->name();
  1445   unsigned int d_hash = dictionary()->compute_hash(name_h, loader_data);
  1446   int d_index = dictionary()->hash_to_index(d_hash);
  1447   check_constraints(d_index, d_hash, k, class_loader_h, true, CHECK);
  1449   // Register class just loaded with class loader (placed in Vector)
  1450   // Note we do this before updating the dictionary, as this can
  1451   // fail with an OutOfMemoryError (if it does, we will *not* put this
  1452   // class in the dictionary and will not update the class hierarchy).
  1453   // JVMTI FollowReferences needs to find the classes this way.
  1454   if (k->class_loader() != NULL) {
  1455     methodHandle m(THREAD, Universe::loader_addClass_method());
  1456     JavaValue result(T_VOID);
  1457     JavaCallArguments args(class_loader_h);
  1458     args.push_oop(Handle(THREAD, k->java_mirror()));
  1459     JavaCalls::call(&result, m, &args, CHECK);
  1462   // Add the new class. We need recompile lock during update of CHA.
  1464     unsigned int p_hash = placeholders()->compute_hash(name_h, loader_data);
  1465     int p_index = placeholders()->hash_to_index(p_hash);
  1467     MutexLocker mu_r(Compile_lock, THREAD);
  1469     // Add to class hierarchy, initialize vtables, and do possible
  1470     // deoptimizations.
  1471     add_to_hierarchy(k, CHECK); // No exception, but can block
  1473     // Add to systemDictionary - so other classes can see it.
  1474     // Grabs and releases SystemDictionary_lock
  1475     update_dictionary(d_index, d_hash, p_index, p_hash,
  1476                       k, class_loader_h, THREAD);
  1478   k->eager_initialize(THREAD);
  1480   // notify jvmti
  1481   if (JvmtiExport::should_post_class_load()) {
  1482       assert(THREAD->is_Java_thread(), "thread->is_Java_thread()");
  1483       JvmtiExport::post_class_load((JavaThread *) THREAD, k());
  1488 // Support parallel classloading
  1489 // All parallel class loaders, including bootstrap classloader
  1490 // lock a placeholder entry for this class/class_loader pair
  1491 // to allow parallel defines of different classes for this class loader
  1492 // With AllowParallelDefine flag==true, in case they do not synchronize around
  1493 // FindLoadedClass/DefineClass, calls, we check for parallel
  1494 // loading for them, wait if a defineClass is in progress
  1495 // and return the initial requestor's results
  1496 // This flag does not apply to the bootstrap classloader.
  1497 // With AllowParallelDefine flag==false, call through to define_instance_class
  1498 // which will throw LinkageError: duplicate class definition.
  1499 // False is the requested default.
  1500 // For better performance, the class loaders should synchronize
  1501 // findClass(), i.e. FindLoadedClass/DefineClassIfAbsent or they
  1502 // potentially waste time reading and parsing the bytestream.
  1503 // Note: VM callers should ensure consistency of k/class_name,class_loader
  1504 instanceKlassHandle SystemDictionary::find_or_define_instance_class(Symbol* class_name, Handle class_loader, instanceKlassHandle k, TRAPS) {
  1506   instanceKlassHandle nh = instanceKlassHandle(); // null Handle
  1507   Symbol*  name_h = k->name(); // passed in class_name may be null
  1508   ClassLoaderData* loader_data = class_loader_data(class_loader);
  1510   unsigned int d_hash = dictionary()->compute_hash(name_h, loader_data);
  1511   int d_index = dictionary()->hash_to_index(d_hash);
  1513 // Hold SD lock around find_class and placeholder creation for DEFINE_CLASS
  1514   unsigned int p_hash = placeholders()->compute_hash(name_h, loader_data);
  1515   int p_index = placeholders()->hash_to_index(p_hash);
  1516   PlaceholderEntry* probe;
  1519     MutexLocker mu(SystemDictionary_lock, THREAD);
  1520     // First check if class already defined
  1521     if (UnsyncloadClass || (is_parallelDefine(class_loader))) {
  1522       Klass* check = find_class(d_index, d_hash, name_h, loader_data);
  1523       if (check != NULL) {
  1524         return(instanceKlassHandle(THREAD, check));
  1528     // Acquire define token for this class/classloader
  1529     probe = placeholders()->find_and_add(p_index, p_hash, name_h, loader_data, PlaceholderTable::DEFINE_CLASS, NULL, THREAD);
  1530     // Wait if another thread defining in parallel
  1531     // All threads wait - even those that will throw duplicate class: otherwise
  1532     // caller is surprised by LinkageError: duplicate, but findLoadedClass fails
  1533     // if other thread has not finished updating dictionary
  1534     while (probe->definer() != NULL) {
  1535       SystemDictionary_lock->wait();
  1537     // Only special cases allow parallel defines and can use other thread's results
  1538     // Other cases fall through, and may run into duplicate defines
  1539     // caught by finding an entry in the SystemDictionary
  1540     if ((UnsyncloadClass || is_parallelDefine(class_loader)) && (probe->InstanceKlass() != NULL)) {
  1541         probe->remove_seen_thread(THREAD, PlaceholderTable::DEFINE_CLASS);
  1542         placeholders()->find_and_remove(p_index, p_hash, name_h, loader_data, THREAD);
  1543         SystemDictionary_lock->notify_all();
  1544 #ifdef ASSERT
  1545         Klass* check = find_class(d_index, d_hash, name_h, loader_data);
  1546         assert(check != NULL, "definer missed recording success");
  1547 #endif
  1548         return(instanceKlassHandle(THREAD, probe->InstanceKlass()));
  1549     } else {
  1550       // This thread will define the class (even if earlier thread tried and had an error)
  1551       probe->set_definer(THREAD);
  1555   define_instance_class(k, THREAD);
  1557   Handle linkage_exception = Handle(); // null handle
  1559   // definer must notify any waiting threads
  1561     MutexLocker mu(SystemDictionary_lock, THREAD);
  1562     PlaceholderEntry* probe = placeholders()->get_entry(p_index, p_hash, name_h, loader_data);
  1563     assert(probe != NULL, "DEFINE_CLASS placeholder lost?");
  1564     if (probe != NULL) {
  1565       if (HAS_PENDING_EXCEPTION) {
  1566         linkage_exception = Handle(THREAD,PENDING_EXCEPTION);
  1567         CLEAR_PENDING_EXCEPTION;
  1568       } else {
  1569         probe->set_instanceKlass(k());
  1571       probe->set_definer(NULL);
  1572       probe->remove_seen_thread(THREAD, PlaceholderTable::DEFINE_CLASS);
  1573       placeholders()->find_and_remove(p_index, p_hash, name_h, loader_data, THREAD);
  1574       SystemDictionary_lock->notify_all();
  1578   // Can't throw exception while holding lock due to rank ordering
  1579   if (linkage_exception() != NULL) {
  1580     THROW_OOP_(linkage_exception(), nh); // throws exception and returns
  1583   return k;
  1585 Handle SystemDictionary::compute_loader_lock_object(Handle class_loader, TRAPS) {
  1586   // If class_loader is NULL we synchronize on _system_loader_lock_obj
  1587   if (class_loader.is_null()) {
  1588     return Handle(THREAD, _system_loader_lock_obj);
  1589   } else {
  1590     return class_loader;
  1594 // This method is added to check how often we have to wait to grab loader
  1595 // lock. The results are being recorded in the performance counters defined in
  1596 // ClassLoader::_sync_systemLoaderLockContentionRate and
  1597 // ClassLoader::_sync_nonSystemLoaderLockConteionRate.
  1598 void SystemDictionary::check_loader_lock_contention(Handle loader_lock, TRAPS) {
  1599   if (!UsePerfData) {
  1600     return;
  1603   assert(!loader_lock.is_null(), "NULL lock object");
  1605   if (ObjectSynchronizer::query_lock_ownership((JavaThread*)THREAD, loader_lock)
  1606       == ObjectSynchronizer::owner_other) {
  1607     // contention will likely happen, so increment the corresponding
  1608     // contention counter.
  1609     if (loader_lock() == _system_loader_lock_obj) {
  1610       ClassLoader::sync_systemLoaderLockContentionRate()->inc();
  1611     } else {
  1612       ClassLoader::sync_nonSystemLoaderLockContentionRate()->inc();
  1617 // ----------------------------------------------------------------------------
  1618 // Lookup
  1620 Klass* SystemDictionary::find_class(int index, unsigned int hash,
  1621                                       Symbol* class_name,
  1622                                       ClassLoaderData* loader_data) {
  1623   assert_locked_or_safepoint(SystemDictionary_lock);
  1624   assert (index == dictionary()->index_for(class_name, loader_data),
  1625           "incorrect index?");
  1627   Klass* k = dictionary()->find_class(index, hash, class_name, loader_data);
  1628   return k;
  1632 // Basic find on classes in the midst of being loaded
  1633 Symbol* SystemDictionary::find_placeholder(Symbol* class_name,
  1634                                            ClassLoaderData* loader_data) {
  1635   assert_locked_or_safepoint(SystemDictionary_lock);
  1636   unsigned int p_hash = placeholders()->compute_hash(class_name, loader_data);
  1637   int p_index = placeholders()->hash_to_index(p_hash);
  1638   return placeholders()->find_entry(p_index, p_hash, class_name, loader_data);
  1642 // Used for assertions and verification only
  1643 Klass* SystemDictionary::find_class(Symbol* class_name, ClassLoaderData* loader_data) {
  1644   #ifndef ASSERT
  1645   guarantee(VerifyBeforeGC   ||
  1646             VerifyDuringGC   ||
  1647             VerifyBeforeExit ||
  1648             VerifyAfterGC, "too expensive");
  1649   #endif
  1650   assert_locked_or_safepoint(SystemDictionary_lock);
  1652   // First look in the loaded class array
  1653   unsigned int d_hash = dictionary()->compute_hash(class_name, loader_data);
  1654   int d_index = dictionary()->hash_to_index(d_hash);
  1655   return find_class(d_index, d_hash, class_name, loader_data);
  1659 // Get the next class in the diictionary.
  1660 Klass* SystemDictionary::try_get_next_class() {
  1661   return dictionary()->try_get_next_class();
  1665 // ----------------------------------------------------------------------------
  1666 // Update hierachy. This is done before the new klass has been added to the SystemDictionary. The Recompile_lock
  1667 // is held, to ensure that the compiler is not using the class hierachy, and that deoptimization will kick in
  1668 // before a new class is used.
  1670 void SystemDictionary::add_to_hierarchy(instanceKlassHandle k, TRAPS) {
  1671   assert(k.not_null(), "just checking");
  1672   assert_locked_or_safepoint(Compile_lock);
  1674   // Link into hierachy. Make sure the vtables are initialized before linking into
  1675   k->append_to_sibling_list();                    // add to superklass/sibling list
  1676   k->process_interfaces(THREAD);                  // handle all "implements" declarations
  1677   k->set_init_state(InstanceKlass::loaded);
  1678   // Now flush all code that depended on old class hierarchy.
  1679   // Note: must be done *after* linking k into the hierarchy (was bug 12/9/97)
  1680   // Also, first reinitialize vtable because it may have gotten out of synch
  1681   // while the new class wasn't connected to the class hierarchy.
  1682   Universe::flush_dependents_on(k);
  1686 // ----------------------------------------------------------------------------
  1687 // GC support
  1689 // Following roots during mark-sweep is separated in two phases.
  1690 //
  1691 // The first phase follows preloaded classes and all other system
  1692 // classes, since these will never get unloaded anyway.
  1693 //
  1694 // The second phase removes (unloads) unreachable classes from the
  1695 // system dictionary and follows the remaining classes' contents.
  1697 void SystemDictionary::always_strong_oops_do(OopClosure* blk) {
  1698   blk->do_oop(&_java_system_loader);
  1699   blk->do_oop(&_system_loader_lock_obj);
  1701   dictionary()->always_strong_oops_do(blk);
  1704 void SystemDictionary::always_strong_classes_do(KlassClosure* closure) {
  1705   // Follow all system classes and temporary placeholders in dictionary
  1706   dictionary()->always_strong_classes_do(closure);
  1708   // Placeholders. These represent classes we're actively loading.
  1709   placeholders()->classes_do(closure);
  1712 // Calculate a "good" systemdictionary size based
  1713 // on predicted or current loaded classes count
  1714 int SystemDictionary::calculate_systemdictionary_size(int classcount) {
  1715   int newsize = _old_default_sdsize;
  1716   if ((classcount > 0)  && !DumpSharedSpaces) {
  1717     int desiredsize = classcount/_average_depth_goal;
  1718     for (newsize = _primelist[_sdgeneration]; _sdgeneration < _prime_array_size -1;
  1719          newsize = _primelist[++_sdgeneration]) {
  1720       if (desiredsize <=  newsize) {
  1721         break;
  1725   return newsize;
  1727 bool SystemDictionary::do_unloading(BoolObjectClosure* is_alive) {
  1728   // First, mark for unload all ClassLoaderData referencing a dead class loader.
  1729   bool has_dead_loaders = ClassLoaderDataGraph::do_unloading(is_alive);
  1730   bool unloading_occurred = false;
  1731   if (has_dead_loaders) {
  1732     unloading_occurred = dictionary()->do_unloading();
  1733     constraints()->purge_loader_constraints();
  1734     resolution_errors()->purge_resolution_errors();
  1736   return unloading_occurred;
  1739 void SystemDictionary::oops_do(OopClosure* f) {
  1740   f->do_oop(&_java_system_loader);
  1741   f->do_oop(&_system_loader_lock_obj);
  1743   // Adjust dictionary
  1744   dictionary()->oops_do(f);
  1746   // Visit extra methods
  1747   invoke_method_table()->oops_do(f);
  1750 // Extended Class redefinition support.
  1751 // If one of these classes is replaced, we need to replace it in these places.
  1752 // KlassClosure::do_klass should take the address of a class but we can
  1753 // change that later.
  1754 void SystemDictionary::preloaded_classes_do(KlassClosure* f) {
  1755   for (int k = (int)FIRST_WKID; k < (int)WKID_LIMIT; k++) {
  1756     f->do_klass(_well_known_klasses[k]);
  1760     for (int i = 0; i < T_VOID+1; i++) {
  1761       if (_box_klasses[i] != NULL) {
  1762         assert(i >= T_BOOLEAN, "checking");
  1763         f->do_klass(_box_klasses[i]);
  1768   FilteredFieldsMap::classes_do(f);
  1771 void SystemDictionary::lazily_loaded_classes_do(KlassClosure* f) {
  1772   f->do_klass(_abstract_ownable_synchronizer_klass);
  1775 // Just the classes from defining class loaders
  1776 // Don't iterate over placeholders
  1777 void SystemDictionary::classes_do(void f(Klass*)) {
  1778   dictionary()->classes_do(f);
  1781 // Added for initialize_itable_for_klass
  1782 //   Just the classes from defining class loaders
  1783 // Don't iterate over placeholders
  1784 void SystemDictionary::classes_do(void f(Klass*, TRAPS), TRAPS) {
  1785   dictionary()->classes_do(f, CHECK);
  1788 //   All classes, and their class loaders
  1789 // Don't iterate over placeholders
  1790 void SystemDictionary::classes_do(void f(Klass*, ClassLoaderData*)) {
  1791   dictionary()->classes_do(f);
  1794 //   All classes, and their class loaders
  1795 //   (added for helpers that use HandleMarks and ResourceMarks)
  1796 // Don't iterate over placeholders
  1797 void SystemDictionary::classes_do(void f(Klass*, ClassLoaderData*, TRAPS), TRAPS) {
  1798   dictionary()->classes_do(f, CHECK);
  1801 void SystemDictionary::placeholders_do(void f(Symbol*)) {
  1802   placeholders()->entries_do(f);
  1805 void SystemDictionary::methods_do(void f(Method*)) {
  1806   dictionary()->methods_do(f);
  1807   invoke_method_table()->methods_do(f);
  1810 // ----------------------------------------------------------------------------
  1811 // Lazily load klasses
  1813 void SystemDictionary::load_abstract_ownable_synchronizer_klass(TRAPS) {
  1814   assert(JDK_Version::is_gte_jdk16x_version(), "Must be JDK 1.6 or later");
  1816   // if multiple threads calling this function, only one thread will load
  1817   // the class.  The other threads will find the loaded version once the
  1818   // class is loaded.
  1819   Klass* aos = _abstract_ownable_synchronizer_klass;
  1820   if (aos == NULL) {
  1821     Klass* k = resolve_or_fail(vmSymbols::java_util_concurrent_locks_AbstractOwnableSynchronizer(), true, CHECK);
  1822     // Force a fence to prevent any read before the write completes
  1823     OrderAccess::fence();
  1824     _abstract_ownable_synchronizer_klass = k;
  1828 // ----------------------------------------------------------------------------
  1829 // Initialization
  1831 void SystemDictionary::initialize(TRAPS) {
  1832   // Allocate arrays
  1833   assert(dictionary() == NULL,
  1834          "SystemDictionary should only be initialized once");
  1835   _sdgeneration        = 0;
  1836   _dictionary          = new Dictionary(calculate_systemdictionary_size(PredictedLoadedClassCount));
  1837   _placeholders        = new PlaceholderTable(_nof_buckets);
  1838   _number_of_modifications = 0;
  1839   _loader_constraints  = new LoaderConstraintTable(_loader_constraint_size);
  1840   _resolution_errors   = new ResolutionErrorTable(_resolution_error_size);
  1841   _invoke_method_table = new SymbolPropertyTable(_invoke_method_size);
  1843   // Allocate private object used as system class loader lock
  1844   _system_loader_lock_obj = oopFactory::new_intArray(0, CHECK);
  1845   // Initialize basic classes
  1846   initialize_preloaded_classes(CHECK);
  1849 // Compact table of directions on the initialization of klasses:
  1850 static const short wk_init_info[] = {
  1851   #define WK_KLASS_INIT_INFO(name, symbol, option) \
  1852     ( ((int)vmSymbols::VM_SYMBOL_ENUM_NAME(symbol) \
  1853           << SystemDictionary::CEIL_LG_OPTION_LIMIT) \
  1854       | (int)SystemDictionary::option ),
  1855   WK_KLASSES_DO(WK_KLASS_INIT_INFO)
  1856   #undef WK_KLASS_INIT_INFO
  1858 };
  1860 bool SystemDictionary::initialize_wk_klass(WKID id, int init_opt, TRAPS) {
  1861   assert(id >= (int)FIRST_WKID && id < (int)WKID_LIMIT, "oob");
  1862   int  info = wk_init_info[id - FIRST_WKID];
  1863   int  sid  = (info >> CEIL_LG_OPTION_LIMIT);
  1864   Symbol* symbol = vmSymbols::symbol_at((vmSymbols::SID)sid);
  1865   Klass**    klassp = &_well_known_klasses[id];
  1866   bool must_load = (init_opt < SystemDictionary::Opt);
  1867   bool try_load  = true;
  1868   if (init_opt == SystemDictionary::Opt_Kernel) {
  1869 #ifndef KERNEL
  1870     try_load = false;
  1871 #endif //KERNEL
  1873   if ((*klassp) == NULL && try_load) {
  1874     if (must_load) {
  1875       (*klassp) = resolve_or_fail(symbol, true, CHECK_0); // load required class
  1876     } else {
  1877       (*klassp) = resolve_or_null(symbol,       CHECK_0); // load optional klass
  1880   return ((*klassp) != NULL);
  1883 void SystemDictionary::initialize_wk_klasses_until(WKID limit_id, WKID &start_id, TRAPS) {
  1884   assert((int)start_id <= (int)limit_id, "IDs are out of order!");
  1885   for (int id = (int)start_id; id < (int)limit_id; id++) {
  1886     assert(id >= (int)FIRST_WKID && id < (int)WKID_LIMIT, "oob");
  1887     int info = wk_init_info[id - FIRST_WKID];
  1888     int sid  = (info >> CEIL_LG_OPTION_LIMIT);
  1889     int opt  = (info & right_n_bits(CEIL_LG_OPTION_LIMIT));
  1891     initialize_wk_klass((WKID)id, opt, CHECK);
  1894   // move the starting value forward to the limit:
  1895   start_id = limit_id;
  1898 void SystemDictionary::initialize_preloaded_classes(TRAPS) {
  1899   assert(WK_KLASS(Object_klass) == NULL, "preloaded classes should only be initialized once");
  1900   // Preload commonly used klasses
  1901   WKID scan = FIRST_WKID;
  1902   // first do Object, then String, Class
  1903   if (UseSharedSpaces) {
  1904     initialize_wk_klasses_through(WK_KLASS_ENUM_NAME(Object_klass), scan, CHECK);
  1905     // Initialize the constant pool for the Object_class
  1906     InstanceKlass* ik = InstanceKlass::cast(Object_klass());
  1907     ik->constants()->restore_unshareable_info(CHECK);
  1908     initialize_wk_klasses_through(WK_KLASS_ENUM_NAME(Class_klass), scan, CHECK);
  1909   } else {
  1910     initialize_wk_klasses_through(WK_KLASS_ENUM_NAME(Class_klass), scan, CHECK);
  1913   // Calculate offsets for String and Class classes since they are loaded and
  1914   // can be used after this point.
  1915   java_lang_String::compute_offsets();
  1916   java_lang_Class::compute_offsets();
  1918   // Fixup mirrors for classes loaded before java.lang.Class.
  1919   // These calls iterate over the objects currently in the perm gen
  1920   // so calling them at this point is matters (not before when there
  1921   // are fewer objects and not later after there are more objects
  1922   // in the perm gen.
  1923   Universe::initialize_basic_type_mirrors(CHECK);
  1924   Universe::fixup_mirrors(CHECK);
  1926   // do a bunch more:
  1927   initialize_wk_klasses_through(WK_KLASS_ENUM_NAME(Reference_klass), scan, CHECK);
  1929   // Preload ref klasses and set reference types
  1930   InstanceKlass::cast(WK_KLASS(Reference_klass))->set_reference_type(REF_OTHER);
  1931   InstanceRefKlass::update_nonstatic_oop_maps(WK_KLASS(Reference_klass));
  1933   initialize_wk_klasses_through(WK_KLASS_ENUM_NAME(PhantomReference_klass), scan, CHECK);
  1934   InstanceKlass::cast(WK_KLASS(SoftReference_klass))->set_reference_type(REF_SOFT);
  1935   InstanceKlass::cast(WK_KLASS(WeakReference_klass))->set_reference_type(REF_WEAK);
  1936   InstanceKlass::cast(WK_KLASS(FinalReference_klass))->set_reference_type(REF_FINAL);
  1937   InstanceKlass::cast(WK_KLASS(PhantomReference_klass))->set_reference_type(REF_PHANTOM);
  1939   // JSR 292 classes
  1940   WKID jsr292_group_start = WK_KLASS_ENUM_NAME(MethodHandle_klass);
  1941   WKID jsr292_group_end   = WK_KLASS_ENUM_NAME(VolatileCallSite_klass);
  1942   initialize_wk_klasses_until(jsr292_group_start, scan, CHECK);
  1943   if (EnableInvokeDynamic) {
  1944     initialize_wk_klasses_through(jsr292_group_end, scan, CHECK);
  1945   } else {
  1946     // Skip the JSR 292 classes, if not enabled.
  1947     scan = WKID(jsr292_group_end + 1);
  1950   initialize_wk_klasses_until(WKID_LIMIT, scan, CHECK);
  1952   _box_klasses[T_BOOLEAN] = WK_KLASS(Boolean_klass);
  1953   _box_klasses[T_CHAR]    = WK_KLASS(Character_klass);
  1954   _box_klasses[T_FLOAT]   = WK_KLASS(Float_klass);
  1955   _box_klasses[T_DOUBLE]  = WK_KLASS(Double_klass);
  1956   _box_klasses[T_BYTE]    = WK_KLASS(Byte_klass);
  1957   _box_klasses[T_SHORT]   = WK_KLASS(Short_klass);
  1958   _box_klasses[T_INT]     = WK_KLASS(Integer_klass);
  1959   _box_klasses[T_LONG]    = WK_KLASS(Long_klass);
  1960   //_box_klasses[T_OBJECT]  = WK_KLASS(object_klass);
  1961   //_box_klasses[T_ARRAY]   = WK_KLASS(object_klass);
  1963 #ifdef KERNEL
  1964   if (DownloadManager_klass() == NULL) {
  1965     warning("Cannot find sun/jkernel/DownloadManager");
  1967 #endif // KERNEL
  1969   { // Compute whether we should use loadClass or loadClassInternal when loading classes.
  1970     Method* method = InstanceKlass::cast(ClassLoader_klass())->find_method(vmSymbols::loadClassInternal_name(), vmSymbols::string_class_signature());
  1971     _has_loadClassInternal = (method != NULL);
  1973   { // Compute whether we should use checkPackageAccess or NOT
  1974     Method* method = InstanceKlass::cast(ClassLoader_klass())->find_method(vmSymbols::checkPackageAccess_name(), vmSymbols::class_protectiondomain_signature());
  1975     _has_checkPackageAccess = (method != NULL);
  1979 // Tells if a given klass is a box (wrapper class, such as java.lang.Integer).
  1980 // If so, returns the basic type it holds.  If not, returns T_OBJECT.
  1981 BasicType SystemDictionary::box_klass_type(Klass* k) {
  1982   assert(k != NULL, "");
  1983   for (int i = T_BOOLEAN; i < T_VOID+1; i++) {
  1984     if (_box_klasses[i] == k)
  1985       return (BasicType)i;
  1987   return T_OBJECT;
  1990 // Constraints on class loaders. The details of the algorithm can be
  1991 // found in the OOPSLA'98 paper "Dynamic Class Loading in the Java
  1992 // Virtual Machine" by Sheng Liang and Gilad Bracha.  The basic idea is
  1993 // that the system dictionary needs to maintain a set of contraints that
  1994 // must be satisfied by all classes in the dictionary.
  1995 // if defining is true, then LinkageError if already in systemDictionary
  1996 // if initiating loader, then ok if InstanceKlass matches existing entry
  1998 void SystemDictionary::check_constraints(int d_index, unsigned int d_hash,
  1999                                          instanceKlassHandle k,
  2000                                          Handle class_loader, bool defining,
  2001                                          TRAPS) {
  2002   const char *linkage_error = NULL;
  2004     Symbol*  name  = k->name();
  2005     ClassLoaderData *loader_data = class_loader_data(class_loader);
  2007     MutexLocker mu(SystemDictionary_lock, THREAD);
  2009     Klass* check = find_class(d_index, d_hash, name, loader_data);
  2010     if (check != (Klass*)NULL) {
  2011       // if different InstanceKlass - duplicate class definition,
  2012       // else - ok, class loaded by a different thread in parallel,
  2013       // we should only have found it if it was done loading and ok to use
  2014       // system dictionary only holds instance classes, placeholders
  2015       // also holds array classes
  2017       assert(check->oop_is_instance(), "noninstance in systemdictionary");
  2018       if ((defining == true) || (k() != check)) {
  2019         linkage_error = "loader (instance of  %s): attempted  duplicate class "
  2020           "definition for name: \"%s\"";
  2021       } else {
  2022         return;
  2026 #ifdef ASSERT
  2027     Symbol* ph_check = find_placeholder(name, loader_data);
  2028     assert(ph_check == NULL || ph_check == name, "invalid symbol");
  2029 #endif
  2031     if (linkage_error == NULL) {
  2032       if (constraints()->check_or_update(k, class_loader, name) == false) {
  2033         linkage_error = "loader constraint violation: loader (instance of %s)"
  2034           " previously initiated loading for a different type with name \"%s\"";
  2039   // Throw error now if needed (cannot throw while holding
  2040   // SystemDictionary_lock because of rank ordering)
  2042   if (linkage_error) {
  2043     ResourceMark rm(THREAD);
  2044     const char* class_loader_name = loader_name(class_loader());
  2045     char* type_name = k->name()->as_C_string();
  2046     size_t buflen = strlen(linkage_error) + strlen(class_loader_name) +
  2047       strlen(type_name);
  2048     char* buf = NEW_RESOURCE_ARRAY_IN_THREAD(THREAD, char, buflen);
  2049     jio_snprintf(buf, buflen, linkage_error, class_loader_name, type_name);
  2050     THROW_MSG(vmSymbols::java_lang_LinkageError(), buf);
  2055 // Update system dictionary - done after check_constraint and add_to_hierachy
  2056 // have been called.
  2057 void SystemDictionary::update_dictionary(int d_index, unsigned int d_hash,
  2058                                          int p_index, unsigned int p_hash,
  2059                                          instanceKlassHandle k,
  2060                                          Handle class_loader,
  2061                                          TRAPS) {
  2062   // Compile_lock prevents systemDictionary updates during compilations
  2063   assert_locked_or_safepoint(Compile_lock);
  2064   Symbol*  name  = k->name();
  2065   ClassLoaderData *loader_data = class_loader_data(class_loader);
  2068   MutexLocker mu1(SystemDictionary_lock, THREAD);
  2070   // See whether biased locking is enabled and if so set it for this
  2071   // klass.
  2072   // Note that this must be done past the last potential blocking
  2073   // point / safepoint. We enable biased locking lazily using a
  2074   // VM_Operation to iterate the SystemDictionary and installing the
  2075   // biasable mark word into each InstanceKlass's prototype header.
  2076   // To avoid race conditions where we accidentally miss enabling the
  2077   // optimization for one class in the process of being added to the
  2078   // dictionary, we must not safepoint after the test of
  2079   // BiasedLocking::enabled().
  2080   if (UseBiasedLocking && BiasedLocking::enabled()) {
  2081     // Set biased locking bit for all loaded classes; it will be
  2082     // cleared if revocation occurs too often for this type
  2083     // NOTE that we must only do this when the class is initally
  2084     // defined, not each time it is referenced from a new class loader
  2085     if (k->class_loader() == class_loader()) {
  2086       k->set_prototype_header(markOopDesc::biased_locking_prototype());
  2090   // Assign a classid if one has not already been assigned.  The
  2091   // counter does not need to be atomically incremented since this
  2092   // is only done while holding the SystemDictionary_lock.
  2093   // All loaded classes get a unique ID.
  2094   TRACE_INIT_ID(k);
  2096   // Check for a placeholder. If there, remove it and make a
  2097   // new system dictionary entry.
  2098   placeholders()->find_and_remove(p_index, p_hash, name, loader_data, THREAD);
  2099   Klass* sd_check = find_class(d_index, d_hash, name, loader_data);
  2100   if (sd_check == NULL) {
  2101     dictionary()->add_klass(name, loader_data, k);
  2102     notice_modification();
  2104 #ifdef ASSERT
  2105   sd_check = find_class(d_index, d_hash, name, loader_data);
  2106   assert (sd_check != NULL, "should have entry in system dictionary");
  2107 // Changed to allow PH to remain to complete class circularity checking
  2108 // while only one thread can define a class at one time, multiple
  2109 // classes can resolve the superclass for a class at one time,
  2110 // and the placeholder is used to track that
  2111 //  Symbol* ph_check = find_placeholder(name, class_loader);
  2112 //  assert (ph_check == NULL, "should not have a placeholder entry");
  2113 #endif
  2114     SystemDictionary_lock->notify_all();
  2119 // Try to find a class name using the loader constraints.  The
  2120 // loader constraints might know about a class that isn't fully loaded
  2121 // yet and these will be ignored.
  2122 Klass* SystemDictionary::find_constrained_instance_or_array_klass(
  2123                     Symbol* class_name, Handle class_loader, TRAPS) {
  2125   // First see if it has been loaded directly.
  2126   // Force the protection domain to be null.  (This removes protection checks.)
  2127   Handle no_protection_domain;
  2128   Klass* klass = find_instance_or_array_klass(class_name, class_loader,
  2129                                               no_protection_domain, CHECK_NULL);
  2130   if (klass != NULL)
  2131     return klass;
  2133   // Now look to see if it has been loaded elsewhere, and is subject to
  2134   // a loader constraint that would require this loader to return the
  2135   // klass that is already loaded.
  2136   if (FieldType::is_array(class_name)) {
  2137     // For array classes, their Klass*s are not kept in the
  2138     // constraint table. The element Klass*s are.
  2139     FieldArrayInfo fd;
  2140     BasicType t = FieldType::get_array_info(class_name, fd, CHECK_(NULL));
  2141     if (t != T_OBJECT) {
  2142       klass = Universe::typeArrayKlassObj(t);
  2143     } else {
  2144       MutexLocker mu(SystemDictionary_lock, THREAD);
  2145       klass = constraints()->find_constrained_klass(fd.object_key(), class_loader);
  2147     // If element class already loaded, allocate array klass
  2148     if (klass != NULL) {
  2149       klass = Klass::cast(klass)->array_klass_or_null(fd.dimension());
  2151   } else {
  2152     MutexLocker mu(SystemDictionary_lock, THREAD);
  2153     // Non-array classes are easy: simply check the constraint table.
  2154     klass = constraints()->find_constrained_klass(class_name, class_loader);
  2157   return klass;
  2161 bool SystemDictionary::add_loader_constraint(Symbol* class_name,
  2162                                              Handle class_loader1,
  2163                                              Handle class_loader2,
  2164                                              Thread* THREAD) {
  2165   ClassLoaderData* loader_data1 = class_loader_data(class_loader1);
  2166   ClassLoaderData* loader_data2 = class_loader_data(class_loader2);
  2168   Symbol* constraint_name = NULL;
  2169   if (!FieldType::is_array(class_name)) {
  2170     constraint_name = class_name;
  2171   } else {
  2172     // For array classes, their Klass*s are not kept in the
  2173     // constraint table. The element classes are.
  2174     FieldArrayInfo fd;
  2175     BasicType t = FieldType::get_array_info(class_name, fd, CHECK_(false));
  2176     // primitive types always pass
  2177     if (t != T_OBJECT) {
  2178       return true;
  2179     } else {
  2180       constraint_name = fd.object_key();
  2183   unsigned int d_hash1 = dictionary()->compute_hash(constraint_name, loader_data1);
  2184   int d_index1 = dictionary()->hash_to_index(d_hash1);
  2186   unsigned int d_hash2 = dictionary()->compute_hash(constraint_name, loader_data2);
  2187   int d_index2 = dictionary()->hash_to_index(d_hash2);
  2189   MutexLocker mu_s(SystemDictionary_lock, THREAD);
  2191   // Better never do a GC while we're holding these oops
  2192   No_Safepoint_Verifier nosafepoint;
  2194   Klass* klass1 = find_class(d_index1, d_hash1, constraint_name, loader_data1);
  2195   Klass* klass2 = find_class(d_index2, d_hash2, constraint_name, loader_data2);
  2196   return constraints()->add_entry(constraint_name, klass1, class_loader1,
  2197                                   klass2, class_loader2);
  2201 // Add entry to resolution error table to record the error when the first
  2202 // attempt to resolve a reference to a class has failed.
  2203 void SystemDictionary::add_resolution_error(constantPoolHandle pool, int which, Symbol* error) {
  2204   unsigned int hash = resolution_errors()->compute_hash(pool, which);
  2205   int index = resolution_errors()->hash_to_index(hash);
  2207     MutexLocker ml(SystemDictionary_lock, Thread::current());
  2208     resolution_errors()->add_entry(index, hash, pool, which, error);
  2212 // Delete a resolution error for RedefineClasses for a constant pool is going away
  2213 void SystemDictionary::delete_resolution_error(ConstantPool* pool) {
  2214   resolution_errors()->delete_entry(pool);
  2217 // Lookup resolution error table. Returns error if found, otherwise NULL.
  2218 Symbol* SystemDictionary::find_resolution_error(constantPoolHandle pool, int which) {
  2219   unsigned int hash = resolution_errors()->compute_hash(pool, which);
  2220   int index = resolution_errors()->hash_to_index(hash);
  2222     MutexLocker ml(SystemDictionary_lock, Thread::current());
  2223     ResolutionErrorEntry* entry = resolution_errors()->find_entry(index, hash, pool, which);
  2224     return (entry != NULL) ? entry->error() : (Symbol*)NULL;
  2229 // Signature constraints ensure that callers and callees agree about
  2230 // the meaning of type names in their signatures.  This routine is the
  2231 // intake for constraints.  It collects them from several places:
  2232 //
  2233 //  * LinkResolver::resolve_method (if check_access is true) requires
  2234 //    that the resolving class (the caller) and the defining class of
  2235 //    the resolved method (the callee) agree on each type in the
  2236 //    method's signature.
  2237 //
  2238 //  * LinkResolver::resolve_interface_method performs exactly the same
  2239 //    checks.
  2240 //
  2241 //  * LinkResolver::resolve_field requires that the constant pool
  2242 //    attempting to link to a field agree with the field's defining
  2243 //    class about the type of the field signature.
  2244 //
  2245 //  * klassVtable::initialize_vtable requires that, when a class
  2246 //    overrides a vtable entry allocated by a superclass, that the
  2247 //    overriding method (i.e., the callee) agree with the superclass
  2248 //    on each type in the method's signature.
  2249 //
  2250 //  * klassItable::initialize_itable requires that, when a class fills
  2251 //    in its itables, for each non-abstract method installed in an
  2252 //    itable, the method (i.e., the callee) agree with the interface
  2253 //    on each type in the method's signature.
  2254 //
  2255 // All those methods have a boolean (check_access, checkconstraints)
  2256 // which turns off the checks.  This is used from specialized contexts
  2257 // such as bootstrapping, dumping, and debugging.
  2258 //
  2259 // No direct constraint is placed between the class and its
  2260 // supertypes.  Constraints are only placed along linked relations
  2261 // between callers and callees.  When a method overrides or implements
  2262 // an abstract method in a supertype (superclass or interface), the
  2263 // constraints are placed as if the supertype were the caller to the
  2264 // overriding method.  (This works well, since callers to the
  2265 // supertype have already established agreement between themselves and
  2266 // the supertype.)  As a result of all this, a class can disagree with
  2267 // its supertype about the meaning of a type name, as long as that
  2268 // class neither calls a relevant method of the supertype, nor is
  2269 // called (perhaps via an override) from the supertype.
  2270 //
  2271 //
  2272 // SystemDictionary::check_signature_loaders(sig, l1, l2)
  2273 //
  2274 // Make sure all class components (including arrays) in the given
  2275 // signature will be resolved to the same class in both loaders.
  2276 // Returns the name of the type that failed a loader constraint check, or
  2277 // NULL if no constraint failed. The returned C string needs cleaning up
  2278 // with a ResourceMark in the caller.  No exception except OOME is thrown.
  2279 // Arrays are not added to the loader constraint table, their elements are.
  2280 char* SystemDictionary::check_signature_loaders(Symbol* signature,
  2281                                                Handle loader1, Handle loader2,
  2282                                                bool is_method, TRAPS)  {
  2283   // Nothing to do if loaders are the same.
  2284   if (loader1() == loader2()) {
  2285     return NULL;
  2288   ResourceMark rm(THREAD);
  2289   SignatureStream sig_strm(signature, is_method);
  2290   while (!sig_strm.is_done()) {
  2291     if (sig_strm.is_object()) {
  2292       Symbol* s = sig_strm.as_symbol(CHECK_NULL);
  2293       Symbol*  sig  = s;
  2294       if (!add_loader_constraint(sig, loader1, loader2, THREAD)) {
  2295         return sig->as_C_string();
  2298     sig_strm.next();
  2300   return NULL;
  2304 methodHandle SystemDictionary::find_method_handle_intrinsic(vmIntrinsics::ID iid,
  2305                                                             Symbol* signature,
  2306                                                             TRAPS) {
  2307   methodHandle empty;
  2308   assert(EnableInvokeDynamic, "");
  2309   assert(MethodHandles::is_signature_polymorphic(iid) &&
  2310          MethodHandles::is_signature_polymorphic_intrinsic(iid) &&
  2311          iid != vmIntrinsics::_invokeGeneric,
  2312          err_msg("must be a known MH intrinsic iid=%d: %s", iid, vmIntrinsics::name_at(iid)));
  2314   unsigned int hash  = invoke_method_table()->compute_hash(signature, iid);
  2315   int          index = invoke_method_table()->hash_to_index(hash);
  2316   SymbolPropertyEntry* spe = invoke_method_table()->find_entry(index, hash, signature, iid);
  2317   methodHandle m;
  2318   if (spe == NULL || spe->method() == NULL) {
  2319     spe = NULL;
  2320     // Must create lots of stuff here, but outside of the SystemDictionary lock.
  2321     m = Method::make_method_handle_intrinsic(iid, signature, CHECK_(empty));
  2322     CompileBroker::compile_method(m, InvocationEntryBci, CompLevel_highest_tier,
  2323                                   methodHandle(), CompileThreshold, "MH", CHECK_(empty));
  2325     // Now grab the lock.  We might have to throw away the new method,
  2326     // if a racing thread has managed to install one at the same time.
  2328       MutexLocker ml(SystemDictionary_lock, THREAD);
  2329       spe = invoke_method_table()->find_entry(index, hash, signature, iid);
  2330       if (spe == NULL)
  2331         spe = invoke_method_table()->add_entry(index, hash, signature, iid);
  2332       if (spe->method() == NULL)
  2333         spe->set_method(m());
  2337   assert(spe != NULL && spe->method() != NULL, "");
  2338   return spe->method();
  2341 // Helper for unpacking the return value from linkMethod and linkCallSite.
  2342 static methodHandle unpack_method_and_appendix(Handle mname,
  2343                                                objArrayHandle appendix_box,
  2344                                                Handle* appendix_result,
  2345                                                TRAPS) {
  2346   methodHandle empty;
  2347   if (mname.not_null()) {
  2348     Metadata* vmtarget = java_lang_invoke_MemberName::vmtarget(mname());
  2349     if (vmtarget != NULL && vmtarget->is_method()) {
  2350       Method* m = (Method*)vmtarget;
  2351       oop appendix = appendix_box->obj_at(0);
  2352       if (TraceMethodHandles) {
  2353     #ifndef PRODUCT
  2354         tty->print("Linked method="INTPTR_FORMAT": ", m);
  2355         m->print();
  2356         if (appendix != NULL) { tty->print("appendix = "); appendix->print(); }
  2357         tty->cr();
  2358     #endif //PRODUCT
  2360       (*appendix_result) = Handle(THREAD, appendix);
  2361       return methodHandle(THREAD, m);
  2364   THROW_MSG_(vmSymbols::java_lang_LinkageError(), "bad value from MethodHandleNatives", empty);
  2365   return empty;
  2368 methodHandle SystemDictionary::find_method_handle_invoker(Symbol* name,
  2369                                                           Symbol* signature,
  2370                                                           KlassHandle accessing_klass,
  2371                                                           Handle *appendix_result,
  2372                                                           Handle *method_type_result,
  2373                                                           TRAPS) {
  2374   methodHandle empty;
  2375   assert(EnableInvokeDynamic, "");
  2376   assert(!THREAD->is_Compiler_thread(), "");
  2377   Handle method_type =
  2378     SystemDictionary::find_method_handle_type(signature, accessing_klass, CHECK_(empty));
  2379   if (false) {  // FIXME: Decide if the Java upcall should resolve signatures.
  2380     method_type = java_lang_String::create_from_symbol(signature, CHECK_(empty));
  2383   KlassHandle  mh_klass = SystemDictionary::MethodHandle_klass();
  2384   int ref_kind = JVM_REF_invokeVirtual;
  2385   Handle name_str = StringTable::intern(name, CHECK_(empty));
  2386   objArrayHandle appendix_box = oopFactory::new_objArray(SystemDictionary::Object_klass(), 1, CHECK_(empty));
  2387   assert(appendix_box->obj_at(0) == NULL, "");
  2389   // call java.lang.invoke.MethodHandleNatives::linkMethod(... String, MethodType) -> MemberName
  2390   JavaCallArguments args;
  2391   args.push_oop(accessing_klass()->java_mirror());
  2392   args.push_int(ref_kind);
  2393   args.push_oop(mh_klass()->java_mirror());
  2394   args.push_oop(name_str());
  2395   args.push_oop(method_type());
  2396   args.push_oop(appendix_box());
  2397   JavaValue result(T_OBJECT);
  2398   JavaCalls::call_static(&result,
  2399                          SystemDictionary::MethodHandleNatives_klass(),
  2400                          vmSymbols::linkMethod_name(),
  2401                          vmSymbols::linkMethod_signature(),
  2402                          &args, CHECK_(empty));
  2403   Handle mname(THREAD, (oop) result.get_jobject());
  2404   (*method_type_result) = method_type;
  2405   return unpack_method_and_appendix(mname, appendix_box, appendix_result, THREAD);
  2409 // Ask Java code to find or construct a java.lang.invoke.MethodType for the given
  2410 // signature, as interpreted relative to the given class loader.
  2411 // Because of class loader constraints, all method handle usage must be
  2412 // consistent with this loader.
  2413 Handle SystemDictionary::find_method_handle_type(Symbol* signature,
  2414                                                  KlassHandle accessing_klass,
  2415                                                  TRAPS) {
  2416   Handle empty;
  2417   vmIntrinsics::ID null_iid = vmIntrinsics::_none;  // distinct from all method handle invoker intrinsics
  2418   unsigned int hash  = invoke_method_table()->compute_hash(signature, null_iid);
  2419   int          index = invoke_method_table()->hash_to_index(hash);
  2420   SymbolPropertyEntry* spe = invoke_method_table()->find_entry(index, hash, signature, null_iid);
  2421   if (spe != NULL && spe->method_type() != NULL) {
  2422     assert(java_lang_invoke_MethodType::is_instance(spe->method_type()), "");
  2423     return Handle(THREAD, spe->method_type());
  2424   } else if (THREAD->is_Compiler_thread()) {
  2425     warning("SystemDictionary::find_method_handle_type called from compiler thread");  // FIXME
  2426     return Handle();  // do not attempt from within compiler, unless it was cached
  2429   Handle class_loader, protection_domain;
  2430   bool is_on_bcp = true;  // keep this true as long as we can materialize from the boot classloader
  2431   int npts = ArgumentCount(signature).size();
  2432   objArrayHandle pts = oopFactory::new_objArray(SystemDictionary::Class_klass(), npts, CHECK_(empty));
  2433   int arg = 0;
  2434   Handle rt;                            // the return type from the signature
  2435   ResourceMark rm(THREAD);
  2436   for (SignatureStream ss(signature); !ss.is_done(); ss.next()) {
  2437     oop mirror = NULL;
  2438     if (is_on_bcp) {
  2439       // Note:  class_loader & protection_domain are both null at this point.
  2440       mirror = ss.as_java_mirror(class_loader, protection_domain,
  2441                                  SignatureStream::ReturnNull, CHECK_(empty));
  2442       if (mirror == NULL) {
  2443         // fall back from BCP to accessing_klass
  2444         if (accessing_klass.not_null()) {
  2445           class_loader      = Handle(THREAD, InstanceKlass::cast(accessing_klass())->class_loader());
  2446           protection_domain = Handle(THREAD, InstanceKlass::cast(accessing_klass())->protection_domain());
  2448         is_on_bcp = false;
  2451     if (!is_on_bcp) {
  2452       // Resolve, throwing a real error if it doesn't work.
  2453       mirror = ss.as_java_mirror(class_loader, protection_domain,
  2454                                  SignatureStream::NCDFError, CHECK_(empty));
  2456     if (ss.at_return_type())
  2457       rt = Handle(THREAD, mirror);
  2458     else
  2459       pts->obj_at_put(arg++, mirror);
  2461     // Check accessibility.
  2462     if (ss.is_object() && accessing_klass.not_null()) {
  2463       Klass* sel_klass = java_lang_Class::as_Klass(mirror);
  2464       mirror = NULL;  // safety
  2465       // Emulate ConstantPool::verify_constant_pool_resolve.
  2466       if (Klass::cast(sel_klass)->oop_is_objArray())
  2467         sel_klass = ObjArrayKlass::cast(sel_klass)->bottom_klass();
  2468       if (Klass::cast(sel_klass)->oop_is_instance()) {
  2469         KlassHandle sel_kh(THREAD, sel_klass);
  2470         LinkResolver::check_klass_accessability(accessing_klass, sel_kh, CHECK_(empty));
  2474   assert(arg == npts, "");
  2476   // call java.lang.invoke.MethodHandleNatives::findMethodType(Class rt, Class[] pts) -> MethodType
  2477   JavaCallArguments args(Handle(THREAD, rt()));
  2478   args.push_oop(pts());
  2479   JavaValue result(T_OBJECT);
  2480   JavaCalls::call_static(&result,
  2481                          SystemDictionary::MethodHandleNatives_klass(),
  2482                          vmSymbols::findMethodHandleType_name(),
  2483                          vmSymbols::findMethodHandleType_signature(),
  2484                          &args, CHECK_(empty));
  2485   Handle method_type(THREAD, (oop) result.get_jobject());
  2487   if (is_on_bcp) {
  2488     // We can cache this MethodType inside the JVM.
  2489     MutexLocker ml(SystemDictionary_lock, THREAD);
  2490     spe = invoke_method_table()->find_entry(index, hash, signature, null_iid);
  2491     if (spe == NULL)
  2492       spe = invoke_method_table()->add_entry(index, hash, signature, null_iid);
  2493     if (spe->method_type() == NULL) {
  2494       spe->set_method_type(method_type());
  2498   // report back to the caller with the MethodType
  2499   return method_type;
  2502 // Ask Java code to find or construct a method handle constant.
  2503 Handle SystemDictionary::link_method_handle_constant(KlassHandle caller,
  2504                                                      int ref_kind, //e.g., JVM_REF_invokeVirtual
  2505                                                      KlassHandle callee,
  2506                                                      Symbol* name_sym,
  2507                                                      Symbol* signature,
  2508                                                      TRAPS) {
  2509   Handle empty;
  2510   Handle name = java_lang_String::create_from_symbol(name_sym, CHECK_(empty));
  2511   Handle type;
  2512   if (signature->utf8_length() > 0 && signature->byte_at(0) == '(') {
  2513     type = find_method_handle_type(signature, caller, CHECK_(empty));
  2514   } else {
  2515     ResourceMark rm(THREAD);
  2516     SignatureStream ss(signature, false);
  2517     if (!ss.is_done()) {
  2518       oop mirror = ss.as_java_mirror(caller->class_loader(), caller->protection_domain(),
  2519                                      SignatureStream::NCDFError, CHECK_(empty));
  2520       type = Handle(THREAD, mirror);
  2521       ss.next();
  2522       if (!ss.is_done())  type = Handle();  // error!
  2525   if (type.is_null()) {
  2526     THROW_MSG_(vmSymbols::java_lang_LinkageError(), "bad signature", empty);
  2529   // call java.lang.invoke.MethodHandleNatives::linkMethodHandleConstant(Class caller, int refKind, Class callee, String name, Object type) -> MethodHandle
  2530   JavaCallArguments args;
  2531   args.push_oop(caller->java_mirror());  // the referring class
  2532   args.push_int(ref_kind);
  2533   args.push_oop(callee->java_mirror());  // the target class
  2534   args.push_oop(name());
  2535   args.push_oop(type());
  2536   JavaValue result(T_OBJECT);
  2537   JavaCalls::call_static(&result,
  2538                          SystemDictionary::MethodHandleNatives_klass(),
  2539                          vmSymbols::linkMethodHandleConstant_name(),
  2540                          vmSymbols::linkMethodHandleConstant_signature(),
  2541                          &args, CHECK_(empty));
  2542   return Handle(THREAD, (oop) result.get_jobject());
  2545 // Ask Java code to find or construct a java.lang.invoke.CallSite for the given
  2546 // name and signature, as interpreted relative to the given class loader.
  2547 methodHandle SystemDictionary::find_dynamic_call_site_invoker(KlassHandle caller,
  2548                                                               Handle bootstrap_specifier,
  2549                                                               Symbol* name,
  2550                                                               Symbol* type,
  2551                                                               Handle *appendix_result,
  2552                                                               Handle *method_type_result,
  2553                                                               TRAPS) {
  2554   methodHandle empty;
  2555   Handle bsm, info;
  2556   if (java_lang_invoke_MethodHandle::is_instance(bootstrap_specifier())) {
  2557     bsm = bootstrap_specifier;
  2558   } else {
  2559     assert(bootstrap_specifier->is_objArray(), "");
  2560     objArrayHandle args(THREAD, (objArrayOop) bootstrap_specifier());
  2561     int len = args->length();
  2562     assert(len >= 1, "");
  2563     bsm = Handle(THREAD, args->obj_at(0));
  2564     if (len > 1) {
  2565       objArrayOop args1 = oopFactory::new_objArray(SystemDictionary::Object_klass(), len-1, CHECK_(empty));
  2566       for (int i = 1; i < len; i++)
  2567         args1->obj_at_put(i-1, args->obj_at(i));
  2568       info = Handle(THREAD, args1);
  2571   guarantee(java_lang_invoke_MethodHandle::is_instance(bsm()),
  2572             "caller must supply a valid BSM");
  2574   Handle method_name = java_lang_String::create_from_symbol(name, CHECK_(empty));
  2575   Handle method_type = find_method_handle_type(type, caller, CHECK_(empty));
  2577   objArrayHandle appendix_box = oopFactory::new_objArray(SystemDictionary::Object_klass(), 1, CHECK_(empty));
  2578   assert(appendix_box->obj_at(0) == NULL, "");
  2580   // call java.lang.invoke.MethodHandleNatives::linkCallSite(caller, bsm, name, mtype, info, &appendix)
  2581   JavaCallArguments args;
  2582   args.push_oop(caller->java_mirror());
  2583   args.push_oop(bsm());
  2584   args.push_oop(method_name());
  2585   args.push_oop(method_type());
  2586   args.push_oop(info());
  2587   args.push_oop(appendix_box);
  2588   JavaValue result(T_OBJECT);
  2589   JavaCalls::call_static(&result,
  2590                          SystemDictionary::MethodHandleNatives_klass(),
  2591                          vmSymbols::linkCallSite_name(),
  2592                          vmSymbols::linkCallSite_signature(),
  2593                          &args, CHECK_(empty));
  2594   Handle mname(THREAD, (oop) result.get_jobject());
  2595   (*method_type_result) = method_type;
  2596   return unpack_method_and_appendix(mname, appendix_box, appendix_result, THREAD);
  2599 // Since the identity hash code for symbols changes when the symbols are
  2600 // moved from the regular perm gen (hash in the mark word) to the shared
  2601 // spaces (hash is the address), the classes loaded into the dictionary
  2602 // may be in the wrong buckets.
  2604 void SystemDictionary::reorder_dictionary() {
  2605   dictionary()->reorder_dictionary();
  2609 void SystemDictionary::copy_buckets(char** top, char* end) {
  2610   dictionary()->copy_buckets(top, end);
  2614 void SystemDictionary::copy_table(char** top, char* end) {
  2615   dictionary()->copy_table(top, end);
  2619 void SystemDictionary::reverse() {
  2620   dictionary()->reverse();
  2623 int SystemDictionary::number_of_classes() {
  2624   return dictionary()->number_of_entries();
  2628 // ----------------------------------------------------------------------------
  2629 #ifndef PRODUCT
  2631 void SystemDictionary::print() {
  2632   dictionary()->print();
  2634   // Placeholders
  2635   GCMutexLocker mu(SystemDictionary_lock);
  2636   placeholders()->print();
  2638   // loader constraints - print under SD_lock
  2639   constraints()->print();
  2642 #endif
  2644 void SystemDictionary::verify() {
  2645   guarantee(dictionary() != NULL, "Verify of system dictionary failed");
  2646   guarantee(constraints() != NULL,
  2647             "Verify of loader constraints failed");
  2648   guarantee(dictionary()->number_of_entries() >= 0 &&
  2649             placeholders()->number_of_entries() >= 0,
  2650             "Verify of system dictionary failed");
  2652   // Verify dictionary
  2653   dictionary()->verify();
  2655   GCMutexLocker mu(SystemDictionary_lock);
  2656   placeholders()->verify();
  2658   // Verify constraint table
  2659   guarantee(constraints() != NULL, "Verify of loader constraints failed");
  2660   constraints()->verify(dictionary(), placeholders());
  2664 void SystemDictionary::verify_obj_klass_present(Symbol* class_name,
  2665                                                 ClassLoaderData* loader_data) {
  2666   GCMutexLocker mu(SystemDictionary_lock);
  2667   Symbol* name;
  2669   Klass* probe = find_class(class_name, loader_data);
  2670   if (probe == NULL) {
  2671     probe = SystemDictionary::find_shared_class(class_name);
  2672     if (probe == NULL) {
  2673       name = find_placeholder(class_name, loader_data);
  2676   guarantee(probe != NULL || name != NULL,
  2677             "Loaded klasses should be in SystemDictionary");
  2680 #ifndef PRODUCT
  2682 // statistics code
  2683 class ClassStatistics: AllStatic {
  2684  private:
  2685   static int nclasses;        // number of classes
  2686   static int nmethods;        // number of methods
  2687   static int nmethoddata;     // number of methodData
  2688   static int class_size;      // size of class objects in words
  2689   static int method_size;     // size of method objects in words
  2690   static int debug_size;      // size of debug info in methods
  2691   static int methoddata_size; // size of methodData objects in words
  2693   static void do_class(Klass* k) {
  2694     nclasses++;
  2695     class_size += k->size();
  2696     if (k->oop_is_instance()) {
  2697       InstanceKlass* ik = (InstanceKlass*)k;
  2698       class_size += ik->methods()->size();
  2699       class_size += ik->constants()->size();
  2700       class_size += ik->local_interfaces()->size();
  2701       class_size += ik->transitive_interfaces()->size();
  2702       // We do not have to count implementors, since we only store one!
  2703       // SSS: How should these be accounted now that they have moved?
  2704       // class_size += ik->fields()->length();
  2708   static void do_method(Method* m) {
  2709     nmethods++;
  2710     method_size += m->size();
  2711     // class loader uses same objArray for empty vectors, so don't count these
  2712     if (m->has_stackmap_table()) {
  2713       method_size += m->stackmap_data()->size();
  2716     MethodData* mdo = m->method_data();
  2717     if (mdo != NULL) {
  2718       nmethoddata++;
  2719       methoddata_size += mdo->size();
  2723  public:
  2724   static void print() {
  2725     SystemDictionary::classes_do(do_class);
  2726     SystemDictionary::methods_do(do_method);
  2727     tty->print_cr("Class statistics:");
  2728     tty->print_cr("%d classes (%d bytes)", nclasses, class_size * oopSize);
  2729     tty->print_cr("%d methods (%d bytes = %d base + %d debug info)", nmethods,
  2730                   (method_size + debug_size) * oopSize, method_size * oopSize, debug_size * oopSize);
  2731     tty->print_cr("%d methoddata (%d bytes)", nmethoddata, methoddata_size * oopSize);
  2733 };
  2736 int ClassStatistics::nclasses        = 0;
  2737 int ClassStatistics::nmethods        = 0;
  2738 int ClassStatistics::nmethoddata     = 0;
  2739 int ClassStatistics::class_size      = 0;
  2740 int ClassStatistics::method_size     = 0;
  2741 int ClassStatistics::debug_size      = 0;
  2742 int ClassStatistics::methoddata_size = 0;
  2744 void SystemDictionary::print_class_statistics() {
  2745   ResourceMark rm;
  2746   ClassStatistics::print();
  2750 class MethodStatistics: AllStatic {
  2751  public:
  2752   enum {
  2753     max_parameter_size = 10
  2754   };
  2755  private:
  2757   static int _number_of_methods;
  2758   static int _number_of_final_methods;
  2759   static int _number_of_static_methods;
  2760   static int _number_of_native_methods;
  2761   static int _number_of_synchronized_methods;
  2762   static int _number_of_profiled_methods;
  2763   static int _number_of_bytecodes;
  2764   static int _parameter_size_profile[max_parameter_size];
  2765   static int _bytecodes_profile[Bytecodes::number_of_java_codes];
  2767   static void initialize() {
  2768     _number_of_methods        = 0;
  2769     _number_of_final_methods  = 0;
  2770     _number_of_static_methods = 0;
  2771     _number_of_native_methods = 0;
  2772     _number_of_synchronized_methods = 0;
  2773     _number_of_profiled_methods = 0;
  2774     _number_of_bytecodes      = 0;
  2775     for (int i = 0; i < max_parameter_size             ; i++) _parameter_size_profile[i] = 0;
  2776     for (int j = 0; j < Bytecodes::number_of_java_codes; j++) _bytecodes_profile     [j] = 0;
  2777   };
  2779   static void do_method(Method* m) {
  2780     _number_of_methods++;
  2781     // collect flag info
  2782     if (m->is_final()       ) _number_of_final_methods++;
  2783     if (m->is_static()      ) _number_of_static_methods++;
  2784     if (m->is_native()      ) _number_of_native_methods++;
  2785     if (m->is_synchronized()) _number_of_synchronized_methods++;
  2786     if (m->method_data() != NULL) _number_of_profiled_methods++;
  2787     // collect parameter size info (add one for receiver, if any)
  2788     _parameter_size_profile[MIN2(m->size_of_parameters() + (m->is_static() ? 0 : 1), max_parameter_size - 1)]++;
  2789     // collect bytecodes info
  2791       Thread *thread = Thread::current();
  2792       HandleMark hm(thread);
  2793       BytecodeStream s(methodHandle(thread, m));
  2794       Bytecodes::Code c;
  2795       while ((c = s.next()) >= 0) {
  2796         _number_of_bytecodes++;
  2797         _bytecodes_profile[c]++;
  2802  public:
  2803   static void print() {
  2804     initialize();
  2805     SystemDictionary::methods_do(do_method);
  2806     // generate output
  2807     tty->cr();
  2808     tty->print_cr("Method statistics (static):");
  2809     // flag distribution
  2810     tty->cr();
  2811     tty->print_cr("%6d final        methods  %6.1f%%", _number_of_final_methods       , _number_of_final_methods        * 100.0F / _number_of_methods);
  2812     tty->print_cr("%6d static       methods  %6.1f%%", _number_of_static_methods      , _number_of_static_methods       * 100.0F / _number_of_methods);
  2813     tty->print_cr("%6d native       methods  %6.1f%%", _number_of_native_methods      , _number_of_native_methods       * 100.0F / _number_of_methods);
  2814     tty->print_cr("%6d synchronized methods  %6.1f%%", _number_of_synchronized_methods, _number_of_synchronized_methods * 100.0F / _number_of_methods);
  2815     tty->print_cr("%6d profiled     methods  %6.1f%%", _number_of_profiled_methods, _number_of_profiled_methods * 100.0F / _number_of_methods);
  2816     // parameter size profile
  2817     tty->cr();
  2818     { int tot = 0;
  2819       int avg = 0;
  2820       for (int i = 0; i < max_parameter_size; i++) {
  2821         int n = _parameter_size_profile[i];
  2822         tot += n;
  2823         avg += n*i;
  2824         tty->print_cr("parameter size = %1d: %6d methods  %5.1f%%", i, n, n * 100.0F / _number_of_methods);
  2826       assert(tot == _number_of_methods, "should be the same");
  2827       tty->print_cr("                    %6d methods  100.0%%", _number_of_methods);
  2828       tty->print_cr("(average parameter size = %3.1f including receiver, if any)", (float)avg / _number_of_methods);
  2830     // bytecodes profile
  2831     tty->cr();
  2832     { int tot = 0;
  2833       for (int i = 0; i < Bytecodes::number_of_java_codes; i++) {
  2834         if (Bytecodes::is_defined(i)) {
  2835           Bytecodes::Code c = Bytecodes::cast(i);
  2836           int n = _bytecodes_profile[c];
  2837           tot += n;
  2838           tty->print_cr("%9d  %7.3f%%  %s", n, n * 100.0F / _number_of_bytecodes, Bytecodes::name(c));
  2841       assert(tot == _number_of_bytecodes, "should be the same");
  2842       tty->print_cr("%9d  100.000%%", _number_of_bytecodes);
  2844     tty->cr();
  2846 };
  2848 int MethodStatistics::_number_of_methods;
  2849 int MethodStatistics::_number_of_final_methods;
  2850 int MethodStatistics::_number_of_static_methods;
  2851 int MethodStatistics::_number_of_native_methods;
  2852 int MethodStatistics::_number_of_synchronized_methods;
  2853 int MethodStatistics::_number_of_profiled_methods;
  2854 int MethodStatistics::_number_of_bytecodes;
  2855 int MethodStatistics::_parameter_size_profile[MethodStatistics::max_parameter_size];
  2856 int MethodStatistics::_bytecodes_profile[Bytecodes::number_of_java_codes];
  2859 void SystemDictionary::print_method_statistics() {
  2860   MethodStatistics::print();
  2863 #endif // PRODUCT

mercurial