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