Path: blob/master/src/hotspot/share/classfile/classLoaderData.cpp
64440 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/systemDictionaryShared.hpp"58#include "classfile/vmClasses.hpp"59#include "logging/log.hpp"60#include "logging/logStream.hpp"61#include "memory/allocation.inline.hpp"62#include "memory/classLoaderMetaspace.hpp"63#include "memory/metadataFactory.hpp"64#include "memory/metaspace.hpp"65#include "memory/resourceArea.hpp"66#include "memory/universe.hpp"67#include "oops/access.inline.hpp"68#include "oops/klass.inline.hpp"69#include "oops/oop.inline.hpp"70#include "oops/oopHandle.inline.hpp"71#include "oops/weakHandle.inline.hpp"72#include "runtime/arguments.hpp"73#include "runtime/atomic.hpp"74#include "runtime/handles.inline.hpp"75#include "runtime/mutex.hpp"76#include "runtime/safepoint.hpp"77#include "utilities/growableArray.hpp"78#include "utilities/macros.hpp"79#include "utilities/ostream.hpp"8081ClassLoaderData * ClassLoaderData::_the_null_class_loader_data = NULL;8283void ClassLoaderData::init_null_class_loader_data() {84assert(_the_null_class_loader_data == NULL, "cannot initialize twice");85assert(ClassLoaderDataGraph::_head == NULL, "cannot initialize twice");8687_the_null_class_loader_data = new ClassLoaderData(Handle(), false);88ClassLoaderDataGraph::_head = _the_null_class_loader_data;89assert(_the_null_class_loader_data->is_the_null_class_loader_data(), "Must be");9091LogTarget(Trace, class, loader, data) lt;92if (lt.is_enabled()) {93ResourceMark rm;94LogStream ls(lt);95ls.print("create ");96_the_null_class_loader_data->print_value_on(&ls);97ls.cr();98}99}100101// Obtain and set the class loader's name within the ClassLoaderData so102// it will be available for error messages, logging, JFR, etc. The name103// and klass are available after the class_loader oop is no longer alive,104// during unloading.105void ClassLoaderData::initialize_name(Handle class_loader) {106ResourceMark rm;107108// Obtain the class loader's name. If the class loader's name was not109// explicitly set during construction, the CLD's _name field will be null.110oop cl_name = java_lang_ClassLoader::name(class_loader());111if (cl_name != NULL) {112const char* cl_instance_name = java_lang_String::as_utf8_string(cl_name);113114if (cl_instance_name != NULL && cl_instance_name[0] != '\0') {115_name = SymbolTable::new_symbol(cl_instance_name);116}117}118119// Obtain the class loader's name and identity hash. If the class loader's120// name was not explicitly set during construction, the class loader's name and id121// will be set to the qualified class name of the class loader along with its122// identity hash.123// If for some reason the ClassLoader's constructor has not been run, instead of124// leaving the _name_and_id field null, fall back to the external qualified class125// name. Thus CLD's _name_and_id field should never have a null value.126oop cl_name_and_id = java_lang_ClassLoader::nameAndId(class_loader());127const char* cl_instance_name_and_id =128(cl_name_and_id == NULL) ? _class_loader_klass->external_name() :129java_lang_String::as_utf8_string(cl_name_and_id);130assert(cl_instance_name_and_id != NULL && cl_instance_name_and_id[0] != '\0', "class loader has no name and id");131_name_and_id = SymbolTable::new_symbol(cl_instance_name_and_id);132}133134ClassLoaderData::ClassLoaderData(Handle h_class_loader, bool has_class_mirror_holder) :135_metaspace(NULL),136_metaspace_lock(new Mutex(Mutex::leaf+1, "Metaspace allocation lock", true,137Mutex::_safepoint_check_never)),138_unloading(false), _has_class_mirror_holder(has_class_mirror_holder),139_modified_oops(true),140// A non-strong hidden class loader data doesn't have anything to keep141// it from being unloaded during parsing of the non-strong hidden class.142// The null-class-loader should always be kept alive.143_keep_alive((has_class_mirror_holder || h_class_loader.is_null()) ? 1 : 0),144_claim(0),145_handles(),146_klasses(NULL), _packages(NULL), _modules(NULL), _unnamed_module(NULL), _dictionary(NULL),147_jmethod_ids(NULL),148_deallocate_list(NULL),149_next(NULL),150_class_loader_klass(NULL), _name(NULL), _name_and_id(NULL) {151152if (!h_class_loader.is_null()) {153_class_loader = _handles.add(h_class_loader());154_class_loader_klass = h_class_loader->klass();155initialize_name(h_class_loader);156}157158if (!has_class_mirror_holder) {159// The holder is initialized later for non-strong hidden classes,160// and before calling anything that call class_loader().161initialize_holder(h_class_loader);162163// A ClassLoaderData created solely for a non-strong hidden class should never164// have a ModuleEntryTable or PackageEntryTable created for it.165_packages = new PackageEntryTable(PackageEntryTable::_packagetable_entry_size);166if (h_class_loader.is_null()) {167// Create unnamed module for boot loader168_unnamed_module = ModuleEntry::create_boot_unnamed_module(this);169} else {170// Create unnamed module for all other loaders171_unnamed_module = ModuleEntry::create_unnamed_module(this);172}173_dictionary = create_dictionary();174}175176NOT_PRODUCT(_dependency_count = 0); // number of class loader dependencies177178JFR_ONLY(INIT_ID(this);)179}180181ClassLoaderData::ChunkedHandleList::~ChunkedHandleList() {182Chunk* c = _head;183while (c != NULL) {184Chunk* next = c->_next;185delete c;186c = next;187}188}189190OopHandle ClassLoaderData::ChunkedHandleList::add(oop o) {191if (_head == NULL || _head->_size == Chunk::CAPACITY) {192Chunk* next = new Chunk(_head);193Atomic::release_store(&_head, next);194}195oop* handle = &_head->_data[_head->_size];196NativeAccess<IS_DEST_UNINITIALIZED>::oop_store(handle, o);197Atomic::release_store(&_head->_size, _head->_size + 1);198return OopHandle(handle);199}200201int ClassLoaderData::ChunkedHandleList::count() const {202int count = 0;203Chunk* chunk = _head;204while (chunk != NULL) {205count += chunk->_size;206chunk = chunk->_next;207}208return count;209}210211inline void ClassLoaderData::ChunkedHandleList::oops_do_chunk(OopClosure* f, Chunk* c, const juint size) {212for (juint i = 0; i < size; i++) {213if (c->_data[i] != NULL) {214f->do_oop(&c->_data[i]);215}216}217}218219void ClassLoaderData::ChunkedHandleList::oops_do(OopClosure* f) {220Chunk* head = Atomic::load_acquire(&_head);221if (head != NULL) {222// Must be careful when reading size of head223oops_do_chunk(f, head, Atomic::load_acquire(&head->_size));224for (Chunk* c = head->_next; c != NULL; c = c->_next) {225oops_do_chunk(f, c, c->_size);226}227}228}229230class VerifyContainsOopClosure : public OopClosure {231oop _target;232bool _found;233234public:235VerifyContainsOopClosure(oop target) : _target(target), _found(false) {}236237void do_oop(oop* p) {238if (p != NULL && NativeAccess<AS_NO_KEEPALIVE>::oop_load(p) == _target) {239_found = true;240}241}242243void do_oop(narrowOop* p) {244// The ChunkedHandleList should not contain any narrowOop245ShouldNotReachHere();246}247248bool found() const {249return _found;250}251};252253bool ClassLoaderData::ChunkedHandleList::contains(oop p) {254VerifyContainsOopClosure cl(p);255oops_do(&cl);256return cl.found();257}258259#ifndef PRODUCT260bool ClassLoaderData::ChunkedHandleList::owner_of(oop* oop_handle) {261Chunk* chunk = _head;262while (chunk != NULL) {263if (&(chunk->_data[0]) <= oop_handle && oop_handle < &(chunk->_data[chunk->_size])) {264return true;265}266chunk = chunk->_next;267}268return false;269}270#endif // PRODUCT271272void ClassLoaderData::clear_claim(int claim) {273for (;;) {274int old_claim = Atomic::load(&_claim);275if ((old_claim & claim) == 0) {276return;277}278int new_claim = old_claim & ~claim;279if (Atomic::cmpxchg(&_claim, old_claim, new_claim) == old_claim) {280return;281}282}283}284285bool ClassLoaderData::try_claim(int claim) {286for (;;) {287int old_claim = Atomic::load(&_claim);288if ((old_claim & claim) == claim) {289return false;290}291int new_claim = old_claim | claim;292if (Atomic::cmpxchg(&_claim, old_claim, new_claim) == old_claim) {293return true;294}295}296}297298// Non-strong hidden classes have their own ClassLoaderData that is marked to keep alive299// while the class is being parsed, and if the class appears on the module fixup list.300// Due to the uniqueness that no other class shares the hidden class' name or301// ClassLoaderData, no other non-GC thread has knowledge of the hidden class while302// it is being defined, therefore _keep_alive is not volatile or atomic.303void ClassLoaderData::inc_keep_alive() {304if (has_class_mirror_holder()) {305assert(_keep_alive > 0, "Invalid keep alive increment count");306_keep_alive++;307}308}309310void ClassLoaderData::dec_keep_alive() {311if (has_class_mirror_holder()) {312assert(_keep_alive > 0, "Invalid keep alive decrement count");313_keep_alive--;314}315}316317void ClassLoaderData::oops_do(OopClosure* f, int claim_value, bool clear_mod_oops) {318if (claim_value != ClassLoaderData::_claim_none && !try_claim(claim_value)) {319return;320}321322// Only clear modified_oops after the ClassLoaderData is claimed.323if (clear_mod_oops) {324clear_modified_oops();325}326327_handles.oops_do(f);328}329330void ClassLoaderData::classes_do(KlassClosure* klass_closure) {331// Lock-free access requires load_acquire332for (Klass* k = Atomic::load_acquire(&_klasses); k != NULL; k = k->next_link()) {333klass_closure->do_klass(k);334assert(k != k->next_link(), "no loops!");335}336}337338void ClassLoaderData::classes_do(void f(Klass * const)) {339// Lock-free access requires load_acquire340for (Klass* k = Atomic::load_acquire(&_klasses); k != NULL; k = k->next_link()) {341f(k);342assert(k != k->next_link(), "no loops!");343}344}345346void ClassLoaderData::methods_do(void f(Method*)) {347// Lock-free access requires load_acquire348for (Klass* k = Atomic::load_acquire(&_klasses); k != NULL; k = k->next_link()) {349if (k->is_instance_klass() && InstanceKlass::cast(k)->is_loaded()) {350InstanceKlass::cast(k)->methods_do(f);351}352}353}354355void ClassLoaderData::loaded_classes_do(KlassClosure* klass_closure) {356// To call this, one must have the MultiArray_lock held, but the _klasses list still has lock free reads.357assert_locked_or_safepoint(MultiArray_lock);358359// Lock-free access requires load_acquire360for (Klass* k = Atomic::load_acquire(&_klasses); k != NULL; k = k->next_link()) {361// Do not filter ArrayKlass oops here...362if (k->is_array_klass() || (k->is_instance_klass() && InstanceKlass::cast(k)->is_loaded())) {363#ifdef ASSERT364oop m = k->java_mirror();365assert(m != NULL, "NULL mirror");366assert(m->is_a(vmClasses::Class_klass()), "invalid mirror");367#endif368klass_closure->do_klass(k);369}370}371}372373void ClassLoaderData::classes_do(void f(InstanceKlass*)) {374// Lock-free access requires load_acquire375for (Klass* k = Atomic::load_acquire(&_klasses); k != NULL; k = k->next_link()) {376if (k->is_instance_klass()) {377f(InstanceKlass::cast(k));378}379assert(k != k->next_link(), "no loops!");380}381}382383void ClassLoaderData::modules_do(void f(ModuleEntry*)) {384assert_locked_or_safepoint(Module_lock);385if (_unnamed_module != NULL) {386f(_unnamed_module);387}388if (_modules != NULL) {389for (int i = 0; i < _modules->table_size(); i++) {390for (ModuleEntry* entry = _modules->bucket(i);391entry != NULL;392entry = entry->next()) {393f(entry);394}395}396}397}398399void ClassLoaderData::packages_do(void f(PackageEntry*)) {400assert_locked_or_safepoint(Module_lock);401if (_packages != NULL) {402for (int i = 0; i < _packages->table_size(); i++) {403for (PackageEntry* entry = _packages->bucket(i);404entry != NULL;405entry = entry->next()) {406f(entry);407}408}409}410}411412void ClassLoaderData::record_dependency(const Klass* k) {413assert(k != NULL, "invariant");414415ClassLoaderData * const from_cld = this;416ClassLoaderData * const to_cld = k->class_loader_data();417418// Do not need to record dependency if the dependency is to a class whose419// class loader data is never freed. (i.e. the dependency's class loader420// is one of the three builtin class loaders and the dependency's class421// loader data has a ClassLoader holder, not a Class holder.)422if (to_cld->is_permanent_class_loader_data()) {423return;424}425426oop to;427if (to_cld->has_class_mirror_holder()) {428// Just return if a non-strong hidden class class is attempting to record a dependency429// to itself. (Note that every non-strong hidden class has its own unique class430// loader data.)431if (to_cld == from_cld) {432return;433}434// Hidden class dependencies are through the mirror.435to = k->java_mirror();436} else {437to = to_cld->class_loader();438oop from = from_cld->class_loader();439440// Just return if this dependency is to a class with the same or a parent441// class_loader.442if (from == to || java_lang_ClassLoader::isAncestor(from, to)) {443return; // this class loader is in the parent list, no need to add it.444}445}446447// It's a dependency we won't find through GC, add it.448if (!_handles.contains(to)) {449NOT_PRODUCT(Atomic::inc(&_dependency_count));450LogTarget(Trace, class, loader, data) lt;451if (lt.is_enabled()) {452ResourceMark rm;453LogStream ls(lt);454ls.print("adding dependency from ");455print_value_on(&ls);456ls.print(" to ");457to_cld->print_value_on(&ls);458ls.cr();459}460Handle dependency(Thread::current(), to);461add_handle(dependency);462// Added a potentially young gen oop to the ClassLoaderData463record_modified_oops();464}465}466467void ClassLoaderData::add_class(Klass* k, bool publicize /* true */) {468{469MutexLocker ml(metaspace_lock(), Mutex::_no_safepoint_check_flag);470Klass* old_value = _klasses;471k->set_next_link(old_value);472// Link the new item into the list, making sure the linked class is stable473// since the list can be walked without a lock474Atomic::release_store(&_klasses, k);475if (k->is_array_klass()) {476ClassLoaderDataGraph::inc_array_classes(1);477} else {478ClassLoaderDataGraph::inc_instance_classes(1);479}480}481482if (publicize) {483LogTarget(Trace, class, loader, data) lt;484if (lt.is_enabled()) {485ResourceMark rm;486LogStream ls(lt);487ls.print("Adding k: " PTR_FORMAT " %s to ", p2i(k), k->external_name());488print_value_on(&ls);489ls.cr();490}491}492}493494void ClassLoaderData::initialize_holder(Handle loader_or_mirror) {495if (loader_or_mirror() != NULL) {496assert(_holder.is_null(), "never replace holders");497_holder = WeakHandle(Universe::vm_weak(), loader_or_mirror);498}499}500501// Remove a klass from the _klasses list for scratch_class during redefinition502// or parsed class in the case of an error.503void ClassLoaderData::remove_class(Klass* scratch_class) {504assert_locked_or_safepoint(ClassLoaderDataGraph_lock);505506// Adjust global class iterator.507ClassLoaderDataGraph::adjust_saved_class(scratch_class);508509Klass* prev = NULL;510for (Klass* k = _klasses; k != NULL; k = k->next_link()) {511if (k == scratch_class) {512if (prev == NULL) {513_klasses = k->next_link();514} else {515Klass* next = k->next_link();516prev->set_next_link(next);517}518519if (k->is_array_klass()) {520ClassLoaderDataGraph::dec_array_classes(1);521} else {522ClassLoaderDataGraph::dec_instance_classes(1);523}524525return;526}527prev = k;528assert(k != k->next_link(), "no loops!");529}530ShouldNotReachHere(); // should have found this class!!531}532533void ClassLoaderData::unload() {534_unloading = true;535536LogTarget(Trace, class, loader, data) lt;537if (lt.is_enabled()) {538ResourceMark rm;539LogStream ls(lt);540ls.print("unload");541print_value_on(&ls);542ls.cr();543}544545// Some items on the _deallocate_list need to free their C heap structures546// if they are not already on the _klasses list.547free_deallocate_list_C_heap_structures();548549// Clean up class dependencies and tell serviceability tools550// these classes are unloading. Must be called551// after erroneous classes are released.552classes_do(InstanceKlass::unload_class);553554// Clean up global class iterator for compiler555ClassLoaderDataGraph::adjust_saved_class(this);556}557558ModuleEntryTable* ClassLoaderData::modules() {559// Lazily create the module entry table at first request.560// Lock-free access requires load_acquire.561ModuleEntryTable* modules = Atomic::load_acquire(&_modules);562if (modules == NULL) {563MutexLocker m1(Module_lock);564// Check if _modules got allocated while we were waiting for this lock.565if ((modules = _modules) == NULL) {566modules = new ModuleEntryTable(ModuleEntryTable::_moduletable_entry_size);567568{569MutexLocker m1(metaspace_lock(), Mutex::_no_safepoint_check_flag);570// Ensure _modules is stable, since it is examined without a lock571Atomic::release_store(&_modules, modules);572}573}574}575return modules;576}577578const int _boot_loader_dictionary_size = 1009;579const int _default_loader_dictionary_size = 107;580581Dictionary* ClassLoaderData::create_dictionary() {582assert(!has_class_mirror_holder(), "class mirror holder cld does not have a dictionary");583int size;584bool resizable = false;585if (_the_null_class_loader_data == NULL) {586size = _boot_loader_dictionary_size;587resizable = true;588} else if (class_loader()->is_a(vmClasses::reflect_DelegatingClassLoader_klass())) {589size = 1; // there's only one class in relection class loader and no initiated classes590} else if (is_system_class_loader_data()) {591size = _boot_loader_dictionary_size;592resizable = true;593} else {594size = _default_loader_dictionary_size;595resizable = true;596}597if (!DynamicallyResizeSystemDictionaries || DumpSharedSpaces) {598resizable = false;599}600return new Dictionary(this, size, resizable);601}602603// Tell the GC to keep this klass alive while iterating ClassLoaderDataGraph604oop ClassLoaderData::holder_phantom() const {605// A klass that was previously considered dead can be looked up in the606// CLD/SD, and its _java_mirror or _class_loader can be stored in a root607// or a reachable object making it alive again. The SATB part of G1 needs608// to get notified about this potential resurrection, otherwise the marking609// might not find the object.610if (!_holder.is_null()) { // NULL class_loader611return _holder.resolve();612} else {613return NULL;614}615}616617// Let the GC read the holder without keeping it alive.618oop ClassLoaderData::holder_no_keepalive() const {619if (!_holder.is_null()) { // NULL class_loader620return _holder.peek();621} else {622return NULL;623}624}625626// Unloading support627bool ClassLoaderData::is_alive() const {628bool alive = keep_alive() // null class loader and incomplete non-strong hidden class.629|| (_holder.peek() != NULL); // and not cleaned by the GC weak handle processing.630631return alive;632}633634class ReleaseKlassClosure: public KlassClosure {635private:636size_t _instance_class_released;637size_t _array_class_released;638public:639ReleaseKlassClosure() : _instance_class_released(0), _array_class_released(0) { }640641size_t instance_class_released() const { return _instance_class_released; }642size_t array_class_released() const { return _array_class_released; }643644void do_klass(Klass* k) {645if (k->is_array_klass()) {646_array_class_released ++;647} else {648assert(k->is_instance_klass(), "Must be");649_instance_class_released ++;650}651k->release_C_heap_structures();652}653};654655ClassLoaderData::~ClassLoaderData() {656// Release C heap structures for all the classes.657ReleaseKlassClosure cl;658classes_do(&cl);659660ClassLoaderDataGraph::dec_array_classes(cl.array_class_released());661ClassLoaderDataGraph::dec_instance_classes(cl.instance_class_released());662663// Release the WeakHandle664_holder.release(Universe::vm_weak());665666// Release C heap allocated hashtable for all the packages.667if (_packages != NULL) {668// Destroy the table itself669delete _packages;670_packages = NULL;671}672673// Release C heap allocated hashtable for all the modules.674if (_modules != NULL) {675// Destroy the table itself676delete _modules;677_modules = NULL;678}679680// Release C heap allocated hashtable for the dictionary681if (_dictionary != NULL) {682// Destroy the table itself683delete _dictionary;684_dictionary = NULL;685}686687if (_unnamed_module != NULL) {688_unnamed_module->delete_unnamed_module();689_unnamed_module = NULL;690}691692// release the metaspace693ClassLoaderMetaspace *m = _metaspace;694if (m != NULL) {695_metaspace = NULL;696delete m;697}698// Method::clear_jmethod_ids only sets the jmethod_ids to NULL without699// releasing the memory for related JNIMethodBlocks and JNIMethodBlockNodes.700// This is done intentionally because native code (e.g. JVMTI agent) holding701// jmethod_ids may access them after the associated classes and class loader702// are unloaded. The Java Native Interface Specification says "method ID703// does not prevent the VM from unloading the class from which the ID has704// been derived. After the class is unloaded, the method or field ID becomes705// invalid". In real world usages, the native code may rely on jmethod_ids706// being NULL after class unloading. Hence, it is unsafe to free the memory707// from the VM side without knowing when native code is going to stop using708// them.709if (_jmethod_ids != NULL) {710Method::clear_jmethod_ids(this);711}712// Delete lock713delete _metaspace_lock;714715// Delete free list716if (_deallocate_list != NULL) {717delete _deallocate_list;718}719720// Decrement refcounts of Symbols if created.721if (_name != NULL) {722_name->decrement_refcount();723}724if (_name_and_id != NULL) {725_name_and_id->decrement_refcount();726}727}728729// Returns true if this class loader data is for the app class loader730// or a user defined system class loader. (Note that the class loader731// data may have a Class holder.)732bool ClassLoaderData::is_system_class_loader_data() const {733return SystemDictionary::is_system_class_loader(class_loader());734}735736// Returns true if this class loader data is for the platform class loader.737// (Note that the class loader data may have a Class holder.)738bool ClassLoaderData::is_platform_class_loader_data() const {739return SystemDictionary::is_platform_class_loader(class_loader());740}741742// Returns true if the class loader for this class loader data is one of743// the 3 builtin (boot application/system or platform) class loaders,744// including a user-defined system class loader. Note that if the class745// loader data is for a non-strong hidden class then it may746// get freed by a GC even if its class loader is one of these loaders.747bool ClassLoaderData::is_builtin_class_loader_data() const {748return (is_boot_class_loader_data() ||749SystemDictionary::is_system_class_loader(class_loader()) ||750SystemDictionary::is_platform_class_loader(class_loader()));751}752753// Returns true if this class loader data is a class loader data754// that is not ever freed by a GC. It must be the CLD for one of the builtin755// class loaders and not the CLD for a non-strong hidden class.756bool ClassLoaderData::is_permanent_class_loader_data() const {757return is_builtin_class_loader_data() && !has_class_mirror_holder();758}759760ClassLoaderMetaspace* ClassLoaderData::metaspace_non_null() {761// If the metaspace has not been allocated, create a new one. Might want762// to create smaller arena for Reflection class loaders also.763// The reason for the delayed allocation is because some class loaders are764// simply for delegating with no metadata of their own.765// Lock-free access requires load_acquire.766ClassLoaderMetaspace* metaspace = Atomic::load_acquire(&_metaspace);767if (metaspace == NULL) {768MutexLocker ml(_metaspace_lock, Mutex::_no_safepoint_check_flag);769// Check if _metaspace got allocated while we were waiting for this lock.770if ((metaspace = _metaspace) == NULL) {771if (this == the_null_class_loader_data()) {772assert (class_loader() == NULL, "Must be");773metaspace = new ClassLoaderMetaspace(_metaspace_lock, Metaspace::BootMetaspaceType);774} else if (has_class_mirror_holder()) {775metaspace = new ClassLoaderMetaspace(_metaspace_lock, Metaspace::ClassMirrorHolderMetaspaceType);776} else if (class_loader()->is_a(vmClasses::reflect_DelegatingClassLoader_klass())) {777metaspace = new ClassLoaderMetaspace(_metaspace_lock, Metaspace::ReflectionMetaspaceType);778} else {779metaspace = new ClassLoaderMetaspace(_metaspace_lock, Metaspace::StandardMetaspaceType);780}781// Ensure _metaspace is stable, since it is examined without a lock782Atomic::release_store(&_metaspace, metaspace);783}784}785return metaspace;786}787788OopHandle ClassLoaderData::add_handle(Handle h) {789MutexLocker ml(metaspace_lock(), Mutex::_no_safepoint_check_flag);790record_modified_oops();791return _handles.add(h());792}793794void ClassLoaderData::remove_handle(OopHandle h) {795assert(!is_unloading(), "Do not remove a handle for a CLD that is unloading");796oop* ptr = h.ptr_raw();797if (ptr != NULL) {798assert(_handles.owner_of(ptr), "Got unexpected handle " PTR_FORMAT, p2i(ptr));799NativeAccess<>::oop_store(ptr, oop(NULL));800}801}802803void ClassLoaderData::init_handle_locked(OopHandle& dest, Handle h) {804MutexLocker ml(metaspace_lock(), Mutex::_no_safepoint_check_flag);805if (dest.resolve() != NULL) {806return;807} else {808record_modified_oops();809dest = _handles.add(h());810}811}812813// Add this metadata pointer to be freed when it's safe. This is only during814// a safepoint which checks if handles point to this metadata field.815void ClassLoaderData::add_to_deallocate_list(Metadata* m) {816// Metadata in shared region isn't deleted.817if (!m->is_shared()) {818MutexLocker ml(metaspace_lock(), Mutex::_no_safepoint_check_flag);819if (_deallocate_list == NULL) {820_deallocate_list = new (ResourceObj::C_HEAP, mtClass) GrowableArray<Metadata*>(100, mtClass);821}822_deallocate_list->append_if_missing(m);823log_debug(class, loader, data)("deallocate added for %s", m->print_value_string());824ClassLoaderDataGraph::set_should_clean_deallocate_lists();825}826}827828// Deallocate free metadata on the free list. How useful the PermGen was!829void ClassLoaderData::free_deallocate_list() {830// This must be called at a safepoint because it depends on metadata walking at831// safepoint cleanup time.832assert(SafepointSynchronize::is_at_safepoint(), "only called at safepoint");833assert(!is_unloading(), "only called for ClassLoaderData that are not unloading");834if (_deallocate_list == NULL) {835return;836}837// Go backwards because this removes entries that are freed.838for (int i = _deallocate_list->length() - 1; i >= 0; i--) {839Metadata* m = _deallocate_list->at(i);840if (!m->on_stack()) {841_deallocate_list->remove_at(i);842// There are only three types of metadata that we deallocate directly.843// Cast them so they can be used by the template function.844if (m->is_method()) {845MetadataFactory::free_metadata(this, (Method*)m);846} else if (m->is_constantPool()) {847MetadataFactory::free_metadata(this, (ConstantPool*)m);848} else if (m->is_klass()) {849MetadataFactory::free_metadata(this, (InstanceKlass*)m);850} else {851ShouldNotReachHere();852}853} else {854// Metadata is alive.855// If scratch_class is on stack then it shouldn't be on this list!856assert(!m->is_klass() || !((InstanceKlass*)m)->is_scratch_class(),857"scratch classes on this list should be dead");858// Also should assert that other metadata on the list was found in handles.859// Some cleaning remains.860ClassLoaderDataGraph::set_should_clean_deallocate_lists();861}862}863}864865// This is distinct from free_deallocate_list. For class loader data that are866// unloading, this frees the C heap memory for items on the list, and unlinks867// scratch or error classes so that unloading events aren't triggered for these868// classes. The metadata is removed with the unloading metaspace.869// There isn't C heap memory allocated for methods, so nothing is done for them.870void ClassLoaderData::free_deallocate_list_C_heap_structures() {871assert_locked_or_safepoint(ClassLoaderDataGraph_lock);872assert(is_unloading(), "only called for ClassLoaderData that are unloading");873if (_deallocate_list == NULL) {874return;875}876// Go backwards because this removes entries that are freed.877for (int i = _deallocate_list->length() - 1; i >= 0; i--) {878Metadata* m = _deallocate_list->at(i);879_deallocate_list->remove_at(i);880if (m->is_constantPool()) {881((ConstantPool*)m)->release_C_heap_structures();882} else if (m->is_klass()) {883InstanceKlass* ik = (InstanceKlass*)m;884// also releases ik->constants() C heap memory885ik->release_C_heap_structures();886// Remove the class so unloading events aren't triggered for887// this class (scratch or error class) in do_unloading().888remove_class(ik);889// But still have to remove it from the dumptime_table.890if (Arguments::is_dumping_archive()) {891SystemDictionaryShared::remove_dumptime_info(ik);892}893}894}895}896897// Caller needs ResourceMark898// If the class loader's _name has not been explicitly set, the class loader's899// qualified class name is returned.900const char* ClassLoaderData::loader_name() const {901if (_class_loader_klass == NULL) {902return BOOTSTRAP_LOADER_NAME;903} else if (_name != NULL) {904return _name->as_C_string();905} else {906return _class_loader_klass->external_name();907}908}909910// Caller needs ResourceMark911// Format of the _name_and_id is as follows:912// If the defining loader has a name explicitly set then '<loader-name>' @<id>913// If the defining loader has no name then <qualified-class-name> @<id>914// If built-in loader, then omit '@<id>' as there is only one instance.915const char* ClassLoaderData::loader_name_and_id() const {916if (_class_loader_klass == NULL) {917return "'" BOOTSTRAP_LOADER_NAME "'";918} else if (_name_and_id != NULL) {919return _name_and_id->as_C_string();920} else {921// May be called in a race before _name_and_id is initialized.922return _class_loader_klass->external_name();923}924}925926void ClassLoaderData::print_value_on(outputStream* out) const {927if (!is_unloading() && class_loader() != NULL) {928out->print("loader data: " INTPTR_FORMAT " for instance ", p2i(this));929class_loader()->print_value_on(out); // includes loader_name_and_id() and address of class loader instance930} else {931// loader data: 0xsomeaddr of 'bootstrap'932out->print("loader data: " INTPTR_FORMAT " of %s", p2i(this), loader_name_and_id());933}934if (_has_class_mirror_holder) {935out->print(" has a class holder");936}937}938939void ClassLoaderData::print_value() const { print_value_on(tty); }940941#ifndef PRODUCT942class PrintKlassClosure: public KlassClosure {943outputStream* _out;944public:945PrintKlassClosure(outputStream* out): _out(out) { }946947void do_klass(Klass* k) {948ResourceMark rm;949_out->print("%s,", k->external_name());950}951};952953void ClassLoaderData::print_on(outputStream* out) const {954ResourceMark rm;955out->print_cr("ClassLoaderData(" INTPTR_FORMAT ")", p2i(this));956out->print_cr(" - name %s", loader_name_and_id());957if (!_holder.is_null()) {958out->print (" - holder ");959_holder.print_on(out);960out->print_cr("");961}962out->print_cr(" - class loader " INTPTR_FORMAT, p2i(_class_loader.ptr_raw()));963out->print_cr(" - metaspace " INTPTR_FORMAT, p2i(_metaspace));964out->print_cr(" - unloading %s", _unloading ? "true" : "false");965out->print_cr(" - class mirror holder %s", _has_class_mirror_holder ? "true" : "false");966out->print_cr(" - modified oops %s", _modified_oops ? "true" : "false");967out->print_cr(" - keep alive %d", _keep_alive);968out->print (" - claim ");969switch(_claim) {970case _claim_none: out->print_cr("none"); break;971case _claim_finalizable:out->print_cr("finalizable"); break;972case _claim_strong: out->print_cr("strong"); break;973case _claim_other: out->print_cr("other"); break;974default: ShouldNotReachHere();975}976out->print_cr(" - handles %d", _handles.count());977out->print_cr(" - dependency count %d", _dependency_count);978out->print (" - klasses {");979PrintKlassClosure closure(out);980((ClassLoaderData*)this)->classes_do(&closure);981out->print_cr(" }");982out->print_cr(" - packages " INTPTR_FORMAT, p2i(_packages));983out->print_cr(" - module " INTPTR_FORMAT, p2i(_modules));984out->print_cr(" - unnamed module " INTPTR_FORMAT, p2i(_unnamed_module));985out->print_cr(" - dictionary " INTPTR_FORMAT, p2i(_dictionary));986if (_jmethod_ids != NULL) {987out->print (" - jmethod count ");988Method::print_jmethod_ids_count(this, out);989out->print_cr("");990}991out->print_cr(" - deallocate list " INTPTR_FORMAT, p2i(_deallocate_list));992out->print_cr(" - next CLD " INTPTR_FORMAT, p2i(_next));993}994#endif // PRODUCT995996void ClassLoaderData::print() const { print_on(tty); }997998void ClassLoaderData::verify() {999assert_locked_or_safepoint(_metaspace_lock);1000oop cl = class_loader();10011002guarantee(this == class_loader_data(cl) || has_class_mirror_holder(), "Must be the same");1003guarantee(cl != NULL || this == ClassLoaderData::the_null_class_loader_data() || has_class_mirror_holder(), "must be");10041005// Verify the integrity of the allocated space.1006#ifdef ASSERT1007if (metaspace_or_null() != NULL) {1008metaspace_or_null()->verify();1009}1010#endif10111012for (Klass* k = _klasses; k != NULL; k = k->next_link()) {1013guarantee(k->class_loader_data() == this, "Must be the same");1014k->verify();1015assert(k != k->next_link(), "no loops!");1016}1017}10181019bool ClassLoaderData::contains_klass(Klass* klass) {1020// Lock-free access requires load_acquire1021for (Klass* k = Atomic::load_acquire(&_klasses); k != NULL; k = k->next_link()) {1022if (k == klass) return true;1023}1024return false;1025}102610271028