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