1  /*
   2  * Copyright (c) 2012, 2018, 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/resourceArea.hpp"
  63 #include "oops/access.inline.hpp"
  64 #include "oops/oop.inline.hpp"
  65 #include "oops/oopHandle.inline.hpp"
  66 #include "oops/valueKlass.hpp"
  67 #include "oops/weakHandle.inline.hpp"
  68 #include "runtime/atomic.hpp"
  69 #include "runtime/handles.inline.hpp"
  70 #include "runtime/mutex.hpp"
  71 #include "runtime/orderAccess.hpp"
  72 #include "runtime/safepoint.hpp"
  73 #include "utilities/growableArray.hpp"
  74 #include "utilities/macros.hpp"
  75 #include "utilities/ostream.hpp"
  76 
  77 ClassLoaderData * ClassLoaderData::_the_null_class_loader_data = NULL;
  78 
  79 void ClassLoaderData::init_null_class_loader_data() {
  80   assert(_the_null_class_loader_data == NULL, "cannot initialize twice");
  81   assert(ClassLoaderDataGraph::_head == NULL, "cannot initialize twice");
  82 
  83   _the_null_class_loader_data = new ClassLoaderData(Handle(), false);
  84   ClassLoaderDataGraph::_head = _the_null_class_loader_data;
  85   assert(_the_null_class_loader_data->is_the_null_class_loader_data(), "Must be");
  86 
  87   LogTarget(Trace, class, loader, data) lt;
  88   if (lt.is_enabled()) {
  89     ResourceMark rm;
  90     LogStream ls(lt);
  91     ls.print("create ");
  92     _the_null_class_loader_data->print_value_on(&ls);
  93     ls.cr();
  94   }
  95 }
  96 
  97 // Obtain and set the class loader's name within the ClassLoaderData so
  98 // it will be available for error messages, logging, JFR, etc.  The name
  99 // and klass are available after the class_loader oop is no longer alive,
 100 // during unloading.
 101 void ClassLoaderData::initialize_name(Handle class_loader) {
 102   Thread* THREAD = Thread::current();
 103   ResourceMark rm(THREAD);
 104 
 105   // Obtain the class loader's name.  If the class loader's name was not
 106   // explicitly set during construction, the CLD's _name field will be null.
 107   oop cl_name = java_lang_ClassLoader::name(class_loader());
 108   if (cl_name != NULL) {
 109     const char* cl_instance_name = java_lang_String::as_utf8_string(cl_name);
 110 
 111     if (cl_instance_name != NULL && cl_instance_name[0] != '\0') {
 112       // Can't throw InternalError and SymbolTable doesn't throw OOM anymore.
 113       _name = SymbolTable::new_symbol(cl_instance_name, CATCH);
 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   // Can't throw InternalError and SymbolTable doesn't throw OOM anymore.
 130   _name_and_id = SymbolTable::new_symbol(cl_instance_name_and_id, CATCH);
 131 }
 132 
 133 ClassLoaderData::ClassLoaderData(Handle h_class_loader, bool is_unsafe_anonymous) :
 134   _metaspace(NULL),
 135   _metaspace_lock(new Mutex(Monitor::leaf+1, "Metaspace allocation lock", true,
 136                             Monitor::_safepoint_check_never)),
 137   _unloading(false), _is_unsafe_anonymous(is_unsafe_anonymous),
 138   _modified_oops(true), _accumulated_modified_oops(false),
 139   // An unsafe anonymous class loader data doesn't have anything to keep
 140   // it from being unloaded during parsing of the unsafe anonymous class.
 141   // The null-class-loader should always be kept alive.
 142   _keep_alive((is_unsafe_anonymous || h_class_loader.is_null()) ? 1 : 0),
 143   _claim(0),
 144   _handles(),
 145   _klasses(NULL), _packages(NULL), _modules(NULL), _unnamed_module(NULL), _dictionary(NULL),
 146   _jmethod_ids(NULL),
 147   _deallocate_list(NULL),
 148   _next(NULL),
 149   _class_loader_klass(NULL), _name(NULL), _name_and_id(NULL) {
 150 
 151   if (!h_class_loader.is_null()) {
 152     _class_loader = _handles.add(h_class_loader());
 153     _class_loader_klass = h_class_loader->klass();
 154     initialize_name(h_class_loader);
 155   }
 156 
 157   if (!is_unsafe_anonymous) {
 158     // The holder is initialized later for unsafe anonymous classes, and before calling anything
 159     // that call class_loader().
 160     initialize_holder(h_class_loader);
 161 
 162     // A ClassLoaderData created solely for an unsafe anonymous class should never have a
 163     // ModuleEntryTable or PackageEntryTable created for it. The defining package
 164     // and module for an unsafe anonymous class will be found in its host class.
 165     _packages = new PackageEntryTable(PackageEntryTable::_packagetable_entry_size);
 166     if (h_class_loader.is_null()) {
 167       // Create unnamed module for boot loader
 168       _unnamed_module = ModuleEntry::create_boot_unnamed_module(this);
 169     } else {
 170       // Create unnamed module for all other loaders
 171       _unnamed_module = ModuleEntry::create_unnamed_module(this);
 172     }
 173     _dictionary = create_dictionary();
 174   }
 175 
 176   NOT_PRODUCT(_dependency_count = 0); // number of class loader dependencies
 177 
 178   JFR_ONLY(INIT_ID(this);)
 179 }
 180 
 181 ClassLoaderData::ChunkedHandleList::~ChunkedHandleList() {
 182   Chunk* c = _head;
 183   while (c != NULL) {
 184     Chunk* next = c->_next;
 185     delete c;
 186     c = next;
 187   }
 188 }
 189 
 190 oop* ClassLoaderData::ChunkedHandleList::add(oop o) {
 191   if (_head == NULL || _head->_size == Chunk::CAPACITY) {
 192     Chunk* next = new Chunk(_head);
 193     OrderAccess::release_store(&_head, next);
 194   }
 195   oop* handle = &_head->_data[_head->_size];
 196   NativeAccess<IS_DEST_UNINITIALIZED>::oop_store(handle, o);
 197   OrderAccess::release_store(&_head->_size, _head->_size + 1);
 198   return handle;
 199 }
 200 
 201 int ClassLoaderData::ChunkedHandleList::count() const {
 202   int count = 0;
 203   Chunk* chunk = _head;
 204   while (chunk != NULL) {
 205     count += chunk->_size;
 206     chunk = chunk->_next;
 207   }
 208   return count;
 209 }
 210 
 211 inline void ClassLoaderData::ChunkedHandleList::oops_do_chunk(OopClosure* f, Chunk* c, const juint size) {
 212   for (juint i = 0; i < size; i++) {
 213     if (c->_data[i] != NULL) {
 214       f->do_oop(&c->_data[i]);
 215     }
 216   }
 217 }
 218 
 219 void ClassLoaderData::ChunkedHandleList::oops_do(OopClosure* f) {
 220   Chunk* head = OrderAccess::load_acquire(&_head);
 221   if (head != NULL) {
 222     // Must be careful when reading size of head
 223     oops_do_chunk(f, head, OrderAccess::load_acquire(&head->_size));
 224     for (Chunk* c = head->_next; c != NULL; c = c->_next) {
 225       oops_do_chunk(f, c, c->_size);
 226     }
 227   }
 228 }
 229 
 230 class VerifyContainsOopClosure : public OopClosure {
 231   oop  _target;
 232   bool _found;
 233 
 234  public:
 235   VerifyContainsOopClosure(oop target) : _target(target), _found(false) {}
 236 
 237   void do_oop(oop* p) {
 238     if (p != NULL && oopDesc::equals(NativeAccess<AS_NO_KEEPALIVE>::oop_load(p), _target)) {
 239       _found = true;
 240     }
 241   }
 242 
 243   void do_oop(narrowOop* p) {
 244     // The ChunkedHandleList should not contain any narrowOop
 245     ShouldNotReachHere();
 246   }
 247 
 248   bool found() const {
 249     return _found;
 250   }
 251 };
 252 
 253 bool ClassLoaderData::ChunkedHandleList::contains(oop p) {
 254   VerifyContainsOopClosure cl(p);
 255   oops_do(&cl);
 256   return cl.found();
 257 }
 258 
 259 #ifndef PRODUCT
 260 bool ClassLoaderData::ChunkedHandleList::owner_of(oop* oop_handle) {
 261   Chunk* chunk = _head;
 262   while (chunk != NULL) {
 263     if (&(chunk->_data[0]) <= oop_handle && oop_handle < &(chunk->_data[chunk->_size])) {
 264       return true;
 265     }
 266     chunk = chunk->_next;
 267   }
 268   return false;
 269 }
 270 #endif // PRODUCT
 271 
 272 bool ClassLoaderData::try_claim(int claim) {
 273   for (;;) {
 274     int old_claim = Atomic::load(&_claim);
 275     if ((old_claim & claim) == claim) {
 276       return false;
 277     }
 278     int new_claim = old_claim | claim;
 279     if (Atomic::cmpxchg(new_claim, &_claim, old_claim) == old_claim) {
 280       return true;
 281     }
 282   }
 283 }
 284 
 285 // Unsafe anonymous classes have their own ClassLoaderData that is marked to keep alive
 286 // while the class is being parsed, and if the class appears on the module fixup list.
 287 // Due to the uniqueness that no other class shares the unsafe anonymous class' name or
 288 // ClassLoaderData, no other non-GC thread has knowledge of the unsafe anonymous class while
 289 // it is being defined, therefore _keep_alive is not volatile or atomic.
 290 void ClassLoaderData::inc_keep_alive() {
 291   if (is_unsafe_anonymous()) {
 292     assert(_keep_alive >= 0, "Invalid keep alive increment count");
 293     _keep_alive++;
 294   }
 295 }
 296 
 297 void ClassLoaderData::dec_keep_alive() {
 298   if (is_unsafe_anonymous()) {
 299     assert(_keep_alive > 0, "Invalid keep alive decrement count");
 300     _keep_alive--;
 301   }
 302 }
 303 
 304 void ClassLoaderData::oops_do(OopClosure* f, int claim_value, bool clear_mod_oops) {
 305   if (claim_value != ClassLoaderData::_claim_none && !try_claim(claim_value)) {
 306     return;
 307   }
 308 
 309   // Only clear modified_oops after the ClassLoaderData is claimed.
 310   if (clear_mod_oops) {
 311     clear_modified_oops();
 312   }
 313 
 314   _handles.oops_do(f);
 315 }
 316 
 317 void ClassLoaderData::classes_do(KlassClosure* klass_closure) {
 318   // Lock-free access requires load_acquire
 319   for (Klass* k = OrderAccess::load_acquire(&_klasses); k != NULL; k = k->next_link()) {
 320     klass_closure->do_klass(k);
 321     assert(k != k->next_link(), "no loops!");
 322   }
 323 }
 324 
 325 void ClassLoaderData::classes_do(void f(Klass * const)) {
 326   // Lock-free access requires load_acquire
 327   for (Klass* k = OrderAccess::load_acquire(&_klasses); k != NULL; k = k->next_link()) {
 328     f(k);
 329     assert(k != k->next_link(), "no loops!");
 330   }
 331 }
 332 
 333 void ClassLoaderData::methods_do(void f(Method*)) {
 334   // Lock-free access requires load_acquire
 335   for (Klass* k = OrderAccess::load_acquire(&_klasses); k != NULL; k = k->next_link()) {
 336     if (k->is_instance_klass() && InstanceKlass::cast(k)->is_loaded()) {
 337       InstanceKlass::cast(k)->methods_do(f);
 338     }
 339   }
 340 }
 341 
 342 void ClassLoaderData::loaded_classes_do(KlassClosure* klass_closure) {
 343   // Lock-free access requires load_acquire
 344   for (Klass* k = OrderAccess::load_acquire(&_klasses); k != NULL; k = k->next_link()) {
 345     // Do not filter ArrayKlass oops here...
 346     if (k->is_array_klass() || (k->is_instance_klass() && InstanceKlass::cast(k)->is_loaded())) {
 347 #ifdef ASSERT
 348       oop m = k->java_mirror();
 349       assert(m != NULL, "NULL mirror");
 350       assert(m->is_a(SystemDictionary::Class_klass()), "invalid mirror");
 351 #endif
 352       klass_closure->do_klass(k);
 353     }
 354   }
 355 }
 356 
 357 void ClassLoaderData::classes_do(void f(InstanceKlass*)) {
 358   // Lock-free access requires load_acquire
 359   for (Klass* k = OrderAccess::load_acquire(&_klasses); k != NULL; k = k->next_link()) {
 360     if (k->is_instance_klass()) {
 361       f(InstanceKlass::cast(k));
 362     }
 363     assert(k != k->next_link(), "no loops!");
 364   }
 365 }
 366 
 367 void ClassLoaderData::value_classes_do(void f(ValueKlass*)) {
 368   // Lock-free access requires load_acquire
 369   for (Klass* k = OrderAccess::load_acquire(&_klasses); k != NULL; k = k->next_link()) {
 370     if (k->is_value()) {
 371       f(ValueKlass::cast(k));
 372     }
 373     assert(k != k->next_link(), "no loops!");
 374   }
 375 }
 376 
 377 void ClassLoaderData::modules_do(void f(ModuleEntry*)) {
 378   assert_locked_or_safepoint(Module_lock);
 379   if (_unnamed_module != NULL) {
 380     f(_unnamed_module);
 381   }
 382   if (_modules != NULL) {
 383     for (int i = 0; i < _modules->table_size(); i++) {
 384       for (ModuleEntry* entry = _modules->bucket(i);
 385            entry != NULL;
 386            entry = entry->next()) {
 387         f(entry);
 388       }
 389     }
 390   }
 391 }
 392 
 393 void ClassLoaderData::packages_do(void f(PackageEntry*)) {
 394   assert_locked_or_safepoint(Module_lock);
 395   if (_packages != NULL) {
 396     for (int i = 0; i < _packages->table_size(); i++) {
 397       for (PackageEntry* entry = _packages->bucket(i);
 398            entry != NULL;
 399            entry = entry->next()) {
 400         f(entry);
 401       }
 402     }
 403   }
 404 }
 405 
 406 void ClassLoaderData::record_dependency(const Klass* k) {
 407   assert(k != NULL, "invariant");
 408 
 409   ClassLoaderData * const from_cld = this;
 410   ClassLoaderData * const to_cld = k->class_loader_data();
 411 
 412   // Do not need to record dependency if the dependency is to a class whose
 413   // class loader data is never freed.  (i.e. the dependency's class loader
 414   // is one of the three builtin class loaders and the dependency is not
 415   // unsafe anonymous.)
 416   if (to_cld->is_permanent_class_loader_data()) {
 417     return;
 418   }
 419 
 420   oop to;
 421   if (to_cld->is_unsafe_anonymous()) {
 422     // Just return if an unsafe anonymous class is attempting to record a dependency
 423     // to itself.  (Note that every unsafe anonymous class has its own unique class
 424     // loader data.)
 425     if (to_cld == from_cld) {
 426       return;
 427     }
 428     // Unsafe anonymous class dependencies are through the mirror.
 429     to = k->java_mirror();
 430   } else {
 431     to = to_cld->class_loader();
 432     oop from = from_cld->class_loader();
 433 
 434     // Just return if this dependency is to a class with the same or a parent
 435     // class_loader.
 436     if (oopDesc::equals(from, to) || java_lang_ClassLoader::isAncestor(from, to)) {
 437       return; // this class loader is in the parent list, no need to add it.
 438     }
 439   }
 440 
 441   // It's a dependency we won't find through GC, add it.
 442   if (!_handles.contains(to)) {
 443     NOT_PRODUCT(Atomic::inc(&_dependency_count));
 444     LogTarget(Trace, class, loader, data) lt;
 445     if (lt.is_enabled()) {
 446       ResourceMark rm;
 447       LogStream ls(lt);
 448       ls.print("adding dependency from ");
 449       print_value_on(&ls);
 450       ls.print(" to ");
 451       to_cld->print_value_on(&ls);
 452       ls.cr();
 453     }
 454     Handle dependency(Thread::current(), to);
 455     add_handle(dependency);
 456     // Added a potentially young gen oop to the ClassLoaderData
 457     record_modified_oops();
 458   }
 459 }
 460 
 461 void ClassLoaderData::add_class(Klass* k, bool publicize /* true */) {
 462   {
 463     MutexLockerEx ml(metaspace_lock(), Mutex::_no_safepoint_check_flag);
 464     Klass* old_value = _klasses;
 465     k->set_next_link(old_value);
 466     // Link the new item into the list, making sure the linked class is stable
 467     // since the list can be walked without a lock
 468     OrderAccess::release_store(&_klasses, k);
 469     if (k->is_array_klass()) {
 470       ClassLoaderDataGraph::inc_array_classes(1);
 471     } else {
 472       ClassLoaderDataGraph::inc_instance_classes(1);
 473     }
 474   }
 475 
 476   if (publicize) {
 477     LogTarget(Trace, class, loader, data) lt;
 478     if (lt.is_enabled()) {
 479       ResourceMark rm;
 480       LogStream ls(lt);
 481       ls.print("Adding k: " PTR_FORMAT " %s to ", p2i(k), k->external_name());
 482       print_value_on(&ls);
 483       ls.cr();
 484     }
 485   }
 486 }
 487 
 488 void ClassLoaderData::initialize_holder(Handle loader_or_mirror) {
 489   if (loader_or_mirror() != NULL) {
 490     assert(_holder.is_null(), "never replace holders");
 491     _holder = WeakHandle<vm_class_loader_data>::create(loader_or_mirror);
 492   }
 493 }
 494 
 495 // Remove a klass from the _klasses list for scratch_class during redefinition
 496 // or parsed class in the case of an error.
 497 void ClassLoaderData::remove_class(Klass* scratch_class) {
 498   assert_locked_or_safepoint(ClassLoaderDataGraph_lock);
 499 
 500   // Adjust global class iterator.
 501   ClassLoaderDataGraph::adjust_saved_class(scratch_class);
 502 
 503   Klass* prev = NULL;
 504   for (Klass* k = _klasses; k != NULL; k = k->next_link()) {
 505     if (k == scratch_class) {
 506       if (prev == NULL) {
 507         _klasses = k->next_link();
 508       } else {
 509         Klass* next = k->next_link();
 510         prev->set_next_link(next);
 511       }
 512 
 513       if (k->is_array_klass()) {
 514         ClassLoaderDataGraph::dec_array_classes(1);
 515       } else {
 516         ClassLoaderDataGraph::dec_instance_classes(1);
 517       }
 518 
 519       return;
 520     }
 521     prev = k;
 522     assert(k != k->next_link(), "no loops!");
 523   }
 524   ShouldNotReachHere();   // should have found this class!!
 525 }
 526 
 527 void ClassLoaderData::unload() {
 528   _unloading = true;
 529 
 530   LogTarget(Trace, class, loader, data) lt;
 531   if (lt.is_enabled()) {
 532     ResourceMark rm;
 533     LogStream ls(lt);
 534     ls.print("unload");
 535     print_value_on(&ls);
 536     ls.cr();
 537   }
 538 
 539   // Some items on the _deallocate_list need to free their C heap structures
 540   // if they are not already on the _klasses list.
 541   free_deallocate_list_C_heap_structures();
 542 
 543   value_classes_do(ValueKlass::cleanup);
 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 = OrderAccess::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         MutexLockerEx m1(metaspace_lock(), Mutex::_no_safepoint_check_flag);
 566         // Ensure _modules is stable, since it is examined without a lock
 567         OrderAccess::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(!is_unsafe_anonymous(), "unsafe anonymous class loader data do 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 unsafe anonymous klasses.
 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       InstanceKlass::release_C_heap_structures(InstanceKlass::cast(k));
 647     }
 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();
 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 be unsafe anonymous.)
 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 be unsafe anonymous.)
 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 an unsafe anonymous class then it may get freed by a GC
 737 // 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 an unsafe anonymous class.
 747 bool ClassLoaderData::is_permanent_class_loader_data() const {
 748   return is_builtin_class_loader_data() && !is_unsafe_anonymous();
 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 = OrderAccess::load_acquire(&_metaspace);
 758   if (metaspace == NULL) {
 759     MutexLockerEx 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 (is_unsafe_anonymous()) {
 766         metaspace = new ClassLoaderMetaspace(_metaspace_lock, Metaspace::UnsafeAnonymousMetaspaceType);
 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       OrderAccess::release_store(&_metaspace, metaspace);
 774     }
 775   }
 776   return metaspace;
 777 }
 778 
 779 OopHandle ClassLoaderData::add_handle(Handle h) {
 780   MutexLockerEx ml(metaspace_lock(),  Mutex::_no_safepoint_check_flag);
 781   record_modified_oops();
 782   return OopHandle(_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   MutexLockerEx 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     MutexLockerEx ml(metaspace_lock(),  Mutex::_no_safepoint_check_flag);
 809     if (_deallocate_list == NULL) {
 810       _deallocate_list = new (ResourceObj::C_HEAP, mtClass) GrowableArray<Metadata*>(100, true);
 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         if (!((Klass*)m)->is_value()) {
 840           MetadataFactory::free_metadata(this, (InstanceKlass*)m);
 841         } else {
 842           MetadataFactory::free_metadata(this, (ValueKlass*)m);
 843         }
 844       } else {
 845         ShouldNotReachHere();
 846       }
 847     } else {
 848       // Metadata is alive.
 849       // If scratch_class is on stack then it shouldn't be on this list!
 850       assert(!m->is_klass() || !((InstanceKlass*)m)->is_scratch_class(),
 851              "scratch classes on this list should be dead");
 852       // Also should assert that other metadata on the list was found in handles.
 853       // Some cleaning remains.
 854       ClassLoaderDataGraph::set_should_clean_deallocate_lists();
 855     }
 856   }
 857 }
 858 
 859 // This is distinct from free_deallocate_list.  For class loader data that are
 860 // unloading, this frees the C heap memory for items on the list, and unlinks
 861 // scratch or error classes so that unloading events aren't triggered for these
 862 // classes. The metadata is removed with the unloading metaspace.
 863 // There isn't C heap memory allocated for methods, so nothing is done for them.
 864 void ClassLoaderData::free_deallocate_list_C_heap_structures() {
 865   assert_locked_or_safepoint(ClassLoaderDataGraph_lock);
 866   assert(is_unloading(), "only called for ClassLoaderData that are unloading");
 867   if (_deallocate_list == NULL) {
 868     return;
 869   }
 870   // Go backwards because this removes entries that are freed.
 871   for (int i = _deallocate_list->length() - 1; i >= 0; i--) {
 872     Metadata* m = _deallocate_list->at(i);
 873     _deallocate_list->remove_at(i);
 874     if (m->is_constantPool()) {
 875       ((ConstantPool*)m)->release_C_heap_structures();
 876     } else if (m->is_klass()) {
 877       InstanceKlass* ik = (InstanceKlass*)m;
 878       // also releases ik->constants() C heap memory
 879       InstanceKlass::release_C_heap_structures(ik);
 880       // Remove the class so unloading events aren't triggered for
 881       // this class (scratch or error class) in do_unloading().
 882       remove_class(ik);
 883     }
 884   }
 885 }
 886 
 887 // These CLDs are to contain unsafe anonymous classes used for JSR292
 888 ClassLoaderData* ClassLoaderData::unsafe_anonymous_class_loader_data(Handle loader) {
 889   // Add a new class loader data to the graph.
 890   return ClassLoaderDataGraph::add(loader, true);
 891 }
 892 
 893 // Caller needs ResourceMark
 894 // If the class loader's _name has not been explicitly set, the class loader's
 895 // qualified class name is returned.
 896 const char* ClassLoaderData::loader_name() const {
 897    if (_class_loader_klass == NULL) {
 898      return BOOTSTRAP_LOADER_NAME;
 899    } else if (_name != NULL) {
 900      return _name->as_C_string();
 901    } else {
 902      return _class_loader_klass->external_name();
 903    }
 904 }
 905 
 906 // Caller needs ResourceMark
 907 // Format of the _name_and_id is as follows:
 908 //   If the defining loader has a name explicitly set then '<loader-name>' @<id>
 909 //   If the defining loader has no name then <qualified-class-name> @<id>
 910 //   If built-in loader, then omit '@<id>' as there is only one instance.
 911 const char* ClassLoaderData::loader_name_and_id() const {
 912   if (_class_loader_klass == NULL) {
 913     return "'" BOOTSTRAP_LOADER_NAME "'";
 914   } else if (_name_and_id != NULL) {
 915     return _name_and_id->as_C_string();
 916   } else {
 917     // May be called in a race before _name_and_id is initialized.
 918     return _class_loader_klass->external_name();
 919   }
 920 }
 921 
 922 void ClassLoaderData::print_value_on(outputStream* out) const {
 923   if (!is_unloading() && class_loader() != NULL) {
 924     out->print("loader data: " INTPTR_FORMAT " for instance ", p2i(this));
 925     class_loader()->print_value_on(out);  // includes loader_name_and_id() and address of class loader instance
 926   } else {
 927     // loader data: 0xsomeaddr of 'bootstrap'
 928     out->print("loader data: " INTPTR_FORMAT " of %s", p2i(this), loader_name_and_id());
 929   }
 930   if (is_unsafe_anonymous()) {
 931     out->print(" unsafe anonymous");
 932   }
 933 }
 934 
 935 #ifndef PRODUCT
 936 void ClassLoaderData::print_on(outputStream* out) const {
 937   out->print("ClassLoaderData CLD: " PTR_FORMAT ", loader: " PTR_FORMAT ", loader_klass: %s {",
 938               p2i(this), p2i(_class_loader.ptr_raw()), loader_name_and_id());
 939   if (is_unsafe_anonymous()) out->print(" unsafe anonymous");
 940   if (claimed()) out->print(" claimed");
 941   if (is_unloading()) out->print(" unloading");
 942   out->print(" metaspace: " INTPTR_FORMAT, p2i(metaspace_or_null()));
 943 
 944   if (_jmethod_ids != NULL) {
 945     Method::print_jmethod_ids(this, out);
 946   }
 947   out->print(" handles count %d", _handles.count());
 948   out->print(" dependencies %d", _dependency_count);
 949   out->print_cr("}");
 950 }
 951 #endif // PRODUCT
 952 
 953 void ClassLoaderData::verify() {
 954   assert_locked_or_safepoint(_metaspace_lock);
 955   oop cl = class_loader();
 956 
 957   guarantee(this == class_loader_data(cl) || is_unsafe_anonymous(), "Must be the same");
 958   guarantee(cl != NULL || this == ClassLoaderData::the_null_class_loader_data() || is_unsafe_anonymous(), "must be");
 959 
 960   // Verify the integrity of the allocated space.
 961   if (metaspace_or_null() != NULL) {
 962     metaspace_or_null()->verify();
 963   }
 964 
 965   for (Klass* k = _klasses; k != NULL; k = k->next_link()) {
 966     guarantee(k->class_loader_data() == this, "Must be the same");
 967     k->verify();
 968     assert(k != k->next_link(), "no loops!");
 969   }
 970 }
 971 
 972 bool ClassLoaderData::contains_klass(Klass* klass) {
 973   // Lock-free access requires load_acquire
 974   for (Klass* k = OrderAccess::load_acquire(&_klasses); k != NULL; k = k->next_link()) {
 975     if (k == klass) return true;
 976   }
 977   return false;
 978 }