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