Path: blob/aarch64-shenandoah-jdk8u272-b10/hotspot/src/share/vm/classfile/systemDictionary.cpp
32285 views
/*1* Copyright (c) 1997, 2020, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation.7*8* This code is distributed in the hope that it will be useful, but WITHOUT9* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or10* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License11* version 2 for more details (a copy is included in the LICENSE file that12* accompanied this code).13*14* You should have received a copy of the GNU General Public License version15* 2 along with this work; if not, write to the Free Software Foundation,16* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.17*18* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA19* or visit www.oracle.com if you need additional information or have any20* questions.21*22*/2324#include "precompiled.hpp"25#include "classfile/classLoaderData.inline.hpp"26#include "classfile/dictionary.hpp"27#include "classfile/javaClasses.hpp"28#include "classfile/loaderConstraints.hpp"29#include "classfile/placeholders.hpp"30#include "classfile/resolutionErrors.hpp"31#include "classfile/systemDictionary.hpp"32#if INCLUDE_CDS33#include "classfile/sharedClassUtil.hpp"34#include "classfile/systemDictionaryShared.hpp"35#endif36#include "classfile/vmSymbols.hpp"37#include "compiler/compileBroker.hpp"38#include "interpreter/bytecodeStream.hpp"39#include "interpreter/interpreter.hpp"40#include "jfr/jfrEvents.hpp"41#include "jfr/jni/jfrUpcalls.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"6869Dictionary* SystemDictionary::_dictionary = NULL;70PlaceholderTable* SystemDictionary::_placeholders = NULL;71Dictionary* SystemDictionary::_shared_dictionary = NULL;72LoaderConstraintTable* SystemDictionary::_loader_constraints = NULL;73ResolutionErrorTable* SystemDictionary::_resolution_errors = NULL;74SymbolPropertyTable* SystemDictionary::_invoke_method_table = NULL;757677int SystemDictionary::_number_of_modifications = 0;78int SystemDictionary::_sdgeneration = 0;79const int SystemDictionary::_primelist[_prime_array_size] = {1009,2017,4049,5051,10103,8020201,40423,99991};8182oop SystemDictionary::_system_loader_lock_obj = NULL;8384Klass* SystemDictionary::_well_known_klasses[SystemDictionary::WKID_LIMIT]85= { NULL /*, NULL...*/ };8687Klass* SystemDictionary::_box_klasses[T_VOID+1] = { NULL /*, NULL...*/ };8889oop SystemDictionary::_java_system_loader = NULL;9091bool SystemDictionary::_has_loadClassInternal = false;92bool SystemDictionary::_has_checkPackageAccess = false;9394// lazily initialized klass variables95Klass* volatile SystemDictionary::_abstract_ownable_synchronizer_klass = NULL;9697#if INCLUDE_JFR98static const Symbol* jfr_event_handler_proxy = NULL;99#endif // INCLUDE_JFR100101// ----------------------------------------------------------------------------102// Java-level SystemLoader103104oop SystemDictionary::java_system_loader() {105return _java_system_loader;106}107108void SystemDictionary::compute_java_system_loader(TRAPS) {109KlassHandle system_klass(THREAD, WK_KLASS(ClassLoader_klass));110JavaValue result(T_OBJECT);111JavaCalls::call_static(&result,112KlassHandle(THREAD, WK_KLASS(ClassLoader_klass)),113vmSymbols::getSystemClassLoader_name(),114vmSymbols::void_classloader_signature(),115CHECK);116117_java_system_loader = (oop)result.get_jobject();118119CDS_ONLY(SystemDictionaryShared::initialize(CHECK);)120}121122123ClassLoaderData* SystemDictionary::register_loader(Handle class_loader, TRAPS) {124if (class_loader() == NULL) return ClassLoaderData::the_null_class_loader_data();125return ClassLoaderDataGraph::find_or_create(class_loader, THREAD);126}127128// ----------------------------------------------------------------------------129// debugging130131#ifdef ASSERT132133// return true if class_name contains no '.' (internal format is '/')134bool SystemDictionary::is_internal_format(Symbol* class_name) {135if (class_name != NULL) {136ResourceMark rm;137char* name = class_name->as_C_string();138return strchr(name, '.') == NULL;139} else {140return true;141}142}143144#endif145#if INCLUDE_JFR146#include "jfr/jfr.hpp"147#endif148149// ----------------------------------------------------------------------------150// Parallel class loading check151152bool SystemDictionary::is_parallelCapable(Handle class_loader) {153if (UnsyncloadClass || class_loader.is_null()) return true;154if (AlwaysLockClassLoader) return false;155return java_lang_ClassLoader::parallelCapable(class_loader());156}157// ----------------------------------------------------------------------------158// ParallelDefineClass flag does not apply to bootclass loader159bool SystemDictionary::is_parallelDefine(Handle class_loader) {160if (class_loader.is_null()) return false;161if (AllowParallelDefineClass && java_lang_ClassLoader::parallelCapable(class_loader())) {162return true;163}164return false;165}166167/**168* Returns true if the passed class loader is the extension class loader.169*/170bool SystemDictionary::is_ext_class_loader(Handle class_loader) {171if (class_loader.is_null()) {172return false;173}174return (class_loader->klass()->name() == vmSymbols::sun_misc_Launcher_ExtClassLoader());175}176177// ----------------------------------------------------------------------------178// Resolving of classes179180// Forwards to resolve_or_null181182Klass* SystemDictionary::resolve_or_fail(Symbol* class_name, Handle class_loader, Handle protection_domain, bool throw_error, TRAPS) {183Klass* klass = resolve_or_null(class_name, class_loader, protection_domain, THREAD);184if (HAS_PENDING_EXCEPTION || klass == NULL) {185KlassHandle k_h(THREAD, klass);186// can return a null klass187klass = handle_resolution_exception(class_name, throw_error, k_h, THREAD);188}189return klass;190}191192Klass* SystemDictionary::handle_resolution_exception(Symbol* class_name,193bool throw_error,194KlassHandle klass_h, TRAPS) {195if (HAS_PENDING_EXCEPTION) {196// If we have a pending exception we forward it to the caller, unless throw_error is true,197// in which case we have to check whether the pending exception is a ClassNotFoundException,198// and if so convert it to a NoClassDefFoundError199// And chain the original ClassNotFoundException200if (throw_error && PENDING_EXCEPTION->is_a(SystemDictionary::ClassNotFoundException_klass())) {201ResourceMark rm(THREAD);202assert(klass_h() == NULL, "Should not have result with exception pending");203Handle e(THREAD, PENDING_EXCEPTION);204CLEAR_PENDING_EXCEPTION;205THROW_MSG_CAUSE_NULL(vmSymbols::java_lang_NoClassDefFoundError(), class_name->as_C_string(), e);206} else {207return NULL;208}209}210// Class not found, throw appropriate error or exception depending on value of throw_error211if (klass_h() == NULL) {212ResourceMark rm(THREAD);213if (throw_error) {214THROW_MSG_NULL(vmSymbols::java_lang_NoClassDefFoundError(), class_name->as_C_string());215} else {216THROW_MSG_NULL(vmSymbols::java_lang_ClassNotFoundException(), class_name->as_C_string());217}218}219return (Klass*)klass_h();220}221222223Klass* SystemDictionary::resolve_or_fail(Symbol* class_name,224bool throw_error, TRAPS)225{226return resolve_or_fail(class_name, Handle(), Handle(), throw_error, THREAD);227}228229230// Forwards to resolve_instance_class_or_null231232Klass* SystemDictionary::resolve_or_null(Symbol* class_name, Handle class_loader, Handle protection_domain, TRAPS) {233assert(!THREAD->is_Compiler_thread(),234err_msg("can not load classes with compiler thread: class=%s, classloader=%s",235class_name->as_C_string(),236class_loader.is_null() ? "null" : class_loader->klass()->name()->as_C_string()));237if (FieldType::is_array(class_name)) {238return resolve_array_class_or_null(class_name, class_loader, protection_domain, THREAD);239} else if (FieldType::is_obj(class_name)) {240ResourceMark rm(THREAD);241// Ignore wrapping L and ;.242TempNewSymbol name = SymbolTable::new_symbol(class_name->as_C_string() + 1,243class_name->utf8_length() - 2, CHECK_NULL);244return resolve_instance_class_or_null(name, class_loader, protection_domain, THREAD);245} else {246return resolve_instance_class_or_null(class_name, class_loader, protection_domain, THREAD);247}248}249250Klass* SystemDictionary::resolve_or_null(Symbol* class_name, TRAPS) {251return resolve_or_null(class_name, Handle(), Handle(), THREAD);252}253254// Forwards to resolve_instance_class_or_null255256Klass* SystemDictionary::resolve_array_class_or_null(Symbol* class_name,257Handle class_loader,258Handle protection_domain,259TRAPS) {260assert(FieldType::is_array(class_name), "must be array");261Klass* k = NULL;262FieldArrayInfo fd;263// dimension and object_key in FieldArrayInfo are assigned as a side-effect264// of this call265BasicType t = FieldType::get_array_info(class_name, fd, CHECK_NULL);266if (t == T_OBJECT) {267// naked oop "k" is OK here -- we assign back into it268k = SystemDictionary::resolve_instance_class_or_null(fd.object_key(),269class_loader,270protection_domain,271CHECK_NULL);272if (k != NULL) {273k = k->array_klass(fd.dimension(), CHECK_NULL);274}275} else {276k = Universe::typeArrayKlassObj(t);277k = TypeArrayKlass::cast(k)->array_klass(fd.dimension(), CHECK_NULL);278}279return k;280}281282283// Must be called for any super-class or super-interface resolution284// during class definition to allow class circularity checking285// super-interface callers:286// parse_interfaces - for defineClass & jvmtiRedefineClasses287// super-class callers:288// ClassFileParser - for defineClass & jvmtiRedefineClasses289// load_shared_class - while loading a class from shared archive290// resolve_instance_class_or_null:291// via: handle_parallel_super_load292// when resolving a class that has an existing placeholder with293// a saved superclass [i.e. a defineClass is currently in progress]294// if another thread is trying to resolve the class, it must do295// super-class checks on its own thread to catch class circularity296// This last call is critical in class circularity checking for cases297// where classloading is delegated to different threads and the298// classloader lock is released.299// Take the case: Base->Super->Base300// 1. If thread T1 tries to do a defineClass of class Base301// resolve_super_or_fail creates placeholder: T1, Base (super Super)302// 2. resolve_instance_class_or_null does not find SD or placeholder for Super303// so it tries to load Super304// 3. If we load the class internally, or user classloader uses same thread305// loadClassFromxxx or defineClass via parseClassFile Super ...306// 3.1 resolve_super_or_fail creates placeholder: T1, Super (super Base)307// 3.3 resolve_instance_class_or_null Base, finds placeholder for Base308// 3.4 calls resolve_super_or_fail Base309// 3.5 finds T1,Base -> throws class circularity310//OR 4. If T2 tries to resolve Super via defineClass Super ...311// 4.1 resolve_super_or_fail creates placeholder: T2, Super (super Base)312// 4.2 resolve_instance_class_or_null Base, finds placeholder for Base (super Super)313// 4.3 calls resolve_super_or_fail Super in parallel on own thread T2314// 4.4 finds T2, Super -> throws class circularity315// Must be called, even if superclass is null, since this is316// where the placeholder entry is created which claims this317// thread is loading this class/classloader.318Klass* SystemDictionary::resolve_super_or_fail(Symbol* child_name,319Symbol* class_name,320Handle class_loader,321Handle protection_domain,322bool is_superclass,323TRAPS) {324// Double-check, if child class is already loaded, just return super-class,interface325// Don't add a placedholder if already loaded, i.e. already in system dictionary326// Make sure there's a placeholder for the *child* before resolving.327// Used as a claim that this thread is currently loading superclass/classloader328// Used here for ClassCircularity checks and also for heap verification329// (every InstanceKlass in the heap needs to be in the system dictionary330// or have a placeholder).331// Must check ClassCircularity before checking if super class is already loaded332//333// We might not already have a placeholder if this child_name was334// first seen via resolve_from_stream (jni_DefineClass or JVM_DefineClass);335// the name of the class might not be known until the stream is actually336// parsed.337// Bugs 4643874, 4715493338// compute_hash can have a safepoint339340ClassLoaderData* loader_data = class_loader_data(class_loader);341unsigned int d_hash = dictionary()->compute_hash(child_name, loader_data);342int d_index = dictionary()->hash_to_index(d_hash);343unsigned int p_hash = placeholders()->compute_hash(child_name, loader_data);344int p_index = placeholders()->hash_to_index(p_hash);345// can't throw error holding a lock346bool child_already_loaded = false;347bool throw_circularity_error = false;348{349MutexLocker mu(SystemDictionary_lock, THREAD);350Klass* childk = find_class(d_index, d_hash, child_name, loader_data);351Klass* quicksuperk;352// to support // loading: if child done loading, just return superclass353// if class_name, & class_loader don't match:354// if initial define, SD update will give LinkageError355// if redefine: compare_class_versions will give HIERARCHY_CHANGED356// so we don't throw an exception here.357// see: nsk redefclass014 & java.lang.instrument Instrument032358if ((childk != NULL ) && (is_superclass) &&359((quicksuperk = InstanceKlass::cast(childk)->super()) != NULL) &&360361((quicksuperk->name() == class_name) &&362(quicksuperk->class_loader() == class_loader()))) {363return quicksuperk;364} else {365PlaceholderEntry* probe = placeholders()->get_entry(p_index, p_hash, child_name, loader_data);366if (probe && probe->check_seen_thread(THREAD, PlaceholderTable::LOAD_SUPER)) {367throw_circularity_error = true;368}369}370if (!throw_circularity_error) {371PlaceholderEntry* newprobe = placeholders()->find_and_add(p_index, p_hash, child_name, loader_data, PlaceholderTable::LOAD_SUPER, class_name, THREAD);372}373}374if (throw_circularity_error) {375ResourceMark rm(THREAD);376THROW_MSG_NULL(vmSymbols::java_lang_ClassCircularityError(), child_name->as_C_string());377}378379// java.lang.Object should have been found above380assert(class_name != NULL, "null super class for resolving");381// Resolve the super class or interface, check results on return382Klass* superk = SystemDictionary::resolve_or_null(class_name,383class_loader,384protection_domain,385THREAD);386387KlassHandle superk_h(THREAD, superk);388389// Clean up of placeholders moved so that each classloadAction registrar self-cleans up390// It is no longer necessary to keep the placeholder table alive until update_dictionary391// or error. GC used to walk the placeholder table as strong roots.392// The instanceKlass is kept alive because the class loader is on the stack,393// which keeps the loader_data alive, as well as all instanceKlasses in394// the loader_data. parseClassFile adds the instanceKlass to loader_data.395{396MutexLocker mu(SystemDictionary_lock, THREAD);397placeholders()->find_and_remove(p_index, p_hash, child_name, loader_data, PlaceholderTable::LOAD_SUPER, THREAD);398SystemDictionary_lock->notify_all();399}400if (HAS_PENDING_EXCEPTION || superk_h() == NULL) {401// can null superk402superk_h = KlassHandle(THREAD, handle_resolution_exception(class_name, true, superk_h, THREAD));403}404405return superk_h();406}407408void SystemDictionary::validate_protection_domain(instanceKlassHandle klass,409Handle class_loader,410Handle protection_domain,411TRAPS) {412if(!has_checkPackageAccess()) return;413414// Now we have to call back to java to check if the initating class has access415JavaValue result(T_VOID);416if (TraceProtectionDomainVerification) {417// Print out trace information418tty->print_cr("Checking package access");419tty->print(" - class loader: "); class_loader()->print_value_on(tty); tty->cr();420tty->print(" - protection domain: "); protection_domain()->print_value_on(tty); tty->cr();421tty->print(" - loading: "); klass()->print_value_on(tty); tty->cr();422}423424KlassHandle system_loader(THREAD, SystemDictionary::ClassLoader_klass());425JavaCalls::call_special(&result,426class_loader,427system_loader,428vmSymbols::checkPackageAccess_name(),429vmSymbols::class_protectiondomain_signature(),430Handle(THREAD, klass->java_mirror()),431protection_domain,432THREAD);433434if (TraceProtectionDomainVerification) {435if (HAS_PENDING_EXCEPTION) {436tty->print_cr(" -> DENIED !!!!!!!!!!!!!!!!!!!!!");437} else {438tty->print_cr(" -> granted");439}440tty->cr();441}442443if (HAS_PENDING_EXCEPTION) return;444445// If no exception has been thrown, we have validated the protection domain446// Insert the protection domain of the initiating class into the set.447{448// We recalculate the entry here -- we've called out to java since449// the last time it was calculated.450ClassLoaderData* loader_data = class_loader_data(class_loader);451452Symbol* kn = klass->name();453unsigned int d_hash = dictionary()->compute_hash(kn, loader_data);454int d_index = dictionary()->hash_to_index(d_hash);455456MutexLocker mu(SystemDictionary_lock, THREAD);457{458// Note that we have an entry, and entries can be deleted only during GC,459// so we cannot allow GC to occur while we're holding this entry.460461// We're using a No_Safepoint_Verifier to catch any place where we462// might potentially do a GC at all.463// Dictionary::do_unloading() asserts that classes in SD are only464// unloaded at a safepoint. Anonymous classes are not in SD.465No_Safepoint_Verifier nosafepoint;466dictionary()->add_protection_domain(d_index, d_hash, klass, loader_data,467protection_domain, THREAD);468}469}470}471472// We only get here if this thread finds that another thread473// has already claimed the placeholder token for the current operation,474// but that other thread either never owned or gave up the475// object lock476// Waits on SystemDictionary_lock to indicate placeholder table updated477// On return, caller must recheck placeholder table state478//479// We only get here if480// 1) custom classLoader, i.e. not bootstrap classloader481// 2) UnsyncloadClass not set482// 3) custom classLoader has broken the class loader objectLock483// so another thread got here in parallel484//485// lockObject must be held.486// Complicated dance due to lock ordering:487// Must first release the classloader object lock to488// allow initial definer to complete the class definition489// and to avoid deadlock490// Reclaim classloader lock object with same original recursion count491// Must release SystemDictionary_lock after notify, since492// class loader lock must be claimed before SystemDictionary_lock493// to prevent deadlocks494//495// The notify allows applications that did an untimed wait() on496// the classloader object lock to not hang.497void SystemDictionary::double_lock_wait(Handle lockObject, TRAPS) {498assert_lock_strong(SystemDictionary_lock);499500bool calledholdinglock501= ObjectSynchronizer::current_thread_holds_lock((JavaThread*)THREAD, lockObject);502assert(calledholdinglock,"must hold lock for notify");503assert((!(lockObject() == _system_loader_lock_obj) && !is_parallelCapable(lockObject)), "unexpected double_lock_wait");504ObjectSynchronizer::notifyall(lockObject, THREAD);505intptr_t recursions = ObjectSynchronizer::complete_exit(lockObject, THREAD);506SystemDictionary_lock->wait();507SystemDictionary_lock->unlock();508ObjectSynchronizer::reenter(lockObject, recursions, THREAD);509SystemDictionary_lock->lock();510}511512// If the class in is in the placeholder table, class loading is in progress513// For cases where the application changes threads to load classes, it514// is critical to ClassCircularity detection that we try loading515// the superclass on the same thread internally, so we do parallel516// super class loading here.517// This also is critical in cases where the original thread gets stalled518// even in non-circularity situations.519// Note: must call resolve_super_or_fail even if null super -520// to force placeholder entry creation for this class for circularity detection521// Caller must check for pending exception522// Returns non-null Klass* if other thread has completed load523// and we are done,524// If return null Klass* and no pending exception, the caller must load the class525instanceKlassHandle SystemDictionary::handle_parallel_super_load(526Symbol* name, Symbol* superclassname, Handle class_loader,527Handle protection_domain, Handle lockObject, TRAPS) {528529instanceKlassHandle nh = instanceKlassHandle(); // null Handle530ClassLoaderData* loader_data = class_loader_data(class_loader);531unsigned int d_hash = dictionary()->compute_hash(name, loader_data);532int d_index = dictionary()->hash_to_index(d_hash);533unsigned int p_hash = placeholders()->compute_hash(name, loader_data);534int p_index = placeholders()->hash_to_index(p_hash);535536// superk is not used, resolve_super called for circularity check only537// This code is reached in two situations. One if this thread538// is loading the same class twice (e.g. ClassCircularity, or539// java.lang.instrument).540// The second is if another thread started the resolve_super first541// and has not yet finished.542// In both cases the original caller will clean up the placeholder543// entry on error.544Klass* superk = SystemDictionary::resolve_super_or_fail(name,545superclassname,546class_loader,547protection_domain,548true,549CHECK_(nh));550551// parallelCapable class loaders do NOT wait for parallel superclass loads to complete552// Serial class loaders and bootstrap classloader do wait for superclass loads553if (!class_loader.is_null() && is_parallelCapable(class_loader)) {554MutexLocker mu(SystemDictionary_lock, THREAD);555// Check if classloading completed while we were loading superclass or waiting556Klass* check = find_class(d_index, d_hash, name, loader_data);557if (check != NULL) {558// Klass is already loaded, so just return it559return(instanceKlassHandle(THREAD, check));560} else {561return nh;562}563}564565// must loop to both handle other placeholder updates566// and spurious notifications567bool super_load_in_progress = true;568PlaceholderEntry* placeholder;569while (super_load_in_progress) {570MutexLocker mu(SystemDictionary_lock, THREAD);571// Check if classloading completed while we were loading superclass or waiting572Klass* check = find_class(d_index, d_hash, name, loader_data);573if (check != NULL) {574// Klass is already loaded, so just return it575return(instanceKlassHandle(THREAD, check));576} else {577placeholder = placeholders()->get_entry(p_index, p_hash, name, loader_data);578if (placeholder && placeholder->super_load_in_progress() ){579// Before UnsyncloadClass:580// We only get here if the application has released the581// classloader lock when another thread was in the middle of loading a582// superclass/superinterface for this class, and now583// this thread is also trying to load this class.584// To minimize surprises, the first thread that started to585// load a class should be the one to complete the loading586// with the classfile it initially expected.587// This logic has the current thread wait once it has done588// all the superclass/superinterface loading it can, until589// the original thread completes the class loading or fails590// If it completes we will use the resulting InstanceKlass591// which we will find below in the systemDictionary.592// We also get here for parallel bootstrap classloader593if (class_loader.is_null()) {594SystemDictionary_lock->wait();595} else {596double_lock_wait(lockObject, THREAD);597}598} else {599// If not in SD and not in PH, other thread's load must have failed600super_load_in_progress = false;601}602}603}604return (nh);605}606607// utility function for class load event608static void post_class_load_event(EventClassLoad &event,609instanceKlassHandle k,610Handle initiating_loader) {611#if INCLUDE_JFR612if (event.should_commit()) {613event.set_loadedClass(k());614event.set_definingClassLoader(k->class_loader_data());615oop class_loader = initiating_loader.is_null() ? (oop)NULL : initiating_loader();616event.set_initiatingClassLoader(class_loader != NULL ?617ClassLoaderData::class_loader_data_or_null(class_loader) :618(ClassLoaderData*)NULL);619event.commit();620}621#endif622}623624Klass* SystemDictionary::resolve_instance_class_or_null(Symbol* name,625Handle class_loader,626Handle protection_domain,627TRAPS) {628assert(name != NULL && !FieldType::is_array(name) &&629!FieldType::is_obj(name), "invalid class name");630631EventClassLoad class_load_start_event;632633// UseNewReflection634// Fix for 4474172; see evaluation for more details635class_loader = Handle(THREAD, java_lang_ClassLoader::non_reflection_class_loader(class_loader()));636ClassLoaderData *loader_data = register_loader(class_loader, CHECK_NULL);637638// Do lookup to see if class already exist and the protection domain639// has the right access640// This call uses find which checks protection domain already matches641// All subsequent calls use find_class, and set has_loaded_class so that642// before we return a result we call out to java to check for valid protection domain643// to allow returning the Klass* and add it to the pd_set if it is valid644unsigned int d_hash = dictionary()->compute_hash(name, loader_data);645int d_index = dictionary()->hash_to_index(d_hash);646Klass* probe = dictionary()->find(d_index, d_hash, name, loader_data,647protection_domain, THREAD);648if (probe != NULL) return probe;649650651// Non-bootstrap class loaders will call out to class loader and652// define via jvm/jni_DefineClass which will acquire the653// class loader object lock to protect against multiple threads654// defining the class in parallel by accident.655// This lock must be acquired here so the waiter will find656// any successful result in the SystemDictionary and not attempt657// the define658// ParallelCapable Classloaders and the bootstrap classloader,659// or all classloaders with UnsyncloadClass do not acquire lock here660bool DoObjectLock = true;661if (is_parallelCapable(class_loader)) {662DoObjectLock = false;663}664665unsigned int p_hash = placeholders()->compute_hash(name, loader_data);666int p_index = placeholders()->hash_to_index(p_hash);667668// Class is not in SystemDictionary so we have to do loading.669// Make sure we are synchronized on the class loader before we proceed670Handle lockObject = compute_loader_lock_object(class_loader, THREAD);671check_loader_lock_contention(lockObject, THREAD);672ObjectLocker ol(lockObject, THREAD, DoObjectLock);673674// Check again (after locking) if class already exist in SystemDictionary675bool class_has_been_loaded = false;676bool super_load_in_progress = false;677bool havesupername = false;678instanceKlassHandle k;679PlaceholderEntry* placeholder;680Symbol* superclassname = NULL;681682{683MutexLocker mu(SystemDictionary_lock, THREAD);684Klass* check = find_class(d_index, d_hash, name, loader_data);685if (check != NULL) {686// Klass is already loaded, so just return it687class_has_been_loaded = true;688k = instanceKlassHandle(THREAD, check);689} else {690placeholder = placeholders()->get_entry(p_index, p_hash, name, loader_data);691if (placeholder && placeholder->super_load_in_progress()) {692super_load_in_progress = true;693if (placeholder->havesupername() == true) {694superclassname = placeholder->supername();695havesupername = true;696}697}698}699}700701// If the class is in the placeholder table, class loading is in progress702if (super_load_in_progress && havesupername==true) {703k = SystemDictionary::handle_parallel_super_load(name, superclassname,704class_loader, protection_domain, lockObject, THREAD);705if (HAS_PENDING_EXCEPTION) {706return NULL;707}708if (!k.is_null()) {709class_has_been_loaded = true;710}711}712713bool throw_circularity_error = false;714if (!class_has_been_loaded) {715bool load_instance_added = false;716717// add placeholder entry to record loading instance class718// Five cases:719// All cases need to prevent modifying bootclasssearchpath720// in parallel with a classload of same classname721// Redefineclasses uses existence of the placeholder for the duration722// of the class load to prevent concurrent redefinition of not completely723// defined classes.724// case 1. traditional classloaders that rely on the classloader object lock725// - no other need for LOAD_INSTANCE726// case 2. traditional classloaders that break the classloader object lock727// as a deadlock workaround. Detection of this case requires that728// this check is done while holding the classloader object lock,729// and that lock is still held when calling classloader's loadClass.730// For these classloaders, we ensure that the first requestor731// completes the load and other requestors wait for completion.732// case 3. UnsyncloadClass - don't use objectLocker733// With this flag, we allow parallel classloading of a734// class/classloader pair735// case4. Bootstrap classloader - don't own objectLocker736// This classloader supports parallelism at the classloader level,737// but only allows a single load of a class/classloader pair.738// No performance benefit and no deadlock issues.739// case 5. parallelCapable user level classloaders - without objectLocker740// Allow parallel classloading of a class/classloader pair741742{743MutexLocker mu(SystemDictionary_lock, THREAD);744if (class_loader.is_null() || !is_parallelCapable(class_loader)) {745PlaceholderEntry* oldprobe = placeholders()->get_entry(p_index, p_hash, name, loader_data);746if (oldprobe) {747// only need check_seen_thread once, not on each loop748// 6341374 java/lang/Instrument with -Xcomp749if (oldprobe->check_seen_thread(THREAD, PlaceholderTable::LOAD_INSTANCE)) {750throw_circularity_error = true;751} else {752// case 1: traditional: should never see load_in_progress.753while (!class_has_been_loaded && oldprobe && oldprobe->instance_load_in_progress()) {754755// case 4: bootstrap classloader: prevent futile classloading,756// wait on first requestor757if (class_loader.is_null()) {758SystemDictionary_lock->wait();759} else {760// case 2: traditional with broken classloader lock. wait on first761// requestor.762double_lock_wait(lockObject, THREAD);763}764// Check if classloading completed while we were waiting765Klass* check = find_class(d_index, d_hash, name, loader_data);766if (check != NULL) {767// Klass is already loaded, so just return it768k = instanceKlassHandle(THREAD, check);769class_has_been_loaded = true;770}771// check if other thread failed to load and cleaned up772oldprobe = placeholders()->get_entry(p_index, p_hash, name, loader_data);773}774}775}776}777// All cases: add LOAD_INSTANCE holding SystemDictionary_lock778// case 3: UnsyncloadClass || case 5: parallelCapable: allow competing threads to try779// LOAD_INSTANCE in parallel780781if (!throw_circularity_error && !class_has_been_loaded) {782PlaceholderEntry* newprobe = placeholders()->find_and_add(p_index, p_hash, name, loader_data, PlaceholderTable::LOAD_INSTANCE, NULL, THREAD);783load_instance_added = true;784// For class loaders that do not acquire the classloader object lock,785// if they did not catch another thread holding LOAD_INSTANCE,786// need a check analogous to the acquire ObjectLocker/find_class787// i.e. now that we hold the LOAD_INSTANCE token on loading this class/CL788// one final check if the load has already completed789// class loaders holding the ObjectLock shouldn't find the class here790Klass* check = find_class(d_index, d_hash, name, loader_data);791if (check != NULL) {792// Klass is already loaded, so return it after checking/adding protection domain793k = instanceKlassHandle(THREAD, check);794class_has_been_loaded = true;795}796}797}798799// must throw error outside of owning lock800if (throw_circularity_error) {801assert(!HAS_PENDING_EXCEPTION && load_instance_added == false,"circularity error cleanup");802ResourceMark rm(THREAD);803THROW_MSG_NULL(vmSymbols::java_lang_ClassCircularityError(), name->as_C_string());804}805806if (!class_has_been_loaded) {807808// Do actual loading809k = load_instance_class(name, class_loader, THREAD);810811// For UnsyncloadClass only812// If they got a linkageError, check if a parallel class load succeeded.813// If it did, then for bytecode resolution the specification requires814// that we return the same result we did for the other thread, i.e. the815// successfully loaded InstanceKlass816// Should not get here for classloaders that support parallelism817// with the new cleaner mechanism, even with AllowParallelDefineClass818// Bootstrap goes through here to allow for an extra guarantee check819if (UnsyncloadClass || (class_loader.is_null())) {820if (k.is_null() && HAS_PENDING_EXCEPTION821&& PENDING_EXCEPTION->is_a(SystemDictionary::LinkageError_klass())) {822MutexLocker mu(SystemDictionary_lock, THREAD);823Klass* check = find_class(d_index, d_hash, name, loader_data);824if (check != NULL) {825// Klass is already loaded, so just use it826k = instanceKlassHandle(THREAD, check);827CLEAR_PENDING_EXCEPTION;828guarantee((!class_loader.is_null()), "dup definition for bootstrap loader?");829}830}831}832833// If everything was OK (no exceptions, no null return value), and834// class_loader is NOT the defining loader, do a little more bookkeeping.835if (!HAS_PENDING_EXCEPTION && !k.is_null() &&836k->class_loader() != class_loader()) {837838check_constraints(d_index, d_hash, k, class_loader, false, THREAD);839840// Need to check for a PENDING_EXCEPTION again; check_constraints841// can throw but we may have to remove entry from the placeholder table below.842if (!HAS_PENDING_EXCEPTION) {843// Record dependency for non-parent delegation.844// This recording keeps the defining class loader of the klass (k) found845// from being unloaded while the initiating class loader is loaded846// even if the reference to the defining class loader is dropped847// before references to the initiating class loader.848loader_data->record_dependency(k(), THREAD);849}850851if (!HAS_PENDING_EXCEPTION) {852{ // Grabbing the Compile_lock prevents systemDictionary updates853// during compilations.854MutexLocker mu(Compile_lock, THREAD);855update_dictionary(d_index, d_hash, p_index, p_hash,856k, class_loader, THREAD);857}858859if (JvmtiExport::should_post_class_load()) {860Thread *thread = THREAD;861assert(thread->is_Java_thread(), "thread->is_Java_thread()");862JvmtiExport::post_class_load((JavaThread *) thread, k());863}864}865}866} // load_instance_class loop867868if (load_instance_added == true) {869// clean up placeholder entries for LOAD_INSTANCE success or error870// This brackets the SystemDictionary updates for both defining871// and initiating loaders872MutexLocker mu(SystemDictionary_lock, THREAD);873placeholders()->find_and_remove(p_index, p_hash, name, loader_data, PlaceholderTable::LOAD_INSTANCE, THREAD);874SystemDictionary_lock->notify_all();875}876}877878if (HAS_PENDING_EXCEPTION || k.is_null()) {879return NULL;880}881882post_class_load_event(class_load_start_event, k, class_loader);883884#ifdef ASSERT885{886ClassLoaderData* loader_data = k->class_loader_data();887MutexLocker mu(SystemDictionary_lock, THREAD);888Klass* kk = find_class(name, loader_data);889assert(kk == k(), "should be present in dictionary");890}891#endif892893// return if the protection domain in NULL894if (protection_domain() == NULL) return k();895896// Check the protection domain has the right access897{898MutexLocker mu(SystemDictionary_lock, THREAD);899// Note that we have an entry, and entries can be deleted only during GC,900// so we cannot allow GC to occur while we're holding this entry.901// We're using a No_Safepoint_Verifier to catch any place where we902// might potentially do a GC at all.903// Dictionary::do_unloading() asserts that classes in SD are only904// unloaded at a safepoint. Anonymous classes are not in SD.905No_Safepoint_Verifier nosafepoint;906if (dictionary()->is_valid_protection_domain(d_index, d_hash, name,907loader_data,908protection_domain)) {909return k();910}911}912913// Verify protection domain. If it fails an exception is thrown914validate_protection_domain(k, class_loader, protection_domain, CHECK_NULL);915916return k();917}918919920// This routine does not lock the system dictionary.921//922// Since readers don't hold a lock, we must make sure that system923// dictionary entries are only removed at a safepoint (when only one924// thread is running), and are added to in a safe way (all links must925// be updated in an MT-safe manner).926//927// Callers should be aware that an entry could be added just after928// _dictionary->bucket(index) is read here, so the caller will not see929// the new entry.930931Klass* SystemDictionary::find(Symbol* class_name,932Handle class_loader,933Handle protection_domain,934TRAPS) {935936// UseNewReflection937// The result of this call should be consistent with the result938// of the call to resolve_instance_class_or_null().939// See evaluation 6790209 and 4474172 for more details.940class_loader = Handle(THREAD, java_lang_ClassLoader::non_reflection_class_loader(class_loader()));941ClassLoaderData* loader_data = ClassLoaderData::class_loader_data_or_null(class_loader());942943if (loader_data == NULL) {944// If the ClassLoaderData has not been setup,945// then the class loader has no entries in the dictionary.946return NULL;947}948949unsigned int d_hash = dictionary()->compute_hash(class_name, loader_data);950int d_index = dictionary()->hash_to_index(d_hash);951952{953// Note that we have an entry, and entries can be deleted only during GC,954// so we cannot allow GC to occur while we're holding this entry.955// We're using a No_Safepoint_Verifier to catch any place where we956// might potentially do a GC at all.957// Dictionary::do_unloading() asserts that classes in SD are only958// unloaded at a safepoint. Anonymous classes are not in SD.959No_Safepoint_Verifier nosafepoint;960return dictionary()->find(d_index, d_hash, class_name, loader_data,961protection_domain, THREAD);962}963}964965966// Look for a loaded instance or array klass by name. Do not do any loading.967// return NULL in case of error.968Klass* SystemDictionary::find_instance_or_array_klass(Symbol* class_name,969Handle class_loader,970Handle protection_domain,971TRAPS) {972Klass* k = NULL;973assert(class_name != NULL, "class name must be non NULL");974975if (FieldType::is_array(class_name)) {976// The name refers to an array. Parse the name.977// dimension and object_key in FieldArrayInfo are assigned as a978// side-effect of this call979FieldArrayInfo fd;980BasicType t = FieldType::get_array_info(class_name, fd, CHECK_(NULL));981if (t != T_OBJECT) {982k = Universe::typeArrayKlassObj(t);983} else {984k = SystemDictionary::find(fd.object_key(), class_loader, protection_domain, THREAD);985}986if (k != NULL) {987k = k->array_klass_or_null(fd.dimension());988}989} else {990k = find(class_name, class_loader, protection_domain, THREAD);991}992return k;993}994995// Note: this method is much like resolve_from_stream, but996// updates no supplemental data structures.997// TODO consolidate the two methods with a helper routine?998Klass* SystemDictionary::parse_stream(Symbol* class_name,999Handle class_loader,1000Handle protection_domain,1001ClassFileStream* st,1002KlassHandle host_klass,1003GrowableArray<Handle>* cp_patches,1004TRAPS) {1005TempNewSymbol parsed_name = NULL;10061007EventClassLoad class_load_start_event;10081009ClassLoaderData* loader_data;1010if (host_klass.not_null()) {1011// Create a new CLD for anonymous class, that uses the same class loader1012// as the host_klass1013assert(EnableInvokeDynamic, "");1014guarantee(host_klass->class_loader() == class_loader(), "should be the same");1015guarantee(!DumpSharedSpaces, "must not create anonymous classes when dumping");1016loader_data = ClassLoaderData::anonymous_class_loader_data(class_loader(), CHECK_NULL);1017loader_data->record_dependency(host_klass(), CHECK_NULL);1018} else {1019loader_data = ClassLoaderData::class_loader_data(class_loader());1020}10211022// Parse the stream. Note that we do this even though this klass might1023// already be present in the SystemDictionary, otherwise we would not1024// throw potential ClassFormatErrors.1025//1026// Note: "name" is updated.10271028instanceKlassHandle k;1029{1030// Callers are expected to declare a ResourceMark to determine1031// the lifetime of any updated (resource) allocated under1032// this call to parseClassFile1033ResourceMark rm(THREAD);1034k = ClassFileParser(st).parseClassFile(class_name,1035loader_data,1036protection_domain,1037host_klass,1038cp_patches,1039parsed_name,1040true,1041THREAD);1042}104310441045if (host_klass.not_null() && k.not_null()) {1046assert(EnableInvokeDynamic, "");1047// If it's anonymous, initialize it now, since nobody else will.10481049{1050MutexLocker mu_r(Compile_lock, THREAD);10511052// Add to class hierarchy, initialize vtables, and do possible1053// deoptimizations.1054add_to_hierarchy(k, CHECK_NULL); // No exception, but can block10551056// But, do not add to system dictionary.10571058// compiled code dependencies need to be validated anyway1059notice_modification();1060}10611062// Rewrite and patch constant pool here.1063k->link_class(CHECK_NULL);1064if (cp_patches != NULL) {1065k->constants()->patch_resolved_references(cp_patches);1066}1067k->eager_initialize(CHECK_NULL);10681069// notify jvmti1070if (JvmtiExport::should_post_class_load()) {1071assert(THREAD->is_Java_thread(), "thread->is_Java_thread()");1072JvmtiExport::post_class_load((JavaThread *) THREAD, k());1073}10741075post_class_load_event(class_load_start_event, k, class_loader);1076}1077assert(host_klass.not_null() || cp_patches == NULL,1078"cp_patches only found with host_klass");10791080return k();1081}10821083static bool is_prohibited_package_slow(Symbol* class_name) {1084// Caller has ResourceMark1085int length;1086jchar* unicode = class_name->as_unicode(length);1087return (length >= 5 &&1088unicode[0] == 'j' &&1089unicode[1] == 'a' &&1090unicode[2] == 'v' &&1091unicode[3] == 'a' &&1092unicode[4] == '/');1093}10941095// Add a klass to the system from a stream (called by jni_DefineClass and1096// JVM_DefineClass).1097// Note: class_name can be NULL. In that case we do not know the name of1098// the class until we have parsed the stream.10991100Klass* SystemDictionary::resolve_from_stream(Symbol* class_name,1101Handle class_loader,1102Handle protection_domain,1103ClassFileStream* st,1104bool verify,1105TRAPS) {11061107// Classloaders that support parallelism, e.g. bootstrap classloader,1108// or all classloaders with UnsyncloadClass do not acquire lock here1109bool DoObjectLock = true;1110if (is_parallelCapable(class_loader)) {1111DoObjectLock = false;1112}11131114ClassLoaderData* loader_data = register_loader(class_loader, CHECK_NULL);11151116// Make sure we are synchronized on the class loader before we proceed1117Handle lockObject = compute_loader_lock_object(class_loader, THREAD);1118check_loader_lock_contention(lockObject, THREAD);1119ObjectLocker ol(lockObject, THREAD, DoObjectLock);11201121TempNewSymbol parsed_name = NULL;11221123// Parse the stream. Note that we do this even though this klass might1124// already be present in the SystemDictionary, otherwise we would not1125// throw potential ClassFormatErrors.1126//1127// Note: "name" is updated.11281129// Callers are expected to declare a ResourceMark to determine1130// the lifetime of any updated (resource) allocated under1131// this call to parseClassFile1132ResourceMark rm(THREAD);1133ClassFileParser parser(st);1134instanceKlassHandle k = parser.parseClassFile(class_name,1135loader_data,1136protection_domain,1137parsed_name,1138verify,1139THREAD);11401141const char* pkg = "java/";1142size_t pkglen = strlen(pkg);1143if (!HAS_PENDING_EXCEPTION &&1144!class_loader.is_null() &&1145parsed_name != NULL &&1146parsed_name->utf8_length() >= (int)pkglen) {1147ResourceMark rm(THREAD);1148bool prohibited;1149const jbyte* base = parsed_name->base();1150if ((base[0] | base[1] | base[2] | base[3] | base[4]) & 0x80) {1151prohibited = is_prohibited_package_slow(parsed_name);1152} else {1153char* name = parsed_name->as_C_string();1154prohibited = (strncmp(name, pkg, pkglen) == 0);1155}1156if (prohibited) {1157// It is illegal to define classes in the "java." package from1158// JVM_DefineClass or jni_DefineClass unless you're the bootclassloader1159char* name = parsed_name->as_C_string();1160char* index = strrchr(name, '/');1161assert(index != NULL, "must be");1162*index = '\0'; // chop to just the package name1163while ((index = strchr(name, '/')) != NULL) {1164*index = '.'; // replace '/' with '.' in package name1165}1166const char* fmt = "Prohibited package name: %s";1167size_t len = strlen(fmt) + strlen(name);1168char* message = NEW_RESOURCE_ARRAY(char, len);1169jio_snprintf(message, len, fmt, name);1170Exceptions::_throw_msg(THREAD_AND_LOCATION,1171vmSymbols::java_lang_SecurityException(), message);1172}1173}11741175if (!HAS_PENDING_EXCEPTION) {1176assert(parsed_name != NULL, "Sanity");1177assert(class_name == NULL || class_name == parsed_name, "name mismatch");1178// Verification prevents us from creating names with dots in them, this1179// asserts that that's the case.1180assert(is_internal_format(parsed_name),1181"external class name format used internally");11821183#if INCLUDE_JFR1184{1185InstanceKlass* ik = k();1186ON_KLASS_CREATION(ik, parser, THREAD);1187k = instanceKlassHandle(ik);1188}1189#endif11901191// Add class just loaded1192// If a class loader supports parallel classloading handle parallel define requests1193// find_or_define_instance_class may return a different InstanceKlass1194if (is_parallelCapable(class_loader)) {1195k = find_or_define_instance_class(class_name, class_loader, k, THREAD);1196} else {1197define_instance_class(k, THREAD);1198}1199}12001201// Make sure we have an entry in the SystemDictionary on success1202debug_only( {1203if (!HAS_PENDING_EXCEPTION) {1204assert(parsed_name != NULL, "parsed_name is still null?");1205Symbol* h_name = k->name();1206ClassLoaderData *defining_loader_data = k->class_loader_data();12071208MutexLocker mu(SystemDictionary_lock, THREAD);12091210Klass* check = find_class(parsed_name, loader_data);1211assert(check == k(), "should be present in the dictionary");12121213Klass* check2 = find_class(h_name, defining_loader_data);1214assert(check == check2, "name inconsistancy in SystemDictionary");1215}1216} );12171218return k();1219}12201221#if INCLUDE_CDS1222void SystemDictionary::set_shared_dictionary(HashtableBucket<mtClass>* t, int length,1223int number_of_entries) {1224assert(length == _nof_buckets * sizeof(HashtableBucket<mtClass>),1225"bad shared dictionary size.");1226_shared_dictionary = new Dictionary(_nof_buckets, t, number_of_entries);1227}122812291230// If there is a shared dictionary, then find the entry for the1231// given shared system class, if any.12321233Klass* SystemDictionary::find_shared_class(Symbol* class_name) {1234if (shared_dictionary() != NULL) {1235unsigned int d_hash = shared_dictionary()->compute_hash(class_name, NULL);1236int d_index = shared_dictionary()->hash_to_index(d_hash);12371238return shared_dictionary()->find_shared_class(d_index, d_hash, class_name);1239} else {1240return NULL;1241}1242}124312441245// Load a class from the shared spaces (found through the shared system1246// dictionary). Force the superclass and all interfaces to be loaded.1247// Update the class definition to include sibling classes and no1248// subclasses (yet). [Classes in the shared space are not part of the1249// object hierarchy until loaded.]12501251instanceKlassHandle SystemDictionary::load_shared_class(1252Symbol* class_name, Handle class_loader, TRAPS) {1253instanceKlassHandle ik (THREAD, find_shared_class(class_name));1254// Make sure we only return the boot class for the NULL classloader.1255if (ik.not_null() &&1256SharedClassUtil::is_shared_boot_class(ik()) && class_loader.is_null()) {1257Handle protection_domain;1258return load_shared_class(ik, class_loader, protection_domain, THREAD);1259}1260return instanceKlassHandle();1261}12621263instanceKlassHandle SystemDictionary::load_shared_class(instanceKlassHandle ik,1264Handle class_loader,1265Handle protection_domain, TRAPS) {1266if (ik.not_null()) {1267instanceKlassHandle nh = instanceKlassHandle(); // null Handle1268Symbol* class_name = ik->name();12691270// Found the class, now load the superclass and interfaces. If they1271// are shared, add them to the main system dictionary and reset1272// their hierarchy references (supers, subs, and interfaces).12731274if (ik->super() != NULL) {1275Symbol* cn = ik->super()->name();1276Klass *s = resolve_super_or_fail(class_name, cn,1277class_loader, protection_domain, true, CHECK_(nh));1278if (s != ik->super()) {1279// The dynamically resolved super class is not the same as the one we used during dump time,1280// so we cannot use ik.1281return nh;1282}1283}12841285Array<Klass*>* interfaces = ik->local_interfaces();1286int num_interfaces = interfaces->length();1287for (int index = 0; index < num_interfaces; index++) {1288Klass* k = interfaces->at(index);12891290// Note: can not use InstanceKlass::cast here because1291// interfaces' InstanceKlass's C++ vtbls haven't been1292// reinitialized yet (they will be once the interface classes1293// are loaded)1294Symbol* name = k->name();1295Klass* i = resolve_super_or_fail(class_name, name, class_loader, protection_domain, false, CHECK_(nh));1296if (k != i) {1297// The dynamically resolved interface class is not the same as the one we used during dump time,1298// so we cannot use ik.1299return nh;1300}1301}13021303// Adjust methods to recover missing data. They need addresses for1304// interpreter entry points and their default native method address1305// must be reset.13061307// Updating methods must be done under a lock so multiple1308// threads don't update these in parallel1309//1310// Shared classes are all currently loaded by either the bootstrap or1311// internal parallel class loaders, so this will never cause a deadlock1312// on a custom class loader lock.13131314ClassLoaderData* loader_data = ClassLoaderData::class_loader_data(class_loader());1315{1316Handle lockObject = compute_loader_lock_object(class_loader, THREAD);1317check_loader_lock_contention(lockObject, THREAD);1318ObjectLocker ol(lockObject, THREAD, true);1319ik->restore_unshareable_info(loader_data, protection_domain, CHECK_(nh));1320}13211322if (TraceClassLoading) {1323ResourceMark rm;1324tty->print("[Loaded %s", ik->external_name());1325tty->print(" from shared objects file");1326if (class_loader.not_null()) {1327tty->print(" by %s", loader_data->loader_name());1328}1329tty->print_cr("]");1330}13311332if (DumpLoadedClassList != NULL && classlist_file->is_open()) {1333// Only dump the classes that can be stored into CDS archive1334if (SystemDictionaryShared::is_sharing_possible(loader_data)) {1335ResourceMark rm(THREAD);1336classlist_file->print_cr("%s", ik->name()->as_C_string());1337classlist_file->flush();1338}1339}13401341// notify a class loaded from shared object1342ClassLoadingService::notify_class_loaded(InstanceKlass::cast(ik()),1343true /* shared class */);1344}1345return ik;1346}1347#endif // INCLUDE_CDS13481349instanceKlassHandle SystemDictionary::load_instance_class(Symbol* class_name, Handle class_loader, TRAPS) {1350instanceKlassHandle nh = instanceKlassHandle(); // null Handle1351if (class_loader.is_null()) {13521353// Search the shared system dictionary for classes preloaded into the1354// shared spaces.1355instanceKlassHandle k;1356{1357#if INCLUDE_CDS1358PerfTraceTime vmtimer(ClassLoader::perf_shared_classload_time());1359k = load_shared_class(class_name, class_loader, THREAD);1360#endif1361}13621363if (k.is_null()) {1364// Use VM class loader1365PerfTraceTime vmtimer(ClassLoader::perf_sys_classload_time());1366k = ClassLoader::load_classfile(class_name, CHECK_(nh));1367}13681369// find_or_define_instance_class may return a different InstanceKlass1370if (!k.is_null()) {1371k = find_or_define_instance_class(class_name, class_loader, k, CHECK_(nh));1372}13731374#if INCLUDE_JFR1375if (k.is_null() && (class_name == jfr_event_handler_proxy)) {1376assert(jfr_event_handler_proxy != NULL, "invariant");1377// EventHandlerProxy class is generated dynamically in1378// EventHandlerProxyCreator::makeEventHandlerProxyClass1379// method, so we generate a Java call from here.1380//1381// EventHandlerProxy class will finally be defined in1382// SystemDictionary::resolve_from_stream method, down1383// the call stack. Bootstrap classloader is parallel-capable,1384// so no concurrency issues are expected.1385CLEAR_PENDING_EXCEPTION;1386k = JfrUpcalls::load_event_handler_proxy_class(THREAD);1387assert(!k.is_null(), "invariant");1388}1389#endif13901391return k;1392} else {1393// Use user specified class loader to load class. Call loadClass operation on class_loader.1394ResourceMark rm(THREAD);13951396assert(THREAD->is_Java_thread(), "must be a JavaThread");1397JavaThread* jt = (JavaThread*) THREAD;13981399PerfClassTraceTime vmtimer(ClassLoader::perf_app_classload_time(),1400ClassLoader::perf_app_classload_selftime(),1401ClassLoader::perf_app_classload_count(),1402jt->get_thread_stat()->perf_recursion_counts_addr(),1403jt->get_thread_stat()->perf_timers_addr(),1404PerfClassTraceTime::CLASS_LOAD);14051406Handle s = java_lang_String::create_from_symbol(class_name, CHECK_(nh));1407// Translate to external class name format, i.e., convert '/' chars to '.'1408Handle string = java_lang_String::externalize_classname(s, CHECK_(nh));14091410JavaValue result(T_OBJECT);14111412KlassHandle spec_klass (THREAD, SystemDictionary::ClassLoader_klass());14131414// Call public unsynchronized loadClass(String) directly for all class loaders1415// for parallelCapable class loaders. JDK >=7, loadClass(String, boolean) will1416// acquire a class-name based lock rather than the class loader object lock.1417// JDK < 7 already acquire the class loader lock in loadClass(String, boolean),1418// so the call to loadClassInternal() was not required.1419//1420// UnsyncloadClass flag means both call loadClass(String) and do1421// not acquire the class loader lock even for class loaders that are1422// not parallelCapable. This was a risky transitional1423// flag for diagnostic purposes only. It is risky to call1424// custom class loaders without synchronization.1425// WARNING If a custom class loader does NOT synchronizer findClass, or callers of1426// findClass, the UnsyncloadClass flag risks unexpected timing bugs in the field.1427// Do NOT assume this will be supported in future releases.1428//1429// Added MustCallLoadClassInternal in case we discover in the field1430// a customer that counts on this call1431if (MustCallLoadClassInternal && has_loadClassInternal()) {1432JavaCalls::call_special(&result,1433class_loader,1434spec_klass,1435vmSymbols::loadClassInternal_name(),1436vmSymbols::string_class_signature(),1437string,1438CHECK_(nh));1439} else {1440JavaCalls::call_virtual(&result,1441class_loader,1442spec_klass,1443vmSymbols::loadClass_name(),1444vmSymbols::string_class_signature(),1445string,1446CHECK_(nh));1447}14481449assert(result.get_type() == T_OBJECT, "just checking");1450oop obj = (oop) result.get_jobject();14511452// Primitive classes return null since forName() can not be1453// used to obtain any of the Class objects representing primitives or void1454if ((obj != NULL) && !(java_lang_Class::is_primitive(obj))) {1455instanceKlassHandle k =1456instanceKlassHandle(THREAD, java_lang_Class::as_Klass(obj));1457// For user defined Java class loaders, check that the name returned is1458// the same as that requested. This check is done for the bootstrap1459// loader when parsing the class file.1460if (class_name == k->name()) {1461return k;1462}1463}1464// Class is not found or has the wrong name, return NULL1465return nh;1466}1467}14681469static void post_class_define_event(InstanceKlass* k, const ClassLoaderData* def_cld) {1470EventClassDefine event;1471if (event.should_commit()) {1472event.set_definedClass(k);1473event.set_definingClassLoader(def_cld);1474event.commit();1475}1476}14771478void SystemDictionary::define_instance_class(instanceKlassHandle k, TRAPS) {14791480ClassLoaderData* loader_data = k->class_loader_data();1481Handle class_loader_h(THREAD, loader_data->class_loader());14821483for (uintx it = 0; it < GCExpandToAllocateDelayMillis; it++){}14841485// for bootstrap and other parallel classloaders don't acquire lock,1486// use placeholder token1487// If a parallelCapable class loader calls define_instance_class instead of1488// find_or_define_instance_class to get here, we have a timing1489// hole with systemDictionary updates and check_constraints1490if (!class_loader_h.is_null() && !is_parallelCapable(class_loader_h)) {1491assert(ObjectSynchronizer::current_thread_holds_lock((JavaThread*)THREAD,1492compute_loader_lock_object(class_loader_h, THREAD)),1493"define called without lock");1494}14951496// Check class-loading constraints. Throw exception if violation is detected.1497// Grabs and releases SystemDictionary_lock1498// The check_constraints/find_class call and update_dictionary sequence1499// must be "atomic" for a specific class/classloader pair so we never1500// define two different instanceKlasses for that class/classloader pair.1501// Existing classloaders will call define_instance_class with the1502// classloader lock held1503// Parallel classloaders will call find_or_define_instance_class1504// which will require a token to perform the define class1505Symbol* name_h = k->name();1506unsigned int d_hash = dictionary()->compute_hash(name_h, loader_data);1507int d_index = dictionary()->hash_to_index(d_hash);1508check_constraints(d_index, d_hash, k, class_loader_h, true, CHECK);15091510// Register class just loaded with class loader (placed in Vector)1511// Note we do this before updating the dictionary, as this can1512// fail with an OutOfMemoryError (if it does, we will *not* put this1513// class in the dictionary and will not update the class hierarchy).1514// JVMTI FollowReferences needs to find the classes this way.1515if (k->class_loader() != NULL) {1516methodHandle m(THREAD, Universe::loader_addClass_method());1517JavaValue result(T_VOID);1518JavaCallArguments args(class_loader_h);1519args.push_oop(Handle(THREAD, k->java_mirror()));1520JavaCalls::call(&result, m, &args, CHECK);1521}15221523// Add the new class. We need recompile lock during update of CHA.1524{1525unsigned int p_hash = placeholders()->compute_hash(name_h, loader_data);1526int p_index = placeholders()->hash_to_index(p_hash);15271528MutexLocker mu_r(Compile_lock, THREAD);15291530// Add to class hierarchy, initialize vtables, and do possible1531// deoptimizations.1532add_to_hierarchy(k, CHECK); // No exception, but can block15331534// Add to systemDictionary - so other classes can see it.1535// Grabs and releases SystemDictionary_lock1536update_dictionary(d_index, d_hash, p_index, p_hash,1537k, class_loader_h, THREAD);1538}1539k->eager_initialize(THREAD);15401541// notify jvmti1542if (JvmtiExport::should_post_class_load()) {1543assert(THREAD->is_Java_thread(), "thread->is_Java_thread()");1544JvmtiExport::post_class_load((JavaThread *) THREAD, k());15451546}15471548post_class_define_event(k(), loader_data);1549}15501551// Support parallel classloading1552// All parallel class loaders, including bootstrap classloader1553// lock a placeholder entry for this class/class_loader pair1554// to allow parallel defines of different classes for this class loader1555// With AllowParallelDefine flag==true, in case they do not synchronize around1556// FindLoadedClass/DefineClass, calls, we check for parallel1557// loading for them, wait if a defineClass is in progress1558// and return the initial requestor's results1559// This flag does not apply to the bootstrap classloader.1560// With AllowParallelDefine flag==false, call through to define_instance_class1561// which will throw LinkageError: duplicate class definition.1562// False is the requested default.1563// For better performance, the class loaders should synchronize1564// findClass(), i.e. FindLoadedClass/DefineClassIfAbsent or they1565// potentially waste time reading and parsing the bytestream.1566// Note: VM callers should ensure consistency of k/class_name,class_loader1567instanceKlassHandle SystemDictionary::find_or_define_instance_class(Symbol* class_name, Handle class_loader, instanceKlassHandle k, TRAPS) {15681569instanceKlassHandle nh = instanceKlassHandle(); // null Handle1570Symbol* name_h = k->name(); // passed in class_name may be null1571ClassLoaderData* loader_data = class_loader_data(class_loader);15721573unsigned int d_hash = dictionary()->compute_hash(name_h, loader_data);1574int d_index = dictionary()->hash_to_index(d_hash);15751576// Hold SD lock around find_class and placeholder creation for DEFINE_CLASS1577unsigned int p_hash = placeholders()->compute_hash(name_h, loader_data);1578int p_index = placeholders()->hash_to_index(p_hash);1579PlaceholderEntry* probe;15801581{1582MutexLocker mu(SystemDictionary_lock, THREAD);1583// First check if class already defined1584if (UnsyncloadClass || (is_parallelDefine(class_loader))) {1585Klass* check = find_class(d_index, d_hash, name_h, loader_data);1586if (check != NULL) {1587return(instanceKlassHandle(THREAD, check));1588}1589}15901591// Acquire define token for this class/classloader1592probe = placeholders()->find_and_add(p_index, p_hash, name_h, loader_data, PlaceholderTable::DEFINE_CLASS, NULL, THREAD);1593// Wait if another thread defining in parallel1594// All threads wait - even those that will throw duplicate class: otherwise1595// caller is surprised by LinkageError: duplicate, but findLoadedClass fails1596// if other thread has not finished updating dictionary1597while (probe->definer() != NULL) {1598SystemDictionary_lock->wait();1599}1600// Only special cases allow parallel defines and can use other thread's results1601// Other cases fall through, and may run into duplicate defines1602// caught by finding an entry in the SystemDictionary1603if ((UnsyncloadClass || is_parallelDefine(class_loader)) && (probe->instance_klass() != NULL)) {1604placeholders()->find_and_remove(p_index, p_hash, name_h, loader_data, PlaceholderTable::DEFINE_CLASS, THREAD);1605SystemDictionary_lock->notify_all();1606#ifdef ASSERT1607Klass* check = find_class(d_index, d_hash, name_h, loader_data);1608assert(check != NULL, "definer missed recording success");1609#endif1610return(instanceKlassHandle(THREAD, probe->instance_klass()));1611} else {1612// This thread will define the class (even if earlier thread tried and had an error)1613probe->set_definer(THREAD);1614}1615}16161617define_instance_class(k, THREAD);16181619Handle linkage_exception = Handle(); // null handle16201621// definer must notify any waiting threads1622{1623MutexLocker mu(SystemDictionary_lock, THREAD);1624PlaceholderEntry* probe = placeholders()->get_entry(p_index, p_hash, name_h, loader_data);1625assert(probe != NULL, "DEFINE_CLASS placeholder lost?");1626if (probe != NULL) {1627if (HAS_PENDING_EXCEPTION) {1628linkage_exception = Handle(THREAD,PENDING_EXCEPTION);1629CLEAR_PENDING_EXCEPTION;1630} else {1631probe->set_instance_klass(k());1632}1633probe->set_definer(NULL);1634placeholders()->find_and_remove(p_index, p_hash, name_h, loader_data, PlaceholderTable::DEFINE_CLASS, THREAD);1635SystemDictionary_lock->notify_all();1636}1637}16381639// Can't throw exception while holding lock due to rank ordering1640if (linkage_exception() != NULL) {1641THROW_OOP_(linkage_exception(), nh); // throws exception and returns1642}16431644return k;1645}1646Handle SystemDictionary::compute_loader_lock_object(Handle class_loader, TRAPS) {1647// If class_loader is NULL we synchronize on _system_loader_lock_obj1648if (class_loader.is_null()) {1649return Handle(THREAD, _system_loader_lock_obj);1650} else {1651return class_loader;1652}1653}16541655// This method is added to check how often we have to wait to grab loader1656// lock. The results are being recorded in the performance counters defined in1657// ClassLoader::_sync_systemLoaderLockContentionRate and1658// ClassLoader::_sync_nonSystemLoaderLockConteionRate.1659void SystemDictionary::check_loader_lock_contention(Handle loader_lock, TRAPS) {1660if (!UsePerfData) {1661return;1662}16631664assert(!loader_lock.is_null(), "NULL lock object");16651666if (ObjectSynchronizer::query_lock_ownership((JavaThread*)THREAD, loader_lock)1667== ObjectSynchronizer::owner_other) {1668// contention will likely happen, so increment the corresponding1669// contention counter.1670if (loader_lock() == _system_loader_lock_obj) {1671ClassLoader::sync_systemLoaderLockContentionRate()->inc();1672} else {1673ClassLoader::sync_nonSystemLoaderLockContentionRate()->inc();1674}1675}1676}16771678// ----------------------------------------------------------------------------1679// Lookup16801681Klass* SystemDictionary::find_class(int index, unsigned int hash,1682Symbol* class_name,1683ClassLoaderData* loader_data) {1684assert_locked_or_safepoint(SystemDictionary_lock);1685assert (index == dictionary()->index_for(class_name, loader_data),1686"incorrect index?");16871688Klass* k = dictionary()->find_class(index, hash, class_name, loader_data);1689return k;1690}169116921693// Basic find on classes in the midst of being loaded1694Symbol* SystemDictionary::find_placeholder(Symbol* class_name,1695ClassLoaderData* loader_data) {1696assert_locked_or_safepoint(SystemDictionary_lock);1697unsigned int p_hash = placeholders()->compute_hash(class_name, loader_data);1698int p_index = placeholders()->hash_to_index(p_hash);1699return placeholders()->find_entry(p_index, p_hash, class_name, loader_data);1700}170117021703// Used for assertions and verification only1704Klass* SystemDictionary::find_class(Symbol* class_name, ClassLoaderData* loader_data) {1705#ifndef ASSERT1706guarantee(VerifyBeforeGC ||1707VerifyDuringGC ||1708VerifyBeforeExit ||1709VerifyDuringStartup ||1710VerifyAfterGC, "too expensive");1711#endif1712assert_locked_or_safepoint(SystemDictionary_lock);17131714// First look in the loaded class array1715unsigned int d_hash = dictionary()->compute_hash(class_name, loader_data);1716int d_index = dictionary()->hash_to_index(d_hash);1717return find_class(d_index, d_hash, class_name, loader_data);1718}171917201721// Get the next class in the diictionary.1722Klass* SystemDictionary::try_get_next_class() {1723return dictionary()->try_get_next_class();1724}172517261727// ----------------------------------------------------------------------------1728// Update hierachy. This is done before the new klass has been added to the SystemDictionary. The Recompile_lock1729// is held, to ensure that the compiler is not using the class hierachy, and that deoptimization will kick in1730// before a new class is used.17311732void SystemDictionary::add_to_hierarchy(instanceKlassHandle k, TRAPS) {1733assert(k.not_null(), "just checking");1734assert_locked_or_safepoint(Compile_lock);17351736// Link into hierachy. Make sure the vtables are initialized before linking into1737k->append_to_sibling_list(); // add to superklass/sibling list1738k->process_interfaces(THREAD); // handle all "implements" declarations1739k->set_init_state(InstanceKlass::loaded);1740// Now flush all code that depended on old class hierarchy.1741// Note: must be done *after* linking k into the hierarchy (was bug 12/9/97)1742// Also, first reinitialize vtable because it may have gotten out of synch1743// while the new class wasn't connected to the class hierarchy.1744Universe::flush_dependents_on(k);1745}17461747// ----------------------------------------------------------------------------1748// GC support17491750// Following roots during mark-sweep is separated in two phases.1751//1752// The first phase follows preloaded classes and all other system1753// classes, since these will never get unloaded anyway.1754//1755// The second phase removes (unloads) unreachable classes from the1756// system dictionary and follows the remaining classes' contents.17571758void SystemDictionary::always_strong_oops_do(OopClosure* blk) {1759roots_oops_do(blk, NULL);1760}17611762void SystemDictionary::always_strong_classes_do(KlassClosure* closure) {1763// Follow all system classes and temporary placeholders in dictionary1764dictionary()->always_strong_classes_do(closure);17651766// Placeholders. These represent classes we're actively loading.1767placeholders()->classes_do(closure);1768}17691770// Calculate a "good" systemdictionary size based1771// on predicted or current loaded classes count1772int SystemDictionary::calculate_systemdictionary_size(int classcount) {1773int newsize = _old_default_sdsize;1774if ((classcount > 0) && !DumpSharedSpaces) {1775int desiredsize = classcount/_average_depth_goal;1776for (newsize = _primelist[_sdgeneration]; _sdgeneration < _prime_array_size -1;1777newsize = _primelist[++_sdgeneration]) {1778if (desiredsize <= newsize) {1779break;1780}1781}1782}1783return newsize;1784}17851786#ifdef ASSERT1787class VerifySDReachableAndLiveClosure : public OopClosure {1788private:1789BoolObjectClosure* _is_alive;17901791template <class T> void do_oop_work(T* p) {1792oop obj = oopDesc::load_decode_heap_oop(p);1793guarantee(_is_alive->do_object_b(obj), "Oop in system dictionary must be live");1794}17951796public:1797VerifySDReachableAndLiveClosure(BoolObjectClosure* is_alive) : OopClosure(), _is_alive(is_alive) { }17981799virtual void do_oop(oop* p) { do_oop_work(p); }1800virtual void do_oop(narrowOop* p) { do_oop_work(p); }1801};1802#endif18031804// Assumes classes in the SystemDictionary are only unloaded at a safepoint1805// Note: anonymous classes are not in the SD.1806bool SystemDictionary::do_unloading(BoolObjectClosure* is_alive, bool clean_alive) {1807// First, mark for unload all ClassLoaderData referencing a dead class loader.1808bool unloading_occurred = ClassLoaderDataGraph::do_unloading(is_alive, clean_alive);1809if (unloading_occurred) {1810JFR_ONLY(Jfr::on_unloading_classes();)1811dictionary()->do_unloading();1812constraints()->purge_loader_constraints();1813resolution_errors()->purge_resolution_errors();1814}1815// Oops referenced by the system dictionary may get unreachable independently1816// of the class loader (eg. cached protection domain oops). So we need to1817// explicitly unlink them here instead of in Dictionary::do_unloading.1818dictionary()->unlink(is_alive);1819#ifdef ASSERT1820VerifySDReachableAndLiveClosure cl(is_alive);1821dictionary()->oops_do(&cl);1822#endif1823return unloading_occurred;1824}18251826void SystemDictionary::roots_oops_do(OopClosure* strong, OopClosure* weak) {1827strong->do_oop(&_java_system_loader);1828strong->do_oop(&_system_loader_lock_obj);1829CDS_ONLY(SystemDictionaryShared::roots_oops_do(strong);)18301831// Adjust dictionary1832dictionary()->roots_oops_do(strong, weak);18331834// Visit extra methods1835invoke_method_table()->oops_do(strong);1836}18371838void SystemDictionary::oops_do(OopClosure* f) {1839f->do_oop(&_java_system_loader);1840f->do_oop(&_system_loader_lock_obj);1841CDS_ONLY(SystemDictionaryShared::oops_do(f);)18421843// Adjust dictionary1844dictionary()->oops_do(f);18451846// Visit extra methods1847invoke_method_table()->oops_do(f);1848}18491850// Extended Class redefinition support.1851// If one of these classes is replaced, we need to replace it in these places.1852// KlassClosure::do_klass should take the address of a class but we can1853// change that later.1854void SystemDictionary::preloaded_classes_do(KlassClosure* f) {1855for (int k = (int)FIRST_WKID; k < (int)WKID_LIMIT; k++) {1856f->do_klass(_well_known_klasses[k]);1857}18581859{1860for (int i = 0; i < T_VOID+1; i++) {1861if (_box_klasses[i] != NULL) {1862assert(i >= T_BOOLEAN, "checking");1863f->do_klass(_box_klasses[i]);1864}1865}1866}18671868FilteredFieldsMap::classes_do(f);1869}18701871void SystemDictionary::lazily_loaded_classes_do(KlassClosure* f) {1872f->do_klass(_abstract_ownable_synchronizer_klass);1873}18741875// Just the classes from defining class loaders1876// Don't iterate over placeholders1877void SystemDictionary::classes_do(void f(Klass*)) {1878dictionary()->classes_do(f);1879}18801881// Added for initialize_itable_for_klass1882// Just the classes from defining class loaders1883// Don't iterate over placeholders1884void SystemDictionary::classes_do(void f(Klass*, TRAPS), TRAPS) {1885dictionary()->classes_do(f, CHECK);1886}18871888// All classes, and their class loaders1889// Don't iterate over placeholders1890void SystemDictionary::classes_do(void f(Klass*, ClassLoaderData*)) {1891dictionary()->classes_do(f);1892}18931894void SystemDictionary::placeholders_do(void f(Symbol*)) {1895placeholders()->entries_do(f);1896}18971898void SystemDictionary::methods_do(void f(Method*)) {1899dictionary()->methods_do(f);1900invoke_method_table()->methods_do(f);1901}19021903void SystemDictionary::remove_classes_in_error_state() {1904dictionary()->remove_classes_in_error_state();1905}19061907// ----------------------------------------------------------------------------1908// Lazily load klasses19091910void SystemDictionary::load_abstract_ownable_synchronizer_klass(TRAPS) {1911assert(JDK_Version::is_gte_jdk16x_version(), "Must be JDK 1.6 or later");19121913// if multiple threads calling this function, only one thread will load1914// the class. The other threads will find the loaded version once the1915// class is loaded.1916Klass* aos = _abstract_ownable_synchronizer_klass;1917if (aos == NULL) {1918Klass* k = resolve_or_fail(vmSymbols::java_util_concurrent_locks_AbstractOwnableSynchronizer(), true, CHECK);1919// Force a fence to prevent any read before the write completes1920OrderAccess::fence();1921_abstract_ownable_synchronizer_klass = k;1922}1923}19241925// ----------------------------------------------------------------------------1926// Initialization19271928void SystemDictionary::initialize(TRAPS) {1929// Allocate arrays1930assert(dictionary() == NULL,1931"SystemDictionary should only be initialized once");1932_sdgeneration = 0;1933_dictionary = new Dictionary(calculate_systemdictionary_size(PredictedLoadedClassCount));1934_placeholders = new PlaceholderTable(_nof_buckets);1935_number_of_modifications = 0;1936_loader_constraints = new LoaderConstraintTable(_loader_constraint_size);1937_resolution_errors = new ResolutionErrorTable(_resolution_error_size);1938_invoke_method_table = new SymbolPropertyTable(_invoke_method_size);19391940// Allocate private object used as system class loader lock1941_system_loader_lock_obj = oopFactory::new_intArray(0, CHECK);1942// Initialize basic classes1943initialize_preloaded_classes(CHECK);1944#if INCLUDE_JFR1945jfr_event_handler_proxy = SymbolTable::new_permanent_symbol("jdk/jfr/proxy/internal/EventHandlerProxy", CHECK);1946#endif // INCLUDE_JFR1947}19481949// Compact table of directions on the initialization of klasses:1950static const short wk_init_info[] = {1951#define WK_KLASS_INIT_INFO(name, symbol, option) \1952( ((int)vmSymbols::VM_SYMBOL_ENUM_NAME(symbol) \1953<< SystemDictionary::CEIL_LG_OPTION_LIMIT) \1954| (int)SystemDictionary::option ),1955WK_KLASSES_DO(WK_KLASS_INIT_INFO)1956#undef WK_KLASS_INIT_INFO195701958};19591960bool SystemDictionary::initialize_wk_klass(WKID id, int init_opt, TRAPS) {1961assert(id >= (int)FIRST_WKID && id < (int)WKID_LIMIT, "oob");1962int info = wk_init_info[id - FIRST_WKID];1963int sid = (info >> CEIL_LG_OPTION_LIMIT);1964Symbol* symbol = vmSymbols::symbol_at((vmSymbols::SID)sid);1965Klass** klassp = &_well_known_klasses[id];1966bool must_load = (init_opt < SystemDictionary::Opt);1967if ((*klassp) == NULL) {1968if (must_load) {1969(*klassp) = resolve_or_fail(symbol, true, CHECK_0); // load required class1970} else {1971(*klassp) = resolve_or_null(symbol, CHECK_0); // load optional klass1972}1973}1974return ((*klassp) != NULL);1975}19761977void SystemDictionary::initialize_wk_klasses_until(WKID limit_id, WKID &start_id, TRAPS) {1978assert((int)start_id <= (int)limit_id, "IDs are out of order!");1979for (int id = (int)start_id; id < (int)limit_id; id++) {1980assert(id >= (int)FIRST_WKID && id < (int)WKID_LIMIT, "oob");1981int info = wk_init_info[id - FIRST_WKID];1982int sid = (info >> CEIL_LG_OPTION_LIMIT);1983int opt = (info & right_n_bits(CEIL_LG_OPTION_LIMIT));19841985initialize_wk_klass((WKID)id, opt, CHECK);1986}19871988// move the starting value forward to the limit:1989start_id = limit_id;1990}19911992void SystemDictionary::initialize_preloaded_classes(TRAPS) {1993assert(WK_KLASS(Object_klass) == NULL, "preloaded classes should only be initialized once");1994// Preload commonly used klasses1995WKID scan = FIRST_WKID;1996// first do Object, then String, Class1997if (UseSharedSpaces) {1998initialize_wk_klasses_through(WK_KLASS_ENUM_NAME(Object_klass), scan, CHECK);1999// Initialize the constant pool for the Object_class2000InstanceKlass* ik = InstanceKlass::cast(Object_klass());2001ik->constants()->restore_unshareable_info(CHECK);2002initialize_wk_klasses_through(WK_KLASS_ENUM_NAME(Class_klass), scan, CHECK);2003} else {2004initialize_wk_klasses_through(WK_KLASS_ENUM_NAME(Class_klass), scan, CHECK);2005}20062007// Calculate offsets for String and Class classes since they are loaded and2008// can be used after this point.2009java_lang_String::compute_offsets();2010java_lang_Class::compute_offsets();20112012// Fixup mirrors for classes loaded before java.lang.Class.2013// These calls iterate over the objects currently in the perm gen2014// so calling them at this point is matters (not before when there2015// are fewer objects and not later after there are more objects2016// in the perm gen.2017Universe::initialize_basic_type_mirrors(CHECK);2018Universe::fixup_mirrors(CHECK);20192020// do a bunch more:2021initialize_wk_klasses_through(WK_KLASS_ENUM_NAME(Reference_klass), scan, CHECK);20222023// Preload ref klasses and set reference types2024InstanceKlass::cast(WK_KLASS(Reference_klass))->set_reference_type(REF_OTHER);2025InstanceRefKlass::update_nonstatic_oop_maps(WK_KLASS(Reference_klass));20262027initialize_wk_klasses_through(WK_KLASS_ENUM_NAME(Cleaner_klass), scan, CHECK);2028InstanceKlass::cast(WK_KLASS(SoftReference_klass))->set_reference_type(REF_SOFT);2029InstanceKlass::cast(WK_KLASS(WeakReference_klass))->set_reference_type(REF_WEAK);2030InstanceKlass::cast(WK_KLASS(FinalReference_klass))->set_reference_type(REF_FINAL);2031InstanceKlass::cast(WK_KLASS(PhantomReference_klass))->set_reference_type(REF_PHANTOM);2032InstanceKlass::cast(WK_KLASS(Cleaner_klass))->set_reference_type(REF_CLEANER);20332034initialize_wk_klasses_through(WK_KLASS_ENUM_NAME(ReferenceQueue_klass), scan, CHECK);20352036// JSR 292 classes2037WKID jsr292_group_start = WK_KLASS_ENUM_NAME(MethodHandle_klass);2038WKID jsr292_group_end = WK_KLASS_ENUM_NAME(VolatileCallSite_klass);2039initialize_wk_klasses_until(jsr292_group_start, scan, CHECK);2040if (EnableInvokeDynamic) {2041initialize_wk_klasses_through(jsr292_group_end, scan, CHECK);2042} else {2043// Skip the JSR 292 classes, if not enabled.2044scan = WKID(jsr292_group_end + 1);2045}20462047initialize_wk_klasses_until(WKID_LIMIT, scan, CHECK);20482049_box_klasses[T_BOOLEAN] = WK_KLASS(Boolean_klass);2050_box_klasses[T_CHAR] = WK_KLASS(Character_klass);2051_box_klasses[T_FLOAT] = WK_KLASS(Float_klass);2052_box_klasses[T_DOUBLE] = WK_KLASS(Double_klass);2053_box_klasses[T_BYTE] = WK_KLASS(Byte_klass);2054_box_klasses[T_SHORT] = WK_KLASS(Short_klass);2055_box_klasses[T_INT] = WK_KLASS(Integer_klass);2056_box_klasses[T_LONG] = WK_KLASS(Long_klass);2057//_box_klasses[T_OBJECT] = WK_KLASS(object_klass);2058//_box_klasses[T_ARRAY] = WK_KLASS(object_klass);20592060{ // Compute whether we should use loadClass or loadClassInternal when loading classes.2061Method* method = InstanceKlass::cast(ClassLoader_klass())->find_method(vmSymbols::loadClassInternal_name(), vmSymbols::string_class_signature());2062_has_loadClassInternal = (method != NULL);2063}2064{ // Compute whether we should use checkPackageAccess or NOT2065Method* method = InstanceKlass::cast(ClassLoader_klass())->find_method(vmSymbols::checkPackageAccess_name(), vmSymbols::class_protectiondomain_signature());2066_has_checkPackageAccess = (method != NULL);2067}2068}20692070// Tells if a given klass is a box (wrapper class, such as java.lang.Integer).2071// If so, returns the basic type it holds. If not, returns T_OBJECT.2072BasicType SystemDictionary::box_klass_type(Klass* k) {2073assert(k != NULL, "");2074for (int i = T_BOOLEAN; i < T_VOID+1; i++) {2075if (_box_klasses[i] == k)2076return (BasicType)i;2077}2078return T_OBJECT;2079}20802081// Constraints on class loaders. The details of the algorithm can be2082// found in the OOPSLA'98 paper "Dynamic Class Loading in the Java2083// Virtual Machine" by Sheng Liang and Gilad Bracha. The basic idea is2084// that the system dictionary needs to maintain a set of contraints that2085// must be satisfied by all classes in the dictionary.2086// if defining is true, then LinkageError if already in systemDictionary2087// if initiating loader, then ok if InstanceKlass matches existing entry20882089void SystemDictionary::check_constraints(int d_index, unsigned int d_hash,2090instanceKlassHandle k,2091Handle class_loader, bool defining,2092TRAPS) {2093const char *linkage_error = NULL;2094{2095Symbol* name = k->name();2096ClassLoaderData *loader_data = class_loader_data(class_loader);20972098MutexLocker mu(SystemDictionary_lock, THREAD);20992100Klass* check = find_class(d_index, d_hash, name, loader_data);2101if (check != (Klass*)NULL) {2102// if different InstanceKlass - duplicate class definition,2103// else - ok, class loaded by a different thread in parallel,2104// we should only have found it if it was done loading and ok to use2105// system dictionary only holds instance classes, placeholders2106// also holds array classes21072108assert(check->oop_is_instance(), "noninstance in systemdictionary");2109if ((defining == true) || (k() != check)) {2110linkage_error = "loader (instance of %s): attempted duplicate class "2111"definition for name: \"%s\"";2112} else {2113return;2114}2115}21162117#ifdef ASSERT2118Symbol* ph_check = find_placeholder(name, loader_data);2119assert(ph_check == NULL || ph_check == name, "invalid symbol");2120#endif21212122if (linkage_error == NULL) {2123if (constraints()->check_or_update(k, class_loader, name) == false) {2124linkage_error = "loader constraint violation: loader (instance of %s)"2125" previously initiated loading for a different type with name \"%s\"";2126}2127}2128}21292130// Throw error now if needed (cannot throw while holding2131// SystemDictionary_lock because of rank ordering)21322133if (linkage_error) {2134ResourceMark rm(THREAD);2135const char* class_loader_name = loader_name(class_loader());2136char* type_name = k->name()->as_C_string();2137size_t buflen = strlen(linkage_error) + strlen(class_loader_name) +2138strlen(type_name);2139char* buf = NEW_RESOURCE_ARRAY_IN_THREAD(THREAD, char, buflen);2140jio_snprintf(buf, buflen, linkage_error, class_loader_name, type_name);2141THROW_MSG(vmSymbols::java_lang_LinkageError(), buf);2142}2143}214421452146// Update system dictionary - done after check_constraint and add_to_hierachy2147// have been called.2148void SystemDictionary::update_dictionary(int d_index, unsigned int d_hash,2149int p_index, unsigned int p_hash,2150instanceKlassHandle k,2151Handle class_loader,2152TRAPS) {2153// Compile_lock prevents systemDictionary updates during compilations2154assert_locked_or_safepoint(Compile_lock);2155Symbol* name = k->name();2156ClassLoaderData *loader_data = class_loader_data(class_loader);21572158{2159MutexLocker mu1(SystemDictionary_lock, THREAD);21602161// See whether biased locking is enabled and if so set it for this2162// klass.2163// Note that this must be done past the last potential blocking2164// point / safepoint. We enable biased locking lazily using a2165// VM_Operation to iterate the SystemDictionary and installing the2166// biasable mark word into each InstanceKlass's prototype header.2167// To avoid race conditions where we accidentally miss enabling the2168// optimization for one class in the process of being added to the2169// dictionary, we must not safepoint after the test of2170// BiasedLocking::enabled().2171if (UseBiasedLocking && BiasedLocking::enabled()) {2172// Set biased locking bit for all loaded classes; it will be2173// cleared if revocation occurs too often for this type2174// NOTE that we must only do this when the class is initally2175// defined, not each time it is referenced from a new class loader2176if (k->class_loader() == class_loader()) {2177k->set_prototype_header(markOopDesc::biased_locking_prototype());2178}2179}21802181// Make a new system dictionary entry.2182Klass* sd_check = find_class(d_index, d_hash, name, loader_data);2183if (sd_check == NULL) {2184dictionary()->add_klass(name, loader_data, k);2185notice_modification();2186}2187#ifdef ASSERT2188sd_check = find_class(d_index, d_hash, name, loader_data);2189assert (sd_check != NULL, "should have entry in system dictionary");2190// Note: there may be a placeholder entry: for circularity testing2191// or for parallel defines2192#endif2193SystemDictionary_lock->notify_all();2194}2195}219621972198// Try to find a class name using the loader constraints. The2199// loader constraints might know about a class that isn't fully loaded2200// yet and these will be ignored.2201Klass* SystemDictionary::find_constrained_instance_or_array_klass(2202Symbol* class_name, Handle class_loader, TRAPS) {22032204// First see if it has been loaded directly.2205// Force the protection domain to be null. (This removes protection checks.)2206Handle no_protection_domain;2207Klass* klass = find_instance_or_array_klass(class_name, class_loader,2208no_protection_domain, CHECK_NULL);2209if (klass != NULL)2210return klass;22112212// Now look to see if it has been loaded elsewhere, and is subject to2213// a loader constraint that would require this loader to return the2214// klass that is already loaded.2215if (FieldType::is_array(class_name)) {2216// For array classes, their Klass*s are not kept in the2217// constraint table. The element Klass*s are.2218FieldArrayInfo fd;2219BasicType t = FieldType::get_array_info(class_name, fd, CHECK_(NULL));2220if (t != T_OBJECT) {2221klass = Universe::typeArrayKlassObj(t);2222} else {2223MutexLocker mu(SystemDictionary_lock, THREAD);2224klass = constraints()->find_constrained_klass(fd.object_key(), class_loader);2225}2226// If element class already loaded, allocate array klass2227if (klass != NULL) {2228klass = klass->array_klass_or_null(fd.dimension());2229}2230} else {2231MutexLocker mu(SystemDictionary_lock, THREAD);2232// Non-array classes are easy: simply check the constraint table.2233klass = constraints()->find_constrained_klass(class_name, class_loader);2234}22352236return klass;2237}223822392240bool SystemDictionary::add_loader_constraint(Symbol* class_name,2241Handle class_loader1,2242Handle class_loader2,2243Thread* THREAD) {2244ClassLoaderData* loader_data1 = class_loader_data(class_loader1);2245ClassLoaderData* loader_data2 = class_loader_data(class_loader2);22462247Symbol* constraint_name = NULL;2248if (!FieldType::is_array(class_name)) {2249constraint_name = class_name;2250} else {2251// For array classes, their Klass*s are not kept in the2252// constraint table. The element classes are.2253FieldArrayInfo fd;2254BasicType t = FieldType::get_array_info(class_name, fd, CHECK_(false));2255// primitive types always pass2256if (t != T_OBJECT) {2257return true;2258} else {2259constraint_name = fd.object_key();2260}2261}2262unsigned int d_hash1 = dictionary()->compute_hash(constraint_name, loader_data1);2263int d_index1 = dictionary()->hash_to_index(d_hash1);22642265unsigned int d_hash2 = dictionary()->compute_hash(constraint_name, loader_data2);2266int d_index2 = dictionary()->hash_to_index(d_hash2);2267{2268MutexLocker mu_s(SystemDictionary_lock, THREAD);22692270// Better never do a GC while we're holding these oops2271No_Safepoint_Verifier nosafepoint;22722273Klass* klass1 = find_class(d_index1, d_hash1, constraint_name, loader_data1);2274Klass* klass2 = find_class(d_index2, d_hash2, constraint_name, loader_data2);2275return constraints()->add_entry(constraint_name, klass1, class_loader1,2276klass2, class_loader2);2277}2278}22792280// Add entry to resolution error table to record the error when the first2281// attempt to resolve a reference to a class has failed.2282void SystemDictionary::add_resolution_error(constantPoolHandle pool, int which,2283Symbol* error, Symbol* message) {2284unsigned int hash = resolution_errors()->compute_hash(pool, which);2285int index = resolution_errors()->hash_to_index(hash);2286{2287MutexLocker ml(SystemDictionary_lock, Thread::current());2288resolution_errors()->add_entry(index, hash, pool, which, error, message);2289}2290}22912292// Delete a resolution error for RedefineClasses for a constant pool is going away2293void SystemDictionary::delete_resolution_error(ConstantPool* pool) {2294resolution_errors()->delete_entry(pool);2295}22962297// Lookup resolution error table. Returns error if found, otherwise NULL.2298Symbol* SystemDictionary::find_resolution_error(constantPoolHandle pool, int which,2299Symbol** message) {2300unsigned int hash = resolution_errors()->compute_hash(pool, which);2301int index = resolution_errors()->hash_to_index(hash);2302{2303MutexLocker ml(SystemDictionary_lock, Thread::current());2304ResolutionErrorEntry* entry = resolution_errors()->find_entry(index, hash, pool, which);2305if (entry != NULL) {2306*message = entry->message();2307return entry->error();2308} else {2309return NULL;2310}2311}2312}231323142315// Signature constraints ensure that callers and callees agree about2316// the meaning of type names in their signatures. This routine is the2317// intake for constraints. It collects them from several places:2318//2319// * LinkResolver::resolve_method (if check_access is true) requires2320// that the resolving class (the caller) and the defining class of2321// the resolved method (the callee) agree on each type in the2322// method's signature.2323//2324// * LinkResolver::resolve_interface_method performs exactly the same2325// checks.2326//2327// * LinkResolver::resolve_field requires that the constant pool2328// attempting to link to a field agree with the field's defining2329// class about the type of the field signature.2330//2331// * klassVtable::initialize_vtable requires that, when a class2332// overrides a vtable entry allocated by a superclass, that the2333// overriding method (i.e., the callee) agree with the superclass2334// on each type in the method's signature.2335//2336// * klassItable::initialize_itable requires that, when a class fills2337// in its itables, for each non-abstract method installed in an2338// itable, the method (i.e., the callee) agree with the interface2339// on each type in the method's signature.2340//2341// All those methods have a boolean (check_access, checkconstraints)2342// which turns off the checks. This is used from specialized contexts2343// such as bootstrapping, dumping, and debugging.2344//2345// No direct constraint is placed between the class and its2346// supertypes. Constraints are only placed along linked relations2347// between callers and callees. When a method overrides or implements2348// an abstract method in a supertype (superclass or interface), the2349// constraints are placed as if the supertype were the caller to the2350// overriding method. (This works well, since callers to the2351// supertype have already established agreement between themselves and2352// the supertype.) As a result of all this, a class can disagree with2353// its supertype about the meaning of a type name, as long as that2354// class neither calls a relevant method of the supertype, nor is2355// called (perhaps via an override) from the supertype.2356//2357//2358// SystemDictionary::check_signature_loaders(sig, l1, l2)2359//2360// Make sure all class components (including arrays) in the given2361// signature will be resolved to the same class in both loaders.2362// Returns the name of the type that failed a loader constraint check, or2363// NULL if no constraint failed. No exception except OOME is thrown.2364// Arrays are not added to the loader constraint table, their elements are.2365Symbol* SystemDictionary::check_signature_loaders(Symbol* signature,2366Handle loader1, Handle loader2,2367bool is_method, TRAPS) {2368// Nothing to do if loaders are the same.2369if (loader1() == loader2()) {2370return NULL;2371}23722373SignatureStream sig_strm(signature, is_method);2374while (!sig_strm.is_done()) {2375if (sig_strm.is_object()) {2376Symbol* sig = sig_strm.as_symbol(CHECK_NULL);2377if (!add_loader_constraint(sig, loader1, loader2, THREAD)) {2378return sig;2379}2380}2381sig_strm.next();2382}2383return NULL;2384}238523862387methodHandle SystemDictionary::find_method_handle_intrinsic(vmIntrinsics::ID iid,2388Symbol* signature,2389TRAPS) {2390methodHandle empty;2391assert(EnableInvokeDynamic, "");2392assert(MethodHandles::is_signature_polymorphic(iid) &&2393MethodHandles::is_signature_polymorphic_intrinsic(iid) &&2394iid != vmIntrinsics::_invokeGeneric,2395err_msg("must be a known MH intrinsic iid=%d: %s", iid, vmIntrinsics::name_at(iid)));23962397unsigned int hash = invoke_method_table()->compute_hash(signature, iid);2398int index = invoke_method_table()->hash_to_index(hash);2399SymbolPropertyEntry* spe = invoke_method_table()->find_entry(index, hash, signature, iid);2400methodHandle m;2401if (spe == NULL || spe->method() == NULL) {2402spe = NULL;2403// Must create lots of stuff here, but outside of the SystemDictionary lock.2404m = Method::make_method_handle_intrinsic(iid, signature, CHECK_(empty));2405if (!Arguments::is_interpreter_only()) {2406// Generate a compiled form of the MH intrinsic.2407AdapterHandlerLibrary::create_native_wrapper(m);2408// Check if have the compiled code.2409if (!m->has_compiled_code()) {2410THROW_MSG_(vmSymbols::java_lang_VirtualMachineError(),2411"out of space in CodeCache for method handle intrinsic", empty);2412}2413}2414// Now grab the lock. We might have to throw away the new method,2415// if a racing thread has managed to install one at the same time.2416{2417MutexLocker ml(SystemDictionary_lock, THREAD);2418spe = invoke_method_table()->find_entry(index, hash, signature, iid);2419if (spe == NULL)2420spe = invoke_method_table()->add_entry(index, hash, signature, iid);2421if (spe->method() == NULL)2422spe->set_method(m());2423}2424}24252426assert(spe != NULL && spe->method() != NULL, "");2427assert(Arguments::is_interpreter_only() || (spe->method()->has_compiled_code() &&2428spe->method()->code()->entry_point() == spe->method()->from_compiled_entry()),2429"MH intrinsic invariant");2430return spe->method();2431}24322433// Helper for unpacking the return value from linkMethod and linkCallSite.2434static methodHandle unpack_method_and_appendix(Handle mname,2435KlassHandle accessing_klass,2436objArrayHandle appendix_box,2437Handle* appendix_result,2438TRAPS) {2439methodHandle empty;2440if (mname.not_null()) {2441Metadata* vmtarget = java_lang_invoke_MemberName::vmtarget(mname());2442if (vmtarget != NULL && vmtarget->is_method()) {2443Method* m = (Method*)vmtarget;2444oop appendix = appendix_box->obj_at(0);2445if (TraceMethodHandles) {2446#ifndef PRODUCT2447tty->print("Linked method=" INTPTR_FORMAT ": ", p2i(m));2448m->print();2449if (appendix != NULL) { tty->print("appendix = "); appendix->print(); }2450tty->cr();2451#endif //PRODUCT2452}2453(*appendix_result) = Handle(THREAD, appendix);2454// the target is stored in the cpCache and if a reference to this2455// MethodName is dropped we need a way to make sure the2456// class_loader containing this method is kept alive.2457// FIXME: the appendix might also preserve this dependency.2458ClassLoaderData* this_key = InstanceKlass::cast(accessing_klass())->class_loader_data();2459this_key->record_dependency(m->method_holder(), CHECK_NULL); // Can throw OOM2460return methodHandle(THREAD, m);2461}2462}2463THROW_MSG_(vmSymbols::java_lang_LinkageError(), "bad value from MethodHandleNatives", empty);2464return empty;2465}24662467methodHandle SystemDictionary::find_method_handle_invoker(Symbol* name,2468Symbol* signature,2469KlassHandle accessing_klass,2470Handle *appendix_result,2471Handle *method_type_result,2472TRAPS) {2473methodHandle empty;2474assert(EnableInvokeDynamic, "");2475assert(!THREAD->is_Compiler_thread(), "");2476Handle method_type =2477SystemDictionary::find_method_handle_type(signature, accessing_klass, CHECK_(empty));24782479KlassHandle mh_klass = SystemDictionary::MethodHandle_klass();2480int ref_kind = JVM_REF_invokeVirtual;2481Handle name_str = StringTable::intern(name, CHECK_(empty));2482objArrayHandle appendix_box = oopFactory::new_objArray(SystemDictionary::Object_klass(), 1, CHECK_(empty));2483assert(appendix_box->obj_at(0) == NULL, "");24842485// This should not happen. JDK code should take care of that.2486if (accessing_klass.is_null() || method_type.is_null()) {2487THROW_MSG_(vmSymbols::java_lang_InternalError(), "bad invokehandle", empty);2488}24892490// call java.lang.invoke.MethodHandleNatives::linkMethod(... String, MethodType) -> MemberName2491JavaCallArguments args;2492args.push_oop(accessing_klass()->java_mirror());2493args.push_int(ref_kind);2494args.push_oop(mh_klass()->java_mirror());2495args.push_oop(name_str());2496args.push_oop(method_type());2497args.push_oop(appendix_box());2498JavaValue result(T_OBJECT);2499JavaCalls::call_static(&result,2500SystemDictionary::MethodHandleNatives_klass(),2501vmSymbols::linkMethod_name(),2502vmSymbols::linkMethod_signature(),2503&args, CHECK_(empty));2504Handle mname(THREAD, (oop) result.get_jobject());2505(*method_type_result) = method_type;2506return unpack_method_and_appendix(mname, accessing_klass, appendix_box, appendix_result, THREAD);2507}25082509// Decide if we can globally cache a lookup of this class, to be returned to any client that asks.2510// We must ensure that all class loaders everywhere will reach this class, for any client.2511// This is a safe bet for public classes in java.lang, such as Object and String.2512// We also include public classes in java.lang.invoke, because they appear frequently in system-level method types.2513// Out of an abundance of caution, we do not include any other classes, not even for packages like java.util.2514static bool is_always_visible_class(oop mirror) {2515Klass* klass = java_lang_Class::as_Klass(mirror);2516if (klass->oop_is_objArray()) {2517klass = ObjArrayKlass::cast(klass)->bottom_klass(); // check element type2518}2519if (klass->oop_is_typeArray()) {2520return true; // primitive array2521}2522assert(klass->oop_is_instance(), klass->external_name());2523return klass->is_public() &&2524(InstanceKlass::cast(klass)->is_same_class_package(SystemDictionary::Object_klass()) || // java.lang2525InstanceKlass::cast(klass)->is_same_class_package(SystemDictionary::MethodHandle_klass())); // java.lang.invoke2526}25272528// Ask Java code to find or construct a java.lang.invoke.MethodType for the given2529// signature, as interpreted relative to the given class loader.2530// Because of class loader constraints, all method handle usage must be2531// consistent with this loader.2532Handle SystemDictionary::find_method_handle_type(Symbol* signature,2533KlassHandle accessing_klass,2534TRAPS) {2535Handle empty;2536vmIntrinsics::ID null_iid = vmIntrinsics::_none; // distinct from all method handle invoker intrinsics2537unsigned int hash = invoke_method_table()->compute_hash(signature, null_iid);2538int index = invoke_method_table()->hash_to_index(hash);2539SymbolPropertyEntry* spe = invoke_method_table()->find_entry(index, hash, signature, null_iid);2540if (spe != NULL && spe->method_type() != NULL) {2541assert(java_lang_invoke_MethodType::is_instance(spe->method_type()), "");2542return Handle(THREAD, spe->method_type());2543} else if (THREAD->is_Compiler_thread()) {2544warning("SystemDictionary::find_method_handle_type called from compiler thread"); // FIXME2545return Handle(); // do not attempt from within compiler, unless it was cached2546}25472548Handle class_loader, protection_domain;2549if (accessing_klass.not_null()) {2550class_loader = Handle(THREAD, InstanceKlass::cast(accessing_klass())->class_loader());2551protection_domain = Handle(THREAD, InstanceKlass::cast(accessing_klass())->protection_domain());2552}2553bool can_be_cached = true;2554int npts = ArgumentCount(signature).size();2555objArrayHandle pts = oopFactory::new_objArray(SystemDictionary::Class_klass(), npts, CHECK_(empty));2556int arg = 0;2557Handle rt; // the return type from the signature2558ResourceMark rm(THREAD);2559for (SignatureStream ss(signature); !ss.is_done(); ss.next()) {2560oop mirror = NULL;2561if (can_be_cached) {2562// Use neutral class loader to lookup candidate classes to be placed in the cache.2563mirror = ss.as_java_mirror(Handle(), Handle(),2564SignatureStream::ReturnNull, CHECK_(empty));2565if (mirror == NULL || (ss.is_object() && !is_always_visible_class(mirror))) {2566// Fall back to accessing_klass context.2567can_be_cached = false;2568}2569}2570if (!can_be_cached) {2571// Resolve, throwing a real error if it doesn't work.2572mirror = ss.as_java_mirror(class_loader, protection_domain,2573SignatureStream::NCDFError, CHECK_(empty));2574}2575assert(!oopDesc::is_null(mirror), ss.as_symbol(THREAD)->as_C_string());2576if (ss.at_return_type())2577rt = Handle(THREAD, mirror);2578else2579pts->obj_at_put(arg++, mirror);25802581// Check accessibility.2582if (ss.is_object() && accessing_klass.not_null()) {2583Klass* sel_klass = java_lang_Class::as_Klass(mirror);2584mirror = NULL; // safety2585// Emulate ConstantPool::verify_constant_pool_resolve.2586if (sel_klass->oop_is_objArray())2587sel_klass = ObjArrayKlass::cast(sel_klass)->bottom_klass();2588if (sel_klass->oop_is_instance()) {2589KlassHandle sel_kh(THREAD, sel_klass);2590LinkResolver::check_klass_accessability(accessing_klass, sel_kh, CHECK_(empty));2591}2592}2593}2594assert(arg == npts, "");25952596// call java.lang.invoke.MethodHandleNatives::findMethodType(Class rt, Class[] pts) -> MethodType2597JavaCallArguments args(Handle(THREAD, rt()));2598args.push_oop(pts());2599JavaValue result(T_OBJECT);2600JavaCalls::call_static(&result,2601SystemDictionary::MethodHandleNatives_klass(),2602vmSymbols::findMethodHandleType_name(),2603vmSymbols::findMethodHandleType_signature(),2604&args, CHECK_(empty));2605Handle method_type(THREAD, (oop) result.get_jobject());26062607if (can_be_cached) {2608// We can cache this MethodType inside the JVM.2609MutexLocker ml(SystemDictionary_lock, THREAD);2610spe = invoke_method_table()->find_entry(index, hash, signature, null_iid);2611if (spe == NULL)2612spe = invoke_method_table()->add_entry(index, hash, signature, null_iid);2613if (spe->method_type() == NULL) {2614spe->set_method_type(method_type());2615}2616}26172618// report back to the caller with the MethodType2619return method_type;2620}26212622// Ask Java code to find or construct a method handle constant.2623Handle SystemDictionary::link_method_handle_constant(KlassHandle caller,2624int ref_kind, //e.g., JVM_REF_invokeVirtual2625KlassHandle callee,2626Symbol* name_sym,2627Symbol* signature,2628TRAPS) {2629Handle empty;2630Handle name = java_lang_String::create_from_symbol(name_sym, CHECK_(empty));2631Handle type;2632if (signature->utf8_length() > 0 && signature->byte_at(0) == '(') {2633type = find_method_handle_type(signature, caller, CHECK_(empty));2634} else if (caller.is_null()) {2635// This should not happen. JDK code should take care of that.2636THROW_MSG_(vmSymbols::java_lang_InternalError(), "bad MH constant", empty);2637} else {2638ResourceMark rm(THREAD);2639SignatureStream ss(signature, false);2640if (!ss.is_done()) {2641oop mirror = ss.as_java_mirror(caller->class_loader(), caller->protection_domain(),2642SignatureStream::NCDFError, CHECK_(empty));2643type = Handle(THREAD, mirror);2644ss.next();2645if (!ss.is_done()) type = Handle(); // error!2646}2647}2648if (type.is_null()) {2649THROW_MSG_(vmSymbols::java_lang_LinkageError(), "bad signature", empty);2650}26512652// call java.lang.invoke.MethodHandleNatives::linkMethodHandleConstant(Class caller, int refKind, Class callee, String name, Object type) -> MethodHandle2653JavaCallArguments args;2654args.push_oop(caller->java_mirror()); // the referring class2655args.push_int(ref_kind);2656args.push_oop(callee->java_mirror()); // the target class2657args.push_oop(name());2658args.push_oop(type());2659JavaValue result(T_OBJECT);2660JavaCalls::call_static(&result,2661SystemDictionary::MethodHandleNatives_klass(),2662vmSymbols::linkMethodHandleConstant_name(),2663vmSymbols::linkMethodHandleConstant_signature(),2664&args, CHECK_(empty));2665return Handle(THREAD, (oop) result.get_jobject());2666}26672668// Ask Java code to find or construct a java.lang.invoke.CallSite for the given2669// name and signature, as interpreted relative to the given class loader.2670methodHandle SystemDictionary::find_dynamic_call_site_invoker(KlassHandle caller,2671Handle bootstrap_specifier,2672Symbol* name,2673Symbol* type,2674Handle *appendix_result,2675Handle *method_type_result,2676TRAPS) {2677methodHandle empty;2678Handle bsm, info;2679if (java_lang_invoke_MethodHandle::is_instance(bootstrap_specifier())) {2680bsm = bootstrap_specifier;2681} else {2682assert(bootstrap_specifier->is_objArray(), "");2683objArrayHandle args(THREAD, (objArrayOop) bootstrap_specifier());2684int len = args->length();2685assert(len >= 1, "");2686bsm = Handle(THREAD, args->obj_at(0));2687if (len > 1) {2688objArrayOop args1 = oopFactory::new_objArray(SystemDictionary::Object_klass(), len-1, CHECK_(empty));2689for (int i = 1; i < len; i++)2690args1->obj_at_put(i-1, args->obj_at(i));2691info = Handle(THREAD, args1);2692}2693}2694guarantee(java_lang_invoke_MethodHandle::is_instance(bsm()),2695"caller must supply a valid BSM");26962697Handle method_name = java_lang_String::create_from_symbol(name, CHECK_(empty));2698Handle method_type = find_method_handle_type(type, caller, CHECK_(empty));26992700// This should not happen. JDK code should take care of that.2701if (caller.is_null() || method_type.is_null()) {2702THROW_MSG_(vmSymbols::java_lang_InternalError(), "bad invokedynamic", empty);2703}27042705objArrayHandle appendix_box = oopFactory::new_objArray(SystemDictionary::Object_klass(), 1, CHECK_(empty));2706assert(appendix_box->obj_at(0) == NULL, "");27072708// call java.lang.invoke.MethodHandleNatives::linkCallSite(caller, bsm, name, mtype, info, &appendix)2709JavaCallArguments args;2710args.push_oop(caller->java_mirror());2711args.push_oop(bsm());2712args.push_oop(method_name());2713args.push_oop(method_type());2714args.push_oop(info());2715args.push_oop(appendix_box);2716JavaValue result(T_OBJECT);2717JavaCalls::call_static(&result,2718SystemDictionary::MethodHandleNatives_klass(),2719vmSymbols::linkCallSite_name(),2720vmSymbols::linkCallSite_signature(),2721&args, CHECK_(empty));2722Handle mname(THREAD, (oop) result.get_jobject());2723(*method_type_result) = method_type;2724return unpack_method_and_appendix(mname, caller, appendix_box, appendix_result, THREAD);2725}27262727// Since the identity hash code for symbols changes when the symbols are2728// moved from the regular perm gen (hash in the mark word) to the shared2729// spaces (hash is the address), the classes loaded into the dictionary2730// may be in the wrong buckets.27312732void SystemDictionary::reorder_dictionary() {2733dictionary()->reorder_dictionary();2734}273527362737void SystemDictionary::copy_buckets(char** top, char* end) {2738dictionary()->copy_buckets(top, end);2739}274027412742void SystemDictionary::copy_table(char** top, char* end) {2743dictionary()->copy_table(top, end);2744}274527462747void SystemDictionary::reverse() {2748dictionary()->reverse();2749}27502751int SystemDictionary::number_of_classes() {2752return dictionary()->number_of_entries();2753}275427552756// ----------------------------------------------------------------------------2757void SystemDictionary::print_shared(bool details) {2758shared_dictionary()->print(details);2759}27602761void SystemDictionary::print(bool details) {2762dictionary()->print(details);27632764// Placeholders2765GCMutexLocker mu(SystemDictionary_lock);2766placeholders()->print();27672768// loader constraints - print under SD_lock2769constraints()->print();2770}277127722773void SystemDictionary::verify() {2774guarantee(dictionary() != NULL, "Verify of system dictionary failed");2775guarantee(constraints() != NULL,2776"Verify of loader constraints failed");2777guarantee(dictionary()->number_of_entries() >= 0 &&2778placeholders()->number_of_entries() >= 0,2779"Verify of system dictionary failed");27802781// Verify dictionary2782dictionary()->verify();27832784GCMutexLocker mu(SystemDictionary_lock);2785placeholders()->verify();27862787// Verify constraint table2788guarantee(constraints() != NULL, "Verify of loader constraints failed");2789constraints()->verify(dictionary(), placeholders());2790}27912792#ifndef PRODUCT27932794// statistics code2795class ClassStatistics: AllStatic {2796private:2797static int nclasses; // number of classes2798static int nmethods; // number of methods2799static int nmethoddata; // number of methodData2800static int class_size; // size of class objects in words2801static int method_size; // size of method objects in words2802static int debug_size; // size of debug info in methods2803static int methoddata_size; // size of methodData objects in words28042805static void do_class(Klass* k) {2806nclasses++;2807class_size += k->size();2808if (k->oop_is_instance()) {2809InstanceKlass* ik = (InstanceKlass*)k;2810class_size += ik->methods()->size();2811class_size += ik->constants()->size();2812class_size += ik->local_interfaces()->size();2813class_size += ik->transitive_interfaces()->size();2814// We do not have to count implementors, since we only store one!2815// SSS: How should these be accounted now that they have moved?2816// class_size += ik->fields()->length();2817}2818}28192820static void do_method(Method* m) {2821nmethods++;2822method_size += m->size();2823// class loader uses same objArray for empty vectors, so don't count these2824if (m->has_stackmap_table()) {2825method_size += m->stackmap_data()->size();2826}28272828MethodData* mdo = m->method_data();2829if (mdo != NULL) {2830nmethoddata++;2831methoddata_size += mdo->size();2832}2833}28342835public:2836static void print() {2837SystemDictionary::classes_do(do_class);2838SystemDictionary::methods_do(do_method);2839tty->print_cr("Class statistics:");2840tty->print_cr("%d classes (%d bytes)", nclasses, class_size * oopSize);2841tty->print_cr("%d methods (%d bytes = %d base + %d debug info)", nmethods,2842(method_size + debug_size) * oopSize, method_size * oopSize, debug_size * oopSize);2843tty->print_cr("%d methoddata (%d bytes)", nmethoddata, methoddata_size * oopSize);2844}2845};284628472848int ClassStatistics::nclasses = 0;2849int ClassStatistics::nmethods = 0;2850int ClassStatistics::nmethoddata = 0;2851int ClassStatistics::class_size = 0;2852int ClassStatistics::method_size = 0;2853int ClassStatistics::debug_size = 0;2854int ClassStatistics::methoddata_size = 0;28552856void SystemDictionary::print_class_statistics() {2857ResourceMark rm;2858ClassStatistics::print();2859}286028612862class MethodStatistics: AllStatic {2863public:2864enum {2865max_parameter_size = 102866};2867private:28682869static int _number_of_methods;2870static int _number_of_final_methods;2871static int _number_of_static_methods;2872static int _number_of_native_methods;2873static int _number_of_synchronized_methods;2874static int _number_of_profiled_methods;2875static int _number_of_bytecodes;2876static int _parameter_size_profile[max_parameter_size];2877static int _bytecodes_profile[Bytecodes::number_of_java_codes];28782879static void initialize() {2880_number_of_methods = 0;2881_number_of_final_methods = 0;2882_number_of_static_methods = 0;2883_number_of_native_methods = 0;2884_number_of_synchronized_methods = 0;2885_number_of_profiled_methods = 0;2886_number_of_bytecodes = 0;2887for (int i = 0; i < max_parameter_size ; i++) _parameter_size_profile[i] = 0;2888for (int j = 0; j < Bytecodes::number_of_java_codes; j++) _bytecodes_profile [j] = 0;2889};28902891static void do_method(Method* m) {2892_number_of_methods++;2893// collect flag info2894if (m->is_final() ) _number_of_final_methods++;2895if (m->is_static() ) _number_of_static_methods++;2896if (m->is_native() ) _number_of_native_methods++;2897if (m->is_synchronized()) _number_of_synchronized_methods++;2898if (m->method_data() != NULL) _number_of_profiled_methods++;2899// collect parameter size info (add one for receiver, if any)2900_parameter_size_profile[MIN2(m->size_of_parameters() + (m->is_static() ? 0 : 1), max_parameter_size - 1)]++;2901// collect bytecodes info2902{2903Thread *thread = Thread::current();2904HandleMark hm(thread);2905BytecodeStream s(methodHandle(thread, m));2906Bytecodes::Code c;2907while ((c = s.next()) >= 0) {2908_number_of_bytecodes++;2909_bytecodes_profile[c]++;2910}2911}2912}29132914public:2915static void print() {2916initialize();2917SystemDictionary::methods_do(do_method);2918// generate output2919tty->cr();2920tty->print_cr("Method statistics (static):");2921// flag distribution2922tty->cr();2923tty->print_cr("%6d final methods %6.1f%%", _number_of_final_methods , _number_of_final_methods * 100.0F / _number_of_methods);2924tty->print_cr("%6d static methods %6.1f%%", _number_of_static_methods , _number_of_static_methods * 100.0F / _number_of_methods);2925tty->print_cr("%6d native methods %6.1f%%", _number_of_native_methods , _number_of_native_methods * 100.0F / _number_of_methods);2926tty->print_cr("%6d synchronized methods %6.1f%%", _number_of_synchronized_methods, _number_of_synchronized_methods * 100.0F / _number_of_methods);2927tty->print_cr("%6d profiled methods %6.1f%%", _number_of_profiled_methods, _number_of_profiled_methods * 100.0F / _number_of_methods);2928// parameter size profile2929tty->cr();2930{ int tot = 0;2931int avg = 0;2932for (int i = 0; i < max_parameter_size; i++) {2933int n = _parameter_size_profile[i];2934tot += n;2935avg += n*i;2936tty->print_cr("parameter size = %1d: %6d methods %5.1f%%", i, n, n * 100.0F / _number_of_methods);2937}2938assert(tot == _number_of_methods, "should be the same");2939tty->print_cr(" %6d methods 100.0%%", _number_of_methods);2940tty->print_cr("(average parameter size = %3.1f including receiver, if any)", (float)avg / _number_of_methods);2941}2942// bytecodes profile2943tty->cr();2944{ int tot = 0;2945for (int i = 0; i < Bytecodes::number_of_java_codes; i++) {2946if (Bytecodes::is_defined(i)) {2947Bytecodes::Code c = Bytecodes::cast(i);2948int n = _bytecodes_profile[c];2949tot += n;2950tty->print_cr("%9d %7.3f%% %s", n, n * 100.0F / _number_of_bytecodes, Bytecodes::name(c));2951}2952}2953assert(tot == _number_of_bytecodes, "should be the same");2954tty->print_cr("%9d 100.000%%", _number_of_bytecodes);2955}2956tty->cr();2957}2958};29592960int MethodStatistics::_number_of_methods;2961int MethodStatistics::_number_of_final_methods;2962int MethodStatistics::_number_of_static_methods;2963int MethodStatistics::_number_of_native_methods;2964int MethodStatistics::_number_of_synchronized_methods;2965int MethodStatistics::_number_of_profiled_methods;2966int MethodStatistics::_number_of_bytecodes;2967int MethodStatistics::_parameter_size_profile[MethodStatistics::max_parameter_size];2968int MethodStatistics::_bytecodes_profile[Bytecodes::number_of_java_codes];296929702971void SystemDictionary::print_method_statistics() {2972MethodStatistics::print();2973}29742975#endif // PRODUCT297629772978