Path: blob/master/src/hotspot/share/classfile/classLoaderData.cpp
40949 views
/*1* Copyright (c) 2012, 2021, 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// A ClassLoaderData identifies the full set of class types that a class25// loader's name resolution strategy produces for a given configuration of the26// class loader.27// Class types in the ClassLoaderData may be defined by from class file binaries28// provided by the class loader, or from other class loader it interacts with29// according to its name resolution strategy.30//31// Class loaders that implement a deterministic name resolution strategy32// (including with respect to their delegation behavior), such as the boot, the33// platform, and the system loaders of the JDK's built-in class loader34// hierarchy, always produce the same linkset for a given configuration.35//36// ClassLoaderData carries information related to a linkset (e.g.,37// metaspace holding its klass definitions).38// The System Dictionary and related data structures (e.g., placeholder table,39// loader constraints table) as well as the runtime representation of classes40// only reference ClassLoaderData.41//42// Instances of java.lang.ClassLoader holds a pointer to a ClassLoaderData that43// that represent the loader's "linking domain" in the JVM.44//45// The bootstrap loader (represented by NULL) also has a ClassLoaderData,46// the singleton class the_null_class_loader_data().4748#include "precompiled.hpp"49#include "classfile/classLoaderData.inline.hpp"50#include "classfile/classLoaderDataGraph.inline.hpp"51#include "classfile/dictionary.hpp"52#include "classfile/javaClasses.hpp"53#include "classfile/moduleEntry.hpp"54#include "classfile/packageEntry.hpp"55#include "classfile/symbolTable.hpp"56#include "classfile/systemDictionary.hpp"57#include "classfile/vmClasses.hpp"58#include "logging/log.hpp"59#include "logging/logStream.hpp"60#include "memory/allocation.inline.hpp"61#include "memory/classLoaderMetaspace.hpp"62#include "memory/metadataFactory.hpp"63#include "memory/metaspace.hpp"64#include "memory/resourceArea.hpp"65#include "memory/universe.hpp"66#include "oops/access.inline.hpp"67#include "oops/klass.inline.hpp"68#include "oops/oop.inline.hpp"69#include "oops/oopHandle.inline.hpp"70#include "oops/weakHandle.inline.hpp"71#include "runtime/arguments.hpp"72#include "runtime/atomic.hpp"73#include "runtime/handles.inline.hpp"74#include "runtime/mutex.hpp"75#include "runtime/safepoint.hpp"76#include "utilities/growableArray.hpp"77#include "utilities/macros.hpp"78#include "utilities/ostream.hpp"7980ClassLoaderData * ClassLoaderData::_the_null_class_loader_data = NULL;8182void ClassLoaderData::init_null_class_loader_data() {83assert(_the_null_class_loader_data == NULL, "cannot initialize twice");84assert(ClassLoaderDataGraph::_head == NULL, "cannot initialize twice");8586_the_null_class_loader_data = new ClassLoaderData(Handle(), false);87ClassLoaderDataGraph::_head = _the_null_class_loader_data;88assert(_the_null_class_loader_data->is_the_null_class_loader_data(), "Must be");8990LogTarget(Trace, class, loader, data) lt;91if (lt.is_enabled()) {92ResourceMark rm;93LogStream ls(lt);94ls.print("create ");95_the_null_class_loader_data->print_value_on(&ls);96ls.cr();97}98}99100// Obtain and set the class loader's name within the ClassLoaderData so101// it will be available for error messages, logging, JFR, etc. The name102// and klass are available after the class_loader oop is no longer alive,103// during unloading.104void ClassLoaderData::initialize_name(Handle class_loader) {105ResourceMark rm;106107// Obtain the class loader's name. If the class loader's name was not108// explicitly set during construction, the CLD's _name field will be null.109oop cl_name = java_lang_ClassLoader::name(class_loader());110if (cl_name != NULL) {111const char* cl_instance_name = java_lang_String::as_utf8_string(cl_name);112113if (cl_instance_name != NULL && cl_instance_name[0] != '\0') {114_name = SymbolTable::new_symbol(cl_instance_name);115}116}117118// Obtain the class loader's name and identity hash. If the class loader's119// name was not explicitly set during construction, the class loader's name and id120// will be set to the qualified class name of the class loader along with its121// identity hash.122// If for some reason the ClassLoader's constructor has not been run, instead of123// leaving the _name_and_id field null, fall back to the external qualified class124// name. Thus CLD's _name_and_id field should never have a null value.125oop cl_name_and_id = java_lang_ClassLoader::nameAndId(class_loader());126const char* cl_instance_name_and_id =127(cl_name_and_id == NULL) ? _class_loader_klass->external_name() :128java_lang_String::as_utf8_string(cl_name_and_id);129assert(cl_instance_name_and_id != NULL && cl_instance_name_and_id[0] != '\0', "class loader has no name and id");130_name_and_id = SymbolTable::new_symbol(cl_instance_name_and_id);131}132133ClassLoaderData::ClassLoaderData(Handle h_class_loader, bool has_class_mirror_holder) :134_metaspace(NULL),135_metaspace_lock(new Mutex(Mutex::leaf+1, "Metaspace allocation lock", true,136Mutex::_safepoint_check_never)),137_unloading(false), _has_class_mirror_holder(has_class_mirror_holder),138_modified_oops(true),139// A non-strong hidden class loader data doesn't have anything to keep140// it from being unloaded during parsing of the non-strong hidden class.141// The null-class-loader should always be kept alive.142_keep_alive((has_class_mirror_holder || h_class_loader.is_null()) ? 1 : 0),143_claim(0),144_handles(),145_klasses(NULL), _packages(NULL), _modules(NULL), _unnamed_module(NULL), _dictionary(NULL),146_jmethod_ids(NULL),147_deallocate_list(NULL),148_next(NULL),149_class_loader_klass(NULL), _name(NULL), _name_and_id(NULL) {150151if (!h_class_loader.is_null()) {152_class_loader = _handles.add(h_class_loader());153_class_loader_klass = h_class_loader->klass();154initialize_name(h_class_loader);155}156157if (!has_class_mirror_holder) {158// The holder is initialized later for non-strong hidden classes,159// and before calling anything that call class_loader().160initialize_holder(h_class_loader);161162// A ClassLoaderData created solely for a non-strong hidden class should never163// have a ModuleEntryTable or PackageEntryTable created for it.164_packages = new PackageEntryTable(PackageEntryTable::_packagetable_entry_size);165if (h_class_loader.is_null()) {166// Create unnamed module for boot loader167_unnamed_module = ModuleEntry::create_boot_unnamed_module(this);168} else {169// Create unnamed module for all other loaders170_unnamed_module = ModuleEntry::create_unnamed_module(this);171}172_dictionary = create_dictionary();173}174175NOT_PRODUCT(_dependency_count = 0); // number of class loader dependencies176177JFR_ONLY(INIT_ID(this);)178}179180ClassLoaderData::ChunkedHandleList::~ChunkedHandleList() {181Chunk* c = _head;182while (c != NULL) {183Chunk* next = c->_next;184delete c;185c = next;186}187}188189OopHandle ClassLoaderData::ChunkedHandleList::add(oop o) {190if (_head == NULL || _head->_size == Chunk::CAPACITY) {191Chunk* next = new Chunk(_head);192Atomic::release_store(&_head, next);193}194oop* handle = &_head->_data[_head->_size];195NativeAccess<IS_DEST_UNINITIALIZED>::oop_store(handle, o);196Atomic::release_store(&_head->_size, _head->_size + 1);197return OopHandle(handle);198}199200int ClassLoaderData::ChunkedHandleList::count() const {201int count = 0;202Chunk* chunk = _head;203while (chunk != NULL) {204count += chunk->_size;205chunk = chunk->_next;206}207return count;208}209210inline void ClassLoaderData::ChunkedHandleList::oops_do_chunk(OopClosure* f, Chunk* c, const juint size) {211for (juint i = 0; i < size; i++) {212if (c->_data[i] != NULL) {213f->do_oop(&c->_data[i]);214}215}216}217218void ClassLoaderData::ChunkedHandleList::oops_do(OopClosure* f) {219Chunk* head = Atomic::load_acquire(&_head);220if (head != NULL) {221// Must be careful when reading size of head222oops_do_chunk(f, head, Atomic::load_acquire(&head->_size));223for (Chunk* c = head->_next; c != NULL; c = c->_next) {224oops_do_chunk(f, c, c->_size);225}226}227}228229class VerifyContainsOopClosure : public OopClosure {230oop _target;231bool _found;232233public:234VerifyContainsOopClosure(oop target) : _target(target), _found(false) {}235236void do_oop(oop* p) {237if (p != NULL && NativeAccess<AS_NO_KEEPALIVE>::oop_load(p) == _target) {238_found = true;239}240}241242void do_oop(narrowOop* p) {243// The ChunkedHandleList should not contain any narrowOop244ShouldNotReachHere();245}246247bool found() const {248return _found;249}250};251252bool ClassLoaderData::ChunkedHandleList::contains(oop p) {253VerifyContainsOopClosure cl(p);254oops_do(&cl);255return cl.found();256}257258#ifndef PRODUCT259bool ClassLoaderData::ChunkedHandleList::owner_of(oop* oop_handle) {260Chunk* chunk = _head;261while (chunk != NULL) {262if (&(chunk->_data[0]) <= oop_handle && oop_handle < &(chunk->_data[chunk->_size])) {263return true;264}265chunk = chunk->_next;266}267return false;268}269#endif // PRODUCT270271void ClassLoaderData::clear_claim(int claim) {272for (;;) {273int old_claim = Atomic::load(&_claim);274if ((old_claim & claim) == 0) {275return;276}277int new_claim = old_claim & ~claim;278if (Atomic::cmpxchg(&_claim, old_claim, new_claim) == old_claim) {279return;280}281}282}283284bool ClassLoaderData::try_claim(int claim) {285for (;;) {286int old_claim = Atomic::load(&_claim);287if ((old_claim & claim) == claim) {288return false;289}290int new_claim = old_claim | claim;291if (Atomic::cmpxchg(&_claim, old_claim, new_claim) == old_claim) {292return true;293}294}295}296297// Non-strong hidden classes have their own ClassLoaderData that is marked to keep alive298// while the class is being parsed, and if the class appears on the module fixup list.299// Due to the uniqueness that no other class shares the hidden class' name or300// ClassLoaderData, no other non-GC thread has knowledge of the hidden class while301// it is being defined, therefore _keep_alive is not volatile or atomic.302void ClassLoaderData::inc_keep_alive() {303if (has_class_mirror_holder()) {304if (!Arguments::is_dumping_archive()) {305assert(_keep_alive > 0, "Invalid keep alive increment count");306}307_keep_alive++;308}309}310311void ClassLoaderData::dec_keep_alive() {312if (has_class_mirror_holder()) {313assert(_keep_alive > 0, "Invalid keep alive decrement count");314_keep_alive--;315}316}317318void ClassLoaderData::oops_do(OopClosure* f, int claim_value, bool clear_mod_oops) {319if (claim_value != ClassLoaderData::_claim_none && !try_claim(claim_value)) {320return;321}322323// Only clear modified_oops after the ClassLoaderData is claimed.324if (clear_mod_oops) {325clear_modified_oops();326}327328_handles.oops_do(f);329}330331void ClassLoaderData::classes_do(KlassClosure* klass_closure) {332// Lock-free access requires load_acquire333for (Klass* k = Atomic::load_acquire(&_klasses); k != NULL; k = k->next_link()) {334klass_closure->do_klass(k);335assert(k != k->next_link(), "no loops!");336}337}338339void ClassLoaderData::classes_do(void f(Klass * const)) {340// Lock-free access requires load_acquire341for (Klass* k = Atomic::load_acquire(&_klasses); k != NULL; k = k->next_link()) {342f(k);343assert(k != k->next_link(), "no loops!");344}345}346347void ClassLoaderData::methods_do(void f(Method*)) {348// Lock-free access requires load_acquire349for (Klass* k = Atomic::load_acquire(&_klasses); k != NULL; k = k->next_link()) {350if (k->is_instance_klass() && InstanceKlass::cast(k)->is_loaded()) {351InstanceKlass::cast(k)->methods_do(f);352}353}354}355356void ClassLoaderData::loaded_classes_do(KlassClosure* klass_closure) {357// Lock-free access requires load_acquire358for (Klass* k = Atomic::load_acquire(&_klasses); k != NULL; k = k->next_link()) {359// Do not filter ArrayKlass oops here...360if (k->is_array_klass() || (k->is_instance_klass() && InstanceKlass::cast(k)->is_loaded())) {361#ifdef ASSERT362oop m = k->java_mirror();363assert(m != NULL, "NULL mirror");364assert(m->is_a(vmClasses::Class_klass()), "invalid mirror");365#endif366klass_closure->do_klass(k);367}368}369}370371void ClassLoaderData::classes_do(void f(InstanceKlass*)) {372// Lock-free access requires load_acquire373for (Klass* k = Atomic::load_acquire(&_klasses); k != NULL; k = k->next_link()) {374if (k->is_instance_klass()) {375f(InstanceKlass::cast(k));376}377assert(k != k->next_link(), "no loops!");378}379}380381void ClassLoaderData::modules_do(void f(ModuleEntry*)) {382assert_locked_or_safepoint(Module_lock);383if (_unnamed_module != NULL) {384f(_unnamed_module);385}386if (_modules != NULL) {387for (int i = 0; i < _modules->table_size(); i++) {388for (ModuleEntry* entry = _modules->bucket(i);389entry != NULL;390entry = entry->next()) {391f(entry);392}393}394}395}396397void ClassLoaderData::packages_do(void f(PackageEntry*)) {398assert_locked_or_safepoint(Module_lock);399if (_packages != NULL) {400for (int i = 0; i < _packages->table_size(); i++) {401for (PackageEntry* entry = _packages->bucket(i);402entry != NULL;403entry = entry->next()) {404f(entry);405}406}407}408}409410void ClassLoaderData::record_dependency(const Klass* k) {411assert(k != NULL, "invariant");412413ClassLoaderData * const from_cld = this;414ClassLoaderData * const to_cld = k->class_loader_data();415416// Do not need to record dependency if the dependency is to a class whose417// class loader data is never freed. (i.e. the dependency's class loader418// is one of the three builtin class loaders and the dependency's class419// loader data has a ClassLoader holder, not a Class holder.)420if (to_cld->is_permanent_class_loader_data()) {421return;422}423424oop to;425if (to_cld->has_class_mirror_holder()) {426// Just return if a non-strong hidden class class is attempting to record a dependency427// to itself. (Note that every non-strong hidden class has its own unique class428// loader data.)429if (to_cld == from_cld) {430return;431}432// Hidden class dependencies are through the mirror.433to = k->java_mirror();434} else {435to = to_cld->class_loader();436oop from = from_cld->class_loader();437438// Just return if this dependency is to a class with the same or a parent439// class_loader.440if (from == to || java_lang_ClassLoader::isAncestor(from, to)) {441return; // this class loader is in the parent list, no need to add it.442}443}444445// It's a dependency we won't find through GC, add it.446if (!_handles.contains(to)) {447NOT_PRODUCT(Atomic::inc(&_dependency_count));448LogTarget(Trace, class, loader, data) lt;449if (lt.is_enabled()) {450ResourceMark rm;451LogStream ls(lt);452ls.print("adding dependency from ");453print_value_on(&ls);454ls.print(" to ");455to_cld->print_value_on(&ls);456ls.cr();457}458Handle dependency(Thread::current(), to);459add_handle(dependency);460// Added a potentially young gen oop to the ClassLoaderData461record_modified_oops();462}463}464465void ClassLoaderData::add_class(Klass* k, bool publicize /* true */) {466{467MutexLocker ml(metaspace_lock(), Mutex::_no_safepoint_check_flag);468Klass* old_value = _klasses;469k->set_next_link(old_value);470// Link the new item into the list, making sure the linked class is stable471// since the list can be walked without a lock472Atomic::release_store(&_klasses, k);473if (k->is_array_klass()) {474ClassLoaderDataGraph::inc_array_classes(1);475} else {476ClassLoaderDataGraph::inc_instance_classes(1);477}478}479480if (publicize) {481LogTarget(Trace, class, loader, data) lt;482if (lt.is_enabled()) {483ResourceMark rm;484LogStream ls(lt);485ls.print("Adding k: " PTR_FORMAT " %s to ", p2i(k), k->external_name());486print_value_on(&ls);487ls.cr();488}489}490}491492void ClassLoaderData::initialize_holder(Handle loader_or_mirror) {493if (loader_or_mirror() != NULL) {494assert(_holder.is_null(), "never replace holders");495_holder = WeakHandle(Universe::vm_weak(), loader_or_mirror);496}497}498499// Remove a klass from the _klasses list for scratch_class during redefinition500// or parsed class in the case of an error.501void ClassLoaderData::remove_class(Klass* scratch_class) {502assert_locked_or_safepoint(ClassLoaderDataGraph_lock);503504// Adjust global class iterator.505ClassLoaderDataGraph::adjust_saved_class(scratch_class);506507Klass* prev = NULL;508for (Klass* k = _klasses; k != NULL; k = k->next_link()) {509if (k == scratch_class) {510if (prev == NULL) {511_klasses = k->next_link();512} else {513Klass* next = k->next_link();514prev->set_next_link(next);515}516517if (k->is_array_klass()) {518ClassLoaderDataGraph::dec_array_classes(1);519} else {520ClassLoaderDataGraph::dec_instance_classes(1);521}522523return;524}525prev = k;526assert(k != k->next_link(), "no loops!");527}528ShouldNotReachHere(); // should have found this class!!529}530531void ClassLoaderData::unload() {532_unloading = true;533534LogTarget(Trace, class, loader, data) lt;535if (lt.is_enabled()) {536ResourceMark rm;537LogStream ls(lt);538ls.print("unload");539print_value_on(&ls);540ls.cr();541}542543// Some items on the _deallocate_list need to free their C heap structures544// if they are not already on the _klasses list.545free_deallocate_list_C_heap_structures();546547// Clean up class dependencies and tell serviceability tools548// these classes are unloading. Must be called549// after erroneous classes are released.550classes_do(InstanceKlass::unload_class);551552// Clean up global class iterator for compiler553ClassLoaderDataGraph::adjust_saved_class(this);554}555556ModuleEntryTable* ClassLoaderData::modules() {557// Lazily create the module entry table at first request.558// Lock-free access requires load_acquire.559ModuleEntryTable* modules = Atomic::load_acquire(&_modules);560if (modules == NULL) {561MutexLocker m1(Module_lock);562// Check if _modules got allocated while we were waiting for this lock.563if ((modules = _modules) == NULL) {564modules = new ModuleEntryTable(ModuleEntryTable::_moduletable_entry_size);565566{567MutexLocker m1(metaspace_lock(), Mutex::_no_safepoint_check_flag);568// Ensure _modules is stable, since it is examined without a lock569Atomic::release_store(&_modules, modules);570}571}572}573return modules;574}575576const int _boot_loader_dictionary_size = 1009;577const int _default_loader_dictionary_size = 107;578579Dictionary* ClassLoaderData::create_dictionary() {580assert(!has_class_mirror_holder(), "class mirror holder cld does not have a dictionary");581int size;582bool resizable = false;583if (_the_null_class_loader_data == NULL) {584size = _boot_loader_dictionary_size;585resizable = true;586} else if (class_loader()->is_a(vmClasses::reflect_DelegatingClassLoader_klass())) {587size = 1; // there's only one class in relection class loader and no initiated classes588} else if (is_system_class_loader_data()) {589size = _boot_loader_dictionary_size;590resizable = true;591} else {592size = _default_loader_dictionary_size;593resizable = true;594}595if (!DynamicallyResizeSystemDictionaries || DumpSharedSpaces) {596resizable = false;597}598return new Dictionary(this, size, resizable);599}600601// Tell the GC to keep this klass alive while iterating ClassLoaderDataGraph602oop ClassLoaderData::holder_phantom() const {603// A klass that was previously considered dead can be looked up in the604// CLD/SD, and its _java_mirror or _class_loader can be stored in a root605// or a reachable object making it alive again. The SATB part of G1 needs606// to get notified about this potential resurrection, otherwise the marking607// might not find the object.608if (!_holder.is_null()) { // NULL class_loader609return _holder.resolve();610} else {611return NULL;612}613}614615// Let the GC read the holder without keeping it alive.616oop ClassLoaderData::holder_no_keepalive() const {617if (!_holder.is_null()) { // NULL class_loader618return _holder.peek();619} else {620return NULL;621}622}623624// Unloading support625bool ClassLoaderData::is_alive() const {626bool alive = keep_alive() // null class loader and incomplete non-strong hidden class.627|| (_holder.peek() != NULL); // and not cleaned by the GC weak handle processing.628629return alive;630}631632class ReleaseKlassClosure: public KlassClosure {633private:634size_t _instance_class_released;635size_t _array_class_released;636public:637ReleaseKlassClosure() : _instance_class_released(0), _array_class_released(0) { }638639size_t instance_class_released() const { return _instance_class_released; }640size_t array_class_released() const { return _array_class_released; }641642void do_klass(Klass* k) {643if (k->is_array_klass()) {644_array_class_released ++;645} else {646assert(k->is_instance_klass(), "Must be");647_instance_class_released ++;648}649k->release_C_heap_structures();650}651};652653ClassLoaderData::~ClassLoaderData() {654// Release C heap structures for all the classes.655ReleaseKlassClosure cl;656classes_do(&cl);657658ClassLoaderDataGraph::dec_array_classes(cl.array_class_released());659ClassLoaderDataGraph::dec_instance_classes(cl.instance_class_released());660661// Release the WeakHandle662_holder.release(Universe::vm_weak());663664// Release C heap allocated hashtable for all the packages.665if (_packages != NULL) {666// Destroy the table itself667delete _packages;668_packages = NULL;669}670671// Release C heap allocated hashtable for all the modules.672if (_modules != NULL) {673// Destroy the table itself674delete _modules;675_modules = NULL;676}677678// Release C heap allocated hashtable for the dictionary679if (_dictionary != NULL) {680// Destroy the table itself681delete _dictionary;682_dictionary = NULL;683}684685if (_unnamed_module != NULL) {686_unnamed_module->delete_unnamed_module();687_unnamed_module = NULL;688}689690// release the metaspace691ClassLoaderMetaspace *m = _metaspace;692if (m != NULL) {693_metaspace = NULL;694delete m;695}696// Clear all the JNI handles for methods697// These aren't deallocated and are going to look like a leak, but that's698// needed because we can't really get rid of jmethodIDs because we don't699// know when native code is going to stop using them. The spec says that700// they're "invalid" but existing programs likely rely on their being701// NULL after class unloading.702if (_jmethod_ids != NULL) {703Method::clear_jmethod_ids(this);704}705// Delete lock706delete _metaspace_lock;707708// Delete free list709if (_deallocate_list != NULL) {710delete _deallocate_list;711}712713// Decrement refcounts of Symbols if created.714if (_name != NULL) {715_name->decrement_refcount();716}717if (_name_and_id != NULL) {718_name_and_id->decrement_refcount();719}720}721722// Returns true if this class loader data is for the app class loader723// or a user defined system class loader. (Note that the class loader724// data may have a Class holder.)725bool ClassLoaderData::is_system_class_loader_data() const {726return SystemDictionary::is_system_class_loader(class_loader());727}728729// Returns true if this class loader data is for the platform class loader.730// (Note that the class loader data may have a Class holder.)731bool ClassLoaderData::is_platform_class_loader_data() const {732return SystemDictionary::is_platform_class_loader(class_loader());733}734735// Returns true if the class loader for this class loader data is one of736// the 3 builtin (boot application/system or platform) class loaders,737// including a user-defined system class loader. Note that if the class738// loader data is for a non-strong hidden class then it may739// get freed by a GC even if its class loader is one of these loaders.740bool ClassLoaderData::is_builtin_class_loader_data() const {741return (is_boot_class_loader_data() ||742SystemDictionary::is_system_class_loader(class_loader()) ||743SystemDictionary::is_platform_class_loader(class_loader()));744}745746// Returns true if this class loader data is a class loader data747// that is not ever freed by a GC. It must be the CLD for one of the builtin748// class loaders and not the CLD for a non-strong hidden class.749bool ClassLoaderData::is_permanent_class_loader_data() const {750return is_builtin_class_loader_data() && !has_class_mirror_holder();751}752753ClassLoaderMetaspace* ClassLoaderData::metaspace_non_null() {754// If the metaspace has not been allocated, create a new one. Might want755// to create smaller arena for Reflection class loaders also.756// The reason for the delayed allocation is because some class loaders are757// simply for delegating with no metadata of their own.758// Lock-free access requires load_acquire.759ClassLoaderMetaspace* metaspace = Atomic::load_acquire(&_metaspace);760if (metaspace == NULL) {761MutexLocker ml(_metaspace_lock, Mutex::_no_safepoint_check_flag);762// Check if _metaspace got allocated while we were waiting for this lock.763if ((metaspace = _metaspace) == NULL) {764if (this == the_null_class_loader_data()) {765assert (class_loader() == NULL, "Must be");766metaspace = new ClassLoaderMetaspace(_metaspace_lock, Metaspace::BootMetaspaceType);767} else if (has_class_mirror_holder()) {768metaspace = new ClassLoaderMetaspace(_metaspace_lock, Metaspace::ClassMirrorHolderMetaspaceType);769} else if (class_loader()->is_a(vmClasses::reflect_DelegatingClassLoader_klass())) {770metaspace = new ClassLoaderMetaspace(_metaspace_lock, Metaspace::ReflectionMetaspaceType);771} else {772metaspace = new ClassLoaderMetaspace(_metaspace_lock, Metaspace::StandardMetaspaceType);773}774// Ensure _metaspace is stable, since it is examined without a lock775Atomic::release_store(&_metaspace, metaspace);776}777}778return metaspace;779}780781OopHandle ClassLoaderData::add_handle(Handle h) {782MutexLocker ml(metaspace_lock(), Mutex::_no_safepoint_check_flag);783record_modified_oops();784return _handles.add(h());785}786787void ClassLoaderData::remove_handle(OopHandle h) {788assert(!is_unloading(), "Do not remove a handle for a CLD that is unloading");789oop* ptr = h.ptr_raw();790if (ptr != NULL) {791assert(_handles.owner_of(ptr), "Got unexpected handle " PTR_FORMAT, p2i(ptr));792NativeAccess<>::oop_store(ptr, oop(NULL));793}794}795796void ClassLoaderData::init_handle_locked(OopHandle& dest, Handle h) {797MutexLocker ml(metaspace_lock(), Mutex::_no_safepoint_check_flag);798if (dest.resolve() != NULL) {799return;800} else {801dest = _handles.add(h());802}803}804805// Add this metadata pointer to be freed when it's safe. This is only during806// a safepoint which checks if handles point to this metadata field.807void ClassLoaderData::add_to_deallocate_list(Metadata* m) {808// Metadata in shared region isn't deleted.809if (!m->is_shared()) {810MutexLocker ml(metaspace_lock(), Mutex::_no_safepoint_check_flag);811if (_deallocate_list == NULL) {812_deallocate_list = new (ResourceObj::C_HEAP, mtClass) GrowableArray<Metadata*>(100, mtClass);813}814_deallocate_list->append_if_missing(m);815log_debug(class, loader, data)("deallocate added for %s", m->print_value_string());816ClassLoaderDataGraph::set_should_clean_deallocate_lists();817}818}819820// Deallocate free metadata on the free list. How useful the PermGen was!821void ClassLoaderData::free_deallocate_list() {822// This must be called at a safepoint because it depends on metadata walking at823// safepoint cleanup time.824assert(SafepointSynchronize::is_at_safepoint(), "only called at safepoint");825assert(!is_unloading(), "only called for ClassLoaderData that are not unloading");826if (_deallocate_list == NULL) {827return;828}829// Go backwards because this removes entries that are freed.830for (int i = _deallocate_list->length() - 1; i >= 0; i--) {831Metadata* m = _deallocate_list->at(i);832if (!m->on_stack()) {833_deallocate_list->remove_at(i);834// There are only three types of metadata that we deallocate directly.835// Cast them so they can be used by the template function.836if (m->is_method()) {837MetadataFactory::free_metadata(this, (Method*)m);838} else if (m->is_constantPool()) {839MetadataFactory::free_metadata(this, (ConstantPool*)m);840} else if (m->is_klass()) {841MetadataFactory::free_metadata(this, (InstanceKlass*)m);842} else {843ShouldNotReachHere();844}845} else {846// Metadata is alive.847// If scratch_class is on stack then it shouldn't be on this list!848assert(!m->is_klass() || !((InstanceKlass*)m)->is_scratch_class(),849"scratch classes on this list should be dead");850// Also should assert that other metadata on the list was found in handles.851// Some cleaning remains.852ClassLoaderDataGraph::set_should_clean_deallocate_lists();853}854}855}856857// This is distinct from free_deallocate_list. For class loader data that are858// unloading, this frees the C heap memory for items on the list, and unlinks859// scratch or error classes so that unloading events aren't triggered for these860// classes. The metadata is removed with the unloading metaspace.861// There isn't C heap memory allocated for methods, so nothing is done for them.862void ClassLoaderData::free_deallocate_list_C_heap_structures() {863assert_locked_or_safepoint(ClassLoaderDataGraph_lock);864assert(is_unloading(), "only called for ClassLoaderData that are unloading");865if (_deallocate_list == NULL) {866return;867}868// Go backwards because this removes entries that are freed.869for (int i = _deallocate_list->length() - 1; i >= 0; i--) {870Metadata* m = _deallocate_list->at(i);871_deallocate_list->remove_at(i);872if (m->is_constantPool()) {873((ConstantPool*)m)->release_C_heap_structures();874} else if (m->is_klass()) {875InstanceKlass* ik = (InstanceKlass*)m;876// also releases ik->constants() C heap memory877ik->release_C_heap_structures();878// Remove the class so unloading events aren't triggered for879// this class (scratch or error class) in do_unloading().880remove_class(ik);881}882}883}884885// Caller needs ResourceMark886// If the class loader's _name has not been explicitly set, the class loader's887// qualified class name is returned.888const char* ClassLoaderData::loader_name() const {889if (_class_loader_klass == NULL) {890return BOOTSTRAP_LOADER_NAME;891} else if (_name != NULL) {892return _name->as_C_string();893} else {894return _class_loader_klass->external_name();895}896}897898// Caller needs ResourceMark899// Format of the _name_and_id is as follows:900// If the defining loader has a name explicitly set then '<loader-name>' @<id>901// If the defining loader has no name then <qualified-class-name> @<id>902// If built-in loader, then omit '@<id>' as there is only one instance.903const char* ClassLoaderData::loader_name_and_id() const {904if (_class_loader_klass == NULL) {905return "'" BOOTSTRAP_LOADER_NAME "'";906} else if (_name_and_id != NULL) {907return _name_and_id->as_C_string();908} else {909// May be called in a race before _name_and_id is initialized.910return _class_loader_klass->external_name();911}912}913914void ClassLoaderData::print_value_on(outputStream* out) const {915if (!is_unloading() && class_loader() != NULL) {916out->print("loader data: " INTPTR_FORMAT " for instance ", p2i(this));917class_loader()->print_value_on(out); // includes loader_name_and_id() and address of class loader instance918} else {919// loader data: 0xsomeaddr of 'bootstrap'920out->print("loader data: " INTPTR_FORMAT " of %s", p2i(this), loader_name_and_id());921}922if (_has_class_mirror_holder) {923out->print(" has a class holder");924}925}926927void ClassLoaderData::print_value() const { print_value_on(tty); }928929#ifndef PRODUCT930class PrintKlassClosure: public KlassClosure {931outputStream* _out;932public:933PrintKlassClosure(outputStream* out): _out(out) { }934935void do_klass(Klass* k) {936ResourceMark rm;937_out->print("%s,", k->external_name());938}939};940941void ClassLoaderData::print_on(outputStream* out) const {942ResourceMark rm;943out->print_cr("ClassLoaderData(" INTPTR_FORMAT ")", p2i(this));944out->print_cr(" - name %s", loader_name_and_id());945if (!_holder.is_null()) {946out->print (" - holder ");947_holder.print_on(out);948out->print_cr("");949}950out->print_cr(" - class loader " INTPTR_FORMAT, p2i(_class_loader.ptr_raw()));951out->print_cr(" - metaspace " INTPTR_FORMAT, p2i(_metaspace));952out->print_cr(" - unloading %s", _unloading ? "true" : "false");953out->print_cr(" - class mirror holder %s", _has_class_mirror_holder ? "true" : "false");954out->print_cr(" - modified oops %s", _modified_oops ? "true" : "false");955out->print_cr(" - keep alive %d", _keep_alive);956out->print (" - claim ");957switch(_claim) {958case _claim_none: out->print_cr("none"); break;959case _claim_finalizable:out->print_cr("finalizable"); break;960case _claim_strong: out->print_cr("strong"); break;961case _claim_other: out->print_cr("other"); break;962default: ShouldNotReachHere();963}964out->print_cr(" - handles %d", _handles.count());965out->print_cr(" - dependency count %d", _dependency_count);966out->print (" - klasses {");967PrintKlassClosure closure(out);968((ClassLoaderData*)this)->classes_do(&closure);969out->print_cr(" }");970out->print_cr(" - packages " INTPTR_FORMAT, p2i(_packages));971out->print_cr(" - module " INTPTR_FORMAT, p2i(_modules));972out->print_cr(" - unnamed module " INTPTR_FORMAT, p2i(_unnamed_module));973out->print_cr(" - dictionary " INTPTR_FORMAT, p2i(_dictionary));974if (_jmethod_ids != NULL) {975out->print (" - jmethod count ");976Method::print_jmethod_ids_count(this, out);977out->print_cr("");978}979out->print_cr(" - deallocate list " INTPTR_FORMAT, p2i(_deallocate_list));980out->print_cr(" - next CLD " INTPTR_FORMAT, p2i(_next));981}982#endif // PRODUCT983984void ClassLoaderData::print() const { print_on(tty); }985986void ClassLoaderData::verify() {987assert_locked_or_safepoint(_metaspace_lock);988oop cl = class_loader();989990guarantee(this == class_loader_data(cl) || has_class_mirror_holder(), "Must be the same");991guarantee(cl != NULL || this == ClassLoaderData::the_null_class_loader_data() || has_class_mirror_holder(), "must be");992993// Verify the integrity of the allocated space.994#ifdef ASSERT995if (metaspace_or_null() != NULL) {996metaspace_or_null()->verify();997}998#endif9991000for (Klass* k = _klasses; k != NULL; k = k->next_link()) {1001guarantee(k->class_loader_data() == this, "Must be the same");1002k->verify();1003assert(k != k->next_link(), "no loops!");1004}1005}10061007bool ClassLoaderData::contains_klass(Klass* klass) {1008// Lock-free access requires load_acquire1009for (Klass* k = Atomic::load_acquire(&_klasses); k != NULL; k = k->next_link()) {1010if (k == klass) return true;1011}1012return false;1013}101410151016