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