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