1  /*
   2  * Copyright (c) 2012, 2018, 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.hpp"
  51 #include "classfile/classLoaderData.inline.hpp"
  52 #include "classfile/dictionary.hpp"
  53 #include "classfile/javaClasses.hpp"
  54 #include "classfile/metadataOnStackMark.hpp"
  55 #include "classfile/moduleEntry.hpp"
  56 #include "classfile/packageEntry.hpp"
  57 #include "classfile/symbolTable.hpp"
  58 #include "classfile/systemDictionary.hpp"
  59 #include "logging/log.hpp"
  60 #include "logging/logStream.hpp"
  61 #include "memory/allocation.inline.hpp"
  62 #include "memory/metadataFactory.hpp"
  63 #include "memory/metaspaceShared.hpp"
  64 #include "memory/resourceArea.hpp"
  65 #include "memory/universe.hpp"
  66 #include "oops/access.inline.hpp"
  67 #include "oops/oop.inline.hpp"
  68 #include "oops/oopHandle.inline.hpp"
  69 #include "oops/weakHandle.inline.hpp"
  70 #include "runtime/atomic.hpp"
  71 #include "runtime/handles.inline.hpp"
  72 #include "runtime/mutex.hpp"
  73 #include "runtime/orderAccess.hpp"
  74 #include "runtime/safepoint.hpp"
  75 #include "runtime/safepointVerifiers.hpp"
  76 #include "utilities/growableArray.hpp"
  77 #include "utilities/macros.hpp"
  78 #include "utilities/ostream.hpp"
  79 #include "utilities/ticks.hpp"
  80 #if INCLUDE_JFR
  81 #include "jfr/jfr.hpp"
  82 #include "jfr/jfrEvents.hpp"
  83 #endif
  84 
  85 volatile size_t ClassLoaderDataGraph::_num_array_classes = 0;
  86 volatile size_t ClassLoaderDataGraph::_num_instance_classes = 0;
  87 
  88 ClassLoaderData * ClassLoaderData::_the_null_class_loader_data = NULL;
  89 
  90 void ClassLoaderData::init_null_class_loader_data() {
  91   assert(_the_null_class_loader_data == NULL, "cannot initialize twice");
  92   assert(ClassLoaderDataGraph::_head == NULL, "cannot initialize twice");
  93 
  94   _the_null_class_loader_data = new ClassLoaderData(Handle(), false);
  95   ClassLoaderDataGraph::_head = _the_null_class_loader_data;
  96   assert(_the_null_class_loader_data->is_the_null_class_loader_data(), "Must be");
  97 
  98   LogTarget(Debug, class, loader, data) lt;
  99   if (lt.is_enabled()) {
 100     ResourceMark rm;
 101     LogStream ls(lt);
 102     ls.print("create ");
 103     _the_null_class_loader_data->print_value_on(&ls);
 104     ls.cr();
 105   }
 106 }
 107 
 108 // Obtain and set the class loader's name within the ClassLoaderData so
 109 // it will be available for error messages, logging, JFR, etc.  The name
 110 // and klass are available after the class_loader oop is no longer alive,
 111 // during unloading.
 112 void ClassLoaderData::initialize_name(Handle class_loader) {
 113   Thread* THREAD = Thread::current();
 114   ResourceMark rm(THREAD);
 115 
 116   // Obtain the class loader's name.  If the class loader's name was not
 117   // explicitly set during construction, the CLD's _name field will be null.
 118   oop cl_name = java_lang_ClassLoader::name(class_loader());
 119   if (cl_name != NULL) {
 120     const char* cl_instance_name = java_lang_String::as_utf8_string(cl_name);
 121 
 122     if (cl_instance_name != NULL && cl_instance_name[0] != '\0') {
 123       // Can't throw InternalError and SymbolTable doesn't throw OOM anymore.
 124       _name = SymbolTable::new_symbol(cl_instance_name, CATCH);
 125     }
 126   }
 127 
 128   // Obtain the class loader's name and identity hash.  If the class loader's
 129   // name was not explicitly set during construction, the class loader's name and id
 130   // will be set to the qualified class name of the class loader along with its
 131   // identity hash.
 132   // If for some reason the ClassLoader's constructor has not been run, instead of
 133   // leaving the _name_and_id field null, fall back to the external qualified class
 134   // name.  Thus CLD's _name_and_id field should never have a null value.
 135   oop cl_name_and_id = java_lang_ClassLoader::nameAndId(class_loader());
 136   const char* cl_instance_name_and_id =
 137                   (cl_name_and_id == NULL) ? _class_loader_klass->external_name() :
 138                                              java_lang_String::as_utf8_string(cl_name_and_id);
 139   assert(cl_instance_name_and_id != NULL && cl_instance_name_and_id[0] != '\0', "class loader has no name and id");
 140   // Can't throw InternalError and SymbolTable doesn't throw OOM anymore.
 141   _name_and_id = SymbolTable::new_symbol(cl_instance_name_and_id, CATCH);
 142 }
 143 
 144 ClassLoaderData::ClassLoaderData(Handle h_class_loader, bool is_anonymous) :
 145   _is_anonymous(is_anonymous),
 146   // An anonymous class loader data doesn't have anything to keep
 147   // it from being unloaded during parsing of the anonymous class.
 148   // The null-class-loader should always be kept alive.
 149   _keep_alive((is_anonymous || h_class_loader.is_null()) ? 1 : 0),
 150   _metaspace(NULL), _unloading(false), _klasses(NULL),
 151   _modules(NULL), _packages(NULL), _unnamed_module(NULL), _dictionary(NULL),
 152   _claimed(0), _modified_oops(true), _accumulated_modified_oops(false),
 153   _jmethod_ids(NULL), _handles(), _deallocate_list(NULL),
 154   _next(NULL),
 155   _class_loader_klass(NULL), _name(NULL), _name_and_id(NULL),
 156   _metaspace_lock(new Mutex(Monitor::leaf+1, "Metaspace allocation lock", true,
 157                             Monitor::_safepoint_check_never)) {
 158 
 159   if (!h_class_loader.is_null()) {
 160     _class_loader = _handles.add(h_class_loader());
 161     _class_loader_klass = h_class_loader->klass();
 162   }
 163 
 164   if (!is_anonymous) {
 165     // The holder is initialized later for anonymous classes, and before calling anything
 166     // that call class_loader().
 167     initialize_holder(h_class_loader);
 168 
 169     // A ClassLoaderData created solely for an anonymous class should never have a
 170     // ModuleEntryTable or PackageEntryTable created for it. The defining package
 171     // and module for an anonymous class will be found in its host class.
 172     _packages = new PackageEntryTable(PackageEntryTable::_packagetable_entry_size);
 173     if (h_class_loader.is_null()) {
 174       // Create unnamed module for boot loader
 175       _unnamed_module = ModuleEntry::create_boot_unnamed_module(this);
 176     } else {
 177       // Create unnamed module for all other loaders
 178       _unnamed_module = ModuleEntry::create_unnamed_module(this);
 179     }
 180     _dictionary = create_dictionary();
 181   }
 182 
 183   NOT_PRODUCT(_dependency_count = 0); // number of class loader dependencies
 184 
 185   JFR_ONLY(INIT_ID(this);)
 186 }
 187 
 188 ClassLoaderData::ChunkedHandleList::~ChunkedHandleList() {
 189   Chunk* c = _head;
 190   while (c != NULL) {
 191     Chunk* next = c->_next;
 192     delete c;
 193     c = next;
 194   }
 195 }
 196 
 197 oop* ClassLoaderData::ChunkedHandleList::add(oop o) {
 198   if (_head == NULL || _head->_size == Chunk::CAPACITY) {
 199     Chunk* next = new Chunk(_head);
 200     OrderAccess::release_store(&_head, next);
 201   }
 202   oop* handle = &_head->_data[_head->_size];
 203   *handle = o;
 204   OrderAccess::release_store(&_head->_size, _head->_size + 1);
 205   return handle;
 206 }
 207 
 208 int ClassLoaderData::ChunkedHandleList::count() const {
 209   int count = 0;
 210   Chunk* chunk = _head;
 211   while (chunk != NULL) {
 212     count += chunk->_size;
 213     chunk = chunk->_next;
 214   }
 215   return count;
 216 }
 217 
 218 inline void ClassLoaderData::ChunkedHandleList::oops_do_chunk(OopClosure* f, Chunk* c, const juint size) {
 219   for (juint i = 0; i < size; i++) {
 220     if (c->_data[i] != NULL) {
 221       f->do_oop(&c->_data[i]);
 222     }
 223   }
 224 }
 225 
 226 void ClassLoaderData::ChunkedHandleList::oops_do(OopClosure* f) {
 227   Chunk* head = OrderAccess::load_acquire(&_head);
 228   if (head != NULL) {
 229     // Must be careful when reading size of head
 230     oops_do_chunk(f, head, OrderAccess::load_acquire(&head->_size));
 231     for (Chunk* c = head->_next; c != NULL; c = c->_next) {
 232       oops_do_chunk(f, c, c->_size);
 233     }
 234   }
 235 }
 236 
 237 class VerifyContainsOopClosure : public OopClosure {
 238   oop  _target;
 239   bool _found;
 240 
 241  public:
 242   VerifyContainsOopClosure(oop target) : _target(target), _found(false) {}
 243 
 244   void do_oop(oop* p) {
 245     if (p != NULL && oopDesc::equals(RawAccess<>::oop_load(p), _target)) {
 246       _found = true;
 247     }
 248   }
 249 
 250   void do_oop(narrowOop* p) {
 251     // The ChunkedHandleList should not contain any narrowOop
 252     ShouldNotReachHere();
 253   }
 254 
 255   bool found() const {
 256     return _found;
 257   }
 258 };
 259 
 260 bool ClassLoaderData::ChunkedHandleList::contains(oop p) {
 261   VerifyContainsOopClosure cl(p);
 262   oops_do(&cl);
 263   return cl.found();
 264 }
 265 
 266 #ifndef PRODUCT
 267 bool ClassLoaderData::ChunkedHandleList::owner_of(oop* oop_handle) {
 268   Chunk* chunk = _head;
 269   while (chunk != NULL) {
 270     if (&(chunk->_data[0]) <= oop_handle && oop_handle < &(chunk->_data[chunk->_size])) {
 271       return true;
 272     }
 273     chunk = chunk->_next;
 274   }
 275   return false;
 276 }
 277 #endif // PRODUCT
 278 
 279 bool ClassLoaderData::claim() {
 280   if (_claimed == 1) {
 281     return false;
 282   }
 283 
 284   return (int) Atomic::cmpxchg(1, &_claimed, 0) == 0;
 285 }
 286 
 287 // Anonymous classes have their own ClassLoaderData that is marked to keep alive
 288 // while the class is being parsed, and if the class appears on the module fixup list.
 289 // Due to the uniqueness that no other class shares the anonymous class' name or
 290 // ClassLoaderData, no other non-GC thread has knowledge of the anonymous class while
 291 // it is being defined, therefore _keep_alive is not volatile or atomic.
 292 void ClassLoaderData::inc_keep_alive() {
 293   if (is_anonymous()) {
 294     assert(_keep_alive >= 0, "Invalid keep alive increment count");
 295     _keep_alive++;
 296   }
 297 }
 298 
 299 void ClassLoaderData::dec_keep_alive() {
 300   if (is_anonymous()) {
 301     assert(_keep_alive > 0, "Invalid keep alive decrement count");
 302     _keep_alive--;
 303   }
 304 }
 305 
 306 void ClassLoaderData::oops_do(OopClosure* f, bool must_claim, bool clear_mod_oops) {
 307   if (must_claim && !claim()) {
 308     return;
 309   }
 310 
 311   // Only clear modified_oops after the ClassLoaderData is claimed.
 312   if (clear_mod_oops) {
 313     clear_modified_oops();
 314   }
 315 
 316   _handles.oops_do(f);
 317 }
 318 
 319 void ClassLoaderData::classes_do(KlassClosure* klass_closure) {
 320   // Lock-free access requires load_acquire
 321   for (Klass* k = OrderAccess::load_acquire(&_klasses); k != NULL; k = k->next_link()) {
 322     klass_closure->do_klass(k);
 323     assert(k != k->next_link(), "no loops!");
 324   }
 325 }
 326 
 327 void ClassLoaderData::classes_do(void f(Klass * const)) {
 328   // Lock-free access requires load_acquire
 329   for (Klass* k = OrderAccess::load_acquire(&_klasses); k != NULL; k = k->next_link()) {
 330     f(k);
 331     assert(k != k->next_link(), "no loops!");
 332   }
 333 }
 334 
 335 void ClassLoaderData::methods_do(void f(Method*)) {
 336   // Lock-free access requires load_acquire
 337   for (Klass* k = OrderAccess::load_acquire(&_klasses); k != NULL; k = k->next_link()) {
 338     if (k->is_instance_klass() && InstanceKlass::cast(k)->is_loaded()) {
 339       InstanceKlass::cast(k)->methods_do(f);
 340     }
 341   }
 342 }
 343 
 344 void ClassLoaderData::loaded_classes_do(KlassClosure* klass_closure) {
 345   // Lock-free access requires load_acquire
 346   for (Klass* k = OrderAccess::load_acquire(&_klasses); k != NULL; k = k->next_link()) {
 347     // Do not filter ArrayKlass oops here...
 348     if (k->is_array_klass() || (k->is_instance_klass() && InstanceKlass::cast(k)->is_loaded())) {
 349 #ifdef ASSERT
 350       oop m = k->java_mirror();
 351       assert(m != NULL, "NULL mirror");
 352       assert(m->is_a(SystemDictionary::Class_klass()), "invalid mirror");
 353 #endif
 354       klass_closure->do_klass(k);
 355     }
 356   }
 357 }
 358 
 359 void ClassLoaderData::classes_do(void f(InstanceKlass*)) {
 360   // Lock-free access requires load_acquire
 361   for (Klass* k = OrderAccess::load_acquire(&_klasses); k != NULL; k = k->next_link()) {
 362     if (k->is_instance_klass()) {
 363       f(InstanceKlass::cast(k));
 364     }
 365     assert(k != k->next_link(), "no loops!");
 366   }
 367 }
 368 
 369 void ClassLoaderData::modules_do(void f(ModuleEntry*)) {
 370   assert_locked_or_safepoint(Module_lock);
 371   if (_unnamed_module != NULL) {
 372     f(_unnamed_module);
 373   }
 374   if (_modules != NULL) {
 375     for (int i = 0; i < _modules->table_size(); i++) {
 376       for (ModuleEntry* entry = _modules->bucket(i);
 377            entry != NULL;
 378            entry = entry->next()) {
 379         f(entry);
 380       }
 381     }
 382   }
 383 }
 384 
 385 void ClassLoaderData::packages_do(void f(PackageEntry*)) {
 386   assert_locked_or_safepoint(Module_lock);
 387   if (_packages != NULL) {
 388     for (int i = 0; i < _packages->table_size(); i++) {
 389       for (PackageEntry* entry = _packages->bucket(i);
 390            entry != NULL;
 391            entry = entry->next()) {
 392         f(entry);
 393       }
 394     }
 395   }
 396 }
 397 
 398 void ClassLoaderData::record_dependency(const Klass* k) {
 399   assert(k != NULL, "invariant");
 400 
 401   ClassLoaderData * const from_cld = this;
 402   ClassLoaderData * const to_cld = k->class_loader_data();
 403 
 404   // Do not need to record dependency if the dependency is to a class whose
 405   // class loader data is never freed.  (i.e. the dependency's class loader
 406   // is one of the three builtin class loaders and the dependency is not
 407   // anonymous.)
 408   if (to_cld->is_permanent_class_loader_data()) {
 409     return;
 410   }
 411 
 412   oop to;
 413   if (to_cld->is_anonymous()) {
 414     // Just return if an anonymous class is attempting to record a dependency
 415     // to itself.  (Note that every anonymous class has its own unique class
 416     // loader data.)
 417     if (to_cld == from_cld) {
 418       return;
 419     }
 420     // Anonymous class dependencies are through the mirror.
 421     to = k->java_mirror();
 422   } else {
 423     to = to_cld->class_loader();
 424     oop from = from_cld->class_loader();
 425 
 426     // Just return if this dependency is to a class with the same or a parent
 427     // class_loader.
 428     if (oopDesc::equals(from, to) || java_lang_ClassLoader::isAncestor(from, to)) {
 429       return; // this class loader is in the parent list, no need to add it.
 430     }
 431   }
 432 
 433   // It's a dependency we won't find through GC, add it.
 434   if (!_handles.contains(to)) {
 435     NOT_PRODUCT(Atomic::inc(&_dependency_count));
 436     LogTarget(Trace, class, loader, data) lt;
 437     if (lt.is_enabled()) {
 438       ResourceMark rm;
 439       LogStream ls(lt);
 440       ls.print("adding dependency from ");
 441       print_value_on(&ls);
 442       ls.print(" to ");
 443       to_cld->print_value_on(&ls);
 444       ls.cr();
 445     }
 446     Handle dependency(Thread::current(), to);
 447     add_handle(dependency);
 448     // Added a potentially young gen oop to the ClassLoaderData
 449     record_modified_oops();
 450   }
 451 }
 452 
 453 
 454 void ClassLoaderDataGraph::clear_claimed_marks() {
 455   for (ClassLoaderData* cld = _head; cld != NULL; cld = cld->next()) {
 456     cld->clear_claimed();
 457   }
 458 }
 459 
 460 void ClassLoaderData::add_class(Klass* k, bool publicize /* true */) {
 461   {
 462     MutexLockerEx ml(metaspace_lock(), Mutex::_no_safepoint_check_flag);
 463     Klass* old_value = _klasses;
 464     k->set_next_link(old_value);
 465     // Link the new item into the list, making sure the linked class is stable
 466     // since the list can be walked without a lock
 467     OrderAccess::release_store(&_klasses, k);
 468     if (k->is_array_klass()) {
 469       ClassLoaderDataGraph::inc_array_classes(1);
 470     } else {
 471       ClassLoaderDataGraph::inc_instance_classes(1);
 472     }
 473   }
 474 
 475   if (publicize) {
 476     LogTarget(Trace, class, loader, data) lt;
 477     if (lt.is_enabled()) {
 478       ResourceMark rm;
 479       LogStream ls(lt);
 480       ls.print("Adding k: " PTR_FORMAT " %s to ", p2i(k), k->external_name());
 481       print_value_on(&ls);
 482       ls.cr();
 483     }
 484   }
 485 }
 486 
 487 // Class iterator used by the compiler.  It gets some number of classes at
 488 // a safepoint to decay invocation counters on the methods.
 489 class ClassLoaderDataGraphKlassIteratorStatic {
 490   ClassLoaderData* _current_loader_data;
 491   Klass*           _current_class_entry;
 492  public:
 493 
 494   ClassLoaderDataGraphKlassIteratorStatic() : _current_loader_data(NULL), _current_class_entry(NULL) {}
 495 
 496   InstanceKlass* try_get_next_class() {
 497     assert(SafepointSynchronize::is_at_safepoint(), "only called at safepoint");
 498     size_t max_classes = ClassLoaderDataGraph::num_instance_classes();
 499     assert(max_classes > 0, "should not be called with no instance classes");
 500     for (size_t i = 0; i < max_classes; ) {
 501 
 502       if (_current_class_entry != NULL) {
 503         Klass* k = _current_class_entry;
 504         _current_class_entry = _current_class_entry->next_link();
 505 
 506         if (k->is_instance_klass()) {
 507           InstanceKlass* ik = InstanceKlass::cast(k);
 508           i++;  // count all instance classes found
 509           // Not yet loaded classes are counted in max_classes
 510           // but only return loaded classes.
 511           if (ik->is_loaded()) {
 512             return ik;
 513           }
 514         }
 515       } else {
 516         // Go to next CLD
 517         if (_current_loader_data != NULL) {
 518           _current_loader_data = _current_loader_data->next();
 519         }
 520         // Start at the beginning
 521         if (_current_loader_data == NULL) {
 522           _current_loader_data = ClassLoaderDataGraph::_head;
 523         }
 524 
 525         _current_class_entry = _current_loader_data->klasses();
 526       }
 527     }
 528     // Should never be reached unless all instance classes have failed or are not fully loaded.
 529     // Caller handles NULL.
 530     return NULL;
 531   }
 532 
 533   // If the current class for the static iterator is a class being unloaded or
 534   // deallocated, adjust the current class.
 535   void adjust_saved_class(ClassLoaderData* cld) {
 536     if (_current_loader_data == cld) {
 537       _current_loader_data = cld->next();
 538       if (_current_loader_data != NULL) {
 539         _current_class_entry = _current_loader_data->klasses();
 540       }  // else try_get_next_class will start at the head
 541     }
 542   }
 543 
 544   void adjust_saved_class(Klass* klass) {
 545     if (_current_class_entry == klass) {
 546       _current_class_entry = klass->next_link();
 547     }
 548   }
 549 };
 550 
 551 static ClassLoaderDataGraphKlassIteratorStatic static_klass_iterator;
 552 
 553 InstanceKlass* ClassLoaderDataGraph::try_get_next_class() {
 554   return static_klass_iterator.try_get_next_class();
 555 }
 556 
 557 
 558 void ClassLoaderData::initialize_holder(Handle loader_or_mirror) {
 559   if (loader_or_mirror() != NULL) {
 560     assert(_holder.is_null(), "never replace holders");
 561     _holder = WeakHandle<vm_class_loader_data>::create(loader_or_mirror);
 562   }
 563 }
 564 
 565 // Remove a klass from the _klasses list for scratch_class during redefinition
 566 // or parsed class in the case of an error.
 567 void ClassLoaderData::remove_class(Klass* scratch_class) {
 568   assert(SafepointSynchronize::is_at_safepoint(), "only called at safepoint");
 569 
 570   // Adjust global class iterator.
 571   static_klass_iterator.adjust_saved_class(scratch_class);
 572 
 573   Klass* prev = NULL;
 574   for (Klass* k = _klasses; k != NULL; k = k->next_link()) {
 575     if (k == scratch_class) {
 576       if (prev == NULL) {
 577         _klasses = k->next_link();
 578       } else {
 579         Klass* next = k->next_link();
 580         prev->set_next_link(next);
 581       }
 582 
 583       if (k->is_array_klass()) {
 584         ClassLoaderDataGraph::dec_array_classes(1);
 585       } else {
 586         ClassLoaderDataGraph::dec_instance_classes(1);
 587       }
 588 
 589       return;
 590     }
 591     prev = k;
 592     assert(k != k->next_link(), "no loops!");
 593   }
 594   ShouldNotReachHere();   // should have found this class!!
 595 }
 596 
 597 void ClassLoaderData::unload() {
 598   _unloading = true;
 599 
 600   LogTarget(Debug, class, loader, data) lt;
 601   if (lt.is_enabled()) {
 602     ResourceMark rm;
 603     LogStream ls(lt);
 604     ls.print("unload");
 605     print_value_on(&ls);
 606     ls.cr();
 607   }
 608 
 609   // Some items on the _deallocate_list need to free their C heap structures
 610   // if they are not already on the _klasses list.
 611   unload_deallocate_list();
 612 
 613   // Tell serviceability tools these classes are unloading
 614   // after erroneous classes are released.
 615   classes_do(InstanceKlass::notify_unload_class);
 616 
 617   // Clean up global class iterator for compiler
 618   static_klass_iterator.adjust_saved_class(this);
 619 }
 620 
 621 ModuleEntryTable* ClassLoaderData::modules() {
 622   // Lazily create the module entry table at first request.
 623   // Lock-free access requires load_acquire.
 624   ModuleEntryTable* modules = OrderAccess::load_acquire(&_modules);
 625   if (modules == NULL) {
 626     MutexLocker m1(Module_lock);
 627     // Check if _modules got allocated while we were waiting for this lock.
 628     if ((modules = _modules) == NULL) {
 629       modules = new ModuleEntryTable(ModuleEntryTable::_moduletable_entry_size);
 630 
 631       {
 632         MutexLockerEx m1(metaspace_lock(), Mutex::_no_safepoint_check_flag);
 633         // Ensure _modules is stable, since it is examined without a lock
 634         OrderAccess::release_store(&_modules, modules);
 635       }
 636     }
 637   }
 638   return modules;
 639 }
 640 
 641 const int _boot_loader_dictionary_size    = 1009;
 642 const int _default_loader_dictionary_size = 107;
 643 
 644 Dictionary* ClassLoaderData::create_dictionary() {
 645   assert(!is_anonymous(), "anonymous class loader data do not have a dictionary");
 646   int size;
 647   bool resizable = false;
 648   if (_the_null_class_loader_data == NULL) {
 649     size = _boot_loader_dictionary_size;
 650     resizable = true;
 651   } else if (class_loader()->is_a(SystemDictionary::reflect_DelegatingClassLoader_klass())) {
 652     size = 1;  // there's only one class in relection class loader and no initiated classes
 653   } else if (is_system_class_loader_data()) {
 654     size = _boot_loader_dictionary_size;
 655     resizable = true;
 656   } else {
 657     size = _default_loader_dictionary_size;
 658     resizable = true;
 659   }
 660   if (!DynamicallyResizeSystemDictionaries || DumpSharedSpaces) {
 661     resizable = false;
 662   }
 663   return new Dictionary(this, size, resizable);
 664 }
 665 
 666 // Tell the GC to keep this klass alive while iterating ClassLoaderDataGraph
 667 oop ClassLoaderData::holder_phantom() const {
 668   // A klass that was previously considered dead can be looked up in the
 669   // CLD/SD, and its _java_mirror or _class_loader can be stored in a root
 670   // or a reachable object making it alive again. The SATB part of G1 needs
 671   // to get notified about this potential resurrection, otherwise the marking
 672   // might not find the object.
 673   if (!_holder.is_null()) {  // NULL class_loader
 674     return _holder.resolve();
 675   } else {
 676     return NULL;
 677   }
 678 }
 679 
 680 // Unloading support
 681 bool ClassLoaderData::is_alive() const {
 682   bool alive = keep_alive()         // null class loader and incomplete anonymous klasses.
 683       || (_holder.peek() != NULL);  // and not cleaned by the GC weak handle processing.
 684 
 685   return alive;
 686 }
 687 
 688 class ReleaseKlassClosure: public KlassClosure {
 689 private:
 690   size_t  _instance_class_released;
 691   size_t  _array_class_released;
 692 public:
 693   ReleaseKlassClosure() : _instance_class_released(0), _array_class_released(0) { }
 694 
 695   size_t instance_class_released() const { return _instance_class_released; }
 696   size_t array_class_released()    const { return _array_class_released;    }
 697 
 698   void do_klass(Klass* k) {
 699     if (k->is_array_klass()) {
 700       _array_class_released ++;
 701     } else {
 702       assert(k->is_instance_klass(), "Must be");
 703       _instance_class_released ++;
 704       InstanceKlass::release_C_heap_structures(InstanceKlass::cast(k));
 705     }
 706   }
 707 };
 708 
 709 ClassLoaderData::~ClassLoaderData() {
 710   // Release C heap structures for all the classes.
 711   ReleaseKlassClosure cl;
 712   classes_do(&cl);
 713 
 714   ClassLoaderDataGraph::dec_array_classes(cl.array_class_released());
 715   ClassLoaderDataGraph::dec_instance_classes(cl.instance_class_released());
 716 
 717   // Release the WeakHandle
 718   _holder.release();
 719 
 720   // Release C heap allocated hashtable for all the packages.
 721   if (_packages != NULL) {
 722     // Destroy the table itself
 723     delete _packages;
 724     _packages = NULL;
 725   }
 726 
 727   // Release C heap allocated hashtable for all the modules.
 728   if (_modules != NULL) {
 729     // Destroy the table itself
 730     delete _modules;
 731     _modules = NULL;
 732   }
 733 
 734   // Release C heap allocated hashtable for the dictionary
 735   if (_dictionary != NULL) {
 736     // Destroy the table itself
 737     delete _dictionary;
 738     _dictionary = NULL;
 739   }
 740 
 741   if (_unnamed_module != NULL) {
 742     _unnamed_module->delete_unnamed_module();
 743     _unnamed_module = NULL;
 744   }
 745 
 746   // release the metaspace
 747   ClassLoaderMetaspace *m = _metaspace;
 748   if (m != NULL) {
 749     _metaspace = NULL;
 750     delete m;
 751   }
 752   // Clear all the JNI handles for methods
 753   // These aren't deallocated and are going to look like a leak, but that's
 754   // needed because we can't really get rid of jmethodIDs because we don't
 755   // know when native code is going to stop using them.  The spec says that
 756   // they're "invalid" but existing programs likely rely on their being
 757   // NULL after class unloading.
 758   if (_jmethod_ids != NULL) {
 759     Method::clear_jmethod_ids(this);
 760   }
 761   // Delete lock
 762   delete _metaspace_lock;
 763 
 764   // Delete free list
 765   if (_deallocate_list != NULL) {
 766     delete _deallocate_list;
 767   }
 768 
 769   // Decrement refcounts of Symbols if created.
 770   if (_name != NULL) {
 771     _name->decrement_refcount();
 772   }
 773   if (_name_and_id != NULL) {
 774     _name_and_id->decrement_refcount();
 775   }
 776 }
 777 
 778 // Returns true if this class loader data is for the app class loader
 779 // or a user defined system class loader.  (Note that the class loader
 780 // data may be anonymous.)
 781 bool ClassLoaderData::is_system_class_loader_data() const {
 782   return SystemDictionary::is_system_class_loader(class_loader());
 783 }
 784 
 785 // Returns true if this class loader data is for the platform class loader.
 786 // (Note that the class loader data may be anonymous.)
 787 bool ClassLoaderData::is_platform_class_loader_data() const {
 788   return SystemDictionary::is_platform_class_loader(class_loader());
 789 }
 790 
 791 // Returns true if the class loader for this class loader data is one of
 792 // the 3 builtin (boot application/system or platform) class loaders,
 793 // including a user-defined system class loader.  Note that if the class
 794 // loader data is for an anonymous class then it may get freed by a GC
 795 // even if its class loader is one of these loaders.
 796 bool ClassLoaderData::is_builtin_class_loader_data() const {
 797   return (is_boot_class_loader_data() ||
 798           SystemDictionary::is_system_class_loader(class_loader()) ||
 799           SystemDictionary::is_platform_class_loader(class_loader()));
 800 }
 801 
 802 // Returns true if this class loader data is a class loader data
 803 // that is not ever freed by a GC.  It must be one of the builtin
 804 // class loaders and not anonymous.
 805 bool ClassLoaderData::is_permanent_class_loader_data() const {
 806   return is_builtin_class_loader_data() && !is_anonymous();
 807 }
 808 
 809 ClassLoaderMetaspace* ClassLoaderData::metaspace_non_null() {
 810   // If the metaspace has not been allocated, create a new one.  Might want
 811   // to create smaller arena for Reflection class loaders also.
 812   // The reason for the delayed allocation is because some class loaders are
 813   // simply for delegating with no metadata of their own.
 814   // Lock-free access requires load_acquire.
 815   ClassLoaderMetaspace* metaspace = OrderAccess::load_acquire(&_metaspace);
 816   if (metaspace == NULL) {
 817     MutexLockerEx ml(_metaspace_lock,  Mutex::_no_safepoint_check_flag);
 818     // Check if _metaspace got allocated while we were waiting for this lock.
 819     if ((metaspace = _metaspace) == NULL) {
 820       if (this == the_null_class_loader_data()) {
 821         assert (class_loader() == NULL, "Must be");
 822         metaspace = new ClassLoaderMetaspace(_metaspace_lock, Metaspace::BootMetaspaceType);
 823       } else if (is_anonymous()) {
 824         metaspace = new ClassLoaderMetaspace(_metaspace_lock, Metaspace::AnonymousMetaspaceType);
 825       } else if (class_loader()->is_a(SystemDictionary::reflect_DelegatingClassLoader_klass())) {
 826         metaspace = new ClassLoaderMetaspace(_metaspace_lock, Metaspace::ReflectionMetaspaceType);
 827       } else {
 828         metaspace = new ClassLoaderMetaspace(_metaspace_lock, Metaspace::StandardMetaspaceType);
 829       }
 830       // Ensure _metaspace is stable, since it is examined without a lock
 831       OrderAccess::release_store(&_metaspace, metaspace);
 832     }
 833   }
 834   return metaspace;
 835 }
 836 
 837 OopHandle ClassLoaderData::add_handle(Handle h) {
 838   MutexLockerEx ml(metaspace_lock(),  Mutex::_no_safepoint_check_flag);
 839   record_modified_oops();
 840   return OopHandle(_handles.add(h()));
 841 }
 842 
 843 void ClassLoaderData::remove_handle(OopHandle h) {
 844   assert(!is_unloading(), "Do not remove a handle for a CLD that is unloading");
 845   oop* ptr = h.ptr_raw();
 846   if (ptr != NULL) {
 847     assert(_handles.owner_of(ptr), "Got unexpected handle " PTR_FORMAT, p2i(ptr));
 848     NativeAccess<>::oop_store(ptr, oop(NULL));
 849   }
 850 }
 851 
 852 void ClassLoaderData::init_handle_locked(OopHandle& dest, Handle h) {
 853   MutexLockerEx ml(metaspace_lock(),  Mutex::_no_safepoint_check_flag);
 854   if (dest.resolve() != NULL) {
 855     return;
 856   } else {
 857     dest = _handles.add(h());
 858   }
 859 }
 860 
 861 // Add this metadata pointer to be freed when it's safe.  This is only during
 862 // class unloading because Handles might point to this metadata field.
 863 void ClassLoaderData::add_to_deallocate_list(Metadata* m) {
 864   // Metadata in shared region isn't deleted.
 865   if (!m->is_shared()) {
 866     MutexLockerEx ml(metaspace_lock(),  Mutex::_no_safepoint_check_flag);
 867     if (_deallocate_list == NULL) {
 868       _deallocate_list = new (ResourceObj::C_HEAP, mtClass) GrowableArray<Metadata*>(100, true);
 869     }
 870     _deallocate_list->append_if_missing(m);
 871   }
 872 }
 873 
 874 // Deallocate free metadata on the free list.  How useful the PermGen was!
 875 void ClassLoaderData::free_deallocate_list() {
 876   // Don't need lock, at safepoint
 877   assert(SafepointSynchronize::is_at_safepoint(), "only called at safepoint");
 878   assert(!is_unloading(), "only called for ClassLoaderData that are not unloading");
 879   if (_deallocate_list == NULL) {
 880     return;
 881   }
 882   // Go backwards because this removes entries that are freed.
 883   for (int i = _deallocate_list->length() - 1; i >= 0; i--) {
 884     Metadata* m = _deallocate_list->at(i);
 885     if (!m->on_stack()) {
 886       _deallocate_list->remove_at(i);
 887       // There are only three types of metadata that we deallocate directly.
 888       // Cast them so they can be used by the template function.
 889       if (m->is_method()) {
 890         MetadataFactory::free_metadata(this, (Method*)m);
 891       } else if (m->is_constantPool()) {
 892         MetadataFactory::free_metadata(this, (ConstantPool*)m);
 893       } else if (m->is_klass()) {
 894         MetadataFactory::free_metadata(this, (InstanceKlass*)m);
 895       } else {
 896         ShouldNotReachHere();
 897       }
 898     } else {
 899       // Metadata is alive.
 900       // If scratch_class is on stack then it shouldn't be on this list!
 901       assert(!m->is_klass() || !((InstanceKlass*)m)->is_scratch_class(),
 902              "scratch classes on this list should be dead");
 903       // Also should assert that other metadata on the list was found in handles.
 904     }
 905   }
 906 }
 907 
 908 // This is distinct from free_deallocate_list.  For class loader data that are
 909 // unloading, this frees the C heap memory for items on the list, and unlinks
 910 // scratch or error classes so that unloading events aren't triggered for these
 911 // classes. The metadata is removed with the unloading metaspace.
 912 // There isn't C heap memory allocated for methods, so nothing is done for them.
 913 void ClassLoaderData::unload_deallocate_list() {
 914   // Don't need lock, at safepoint
 915   assert(SafepointSynchronize::is_at_safepoint(), "only called at safepoint");
 916   assert(is_unloading(), "only called for ClassLoaderData that are unloading");
 917   if (_deallocate_list == NULL) {
 918     return;
 919   }
 920   // Go backwards because this removes entries that are freed.
 921   for (int i = _deallocate_list->length() - 1; i >= 0; i--) {
 922     Metadata* m = _deallocate_list->at(i);
 923     assert (!m->on_stack(), "wouldn't be unloading if this were so");
 924     _deallocate_list->remove_at(i);
 925     if (m->is_constantPool()) {
 926       ((ConstantPool*)m)->release_C_heap_structures();
 927     } else if (m->is_klass()) {
 928       InstanceKlass* ik = (InstanceKlass*)m;
 929       // also releases ik->constants() C heap memory
 930       InstanceKlass::release_C_heap_structures(ik);
 931       // Remove the class so unloading events aren't triggered for
 932       // this class (scratch or error class) in do_unloading().
 933       remove_class(ik);
 934     }
 935   }
 936 }
 937 
 938 // These anonymous class loaders are to contain classes used for JSR292
 939 ClassLoaderData* ClassLoaderData::anonymous_class_loader_data(Handle loader) {
 940   // Add a new class loader data to the graph.
 941   return ClassLoaderDataGraph::add(loader, true);
 942 }
 943 
 944 // Caller needs ResourceMark
 945 // If the class loader's _name has not been explicitly set, the class loader's
 946 // qualified class name is returned.
 947 const char* ClassLoaderData::loader_name() const {
 948    if (_class_loader_klass == NULL) {
 949      return BOOTSTRAP_LOADER_NAME;
 950    } else if (_name != NULL) {
 951      return _name->as_C_string();
 952    } else {
 953      return _class_loader_klass->external_name();
 954    }
 955 }
 956 
 957 // Caller needs ResourceMark
 958 // Format of the _name_and_id is as follows:
 959 //   If the defining loader has a name explicitly set then '<loader-name>' @<id>
 960 //   If the defining loader has no name then <qualified-class-name> @<id>
 961 //   If built-in loader, then omit '@<id>' as there is only one instance.
 962 const char* ClassLoaderData::loader_name_and_id() const {
 963   if (_class_loader_klass == NULL) {
 964     return "'" BOOTSTRAP_LOADER_NAME "'";
 965   } else if (_name_and_id != NULL) {
 966     return _name_and_id->as_C_string();
 967   } else {
 968     // May be called in a race before _name_and_id is initialized.
 969     return _class_loader_klass->external_name();
 970   }
 971 }
 972 
 973 void ClassLoaderData::print_value_on(outputStream* out) const {
 974   if (!is_unloading() && class_loader() != NULL) {
 975     out->print("loader data: " INTPTR_FORMAT " for instance ", p2i(this));
 976     class_loader()->print_value_on(out);  // includes loader_name_and_id() and address of class loader instance
 977   } else {
 978     // loader data: 0xsomeaddr of 'bootstrap'
 979     out->print("loader data: " INTPTR_FORMAT " of %s", p2i(this), loader_name_and_id());
 980   }
 981   if (is_anonymous()) {
 982     out->print(" anonymous");
 983   }
 984 }
 985 
 986 #ifndef PRODUCT
 987 void ClassLoaderData::print_on(outputStream* out) const {
 988   out->print("ClassLoaderData CLD: " PTR_FORMAT ", loader: " PTR_FORMAT ", loader_klass: %s {",
 989               p2i(this), p2i(_class_loader.ptr_raw()), loader_name_and_id());
 990   if (is_anonymous()) out->print(" anonymous");
 991   if (claimed()) out->print(" claimed");
 992   if (is_unloading()) out->print(" unloading");
 993   out->print(" metaspace: " INTPTR_FORMAT, p2i(metaspace_or_null()));
 994 
 995   if (_jmethod_ids != NULL) {
 996     Method::print_jmethod_ids(this, out);
 997   }
 998   out->print(" handles count %d", _handles.count());
 999   out->print(" dependencies %d", _dependency_count);
1000   out->print_cr("}");
1001 }
1002 #endif // PRODUCT
1003 
1004 void ClassLoaderData::verify() {
1005   assert_locked_or_safepoint(_metaspace_lock);
1006   oop cl = class_loader();
1007 
1008   guarantee(this == class_loader_data(cl) || is_anonymous(), "Must be the same");
1009   guarantee(cl != NULL || this == ClassLoaderData::the_null_class_loader_data() || is_anonymous(), "must be");
1010 
1011   // Verify the integrity of the allocated space.
1012   if (metaspace_or_null() != NULL) {
1013     metaspace_or_null()->verify();
1014   }
1015 
1016   for (Klass* k = _klasses; k != NULL; k = k->next_link()) {
1017     guarantee(k->class_loader_data() == this, "Must be the same");
1018     k->verify();
1019     assert(k != k->next_link(), "no loops!");
1020   }
1021 }
1022 
1023 bool ClassLoaderData::contains_klass(Klass* klass) {
1024   // Lock-free access requires load_acquire
1025   for (Klass* k = OrderAccess::load_acquire(&_klasses); k != NULL; k = k->next_link()) {
1026     if (k == klass) return true;
1027   }
1028   return false;
1029 }
1030 
1031 
1032 // GC root of class loader data created.
1033 ClassLoaderData* ClassLoaderDataGraph::_head = NULL;
1034 ClassLoaderData* ClassLoaderDataGraph::_unloading = NULL;
1035 ClassLoaderData* ClassLoaderDataGraph::_saved_unloading = NULL;
1036 ClassLoaderData* ClassLoaderDataGraph::_saved_head = NULL;
1037 
1038 bool ClassLoaderDataGraph::_should_purge = false;
1039 bool ClassLoaderDataGraph::_metaspace_oom = false;
1040 
1041 // Add a new class loader data node to the list.  Assign the newly created
1042 // ClassLoaderData into the java/lang/ClassLoader object as a hidden field
1043 ClassLoaderData* ClassLoaderDataGraph::add_to_graph(Handle loader, bool is_anonymous) {
1044   NoSafepointVerifier no_safepoints; // we mustn't GC until we've installed the
1045                                      // ClassLoaderData in the graph since the CLD
1046                                      // contains oops in _handles that must be walked.
1047 
1048   ClassLoaderData* cld = new ClassLoaderData(loader, is_anonymous);
1049 
1050   if (!is_anonymous) {
1051     // First, Atomically set it
1052     ClassLoaderData* old = java_lang_ClassLoader::cmpxchg_loader_data(cld, loader(), NULL);
1053     if (old != NULL) {
1054       delete cld;
1055       // Returns the data.
1056       return old;
1057     }
1058   }
1059 
1060   // We won the race, and therefore the task of adding the data to the list of
1061   // class loader data
1062   ClassLoaderData** list_head = &_head;
1063   ClassLoaderData* next = _head;
1064 
1065   do {
1066     cld->set_next(next);
1067     ClassLoaderData* exchanged = Atomic::cmpxchg(cld, list_head, next);
1068     if (exchanged == next) {
1069       LogTarget(Debug, class, loader, data) lt;
1070       if (lt.is_enabled()) {
1071         ResourceMark rm;
1072         LogStream ls(lt);
1073         ls.print("create ");
1074         cld->print_value_on(&ls);
1075         ls.cr();
1076       }
1077       return cld;
1078     }
1079     next = exchanged;
1080   } while (true);
1081 }
1082 
1083 ClassLoaderData* ClassLoaderDataGraph::add(Handle loader, bool is_anonymous) {
1084   ClassLoaderData* loader_data = add_to_graph(loader, is_anonymous);
1085   // Initialize _name and _name_and_id after the loader data is added to the
1086   // CLDG because adding the Symbol for _name and _name_and_id might safepoint.
1087   if (loader.not_null()) {
1088     loader_data->initialize_name(loader);
1089   }
1090   return loader_data;
1091 }
1092 
1093 void ClassLoaderDataGraph::oops_do(OopClosure* f, bool must_claim) {
1094   for (ClassLoaderData* cld = _head; cld != NULL; cld = cld->next()) {
1095     cld->oops_do(f, must_claim);
1096   }
1097 }
1098 
1099 void ClassLoaderDataGraph::keep_alive_oops_do(OopClosure* f, bool must_claim) {
1100   for (ClassLoaderData* cld = _head; cld != NULL; cld = cld->next()) {
1101     if (cld->keep_alive()) {
1102       cld->oops_do(f, must_claim);
1103     }
1104   }
1105 }
1106 
1107 void ClassLoaderDataGraph::always_strong_oops_do(OopClosure* f, bool must_claim) {
1108   if (ClassUnloading) {
1109     keep_alive_oops_do(f, must_claim);
1110   } else {
1111     oops_do(f, must_claim);
1112   }
1113 }
1114 
1115 void ClassLoaderDataGraph::cld_do(CLDClosure* cl) {
1116   for (ClassLoaderData* cld = _head; cl != NULL && cld != NULL; cld = cld->next()) {
1117     cl->do_cld(cld);
1118   }
1119 }
1120 
1121 void ClassLoaderDataGraph::cld_unloading_do(CLDClosure* cl) {
1122   assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint!");
1123   // Only walk the head until any clds not purged from prior unloading
1124   // (CMS doesn't purge right away).
1125   for (ClassLoaderData* cld = _unloading; cld != _saved_unloading; cld = cld->next()) {
1126     assert(cld->is_unloading(), "invariant");
1127     cl->do_cld(cld);
1128   }
1129 }
1130 
1131 void ClassLoaderDataGraph::roots_cld_do(CLDClosure* strong, CLDClosure* weak) {
1132   for (ClassLoaderData* cld = _head;  cld != NULL; cld = cld->_next) {
1133     CLDClosure* closure = cld->keep_alive() ? strong : weak;
1134     if (closure != NULL) {
1135       closure->do_cld(cld);
1136     }
1137   }
1138 }
1139 
1140 void ClassLoaderDataGraph::keep_alive_cld_do(CLDClosure* cl) {
1141   roots_cld_do(cl, NULL);
1142 }
1143 
1144 void ClassLoaderDataGraph::always_strong_cld_do(CLDClosure* cl) {
1145   if (ClassUnloading) {
1146     keep_alive_cld_do(cl);
1147   } else {
1148     cld_do(cl);
1149   }
1150 }
1151 
1152 void ClassLoaderDataGraph::classes_do(KlassClosure* klass_closure) {
1153   Thread* thread = Thread::current();
1154   for (ClassLoaderData* cld = _head; cld != NULL; cld = cld->next()) {
1155     Handle holder(thread, cld->holder_phantom());
1156     cld->classes_do(klass_closure);
1157   }
1158 }
1159 
1160 void ClassLoaderDataGraph::classes_do(void f(Klass* const)) {
1161   Thread* thread = Thread::current();
1162   for (ClassLoaderData* cld = _head; cld != NULL; cld = cld->next()) {
1163     Handle holder(thread, cld->holder_phantom());
1164     cld->classes_do(f);
1165   }
1166 }
1167 
1168 void ClassLoaderDataGraph::methods_do(void f(Method*)) {
1169   Thread* thread = Thread::current();
1170   for (ClassLoaderData* cld = _head; cld != NULL; cld = cld->next()) {
1171     Handle holder(thread, cld->holder_phantom());
1172     cld->methods_do(f);
1173   }
1174 }
1175 
1176 void ClassLoaderDataGraph::modules_do(void f(ModuleEntry*)) {
1177   assert_locked_or_safepoint(Module_lock);
1178   Thread* thread = Thread::current();
1179   for (ClassLoaderData* cld = _head; cld != NULL; cld = cld->next()) {
1180     Handle holder(thread, cld->holder_phantom());
1181     cld->modules_do(f);
1182   }
1183 }
1184 
1185 void ClassLoaderDataGraph::modules_unloading_do(void f(ModuleEntry*)) {
1186   assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint!");
1187   // Only walk the head until any clds not purged from prior unloading
1188   // (CMS doesn't purge right away).
1189   for (ClassLoaderData* cld = _unloading; cld != _saved_unloading; cld = cld->next()) {
1190     assert(cld->is_unloading(), "invariant");
1191     cld->modules_do(f);
1192   }
1193 }
1194 
1195 void ClassLoaderDataGraph::packages_do(void f(PackageEntry*)) {
1196   assert_locked_or_safepoint(Module_lock);
1197   Thread* thread = Thread::current();
1198   for (ClassLoaderData* cld = _head; cld != NULL; cld = cld->next()) {
1199     Handle holder(thread, cld->holder_phantom());
1200     cld->packages_do(f);
1201   }
1202 }
1203 
1204 void ClassLoaderDataGraph::packages_unloading_do(void f(PackageEntry*)) {
1205   assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint!");
1206   // Only walk the head until any clds not purged from prior unloading
1207   // (CMS doesn't purge right away).
1208   for (ClassLoaderData* cld = _unloading; cld != _saved_unloading; cld = cld->next()) {
1209     assert(cld->is_unloading(), "invariant");
1210     cld->packages_do(f);
1211   }
1212 }
1213 
1214 void ClassLoaderDataGraph::loaded_classes_do(KlassClosure* klass_closure) {
1215   Thread* thread = Thread::current();
1216   for (ClassLoaderData* cld = _head; cld != NULL; cld = cld->next()) {
1217     Handle holder(thread, cld->holder_phantom());
1218     cld->loaded_classes_do(klass_closure);
1219   }
1220 }
1221 
1222 void ClassLoaderDataGraph::classes_unloading_do(void f(Klass* const)) {
1223   assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint!");
1224   // Only walk the head until any clds not purged from prior unloading
1225   // (CMS doesn't purge right away).
1226   for (ClassLoaderData* cld = _unloading; cld != _saved_unloading; cld = cld->next()) {
1227     assert(cld->is_unloading(), "invariant");
1228     cld->classes_do(f);
1229   }
1230 }
1231 
1232 #define FOR_ALL_DICTIONARY(X) for (ClassLoaderData* X = _head; X != NULL; X = X->next()) \
1233                                 if (X->dictionary() != NULL)
1234 
1235 // Walk classes in the loaded class dictionaries in various forms.
1236 // Only walks the classes defined in this class loader.
1237 void ClassLoaderDataGraph::dictionary_classes_do(void f(InstanceKlass*)) {
1238   Thread* thread = Thread::current();
1239   FOR_ALL_DICTIONARY(cld) {
1240     Handle holder(thread, cld->holder_phantom());
1241     cld->dictionary()->classes_do(f);
1242   }
1243 }
1244 
1245 // Only walks the classes defined in this class loader.
1246 void ClassLoaderDataGraph::dictionary_classes_do(void f(InstanceKlass*, TRAPS), TRAPS) {
1247   Thread* thread = Thread::current();
1248   FOR_ALL_DICTIONARY(cld) {
1249     Handle holder(thread, cld->holder_phantom());
1250     cld->dictionary()->classes_do(f, CHECK);
1251   }
1252 }
1253 
1254 // Walks all entries in the dictionary including entries initiated by this class loader.
1255 void ClassLoaderDataGraph::dictionary_all_entries_do(void f(InstanceKlass*, ClassLoaderData*)) {
1256   Thread* thread = Thread::current();
1257   FOR_ALL_DICTIONARY(cld) {
1258     Handle holder(thread, cld->holder_phantom());
1259     cld->dictionary()->all_entries_do(f);
1260   }
1261 }
1262 
1263 void ClassLoaderDataGraph::verify_dictionary() {
1264   FOR_ALL_DICTIONARY(cld) {
1265     cld->dictionary()->verify();
1266   }
1267 }
1268 
1269 void ClassLoaderDataGraph::print_dictionary(outputStream* st) {
1270   FOR_ALL_DICTIONARY(cld) {
1271     st->print("Dictionary for ");
1272     cld->print_value_on(st);
1273     st->cr();
1274     cld->dictionary()->print_on(st);
1275     st->cr();
1276   }
1277 }
1278 
1279 void ClassLoaderDataGraph::print_dictionary_statistics(outputStream* st) {
1280   FOR_ALL_DICTIONARY(cld) {
1281     ResourceMark rm;
1282     stringStream tempst;
1283     tempst.print("System Dictionary for %s class loader", cld->loader_name_and_id());
1284     cld->dictionary()->print_table_statistics(st, tempst.as_string());
1285   }
1286 }
1287 
1288 GrowableArray<ClassLoaderData*>* ClassLoaderDataGraph::new_clds() {
1289   assert(_head == NULL || _saved_head != NULL, "remember_new_clds(true) not called?");
1290 
1291   GrowableArray<ClassLoaderData*>* array = new GrowableArray<ClassLoaderData*>();
1292 
1293   // The CLDs in [_head, _saved_head] were all added during last call to remember_new_clds(true);
1294   ClassLoaderData* curr = _head;
1295   while (curr != _saved_head) {
1296     if (!curr->claimed()) {
1297       array->push(curr);
1298       LogTarget(Debug, class, loader, data) lt;
1299       if (lt.is_enabled()) {
1300         LogStream ls(lt);
1301         ls.print("found new CLD: ");
1302         curr->print_value_on(&ls);
1303         ls.cr();
1304       }
1305     }
1306 
1307     curr = curr->_next;
1308   }
1309 
1310   return array;
1311 }
1312 
1313 #ifndef PRODUCT
1314 bool ClassLoaderDataGraph::contains_loader_data(ClassLoaderData* loader_data) {
1315   for (ClassLoaderData* data = _head; data != NULL; data = data->next()) {
1316     if (loader_data == data) {
1317       return true;
1318     }
1319   }
1320 
1321   return false;
1322 }
1323 #endif // PRODUCT
1324 
1325 bool ClassLoaderDataGraph::is_valid(ClassLoaderData* loader_data) {
1326   if (loader_data != NULL) {
1327     if (loader_data == ClassLoaderData::the_null_class_loader_data()) {
1328       return true;
1329     }
1330     for (ClassLoaderData* data = _head; data != NULL; data = data->next()) {
1331       if (loader_data == data) {
1332         return true;
1333       }
1334     }
1335   }
1336   return false;
1337 }
1338 
1339 #if INCLUDE_JFR
1340 static Ticks class_unload_time;
1341 static void post_class_unload_event(Klass* const k) {
1342   assert(k != NULL, "invariant");
1343   EventClassUnload event(UNTIMED);
1344   event.set_endtime(class_unload_time);
1345   event.set_unloadedClass(k);
1346   event.set_definingClassLoader(k->class_loader_data());
1347   event.commit();
1348 }
1349 
1350 static void post_class_unload_events() {
1351   assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint!");
1352   if (Jfr::is_enabled()) {
1353     if (EventClassUnload::is_enabled()) {
1354       class_unload_time = Ticks::now();
1355       ClassLoaderDataGraph::classes_unloading_do(&post_class_unload_event);
1356     }
1357     Jfr::on_unloading_classes();
1358   }
1359 }
1360 #endif // INCLUDE_JFR
1361 
1362 // Move class loader data from main list to the unloaded list for unloading
1363 // and deallocation later.
1364 bool ClassLoaderDataGraph::do_unloading(bool clean_previous_versions) {
1365 
1366   ClassLoaderData* data = _head;
1367   ClassLoaderData* prev = NULL;
1368   bool seen_dead_loader = false;
1369   uint loaders_processed = 0;
1370   uint loaders_removed = 0;
1371 
1372   // Mark metadata seen on the stack only so we can delete unneeded entries.
1373   // Only walk all metadata, including the expensive code cache walk, for Full GC
1374   // and only if class redefinition and if there's previous versions of
1375   // Klasses to delete.
1376   bool walk_all_metadata = clean_previous_versions &&
1377                            JvmtiExport::has_redefined_a_class() &&
1378                            InstanceKlass::has_previous_versions_and_reset();
1379   MetadataOnStackMark md_on_stack(walk_all_metadata);
1380 
1381   // Save previous _unloading pointer for CMS which may add to unloading list before
1382   // purging and we don't want to rewalk the previously unloaded class loader data.
1383   _saved_unloading = _unloading;
1384 
1385   data = _head;
1386   while (data != NULL) {
1387     if (data->is_alive()) {
1388       // clean metaspace
1389       if (walk_all_metadata) {
1390         data->classes_do(InstanceKlass::purge_previous_versions);
1391       }
1392       data->free_deallocate_list();
1393       prev = data;
1394       data = data->next();
1395       loaders_processed++;
1396       continue;
1397     }
1398     seen_dead_loader = true;
1399     loaders_removed++;
1400     ClassLoaderData* dead = data;
1401     dead->unload();
1402     data = data->next();
1403     // Remove from loader list.
1404     // This class loader data will no longer be found
1405     // in the ClassLoaderDataGraph.
1406     if (prev != NULL) {
1407       prev->set_next(data);
1408     } else {
1409       assert(dead == _head, "sanity check");
1410       _head = data;
1411     }
1412     dead->set_next(_unloading);
1413     _unloading = dead;
1414   }
1415 
1416   if (seen_dead_loader) {
1417     data = _head;
1418     while (data != NULL) {
1419       // Walk a ModuleEntry's reads, and a PackageEntry's exports
1420       // lists to determine if there are modules on those lists that are now
1421       // dead and should be removed.  A module's life cycle is equivalent
1422       // to its defining class loader's life cycle.  Since a module is
1423       // considered dead if its class loader is dead, these walks must
1424       // occur after each class loader's aliveness is determined.
1425       if (data->packages() != NULL) {
1426         data->packages()->purge_all_package_exports();
1427       }
1428       if (data->modules_defined()) {
1429         data->modules()->purge_all_module_reads();
1430       }
1431       // Clean cached pd lists
1432       // It's unlikely, but some loaded classes in a dictionary might
1433       // point to a protection_domain that has been unloaded.
1434       // The dictionary pd_set points at entries in the ProtectionDomainCacheTable.
1435       if (data->dictionary() != NULL) {
1436         data->dictionary()->clean_cached_protection_domains();
1437       }
1438       data = data->next();
1439     }
1440     JFR_ONLY(post_class_unload_events();)
1441   }
1442 
1443   log_debug(class, loader, data)("do_unloading: loaders processed %u, loaders removed %u", loaders_processed, loaders_removed);
1444 
1445   return seen_dead_loader;
1446 }
1447 
1448 void ClassLoaderDataGraph::purge() {
1449   assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint!");
1450   ClassLoaderData* list = _unloading;
1451   _unloading = NULL;
1452   ClassLoaderData* next = list;
1453   bool classes_unloaded = false;
1454   while (next != NULL) {
1455     ClassLoaderData* purge_me = next;
1456     next = purge_me->next();
1457     delete purge_me;
1458     classes_unloaded = true;
1459   }
1460   if (classes_unloaded) {
1461     Metaspace::purge();
1462     set_metaspace_oom(false);
1463   }
1464 }
1465 
1466 int ClassLoaderDataGraph::resize_if_needed() {
1467   assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint!");
1468   int resized = 0;
1469   if (Dictionary::does_any_dictionary_needs_resizing()) {
1470     FOR_ALL_DICTIONARY(cld) {
1471       if (cld->dictionary()->resize_if_needed()) {
1472         resized++;
1473       }
1474     }
1475   }
1476   return resized;
1477 }
1478 
1479 ClassLoaderDataGraphKlassIteratorAtomic::ClassLoaderDataGraphKlassIteratorAtomic()
1480     : _next_klass(NULL) {
1481   ClassLoaderData* cld = ClassLoaderDataGraph::_head;
1482   Klass* klass = NULL;
1483 
1484   // Find the first klass in the CLDG.
1485   while (cld != NULL) {
1486     assert_locked_or_safepoint(cld->metaspace_lock());
1487     klass = cld->_klasses;
1488     if (klass != NULL) {
1489       _next_klass = klass;
1490       return;
1491     }
1492     cld = cld->next();
1493   }
1494 }
1495 
1496 Klass* ClassLoaderDataGraphKlassIteratorAtomic::next_klass_in_cldg(Klass* klass) {
1497   Klass* next = klass->next_link();
1498   if (next != NULL) {
1499     return next;
1500   }
1501 
1502   // No more klasses in the current CLD. Time to find a new CLD.
1503   ClassLoaderData* cld = klass->class_loader_data();
1504   assert_locked_or_safepoint(cld->metaspace_lock());
1505   while (next == NULL) {
1506     cld = cld->next();
1507     if (cld == NULL) {
1508       break;
1509     }
1510     next = cld->_klasses;
1511   }
1512 
1513   return next;
1514 }
1515 
1516 Klass* ClassLoaderDataGraphKlassIteratorAtomic::next_klass() {
1517   Klass* head = _next_klass;
1518 
1519   while (head != NULL) {
1520     Klass* next = next_klass_in_cldg(head);
1521 
1522     Klass* old_head = Atomic::cmpxchg(next, &_next_klass, head);
1523 
1524     if (old_head == head) {
1525       return head; // Won the CAS.
1526     }
1527 
1528     head = old_head;
1529   }
1530 
1531   // Nothing more for the iterator to hand out.
1532   assert(head == NULL, "head is " PTR_FORMAT ", expected not null:", p2i(head));
1533   return NULL;
1534 }
1535 
1536 ClassLoaderDataGraphMetaspaceIterator::ClassLoaderDataGraphMetaspaceIterator() {
1537   _data = ClassLoaderDataGraph::_head;
1538 }
1539 
1540 ClassLoaderDataGraphMetaspaceIterator::~ClassLoaderDataGraphMetaspaceIterator() {}
1541 
1542 #ifndef PRODUCT
1543 // callable from debugger
1544 extern "C" int print_loader_data_graph() {
1545   ResourceMark rm;
1546   ClassLoaderDataGraph::print_on(tty);
1547   return 0;
1548 }
1549 
1550 void ClassLoaderDataGraph::verify() {
1551   for (ClassLoaderData* data = _head; data != NULL; data = data->next()) {
1552     data->verify();
1553   }
1554 }
1555 
1556 void ClassLoaderDataGraph::print_on(outputStream * const out) {
1557   for (ClassLoaderData* data = _head; data != NULL; data = data->next()) {
1558     data->print_on(out);
1559   }
1560 }
1561 #endif // PRODUCT