1  /*
   2  * Copyright (c) 2012, 2022, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 // A ClassLoaderData identifies the full set of class types that a class
  26 // loader's name resolution strategy produces for a given configuration of the
  27 // class loader.
  28 // Class types in the ClassLoaderData may be defined by from class file binaries
  29 // provided by the class loader, or from other class loader it interacts with
  30 // according to its name resolution strategy.
  31 //
  32 // Class loaders that implement a deterministic name resolution strategy
  33 // (including with respect to their delegation behavior), such as the boot, the
  34 // platform, and the system loaders of the JDK's built-in class loader
  35 // hierarchy, always produce the same linkset for a given configuration.
  36 //
  37 // ClassLoaderData carries information related to a linkset (e.g.,
  38 // metaspace holding its klass definitions).
  39 // The System Dictionary and related data structures (e.g., placeholder table,
  40 // loader constraints table) as well as the runtime representation of classes
  41 // only reference ClassLoaderData.
  42 //
  43 // Instances of java.lang.ClassLoader holds a pointer to a ClassLoaderData that
  44 // that represent the loader's "linking domain" in the JVM.
  45 //
  46 // The bootstrap loader (represented by NULL) also has a ClassLoaderData,
  47 // the singleton class the_null_class_loader_data().
  48 
  49 #include "precompiled.hpp"
  50 #include "classfile/classLoaderData.inline.hpp"
  51 #include "classfile/classLoaderDataGraph.inline.hpp"
  52 #include "classfile/dictionary.hpp"
  53 #include "classfile/javaClasses.hpp"
  54 #include "classfile/moduleEntry.hpp"
  55 #include "classfile/packageEntry.hpp"
  56 #include "classfile/symbolTable.hpp"
  57 #include "classfile/systemDictionary.hpp"
  58 #include "classfile/systemDictionaryShared.hpp"
  59 #include "classfile/vmClasses.hpp"
  60 #include "logging/log.hpp"
  61 #include "logging/logStream.hpp"
  62 #include "memory/allocation.inline.hpp"
  63 #include "memory/classLoaderMetaspace.hpp"
  64 #include "memory/metadataFactory.hpp"
  65 #include "memory/metaspace.hpp"
  66 #include "memory/resourceArea.hpp"
  67 #include "memory/universe.hpp"
  68 #include "oops/access.inline.hpp"
  69 #include "oops/klass.inline.hpp"
  70 #include "oops/objArrayKlass.hpp"
  71 #include "oops/oop.inline.hpp"
  72 #include "oops/oopHandle.inline.hpp"
  73 #include "oops/inlineKlass.inline.hpp"
  74 #include "oops/weakHandle.inline.hpp"
  75 #include "runtime/arguments.hpp"
  76 #include "runtime/atomic.hpp"
  77 #include "runtime/handles.inline.hpp"
  78 #include "runtime/mutex.hpp"
  79 #include "runtime/safepoint.hpp"
  80 #include "utilities/growableArray.hpp"
  81 #include "utilities/macros.hpp"
  82 #include "utilities/ostream.hpp"
  83 
  84 ClassLoaderData * ClassLoaderData::_the_null_class_loader_data = NULL;
  85 
  86 void ClassLoaderData::init_null_class_loader_data() {
  87   assert(_the_null_class_loader_data == NULL, "cannot initialize twice");
  88   assert(ClassLoaderDataGraph::_head == NULL, "cannot initialize twice");
  89 
  90   _the_null_class_loader_data = new ClassLoaderData(Handle(), false);
  91   ClassLoaderDataGraph::_head = _the_null_class_loader_data;
  92   assert(_the_null_class_loader_data->is_the_null_class_loader_data(), "Must be");
  93 
  94   LogTarget(Trace, class, loader, data) lt;
  95   if (lt.is_enabled()) {
  96     ResourceMark rm;
  97     LogStream ls(lt);
  98     ls.print("create ");
  99     _the_null_class_loader_data->print_value_on(&ls);
 100     ls.cr();
 101   }
 102 }
 103 
 104 // Obtain and set the class loader's name within the ClassLoaderData so
 105 // it will be available for error messages, logging, JFR, etc.  The name
 106 // and klass are available after the class_loader oop is no longer alive,
 107 // during unloading.
 108 void ClassLoaderData::initialize_name(Handle class_loader) {
 109   ResourceMark rm;
 110 
 111   // Obtain the class loader's name.  If the class loader's name was not
 112   // explicitly set during construction, the CLD's _name field will be null.
 113   oop cl_name = java_lang_ClassLoader::name(class_loader());
 114   if (cl_name != NULL) {
 115     const char* cl_instance_name = java_lang_String::as_utf8_string(cl_name);
 116 
 117     if (cl_instance_name != NULL && cl_instance_name[0] != '\0') {
 118       _name = SymbolTable::new_symbol(cl_instance_name);
 119     }
 120   }
 121 
 122   // Obtain the class loader's name and identity hash.  If the class loader's
 123   // name was not explicitly set during construction, the class loader's name and id
 124   // will be set to the qualified class name of the class loader along with its
 125   // identity hash.
 126   // If for some reason the ClassLoader's constructor has not been run, instead of
 127   // leaving the _name_and_id field null, fall back to the external qualified class
 128   // name.  Thus CLD's _name_and_id field should never have a null value.
 129   oop cl_name_and_id = java_lang_ClassLoader::nameAndId(class_loader());
 130   const char* cl_instance_name_and_id =
 131                   (cl_name_and_id == NULL) ? _class_loader_klass->external_name() :
 132                                              java_lang_String::as_utf8_string(cl_name_and_id);
 133   assert(cl_instance_name_and_id != NULL && cl_instance_name_and_id[0] != '\0', "class loader has no name and id");
 134   _name_and_id = SymbolTable::new_symbol(cl_instance_name_and_id);
 135 }
 136 
 137 ClassLoaderData::ClassLoaderData(Handle h_class_loader, bool has_class_mirror_holder) :
 138   _metaspace(NULL),
 139   _metaspace_lock(new Mutex(Mutex::nosafepoint-2, "MetaspaceAllocation_lock")),
 140   _unloading(false), _has_class_mirror_holder(has_class_mirror_holder),
 141   _modified_oops(true),
 142   // A non-strong hidden class loader data doesn't have anything to keep
 143   // it from being unloaded during parsing of the non-strong hidden class.
 144   // The null-class-loader should always be kept alive.
 145   _keep_alive((has_class_mirror_holder || h_class_loader.is_null()) ? 1 : 0),
 146   _claim(0),
 147   _handles(),
 148   _klasses(NULL), _packages(NULL), _modules(NULL), _unnamed_module(NULL), _dictionary(NULL),
 149   _jmethod_ids(NULL),
 150   _deallocate_list(NULL),
 151   _next(NULL),
 152   _class_loader_klass(NULL), _name(NULL), _name_and_id(NULL) {
 153 
 154   if (!h_class_loader.is_null()) {
 155     _class_loader = _handles.add(h_class_loader());
 156     _class_loader_klass = h_class_loader->klass();
 157     initialize_name(h_class_loader);
 158   }
 159 
 160   if (!has_class_mirror_holder) {
 161     // The holder is initialized later for non-strong hidden classes,
 162     // and before calling anything that call class_loader().
 163     initialize_holder(h_class_loader);
 164 
 165     // A ClassLoaderData created solely for a non-strong hidden class should never
 166     // have a ModuleEntryTable or PackageEntryTable created for it.
 167     _packages = new PackageEntryTable(PackageEntryTable::_packagetable_entry_size);
 168     if (h_class_loader.is_null()) {
 169       // Create unnamed module for boot loader
 170       _unnamed_module = ModuleEntry::create_boot_unnamed_module(this);
 171     } else {
 172       // Create unnamed module for all other loaders
 173       _unnamed_module = ModuleEntry::create_unnamed_module(this);
 174     }
 175     _dictionary = create_dictionary();
 176   }
 177 
 178   NOT_PRODUCT(_dependency_count = 0); // number of class loader dependencies
 179 
 180   JFR_ONLY(INIT_ID(this);)
 181 }
 182 
 183 ClassLoaderData::ChunkedHandleList::~ChunkedHandleList() {
 184   Chunk* c = _head;
 185   while (c != NULL) {
 186     Chunk* next = c->_next;
 187     delete c;
 188     c = next;
 189   }
 190 }
 191 
 192 OopHandle ClassLoaderData::ChunkedHandleList::add(oop o) {
 193   if (_head == NULL || _head->_size == Chunk::CAPACITY) {
 194     Chunk* next = new Chunk(_head);
 195     Atomic::release_store(&_head, next);
 196   }
 197   oop* handle = &_head->_data[_head->_size];
 198   NativeAccess<IS_DEST_UNINITIALIZED>::oop_store(handle, o);
 199   Atomic::release_store(&_head->_size, _head->_size + 1);
 200   return OopHandle(handle);
 201 }
 202 
 203 int ClassLoaderData::ChunkedHandleList::count() const {
 204   int count = 0;
 205   Chunk* chunk = _head;
 206   while (chunk != NULL) {
 207     count += chunk->_size;
 208     chunk = chunk->_next;
 209   }
 210   return count;
 211 }
 212 
 213 inline void ClassLoaderData::ChunkedHandleList::oops_do_chunk(OopClosure* f, Chunk* c, const juint size) {
 214   for (juint i = 0; i < size; i++) {
 215     if (c->_data[i] != NULL) {
 216       f->do_oop(&c->_data[i]);
 217     }
 218   }
 219 }
 220 
 221 void ClassLoaderData::ChunkedHandleList::oops_do(OopClosure* f) {
 222   Chunk* head = Atomic::load_acquire(&_head);
 223   if (head != NULL) {
 224     // Must be careful when reading size of head
 225     oops_do_chunk(f, head, Atomic::load_acquire(&head->_size));
 226     for (Chunk* c = head->_next; c != NULL; c = c->_next) {
 227       oops_do_chunk(f, c, c->_size);
 228     }
 229   }
 230 }
 231 
 232 class VerifyContainsOopClosure : public OopClosure {
 233   oop  _target;
 234   bool _found;
 235 
 236  public:
 237   VerifyContainsOopClosure(oop target) : _target(target), _found(false) {}
 238 
 239   void do_oop(oop* p) {
 240     if (p != NULL && NativeAccess<AS_NO_KEEPALIVE>::oop_load(p) == _target) {
 241       _found = true;
 242     }
 243   }
 244 
 245   void do_oop(narrowOop* p) {
 246     // The ChunkedHandleList should not contain any narrowOop
 247     ShouldNotReachHere();
 248   }
 249 
 250   bool found() const {
 251     return _found;
 252   }
 253 };
 254 
 255 bool ClassLoaderData::ChunkedHandleList::contains(oop p) {
 256   VerifyContainsOopClosure cl(p);
 257   oops_do(&cl);
 258   return cl.found();
 259 }
 260 
 261 #ifndef PRODUCT
 262 bool ClassLoaderData::ChunkedHandleList::owner_of(oop* oop_handle) {
 263   Chunk* chunk = _head;
 264   while (chunk != NULL) {
 265     if (&(chunk->_data[0]) <= oop_handle && oop_handle < &(chunk->_data[chunk->_size])) {
 266       return true;
 267     }
 268     chunk = chunk->_next;
 269   }
 270   return false;
 271 }
 272 #endif // PRODUCT
 273 
 274 void ClassLoaderData::clear_claim(int claim) {
 275   for (;;) {
 276     int old_claim = Atomic::load(&_claim);
 277     if ((old_claim & claim) == 0) {
 278       return;
 279     }
 280     int new_claim = old_claim & ~claim;
 281     if (Atomic::cmpxchg(&_claim, old_claim, new_claim) == old_claim) {
 282       return;
 283     }
 284   }
 285 }
 286 
 287 bool ClassLoaderData::try_claim(int claim) {
 288   for (;;) {
 289     int old_claim = Atomic::load(&_claim);
 290     if ((old_claim & claim) == claim) {
 291       return false;
 292     }
 293     int new_claim = old_claim | claim;
 294     if (Atomic::cmpxchg(&_claim, old_claim, new_claim) == old_claim) {
 295       return true;
 296     }
 297   }
 298 }
 299 
 300 // Non-strong hidden classes have their own ClassLoaderData that is marked to keep alive
 301 // while the class is being parsed, and if the class appears on the module fixup list.
 302 // Due to the uniqueness that no other class shares the hidden class' name or
 303 // ClassLoaderData, no other non-GC thread has knowledge of the hidden class while
 304 // it is being defined, therefore _keep_alive is not volatile or atomic.
 305 void ClassLoaderData::inc_keep_alive() {
 306   if (has_class_mirror_holder()) {
 307     assert(_keep_alive > 0, "Invalid keep alive increment count");
 308     _keep_alive++;
 309   }
 310 }
 311 
 312 void ClassLoaderData::dec_keep_alive() {
 313   if (has_class_mirror_holder()) {
 314     assert(_keep_alive > 0, "Invalid keep alive decrement count");
 315     _keep_alive--;
 316   }
 317 }
 318 
 319 void ClassLoaderData::oops_do(OopClosure* f, int claim_value, bool clear_mod_oops) {
 320   if (claim_value != ClassLoaderData::_claim_none && !try_claim(claim_value)) {
 321     return;
 322   }
 323 
 324   // Only clear modified_oops after the ClassLoaderData is claimed.
 325   if (clear_mod_oops) {
 326     clear_modified_oops();
 327   }
 328 
 329   _handles.oops_do(f);
 330 }
 331 
 332 void ClassLoaderData::classes_do(KlassClosure* klass_closure) {
 333   // Lock-free access requires load_acquire
 334   for (Klass* k = Atomic::load_acquire(&_klasses); k != NULL; k = k->next_link()) {
 335     klass_closure->do_klass(k);
 336     assert(k != k->next_link(), "no loops!");
 337   }
 338 }
 339 
 340 void ClassLoaderData::classes_do(void f(Klass * const)) {
 341   // Lock-free access requires load_acquire
 342   for (Klass* k = Atomic::load_acquire(&_klasses); k != NULL; k = k->next_link()) {
 343     f(k);
 344     assert(k != k->next_link(), "no loops!");
 345   }
 346 }
 347 
 348 void ClassLoaderData::methods_do(void f(Method*)) {
 349   // Lock-free access requires load_acquire
 350   for (Klass* k = Atomic::load_acquire(&_klasses); k != NULL; k = k->next_link()) {
 351     if (k->is_instance_klass() && InstanceKlass::cast(k)->is_loaded()) {
 352       InstanceKlass::cast(k)->methods_do(f);
 353     }
 354   }
 355 }
 356 
 357 void ClassLoaderData::loaded_classes_do(KlassClosure* klass_closure) {
 358   // To call this, one must have the MultiArray_lock held, but the _klasses list still has lock free reads.
 359   assert_locked_or_safepoint(MultiArray_lock);
 360 
 361   // Lock-free access requires load_acquire
 362   for (Klass* k = Atomic::load_acquire(&_klasses); k != NULL; k = k->next_link()) {
 363     // Filter out InstanceKlasses (or their ObjArrayKlasses) that have not entered the
 364     // loaded state.
 365     if (k->is_instance_klass()) {
 366       if (!InstanceKlass::cast(k)->is_loaded()) {
 367         continue;
 368       }
 369     } else if (k->is_shared() && k->is_objArray_klass()) {
 370       Klass* bottom = ObjArrayKlass::cast(k)->bottom_klass();
 371       if (bottom->is_instance_klass() && !InstanceKlass::cast(bottom)->is_loaded()) {
 372         // This could happen if <bottom> is a shared class that has been restored
 373         // but is not yet marked as loaded. All archived array classes of the
 374         // bottom class are already restored and placed in the _klasses list.
 375         continue;
 376       }
 377     }
 378 
 379 #ifdef ASSERT
 380     oop m = k->java_mirror();
 381     assert(m != NULL, "NULL mirror");
 382     assert(m->is_a(vmClasses::Class_klass()), "invalid mirror");
 383 #endif
 384     klass_closure->do_klass(k);
 385   }
 386 }
 387 
 388 void ClassLoaderData::classes_do(void f(InstanceKlass*)) {
 389   // Lock-free access requires load_acquire
 390   for (Klass* k = Atomic::load_acquire(&_klasses); k != NULL; k = k->next_link()) {
 391     if (k->is_instance_klass()) {
 392       f(InstanceKlass::cast(k));
 393     }
 394     assert(k != k->next_link(), "no loops!");
 395   }
 396 }
 397 
 398 void ClassLoaderData::inline_classes_do(void f(InlineKlass*)) {
 399   // Lock-free access requires load_acquire
 400   for (Klass* k = Atomic::load_acquire(&_klasses); k != NULL; k = k->next_link()) {
 401     if (k->is_inline_klass()) {
 402       f(InlineKlass::cast(k));
 403     }
 404     assert(k != k->next_link(), "no loops!");
 405   }
 406 }
 407 
 408 void ClassLoaderData::modules_do(void f(ModuleEntry*)) {
 409   assert_locked_or_safepoint(Module_lock);
 410   if (_unnamed_module != NULL) {
 411     f(_unnamed_module);
 412   }
 413   if (_modules != NULL) {
 414     for (int i = 0; i < _modules->table_size(); i++) {
 415       for (ModuleEntry* entry = _modules->bucket(i);
 416            entry != NULL;
 417            entry = entry->next()) {
 418         f(entry);
 419       }
 420     }
 421   }
 422 }
 423 
 424 void ClassLoaderData::packages_do(void f(PackageEntry*)) {
 425   assert_locked_or_safepoint(Module_lock);
 426   if (_packages != NULL) {
 427     for (int i = 0; i < _packages->table_size(); i++) {
 428       for (PackageEntry* entry = _packages->bucket(i);
 429            entry != NULL;
 430            entry = entry->next()) {
 431         f(entry);
 432       }
 433     }
 434   }
 435 }
 436 
 437 void ClassLoaderData::record_dependency(const Klass* k) {
 438   assert(k != NULL, "invariant");
 439 
 440   ClassLoaderData * const from_cld = this;
 441   ClassLoaderData * const to_cld = k->class_loader_data();
 442 
 443   // Do not need to record dependency if the dependency is to a class whose
 444   // class loader data is never freed.  (i.e. the dependency's class loader
 445   // is one of the three builtin class loaders and the dependency's class
 446   // loader data has a ClassLoader holder, not a Class holder.)
 447   if (to_cld->is_permanent_class_loader_data()) {
 448     return;
 449   }
 450 
 451   oop to;
 452   if (to_cld->has_class_mirror_holder()) {
 453     // Just return if a non-strong hidden class class is attempting to record a dependency
 454     // to itself.  (Note that every non-strong hidden class has its own unique class
 455     // loader data.)
 456     if (to_cld == from_cld) {
 457       return;
 458     }
 459     // Hidden class dependencies are through the mirror.
 460     to = k->java_mirror();
 461   } else {
 462     to = to_cld->class_loader();
 463     oop from = from_cld->class_loader();
 464 
 465     // Just return if this dependency is to a class with the same or a parent
 466     // class_loader.
 467     if (from == to || java_lang_ClassLoader::isAncestor(from, to)) {
 468       return; // this class loader is in the parent list, no need to add it.
 469     }
 470   }
 471 
 472   // It's a dependency we won't find through GC, add it.
 473   if (!_handles.contains(to)) {
 474     NOT_PRODUCT(Atomic::inc(&_dependency_count));
 475     LogTarget(Trace, class, loader, data) lt;
 476     if (lt.is_enabled()) {
 477       ResourceMark rm;
 478       LogStream ls(lt);
 479       ls.print("adding dependency from ");
 480       print_value_on(&ls);
 481       ls.print(" to ");
 482       to_cld->print_value_on(&ls);
 483       ls.cr();
 484     }
 485     Handle dependency(Thread::current(), to);
 486     add_handle(dependency);
 487     // Added a potentially young gen oop to the ClassLoaderData
 488     record_modified_oops();
 489   }
 490 }
 491 
 492 void ClassLoaderData::add_class(Klass* k, bool publicize /* true */) {
 493   {
 494     MutexLocker ml(metaspace_lock(), Mutex::_no_safepoint_check_flag);
 495     Klass* old_value = _klasses;
 496     k->set_next_link(old_value);
 497     // Link the new item into the list, making sure the linked class is stable
 498     // since the list can be walked without a lock
 499     Atomic::release_store(&_klasses, k);
 500     if (k->is_array_klass()) {
 501       ClassLoaderDataGraph::inc_array_classes(1);
 502     } else {
 503       ClassLoaderDataGraph::inc_instance_classes(1);
 504     }
 505   }
 506 
 507   if (publicize) {
 508     LogTarget(Trace, class, loader, data) lt;
 509     if (lt.is_enabled()) {
 510       ResourceMark rm;
 511       LogStream ls(lt);
 512       ls.print("Adding k: " PTR_FORMAT " %s to ", p2i(k), k->external_name());
 513       print_value_on(&ls);
 514       ls.cr();
 515     }
 516   }
 517 }
 518 
 519 void ClassLoaderData::initialize_holder(Handle loader_or_mirror) {
 520   if (loader_or_mirror() != NULL) {
 521     assert(_holder.is_null(), "never replace holders");
 522     _holder = WeakHandle(Universe::vm_weak(), loader_or_mirror);
 523   }
 524 }
 525 
 526 // Remove a klass from the _klasses list for scratch_class during redefinition
 527 // or parsed class in the case of an error.
 528 void ClassLoaderData::remove_class(Klass* scratch_class) {
 529   assert_locked_or_safepoint(ClassLoaderDataGraph_lock);
 530 
 531   // Adjust global class iterator.
 532   ClassLoaderDataGraph::adjust_saved_class(scratch_class);
 533 
 534   Klass* prev = NULL;
 535   for (Klass* k = _klasses; k != NULL; k = k->next_link()) {
 536     if (k == scratch_class) {
 537       if (prev == NULL) {
 538         _klasses = k->next_link();
 539       } else {
 540         Klass* next = k->next_link();
 541         prev->set_next_link(next);
 542       }
 543 
 544       if (k->is_array_klass()) {
 545         ClassLoaderDataGraph::dec_array_classes(1);
 546       } else {
 547         ClassLoaderDataGraph::dec_instance_classes(1);
 548       }
 549 
 550       return;
 551     }
 552     prev = k;
 553     assert(k != k->next_link(), "no loops!");
 554   }
 555   ShouldNotReachHere();   // should have found this class!!
 556 }
 557 
 558 void ClassLoaderData::unload() {
 559   _unloading = true;
 560 
 561   LogTarget(Trace, class, loader, data) lt;
 562   if (lt.is_enabled()) {
 563     ResourceMark rm;
 564     LogStream ls(lt);
 565     ls.print("unload");
 566     print_value_on(&ls);
 567     ls.cr();
 568   }
 569 
 570   // Some items on the _deallocate_list need to free their C heap structures
 571   // if they are not already on the _klasses list.
 572   free_deallocate_list_C_heap_structures();
 573 
 574   inline_classes_do(InlineKlass::cleanup);
 575 
 576   // Clean up class dependencies and tell serviceability tools
 577   // these classes are unloading.  Must be called
 578   // after erroneous classes are released.
 579   classes_do(InstanceKlass::unload_class);
 580 
 581   // Method::clear_jmethod_ids only sets the jmethod_ids to NULL without
 582   // releasing the memory for related JNIMethodBlocks and JNIMethodBlockNodes.
 583   // This is done intentionally because native code (e.g. JVMTI agent) holding
 584   // jmethod_ids may access them after the associated classes and class loader
 585   // are unloaded. The Java Native Interface Specification says "method ID
 586   // does not prevent the VM from unloading the class from which the ID has
 587   // been derived. After the class is unloaded, the method or field ID becomes
 588   // invalid". In real world usages, the native code may rely on jmethod_ids
 589   // being NULL after class unloading. Hence, it is unsafe to free the memory
 590   // from the VM side without knowing when native code is going to stop using
 591   // them.
 592   if (_jmethod_ids != NULL) {
 593     Method::clear_jmethod_ids(this);
 594   }
 595 
 596   // Clean up global class iterator for compiler
 597   ClassLoaderDataGraph::adjust_saved_class(this);
 598 }
 599 
 600 ModuleEntryTable* ClassLoaderData::modules() {
 601   // Lazily create the module entry table at first request.
 602   // Lock-free access requires load_acquire.
 603   ModuleEntryTable* modules = Atomic::load_acquire(&_modules);
 604   if (modules == NULL) {
 605     MutexLocker m1(Module_lock);
 606     // Check if _modules got allocated while we were waiting for this lock.
 607     if ((modules = _modules) == NULL) {
 608       modules = new ModuleEntryTable(ModuleEntryTable::_moduletable_entry_size);
 609 
 610       {
 611         MutexLocker m1(metaspace_lock(), Mutex::_no_safepoint_check_flag);
 612         // Ensure _modules is stable, since it is examined without a lock
 613         Atomic::release_store(&_modules, modules);
 614       }
 615     }
 616   }
 617   return modules;
 618 }
 619 
 620 const int _boot_loader_dictionary_size    = 1009;
 621 const int _default_loader_dictionary_size = 107;
 622 
 623 Dictionary* ClassLoaderData::create_dictionary() {
 624   assert(!has_class_mirror_holder(), "class mirror holder cld does not have a dictionary");
 625   int size;
 626   bool resizable = false;
 627   if (_the_null_class_loader_data == NULL) {
 628     size = _boot_loader_dictionary_size;
 629     resizable = true;
 630   } else if (class_loader()->is_a(vmClasses::reflect_DelegatingClassLoader_klass())) {
 631     size = 1;  // there's only one class in relection class loader and no initiated classes
 632   } else if (is_system_class_loader_data()) {
 633     size = _boot_loader_dictionary_size;
 634     resizable = true;
 635   } else {
 636     size = _default_loader_dictionary_size;
 637     resizable = true;
 638   }
 639   if (!DynamicallyResizeSystemDictionaries || DumpSharedSpaces) {
 640     resizable = false;
 641   }
 642   return new Dictionary(this, size, resizable);
 643 }
 644 
 645 // Tell the GC to keep this klass alive. Needed while iterating ClassLoaderDataGraph,
 646 // and any runtime code that uses klasses.
 647 oop ClassLoaderData::holder() const {
 648   // A klass that was previously considered dead can be looked up in the
 649   // CLD/SD, and its _java_mirror or _class_loader can be stored in a root
 650   // or a reachable object making it alive again. The SATB part of G1 needs
 651   // to get notified about this potential resurrection, otherwise the marking
 652   // might not find the object.
 653   if (!_holder.is_null()) {  // NULL class_loader
 654     return _holder.resolve();
 655   } else {
 656     return NULL;
 657   }
 658 }
 659 
 660 // Let the GC read the holder without keeping it alive.
 661 oop ClassLoaderData::holder_no_keepalive() const {
 662   if (!_holder.is_null()) {  // NULL class_loader
 663     return _holder.peek();
 664   } else {
 665     return NULL;
 666   }
 667 }
 668 
 669 // Unloading support
 670 bool ClassLoaderData::is_alive() const {
 671   bool alive = keep_alive()         // null class loader and incomplete non-strong hidden class.
 672       || (_holder.peek() != NULL);  // and not cleaned by the GC weak handle processing.
 673 
 674   return alive;
 675 }
 676 
 677 class ReleaseKlassClosure: public KlassClosure {
 678 private:
 679   size_t  _instance_class_released;
 680   size_t  _array_class_released;
 681 public:
 682   ReleaseKlassClosure() : _instance_class_released(0), _array_class_released(0) { }
 683 
 684   size_t instance_class_released() const { return _instance_class_released; }
 685   size_t array_class_released()    const { return _array_class_released;    }
 686 
 687   void do_klass(Klass* k) {
 688     if (k->is_array_klass()) {
 689       _array_class_released ++;
 690     } else {
 691       assert(k->is_instance_klass(), "Must be");
 692       _instance_class_released ++;
 693     }
 694     k->release_C_heap_structures();
 695   }
 696 };
 697 
 698 ClassLoaderData::~ClassLoaderData() {
 699   // Release C heap structures for all the classes.
 700   ReleaseKlassClosure cl;
 701   classes_do(&cl);
 702 
 703   ClassLoaderDataGraph::dec_array_classes(cl.array_class_released());
 704   ClassLoaderDataGraph::dec_instance_classes(cl.instance_class_released());
 705 
 706   // Release the WeakHandle
 707   _holder.release(Universe::vm_weak());
 708 
 709   // Release C heap allocated hashtable for all the packages.
 710   if (_packages != NULL) {
 711     // Destroy the table itself
 712     delete _packages;
 713     _packages = NULL;
 714   }
 715 
 716   // Release C heap allocated hashtable for all the modules.
 717   if (_modules != NULL) {
 718     // Destroy the table itself
 719     delete _modules;
 720     _modules = NULL;
 721   }
 722 
 723   // Release C heap allocated hashtable for the dictionary
 724   if (_dictionary != NULL) {
 725     // Destroy the table itself
 726     delete _dictionary;
 727     _dictionary = NULL;
 728   }
 729 
 730   if (_unnamed_module != NULL) {
 731     _unnamed_module->delete_unnamed_module();
 732     _unnamed_module = NULL;
 733   }
 734 
 735   // release the metaspace
 736   ClassLoaderMetaspace *m = _metaspace;
 737   if (m != NULL) {
 738     _metaspace = NULL;
 739     delete m;
 740   }
 741 
 742   // Delete lock
 743   delete _metaspace_lock;
 744 
 745   // Delete free list
 746   if (_deallocate_list != NULL) {
 747     delete _deallocate_list;
 748   }
 749 
 750   // Decrement refcounts of Symbols if created.
 751   if (_name != NULL) {
 752     _name->decrement_refcount();
 753   }
 754   if (_name_and_id != NULL) {
 755     _name_and_id->decrement_refcount();
 756   }
 757 }
 758 
 759 // Returns true if this class loader data is for the app class loader
 760 // or a user defined system class loader.  (Note that the class loader
 761 // data may have a Class holder.)
 762 bool ClassLoaderData::is_system_class_loader_data() const {
 763   return SystemDictionary::is_system_class_loader(class_loader());
 764 }
 765 
 766 // Returns true if this class loader data is for the platform class loader.
 767 // (Note that the class loader data may have a Class holder.)
 768 bool ClassLoaderData::is_platform_class_loader_data() const {
 769   return SystemDictionary::is_platform_class_loader(class_loader());
 770 }
 771 
 772 // Returns true if the class loader for this class loader data is one of
 773 // the 3 builtin (boot application/system or platform) class loaders,
 774 // including a user-defined system class loader.  Note that if the class
 775 // loader data is for a non-strong hidden class then it may
 776 // get freed by a GC even if its class loader is one of these loaders.
 777 bool ClassLoaderData::is_builtin_class_loader_data() const {
 778   return (is_boot_class_loader_data() ||
 779           SystemDictionary::is_system_class_loader(class_loader()) ||
 780           SystemDictionary::is_platform_class_loader(class_loader()));
 781 }
 782 
 783 // Returns true if this class loader data is a class loader data
 784 // that is not ever freed by a GC.  It must be the CLD for one of the builtin
 785 // class loaders and not the CLD for a non-strong hidden class.
 786 bool ClassLoaderData::is_permanent_class_loader_data() const {
 787   return is_builtin_class_loader_data() && !has_class_mirror_holder();
 788 }
 789 
 790 ClassLoaderMetaspace* ClassLoaderData::metaspace_non_null() {
 791   // If the metaspace has not been allocated, create a new one.  Might want
 792   // to create smaller arena for Reflection class loaders also.
 793   // The reason for the delayed allocation is because some class loaders are
 794   // simply for delegating with no metadata of their own.
 795   // Lock-free access requires load_acquire.
 796   ClassLoaderMetaspace* metaspace = Atomic::load_acquire(&_metaspace);
 797   if (metaspace == NULL) {
 798     MutexLocker ml(_metaspace_lock,  Mutex::_no_safepoint_check_flag);
 799     // Check if _metaspace got allocated while we were waiting for this lock.
 800     if ((metaspace = _metaspace) == NULL) {
 801       if (this == the_null_class_loader_data()) {
 802         assert (class_loader() == NULL, "Must be");
 803         metaspace = new ClassLoaderMetaspace(_metaspace_lock, Metaspace::BootMetaspaceType);
 804       } else if (has_class_mirror_holder()) {
 805         metaspace = new ClassLoaderMetaspace(_metaspace_lock, Metaspace::ClassMirrorHolderMetaspaceType);
 806       } else if (class_loader()->is_a(vmClasses::reflect_DelegatingClassLoader_klass())) {
 807         metaspace = new ClassLoaderMetaspace(_metaspace_lock, Metaspace::ReflectionMetaspaceType);
 808       } else {
 809         metaspace = new ClassLoaderMetaspace(_metaspace_lock, Metaspace::StandardMetaspaceType);
 810       }
 811       // Ensure _metaspace is stable, since it is examined without a lock
 812       Atomic::release_store(&_metaspace, metaspace);
 813     }
 814   }
 815   return metaspace;
 816 }
 817 
 818 OopHandle ClassLoaderData::add_handle(Handle h) {
 819   MutexLocker ml(metaspace_lock(),  Mutex::_no_safepoint_check_flag);
 820   record_modified_oops();
 821   return _handles.add(h());
 822 }
 823 
 824 void ClassLoaderData::remove_handle(OopHandle h) {
 825   assert(!is_unloading(), "Do not remove a handle for a CLD that is unloading");
 826   oop* ptr = h.ptr_raw();
 827   if (ptr != NULL) {
 828     assert(_handles.owner_of(ptr), "Got unexpected handle " PTR_FORMAT, p2i(ptr));
 829     NativeAccess<>::oop_store(ptr, oop(NULL));
 830   }
 831 }
 832 
 833 void ClassLoaderData::init_handle_locked(OopHandle& dest, Handle h) {
 834   MutexLocker ml(metaspace_lock(),  Mutex::_no_safepoint_check_flag);
 835   if (dest.resolve() != NULL) {
 836     return;
 837   } else {
 838     record_modified_oops();
 839     dest = _handles.add(h());
 840   }
 841 }
 842 
 843 // Add this metadata pointer to be freed when it's safe.  This is only during
 844 // a safepoint which checks if handles point to this metadata field.
 845 void ClassLoaderData::add_to_deallocate_list(Metadata* m) {
 846   // Metadata in shared region isn't deleted.
 847   if (!m->is_shared()) {
 848     MutexLocker ml(metaspace_lock(),  Mutex::_no_safepoint_check_flag);
 849     if (_deallocate_list == NULL) {
 850       _deallocate_list = new (ResourceObj::C_HEAP, mtClass) GrowableArray<Metadata*>(100, mtClass);
 851     }
 852     _deallocate_list->append_if_missing(m);
 853     log_debug(class, loader, data)("deallocate added for %s", m->print_value_string());
 854     ClassLoaderDataGraph::set_should_clean_deallocate_lists();
 855   }
 856 }
 857 
 858 // Deallocate free metadata on the free list.  How useful the PermGen was!
 859 void ClassLoaderData::free_deallocate_list() {
 860   // This must be called at a safepoint because it depends on metadata walking at
 861   // safepoint cleanup time.
 862   assert(SafepointSynchronize::is_at_safepoint(), "only called at safepoint");
 863   assert(!is_unloading(), "only called for ClassLoaderData that are not unloading");
 864   if (_deallocate_list == NULL) {
 865     return;
 866   }
 867   // Go backwards because this removes entries that are freed.
 868   for (int i = _deallocate_list->length() - 1; i >= 0; i--) {
 869     Metadata* m = _deallocate_list->at(i);
 870     if (!m->on_stack()) {
 871       _deallocate_list->remove_at(i);
 872       // There are only three types of metadata that we deallocate directly.
 873       // Cast them so they can be used by the template function.
 874       if (m->is_method()) {
 875         MetadataFactory::free_metadata(this, (Method*)m);
 876       } else if (m->is_constantPool()) {
 877         MetadataFactory::free_metadata(this, (ConstantPool*)m);
 878       } else if (m->is_klass()) {
 879         if (!((Klass*)m)->is_inline_klass()) {
 880           MetadataFactory::free_metadata(this, (InstanceKlass*)m);
 881         } else {
 882           MetadataFactory::free_metadata(this, (InlineKlass*)m);
 883         }
 884       } else {
 885         ShouldNotReachHere();
 886       }
 887     } else {
 888       // Metadata is alive.
 889       // If scratch_class is on stack then it shouldn't be on this list!
 890       assert(!m->is_klass() || !((InstanceKlass*)m)->is_scratch_class(),
 891              "scratch classes on this list should be dead");
 892       // Also should assert that other metadata on the list was found in handles.
 893       // Some cleaning remains.
 894       ClassLoaderDataGraph::set_should_clean_deallocate_lists();
 895     }
 896   }
 897 }
 898 
 899 // This is distinct from free_deallocate_list.  For class loader data that are
 900 // unloading, this frees the C heap memory for items on the list, and unlinks
 901 // scratch or error classes so that unloading events aren't triggered for these
 902 // classes. The metadata is removed with the unloading metaspace.
 903 // There isn't C heap memory allocated for methods, so nothing is done for them.
 904 void ClassLoaderData::free_deallocate_list_C_heap_structures() {
 905   assert_locked_or_safepoint(ClassLoaderDataGraph_lock);
 906   assert(is_unloading(), "only called for ClassLoaderData that are unloading");
 907   if (_deallocate_list == NULL) {
 908     return;
 909   }
 910   // Go backwards because this removes entries that are freed.
 911   for (int i = _deallocate_list->length() - 1; i >= 0; i--) {
 912     Metadata* m = _deallocate_list->at(i);
 913     _deallocate_list->remove_at(i);
 914     if (m->is_constantPool()) {
 915       ((ConstantPool*)m)->release_C_heap_structures();
 916     } else if (m->is_klass()) {
 917       InstanceKlass* ik = (InstanceKlass*)m;
 918       // also releases ik->constants() C heap memory
 919       ik->release_C_heap_structures();
 920       // Remove the class so unloading events aren't triggered for
 921       // this class (scratch or error class) in do_unloading().
 922       remove_class(ik);
 923       // But still have to remove it from the dumptime_table.
 924       SystemDictionaryShared::handle_class_unloading(ik);
 925     }
 926   }
 927 }
 928 
 929 // Caller needs ResourceMark
 930 // If the class loader's _name has not been explicitly set, the class loader's
 931 // qualified class name is returned.
 932 const char* ClassLoaderData::loader_name() const {
 933    if (_class_loader_klass == NULL) {
 934      return BOOTSTRAP_LOADER_NAME;
 935    } else if (_name != NULL) {
 936      return _name->as_C_string();
 937    } else {
 938      return _class_loader_klass->external_name();
 939    }
 940 }
 941 
 942 // Caller needs ResourceMark
 943 // Format of the _name_and_id is as follows:
 944 //   If the defining loader has a name explicitly set then '<loader-name>' @<id>
 945 //   If the defining loader has no name then <qualified-class-name> @<id>
 946 //   If built-in loader, then omit '@<id>' as there is only one instance.
 947 const char* ClassLoaderData::loader_name_and_id() const {
 948   if (_class_loader_klass == NULL) {
 949     return "'" BOOTSTRAP_LOADER_NAME "'";
 950   } else if (_name_and_id != NULL) {
 951     return _name_and_id->as_C_string();
 952   } else {
 953     // May be called in a race before _name_and_id is initialized.
 954     return _class_loader_klass->external_name();
 955   }
 956 }
 957 
 958 void ClassLoaderData::print_value_on(outputStream* out) const {
 959   if (!is_unloading() && class_loader() != NULL) {
 960     out->print("loader data: " INTPTR_FORMAT " for instance ", p2i(this));
 961     class_loader()->print_value_on(out);  // includes loader_name_and_id() and address of class loader instance
 962   } else {
 963     // loader data: 0xsomeaddr of 'bootstrap'
 964     out->print("loader data: " INTPTR_FORMAT " of %s", p2i(this), loader_name_and_id());
 965   }
 966   if (_has_class_mirror_holder) {
 967     out->print(" has a class holder");
 968   }
 969 }
 970 
 971 void ClassLoaderData::print_value() const { print_value_on(tty); }
 972 
 973 #ifndef PRODUCT
 974 class PrintKlassClosure: public KlassClosure {
 975   outputStream* _out;
 976 public:
 977   PrintKlassClosure(outputStream* out): _out(out) { }
 978 
 979   void do_klass(Klass* k) {
 980     ResourceMark rm;
 981     _out->print("%s,", k->external_name());
 982   }
 983 };
 984 
 985 void ClassLoaderData::print_on(outputStream* out) const {
 986   ResourceMark rm;
 987   out->print_cr("ClassLoaderData(" INTPTR_FORMAT ")", p2i(this));
 988   out->print_cr(" - name                %s", loader_name_and_id());
 989   if (!_holder.is_null()) {
 990     out->print   (" - holder              ");
 991     _holder.print_on(out);
 992     out->print_cr("");
 993   }
 994   out->print_cr(" - class loader        " INTPTR_FORMAT, p2i(_class_loader.ptr_raw()));
 995   out->print_cr(" - metaspace           " INTPTR_FORMAT, p2i(_metaspace));
 996   out->print_cr(" - unloading           %s", _unloading ? "true" : "false");
 997   out->print_cr(" - class mirror holder %s", _has_class_mirror_holder ? "true" : "false");
 998   out->print_cr(" - modified oops       %s", _modified_oops ? "true" : "false");
 999   out->print_cr(" - keep alive          %d", _keep_alive);
1000   out->print   (" - claim               ");
1001   switch(_claim) {
1002     case _claim_none:                       out->print_cr("none"); break;
1003     case _claim_finalizable:                out->print_cr("finalizable"); break;
1004     case _claim_strong:                     out->print_cr("strong"); break;
1005     case _claim_other:                      out->print_cr("other"); break;
1006     case _claim_other | _claim_finalizable: out->print_cr("other and finalizable"); break;
1007     case _claim_other | _claim_strong:      out->print_cr("other and strong"); break;
1008     default:                                ShouldNotReachHere();
1009   }
1010   out->print_cr(" - handles             %d", _handles.count());
1011   out->print_cr(" - dependency count    %d", _dependency_count);
1012   out->print   (" - klasses             {");
1013   PrintKlassClosure closure(out);
1014   ((ClassLoaderData*)this)->classes_do(&closure);
1015   out->print_cr(" }");
1016   out->print_cr(" - packages            " INTPTR_FORMAT, p2i(_packages));
1017   out->print_cr(" - module              " INTPTR_FORMAT, p2i(_modules));
1018   out->print_cr(" - unnamed module      " INTPTR_FORMAT, p2i(_unnamed_module));
1019   out->print_cr(" - dictionary          " INTPTR_FORMAT, p2i(_dictionary));
1020   if (_jmethod_ids != NULL) {
1021     out->print   (" - jmethod count       ");
1022     Method::print_jmethod_ids_count(this, out);
1023     out->print_cr("");
1024   }
1025   out->print_cr(" - deallocate list     " INTPTR_FORMAT, p2i(_deallocate_list));
1026   out->print_cr(" - next CLD            " INTPTR_FORMAT, p2i(_next));
1027 }
1028 #endif // PRODUCT
1029 
1030 void ClassLoaderData::print() const { print_on(tty); }
1031 
1032 void ClassLoaderData::verify() {
1033   assert_locked_or_safepoint(_metaspace_lock);
1034   oop cl = class_loader();
1035 
1036   guarantee(this == class_loader_data(cl) || has_class_mirror_holder(), "Must be the same");
1037   guarantee(cl != NULL || this == ClassLoaderData::the_null_class_loader_data() || has_class_mirror_holder(), "must be");
1038 
1039   // Verify the integrity of the allocated space.
1040 #ifdef ASSERT
1041   if (metaspace_or_null() != NULL) {
1042     metaspace_or_null()->verify();
1043   }
1044 #endif
1045 
1046   for (Klass* k = _klasses; k != NULL; k = k->next_link()) {
1047     guarantee(k->class_loader_data() == this, "Must be the same");
1048     k->verify();
1049     assert(k != k->next_link(), "no loops!");
1050   }
1051 }
1052 
1053 bool ClassLoaderData::contains_klass(Klass* klass) {
1054   // Lock-free access requires load_acquire
1055   for (Klass* k = Atomic::load_acquire(&_klasses); k != NULL; k = k->next_link()) {
1056     if (k == klass) return true;
1057   }
1058   return false;
1059 }