/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*
*/
#include "precompiled.hpp"
#include "classfile/dictionary.hpp"
#include "classfile/javaClasses.hpp"
#include "classfile/loaderConstraints.hpp"
#include "classfile/placeholders.hpp"
#include "classfile/resolutionErrors.hpp"
#include "classfile/systemDictionary.hpp"
#include "classfile/vmSymbols.hpp"
#include "compiler/compileBroker.hpp"
#include "interpreter/bytecodeStream.hpp"
#include "interpreter/interpreter.hpp"
#include "memory/gcLocker.hpp"
#include "memory/oopFactory.hpp"
#include "oops/instanceKlass.hpp"
#include "oops/instanceRefKlass.hpp"
#include "oops/klass.inline.hpp"
#include "oops/methodDataOop.hpp"
#include "oops/objArrayKlass.hpp"
#include "oops/oop.inline.hpp"
#include "oops/oop.inline2.hpp"
#include "oops/typeArrayKlass.hpp"
#include "prims/jvmtiEnvBase.hpp"
#include "prims/methodHandles.hpp"
#include "runtime/biasedLocking.hpp"
#include "runtime/fieldType.hpp"
#include "runtime/handles.inline.hpp"
#include "runtime/javaCalls.hpp"
#include "runtime/mutexLocker.hpp"
#include "runtime/signature.hpp"
#include "services/classLoadingService.hpp"
#include "services/threadService.hpp"
#if INCLUDE_TRACE
#include "memory/iterator.hpp"
#include "trace/tracing.hpp"
#endif
20201,40423,99991};
= { NULL /*, NULL...*/ };
// lazily initialized klass variables
// ----------------------------------------------------------------------------
// Java-level SystemLoader
return _java_system_loader;
}
CHECK);
}
// ----------------------------------------------------------------------------
// debugging
#ifdef ASSERT
// return true if class_name contains no '.' (internal format is '/')
if (class_name != NULL) {
} else {
return true;
}
}
#endif
// ----------------------------------------------------------------------------
// Parallel class loading check
if (AlwaysLockClassLoader) return false;
}
// ----------------------------------------------------------------------------
// ParallelDefineClass flag does not apply to bootclass loader
if (class_loader.is_null()) return false;
return true;
}
return false;
}
// ----------------------------------------------------------------------------
// Resolving of classes
// Forwards to resolve_or_null
klassOop SystemDictionary::resolve_or_fail(Symbol* class_name, Handle class_loader, Handle protection_domain, bool throw_error, TRAPS) {
// can return a null klass
klass = handle_resolution_exception(class_name, class_loader, protection_domain, throw_error, k_h, THREAD);
}
return klass;
}
klassOop SystemDictionary::handle_resolution_exception(Symbol* class_name, Handle class_loader, Handle protection_domain, bool throw_error, KlassHandle klass_h, TRAPS) {
if (HAS_PENDING_EXCEPTION) {
// If we have a pending exception we forward it to the caller, unless throw_error is true,
// in which case we have to check whether the pending exception is a ClassNotFoundException,
// and if so convert it to a NoClassDefFoundError
// And chain the original ClassNotFoundException
} else {
return NULL;
}
}
// Class not found, throw appropriate error or exception depending on value of throw_error
if (throw_error) {
} else {
}
}
}
bool throw_error, TRAPS)
{
}
// Forwards to resolve_instance_class_or_null
klassOop SystemDictionary::resolve_or_null(Symbol* class_name, Handle class_loader, Handle protection_domain, TRAPS) {
err_msg("can not load classes with compiler thread: class=%s, classloader=%s",
// Ignore wrapping L and ;.
} else {
}
}
}
// Forwards to resolve_instance_class_or_null
TRAPS) {
// dimension and object_key in FieldArrayInfo are assigned as a side-effect
// of this call
if (t == T_OBJECT) {
// naked oop "k" is OK here -- we assign back into it
if (k != NULL) {
}
} else {
k = Universe::typeArrayKlassObj(t);
}
return k;
}
// Must be called for any super-class or super-interface resolution
// during class definition to allow class circularity checking
// super-interface callers:
// parse_interfaces - for defineClass & jvmtiRedefineClasses
// super-class callers:
// ClassFileParser - for defineClass & jvmtiRedefineClasses
// load_shared_class - while loading a class from shared archive
// resolve_instance_class_or_null:
// via: handle_parallel_super_load
// when resolving a class that has an existing placeholder with
// a saved superclass [i.e. a defineClass is currently in progress]
// if another thread is trying to resolve the class, it must do
// super-class checks on its own thread to catch class circularity
// This last call is critical in class circularity checking for cases
// where classloading is delegated to different threads and the
// classloader lock is released.
// Take the case: Base->Super->Base
// 1. If thread T1 tries to do a defineClass of class Base
// resolve_super_or_fail creates placeholder: T1, Base (super Super)
// 2. resolve_instance_class_or_null does not find SD or placeholder for Super
// so it tries to load Super
// 3. If we load the class internally, or user classloader uses same thread
// loadClassFromxxx or defineClass via parseClassFile Super ...
// 3.1 resolve_super_or_fail creates placeholder: T1, Super (super Base)
// 3.3 resolve_instance_class_or_null Base, finds placeholder for Base
// 3.4 calls resolve_super_or_fail Base
// 3.5 finds T1,Base -> throws class circularity
//OR 4. If T2 tries to resolve Super via defineClass Super ...
// 4.1 resolve_super_or_fail creates placeholder: T2, Super (super Base)
// 4.2 resolve_instance_class_or_null Base, finds placeholder for Base (super Super)
// 4.3 calls resolve_super_or_fail Super in parallel on own thread T2
// 4.4 finds T2, Super -> throws class circularity
// Must be called, even if superclass is null, since this is
// where the placeholder entry is created which claims this
// thread is loading this class/classloader.
bool is_superclass,
TRAPS) {
// Double-check, if child class is already loaded, just return super-class,interface
// Don't add a placedholder if already loaded, i.e. already in system dictionary
// Make sure there's a placeholder for the *child* before resolving.
// Used as a claim that this thread is currently loading superclass/classloader
// Used here for ClassCircularity checks and also for heap verification
// (every instanceKlass in the heap needs to be in the system dictionary
// or have a placeholder).
// Must check ClassCircularity before checking if super class is already loaded
//
// We might not already have a placeholder if this child_name was
// first seen via resolve_from_stream (jni_DefineClass or JVM_DefineClass);
// the name of the class might not be known until the stream is actually
// parsed.
// Bugs 4643874, 4715493
// compute_hash can have a safepoint
// can't throw error holding a lock
bool child_already_loaded = false;
bool throw_circularity_error = false;
{
// to support // loading: if child done loading, just return superclass
// if class_name, & class_loader don't match:
// if initial define, SD update will give LinkageError
// if redefine: compare_class_versions will give HIERARCHY_CHANGED
// so we don't throw an exception here.
// see: nsk redefclass014 & java.lang.instrument Instrument032
return quicksuperk;
} else {
throw_circularity_error = true;
}
}
if (!throw_circularity_error) {
PlaceholderEntry* newprobe = placeholders()->find_and_add(p_index, p_hash, child_name, class_loader, PlaceholderTable::LOAD_SUPER, class_name, THREAD);
}
}
if (throw_circularity_error) {
}
// java.lang.Object should have been found above
// Resolve the super class or interface, check results on return
THREAD);
// Note: clean up of placeholders currently in callers of
// resolve_super_or_fail - either at update_dictionary time
// or on error
{
}
}
// can null superk
superk_h = KlassHandle(THREAD, handle_resolution_exception(class_name, class_loader, protection_domain, true, superk_h, THREAD));
}
return superk_h();
}
TRAPS) {
if(!has_checkPackageAccess()) return;
// Now we have to call back to java to check if the initating class has access
// Print out trace information
}
THREAD);
if (HAS_PENDING_EXCEPTION) {
} else {
}
}
if (HAS_PENDING_EXCEPTION) return;
// If no exception has been thrown, we have validated the protection domain
// Insert the protection domain of the initiating class into the set.
{
// We recalculate the entry here -- we've called out to java since
// the last time it was calculated.
{
// Note that we have an entry, and entries can be deleted only during GC,
// so we cannot allow GC to occur while we're holding this entry.
// We're using a No_Safepoint_Verifier to catch any place where we
// might potentially do a GC at all.
// SystemDictionary::do_unloading() asserts that classes are only
// unloaded at a safepoint.
}
}
}
// We only get here if this thread finds that another thread
// has already claimed the placeholder token for the current operation,
// but that other thread either never owned or gave up the
// object lock
// Waits on SystemDictionary_lock to indicate placeholder table updated
// On return, caller must recheck placeholder table state
//
// We only get here if
// 1) custom classLoader, i.e. not bootstrap classloader
// 2) UnsyncloadClass not set
// 3) custom classLoader has broken the class loader objectLock
// so another thread got here in parallel
//
// lockObject must be held.
// Complicated dance due to lock ordering:
// Must first release the classloader object lock to
// allow initial definer to complete the class definition
// and to avoid deadlock
// Reclaim classloader lock object with same original recursion count
// Must release SystemDictionary_lock after notify, since
// class loader lock must be claimed before SystemDictionary_lock
// to prevent deadlocks
//
// The notify allows applications that did an untimed wait() on
// the classloader object lock to not hang.
bool calledholdinglock
assert((!(lockObject() == _system_loader_lock_obj) && !is_parallelCapable(lockObject)), "unexpected double_lock_wait");
}
// If the class in is in the placeholder table, class loading is in progress
// For cases where the application changes threads to load classes, it
// is critical to ClassCircularity detection that we try loading
// the superclass on the same thread internally, so we do parallel
// super class loading here.
// This also is critical in cases where the original thread gets stalled
// even in non-circularity situations.
// Note: only one thread can define the class, but multiple can resolve
// Note: must call resolve_super_or_fail even if null super -
// to force placeholder entry creation for this class for circularity detection
// Caller must check for pending exception
// Returns non-null klassOop if other thread has completed load
// and we are done,
// If return null klassOop and no pending exception, the caller must load the class
// superk is not used, resolve_super called for circularity check only
// This code is reached in two situations. One if this thread
// is loading the same class twice (e.g. ClassCircularity, or
// java.lang.instrument).
// The second is if another thread started the resolve_super first
// and has not yet finished.
// In both cases the original caller will clean up the placeholder
// entry on error.
true,
// We don't redefine the class, so we just need to clean up if there
// was not an error (don't want to modify any system dictionary
// data structures).
{
}
// parallelCapable class loaders do NOT wait for parallel superclass loads to complete
// Serial class loaders and bootstrap classloader do wait for superclass loads
// Check if classloading completed while we were loading superclass or waiting
// Klass is already loaded, so just return it
} else {
return nh;
}
}
// must loop to both handle other placeholder updates
// and spurious notifications
bool super_load_in_progress = true;
while (super_load_in_progress) {
// Check if classloading completed while we were loading superclass or waiting
// Klass is already loaded, so just return it
} else {
// Before UnsyncloadClass:
// We only get here if the application has released the
// classloader lock when another thread was in the middle of loading a
// superclass/superinterface for this class, and now
// this thread is also trying to load this class.
// To minimize surprises, the first thread that started to
// load a class should be the one to complete the loading
// with the classfile it initially expected.
// This logic has the current thread wait once it has done
// all the superclass/superinterface loading it can, until
// the original thread completes the class loading or fails
// If it completes we will use the resulting instanceKlass
// which we will find below in the systemDictionary.
// We also get here for parallel bootstrap classloader
if (class_loader.is_null()) {
} else {
}
} else {
// If not in SD and not in PH, other thread's load must have failed
super_load_in_progress = false;
}
}
}
return (nh);
}
klassOop SystemDictionary::resolve_instance_class_or_null(Symbol* name, Handle class_loader, Handle protection_domain, TRAPS) {
// UseNewReflection
// Fix for 4474172; see evaluation for more details
// Do lookup to see if class already exist and the protection domain
// has the right access
// Non-bootstrap class loaders will call out to class loader and
// define via jvm/jni_DefineClass which will acquire the
// class loader object lock to protect against multiple threads
// defining the class in parallel by accident.
// This lock must be acquired here so the waiter will find
// any successful result in the SystemDictionary and not attempt
// the define
// ParallelCapable Classloaders and the bootstrap classloader,
// or all classloaders with UnsyncloadClass do not acquire lock here
bool DoObjectLock = true;
if (is_parallelCapable(class_loader)) {
DoObjectLock = false;
}
// Class is not in SystemDictionary so we have to do loading.
// Make sure we are synchronized on the class loader before we proceed
// Check again (after locking) if class already exist in SystemDictionary
bool class_has_been_loaded = false;
bool super_load_in_progress = false;
bool havesupername = false;
{
// Klass is already loaded, so just return it
class_has_been_loaded = true;
} else {
super_load_in_progress = true;
if (placeholder->havesupername() == true) {
havesupername = true;
}
}
}
}
// If the class in is in the placeholder table, class loading is in progress
if (super_load_in_progress && havesupername==true) {
if (HAS_PENDING_EXCEPTION) {
return NULL;
}
if (!k.is_null()) {
class_has_been_loaded = true;
}
}
if (!class_has_been_loaded) {
// add placeholder entry to record loading instance class
// Five cases:
// All cases need to prevent modifying bootclasssearchpath
// in parallel with a classload of same classname
// Redefineclasses uses existence of the placeholder for the duration
// of the class load to prevent concurrent redefinition of not completely
// defined classes.
// case 1. traditional classloaders that rely on the classloader object lock
// - no other need for LOAD_INSTANCE
// case 2. traditional classloaders that break the classloader object lock
// as a deadlock workaround. Detection of this case requires that
// this check is done while holding the classloader object lock,
// and that lock is still held when calling classloader's loadClass.
// For these classloaders, we ensure that the first requestor
// completes the load and other requestors wait for completion.
// case 3. UnsyncloadClass - don't use objectLocker
// With this flag, we allow parallel classloading of a
// class/classloader pair
// case4. Bootstrap classloader - don't own objectLocker
// This classloader supports parallelism at the classloader level,
// but only allows a single load of a class/classloader pair.
// No performance benefit and no deadlock issues.
// case 5. parallelCapable user level classloaders - without objectLocker
// Allow parallel classloading of a class/classloader pair
bool throw_circularity_error = false;
{
if (oldprobe) {
// only need check_seen_thread once, not on each loop
// 6341374 java/lang/Instrument with -Xcomp
throw_circularity_error = true;
} else {
// case 1: traditional: should never see load_in_progress.
// case 4: bootstrap classloader: prevent futile classloading,
// wait on first requestor
if (class_loader.is_null()) {
} else {
// case 2: traditional with broken classloader lock. wait on first
// requestor.
}
// Check if classloading completed while we were waiting
// Klass is already loaded, so just return it
class_has_been_loaded = true;
}
// check if other thread failed to load and cleaned up
}
}
}
}
// All cases: add LOAD_INSTANCE
// case 3: UnsyncloadClass || case 5: parallelCapable: allow competing threads to try
// LOAD_INSTANCE in parallel
// add placeholder entry even if error - callers will remove on error
if (!throw_circularity_error && !class_has_been_loaded) {
PlaceholderEntry* newprobe = placeholders()->find_and_add(p_index, p_hash, name, class_loader, PlaceholderTable::LOAD_INSTANCE, NULL, THREAD);
// For class loaders that do not acquire the classloader object lock,
// if they did not catch another thread holding LOAD_INSTANCE,
// need a check analogous to the acquire ObjectLocker/find_class
// one final check if the load has already completed
// class loaders holding the ObjectLock shouldn't find the class here
// Klass is already loaded, so just return it
class_has_been_loaded = true;
}
}
}
// must throw error outside of owning lock
if (throw_circularity_error) {
}
if (!class_has_been_loaded) {
// Do actual loading
// For UnsyncloadClass only
// If they got a linkageError, check if a parallel class load succeeded.
// If it did, then for bytecode resolution the specification requires
// that we return the same result we did for the other thread, i.e. the
// successfully loaded instanceKlass
// Should not get here for classloaders that support parallelism
// with the new cleaner mechanism, even with AllowParallelDefineClass
// Bootstrap goes through here to allow for an extra guarantee check
if (k.is_null() && HAS_PENDING_EXCEPTION
// Klass is already loaded, so just use it
}
}
}
// clean up placeholder entries for success or error
// This cleans up LOAD_INSTANCE entries
// It also cleans up LOAD_SUPER entries on errors from
// calling load_instance_class
{
}
}
// If everything was OK (no exceptions, no null return value), and
// class_loader is NOT the defining loader, do a little more bookkeeping.
if (!HAS_PENDING_EXCEPTION && !k.is_null() &&
k->class_loader() != class_loader()) {
// Need to check for a PENDING_EXCEPTION again; check_constraints
// can throw and doesn't use the CHECK macro.
if (!HAS_PENDING_EXCEPTION) {
{ // Grabbing the Compile_lock prevents systemDictionary updates
// during compilations.
k, class_loader, THREAD);
}
if (JvmtiExport::should_post_class_load()) {
}
}
}
if (HAS_PENDING_EXCEPTION || k.is_null()) {
// On error, clean up placeholders
{
}
return NULL;
}
}
}
#ifdef ASSERT
{
}
#endif
// return if the protection domain in NULL
if (protection_domain() == NULL) return k();
// Check the protection domain has the right access
{
// Note that we have an entry, and entries can be deleted only during GC,
// so we cannot allow GC to occur while we're holding this entry.
// We're using a No_Safepoint_Verifier to catch any place where we
// might potentially do a GC at all.
// SystemDictionary::do_unloading() asserts that classes are only
// unloaded at a safepoint.
return k();
}
}
// Verify protection domain. If it fails an exception is thrown
return k();
}
// This routine does not lock the system dictionary.
//
// Since readers don't hold a lock, we must make sure that system
// dictionary entries are only removed at a safepoint (when only one
// thread is running), and are added to in a safe way (all links must
// be updated in an MT-safe manner).
//
// Callers should be aware that an entry could be added just after
// _dictionary->bucket(index) is read here, so the caller will not see
// the new entry.
TRAPS) {
// UseNewReflection
// The result of this call should be consistent with the result
// of the call to resolve_instance_class_or_null().
// See evaluation 6790209 and 4474172 for more details.
{
// Note that we have an entry, and entries can be deleted only during GC,
// so we cannot allow GC to occur while we're holding this entry.
// We're using a No_Safepoint_Verifier to catch any place where we
// might potentially do a GC at all.
// SystemDictionary::do_unloading() asserts that classes are only
// unloaded at a safepoint.
}
}
// Look for a loaded instance or array klass by name. Do not do any loading.
// return NULL in case of error.
TRAPS) {
// The name refers to an array. Parse the name.
// dimension and object_key in FieldArrayInfo are assigned as a
// side-effect of this call
if (t != T_OBJECT) {
k = Universe::typeArrayKlassObj(t);
} else {
}
if (k != NULL) {
}
} else {
}
return k;
}
// Note: this method is much like resolve_from_stream, but
// updates no supplemental data structures.
// TODO consolidate the two methods with a helper routine?
TRAPS) {
// Parse the stream. Note that we do this even though this klass might
// already be present in the SystemDictionary, otherwise we would not
// throw potential ClassFormatErrors.
//
// Note: "name" is updated.
// Further note: a placeholder will be added for this class when
// super classes are loaded (resolve_super_or_fail). We expect this
// to be called for all classes but java.lang.Object; and we preload
// java.lang.Object through resolve_or_fail, not this path.
true,
THREAD);
// We don't redefine the class, so we just need to clean up whether there
// was an error or not (don't want to modify any system dictionary
// data structures).
// Parsed name could be null if we threw an error before we got far
// enough along to parse it -- in that case, there is nothing to clean up.
if (parsed_name != NULL) {
{
}
}
// If it's anonymous, initialize it now, since nobody else will.
k->set_host_klass(host_klass());
{
// Add to class hierarchy, initialize vtables, and do possible
// deoptimizations.
// But, do not add to system dictionary.
}
k->eager_initialize(THREAD);
// notify jvmti
if (JvmtiExport::should_post_class_load()) {
}
}
return k();
}
// Add a klass to the system from a stream (called by jni_DefineClass and
// JVM_DefineClass).
// Note: class_name can be NULL. In that case we do not know the name of
// the class until we have parsed the stream.
bool verify,
TRAPS) {
// Classloaders that support parallelism, e.g. bootstrap classloader,
// or all classloaders with UnsyncloadClass do not acquire lock here
bool DoObjectLock = true;
if (is_parallelCapable(class_loader)) {
DoObjectLock = false;
}
// Make sure we are synchronized on the class loader before we proceed
// Parse the stream. Note that we do this even though this klass might
// already be present in the SystemDictionary, otherwise we would not
// throw potential ClassFormatErrors.
//
// Note: "name" is updated.
// Further note: a placeholder will be added for this class when
// super classes are loaded (resolve_super_or_fail). We expect this
// to be called for all classes but java.lang.Object; and we preload
// java.lang.Object through resolve_or_fail, not this path.
THREAD);
if (!HAS_PENDING_EXCEPTION &&
!class_loader.is_null() &&
parsed_name != NULL &&
// It is illegal to define classes in the "java." package from
// JVM_DefineClass or jni_DefineClass unless you're the bootclassloader
}
}
if (!HAS_PENDING_EXCEPTION) {
// Verification prevents us from creating names with dots in them, this
// asserts that that's the case.
"external class name format used internally");
// Add class just loaded
// If a class loader supports parallel classloading handle parallel define requests
// find_or_define_instance_class may return a different instanceKlass
if (is_parallelCapable(class_loader)) {
} else {
}
}
// If parsing the class file or define_instance_class failed, we
// need to remove the placeholder added on our behalf. But we
// must make sure parsed_name is valid first (it won't be if we had
// a format error before the class was parsed far enough to
// find the name).
{
}
return NULL;
}
// Make sure that we didn't leave a place holder in the
// SystemDictionary; this is only done on success
debug_only( {
if (!HAS_PENDING_EXCEPTION) {
}
} );
return k();
}
int number_of_entries) {
"bad shared dictionary size.");
}
// If there is a shared dictionary, then find the entry for the
// given shared system class, if any.
if (shared_dictionary() != NULL) {
} else {
return NULL;
}
}
// Load a class from the shared spaces (found through the shared system
// dictionary). Force the superclass and all interfaces to be loaded.
// Update the class definition to include sibling classes and no
// subclasses (yet). [Classes in the shared space are not part of the
// object hierarchy until loaded.]
}
// Note well! Changes to this method may affect oop access order
// in the shared archive. Please take care to not make changes that
// adversely affect cold start time by changing the oop access order
// that is specified in dump.cpp MarkAndMoveOrderedReadOnly and
// MarkAndMoveOrderedReadWrite closures.
// Found the class, now load the superclass and interfaces. If they
// are shared, add them to the main system dictionary and reset
// their hierarchy references (supers, subs, and interfaces).
}
// Note: can not use instanceKlass::cast here because
// interfaces' instanceKlass's C++ vtbls haven't been
// reinitialized yet (they will be once the interface classes
// are loaded)
}
// Adjust methods to recover missing data. They need addresses for
// interpreter entry points and their default native method address
// must be reset.
// Updating methods must be done under a lock so multiple
// threads don't update these in parallel
// Shared classes are all currently loaded by the bootstrap
// classloader, so this will never cause a deadlock on
// a custom class loader lock.
{
}
if (JvmtiExport::has_redefined_a_class()) {
// Reinitialize vtable because RedefineClasses may have changed some
// entries in this vtable for super classes so the CDS vtable might
// point to old or obsolete entries. RedefineClasses doesn't fix up
// vtables in the shared system dictionary, only the main one.
// It also redefines the itable too so fix that too.
}
}
if (TraceClassLoading) {
}
// notify a class loaded from shared object
true /* shared class */);
}
return ik;
}
instanceKlassHandle SystemDictionary::load_instance_class(Symbol* class_name, Handle class_loader, TRAPS) {
if (class_loader.is_null()) {
// Search the shared system dictionary for classes preloaded into the
// shared spaces.
{
}
if (k.is_null()) {
// Use VM class loader
}
// find_or_define_instance_class may return a different instanceKlass
if (!k.is_null()) {
}
return k;
} else {
// Use user specified class loader to load class. Call loadClass operation on class_loader.
// Translate to external class name format, i.e., convert '/' chars to '.'
// Call public unsynchronized loadClass(String) directly for all class loaders
// for parallelCapable class loaders. JDK >=7, loadClass(String, boolean) will
// acquire a class-name based lock rather than the class loader object lock.
// JDK < 7 already acquire the class loader lock in loadClass(String, boolean),
// so the call to loadClassInternal() was not required.
//
// UnsyncloadClass flag means both call loadClass(String) and do
// not acquire the class loader lock even for class loaders that are
// not parallelCapable. This was a risky transitional
// flag for diagnostic purposes only. It is risky to call
// custom class loaders without synchronization.
// WARNING If a custom class loader does NOT synchronizer findClass, or callers of
// findClass, the UnsyncloadClass flag risks unexpected timing bugs in the field.
// Do NOT assume this will be supported in future releases.
//
// Added MustCallLoadClassInternal in case we discover in the field
// a customer that counts on this call
if (MustCallLoadClassInternal && has_loadClassInternal()) {
} else {
}
// Primitive classes return null since forName() can not be
// used to obtain any of the Class objects representing primitives or void
// For user defined Java class loaders, check that the name returned is
// the same as that requested. This check is done for the bootstrap
// loader when parsing the class file.
if (class_name == k->name()) {
return k;
}
}
// Class is not found or has the wrong name, return NULL
return nh;
}
}
// for bootstrap and other parallel classloaders don't acquire lock,
// use placeholder token
// If a parallelCapable class loader calls define_instance_class instead of
// find_or_define_instance_class to get here, we have a timing
// hole with systemDictionary updates and check_constraints
"define called without lock");
}
// Check class-loading constraints. Throw exception if violation is detected.
// Grabs and releases SystemDictionary_lock
// The check_constraints/find_class call and update_dictionary sequence
// must be "atomic" for a specific class/classloader pair so we never
// define two different instanceKlasses for that class/classloader pair.
// Existing classloaders will call define_instance_class with the
// classloader lock held
// Parallel classloaders will call find_or_define_instance_class
// which will require a token to perform the define class
// Register class just loaded with class loader (placed in Vector)
// Note we do this before updating the dictionary, as this can
// fail with an OutOfMemoryError (if it does, we will *not* put this
// class in the dictionary and will not update the class hierarchy).
if (k->class_loader() != NULL) {
}
// Add the new class. We need recompile lock during update of CHA.
{
// Add to class hierarchy, initialize vtables, and do possible
// deoptimizations.
// Add to systemDictionary - so other classes can see it.
// Grabs and releases SystemDictionary_lock
k, class_loader_h, THREAD);
}
k->eager_initialize(THREAD);
// notify jvmti
if (JvmtiExport::should_post_class_load()) {
}
}
// Support parallel classloading
// All parallel class loaders, including bootstrap classloader
// lock a placeholder entry for this class/class_loader pair
// to allow parallel defines of different classes for this class loader
// With AllowParallelDefine flag==true, in case they do not synchronize around
// FindLoadedClass/DefineClass, calls, we check for parallel
// loading for them, wait if a defineClass is in progress
// and return the initial requestor's results
// This flag does not apply to the bootstrap classloader.
// With AllowParallelDefine flag==false, call through to define_instance_class
// which will throw LinkageError: duplicate class definition.
// False is the requested default.
// For better performance, the class loaders should synchronize
// findClass(), i.e. FindLoadedClass/DefineClassIfAbsent or they
// potentially waste time reading and parsing the bytestream.
// Note: VM callers should ensure consistency of k/class_name,class_loader
instanceKlassHandle SystemDictionary::find_or_define_instance_class(Symbol* class_name, Handle class_loader, instanceKlassHandle k, TRAPS) {
// Hold SD lock around find_class and placeholder creation for DEFINE_CLASS
{
// First check if class already defined
}
}
// Acquire define token for this class/classloader
probe = placeholders()->find_and_add(p_index, p_hash, name_h, class_loader, PlaceholderTable::DEFINE_CLASS, NULL, THREAD);
// Wait if another thread defining in parallel
// All threads wait - even those that will throw duplicate class: otherwise
// caller is surprised by LinkageError: duplicate, but findLoadedClass fails
// if other thread has not finished updating dictionary
}
// Only special cases allow parallel defines and can use other thread's results
// Other cases fall through, and may run into duplicate defines
// caught by finding an entry in the SystemDictionary
#ifdef ASSERT
#endif
} else {
// This thread will define the class (even if earlier thread tried and had an error)
}
}
// definer must notify any waiting threads
{
if (HAS_PENDING_EXCEPTION) {
} else {
probe->set_instanceKlass(k());
}
}
}
// Can't throw exception while holding lock due to rank ordering
if (linkage_exception() != NULL) {
}
return k;
}
// If class_loader is NULL we synchronize on _system_loader_lock_obj
if (class_loader.is_null()) {
} else {
return class_loader;
}
}
// This method is added to check how often we have to wait to grab loader
// lock. The results are being recorded in the performance counters defined in
// ClassLoader::_sync_systemLoaderLockContentionRate and
// ClassLoader::_sync_nonSystemLoaderLockConteionRate.
if (!UsePerfData) {
return;
}
== ObjectSynchronizer::owner_other) {
// contention will likely happen, so increment the corresponding
// contention counter.
if (loader_lock() == _system_loader_lock_obj) {
} else {
}
}
}
// ----------------------------------------------------------------------------
// Lookup
"incorrect index?");
return k;
}
// Basic find on classes in the midst of being loaded
}
// Used for assertions and verification only
#ifndef ASSERT
VerifyAfterGC, "too expensive");
#endif
// First look in the loaded class array
}
// Get the next class in the diictionary.
return dictionary()->try_get_next_class();
}
// ----------------------------------------------------------------------------
// Update hierachy. This is done before the new klass has been added to the SystemDictionary. The Recompile_lock
// is held, to ensure that the compiler is not using the class hierachy, and that deoptimization will kick in
// before a new class is used.
// Link into hierachy. Make sure the vtables are initialized before linking into
k->append_to_sibling_list(); // add to superklass/sibling list
// Now flush all code that depended on old class hierarchy.
// Note: must be done *after* linking k into the hierarchy (was bug 12/9/97)
// Also, first reinitialize vtable because it may have gotten out of synch
// while the new class wasn't connected to the class hierarchy.
}
// ----------------------------------------------------------------------------
// GC support
// Following roots during mark-sweep is separated in two phases.
//
// The first phase follows preloaded classes and all other system
// classes, since these will never get unloaded anyway.
//
// The second phase removes (unloads) unreachable classes from the
// system dictionary and follows the remaining classes' contents.
}
// Follow all system classes and temporary placeholders in dictionary
// Placeholders. These are *always* strong roots, as they
// represent classes we're actively loading.
// Visit extra methods
}
}
// Calculate a "good" systemdictionary size based
// on predicted or current loaded classes count
if ((classcount > 0) && !DumpSharedSpaces) {
if (desiredsize <= newsize) {
break;
}
}
}
return newsize;
}
return result;
}
// The mirrors are scanned by shared_oops_do() which is
// not called by oops_do(). In order to process oops in
// a necessary order, shared_oops_do() is call by
// Universe::oops_do().
// Adjust preloaded classes and system loader object
f->do_oop(&_java_system_loader);
// Adjust dictionary
dictionary()->oops_do(f);
// Visit extra methods
invoke_method_table()->oops_do(f);
// Partially loaded classes
placeholders()->oops_do(f);
// Adjust constraint table
constraints()->oops_do(f);
// Adjust resolution error table
resolution_errors()->oops_do(f);
}
for (int k = (int)FIRST_WKID; k < (int)WKID_LIMIT; k++) {
}
{
for (int i = 0; i < T_VOID+1; i++) {
if (_box_klasses[i] != NULL) {
}
}
}
// The basic type mirrors would have already been processed in
// Universe::oops_do(), via a call to shared_oops_do(), so should
// not be processed again.
}
}
// Just the classes from defining class loaders
// Don't iterate over placeholders
dictionary()->classes_do(f);
}
// Added for initialize_itable_for_klass
// Just the classes from defining class loaders
// Don't iterate over placeholders
}
// All classes, and their class loaders
// Don't iterate over placeholders
dictionary()->classes_do(f);
}
// All classes, and their class loaders
// (added for helpers that use HandleMarks and ResourceMarks)
// Don't iterate over placeholders
}
placeholders()->entries_do(f);
}
dictionary()->methods_do(f);
invoke_method_table()->methods_do(f);
}
// ----------------------------------------------------------------------------
// Lazily load klasses
// if multiple threads calling this function, only one thread will load
// the class. The other threads will find the loaded version once the
// class is loaded.
klassOop k = resolve_or_fail(vmSymbols::java_util_concurrent_locks_AbstractOwnableSynchronizer(), true, CHECK);
// Force a fence to prevent any read before the write completes
OrderAccess::fence();
}
}
// ----------------------------------------------------------------------------
// Initialization
// Allocate arrays
"SystemDictionary should only be initialized once");
_sdgeneration = 0;
// Allocate private object used as system class loader lock
// Initialize basic classes
}
// Compact table of directions on the initialization of klasses:
static const short wk_init_info[] = {
| (int)SystemDictionary::option ),
0
};
if (must_load) {
} else {
}
}
}
}
// move the starting value forward to the limit:
}
// Preload commonly used klasses
// first do Object, String, Class
// Calculate offsets for String and Class classes since they are loaded and
// can be used after this point.
// Fixup mirrors for classes loaded before java.lang.Class.
// These calls iterate over the objects currently in the perm gen
// so calling them at this point is matters (not before when there
// are fewer objects and not later after there are more objects
// in the perm gen.
// do a bunch more:
// Preload ref klasses and set reference types
// JSR 292 classes
if (EnableInvokeDynamic) {
} else {
// Skip the JSR 292 classes, if not enabled.
}
//_box_klasses[T_OBJECT] = WK_KLASS(object_klass);
//_box_klasses[T_ARRAY] = WK_KLASS(object_klass);
{ // Compute whether we should use loadClass or loadClassInternal when loading classes.
methodOop method = instanceKlass::cast(ClassLoader_klass())->find_method(vmSymbols::loadClassInternal_name(), vmSymbols::string_class_signature());
}
{ // Compute whether we should use checkPackageAccess or NOT
methodOop method = instanceKlass::cast(ClassLoader_klass())->find_method(vmSymbols::checkPackageAccess_name(), vmSymbols::class_protectiondomain_signature());
}
}
// Tells if a given klass is a box (wrapper class, such as java.lang.Integer).
// If so, returns the basic type it holds. If not, returns T_OBJECT.
if (_box_klasses[i] == k)
return (BasicType)i;
}
return T_OBJECT;
}
else
return KlassHandle();
}
// Constraints on class loaders. The details of the algorithm can be
// found in the OOPSLA'98 paper "Dynamic Class Loading in the Java
// Virtual Machine" by Sheng Liang and Gilad Bracha. The basic idea is
// that the system dictionary needs to maintain a set of contraints that
// must be satisfied by all classes in the dictionary.
// if defining is true, then LinkageError if already in systemDictionary
// if initiating loader, then ok if instanceKlass matches existing entry
TRAPS) {
{
// if different instanceKlass - duplicate class definition,
// else - ok, class loaded by a different thread in parallel,
// we should only have found it if it was done loading and ok to use
// system dictionary only holds instance classes, placeholders
// also holds array classes
linkage_error = "loader (instance of %s): attempted duplicate class "
"definition for name: \"%s\"";
} else {
return;
}
}
#ifdef ASSERT
#endif
if (linkage_error == NULL) {
linkage_error = "loader constraint violation: loader (instance of %s)"
" previously initiated loading for a different type with name \"%s\"";
}
}
}
// Throw error now if needed (cannot throw while holding
// SystemDictionary_lock because of rank ordering)
if (linkage_error) {
}
}
// Update system dictionary - done after check_constraint and add_to_hierachy
// have been called.
TRAPS) {
// Compile_lock prevents systemDictionary updates during compilations
{
// See whether biased locking is enabled and if so set it for this
// klass.
// Note that this must be done past the last potential blocking
// point / safepoint. We enable biased locking lazily using a
// VM_Operation to iterate the SystemDictionary and installing the
// biasable mark word into each instanceKlass's prototype header.
// To avoid race conditions where we accidentally miss enabling the
// optimization for one class in the process of being added to the
// dictionary, we must not safepoint after the test of
// BiasedLocking::enabled().
// Set biased locking bit for all loaded classes; it will be
// cleared if revocation occurs too often for this type
// NOTE that we must only do this when the class is initally
// defined, not each time it is referenced from a new class loader
if (k->class_loader() == class_loader()) {
}
}
// Check for a placeholder. If there, remove it and make a
// new system dictionary entry.
}
#ifdef ASSERT
// Changed to allow PH to remain to complete class circularity checking
// while only one thread can define a class at one time, multiple
// classes can resolve the superclass for a class at one time,
// and the placeholder is used to track that
// Symbol* ph_check = find_placeholder(name, class_loader);
// assert (ph_check == NULL, "should not have a placeholder entry");
#endif
}
}
// Try to find a class name using the loader constraints. The
// loader constraints might know about a class that isn't fully loaded
// yet and these will be ignored.
// First see if it has been loaded directly.
// Force the protection domain to be null. (This removes protection checks.)
return klass;
// Now look to see if it has been loaded elsewhere, and is subject to
// a loader constraint that would require this loader to return the
// klass that is already loaded.
// For array classes, their klassOops are not kept in the
// constraint table. The element klassOops are.
if (t != T_OBJECT) {
} else {
}
// If element class already loaded, allocate array klass
}
} else {
// Non-array classes are easy: simply check the constraint table.
}
return klass;
}
} else {
// For array classes, their klassOops are not kept in the
// constraint table. The element classes are.
// primitive types always pass
if (t != T_OBJECT) {
return true;
} else {
}
}
{
// Better never do a GC while we're holding these oops
}
}
// Add entry to resolution error table to record the error when the first
// attempt to resolve a reference to a class has failed.
{
}
}
// Lookup resolution error table. Returns error if found, otherwise NULL.
{
}
}
// Signature constraints ensure that callers and callees agree about
// the meaning of type names in their signatures. This routine is the
// intake for constraints. It collects them from several places:
//
// * LinkResolver::resolve_method (if check_access is true) requires
// that the resolving class (the caller) and the defining class of
// the resolved method (the callee) agree on each type in the
// method's signature.
//
// * LinkResolver::resolve_interface_method performs exactly the same
// checks.
//
// * LinkResolver::resolve_field requires that the constant pool
// attempting to link to a field agree with the field's defining
// class about the type of the field signature.
//
// * klassVtable::initialize_vtable requires that, when a class
// overrides a vtable entry allocated by a superclass, that the
// overriding method (i.e., the callee) agree with the superclass
// on each type in the method's signature.
//
// * klassItable::initialize_itable requires that, when a class fills
// in its itables, for each non-abstract method installed in an
// itable, the method (i.e., the callee) agree with the interface
// on each type in the method's signature.
//
// All those methods have a boolean (check_access, checkconstraints)
// which turns off the checks. This is used from specialized contexts
// such as bootstrapping, dumping, and debugging.
//
// No direct constraint is placed between the class and its
// supertypes. Constraints are only placed along linked relations
// between callers and callees. When a method overrides or implements
// an abstract method in a supertype (superclass or interface), the
// constraints are placed as if the supertype were the caller to the
// overriding method. (This works well, since callers to the
// supertype have already established agreement between themselves and
// the supertype.) As a result of all this, a class can disagree with
// its supertype about the meaning of a type name, as long as that
// class neither calls a relevant method of the supertype, nor is
// called (perhaps via an override) from the supertype.
//
//
// SystemDictionary::check_signature_loaders(sig, l1, l2)
//
// Make sure all class components (including arrays) in the given
// signature will be resolved to the same class in both loaders.
// Returns the name of the type that failed a loader constraint check, or
// NULL if no constraint failed. The returned C string needs cleaning up
// with a ResourceMark in the caller. No exception except OOME is thrown.
// Arrays are not added to the loader constraint table, their elements are.
// Nothing to do if loaders are the same.
return NULL;
}
return sig->as_C_string();
}
}
}
return NULL;
}
TRAPS) {
methodHandle m;
// Must create lots of stuff here, but outside of the SystemDictionary lock.
// Now grab the lock. We might have to throw away the new method,
// if a racing thread has managed to install one at the same time.
{
spe->set_property_oop(m());
}
}
return m;
}
// Helper for unpacking the return value from linkMethod and linkCallSite.
TRAPS) {
if (TraceMethodHandles) {
#ifndef PRODUCT
m->print();
#endif //PRODUCT
}
return methodHandle(THREAD, m);
}
}
return empty;
}
TRAPS) {
if (false) { // FIXME: Decide if the Java upcall should resolve signatures.
}
objArrayHandle appendix_box = oopFactory::new_objArray(SystemDictionary::Object_klass(), 1, CHECK_(empty));
// call java.lang.invoke.MethodHandleNatives::linkMethod(... String, MethodType) -> MemberName
}
// Ask Java code to find or construct a java.lang.invoke.MethodType for the given
// signature, as interpreted relative to the given class loader.
// Because of class loader constraints, all method handle usage must be
// consistent with this loader.
TRAPS) {
vmIntrinsics::ID null_iid = vmIntrinsics::_none; // distinct from all method handle invoker intrinsics
} else if (THREAD->is_Compiler_thread()) {
return Handle(); // do not attempt from within compiler, unless it was cached
}
objArrayHandle pts = oopFactory::new_objArray(SystemDictionary::Class_klass(), npts, CHECK_(empty));
int arg = 0;
if (is_on_bcp) {
// Note: class_loader & protection_domain are both null at this point.
// fall back from BCP to accessing_klass
if (accessing_klass.not_null()) {
}
is_on_bcp = false;
}
}
if (!is_on_bcp) {
// Resolve, throwing a real error if it doesn't work.
}
if (ss.at_return_type())
else
// Check accessibility.
// Emulate constantPoolOopDesc::verify_constant_pool_resolve.
}
}
}
// call java.lang.invoke.MethodHandleNatives::findMethodType(Class rt, Class[] pts) -> MethodType
if (is_on_bcp) {
// We can cache this MethodType inside the JVM.
}
}
// report back to the caller with the MethodType
return method_type;
}
// Ask Java code to find or construct a method handle constant.
int ref_kind, //e.g., JVM_REF_invokeVirtual
TRAPS) {
} else {
}
}
}
// call java.lang.invoke.MethodHandleNatives::linkMethodHandleConstant(Class caller, int refKind, Class callee, String name, Object type) -> MethodHandle
}
// Ask Java code to find or construct a java.lang.invoke.CallSite for the given
// name and signature, as interpreted relative to the given class loader.
TRAPS) {
} else {
if (len > 1) {
objArrayOop args1 = oopFactory::new_objArray(SystemDictionary::Object_klass(), len-1, CHECK_(empty));
for (int i = 1; i < len; i++)
}
}
"caller must supply a valid BSM");
objArrayHandle appendix_box = oopFactory::new_objArray(SystemDictionary::Object_klass(), 1, CHECK_(empty));
// call java.lang.invoke.MethodHandleNatives::linkCallSite(caller, bsm, name, mtype, info, &appendix)
}
// Since the identity hash code for symbols changes when the symbols are
// moved from the regular perm gen (hash in the mark word) to the shared
// spaces (hash is the address), the classes loaded into the dictionary
// may be in the wrong buckets.
dictionary()->reorder_dictionary();
}
}
}
dictionary()->reverse();
}
return dictionary()->number_of_entries();
}
// ----------------------------------------------------------------------------
#ifndef PRODUCT
dictionary()->print();
// Placeholders
placeholders()->print();
// loader constraints - print under SD_lock
constraints()->print();
}
#endif
"Verify of loader constraints failed");
placeholders()->number_of_entries() >= 0,
"Verify of system dictionary failed");
// Verify dictionary
dictionary()->verify();
placeholders()->verify();
// Verify constraint table
}
}
}
"Loaded klasses should be in SystemDictionary");
}
// utility function for posting class load event
#if INCLUDE_TRACE
if (event.should_commit()) {
event.set_loadedClass(k());
}
#endif /* INCLUDE_TRACE */
}
#if INCLUDE_TRACE
if (_no_of_classes_unloading > 0) {
}
_should_write_unload_events = false;
}
#endif /* INCLUDE_TRACE */
}
#if INCLUDE_TRACE
if (_should_write_unload_events) {
// post class unload event
}
}
}
#endif /* INCLUDE_TRACE */
#ifndef PRODUCT
// statistics code
private:
nclasses++;
class_size += k->size();
if (k->klass_part()->oop_is_instance()) {
// We do not have to count implementors, since we only store one!
}
}
nmethods++;
method_size += m->size();
// class loader uses same objArray for empty vectors, so don't count these
if (m->has_stackmap_table()) {
}
nmethoddata++;
}
}
public:
static void print() {
}
};
ClassStatistics::print();
}
public:
enum {
};
private:
static int _number_of_methods;
static int _number_of_final_methods;
static int _number_of_static_methods;
static int _number_of_native_methods;
static int _number_of_synchronized_methods;
static int _number_of_profiled_methods;
static int _number_of_bytecodes;
static void initialize() {
_number_of_methods = 0;
_number_of_bytecodes = 0;
for (int i = 0; i < max_parameter_size ; i++) _parameter_size_profile[i] = 0;
};
// collect flag info
if (m->is_final() ) _number_of_final_methods++;
if (m->is_static() ) _number_of_static_methods++;
if (m->is_native() ) _number_of_native_methods++;
if (m->is_synchronized()) _number_of_synchronized_methods++;
// collect parameter size info (add one for receiver, if any)
_parameter_size_profile[MIN2(m->size_of_parameters() + (m->is_static() ? 0 : 1), max_parameter_size - 1)]++;
// collect bytecodes info
{
while ((c = s.next()) >= 0) {
_bytecodes_profile[c]++;
}
}
}
public:
static void print() {
initialize();
// generate output
// flag distribution
tty->print_cr("%6d final methods %6.1f%%", _number_of_final_methods , _number_of_final_methods * 100.0F / _number_of_methods);
tty->print_cr("%6d static methods %6.1f%%", _number_of_static_methods , _number_of_static_methods * 100.0F / _number_of_methods);
tty->print_cr("%6d native methods %6.1f%%", _number_of_native_methods , _number_of_native_methods * 100.0F / _number_of_methods);
tty->print_cr("%6d synchronized methods %6.1f%%", _number_of_synchronized_methods, _number_of_synchronized_methods * 100.0F / _number_of_methods);
tty->print_cr("%6d profiled methods %6.1f%%", _number_of_profiled_methods, _number_of_profiled_methods * 100.0F / _number_of_methods);
// parameter size profile
{ int tot = 0;
int avg = 0;
for (int i = 0; i < max_parameter_size; i++) {
int n = _parameter_size_profile[i];
tot += n;
avg += n*i;
}
tty->print_cr("(average parameter size = %3.1f including receiver, if any)", (float)avg / _number_of_methods);
}
// bytecodes profile
{ int tot = 0;
for (int i = 0; i < Bytecodes::number_of_java_codes; i++) {
if (Bytecodes::is_defined(i)) {
int n = _bytecodes_profile[c];
tot += n;
}
}
}
}
};
}
#endif // PRODUCT