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