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