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