src/share/vm/classfile/systemDictionary.cpp

Mon, 12 Aug 2019 18:30:40 +0300

author
apetushkov
date
Mon, 12 Aug 2019 18:30:40 +0300
changeset 9858
b985cbb00e68
parent 9550
270570f695e0
child 9866
41515291559a
permissions
-rw-r--r--

8223147: JFR Backport
8199712: Flight Recorder
8203346: JFR: Inconsistent signature of jfr_add_string_constant
8195817: JFR.stop should require name of recording
8195818: JFR.start should increase autogenerated name by one
8195819: Remove recording=x from jcmd JFR.check output
8203921: JFR thread sampling is missing fixes from JDK-8194552
8203929: Limit amount of data for JFR.dump
8203664: JFR start failure after AppCDS archive created with JFR StartFlightRecording
8003209: JFR events for network utilization
8207392: [PPC64] Implement JFR profiling
8202835: jfr/event/os/TestSystemProcess.java fails on missing events
Summary: Backport JFR from JDK11. Initial integration
Reviewed-by: neugens

     1 /*
     2  * Copyright (c) 1997, 2018, 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 #if INCLUDE_CDS
    34 #include "classfile/sharedClassUtil.hpp"
    35 #include "classfile/systemDictionaryShared.hpp"
    36 #endif
    37 #include "classfile/vmSymbols.hpp"
    38 #include "compiler/compileBroker.hpp"
    39 #include "interpreter/bytecodeStream.hpp"
    40 #include "interpreter/interpreter.hpp"
    41 #include "jfr/jfrEvents.hpp"
    42 #include "memory/filemap.hpp"
    43 #include "memory/gcLocker.hpp"
    44 #include "memory/oopFactory.hpp"
    45 #include "oops/instanceKlass.hpp"
    46 #include "oops/instanceRefKlass.hpp"
    47 #include "oops/klass.inline.hpp"
    48 #include "oops/methodData.hpp"
    49 #include "oops/objArrayKlass.hpp"
    50 #include "oops/oop.inline.hpp"
    51 #include "oops/oop.inline2.hpp"
    52 #include "oops/typeArrayKlass.hpp"
    53 #include "prims/jvmtiEnvBase.hpp"
    54 #include "prims/methodHandles.hpp"
    55 #include "runtime/arguments.hpp"
    56 #include "runtime/biasedLocking.hpp"
    57 #include "runtime/fieldType.hpp"
    58 #include "runtime/handles.inline.hpp"
    59 #include "runtime/java.hpp"
    60 #include "runtime/javaCalls.hpp"
    61 #include "runtime/mutexLocker.hpp"
    62 #include "runtime/orderAccess.inline.hpp"
    63 #include "runtime/signature.hpp"
    64 #include "services/classLoadingService.hpp"
    65 #include "services/threadService.hpp"
    66 #include "utilities/macros.hpp"
    67 #include "utilities/ticks.hpp"
    69 Dictionary*            SystemDictionary::_dictionary          = NULL;
    70 PlaceholderTable*      SystemDictionary::_placeholders        = NULL;
    71 Dictionary*            SystemDictionary::_shared_dictionary   = NULL;
    72 LoaderConstraintTable* SystemDictionary::_loader_constraints  = NULL;
    73 ResolutionErrorTable*  SystemDictionary::_resolution_errors   = NULL;
    74 SymbolPropertyTable*   SystemDictionary::_invoke_method_table = NULL;
    77 int         SystemDictionary::_number_of_modifications = 0;
    78 int         SystemDictionary::_sdgeneration               = 0;
    79 const int   SystemDictionary::_primelist[_prime_array_size] = {1009,2017,4049,5051,10103,
    80               20201,40423,99991};
    82 oop         SystemDictionary::_system_loader_lock_obj     =  NULL;
    84 Klass*      SystemDictionary::_well_known_klasses[SystemDictionary::WKID_LIMIT]
    85                                                           =  { NULL /*, NULL...*/ };
    87 Klass*      SystemDictionary::_box_klasses[T_VOID+1]      =  { NULL /*, NULL...*/ };
    89 oop         SystemDictionary::_java_system_loader         =  NULL;
    91 bool        SystemDictionary::_has_loadClassInternal      =  false;
    92 bool        SystemDictionary::_has_checkPackageAccess     =  false;
    94 // lazily initialized klass variables
    95 Klass* volatile SystemDictionary::_abstract_ownable_synchronizer_klass = NULL;
    98 // ----------------------------------------------------------------------------
    99 // Java-level SystemLoader
   101 oop SystemDictionary::java_system_loader() {
   102   return _java_system_loader;
   103 }
   105 void SystemDictionary::compute_java_system_loader(TRAPS) {
   106   KlassHandle system_klass(THREAD, WK_KLASS(ClassLoader_klass));
   107   JavaValue result(T_OBJECT);
   108   JavaCalls::call_static(&result,
   109                          KlassHandle(THREAD, WK_KLASS(ClassLoader_klass)),
   110                          vmSymbols::getSystemClassLoader_name(),
   111                          vmSymbols::void_classloader_signature(),
   112                          CHECK);
   114   _java_system_loader = (oop)result.get_jobject();
   116   CDS_ONLY(SystemDictionaryShared::initialize(CHECK);)
   117 }
   120 ClassLoaderData* SystemDictionary::register_loader(Handle class_loader, TRAPS) {
   121   if (class_loader() == NULL) return ClassLoaderData::the_null_class_loader_data();
   122   return ClassLoaderDataGraph::find_or_create(class_loader, THREAD);
   123 }
   125 // ----------------------------------------------------------------------------
   126 // debugging
   128 #ifdef ASSERT
   130 // return true if class_name contains no '.' (internal format is '/')
   131 bool SystemDictionary::is_internal_format(Symbol* class_name) {
   132   if (class_name != NULL) {
   133     ResourceMark rm;
   134     char* name = class_name->as_C_string();
   135     return strchr(name, '.') == NULL;
   136   } else {
   137     return true;
   138   }
   139 }
   141 #endif
   143 // ----------------------------------------------------------------------------
   144 // Parallel class loading check
   146 bool SystemDictionary::is_parallelCapable(Handle class_loader) {
   147   if (UnsyncloadClass || class_loader.is_null()) return true;
   148   if (AlwaysLockClassLoader) return false;
   149   return java_lang_ClassLoader::parallelCapable(class_loader());
   150 }
   151 // ----------------------------------------------------------------------------
   152 // ParallelDefineClass flag does not apply to bootclass loader
   153 bool SystemDictionary::is_parallelDefine(Handle class_loader) {
   154    if (class_loader.is_null()) return false;
   155    if (AllowParallelDefineClass && java_lang_ClassLoader::parallelCapable(class_loader())) {
   156      return true;
   157    }
   158    return false;
   159 }
   161 /**
   162  * Returns true if the passed class loader is the extension class loader.
   163  */
   164 bool SystemDictionary::is_ext_class_loader(Handle class_loader) {
   165   if (class_loader.is_null()) {
   166     return false;
   167   }
   168   return (class_loader->klass()->name() == vmSymbols::sun_misc_Launcher_ExtClassLoader());
   169 }
   171 // ----------------------------------------------------------------------------
   172 // Resolving of classes
   174 // Forwards to resolve_or_null
   176 Klass* SystemDictionary::resolve_or_fail(Symbol* class_name, Handle class_loader, Handle protection_domain, bool throw_error, TRAPS) {
   177   Klass* klass = resolve_or_null(class_name, class_loader, protection_domain, THREAD);
   178   if (HAS_PENDING_EXCEPTION || klass == NULL) {
   179     KlassHandle k_h(THREAD, klass);
   180     // can return a null klass
   181     klass = handle_resolution_exception(class_name, class_loader, protection_domain, throw_error, k_h, THREAD);
   182   }
   183   return klass;
   184 }
   186 Klass* SystemDictionary::handle_resolution_exception(Symbol* class_name, Handle class_loader, Handle protection_domain, bool throw_error, KlassHandle klass_h, TRAPS) {
   187   if (HAS_PENDING_EXCEPTION) {
   188     // If we have a pending exception we forward it to the caller, unless throw_error is true,
   189     // in which case we have to check whether the pending exception is a ClassNotFoundException,
   190     // and if so convert it to a NoClassDefFoundError
   191     // And chain the original ClassNotFoundException
   192     if (throw_error && PENDING_EXCEPTION->is_a(SystemDictionary::ClassNotFoundException_klass())) {
   193       ResourceMark rm(THREAD);
   194       assert(klass_h() == NULL, "Should not have result with exception pending");
   195       Handle e(THREAD, PENDING_EXCEPTION);
   196       CLEAR_PENDING_EXCEPTION;
   197       THROW_MSG_CAUSE_NULL(vmSymbols::java_lang_NoClassDefFoundError(), class_name->as_C_string(), e);
   198     } else {
   199       return NULL;
   200     }
   201   }
   202   // Class not found, throw appropriate error or exception depending on value of throw_error
   203   if (klass_h() == NULL) {
   204     ResourceMark rm(THREAD);
   205     if (throw_error) {
   206       THROW_MSG_NULL(vmSymbols::java_lang_NoClassDefFoundError(), class_name->as_C_string());
   207     } else {
   208       THROW_MSG_NULL(vmSymbols::java_lang_ClassNotFoundException(), class_name->as_C_string());
   209     }
   210   }
   211   return (Klass*)klass_h();
   212 }
   215 Klass* SystemDictionary::resolve_or_fail(Symbol* class_name,
   216                                            bool throw_error, TRAPS)
   217 {
   218   return resolve_or_fail(class_name, Handle(), Handle(), throw_error, THREAD);
   219 }
   222 // Forwards to resolve_instance_class_or_null
   224 Klass* SystemDictionary::resolve_or_null(Symbol* class_name, Handle class_loader, Handle protection_domain, TRAPS) {
   225   assert(!THREAD->is_Compiler_thread(),
   226          err_msg("can not load classes with compiler thread: class=%s, classloader=%s",
   227                  class_name->as_C_string(),
   228                  class_loader.is_null() ? "null" : class_loader->klass()->name()->as_C_string()));
   229   if (FieldType::is_array(class_name)) {
   230     return resolve_array_class_or_null(class_name, class_loader, protection_domain, CHECK_NULL);
   231   } else if (FieldType::is_obj(class_name)) {
   232     ResourceMark rm(THREAD);
   233     // Ignore wrapping L and ;.
   234     TempNewSymbol name = SymbolTable::new_symbol(class_name->as_C_string() + 1,
   235                                    class_name->utf8_length() - 2, CHECK_NULL);
   236     return resolve_instance_class_or_null(name, class_loader, protection_domain, CHECK_NULL);
   237   } else {
   238     return resolve_instance_class_or_null(class_name, class_loader, protection_domain, CHECK_NULL);
   239   }
   240 }
   242 Klass* SystemDictionary::resolve_or_null(Symbol* class_name, TRAPS) {
   243   return resolve_or_null(class_name, Handle(), Handle(), THREAD);
   244 }
   246 // Forwards to resolve_instance_class_or_null
   248 Klass* SystemDictionary::resolve_array_class_or_null(Symbol* class_name,
   249                                                        Handle class_loader,
   250                                                        Handle protection_domain,
   251                                                        TRAPS) {
   252   assert(FieldType::is_array(class_name), "must be array");
   253   Klass* k = NULL;
   254   FieldArrayInfo fd;
   255   // dimension and object_key in FieldArrayInfo are assigned as a side-effect
   256   // of this call
   257   BasicType t = FieldType::get_array_info(class_name, fd, CHECK_NULL);
   258   if (t == T_OBJECT) {
   259     // naked oop "k" is OK here -- we assign back into it
   260     k = SystemDictionary::resolve_instance_class_or_null(fd.object_key(),
   261                                                          class_loader,
   262                                                          protection_domain,
   263                                                          CHECK_NULL);
   264     if (k != NULL) {
   265       k = k->array_klass(fd.dimension(), CHECK_NULL);
   266     }
   267   } else {
   268     k = Universe::typeArrayKlassObj(t);
   269     k = TypeArrayKlass::cast(k)->array_klass(fd.dimension(), CHECK_NULL);
   270   }
   271   return k;
   272 }
   275 // Must be called for any super-class or super-interface resolution
   276 // during class definition to allow class circularity checking
   277 // super-interface callers:
   278 //    parse_interfaces - for defineClass & jvmtiRedefineClasses
   279 // super-class callers:
   280 //   ClassFileParser - for defineClass & jvmtiRedefineClasses
   281 //   load_shared_class - while loading a class from shared archive
   282 //   resolve_instance_class_or_null:
   283 //     via: handle_parallel_super_load
   284 //      when resolving a class that has an existing placeholder with
   285 //      a saved superclass [i.e. a defineClass is currently in progress]
   286 //      if another thread is trying to resolve the class, it must do
   287 //      super-class checks on its own thread to catch class circularity
   288 // This last call is critical in class circularity checking for cases
   289 // where classloading is delegated to different threads and the
   290 // classloader lock is released.
   291 // Take the case: Base->Super->Base
   292 //   1. If thread T1 tries to do a defineClass of class Base
   293 //    resolve_super_or_fail creates placeholder: T1, Base (super Super)
   294 //   2. resolve_instance_class_or_null does not find SD or placeholder for Super
   295 //    so it tries to load Super
   296 //   3. If we load the class internally, or user classloader uses same thread
   297 //      loadClassFromxxx or defineClass via parseClassFile Super ...
   298 //      3.1 resolve_super_or_fail creates placeholder: T1, Super (super Base)
   299 //      3.3 resolve_instance_class_or_null Base, finds placeholder for Base
   300 //      3.4 calls resolve_super_or_fail Base
   301 //      3.5 finds T1,Base -> throws class circularity
   302 //OR 4. If T2 tries to resolve Super via defineClass Super ...
   303 //      4.1 resolve_super_or_fail creates placeholder: T2, Super (super Base)
   304 //      4.2 resolve_instance_class_or_null Base, finds placeholder for Base (super Super)
   305 //      4.3 calls resolve_super_or_fail Super in parallel on own thread T2
   306 //      4.4 finds T2, Super -> throws class circularity
   307 // Must be called, even if superclass is null, since this is
   308 // where the placeholder entry is created which claims this
   309 // thread is loading this class/classloader.
   310 Klass* SystemDictionary::resolve_super_or_fail(Symbol* child_name,
   311                                                  Symbol* class_name,
   312                                                  Handle class_loader,
   313                                                  Handle protection_domain,
   314                                                  bool is_superclass,
   315                                                  TRAPS) {
   316   // Double-check, if child class is already loaded, just return super-class,interface
   317   // Don't add a placedholder if already loaded, i.e. already in system dictionary
   318   // Make sure there's a placeholder for the *child* before resolving.
   319   // Used as a claim that this thread is currently loading superclass/classloader
   320   // Used here for ClassCircularity checks and also for heap verification
   321   // (every InstanceKlass in the heap needs to be in the system dictionary
   322   // or have a placeholder).
   323   // Must check ClassCircularity before checking if super class is already loaded
   324   //
   325   // We might not already have a placeholder if this child_name was
   326   // first seen via resolve_from_stream (jni_DefineClass or JVM_DefineClass);
   327   // the name of the class might not be known until the stream is actually
   328   // parsed.
   329   // Bugs 4643874, 4715493
   330   // compute_hash can have a safepoint
   332   ClassLoaderData* loader_data = class_loader_data(class_loader);
   333   unsigned int d_hash = dictionary()->compute_hash(child_name, loader_data);
   334   int d_index = dictionary()->hash_to_index(d_hash);
   335   unsigned int p_hash = placeholders()->compute_hash(child_name, loader_data);
   336   int p_index = placeholders()->hash_to_index(p_hash);
   337   // can't throw error holding a lock
   338   bool child_already_loaded = false;
   339   bool throw_circularity_error = false;
   340   {
   341     MutexLocker mu(SystemDictionary_lock, THREAD);
   342     Klass* childk = find_class(d_index, d_hash, child_name, loader_data);
   343     Klass* quicksuperk;
   344     // to support // loading: if child done loading, just return superclass
   345     // if class_name, & class_loader don't match:
   346     // if initial define, SD update will give LinkageError
   347     // if redefine: compare_class_versions will give HIERARCHY_CHANGED
   348     // so we don't throw an exception here.
   349     // see: nsk redefclass014 & java.lang.instrument Instrument032
   350     if ((childk != NULL ) && (is_superclass) &&
   351        ((quicksuperk = InstanceKlass::cast(childk)->super()) != NULL) &&
   353          ((quicksuperk->name() == class_name) &&
   354             (quicksuperk->class_loader()  == class_loader()))) {
   355            return quicksuperk;
   356     } else {
   357       PlaceholderEntry* probe = placeholders()->get_entry(p_index, p_hash, child_name, loader_data);
   358       if (probe && probe->check_seen_thread(THREAD, PlaceholderTable::LOAD_SUPER)) {
   359           throw_circularity_error = true;
   360       }
   361     }
   362     if (!throw_circularity_error) {
   363       PlaceholderEntry* newprobe = placeholders()->find_and_add(p_index, p_hash, child_name, loader_data, PlaceholderTable::LOAD_SUPER, class_name, THREAD);
   364     }
   365   }
   366   if (throw_circularity_error) {
   367       ResourceMark rm(THREAD);
   368       THROW_MSG_NULL(vmSymbols::java_lang_ClassCircularityError(), child_name->as_C_string());
   369   }
   371 // java.lang.Object should have been found above
   372   assert(class_name != NULL, "null super class for resolving");
   373   // Resolve the super class or interface, check results on return
   374   Klass* superk = SystemDictionary::resolve_or_null(class_name,
   375                                                  class_loader,
   376                                                  protection_domain,
   377                                                  THREAD);
   379   KlassHandle superk_h(THREAD, superk);
   381   // Clean up of placeholders moved so that each classloadAction registrar self-cleans up
   382   // It is no longer necessary to keep the placeholder table alive until update_dictionary
   383   // or error. GC used to walk the placeholder table as strong roots.
   384   // The instanceKlass is kept alive because the class loader is on the stack,
   385   // which keeps the loader_data alive, as well as all instanceKlasses in
   386   // the loader_data. parseClassFile adds the instanceKlass to loader_data.
   387   {
   388     MutexLocker mu(SystemDictionary_lock, THREAD);
   389     placeholders()->find_and_remove(p_index, p_hash, child_name, loader_data, PlaceholderTable::LOAD_SUPER, THREAD);
   390     SystemDictionary_lock->notify_all();
   391   }
   392   if (HAS_PENDING_EXCEPTION || superk_h() == NULL) {
   393     // can null superk
   394     superk_h = KlassHandle(THREAD, handle_resolution_exception(class_name, class_loader, protection_domain, true, superk_h, THREAD));
   395   }
   397   return superk_h();
   398 }
   400 void SystemDictionary::validate_protection_domain(instanceKlassHandle klass,
   401                                                   Handle class_loader,
   402                                                   Handle protection_domain,
   403                                                   TRAPS) {
   404   if(!has_checkPackageAccess()) return;
   406   // Now we have to call back to java to check if the initating class has access
   407   JavaValue result(T_VOID);
   408   if (TraceProtectionDomainVerification) {
   409     // Print out trace information
   410     tty->print_cr("Checking package access");
   411     tty->print(" - class loader:      "); class_loader()->print_value_on(tty);      tty->cr();
   412     tty->print(" - protection domain: "); protection_domain()->print_value_on(tty); tty->cr();
   413     tty->print(" - loading:           "); klass()->print_value_on(tty);             tty->cr();
   414   }
   416   KlassHandle system_loader(THREAD, SystemDictionary::ClassLoader_klass());
   417   JavaCalls::call_special(&result,
   418                          class_loader,
   419                          system_loader,
   420                          vmSymbols::checkPackageAccess_name(),
   421                          vmSymbols::class_protectiondomain_signature(),
   422                          Handle(THREAD, klass->java_mirror()),
   423                          protection_domain,
   424                          THREAD);
   426   if (TraceProtectionDomainVerification) {
   427     if (HAS_PENDING_EXCEPTION) {
   428       tty->print_cr(" -> DENIED !!!!!!!!!!!!!!!!!!!!!");
   429     } else {
   430      tty->print_cr(" -> granted");
   431     }
   432     tty->cr();
   433   }
   435   if (HAS_PENDING_EXCEPTION) return;
   437   // If no exception has been thrown, we have validated the protection domain
   438   // Insert the protection domain of the initiating class into the set.
   439   {
   440     // We recalculate the entry here -- we've called out to java since
   441     // the last time it was calculated.
   442     ClassLoaderData* loader_data = class_loader_data(class_loader);
   444     Symbol*  kn = klass->name();
   445     unsigned int d_hash = dictionary()->compute_hash(kn, loader_data);
   446     int d_index = dictionary()->hash_to_index(d_hash);
   448     MutexLocker mu(SystemDictionary_lock, THREAD);
   449     {
   450       // Note that we have an entry, and entries can be deleted only during GC,
   451       // so we cannot allow GC to occur while we're holding this entry.
   453       // We're using a No_Safepoint_Verifier to catch any place where we
   454       // might potentially do a GC at all.
   455       // Dictionary::do_unloading() asserts that classes in SD are only
   456       // unloaded at a safepoint. Anonymous classes are not in SD.
   457       No_Safepoint_Verifier nosafepoint;
   458       dictionary()->add_protection_domain(d_index, d_hash, klass, loader_data,
   459                                           protection_domain, THREAD);
   460     }
   461   }
   462 }
   464 // We only get here if this thread finds that another thread
   465 // has already claimed the placeholder token for the current operation,
   466 // but that other thread either never owned or gave up the
   467 // object lock
   468 // Waits on SystemDictionary_lock to indicate placeholder table updated
   469 // On return, caller must recheck placeholder table state
   470 //
   471 // We only get here if
   472 //  1) custom classLoader, i.e. not bootstrap classloader
   473 //  2) UnsyncloadClass not set
   474 //  3) custom classLoader has broken the class loader objectLock
   475 //     so another thread got here in parallel
   476 //
   477 // lockObject must be held.
   478 // Complicated dance due to lock ordering:
   479 // Must first release the classloader object lock to
   480 // allow initial definer to complete the class definition
   481 // and to avoid deadlock
   482 // Reclaim classloader lock object with same original recursion count
   483 // Must release SystemDictionary_lock after notify, since
   484 // class loader lock must be claimed before SystemDictionary_lock
   485 // to prevent deadlocks
   486 //
   487 // The notify allows applications that did an untimed wait() on
   488 // the classloader object lock to not hang.
   489 void SystemDictionary::double_lock_wait(Handle lockObject, TRAPS) {
   490   assert_lock_strong(SystemDictionary_lock);
   492   bool calledholdinglock
   493       = ObjectSynchronizer::current_thread_holds_lock((JavaThread*)THREAD, lockObject);
   494   assert(calledholdinglock,"must hold lock for notify");
   495   assert((!(lockObject() == _system_loader_lock_obj) && !is_parallelCapable(lockObject)), "unexpected double_lock_wait");
   496   ObjectSynchronizer::notifyall(lockObject, THREAD);
   497   intptr_t recursions =  ObjectSynchronizer::complete_exit(lockObject, THREAD);
   498   SystemDictionary_lock->wait();
   499   SystemDictionary_lock->unlock();
   500   ObjectSynchronizer::reenter(lockObject, recursions, THREAD);
   501   SystemDictionary_lock->lock();
   502 }
   504 // If the class in is in the placeholder table, class loading is in progress
   505 // For cases where the application changes threads to load classes, it
   506 // is critical to ClassCircularity detection that we try loading
   507 // the superclass on the same thread internally, so we do parallel
   508 // super class loading here.
   509 // This also is critical in cases where the original thread gets stalled
   510 // even in non-circularity situations.
   511 // Note: must call resolve_super_or_fail even if null super -
   512 // to force placeholder entry creation for this class for circularity detection
   513 // Caller must check for pending exception
   514 // Returns non-null Klass* if other thread has completed load
   515 // and we are done,
   516 // If return null Klass* and no pending exception, the caller must load the class
   517 instanceKlassHandle SystemDictionary::handle_parallel_super_load(
   518     Symbol* name, Symbol* superclassname, Handle class_loader,
   519     Handle protection_domain, Handle lockObject, TRAPS) {
   521   instanceKlassHandle nh = instanceKlassHandle(); // null Handle
   522   ClassLoaderData* loader_data = class_loader_data(class_loader);
   523   unsigned int d_hash = dictionary()->compute_hash(name, loader_data);
   524   int d_index = dictionary()->hash_to_index(d_hash);
   525   unsigned int p_hash = placeholders()->compute_hash(name, loader_data);
   526   int p_index = placeholders()->hash_to_index(p_hash);
   528   // superk is not used, resolve_super called for circularity check only
   529   // This code is reached in two situations. One if this thread
   530   // is loading the same class twice (e.g. ClassCircularity, or
   531   // java.lang.instrument).
   532   // The second is if another thread started the resolve_super first
   533   // and has not yet finished.
   534   // In both cases the original caller will clean up the placeholder
   535   // entry on error.
   536   Klass* superk = SystemDictionary::resolve_super_or_fail(name,
   537                                                           superclassname,
   538                                                           class_loader,
   539                                                           protection_domain,
   540                                                           true,
   541                                                           CHECK_(nh));
   543   // parallelCapable class loaders do NOT wait for parallel superclass loads to complete
   544   // Serial class loaders and bootstrap classloader do wait for superclass loads
   545  if (!class_loader.is_null() && is_parallelCapable(class_loader)) {
   546     MutexLocker mu(SystemDictionary_lock, THREAD);
   547     // Check if classloading completed while we were loading superclass or waiting
   548     Klass* check = find_class(d_index, d_hash, name, loader_data);
   549     if (check != NULL) {
   550       // Klass is already loaded, so just return it
   551       return(instanceKlassHandle(THREAD, check));
   552     } else {
   553       return nh;
   554     }
   555   }
   557   // must loop to both handle other placeholder updates
   558   // and spurious notifications
   559   bool super_load_in_progress = true;
   560   PlaceholderEntry* placeholder;
   561   while (super_load_in_progress) {
   562     MutexLocker mu(SystemDictionary_lock, THREAD);
   563     // Check if classloading completed while we were loading superclass or waiting
   564     Klass* check = find_class(d_index, d_hash, name, loader_data);
   565     if (check != NULL) {
   566       // Klass is already loaded, so just return it
   567       return(instanceKlassHandle(THREAD, check));
   568     } else {
   569       placeholder = placeholders()->get_entry(p_index, p_hash, name, loader_data);
   570       if (placeholder && placeholder->super_load_in_progress() ){
   571         // Before UnsyncloadClass:
   572         // We only get here if the application has released the
   573         // classloader lock when another thread was in the middle of loading a
   574         // superclass/superinterface for this class, and now
   575         // this thread is also trying to load this class.
   576         // To minimize surprises, the first thread that started to
   577         // load a class should be the one to complete the loading
   578         // with the classfile it initially expected.
   579         // This logic has the current thread wait once it has done
   580         // all the superclass/superinterface loading it can, until
   581         // the original thread completes the class loading or fails
   582         // If it completes we will use the resulting InstanceKlass
   583         // which we will find below in the systemDictionary.
   584         // We also get here for parallel bootstrap classloader
   585         if (class_loader.is_null()) {
   586           SystemDictionary_lock->wait();
   587         } else {
   588           double_lock_wait(lockObject, THREAD);
   589         }
   590       } else {
   591         // If not in SD and not in PH, other thread's load must have failed
   592         super_load_in_progress = false;
   593       }
   594     }
   595   }
   596   return (nh);
   597 }
   599 // utility function for class load event
   600 static void post_class_load_event(EventClassLoad &event,
   601                                   instanceKlassHandle k,
   602                                   Handle initiating_loader) {
   603 #if INCLUDE_JFR
   604   if (event.should_commit()) {
   605     event.set_loadedClass(k());
   606     event.set_definingClassLoader(k->class_loader_data());
   607     oop class_loader = initiating_loader.is_null() ? (oop)NULL : initiating_loader();
   608     event.set_initiatingClassLoader(class_loader != NULL ?
   609                                     ClassLoaderData::class_loader_data_or_null(class_loader) :
   610                                     (ClassLoaderData*)NULL);
   611     event.commit();
   612   }
   613 #endif // INCLUDE_JFR
   614 }
   616 Klass* SystemDictionary::resolve_instance_class_or_null(Symbol* name,
   617                                                         Handle class_loader,
   618                                                         Handle protection_domain,
   619                                                         TRAPS) {
   620   assert(name != NULL && !FieldType::is_array(name) &&
   621          !FieldType::is_obj(name), "invalid class name");
   623   EventClassLoad class_load_start_event;
   625   // UseNewReflection
   626   // Fix for 4474172; see evaluation for more details
   627   class_loader = Handle(THREAD, java_lang_ClassLoader::non_reflection_class_loader(class_loader()));
   628   ClassLoaderData *loader_data = register_loader(class_loader, CHECK_NULL);
   630   // Do lookup to see if class already exist and the protection domain
   631   // has the right access
   632   // This call uses find which checks protection domain already matches
   633   // All subsequent calls use find_class, and set has_loaded_class so that
   634   // before we return a result we call out to java to check for valid protection domain
   635   // to allow returning the Klass* and add it to the pd_set if it is valid
   636   unsigned int d_hash = dictionary()->compute_hash(name, loader_data);
   637   int d_index = dictionary()->hash_to_index(d_hash);
   638   Klass* probe = dictionary()->find(d_index, d_hash, name, loader_data,
   639                                       protection_domain, THREAD);
   640   if (probe != NULL) return probe;
   643   // Non-bootstrap class loaders will call out to class loader and
   644   // define via jvm/jni_DefineClass which will acquire the
   645   // class loader object lock to protect against multiple threads
   646   // defining the class in parallel by accident.
   647   // This lock must be acquired here so the waiter will find
   648   // any successful result in the SystemDictionary and not attempt
   649   // the define
   650   // ParallelCapable Classloaders and the bootstrap classloader,
   651   // or all classloaders with UnsyncloadClass do not acquire lock here
   652   bool DoObjectLock = true;
   653   if (is_parallelCapable(class_loader)) {
   654     DoObjectLock = false;
   655   }
   657   unsigned int p_hash = placeholders()->compute_hash(name, loader_data);
   658   int p_index = placeholders()->hash_to_index(p_hash);
   660   // Class is not in SystemDictionary so we have to do loading.
   661   // Make sure we are synchronized on the class loader before we proceed
   662   Handle lockObject = compute_loader_lock_object(class_loader, THREAD);
   663   check_loader_lock_contention(lockObject, THREAD);
   664   ObjectLocker ol(lockObject, THREAD, DoObjectLock);
   666   // Check again (after locking) if class already exist in SystemDictionary
   667   bool class_has_been_loaded   = false;
   668   bool super_load_in_progress  = false;
   669   bool havesupername = false;
   670   instanceKlassHandle k;
   671   PlaceholderEntry* placeholder;
   672   Symbol* superclassname = NULL;
   674   {
   675     MutexLocker mu(SystemDictionary_lock, THREAD);
   676     Klass* check = find_class(d_index, d_hash, name, loader_data);
   677     if (check != NULL) {
   678       // Klass is already loaded, so just return it
   679       class_has_been_loaded = true;
   680       k = instanceKlassHandle(THREAD, check);
   681     } else {
   682       placeholder = placeholders()->get_entry(p_index, p_hash, name, loader_data);
   683       if (placeholder && placeholder->super_load_in_progress()) {
   684          super_load_in_progress = true;
   685          if (placeholder->havesupername() == true) {
   686            superclassname = placeholder->supername();
   687            havesupername = true;
   688          }
   689       }
   690     }
   691   }
   693   // If the class is in the placeholder table, class loading is in progress
   694   if (super_load_in_progress && havesupername==true) {
   695     k = SystemDictionary::handle_parallel_super_load(name, superclassname,
   696         class_loader, protection_domain, lockObject, THREAD);
   697     if (HAS_PENDING_EXCEPTION) {
   698       return NULL;
   699     }
   700     if (!k.is_null()) {
   701       class_has_been_loaded = true;
   702     }
   703   }
   705   bool throw_circularity_error = false;
   706   if (!class_has_been_loaded) {
   707     bool load_instance_added = false;
   709     // add placeholder entry to record loading instance class
   710     // Five cases:
   711     // All cases need to prevent modifying bootclasssearchpath
   712     // in parallel with a classload of same classname
   713     // Redefineclasses uses existence of the placeholder for the duration
   714     // of the class load to prevent concurrent redefinition of not completely
   715     // defined classes.
   716     // case 1. traditional classloaders that rely on the classloader object lock
   717     //   - no other need for LOAD_INSTANCE
   718     // case 2. traditional classloaders that break the classloader object lock
   719     //    as a deadlock workaround. Detection of this case requires that
   720     //    this check is done while holding the classloader object lock,
   721     //    and that lock is still held when calling classloader's loadClass.
   722     //    For these classloaders, we ensure that the first requestor
   723     //    completes the load and other requestors wait for completion.
   724     // case 3. UnsyncloadClass - don't use objectLocker
   725     //    With this flag, we allow parallel classloading of a
   726     //    class/classloader pair
   727     // case4. Bootstrap classloader - don't own objectLocker
   728     //    This classloader supports parallelism at the classloader level,
   729     //    but only allows a single load of a class/classloader pair.
   730     //    No performance benefit and no deadlock issues.
   731     // case 5. parallelCapable user level classloaders - without objectLocker
   732     //    Allow parallel classloading of a class/classloader pair
   734     {
   735       MutexLocker mu(SystemDictionary_lock, THREAD);
   736       if (class_loader.is_null() || !is_parallelCapable(class_loader)) {
   737         PlaceholderEntry* oldprobe = placeholders()->get_entry(p_index, p_hash, name, loader_data);
   738         if (oldprobe) {
   739           // only need check_seen_thread once, not on each loop
   740           // 6341374 java/lang/Instrument with -Xcomp
   741           if (oldprobe->check_seen_thread(THREAD, PlaceholderTable::LOAD_INSTANCE)) {
   742             throw_circularity_error = true;
   743           } else {
   744             // case 1: traditional: should never see load_in_progress.
   745             while (!class_has_been_loaded && oldprobe && oldprobe->instance_load_in_progress()) {
   747               // case 4: bootstrap classloader: prevent futile classloading,
   748               // wait on first requestor
   749               if (class_loader.is_null()) {
   750                 SystemDictionary_lock->wait();
   751               } else {
   752               // case 2: traditional with broken classloader lock. wait on first
   753               // requestor.
   754                 double_lock_wait(lockObject, THREAD);
   755               }
   756               // Check if classloading completed while we were waiting
   757               Klass* check = find_class(d_index, d_hash, name, loader_data);
   758               if (check != NULL) {
   759                 // Klass is already loaded, so just return it
   760                 k = instanceKlassHandle(THREAD, check);
   761                 class_has_been_loaded = true;
   762               }
   763               // check if other thread failed to load and cleaned up
   764               oldprobe = placeholders()->get_entry(p_index, p_hash, name, loader_data);
   765             }
   766           }
   767         }
   768       }
   769       // All cases: add LOAD_INSTANCE holding SystemDictionary_lock
   770       // case 3: UnsyncloadClass || case 5: parallelCapable: allow competing threads to try
   771       // LOAD_INSTANCE in parallel
   773       if (!throw_circularity_error && !class_has_been_loaded) {
   774         PlaceholderEntry* newprobe = placeholders()->find_and_add(p_index, p_hash, name, loader_data, PlaceholderTable::LOAD_INSTANCE, NULL, THREAD);
   775         load_instance_added = true;
   776         // For class loaders that do not acquire the classloader object lock,
   777         // if they did not catch another thread holding LOAD_INSTANCE,
   778         // need a check analogous to the acquire ObjectLocker/find_class
   779         // i.e. now that we hold the LOAD_INSTANCE token on loading this class/CL
   780         // one final check if the load has already completed
   781         // class loaders holding the ObjectLock shouldn't find the class here
   782         Klass* check = find_class(d_index, d_hash, name, loader_data);
   783         if (check != NULL) {
   784         // Klass is already loaded, so return it after checking/adding protection domain
   785           k = instanceKlassHandle(THREAD, check);
   786           class_has_been_loaded = true;
   787         }
   788       }
   789     }
   791     // must throw error outside of owning lock
   792     if (throw_circularity_error) {
   793       assert(!HAS_PENDING_EXCEPTION && load_instance_added == false,"circularity error cleanup");
   794       ResourceMark rm(THREAD);
   795       THROW_MSG_NULL(vmSymbols::java_lang_ClassCircularityError(), name->as_C_string());
   796     }
   798     if (!class_has_been_loaded) {
   800       // Do actual loading
   801       k = load_instance_class(name, class_loader, THREAD);
   803       // For UnsyncloadClass only
   804       // If they got a linkageError, check if a parallel class load succeeded.
   805       // If it did, then for bytecode resolution the specification requires
   806       // that we return the same result we did for the other thread, i.e. the
   807       // successfully loaded InstanceKlass
   808       // Should not get here for classloaders that support parallelism
   809       // with the new cleaner mechanism, even with AllowParallelDefineClass
   810       // Bootstrap goes through here to allow for an extra guarantee check
   811       if (UnsyncloadClass || (class_loader.is_null())) {
   812         if (k.is_null() && HAS_PENDING_EXCEPTION
   813           && PENDING_EXCEPTION->is_a(SystemDictionary::LinkageError_klass())) {
   814           MutexLocker mu(SystemDictionary_lock, THREAD);
   815           Klass* check = find_class(d_index, d_hash, name, loader_data);
   816           if (check != NULL) {
   817             // Klass is already loaded, so just use it
   818             k = instanceKlassHandle(THREAD, check);
   819             CLEAR_PENDING_EXCEPTION;
   820             guarantee((!class_loader.is_null()), "dup definition for bootstrap loader?");
   821           }
   822         }
   823       }
   825       // If everything was OK (no exceptions, no null return value), and
   826       // class_loader is NOT the defining loader, do a little more bookkeeping.
   827       if (!HAS_PENDING_EXCEPTION && !k.is_null() &&
   828         k->class_loader() != class_loader()) {
   830         check_constraints(d_index, d_hash, k, class_loader, false, THREAD);
   832         // Need to check for a PENDING_EXCEPTION again; check_constraints
   833         // can throw but we may have to remove entry from the placeholder table below.
   834         if (!HAS_PENDING_EXCEPTION) {
   835           // Record dependency for non-parent delegation.
   836           // This recording keeps the defining class loader of the klass (k) found
   837           // from being unloaded while the initiating class loader is loaded
   838           // even if the reference to the defining class loader is dropped
   839           // before references to the initiating class loader.
   840           loader_data->record_dependency(k(), THREAD);
   841         }
   843         if (!HAS_PENDING_EXCEPTION) {
   844           { // Grabbing the Compile_lock prevents systemDictionary updates
   845             // during compilations.
   846             MutexLocker mu(Compile_lock, THREAD);
   847             update_dictionary(d_index, d_hash, p_index, p_hash,
   848                               k, class_loader, THREAD);
   849           }
   851           if (JvmtiExport::should_post_class_load()) {
   852             Thread *thread = THREAD;
   853             assert(thread->is_Java_thread(), "thread->is_Java_thread()");
   854             JvmtiExport::post_class_load((JavaThread *) thread, k());
   855           }
   856         }
   857       }
   858     } // load_instance_class loop
   860     if (load_instance_added == true) {
   861       // clean up placeholder entries for LOAD_INSTANCE success or error
   862       // This brackets the SystemDictionary updates for both defining
   863       // and initiating loaders
   864       MutexLocker mu(SystemDictionary_lock, THREAD);
   865       placeholders()->find_and_remove(p_index, p_hash, name, loader_data, PlaceholderTable::LOAD_INSTANCE, THREAD);
   866       SystemDictionary_lock->notify_all();
   867     }
   868   }
   870   if (HAS_PENDING_EXCEPTION || k.is_null()) {
   871     return NULL;
   872   }
   874   post_class_load_event(class_load_start_event, k, class_loader);
   876 #ifdef ASSERT
   877   {
   878     ClassLoaderData* loader_data = k->class_loader_data();
   879     MutexLocker mu(SystemDictionary_lock, THREAD);
   880     Klass* kk = find_class(name, loader_data);
   881     assert(kk == k(), "should be present in dictionary");
   882   }
   883 #endif
   885   // return if the protection domain in NULL
   886   if (protection_domain() == NULL) return k();
   888   // Check the protection domain has the right access
   889   {
   890     MutexLocker mu(SystemDictionary_lock, THREAD);
   891     // Note that we have an entry, and entries can be deleted only during GC,
   892     // so we cannot allow GC to occur while we're holding this entry.
   893     // We're using a No_Safepoint_Verifier to catch any place where we
   894     // might potentially do a GC at all.
   895     // Dictionary::do_unloading() asserts that classes in SD are only
   896     // unloaded at a safepoint. Anonymous classes are not in SD.
   897     No_Safepoint_Verifier nosafepoint;
   898     if (dictionary()->is_valid_protection_domain(d_index, d_hash, name,
   899                                                  loader_data,
   900                                                  protection_domain)) {
   901       return k();
   902     }
   903   }
   905   // Verify protection domain. If it fails an exception is thrown
   906   validate_protection_domain(k, class_loader, protection_domain, CHECK_NULL);
   908   return k();
   909 }
   912 // This routine does not lock the system dictionary.
   913 //
   914 // Since readers don't hold a lock, we must make sure that system
   915 // dictionary entries are only removed at a safepoint (when only one
   916 // thread is running), and are added to in a safe way (all links must
   917 // be updated in an MT-safe manner).
   918 //
   919 // Callers should be aware that an entry could be added just after
   920 // _dictionary->bucket(index) is read here, so the caller will not see
   921 // the new entry.
   923 Klass* SystemDictionary::find(Symbol* class_name,
   924                               Handle class_loader,
   925                               Handle protection_domain,
   926                               TRAPS) {
   928   // UseNewReflection
   929   // The result of this call should be consistent with the result
   930   // of the call to resolve_instance_class_or_null().
   931   // See evaluation 6790209 and 4474172 for more details.
   932   class_loader = Handle(THREAD, java_lang_ClassLoader::non_reflection_class_loader(class_loader()));
   933   ClassLoaderData* loader_data = ClassLoaderData::class_loader_data_or_null(class_loader());
   935   if (loader_data == NULL) {
   936     // If the ClassLoaderData has not been setup,
   937     // then the class loader has no entries in the dictionary.
   938     return NULL;
   939   }
   941   unsigned int d_hash = dictionary()->compute_hash(class_name, loader_data);
   942   int d_index = dictionary()->hash_to_index(d_hash);
   944   {
   945     // Note that we have an entry, and entries can be deleted only during GC,
   946     // so we cannot allow GC to occur while we're holding this entry.
   947     // We're using a No_Safepoint_Verifier to catch any place where we
   948     // might potentially do a GC at all.
   949     // Dictionary::do_unloading() asserts that classes in SD are only
   950     // unloaded at a safepoint. Anonymous classes are not in SD.
   951     No_Safepoint_Verifier nosafepoint;
   952     return dictionary()->find(d_index, d_hash, class_name, loader_data,
   953                               protection_domain, THREAD);
   954   }
   955 }
   958 // Look for a loaded instance or array klass by name.  Do not do any loading.
   959 // return NULL in case of error.
   960 Klass* SystemDictionary::find_instance_or_array_klass(Symbol* class_name,
   961                                                       Handle class_loader,
   962                                                       Handle protection_domain,
   963                                                       TRAPS) {
   964   Klass* k = NULL;
   965   assert(class_name != NULL, "class name must be non NULL");
   967   if (FieldType::is_array(class_name)) {
   968     // The name refers to an array.  Parse the name.
   969     // dimension and object_key in FieldArrayInfo are assigned as a
   970     // side-effect of this call
   971     FieldArrayInfo fd;
   972     BasicType t = FieldType::get_array_info(class_name, fd, CHECK_(NULL));
   973     if (t != T_OBJECT) {
   974       k = Universe::typeArrayKlassObj(t);
   975     } else {
   976       k = SystemDictionary::find(fd.object_key(), class_loader, protection_domain, THREAD);
   977     }
   978     if (k != NULL) {
   979       k = k->array_klass_or_null(fd.dimension());
   980     }
   981   } else {
   982     k = find(class_name, class_loader, protection_domain, THREAD);
   983   }
   984   return k;
   985 }
   987 // Note: this method is much like resolve_from_stream, but
   988 // updates no supplemental data structures.
   989 // TODO consolidate the two methods with a helper routine?
   990 Klass* SystemDictionary::parse_stream(Symbol* class_name,
   991                                       Handle class_loader,
   992                                       Handle protection_domain,
   993                                       ClassFileStream* st,
   994                                       KlassHandle host_klass,
   995                                       GrowableArray<Handle>* cp_patches,
   996                                       TRAPS) {
   997   TempNewSymbol parsed_name = NULL;
   999   EventClassLoad class_load_start_event;
  1001   ClassLoaderData* loader_data;
  1002   if (host_klass.not_null()) {
  1003     // Create a new CLD for anonymous class, that uses the same class loader
  1004     // as the host_klass
  1005     assert(EnableInvokeDynamic, "");
  1006     guarantee(host_klass->class_loader() == class_loader(), "should be the same");
  1007     guarantee(!DumpSharedSpaces, "must not create anonymous classes when dumping");
  1008     loader_data = ClassLoaderData::anonymous_class_loader_data(class_loader(), CHECK_NULL);
  1009     loader_data->record_dependency(host_klass(), CHECK_NULL);
  1010   } else {
  1011     loader_data = ClassLoaderData::class_loader_data(class_loader());
  1014   // Parse the stream. Note that we do this even though this klass might
  1015   // already be present in the SystemDictionary, otherwise we would not
  1016   // throw potential ClassFormatErrors.
  1017   //
  1018   // Note: "name" is updated.
  1020   instanceKlassHandle k = ClassFileParser(st).parseClassFile(class_name,
  1021                                                              loader_data,
  1022                                                              protection_domain,
  1023                                                              host_klass,
  1024                                                              cp_patches,
  1025                                                              parsed_name,
  1026                                                              true,
  1027                                                              THREAD);
  1030   if (host_klass.not_null() && k.not_null()) {
  1031     assert(EnableInvokeDynamic, "");
  1032     // If it's anonymous, initialize it now, since nobody else will.
  1035       MutexLocker mu_r(Compile_lock, THREAD);
  1037       // Add to class hierarchy, initialize vtables, and do possible
  1038       // deoptimizations.
  1039       add_to_hierarchy(k, CHECK_NULL); // No exception, but can block
  1041       // But, do not add to system dictionary.
  1043       // compiled code dependencies need to be validated anyway
  1044       notice_modification();
  1047     // Rewrite and patch constant pool here.
  1048     k->link_class(CHECK_NULL);
  1049     if (cp_patches != NULL) {
  1050       k->constants()->patch_resolved_references(cp_patches);
  1052     k->eager_initialize(CHECK_NULL);
  1054     // notify jvmti
  1055     if (JvmtiExport::should_post_class_load()) {
  1056         assert(THREAD->is_Java_thread(), "thread->is_Java_thread()");
  1057         JvmtiExport::post_class_load((JavaThread *) THREAD, k());
  1060     post_class_load_event(class_load_start_event, k, class_loader);
  1062   assert(host_klass.not_null() || cp_patches == NULL,
  1063          "cp_patches only found with host_klass");
  1065   return k();
  1068 // Add a klass to the system from a stream (called by jni_DefineClass and
  1069 // JVM_DefineClass).
  1070 // Note: class_name can be NULL. In that case we do not know the name of
  1071 // the class until we have parsed the stream.
  1073 Klass* SystemDictionary::resolve_from_stream(Symbol* class_name,
  1074                                              Handle class_loader,
  1075                                              Handle protection_domain,
  1076                                              ClassFileStream* st,
  1077                                              bool verify,
  1078                                              TRAPS) {
  1080   // Classloaders that support parallelism, e.g. bootstrap classloader,
  1081   // or all classloaders with UnsyncloadClass do not acquire lock here
  1082   bool DoObjectLock = true;
  1083   if (is_parallelCapable(class_loader)) {
  1084     DoObjectLock = false;
  1087   ClassLoaderData* loader_data = register_loader(class_loader, CHECK_NULL);
  1089   // Make sure we are synchronized on the class loader before we proceed
  1090   Handle lockObject = compute_loader_lock_object(class_loader, THREAD);
  1091   check_loader_lock_contention(lockObject, THREAD);
  1092   ObjectLocker ol(lockObject, THREAD, DoObjectLock);
  1094   TempNewSymbol parsed_name = NULL;
  1096   // Parse the stream. Note that we do this even though this klass might
  1097   // already be present in the SystemDictionary, otherwise we would not
  1098   // throw potential ClassFormatErrors.
  1099   //
  1100   // Note: "name" is updated.
  1102   ClassFileParser parser(st);
  1103   instanceKlassHandle k = parser.parseClassFile(class_name,
  1104                                                 loader_data,
  1105                                                 protection_domain,
  1106                                                 parsed_name,
  1107                                                 verify,
  1108                                                 THREAD);
  1110   const char* pkg = "java/";
  1111   size_t pkglen = strlen(pkg);
  1112   if (!HAS_PENDING_EXCEPTION &&
  1113       !class_loader.is_null() &&
  1114       parsed_name != NULL &&
  1115       parsed_name->utf8_length() >= (int)pkglen &&
  1116       !strncmp((const char*)parsed_name->bytes(), pkg, pkglen)) {
  1117     // It is illegal to define classes in the "java." package from
  1118     // JVM_DefineClass or jni_DefineClass unless you're the bootclassloader
  1119     ResourceMark rm(THREAD);
  1120     char* name = parsed_name->as_C_string();
  1121     char* index = strrchr(name, '/');
  1122     assert(index != NULL, "must be");
  1123     *index = '\0'; // chop to just the package name
  1124     while ((index = strchr(name, '/')) != NULL) {
  1125       *index = '.'; // replace '/' with '.' in package name
  1127     const char* fmt = "Prohibited package name: %s";
  1128     size_t len = strlen(fmt) + strlen(name);
  1129     char* message = NEW_RESOURCE_ARRAY(char, len);
  1130     jio_snprintf(message, len, fmt, name);
  1131     Exceptions::_throw_msg(THREAD_AND_LOCATION,
  1132       vmSymbols::java_lang_SecurityException(), message);
  1135   if (!HAS_PENDING_EXCEPTION) {
  1136     assert(parsed_name != NULL, "Sanity");
  1137     assert(class_name == NULL || class_name == parsed_name, "name mismatch");
  1138     // Verification prevents us from creating names with dots in them, this
  1139     // asserts that that's the case.
  1140     assert(is_internal_format(parsed_name),
  1141            "external class name format used internally");
  1143 #if INCLUDE_JFR
  1145       InstanceKlass* ik = k();
  1146       ON_KLASS_CREATION(ik, parser, THREAD);
  1147       k = instanceKlassHandle(ik);
  1149 #endif
  1151     // Add class just loaded
  1152     // If a class loader supports parallel classloading handle parallel define requests
  1153     // find_or_define_instance_class may return a different InstanceKlass
  1154     if (is_parallelCapable(class_loader)) {
  1155       k = find_or_define_instance_class(class_name, class_loader, k, THREAD);
  1156     } else {
  1157       define_instance_class(k, THREAD);
  1161   // Make sure we have an entry in the SystemDictionary on success
  1162   debug_only( {
  1163     if (!HAS_PENDING_EXCEPTION) {
  1164       assert(parsed_name != NULL, "parsed_name is still null?");
  1165       Symbol*  h_name    = k->name();
  1166       ClassLoaderData *defining_loader_data = k->class_loader_data();
  1168       MutexLocker mu(SystemDictionary_lock, THREAD);
  1170       Klass* check = find_class(parsed_name, loader_data);
  1171       assert(check == k(), "should be present in the dictionary");
  1173       Klass* check2 = find_class(h_name, defining_loader_data);
  1174       assert(check == check2, "name inconsistancy in SystemDictionary");
  1176   } );
  1178   return k();
  1181 #if INCLUDE_CDS
  1182 void SystemDictionary::set_shared_dictionary(HashtableBucket<mtClass>* t, int length,
  1183                                              int number_of_entries) {
  1184   assert(length == _nof_buckets * sizeof(HashtableBucket<mtClass>),
  1185          "bad shared dictionary size.");
  1186   _shared_dictionary = new Dictionary(_nof_buckets, t, number_of_entries);
  1190 // If there is a shared dictionary, then find the entry for the
  1191 // given shared system class, if any.
  1193 Klass* SystemDictionary::find_shared_class(Symbol* class_name) {
  1194   if (shared_dictionary() != NULL) {
  1195     unsigned int d_hash = shared_dictionary()->compute_hash(class_name, NULL);
  1196     int d_index = shared_dictionary()->hash_to_index(d_hash);
  1198     return shared_dictionary()->find_shared_class(d_index, d_hash, class_name);
  1199   } else {
  1200     return NULL;
  1205 // Load a class from the shared spaces (found through the shared system
  1206 // dictionary).  Force the superclass and all interfaces to be loaded.
  1207 // Update the class definition to include sibling classes and no
  1208 // subclasses (yet).  [Classes in the shared space are not part of the
  1209 // object hierarchy until loaded.]
  1211 instanceKlassHandle SystemDictionary::load_shared_class(
  1212                  Symbol* class_name, Handle class_loader, TRAPS) {
  1213   instanceKlassHandle ik (THREAD, find_shared_class(class_name));
  1214   // Make sure we only return the boot class for the NULL classloader.
  1215   if (ik.not_null() &&
  1216       SharedClassUtil::is_shared_boot_class(ik()) && class_loader.is_null()) {
  1217     Handle protection_domain;
  1218     return load_shared_class(ik, class_loader, protection_domain, THREAD);
  1220   return instanceKlassHandle();
  1223 instanceKlassHandle SystemDictionary::load_shared_class(instanceKlassHandle ik,
  1224                                                         Handle class_loader,
  1225                                                         Handle protection_domain, TRAPS) {
  1226   if (ik.not_null()) {
  1227     instanceKlassHandle nh = instanceKlassHandle(); // null Handle
  1228     Symbol* class_name = ik->name();
  1230     // Found the class, now load the superclass and interfaces.  If they
  1231     // are shared, add them to the main system dictionary and reset
  1232     // their hierarchy references (supers, subs, and interfaces).
  1234     if (ik->super() != NULL) {
  1235       Symbol*  cn = ik->super()->name();
  1236       Klass *s = resolve_super_or_fail(class_name, cn,
  1237                                        class_loader, protection_domain, true, CHECK_(nh));
  1238       if (s != ik->super()) {
  1239         // The dynamically resolved super class is not the same as the one we used during dump time,
  1240         // so we cannot use ik.
  1241         return nh;
  1245     Array<Klass*>* interfaces = ik->local_interfaces();
  1246     int num_interfaces = interfaces->length();
  1247     for (int index = 0; index < num_interfaces; index++) {
  1248       Klass* k = interfaces->at(index);
  1250       // Note: can not use InstanceKlass::cast here because
  1251       // interfaces' InstanceKlass's C++ vtbls haven't been
  1252       // reinitialized yet (they will be once the interface classes
  1253       // are loaded)
  1254       Symbol*  name  = k->name();
  1255       Klass* i = resolve_super_or_fail(class_name, name, class_loader, protection_domain, false, CHECK_(nh));
  1256       if (k != i) {
  1257         // The dynamically resolved interface class is not the same as the one we used during dump time,
  1258         // so we cannot use ik.
  1259         return nh;
  1263     // Adjust methods to recover missing data.  They need addresses for
  1264     // interpreter entry points and their default native method address
  1265     // must be reset.
  1267     // Updating methods must be done under a lock so multiple
  1268     // threads don't update these in parallel
  1269     //
  1270     // Shared classes are all currently loaded by either the bootstrap or
  1271     // internal parallel class loaders, so this will never cause a deadlock
  1272     // on a custom class loader lock.
  1274     ClassLoaderData* loader_data = ClassLoaderData::class_loader_data(class_loader());
  1276       Handle lockObject = compute_loader_lock_object(class_loader, THREAD);
  1277       check_loader_lock_contention(lockObject, THREAD);
  1278       ObjectLocker ol(lockObject, THREAD, true);
  1279       ik->restore_unshareable_info(loader_data, protection_domain, CHECK_(nh));
  1282     if (TraceClassLoading) {
  1283       ResourceMark rm;
  1284       tty->print("[Loaded %s", ik->external_name());
  1285       tty->print(" from shared objects file");
  1286       if (class_loader.not_null()) {
  1287         tty->print(" by %s", loader_data->loader_name());
  1289       tty->print_cr("]");
  1292     if (DumpLoadedClassList != NULL && classlist_file->is_open()) {
  1293       // Only dump the classes that can be stored into CDS archive
  1294       if (SystemDictionaryShared::is_sharing_possible(loader_data)) {
  1295         ResourceMark rm(THREAD);
  1296         classlist_file->print_cr("%s", ik->name()->as_C_string());
  1297         classlist_file->flush();
  1301     // notify a class loaded from shared object
  1302     ClassLoadingService::notify_class_loaded(InstanceKlass::cast(ik()),
  1303                                              true /* shared class */);
  1305   return ik;
  1307 #endif // INCLUDE_CDS
  1309 instanceKlassHandle SystemDictionary::load_instance_class(Symbol* class_name, Handle class_loader, TRAPS) {
  1310   instanceKlassHandle nh = instanceKlassHandle(); // null Handle
  1311   if (class_loader.is_null()) {
  1313     // Search the shared system dictionary for classes preloaded into the
  1314     // shared spaces.
  1315     instanceKlassHandle k;
  1317 #if INCLUDE_CDS
  1318       PerfTraceTime vmtimer(ClassLoader::perf_shared_classload_time());
  1319       k = load_shared_class(class_name, class_loader, THREAD);
  1320 #endif
  1323     if (k.is_null()) {
  1324       // Use VM class loader
  1325       PerfTraceTime vmtimer(ClassLoader::perf_sys_classload_time());
  1326       k = ClassLoader::load_classfile(class_name, CHECK_(nh));
  1329     // find_or_define_instance_class may return a different InstanceKlass
  1330     if (!k.is_null()) {
  1331       k = find_or_define_instance_class(class_name, class_loader, k, CHECK_(nh));
  1333     return k;
  1334   } else {
  1335     // Use user specified class loader to load class. Call loadClass operation on class_loader.
  1336     ResourceMark rm(THREAD);
  1338     assert(THREAD->is_Java_thread(), "must be a JavaThread");
  1339     JavaThread* jt = (JavaThread*) THREAD;
  1341     PerfClassTraceTime vmtimer(ClassLoader::perf_app_classload_time(),
  1342                                ClassLoader::perf_app_classload_selftime(),
  1343                                ClassLoader::perf_app_classload_count(),
  1344                                jt->get_thread_stat()->perf_recursion_counts_addr(),
  1345                                jt->get_thread_stat()->perf_timers_addr(),
  1346                                PerfClassTraceTime::CLASS_LOAD);
  1348     Handle s = java_lang_String::create_from_symbol(class_name, CHECK_(nh));
  1349     // Translate to external class name format, i.e., convert '/' chars to '.'
  1350     Handle string = java_lang_String::externalize_classname(s, CHECK_(nh));
  1352     JavaValue result(T_OBJECT);
  1354     KlassHandle spec_klass (THREAD, SystemDictionary::ClassLoader_klass());
  1356     // Call public unsynchronized loadClass(String) directly for all class loaders
  1357     // for parallelCapable class loaders. JDK >=7, loadClass(String, boolean) will
  1358     // acquire a class-name based lock rather than the class loader object lock.
  1359     // JDK < 7 already acquire the class loader lock in loadClass(String, boolean),
  1360     // so the call to loadClassInternal() was not required.
  1361     //
  1362     // UnsyncloadClass flag means both call loadClass(String) and do
  1363     // not acquire the class loader lock even for class loaders that are
  1364     // not parallelCapable. This was a risky transitional
  1365     // flag for diagnostic purposes only. It is risky to call
  1366     // custom class loaders without synchronization.
  1367     // WARNING If a custom class loader does NOT synchronizer findClass, or callers of
  1368     // findClass, the UnsyncloadClass flag risks unexpected timing bugs in the field.
  1369     // Do NOT assume this will be supported in future releases.
  1370     //
  1371     // Added MustCallLoadClassInternal in case we discover in the field
  1372     // a customer that counts on this call
  1373     if (MustCallLoadClassInternal && has_loadClassInternal()) {
  1374       JavaCalls::call_special(&result,
  1375                               class_loader,
  1376                               spec_klass,
  1377                               vmSymbols::loadClassInternal_name(),
  1378                               vmSymbols::string_class_signature(),
  1379                               string,
  1380                               CHECK_(nh));
  1381     } else {
  1382       JavaCalls::call_virtual(&result,
  1383                               class_loader,
  1384                               spec_klass,
  1385                               vmSymbols::loadClass_name(),
  1386                               vmSymbols::string_class_signature(),
  1387                               string,
  1388                               CHECK_(nh));
  1391     assert(result.get_type() == T_OBJECT, "just checking");
  1392     oop obj = (oop) result.get_jobject();
  1394     // Primitive classes return null since forName() can not be
  1395     // used to obtain any of the Class objects representing primitives or void
  1396     if ((obj != NULL) && !(java_lang_Class::is_primitive(obj))) {
  1397       instanceKlassHandle k =
  1398                 instanceKlassHandle(THREAD, java_lang_Class::as_Klass(obj));
  1399       // For user defined Java class loaders, check that the name returned is
  1400       // the same as that requested.  This check is done for the bootstrap
  1401       // loader when parsing the class file.
  1402       if (class_name == k->name()) {
  1403         return k;
  1406     // Class is not found or has the wrong name, return NULL
  1407     return nh;
  1411 static void post_class_define_event(InstanceKlass* k, const ClassLoaderData* def_cld) {
  1412   EventClassDefine event;
  1413   if (event.should_commit()) {
  1414     event.set_definedClass(k);
  1415     event.set_definingClassLoader(def_cld);
  1416     event.commit();
  1420 void SystemDictionary::define_instance_class(instanceKlassHandle k, TRAPS) {
  1422   ClassLoaderData* loader_data = k->class_loader_data();
  1423   Handle class_loader_h(THREAD, loader_data->class_loader());
  1425   for (uintx it = 0; it < GCExpandToAllocateDelayMillis; it++){}
  1427  // for bootstrap and other parallel classloaders don't acquire lock,
  1428  // use placeholder token
  1429  // If a parallelCapable class loader calls define_instance_class instead of
  1430  // find_or_define_instance_class to get here, we have a timing
  1431  // hole with systemDictionary updates and check_constraints
  1432  if (!class_loader_h.is_null() && !is_parallelCapable(class_loader_h)) {
  1433     assert(ObjectSynchronizer::current_thread_holds_lock((JavaThread*)THREAD,
  1434          compute_loader_lock_object(class_loader_h, THREAD)),
  1435          "define called without lock");
  1438   // Check class-loading constraints. Throw exception if violation is detected.
  1439   // Grabs and releases SystemDictionary_lock
  1440   // The check_constraints/find_class call and update_dictionary sequence
  1441   // must be "atomic" for a specific class/classloader pair so we never
  1442   // define two different instanceKlasses for that class/classloader pair.
  1443   // Existing classloaders will call define_instance_class with the
  1444   // classloader lock held
  1445   // Parallel classloaders will call find_or_define_instance_class
  1446   // which will require a token to perform the define class
  1447   Symbol*  name_h = k->name();
  1448   unsigned int d_hash = dictionary()->compute_hash(name_h, loader_data);
  1449   int d_index = dictionary()->hash_to_index(d_hash);
  1450   check_constraints(d_index, d_hash, k, class_loader_h, true, CHECK);
  1452   // Register class just loaded with class loader (placed in Vector)
  1453   // Note we do this before updating the dictionary, as this can
  1454   // fail with an OutOfMemoryError (if it does, we will *not* put this
  1455   // class in the dictionary and will not update the class hierarchy).
  1456   // JVMTI FollowReferences needs to find the classes this way.
  1457   if (k->class_loader() != NULL) {
  1458     methodHandle m(THREAD, Universe::loader_addClass_method());
  1459     JavaValue result(T_VOID);
  1460     JavaCallArguments args(class_loader_h);
  1461     args.push_oop(Handle(THREAD, k->java_mirror()));
  1462     JavaCalls::call(&result, m, &args, CHECK);
  1465   // Add the new class. We need recompile lock during update of CHA.
  1467     unsigned int p_hash = placeholders()->compute_hash(name_h, loader_data);
  1468     int p_index = placeholders()->hash_to_index(p_hash);
  1470     MutexLocker mu_r(Compile_lock, THREAD);
  1472     // Add to class hierarchy, initialize vtables, and do possible
  1473     // deoptimizations.
  1474     add_to_hierarchy(k, CHECK); // No exception, but can block
  1476     // Add to systemDictionary - so other classes can see it.
  1477     // Grabs and releases SystemDictionary_lock
  1478     update_dictionary(d_index, d_hash, p_index, p_hash,
  1479                       k, class_loader_h, THREAD);
  1481   k->eager_initialize(THREAD);
  1483   // notify jvmti
  1484   if (JvmtiExport::should_post_class_load()) {
  1485       assert(THREAD->is_Java_thread(), "thread->is_Java_thread()");
  1486       JvmtiExport::post_class_load((JavaThread *) THREAD, k());
  1490   post_class_define_event(k(), loader_data);
  1493 // Support parallel classloading
  1494 // All parallel class loaders, including bootstrap classloader
  1495 // lock a placeholder entry for this class/class_loader pair
  1496 // to allow parallel defines of different classes for this class loader
  1497 // With AllowParallelDefine flag==true, in case they do not synchronize around
  1498 // FindLoadedClass/DefineClass, calls, we check for parallel
  1499 // loading for them, wait if a defineClass is in progress
  1500 // and return the initial requestor's results
  1501 // This flag does not apply to the bootstrap classloader.
  1502 // With AllowParallelDefine flag==false, call through to define_instance_class
  1503 // which will throw LinkageError: duplicate class definition.
  1504 // False is the requested default.
  1505 // For better performance, the class loaders should synchronize
  1506 // findClass(), i.e. FindLoadedClass/DefineClassIfAbsent or they
  1507 // potentially waste time reading and parsing the bytestream.
  1508 // Note: VM callers should ensure consistency of k/class_name,class_loader
  1509 instanceKlassHandle SystemDictionary::find_or_define_instance_class(Symbol* class_name, Handle class_loader, instanceKlassHandle k, TRAPS) {
  1511   instanceKlassHandle nh = instanceKlassHandle(); // null Handle
  1512   Symbol*  name_h = k->name(); // passed in class_name may be null
  1513   ClassLoaderData* loader_data = class_loader_data(class_loader);
  1515   unsigned int d_hash = dictionary()->compute_hash(name_h, loader_data);
  1516   int d_index = dictionary()->hash_to_index(d_hash);
  1518 // Hold SD lock around find_class and placeholder creation for DEFINE_CLASS
  1519   unsigned int p_hash = placeholders()->compute_hash(name_h, loader_data);
  1520   int p_index = placeholders()->hash_to_index(p_hash);
  1521   PlaceholderEntry* probe;
  1524     MutexLocker mu(SystemDictionary_lock, THREAD);
  1525     // First check if class already defined
  1526     if (UnsyncloadClass || (is_parallelDefine(class_loader))) {
  1527       Klass* check = find_class(d_index, d_hash, name_h, loader_data);
  1528       if (check != NULL) {
  1529         return(instanceKlassHandle(THREAD, check));
  1533     // Acquire define token for this class/classloader
  1534     probe = placeholders()->find_and_add(p_index, p_hash, name_h, loader_data, PlaceholderTable::DEFINE_CLASS, NULL, THREAD);
  1535     // Wait if another thread defining in parallel
  1536     // All threads wait - even those that will throw duplicate class: otherwise
  1537     // caller is surprised by LinkageError: duplicate, but findLoadedClass fails
  1538     // if other thread has not finished updating dictionary
  1539     while (probe->definer() != NULL) {
  1540       SystemDictionary_lock->wait();
  1542     // Only special cases allow parallel defines and can use other thread's results
  1543     // Other cases fall through, and may run into duplicate defines
  1544     // caught by finding an entry in the SystemDictionary
  1545     if ((UnsyncloadClass || is_parallelDefine(class_loader)) && (probe->instance_klass() != NULL)) {
  1546         placeholders()->find_and_remove(p_index, p_hash, name_h, loader_data, PlaceholderTable::DEFINE_CLASS, THREAD);
  1547         SystemDictionary_lock->notify_all();
  1548 #ifdef ASSERT
  1549         Klass* check = find_class(d_index, d_hash, name_h, loader_data);
  1550         assert(check != NULL, "definer missed recording success");
  1551 #endif
  1552         return(instanceKlassHandle(THREAD, probe->instance_klass()));
  1553     } else {
  1554       // This thread will define the class (even if earlier thread tried and had an error)
  1555       probe->set_definer(THREAD);
  1559   define_instance_class(k, THREAD);
  1561   Handle linkage_exception = Handle(); // null handle
  1563   // definer must notify any waiting threads
  1565     MutexLocker mu(SystemDictionary_lock, THREAD);
  1566     PlaceholderEntry* probe = placeholders()->get_entry(p_index, p_hash, name_h, loader_data);
  1567     assert(probe != NULL, "DEFINE_CLASS placeholder lost?");
  1568     if (probe != NULL) {
  1569       if (HAS_PENDING_EXCEPTION) {
  1570         linkage_exception = Handle(THREAD,PENDING_EXCEPTION);
  1571         CLEAR_PENDING_EXCEPTION;
  1572       } else {
  1573         probe->set_instance_klass(k());
  1575       probe->set_definer(NULL);
  1576       placeholders()->find_and_remove(p_index, p_hash, name_h, loader_data, PlaceholderTable::DEFINE_CLASS, THREAD);
  1577       SystemDictionary_lock->notify_all();
  1581   // Can't throw exception while holding lock due to rank ordering
  1582   if (linkage_exception() != NULL) {
  1583     THROW_OOP_(linkage_exception(), nh); // throws exception and returns
  1586   return k;
  1588 Handle SystemDictionary::compute_loader_lock_object(Handle class_loader, TRAPS) {
  1589   // If class_loader is NULL we synchronize on _system_loader_lock_obj
  1590   if (class_loader.is_null()) {
  1591     return Handle(THREAD, _system_loader_lock_obj);
  1592   } else {
  1593     return class_loader;
  1597 // This method is added to check how often we have to wait to grab loader
  1598 // lock. The results are being recorded in the performance counters defined in
  1599 // ClassLoader::_sync_systemLoaderLockContentionRate and
  1600 // ClassLoader::_sync_nonSystemLoaderLockConteionRate.
  1601 void SystemDictionary::check_loader_lock_contention(Handle loader_lock, TRAPS) {
  1602   if (!UsePerfData) {
  1603     return;
  1606   assert(!loader_lock.is_null(), "NULL lock object");
  1608   if (ObjectSynchronizer::query_lock_ownership((JavaThread*)THREAD, loader_lock)
  1609       == ObjectSynchronizer::owner_other) {
  1610     // contention will likely happen, so increment the corresponding
  1611     // contention counter.
  1612     if (loader_lock() == _system_loader_lock_obj) {
  1613       ClassLoader::sync_systemLoaderLockContentionRate()->inc();
  1614     } else {
  1615       ClassLoader::sync_nonSystemLoaderLockContentionRate()->inc();
  1620 // ----------------------------------------------------------------------------
  1621 // Lookup
  1623 Klass* SystemDictionary::find_class(int index, unsigned int hash,
  1624                                       Symbol* class_name,
  1625                                       ClassLoaderData* loader_data) {
  1626   assert_locked_or_safepoint(SystemDictionary_lock);
  1627   assert (index == dictionary()->index_for(class_name, loader_data),
  1628           "incorrect index?");
  1630   Klass* k = dictionary()->find_class(index, hash, class_name, loader_data);
  1631   return k;
  1635 // Basic find on classes in the midst of being loaded
  1636 Symbol* SystemDictionary::find_placeholder(Symbol* class_name,
  1637                                            ClassLoaderData* loader_data) {
  1638   assert_locked_or_safepoint(SystemDictionary_lock);
  1639   unsigned int p_hash = placeholders()->compute_hash(class_name, loader_data);
  1640   int p_index = placeholders()->hash_to_index(p_hash);
  1641   return placeholders()->find_entry(p_index, p_hash, class_name, loader_data);
  1645 // Used for assertions and verification only
  1646 Klass* SystemDictionary::find_class(Symbol* class_name, ClassLoaderData* loader_data) {
  1647   #ifndef ASSERT
  1648   guarantee(VerifyBeforeGC      ||
  1649             VerifyDuringGC      ||
  1650             VerifyBeforeExit    ||
  1651             VerifyDuringStartup ||
  1652             VerifyAfterGC, "too expensive");
  1653   #endif
  1654   assert_locked_or_safepoint(SystemDictionary_lock);
  1656   // First look in the loaded class array
  1657   unsigned int d_hash = dictionary()->compute_hash(class_name, loader_data);
  1658   int d_index = dictionary()->hash_to_index(d_hash);
  1659   return find_class(d_index, d_hash, class_name, loader_data);
  1663 // Get the next class in the diictionary.
  1664 Klass* SystemDictionary::try_get_next_class() {
  1665   return dictionary()->try_get_next_class();
  1669 // ----------------------------------------------------------------------------
  1670 // Update hierachy. This is done before the new klass has been added to the SystemDictionary. The Recompile_lock
  1671 // is held, to ensure that the compiler is not using the class hierachy, and that deoptimization will kick in
  1672 // before a new class is used.
  1674 void SystemDictionary::add_to_hierarchy(instanceKlassHandle k, TRAPS) {
  1675   assert(k.not_null(), "just checking");
  1676   assert_locked_or_safepoint(Compile_lock);
  1678   // Link into hierachy. Make sure the vtables are initialized before linking into
  1679   k->append_to_sibling_list();                    // add to superklass/sibling list
  1680   k->process_interfaces(THREAD);                  // handle all "implements" declarations
  1681   k->set_init_state(InstanceKlass::loaded);
  1682   // Now flush all code that depended on old class hierarchy.
  1683   // Note: must be done *after* linking k into the hierarchy (was bug 12/9/97)
  1684   // Also, first reinitialize vtable because it may have gotten out of synch
  1685   // while the new class wasn't connected to the class hierarchy.
  1686   Universe::flush_dependents_on(k);
  1689 // ----------------------------------------------------------------------------
  1690 // GC support
  1692 // Following roots during mark-sweep is separated in two phases.
  1693 //
  1694 // The first phase follows preloaded classes and all other system
  1695 // classes, since these will never get unloaded anyway.
  1696 //
  1697 // The second phase removes (unloads) unreachable classes from the
  1698 // system dictionary and follows the remaining classes' contents.
  1700 void SystemDictionary::always_strong_oops_do(OopClosure* blk) {
  1701   roots_oops_do(blk, NULL);
  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;
  1728 #ifdef ASSERT
  1729 class VerifySDReachableAndLiveClosure : public OopClosure {
  1730 private:
  1731   BoolObjectClosure* _is_alive;
  1733   template <class T> void do_oop_work(T* p) {
  1734     oop obj = oopDesc::load_decode_heap_oop(p);
  1735     guarantee(_is_alive->do_object_b(obj), "Oop in system dictionary must be live");
  1738 public:
  1739   VerifySDReachableAndLiveClosure(BoolObjectClosure* is_alive) : OopClosure(), _is_alive(is_alive) { }
  1741   virtual void do_oop(oop* p)       { do_oop_work(p); }
  1742   virtual void do_oop(narrowOop* p) { do_oop_work(p); }
  1743 };
  1744 #endif
  1746 // Assumes classes in the SystemDictionary are only unloaded at a safepoint
  1747 // Note: anonymous classes are not in the SD.
  1748 bool SystemDictionary::do_unloading(BoolObjectClosure* is_alive, bool clean_alive) {
  1749   // First, mark for unload all ClassLoaderData referencing a dead class loader.
  1750   bool unloading_occurred = ClassLoaderDataGraph::do_unloading(is_alive, clean_alive);
  1751   if (unloading_occurred) {
  1752     dictionary()->do_unloading();
  1753     constraints()->purge_loader_constraints();
  1754     resolution_errors()->purge_resolution_errors();
  1756   // Oops referenced by the system dictionary may get unreachable independently
  1757   // of the class loader (eg. cached protection domain oops). So we need to
  1758   // explicitly unlink them here instead of in Dictionary::do_unloading.
  1759   dictionary()->unlink(is_alive);
  1760 #ifdef ASSERT
  1761   VerifySDReachableAndLiveClosure cl(is_alive);
  1762   dictionary()->oops_do(&cl);
  1763 #endif
  1764   return unloading_occurred;
  1767 void SystemDictionary::roots_oops_do(OopClosure* strong, OopClosure* weak) {
  1768   strong->do_oop(&_java_system_loader);
  1769   strong->do_oop(&_system_loader_lock_obj);
  1770   CDS_ONLY(SystemDictionaryShared::roots_oops_do(strong);)
  1772   // Adjust dictionary
  1773   dictionary()->roots_oops_do(strong, weak);
  1775   // Visit extra methods
  1776   invoke_method_table()->oops_do(strong);
  1779 void SystemDictionary::oops_do(OopClosure* f) {
  1780   f->do_oop(&_java_system_loader);
  1781   f->do_oop(&_system_loader_lock_obj);
  1782   CDS_ONLY(SystemDictionaryShared::oops_do(f);)
  1784   // Adjust dictionary
  1785   dictionary()->oops_do(f);
  1787   // Visit extra methods
  1788   invoke_method_table()->oops_do(f);
  1791 // Extended Class redefinition support.
  1792 // If one of these classes is replaced, we need to replace it in these places.
  1793 // KlassClosure::do_klass should take the address of a class but we can
  1794 // change that later.
  1795 void SystemDictionary::preloaded_classes_do(KlassClosure* f) {
  1796   for (int k = (int)FIRST_WKID; k < (int)WKID_LIMIT; k++) {
  1797     f->do_klass(_well_known_klasses[k]);
  1801     for (int i = 0; i < T_VOID+1; i++) {
  1802       if (_box_klasses[i] != NULL) {
  1803         assert(i >= T_BOOLEAN, "checking");
  1804         f->do_klass(_box_klasses[i]);
  1809   FilteredFieldsMap::classes_do(f);
  1812 void SystemDictionary::lazily_loaded_classes_do(KlassClosure* f) {
  1813   f->do_klass(_abstract_ownable_synchronizer_klass);
  1816 // Just the classes from defining class loaders
  1817 // Don't iterate over placeholders
  1818 void SystemDictionary::classes_do(void f(Klass*)) {
  1819   dictionary()->classes_do(f);
  1822 // Added for initialize_itable_for_klass
  1823 //   Just the classes from defining class loaders
  1824 // Don't iterate over placeholders
  1825 void SystemDictionary::classes_do(void f(Klass*, TRAPS), TRAPS) {
  1826   dictionary()->classes_do(f, CHECK);
  1829 //   All classes, and their class loaders
  1830 // Don't iterate over placeholders
  1831 void SystemDictionary::classes_do(void f(Klass*, ClassLoaderData*)) {
  1832   dictionary()->classes_do(f);
  1835 void SystemDictionary::placeholders_do(void f(Symbol*)) {
  1836   placeholders()->entries_do(f);
  1839 void SystemDictionary::methods_do(void f(Method*)) {
  1840   dictionary()->methods_do(f);
  1841   invoke_method_table()->methods_do(f);
  1844 void SystemDictionary::remove_classes_in_error_state() {
  1845   dictionary()->remove_classes_in_error_state();
  1848 // ----------------------------------------------------------------------------
  1849 // Lazily load klasses
  1851 void SystemDictionary::load_abstract_ownable_synchronizer_klass(TRAPS) {
  1852   assert(JDK_Version::is_gte_jdk16x_version(), "Must be JDK 1.6 or later");
  1854   // if multiple threads calling this function, only one thread will load
  1855   // the class.  The other threads will find the loaded version once the
  1856   // class is loaded.
  1857   Klass* aos = _abstract_ownable_synchronizer_klass;
  1858   if (aos == NULL) {
  1859     Klass* k = resolve_or_fail(vmSymbols::java_util_concurrent_locks_AbstractOwnableSynchronizer(), true, CHECK);
  1860     // Force a fence to prevent any read before the write completes
  1861     OrderAccess::fence();
  1862     _abstract_ownable_synchronizer_klass = k;
  1866 // ----------------------------------------------------------------------------
  1867 // Initialization
  1869 void SystemDictionary::initialize(TRAPS) {
  1870   // Allocate arrays
  1871   assert(dictionary() == NULL,
  1872          "SystemDictionary should only be initialized once");
  1873   _sdgeneration        = 0;
  1874   _dictionary          = new Dictionary(calculate_systemdictionary_size(PredictedLoadedClassCount));
  1875   _placeholders        = new PlaceholderTable(_nof_buckets);
  1876   _number_of_modifications = 0;
  1877   _loader_constraints  = new LoaderConstraintTable(_loader_constraint_size);
  1878   _resolution_errors   = new ResolutionErrorTable(_resolution_error_size);
  1879   _invoke_method_table = new SymbolPropertyTable(_invoke_method_size);
  1881   // Allocate private object used as system class loader lock
  1882   _system_loader_lock_obj = oopFactory::new_intArray(0, CHECK);
  1883   // Initialize basic classes
  1884   initialize_preloaded_classes(CHECK);
  1887 // Compact table of directions on the initialization of klasses:
  1888 static const short wk_init_info[] = {
  1889   #define WK_KLASS_INIT_INFO(name, symbol, option) \
  1890     ( ((int)vmSymbols::VM_SYMBOL_ENUM_NAME(symbol) \
  1891           << SystemDictionary::CEIL_LG_OPTION_LIMIT) \
  1892       | (int)SystemDictionary::option ),
  1893   WK_KLASSES_DO(WK_KLASS_INIT_INFO)
  1894   #undef WK_KLASS_INIT_INFO
  1896 };
  1898 bool SystemDictionary::initialize_wk_klass(WKID id, int init_opt, TRAPS) {
  1899   assert(id >= (int)FIRST_WKID && id < (int)WKID_LIMIT, "oob");
  1900   int  info = wk_init_info[id - FIRST_WKID];
  1901   int  sid  = (info >> CEIL_LG_OPTION_LIMIT);
  1902   Symbol* symbol = vmSymbols::symbol_at((vmSymbols::SID)sid);
  1903   Klass**    klassp = &_well_known_klasses[id];
  1904   bool must_load = (init_opt < SystemDictionary::Opt);
  1905   if ((*klassp) == NULL) {
  1906     if (must_load) {
  1907       (*klassp) = resolve_or_fail(symbol, true, CHECK_0); // load required class
  1908     } else {
  1909       (*klassp) = resolve_or_null(symbol,       CHECK_0); // load optional klass
  1912   return ((*klassp) != NULL);
  1915 void SystemDictionary::initialize_wk_klasses_until(WKID limit_id, WKID &start_id, TRAPS) {
  1916   assert((int)start_id <= (int)limit_id, "IDs are out of order!");
  1917   for (int id = (int)start_id; id < (int)limit_id; id++) {
  1918     assert(id >= (int)FIRST_WKID && id < (int)WKID_LIMIT, "oob");
  1919     int info = wk_init_info[id - FIRST_WKID];
  1920     int sid  = (info >> CEIL_LG_OPTION_LIMIT);
  1921     int opt  = (info & right_n_bits(CEIL_LG_OPTION_LIMIT));
  1923     initialize_wk_klass((WKID)id, opt, CHECK);
  1926   // move the starting value forward to the limit:
  1927   start_id = limit_id;
  1930 void SystemDictionary::initialize_preloaded_classes(TRAPS) {
  1931   assert(WK_KLASS(Object_klass) == NULL, "preloaded classes should only be initialized once");
  1932   // Preload commonly used klasses
  1933   WKID scan = FIRST_WKID;
  1934   // first do Object, then String, Class
  1935   if (UseSharedSpaces) {
  1936     initialize_wk_klasses_through(WK_KLASS_ENUM_NAME(Object_klass), scan, CHECK);
  1937     // Initialize the constant pool for the Object_class
  1938     InstanceKlass* ik = InstanceKlass::cast(Object_klass());
  1939     ik->constants()->restore_unshareable_info(CHECK);
  1940     initialize_wk_klasses_through(WK_KLASS_ENUM_NAME(Class_klass), scan, CHECK);
  1941   } else {
  1942     initialize_wk_klasses_through(WK_KLASS_ENUM_NAME(Class_klass), scan, CHECK);
  1945   // Calculate offsets for String and Class classes since they are loaded and
  1946   // can be used after this point.
  1947   java_lang_String::compute_offsets();
  1948   java_lang_Class::compute_offsets();
  1950   // Fixup mirrors for classes loaded before java.lang.Class.
  1951   // These calls iterate over the objects currently in the perm gen
  1952   // so calling them at this point is matters (not before when there
  1953   // are fewer objects and not later after there are more objects
  1954   // in the perm gen.
  1955   Universe::initialize_basic_type_mirrors(CHECK);
  1956   Universe::fixup_mirrors(CHECK);
  1958   // do a bunch more:
  1959   initialize_wk_klasses_through(WK_KLASS_ENUM_NAME(Reference_klass), scan, CHECK);
  1961   // Preload ref klasses and set reference types
  1962   InstanceKlass::cast(WK_KLASS(Reference_klass))->set_reference_type(REF_OTHER);
  1963   InstanceRefKlass::update_nonstatic_oop_maps(WK_KLASS(Reference_klass));
  1965   initialize_wk_klasses_through(WK_KLASS_ENUM_NAME(Cleaner_klass), scan, CHECK);
  1966   InstanceKlass::cast(WK_KLASS(SoftReference_klass))->set_reference_type(REF_SOFT);
  1967   InstanceKlass::cast(WK_KLASS(WeakReference_klass))->set_reference_type(REF_WEAK);
  1968   InstanceKlass::cast(WK_KLASS(FinalReference_klass))->set_reference_type(REF_FINAL);
  1969   InstanceKlass::cast(WK_KLASS(PhantomReference_klass))->set_reference_type(REF_PHANTOM);
  1970   InstanceKlass::cast(WK_KLASS(Cleaner_klass))->set_reference_type(REF_CLEANER);
  1972   initialize_wk_klasses_through(WK_KLASS_ENUM_NAME(ReferenceQueue_klass), scan, CHECK);
  1974   // JSR 292 classes
  1975   WKID jsr292_group_start = WK_KLASS_ENUM_NAME(MethodHandle_klass);
  1976   WKID jsr292_group_end   = WK_KLASS_ENUM_NAME(VolatileCallSite_klass);
  1977   initialize_wk_klasses_until(jsr292_group_start, scan, CHECK);
  1978   if (EnableInvokeDynamic) {
  1979     initialize_wk_klasses_through(jsr292_group_end, scan, CHECK);
  1980   } else {
  1981     // Skip the JSR 292 classes, if not enabled.
  1982     scan = WKID(jsr292_group_end + 1);
  1985   initialize_wk_klasses_until(WKID_LIMIT, scan, CHECK);
  1987   _box_klasses[T_BOOLEAN] = WK_KLASS(Boolean_klass);
  1988   _box_klasses[T_CHAR]    = WK_KLASS(Character_klass);
  1989   _box_klasses[T_FLOAT]   = WK_KLASS(Float_klass);
  1990   _box_klasses[T_DOUBLE]  = WK_KLASS(Double_klass);
  1991   _box_klasses[T_BYTE]    = WK_KLASS(Byte_klass);
  1992   _box_klasses[T_SHORT]   = WK_KLASS(Short_klass);
  1993   _box_klasses[T_INT]     = WK_KLASS(Integer_klass);
  1994   _box_klasses[T_LONG]    = WK_KLASS(Long_klass);
  1995   //_box_klasses[T_OBJECT]  = WK_KLASS(object_klass);
  1996   //_box_klasses[T_ARRAY]   = WK_KLASS(object_klass);
  1998   { // Compute whether we should use loadClass or loadClassInternal when loading classes.
  1999     Method* method = InstanceKlass::cast(ClassLoader_klass())->find_method(vmSymbols::loadClassInternal_name(), vmSymbols::string_class_signature());
  2000     _has_loadClassInternal = (method != NULL);
  2002   { // Compute whether we should use checkPackageAccess or NOT
  2003     Method* method = InstanceKlass::cast(ClassLoader_klass())->find_method(vmSymbols::checkPackageAccess_name(), vmSymbols::class_protectiondomain_signature());
  2004     _has_checkPackageAccess = (method != NULL);
  2008 // Tells if a given klass is a box (wrapper class, such as java.lang.Integer).
  2009 // If so, returns the basic type it holds.  If not, returns T_OBJECT.
  2010 BasicType SystemDictionary::box_klass_type(Klass* k) {
  2011   assert(k != NULL, "");
  2012   for (int i = T_BOOLEAN; i < T_VOID+1; i++) {
  2013     if (_box_klasses[i] == k)
  2014       return (BasicType)i;
  2016   return T_OBJECT;
  2019 // Constraints on class loaders. The details of the algorithm can be
  2020 // found in the OOPSLA'98 paper "Dynamic Class Loading in the Java
  2021 // Virtual Machine" by Sheng Liang and Gilad Bracha.  The basic idea is
  2022 // that the system dictionary needs to maintain a set of contraints that
  2023 // must be satisfied by all classes in the dictionary.
  2024 // if defining is true, then LinkageError if already in systemDictionary
  2025 // if initiating loader, then ok if InstanceKlass matches existing entry
  2027 void SystemDictionary::check_constraints(int d_index, unsigned int d_hash,
  2028                                          instanceKlassHandle k,
  2029                                          Handle class_loader, bool defining,
  2030                                          TRAPS) {
  2031   const char *linkage_error = NULL;
  2033     Symbol*  name  = k->name();
  2034     ClassLoaderData *loader_data = class_loader_data(class_loader);
  2036     MutexLocker mu(SystemDictionary_lock, THREAD);
  2038     Klass* check = find_class(d_index, d_hash, name, loader_data);
  2039     if (check != (Klass*)NULL) {
  2040       // if different InstanceKlass - duplicate class definition,
  2041       // else - ok, class loaded by a different thread in parallel,
  2042       // we should only have found it if it was done loading and ok to use
  2043       // system dictionary only holds instance classes, placeholders
  2044       // also holds array classes
  2046       assert(check->oop_is_instance(), "noninstance in systemdictionary");
  2047       if ((defining == true) || (k() != check)) {
  2048         linkage_error = "loader (instance of  %s): attempted  duplicate class "
  2049           "definition for name: \"%s\"";
  2050       } else {
  2051         return;
  2055 #ifdef ASSERT
  2056     Symbol* ph_check = find_placeholder(name, loader_data);
  2057     assert(ph_check == NULL || ph_check == name, "invalid symbol");
  2058 #endif
  2060     if (linkage_error == NULL) {
  2061       if (constraints()->check_or_update(k, class_loader, name) == false) {
  2062         linkage_error = "loader constraint violation: loader (instance of %s)"
  2063           " previously initiated loading for a different type with name \"%s\"";
  2068   // Throw error now if needed (cannot throw while holding
  2069   // SystemDictionary_lock because of rank ordering)
  2071   if (linkage_error) {
  2072     ResourceMark rm(THREAD);
  2073     const char* class_loader_name = loader_name(class_loader());
  2074     char* type_name = k->name()->as_C_string();
  2075     size_t buflen = strlen(linkage_error) + strlen(class_loader_name) +
  2076       strlen(type_name);
  2077     char* buf = NEW_RESOURCE_ARRAY_IN_THREAD(THREAD, char, buflen);
  2078     jio_snprintf(buf, buflen, linkage_error, class_loader_name, type_name);
  2079     THROW_MSG(vmSymbols::java_lang_LinkageError(), buf);
  2084 // Update system dictionary - done after check_constraint and add_to_hierachy
  2085 // have been called.
  2086 void SystemDictionary::update_dictionary(int d_index, unsigned int d_hash,
  2087                                          int p_index, unsigned int p_hash,
  2088                                          instanceKlassHandle k,
  2089                                          Handle class_loader,
  2090                                          TRAPS) {
  2091   // Compile_lock prevents systemDictionary updates during compilations
  2092   assert_locked_or_safepoint(Compile_lock);
  2093   Symbol*  name  = k->name();
  2094   ClassLoaderData *loader_data = class_loader_data(class_loader);
  2097   MutexLocker mu1(SystemDictionary_lock, THREAD);
  2099   // See whether biased locking is enabled and if so set it for this
  2100   // klass.
  2101   // Note that this must be done past the last potential blocking
  2102   // point / safepoint. We enable biased locking lazily using a
  2103   // VM_Operation to iterate the SystemDictionary and installing the
  2104   // biasable mark word into each InstanceKlass's prototype header.
  2105   // To avoid race conditions where we accidentally miss enabling the
  2106   // optimization for one class in the process of being added to the
  2107   // dictionary, we must not safepoint after the test of
  2108   // BiasedLocking::enabled().
  2109   if (UseBiasedLocking && BiasedLocking::enabled()) {
  2110     // Set biased locking bit for all loaded classes; it will be
  2111     // cleared if revocation occurs too often for this type
  2112     // NOTE that we must only do this when the class is initally
  2113     // defined, not each time it is referenced from a new class loader
  2114     if (k->class_loader() == class_loader()) {
  2115       k->set_prototype_header(markOopDesc::biased_locking_prototype());
  2119   // Make a new system dictionary entry.
  2120   Klass* sd_check = find_class(d_index, d_hash, name, loader_data);
  2121   if (sd_check == NULL) {
  2122     dictionary()->add_klass(name, loader_data, k);
  2123     notice_modification();
  2125 #ifdef ASSERT
  2126   sd_check = find_class(d_index, d_hash, name, loader_data);
  2127   assert (sd_check != NULL, "should have entry in system dictionary");
  2128   // Note: there may be a placeholder entry: for circularity testing
  2129   // or for parallel defines
  2130 #endif
  2131     SystemDictionary_lock->notify_all();
  2136 // Try to find a class name using the loader constraints.  The
  2137 // loader constraints might know about a class that isn't fully loaded
  2138 // yet and these will be ignored.
  2139 Klass* SystemDictionary::find_constrained_instance_or_array_klass(
  2140                     Symbol* class_name, Handle class_loader, TRAPS) {
  2142   // First see if it has been loaded directly.
  2143   // Force the protection domain to be null.  (This removes protection checks.)
  2144   Handle no_protection_domain;
  2145   Klass* klass = find_instance_or_array_klass(class_name, class_loader,
  2146                                               no_protection_domain, CHECK_NULL);
  2147   if (klass != NULL)
  2148     return klass;
  2150   // Now look to see if it has been loaded elsewhere, and is subject to
  2151   // a loader constraint that would require this loader to return the
  2152   // klass that is already loaded.
  2153   if (FieldType::is_array(class_name)) {
  2154     // For array classes, their Klass*s are not kept in the
  2155     // constraint table. The element Klass*s are.
  2156     FieldArrayInfo fd;
  2157     BasicType t = FieldType::get_array_info(class_name, fd, CHECK_(NULL));
  2158     if (t != T_OBJECT) {
  2159       klass = Universe::typeArrayKlassObj(t);
  2160     } else {
  2161       MutexLocker mu(SystemDictionary_lock, THREAD);
  2162       klass = constraints()->find_constrained_klass(fd.object_key(), class_loader);
  2164     // If element class already loaded, allocate array klass
  2165     if (klass != NULL) {
  2166       klass = klass->array_klass_or_null(fd.dimension());
  2168   } else {
  2169     MutexLocker mu(SystemDictionary_lock, THREAD);
  2170     // Non-array classes are easy: simply check the constraint table.
  2171     klass = constraints()->find_constrained_klass(class_name, class_loader);
  2174   return klass;
  2178 bool SystemDictionary::add_loader_constraint(Symbol* class_name,
  2179                                              Handle class_loader1,
  2180                                              Handle class_loader2,
  2181                                              Thread* THREAD) {
  2182   ClassLoaderData* loader_data1 = class_loader_data(class_loader1);
  2183   ClassLoaderData* loader_data2 = class_loader_data(class_loader2);
  2185   Symbol* constraint_name = NULL;
  2186   if (!FieldType::is_array(class_name)) {
  2187     constraint_name = class_name;
  2188   } else {
  2189     // For array classes, their Klass*s are not kept in the
  2190     // constraint table. The element classes are.
  2191     FieldArrayInfo fd;
  2192     BasicType t = FieldType::get_array_info(class_name, fd, CHECK_(false));
  2193     // primitive types always pass
  2194     if (t != T_OBJECT) {
  2195       return true;
  2196     } else {
  2197       constraint_name = fd.object_key();
  2200   unsigned int d_hash1 = dictionary()->compute_hash(constraint_name, loader_data1);
  2201   int d_index1 = dictionary()->hash_to_index(d_hash1);
  2203   unsigned int d_hash2 = dictionary()->compute_hash(constraint_name, loader_data2);
  2204   int d_index2 = dictionary()->hash_to_index(d_hash2);
  2206   MutexLocker mu_s(SystemDictionary_lock, THREAD);
  2208   // Better never do a GC while we're holding these oops
  2209   No_Safepoint_Verifier nosafepoint;
  2211   Klass* klass1 = find_class(d_index1, d_hash1, constraint_name, loader_data1);
  2212   Klass* klass2 = find_class(d_index2, d_hash2, constraint_name, loader_data2);
  2213   return constraints()->add_entry(constraint_name, klass1, class_loader1,
  2214                                   klass2, class_loader2);
  2218 // Add entry to resolution error table to record the error when the first
  2219 // attempt to resolve a reference to a class has failed.
  2220 void SystemDictionary::add_resolution_error(constantPoolHandle pool, int which, Symbol* error) {
  2221   unsigned int hash = resolution_errors()->compute_hash(pool, which);
  2222   int index = resolution_errors()->hash_to_index(hash);
  2224     MutexLocker ml(SystemDictionary_lock, Thread::current());
  2225     resolution_errors()->add_entry(index, hash, pool, which, error);
  2229 // Delete a resolution error for RedefineClasses for a constant pool is going away
  2230 void SystemDictionary::delete_resolution_error(ConstantPool* pool) {
  2231   resolution_errors()->delete_entry(pool);
  2234 // Lookup resolution error table. Returns error if found, otherwise NULL.
  2235 Symbol* SystemDictionary::find_resolution_error(constantPoolHandle pool, int which) {
  2236   unsigned int hash = resolution_errors()->compute_hash(pool, which);
  2237   int index = resolution_errors()->hash_to_index(hash);
  2239     MutexLocker ml(SystemDictionary_lock, Thread::current());
  2240     ResolutionErrorEntry* entry = resolution_errors()->find_entry(index, hash, pool, which);
  2241     return (entry != NULL) ? entry->error() : (Symbol*)NULL;
  2246 // Signature constraints ensure that callers and callees agree about
  2247 // the meaning of type names in their signatures.  This routine is the
  2248 // intake for constraints.  It collects them from several places:
  2249 //
  2250 //  * LinkResolver::resolve_method (if check_access is true) requires
  2251 //    that the resolving class (the caller) and the defining class of
  2252 //    the resolved method (the callee) agree on each type in the
  2253 //    method's signature.
  2254 //
  2255 //  * LinkResolver::resolve_interface_method performs exactly the same
  2256 //    checks.
  2257 //
  2258 //  * LinkResolver::resolve_field requires that the constant pool
  2259 //    attempting to link to a field agree with the field's defining
  2260 //    class about the type of the field signature.
  2261 //
  2262 //  * klassVtable::initialize_vtable requires that, when a class
  2263 //    overrides a vtable entry allocated by a superclass, that the
  2264 //    overriding method (i.e., the callee) agree with the superclass
  2265 //    on each type in the method's signature.
  2266 //
  2267 //  * klassItable::initialize_itable requires that, when a class fills
  2268 //    in its itables, for each non-abstract method installed in an
  2269 //    itable, the method (i.e., the callee) agree with the interface
  2270 //    on each type in the method's signature.
  2271 //
  2272 // All those methods have a boolean (check_access, checkconstraints)
  2273 // which turns off the checks.  This is used from specialized contexts
  2274 // such as bootstrapping, dumping, and debugging.
  2275 //
  2276 // No direct constraint is placed between the class and its
  2277 // supertypes.  Constraints are only placed along linked relations
  2278 // between callers and callees.  When a method overrides or implements
  2279 // an abstract method in a supertype (superclass or interface), the
  2280 // constraints are placed as if the supertype were the caller to the
  2281 // overriding method.  (This works well, since callers to the
  2282 // supertype have already established agreement between themselves and
  2283 // the supertype.)  As a result of all this, a class can disagree with
  2284 // its supertype about the meaning of a type name, as long as that
  2285 // class neither calls a relevant method of the supertype, nor is
  2286 // called (perhaps via an override) from the supertype.
  2287 //
  2288 //
  2289 // SystemDictionary::check_signature_loaders(sig, l1, l2)
  2290 //
  2291 // Make sure all class components (including arrays) in the given
  2292 // signature will be resolved to the same class in both loaders.
  2293 // Returns the name of the type that failed a loader constraint check, or
  2294 // NULL if no constraint failed.  No exception except OOME is thrown.
  2295 // Arrays are not added to the loader constraint table, their elements are.
  2296 Symbol* SystemDictionary::check_signature_loaders(Symbol* signature,
  2297                                                Handle loader1, Handle loader2,
  2298                                                bool is_method, TRAPS)  {
  2299   // Nothing to do if loaders are the same.
  2300   if (loader1() == loader2()) {
  2301     return NULL;
  2304   SignatureStream sig_strm(signature, is_method);
  2305   while (!sig_strm.is_done()) {
  2306     if (sig_strm.is_object()) {
  2307       Symbol* sig = sig_strm.as_symbol(CHECK_NULL);
  2308       if (!add_loader_constraint(sig, loader1, loader2, THREAD)) {
  2309         return sig;
  2312     sig_strm.next();
  2314   return NULL;
  2318 methodHandle SystemDictionary::find_method_handle_intrinsic(vmIntrinsics::ID iid,
  2319                                                             Symbol* signature,
  2320                                                             TRAPS) {
  2321   methodHandle empty;
  2322   assert(EnableInvokeDynamic, "");
  2323   assert(MethodHandles::is_signature_polymorphic(iid) &&
  2324          MethodHandles::is_signature_polymorphic_intrinsic(iid) &&
  2325          iid != vmIntrinsics::_invokeGeneric,
  2326          err_msg("must be a known MH intrinsic iid=%d: %s", iid, vmIntrinsics::name_at(iid)));
  2328   unsigned int hash  = invoke_method_table()->compute_hash(signature, iid);
  2329   int          index = invoke_method_table()->hash_to_index(hash);
  2330   SymbolPropertyEntry* spe = invoke_method_table()->find_entry(index, hash, signature, iid);
  2331   methodHandle m;
  2332   if (spe == NULL || spe->method() == NULL) {
  2333     spe = NULL;
  2334     // Must create lots of stuff here, but outside of the SystemDictionary lock.
  2335     m = Method::make_method_handle_intrinsic(iid, signature, CHECK_(empty));
  2336     if (!Arguments::is_interpreter_only()) {
  2337       // Generate a compiled form of the MH intrinsic.
  2338       AdapterHandlerLibrary::create_native_wrapper(m);
  2339       // Check if have the compiled code.
  2340       if (!m->has_compiled_code()) {
  2341         THROW_MSG_(vmSymbols::java_lang_VirtualMachineError(),
  2342                    "out of space in CodeCache for method handle intrinsic", empty);
  2345     // Now grab the lock.  We might have to throw away the new method,
  2346     // if a racing thread has managed to install one at the same time.
  2348       MutexLocker ml(SystemDictionary_lock, THREAD);
  2349       spe = invoke_method_table()->find_entry(index, hash, signature, iid);
  2350       if (spe == NULL)
  2351         spe = invoke_method_table()->add_entry(index, hash, signature, iid);
  2352       if (spe->method() == NULL)
  2353         spe->set_method(m());
  2357   assert(spe != NULL && spe->method() != NULL, "");
  2358   assert(Arguments::is_interpreter_only() || (spe->method()->has_compiled_code() &&
  2359          spe->method()->code()->entry_point() == spe->method()->from_compiled_entry()),
  2360          "MH intrinsic invariant");
  2361   return spe->method();
  2364 // Helper for unpacking the return value from linkMethod and linkCallSite.
  2365 static methodHandle unpack_method_and_appendix(Handle mname,
  2366                                                KlassHandle accessing_klass,
  2367                                                objArrayHandle appendix_box,
  2368                                                Handle* appendix_result,
  2369                                                TRAPS) {
  2370   methodHandle empty;
  2371   if (mname.not_null()) {
  2372     Metadata* vmtarget = java_lang_invoke_MemberName::vmtarget(mname());
  2373     if (vmtarget != NULL && vmtarget->is_method()) {
  2374       Method* m = (Method*)vmtarget;
  2375       oop appendix = appendix_box->obj_at(0);
  2376       if (TraceMethodHandles) {
  2377     #ifndef PRODUCT
  2378         tty->print("Linked method=" INTPTR_FORMAT ": ", p2i(m));
  2379         m->print();
  2380         if (appendix != NULL) { tty->print("appendix = "); appendix->print(); }
  2381         tty->cr();
  2382     #endif //PRODUCT
  2384       (*appendix_result) = Handle(THREAD, appendix);
  2385       // the target is stored in the cpCache and if a reference to this
  2386       // MethodName is dropped we need a way to make sure the
  2387       // class_loader containing this method is kept alive.
  2388       // FIXME: the appendix might also preserve this dependency.
  2389       ClassLoaderData* this_key = InstanceKlass::cast(accessing_klass())->class_loader_data();
  2390       this_key->record_dependency(m->method_holder(), CHECK_NULL); // Can throw OOM
  2391       return methodHandle(THREAD, m);
  2394   THROW_MSG_(vmSymbols::java_lang_LinkageError(), "bad value from MethodHandleNatives", empty);
  2395   return empty;
  2398 methodHandle SystemDictionary::find_method_handle_invoker(Symbol* name,
  2399                                                           Symbol* signature,
  2400                                                           KlassHandle accessing_klass,
  2401                                                           Handle *appendix_result,
  2402                                                           Handle *method_type_result,
  2403                                                           TRAPS) {
  2404   methodHandle empty;
  2405   assert(EnableInvokeDynamic, "");
  2406   assert(!THREAD->is_Compiler_thread(), "");
  2407   Handle method_type =
  2408     SystemDictionary::find_method_handle_type(signature, accessing_klass, CHECK_(empty));
  2410   KlassHandle  mh_klass = SystemDictionary::MethodHandle_klass();
  2411   int ref_kind = JVM_REF_invokeVirtual;
  2412   Handle name_str = StringTable::intern(name, CHECK_(empty));
  2413   objArrayHandle appendix_box = oopFactory::new_objArray(SystemDictionary::Object_klass(), 1, CHECK_(empty));
  2414   assert(appendix_box->obj_at(0) == NULL, "");
  2416   // This should not happen.  JDK code should take care of that.
  2417   if (accessing_klass.is_null() || method_type.is_null()) {
  2418     THROW_MSG_(vmSymbols::java_lang_InternalError(), "bad invokehandle", empty);
  2421   // call java.lang.invoke.MethodHandleNatives::linkMethod(... String, MethodType) -> MemberName
  2422   JavaCallArguments args;
  2423   args.push_oop(accessing_klass()->java_mirror());
  2424   args.push_int(ref_kind);
  2425   args.push_oop(mh_klass()->java_mirror());
  2426   args.push_oop(name_str());
  2427   args.push_oop(method_type());
  2428   args.push_oop(appendix_box());
  2429   JavaValue result(T_OBJECT);
  2430   JavaCalls::call_static(&result,
  2431                          SystemDictionary::MethodHandleNatives_klass(),
  2432                          vmSymbols::linkMethod_name(),
  2433                          vmSymbols::linkMethod_signature(),
  2434                          &args, CHECK_(empty));
  2435   Handle mname(THREAD, (oop) result.get_jobject());
  2436   (*method_type_result) = method_type;
  2437   return unpack_method_and_appendix(mname, accessing_klass, appendix_box, appendix_result, THREAD);
  2440 // Decide if we can globally cache a lookup of this class, to be returned to any client that asks.
  2441 // We must ensure that all class loaders everywhere will reach this class, for any client.
  2442 // This is a safe bet for public classes in java.lang, such as Object and String.
  2443 // We also include public classes in java.lang.invoke, because they appear frequently in system-level method types.
  2444 // Out of an abundance of caution, we do not include any other classes, not even for packages like java.util.
  2445 static bool is_always_visible_class(oop mirror) {
  2446   Klass* klass = java_lang_Class::as_Klass(mirror);
  2447   if (klass->oop_is_objArray()) {
  2448     klass = ObjArrayKlass::cast(klass)->bottom_klass(); // check element type
  2450   if (klass->oop_is_typeArray()) {
  2451     return true; // primitive array
  2453   assert(klass->oop_is_instance(), klass->external_name());
  2454   return klass->is_public() &&
  2455          (InstanceKlass::cast(klass)->is_same_class_package(SystemDictionary::Object_klass()) ||       // java.lang
  2456           InstanceKlass::cast(klass)->is_same_class_package(SystemDictionary::MethodHandle_klass()));  // java.lang.invoke
  2459 // Ask Java code to find or construct a java.lang.invoke.MethodType for the given
  2460 // signature, as interpreted relative to the given class loader.
  2461 // Because of class loader constraints, all method handle usage must be
  2462 // consistent with this loader.
  2463 Handle SystemDictionary::find_method_handle_type(Symbol* signature,
  2464                                                  KlassHandle accessing_klass,
  2465                                                  TRAPS) {
  2466   Handle empty;
  2467   vmIntrinsics::ID null_iid = vmIntrinsics::_none;  // distinct from all method handle invoker intrinsics
  2468   unsigned int hash  = invoke_method_table()->compute_hash(signature, null_iid);
  2469   int          index = invoke_method_table()->hash_to_index(hash);
  2470   SymbolPropertyEntry* spe = invoke_method_table()->find_entry(index, hash, signature, null_iid);
  2471   if (spe != NULL && spe->method_type() != NULL) {
  2472     assert(java_lang_invoke_MethodType::is_instance(spe->method_type()), "");
  2473     return Handle(THREAD, spe->method_type());
  2474   } else if (THREAD->is_Compiler_thread()) {
  2475     warning("SystemDictionary::find_method_handle_type called from compiler thread");  // FIXME
  2476     return Handle();  // do not attempt from within compiler, unless it was cached
  2479   Handle class_loader, protection_domain;
  2480   if (accessing_klass.not_null()) {
  2481     class_loader      = Handle(THREAD, InstanceKlass::cast(accessing_klass())->class_loader());
  2482     protection_domain = Handle(THREAD, InstanceKlass::cast(accessing_klass())->protection_domain());
  2484   bool can_be_cached = true;
  2485   int npts = ArgumentCount(signature).size();
  2486   objArrayHandle pts = oopFactory::new_objArray(SystemDictionary::Class_klass(), npts, CHECK_(empty));
  2487   int arg = 0;
  2488   Handle rt; // the return type from the signature
  2489   ResourceMark rm(THREAD);
  2490   for (SignatureStream ss(signature); !ss.is_done(); ss.next()) {
  2491     oop mirror = NULL;
  2492     if (can_be_cached) {
  2493       // Use neutral class loader to lookup candidate classes to be placed in the cache.
  2494       mirror = ss.as_java_mirror(Handle(), Handle(),
  2495                                  SignatureStream::ReturnNull, CHECK_(empty));
  2496       if (mirror == NULL || (ss.is_object() && !is_always_visible_class(mirror))) {
  2497         // Fall back to accessing_klass context.
  2498         can_be_cached = false;
  2501     if (!can_be_cached) {
  2502       // Resolve, throwing a real error if it doesn't work.
  2503       mirror = ss.as_java_mirror(class_loader, protection_domain,
  2504                                  SignatureStream::NCDFError, CHECK_(empty));
  2506     assert(!oopDesc::is_null(mirror), ss.as_symbol(THREAD)->as_C_string());
  2507     if (ss.at_return_type())
  2508       rt = Handle(THREAD, mirror);
  2509     else
  2510       pts->obj_at_put(arg++, mirror);
  2512     // Check accessibility.
  2513     if (ss.is_object() && accessing_klass.not_null()) {
  2514       Klass* sel_klass = java_lang_Class::as_Klass(mirror);
  2515       mirror = NULL;  // safety
  2516       // Emulate ConstantPool::verify_constant_pool_resolve.
  2517       if (sel_klass->oop_is_objArray())
  2518         sel_klass = ObjArrayKlass::cast(sel_klass)->bottom_klass();
  2519       if (sel_klass->oop_is_instance()) {
  2520         KlassHandle sel_kh(THREAD, sel_klass);
  2521         LinkResolver::check_klass_accessability(accessing_klass, sel_kh, CHECK_(empty));
  2525   assert(arg == npts, "");
  2527   // call java.lang.invoke.MethodHandleNatives::findMethodType(Class rt, Class[] pts) -> MethodType
  2528   JavaCallArguments args(Handle(THREAD, rt()));
  2529   args.push_oop(pts());
  2530   JavaValue result(T_OBJECT);
  2531   JavaCalls::call_static(&result,
  2532                          SystemDictionary::MethodHandleNatives_klass(),
  2533                          vmSymbols::findMethodHandleType_name(),
  2534                          vmSymbols::findMethodHandleType_signature(),
  2535                          &args, CHECK_(empty));
  2536   Handle method_type(THREAD, (oop) result.get_jobject());
  2538   if (can_be_cached) {
  2539     // We can cache this MethodType inside the JVM.
  2540     MutexLocker ml(SystemDictionary_lock, THREAD);
  2541     spe = invoke_method_table()->find_entry(index, hash, signature, null_iid);
  2542     if (spe == NULL)
  2543       spe = invoke_method_table()->add_entry(index, hash, signature, null_iid);
  2544     if (spe->method_type() == NULL) {
  2545       spe->set_method_type(method_type());
  2549   // report back to the caller with the MethodType
  2550   return method_type;
  2553 // Ask Java code to find or construct a method handle constant.
  2554 Handle SystemDictionary::link_method_handle_constant(KlassHandle caller,
  2555                                                      int ref_kind, //e.g., JVM_REF_invokeVirtual
  2556                                                      KlassHandle callee,
  2557                                                      Symbol* name_sym,
  2558                                                      Symbol* signature,
  2559                                                      TRAPS) {
  2560   Handle empty;
  2561   Handle name = java_lang_String::create_from_symbol(name_sym, CHECK_(empty));
  2562   Handle type;
  2563   if (signature->utf8_length() > 0 && signature->byte_at(0) == '(') {
  2564     type = find_method_handle_type(signature, caller, CHECK_(empty));
  2565   } else if (caller.is_null()) {
  2566     // This should not happen.  JDK code should take care of that.
  2567     THROW_MSG_(vmSymbols::java_lang_InternalError(), "bad MH constant", empty);
  2568   } else {
  2569     ResourceMark rm(THREAD);
  2570     SignatureStream ss(signature, false);
  2571     if (!ss.is_done()) {
  2572       oop mirror = ss.as_java_mirror(caller->class_loader(), caller->protection_domain(),
  2573                                      SignatureStream::NCDFError, CHECK_(empty));
  2574       type = Handle(THREAD, mirror);
  2575       ss.next();
  2576       if (!ss.is_done())  type = Handle();  // error!
  2579   if (type.is_null()) {
  2580     THROW_MSG_(vmSymbols::java_lang_LinkageError(), "bad signature", empty);
  2583   // call java.lang.invoke.MethodHandleNatives::linkMethodHandleConstant(Class caller, int refKind, Class callee, String name, Object type) -> MethodHandle
  2584   JavaCallArguments args;
  2585   args.push_oop(caller->java_mirror());  // the referring class
  2586   args.push_int(ref_kind);
  2587   args.push_oop(callee->java_mirror());  // the target class
  2588   args.push_oop(name());
  2589   args.push_oop(type());
  2590   JavaValue result(T_OBJECT);
  2591   JavaCalls::call_static(&result,
  2592                          SystemDictionary::MethodHandleNatives_klass(),
  2593                          vmSymbols::linkMethodHandleConstant_name(),
  2594                          vmSymbols::linkMethodHandleConstant_signature(),
  2595                          &args, CHECK_(empty));
  2596   return Handle(THREAD, (oop) result.get_jobject());
  2599 // Ask Java code to find or construct a java.lang.invoke.CallSite for the given
  2600 // name and signature, as interpreted relative to the given class loader.
  2601 methodHandle SystemDictionary::find_dynamic_call_site_invoker(KlassHandle caller,
  2602                                                               Handle bootstrap_specifier,
  2603                                                               Symbol* name,
  2604                                                               Symbol* type,
  2605                                                               Handle *appendix_result,
  2606                                                               Handle *method_type_result,
  2607                                                               TRAPS) {
  2608   methodHandle empty;
  2609   Handle bsm, info;
  2610   if (java_lang_invoke_MethodHandle::is_instance(bootstrap_specifier())) {
  2611     bsm = bootstrap_specifier;
  2612   } else {
  2613     assert(bootstrap_specifier->is_objArray(), "");
  2614     objArrayHandle args(THREAD, (objArrayOop) bootstrap_specifier());
  2615     int len = args->length();
  2616     assert(len >= 1, "");
  2617     bsm = Handle(THREAD, args->obj_at(0));
  2618     if (len > 1) {
  2619       objArrayOop args1 = oopFactory::new_objArray(SystemDictionary::Object_klass(), len-1, CHECK_(empty));
  2620       for (int i = 1; i < len; i++)
  2621         args1->obj_at_put(i-1, args->obj_at(i));
  2622       info = Handle(THREAD, args1);
  2625   guarantee(java_lang_invoke_MethodHandle::is_instance(bsm()),
  2626             "caller must supply a valid BSM");
  2628   Handle method_name = java_lang_String::create_from_symbol(name, CHECK_(empty));
  2629   Handle method_type = find_method_handle_type(type, caller, CHECK_(empty));
  2631   // This should not happen.  JDK code should take care of that.
  2632   if (caller.is_null() || method_type.is_null()) {
  2633     THROW_MSG_(vmSymbols::java_lang_InternalError(), "bad invokedynamic", empty);
  2636   objArrayHandle appendix_box = oopFactory::new_objArray(SystemDictionary::Object_klass(), 1, CHECK_(empty));
  2637   assert(appendix_box->obj_at(0) == NULL, "");
  2639   // call java.lang.invoke.MethodHandleNatives::linkCallSite(caller, bsm, name, mtype, info, &appendix)
  2640   JavaCallArguments args;
  2641   args.push_oop(caller->java_mirror());
  2642   args.push_oop(bsm());
  2643   args.push_oop(method_name());
  2644   args.push_oop(method_type());
  2645   args.push_oop(info());
  2646   args.push_oop(appendix_box);
  2647   JavaValue result(T_OBJECT);
  2648   JavaCalls::call_static(&result,
  2649                          SystemDictionary::MethodHandleNatives_klass(),
  2650                          vmSymbols::linkCallSite_name(),
  2651                          vmSymbols::linkCallSite_signature(),
  2652                          &args, CHECK_(empty));
  2653   Handle mname(THREAD, (oop) result.get_jobject());
  2654   (*method_type_result) = method_type;
  2655   return unpack_method_and_appendix(mname, caller, appendix_box, appendix_result, THREAD);
  2658 // Since the identity hash code for symbols changes when the symbols are
  2659 // moved from the regular perm gen (hash in the mark word) to the shared
  2660 // spaces (hash is the address), the classes loaded into the dictionary
  2661 // may be in the wrong buckets.
  2663 void SystemDictionary::reorder_dictionary() {
  2664   dictionary()->reorder_dictionary();
  2668 void SystemDictionary::copy_buckets(char** top, char* end) {
  2669   dictionary()->copy_buckets(top, end);
  2673 void SystemDictionary::copy_table(char** top, char* end) {
  2674   dictionary()->copy_table(top, end);
  2678 void SystemDictionary::reverse() {
  2679   dictionary()->reverse();
  2682 int SystemDictionary::number_of_classes() {
  2683   return dictionary()->number_of_entries();
  2687 // ----------------------------------------------------------------------------
  2688 void SystemDictionary::print_shared(bool details) {
  2689   shared_dictionary()->print(details);
  2692 void SystemDictionary::print(bool details) {
  2693   dictionary()->print(details);
  2695   // Placeholders
  2696   GCMutexLocker mu(SystemDictionary_lock);
  2697   placeholders()->print();
  2699   // loader constraints - print under SD_lock
  2700   constraints()->print();
  2704 void SystemDictionary::verify() {
  2705   guarantee(dictionary() != NULL, "Verify of system dictionary failed");
  2706   guarantee(constraints() != NULL,
  2707             "Verify of loader constraints failed");
  2708   guarantee(dictionary()->number_of_entries() >= 0 &&
  2709             placeholders()->number_of_entries() >= 0,
  2710             "Verify of system dictionary failed");
  2712   // Verify dictionary
  2713   dictionary()->verify();
  2715   GCMutexLocker mu(SystemDictionary_lock);
  2716   placeholders()->verify();
  2718   // Verify constraint table
  2719   guarantee(constraints() != NULL, "Verify of loader constraints failed");
  2720   constraints()->verify(dictionary(), placeholders());
  2723 #ifndef PRODUCT
  2725 // statistics code
  2726 class ClassStatistics: AllStatic {
  2727  private:
  2728   static int nclasses;        // number of classes
  2729   static int nmethods;        // number of methods
  2730   static int nmethoddata;     // number of methodData
  2731   static int class_size;      // size of class objects in words
  2732   static int method_size;     // size of method objects in words
  2733   static int debug_size;      // size of debug info in methods
  2734   static int methoddata_size; // size of methodData objects in words
  2736   static void do_class(Klass* k) {
  2737     nclasses++;
  2738     class_size += k->size();
  2739     if (k->oop_is_instance()) {
  2740       InstanceKlass* ik = (InstanceKlass*)k;
  2741       class_size += ik->methods()->size();
  2742       class_size += ik->constants()->size();
  2743       class_size += ik->local_interfaces()->size();
  2744       class_size += ik->transitive_interfaces()->size();
  2745       // We do not have to count implementors, since we only store one!
  2746       // SSS: How should these be accounted now that they have moved?
  2747       // class_size += ik->fields()->length();
  2751   static void do_method(Method* m) {
  2752     nmethods++;
  2753     method_size += m->size();
  2754     // class loader uses same objArray for empty vectors, so don't count these
  2755     if (m->has_stackmap_table()) {
  2756       method_size += m->stackmap_data()->size();
  2759     MethodData* mdo = m->method_data();
  2760     if (mdo != NULL) {
  2761       nmethoddata++;
  2762       methoddata_size += mdo->size();
  2766  public:
  2767   static void print() {
  2768     SystemDictionary::classes_do(do_class);
  2769     SystemDictionary::methods_do(do_method);
  2770     tty->print_cr("Class statistics:");
  2771     tty->print_cr("%d classes (%d bytes)", nclasses, class_size * oopSize);
  2772     tty->print_cr("%d methods (%d bytes = %d base + %d debug info)", nmethods,
  2773                   (method_size + debug_size) * oopSize, method_size * oopSize, debug_size * oopSize);
  2774     tty->print_cr("%d methoddata (%d bytes)", nmethoddata, methoddata_size * oopSize);
  2776 };
  2779 int ClassStatistics::nclasses        = 0;
  2780 int ClassStatistics::nmethods        = 0;
  2781 int ClassStatistics::nmethoddata     = 0;
  2782 int ClassStatistics::class_size      = 0;
  2783 int ClassStatistics::method_size     = 0;
  2784 int ClassStatistics::debug_size      = 0;
  2785 int ClassStatistics::methoddata_size = 0;
  2787 void SystemDictionary::print_class_statistics() {
  2788   ResourceMark rm;
  2789   ClassStatistics::print();
  2793 class MethodStatistics: AllStatic {
  2794  public:
  2795   enum {
  2796     max_parameter_size = 10
  2797   };
  2798  private:
  2800   static int _number_of_methods;
  2801   static int _number_of_final_methods;
  2802   static int _number_of_static_methods;
  2803   static int _number_of_native_methods;
  2804   static int _number_of_synchronized_methods;
  2805   static int _number_of_profiled_methods;
  2806   static int _number_of_bytecodes;
  2807   static int _parameter_size_profile[max_parameter_size];
  2808   static int _bytecodes_profile[Bytecodes::number_of_java_codes];
  2810   static void initialize() {
  2811     _number_of_methods        = 0;
  2812     _number_of_final_methods  = 0;
  2813     _number_of_static_methods = 0;
  2814     _number_of_native_methods = 0;
  2815     _number_of_synchronized_methods = 0;
  2816     _number_of_profiled_methods = 0;
  2817     _number_of_bytecodes      = 0;
  2818     for (int i = 0; i < max_parameter_size             ; i++) _parameter_size_profile[i] = 0;
  2819     for (int j = 0; j < Bytecodes::number_of_java_codes; j++) _bytecodes_profile     [j] = 0;
  2820   };
  2822   static void do_method(Method* m) {
  2823     _number_of_methods++;
  2824     // collect flag info
  2825     if (m->is_final()       ) _number_of_final_methods++;
  2826     if (m->is_static()      ) _number_of_static_methods++;
  2827     if (m->is_native()      ) _number_of_native_methods++;
  2828     if (m->is_synchronized()) _number_of_synchronized_methods++;
  2829     if (m->method_data() != NULL) _number_of_profiled_methods++;
  2830     // collect parameter size info (add one for receiver, if any)
  2831     _parameter_size_profile[MIN2(m->size_of_parameters() + (m->is_static() ? 0 : 1), max_parameter_size - 1)]++;
  2832     // collect bytecodes info
  2834       Thread *thread = Thread::current();
  2835       HandleMark hm(thread);
  2836       BytecodeStream s(methodHandle(thread, m));
  2837       Bytecodes::Code c;
  2838       while ((c = s.next()) >= 0) {
  2839         _number_of_bytecodes++;
  2840         _bytecodes_profile[c]++;
  2845  public:
  2846   static void print() {
  2847     initialize();
  2848     SystemDictionary::methods_do(do_method);
  2849     // generate output
  2850     tty->cr();
  2851     tty->print_cr("Method statistics (static):");
  2852     // flag distribution
  2853     tty->cr();
  2854     tty->print_cr("%6d final        methods  %6.1f%%", _number_of_final_methods       , _number_of_final_methods        * 100.0F / _number_of_methods);
  2855     tty->print_cr("%6d static       methods  %6.1f%%", _number_of_static_methods      , _number_of_static_methods       * 100.0F / _number_of_methods);
  2856     tty->print_cr("%6d native       methods  %6.1f%%", _number_of_native_methods      , _number_of_native_methods       * 100.0F / _number_of_methods);
  2857     tty->print_cr("%6d synchronized methods  %6.1f%%", _number_of_synchronized_methods, _number_of_synchronized_methods * 100.0F / _number_of_methods);
  2858     tty->print_cr("%6d profiled     methods  %6.1f%%", _number_of_profiled_methods, _number_of_profiled_methods * 100.0F / _number_of_methods);
  2859     // parameter size profile
  2860     tty->cr();
  2861     { int tot = 0;
  2862       int avg = 0;
  2863       for (int i = 0; i < max_parameter_size; i++) {
  2864         int n = _parameter_size_profile[i];
  2865         tot += n;
  2866         avg += n*i;
  2867         tty->print_cr("parameter size = %1d: %6d methods  %5.1f%%", i, n, n * 100.0F / _number_of_methods);
  2869       assert(tot == _number_of_methods, "should be the same");
  2870       tty->print_cr("                    %6d methods  100.0%%", _number_of_methods);
  2871       tty->print_cr("(average parameter size = %3.1f including receiver, if any)", (float)avg / _number_of_methods);
  2873     // bytecodes profile
  2874     tty->cr();
  2875     { int tot = 0;
  2876       for (int i = 0; i < Bytecodes::number_of_java_codes; i++) {
  2877         if (Bytecodes::is_defined(i)) {
  2878           Bytecodes::Code c = Bytecodes::cast(i);
  2879           int n = _bytecodes_profile[c];
  2880           tot += n;
  2881           tty->print_cr("%9d  %7.3f%%  %s", n, n * 100.0F / _number_of_bytecodes, Bytecodes::name(c));
  2884       assert(tot == _number_of_bytecodes, "should be the same");
  2885       tty->print_cr("%9d  100.000%%", _number_of_bytecodes);
  2887     tty->cr();
  2889 };
  2891 int MethodStatistics::_number_of_methods;
  2892 int MethodStatistics::_number_of_final_methods;
  2893 int MethodStatistics::_number_of_static_methods;
  2894 int MethodStatistics::_number_of_native_methods;
  2895 int MethodStatistics::_number_of_synchronized_methods;
  2896 int MethodStatistics::_number_of_profiled_methods;
  2897 int MethodStatistics::_number_of_bytecodes;
  2898 int MethodStatistics::_parameter_size_profile[MethodStatistics::max_parameter_size];
  2899 int MethodStatistics::_bytecodes_profile[Bytecodes::number_of_java_codes];
  2902 void SystemDictionary::print_method_statistics() {
  2903   MethodStatistics::print();
  2906 #endif // PRODUCT

mercurial