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