1 /*
   2  * Copyright (c) 2018, 2019, 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 #include "precompiled.hpp"
  26 #include "classfile/classLoaderDataGraph.inline.hpp"
  27 #include "classfile/dictionary.hpp"
  28 #include "classfile/javaClasses.hpp"
  29 #include "classfile/metadataOnStackMark.hpp"
  30 #include "classfile/moduleEntry.hpp"
  31 #include "classfile/packageEntry.hpp"
  32 #include "code/dependencyContext.hpp"
  33 #include "logging/log.hpp"
  34 #include "logging/logStream.hpp"
  35 #include "memory/allocation.inline.hpp"
  36 #include "memory/metaspace.hpp"
  37 #include "memory/resourceArea.hpp"
  38 #include "runtime/atomic.hpp"
  39 #include "runtime/handles.inline.hpp"
  40 #include "runtime/mutex.hpp"
  41 #include "runtime/orderAccess.hpp"
  42 #include "runtime/safepoint.hpp"
  43 #include "runtime/safepointVerifiers.hpp"
  44 #include "utilities/growableArray.hpp"
  45 #include "utilities/macros.hpp"
  46 #include "utilities/ostream.hpp"
  47 
  48 volatile size_t ClassLoaderDataGraph::_num_array_classes = 0;
  49 volatile size_t ClassLoaderDataGraph::_num_instance_classes = 0;
  50 
  51 void ClassLoaderDataGraph::clear_claimed_marks() {
  52   // The claimed marks of the CLDs in the ClassLoaderDataGraph are cleared
  53   // outside a safepoint and without locking the ClassLoaderDataGraph_lock.
  54   // This is required to avoid a deadlock between concurrent GC threads and safepointing.
  55   //
  56   // We need to make sure that the CLD contents are fully visible to the
  57   // reader thread. This is accomplished by acquire/release of the _head,
  58   // and is sufficient.
  59   //
  60   // Any ClassLoaderData added after or during walking the list are prepended to
  61   // _head. Their claim mark need not be handled here.
  62   for (ClassLoaderData* cld = OrderAccess::load_acquire(&_head); cld != NULL; cld = cld->next()) {
  63     cld->clear_claim();
  64   }
  65 }
  66 
  67 void ClassLoaderDataGraph::clear_claimed_marks(int claim) {
  68  for (ClassLoaderData* cld = OrderAccess::load_acquire(&_head); cld != NULL; cld = cld->next()) {
  69     cld->clear_claim(claim);
  70   }
  71 }
  72 // Class iterator used by the compiler.  It gets some number of classes at
  73 // a safepoint to decay invocation counters on the methods.
  74 class ClassLoaderDataGraphKlassIteratorStatic {
  75   ClassLoaderData* _current_loader_data;
  76   Klass*           _current_class_entry;
  77  public:
  78 
  79   ClassLoaderDataGraphKlassIteratorStatic() : _current_loader_data(NULL), _current_class_entry(NULL) {}
  80 
  81   InstanceKlass* try_get_next_class() {
  82     assert(SafepointSynchronize::is_at_safepoint(), "only called at safepoint");
  83     size_t max_classes = ClassLoaderDataGraph::num_instance_classes();
  84     assert(max_classes > 0, "should not be called with no instance classes");
  85     for (size_t i = 0; i < max_classes; ) {
  86 
  87       if (_current_class_entry != NULL) {
  88         Klass* k = _current_class_entry;
  89         _current_class_entry = _current_class_entry->next_link();
  90 
  91         if (k->is_instance_klass()) {
  92           InstanceKlass* ik = InstanceKlass::cast(k);
  93           i++;  // count all instance classes found
  94           // Not yet loaded classes are counted in max_classes
  95           // but only return loaded classes.
  96           if (ik->is_loaded()) {
  97             return ik;
  98           }
  99         }
 100       } else {
 101         // Go to next CLD
 102         if (_current_loader_data != NULL) {
 103           _current_loader_data = _current_loader_data->next();
 104         }
 105         // Start at the beginning
 106         if (_current_loader_data == NULL) {
 107           _current_loader_data = ClassLoaderDataGraph::_head;
 108         }
 109 
 110         _current_class_entry = _current_loader_data->klasses();
 111       }
 112     }
 113     // Should never be reached unless all instance classes have failed or are not fully loaded.
 114     // Caller handles NULL.
 115     return NULL;
 116   }
 117 
 118   // If the current class for the static iterator is a class being unloaded or
 119   // deallocated, adjust the current class.
 120   void adjust_saved_class(ClassLoaderData* cld) {
 121     if (_current_loader_data == cld) {
 122       _current_loader_data = cld->next();
 123       if (_current_loader_data != NULL) {
 124         _current_class_entry = _current_loader_data->klasses();
 125       }  // else try_get_next_class will start at the head
 126     }
 127   }
 128 
 129   void adjust_saved_class(Klass* klass) {
 130     if (_current_class_entry == klass) {
 131       _current_class_entry = klass->next_link();
 132     }
 133   }
 134 };
 135 
 136 static ClassLoaderDataGraphKlassIteratorStatic static_klass_iterator;
 137 
 138 InstanceKlass* ClassLoaderDataGraph::try_get_next_class() {
 139   assert(SafepointSynchronize::is_at_safepoint(), "only called at safepoint");
 140   return static_klass_iterator.try_get_next_class();
 141 }
 142 
 143 void ClassLoaderDataGraph::adjust_saved_class(ClassLoaderData* cld) {
 144   return static_klass_iterator.adjust_saved_class(cld);
 145 }
 146 
 147 void ClassLoaderDataGraph::adjust_saved_class(Klass* klass) {
 148   return static_klass_iterator.adjust_saved_class(klass);
 149 }
 150 
 151 void ClassLoaderDataGraph::clean_deallocate_lists(bool walk_previous_versions) {
 152   assert(SafepointSynchronize::is_at_safepoint(), "must only be called at safepoint");
 153   uint loaders_processed = 0;
 154   for (ClassLoaderData* cld = _head; cld != NULL; cld = cld->next()) {
 155     // is_alive check will be necessary for concurrent class unloading.
 156     if (cld->is_alive()) {
 157       // clean metaspace
 158       if (walk_previous_versions) {
 159         cld->classes_do(InstanceKlass::purge_previous_versions);
 160       }
 161       cld->free_deallocate_list();
 162       loaders_processed++;
 163     }
 164   }
 165   log_debug(class, loader, data)("clean_deallocate_lists: loaders processed %u %s",
 166                                  loaders_processed, walk_previous_versions ? "walk_previous_versions" : "");
 167 }
 168 
 169 void ClassLoaderDataGraph::walk_metadata_and_clean_metaspaces() {
 170   assert(SafepointSynchronize::is_at_safepoint(), "must only be called at safepoint");
 171 
 172   _should_clean_deallocate_lists = false; // assume everything gets cleaned
 173 
 174   // Mark metadata seen on the stack so we can delete unreferenced entries.
 175   // Walk all metadata, including the expensive code cache walk, only for class redefinition.
 176   // The MetadataOnStackMark walk during redefinition saves previous versions if it finds old methods
 177   // on the stack or in the code cache, so we only have to repeat the full walk if
 178   // they were found at that time.
 179   // TODO: have redefinition clean old methods out of the code cache.  They still exist in some places.
 180   bool walk_all_metadata = InstanceKlass::has_previous_versions_and_reset();
 181 
 182   MetadataOnStackMark md_on_stack(walk_all_metadata, /*redefinition_walk*/false);
 183   clean_deallocate_lists(walk_all_metadata);
 184 }
 185 
 186 // GC root of class loader data created.
 187 ClassLoaderData* volatile ClassLoaderDataGraph::_head = NULL;
 188 ClassLoaderData* ClassLoaderDataGraph::_unloading = NULL;
 189 ClassLoaderData* ClassLoaderDataGraph::_saved_unloading = NULL;
 190 ClassLoaderData* ClassLoaderDataGraph::_saved_head = NULL;
 191 
 192 bool ClassLoaderDataGraph::_should_purge = false;
 193 bool ClassLoaderDataGraph::_should_clean_deallocate_lists = false;
 194 bool ClassLoaderDataGraph::_safepoint_cleanup_needed = false;
 195 bool ClassLoaderDataGraph::_metaspace_oom = false;
 196 
 197 // Add a new class loader data node to the list.  Assign the newly created
 198 // ClassLoaderData into the java/lang/ClassLoader object as a hidden field
 199 ClassLoaderData* ClassLoaderDataGraph::add_to_graph(Handle loader, bool is_unsafe_anonymous) {
 200 
 201   assert_lock_strong(ClassLoaderDataGraph_lock);
 202 
 203   ClassLoaderData* cld;
 204 
 205   // First check if another thread beat us to creating the CLD and installing
 206   // it into the loader while we were waiting for the lock.
 207   if (!is_unsafe_anonymous && loader.not_null()) {
 208     cld = java_lang_ClassLoader::loader_data_acquire(loader());
 209     if (cld != NULL) {
 210       return cld;
 211     }
 212   }
 213 
 214   // We mustn't GC until we've installed the ClassLoaderData in the Graph since the CLD
 215   // contains oops in _handles that must be walked.  GC doesn't walk CLD from the
 216   // loader oop in all collections, particularly young collections.
 217   NoSafepointVerifier no_safepoints;
 218 
 219   cld = new ClassLoaderData(loader, is_unsafe_anonymous);
 220 
 221   // First install the new CLD to the Graph.
 222   cld->set_next(_head);
 223   OrderAccess::release_store(&_head, cld);
 224 
 225   // Next associate with the class_loader.
 226   if (!is_unsafe_anonymous) {
 227     // Use OrderAccess, since readers need to get the loader_data only after
 228     // it's added to the Graph
 229     java_lang_ClassLoader::release_set_loader_data(loader(), cld);
 230   }
 231 
 232   // Lastly log, if requested
 233   LogTarget(Trace, class, loader, data) lt;
 234   if (lt.is_enabled()) {
 235     ResourceMark rm;
 236     LogStream ls(lt);
 237     ls.print("create ");
 238     cld->print_value_on(&ls);
 239     ls.cr();
 240   }
 241   return cld;
 242 }
 243 
 244 ClassLoaderData* ClassLoaderDataGraph::add(Handle loader, bool is_unsafe_anonymous) {
 245   MutexLocker ml(ClassLoaderDataGraph_lock);
 246   ClassLoaderData* loader_data = add_to_graph(loader, is_unsafe_anonymous);
 247   return loader_data;
 248 }
 249 
 250 void ClassLoaderDataGraph::cld_unloading_do(CLDClosure* cl) {
 251   assert_locked_or_safepoint_weak(ClassLoaderDataGraph_lock);
 252   // Only walk the head until any clds not purged from prior unloading
 253   // (CMS doesn't purge right away).
 254   for (ClassLoaderData* cld = _unloading; cld != _saved_unloading; cld = cld->next()) {
 255     assert(cld->is_unloading(), "invariant");
 256     cl->do_cld(cld);
 257   }
 258 }
 259 
 260 // These are functions called by the GC, which require all of the CLDs, including the
 261 // unloading ones.
 262 void ClassLoaderDataGraph::cld_do(CLDClosure* cl) {
 263   assert_locked_or_safepoint_weak(ClassLoaderDataGraph_lock);
 264   for (ClassLoaderData* cld = _head;  cld != NULL; cld = cld->_next) {
 265     cl->do_cld(cld);
 266   }
 267 }
 268 
 269 void ClassLoaderDataGraph::roots_cld_do(CLDClosure* strong, CLDClosure* weak) {
 270   assert_locked_or_safepoint_weak(ClassLoaderDataGraph_lock);
 271   for (ClassLoaderData* cld = _head;  cld != NULL; cld = cld->_next) {
 272     CLDClosure* closure = cld->keep_alive() ? strong : weak;
 273     if (closure != NULL) {
 274       closure->do_cld(cld);
 275     }
 276   }
 277 }
 278 
 279 void ClassLoaderDataGraph::always_strong_cld_do(CLDClosure* cl) {
 280   assert_locked_or_safepoint_weak(ClassLoaderDataGraph_lock);
 281   if (ClassUnloading) {
 282     roots_cld_do(cl, NULL);
 283   } else {
 284     cld_do(cl);
 285   }
 286 }
 287 
 288 // Closure for locking and iterating through classes.
 289 LockedClassesDo::LockedClassesDo(classes_do_func_t f) : _function(f) {
 290   ClassLoaderDataGraph_lock->lock();
 291 }
 292 
 293 LockedClassesDo::LockedClassesDo() : _function(NULL) {
 294   // callers provide their own do_klass
 295   ClassLoaderDataGraph_lock->lock();
 296 }
 297 
 298 LockedClassesDo::~LockedClassesDo() { ClassLoaderDataGraph_lock->unlock(); }
 299 
 300 
 301 // Iterating over the CLDG needs to be locked because
 302 // unloading can remove entries concurrently soon.
 303 class ClassLoaderDataGraphIterator : public StackObj {
 304   ClassLoaderData* _next;
 305   HandleMark       _hm;  // clean up handles when this is done.
 306   Handle           _holder;
 307   Thread*          _thread;
 308   NoSafepointVerifier _nsv; // No safepoints allowed in this scope
 309                             // unless verifying at a safepoint.
 310 
 311 public:
 312   ClassLoaderDataGraphIterator() : _next(ClassLoaderDataGraph::_head) {
 313     _thread = Thread::current();
 314     assert_locked_or_safepoint(ClassLoaderDataGraph_lock);
 315   }
 316 
 317   ClassLoaderData* get_next() {
 318     ClassLoaderData* cld = _next;
 319     // Skip already unloaded CLD for concurrent unloading.
 320     while (cld != NULL && !cld->is_alive()) {
 321       cld = cld->next();
 322     }
 323     if (cld != NULL) {
 324       // Keep cld that is being returned alive.
 325       _holder = Handle(_thread, cld->holder_phantom());
 326       _next = cld->next();
 327     } else {
 328       _next = NULL;
 329     }
 330     return cld;
 331   }
 332 };
 333 
 334 void ClassLoaderDataGraph::loaded_cld_do(CLDClosure* cl) {
 335   ClassLoaderDataGraphIterator iter;
 336   while (ClassLoaderData* cld = iter.get_next()) {
 337     cl->do_cld(cld);
 338   }
 339 }
 340 
 341 // These functions assume that the caller has locked the ClassLoaderDataGraph_lock
 342 // if they are not calling the function from a safepoint.
 343 void ClassLoaderDataGraph::classes_do(KlassClosure* klass_closure) {
 344   ClassLoaderDataGraphIterator iter;
 345   while (ClassLoaderData* cld = iter.get_next()) {
 346     cld->classes_do(klass_closure);
 347   }
 348 }
 349 
 350 void ClassLoaderDataGraph::classes_do(void f(Klass* const)) {
 351   ClassLoaderDataGraphIterator iter;
 352   while (ClassLoaderData* cld = iter.get_next()) {
 353     cld->classes_do(f);
 354   }
 355 }
 356 
 357 void ClassLoaderDataGraph::methods_do(void f(Method*)) {
 358   ClassLoaderDataGraphIterator iter;
 359   while (ClassLoaderData* cld = iter.get_next()) {
 360     cld->methods_do(f);
 361   }
 362 }
 363 
 364 void ClassLoaderDataGraph::modules_do(void f(ModuleEntry*)) {
 365   assert_locked_or_safepoint(Module_lock);
 366   ClassLoaderDataGraphIterator iter;
 367   while (ClassLoaderData* cld = iter.get_next()) {
 368     cld->modules_do(f);
 369   }
 370 }
 371 
 372 void ClassLoaderDataGraph::modules_unloading_do(void f(ModuleEntry*)) {
 373   assert_locked_or_safepoint(ClassLoaderDataGraph_lock);
 374   // Only walk the head until any clds not purged from prior unloading
 375   // (CMS doesn't purge right away).
 376   for (ClassLoaderData* cld = _unloading; cld != _saved_unloading; cld = cld->next()) {
 377     assert(cld->is_unloading(), "invariant");
 378     cld->modules_do(f);
 379   }
 380 }
 381 
 382 void ClassLoaderDataGraph::packages_do(void f(PackageEntry*)) {
 383   assert_locked_or_safepoint(Module_lock);
 384   ClassLoaderDataGraphIterator iter;
 385   while (ClassLoaderData* cld = iter.get_next()) {
 386     cld->packages_do(f);
 387   }
 388 }
 389 
 390 void ClassLoaderDataGraph::packages_unloading_do(void f(PackageEntry*)) {
 391   assert_locked_or_safepoint(ClassLoaderDataGraph_lock);
 392   // Only walk the head until any clds not purged from prior unloading
 393   // (CMS doesn't purge right away).
 394   for (ClassLoaderData* cld = _unloading; cld != _saved_unloading; cld = cld->next()) {
 395     assert(cld->is_unloading(), "invariant");
 396     cld->packages_do(f);
 397   }
 398 }
 399 
 400 void ClassLoaderDataGraph::loaded_classes_do(KlassClosure* klass_closure) {
 401   ClassLoaderDataGraphIterator iter;
 402   while (ClassLoaderData* cld = iter.get_next()) {
 403     cld->loaded_classes_do(klass_closure);
 404   }
 405 }
 406 
 407 // This case can block but cannot do unloading (called from CDS)
 408 void ClassLoaderDataGraph::unlocked_loaded_classes_do(KlassClosure* klass_closure) {
 409   for (ClassLoaderData* cld = _head; cld != NULL; cld = cld->next()) {
 410     cld->loaded_classes_do(klass_closure);
 411   }
 412 }
 413 
 414 
 415 void ClassLoaderDataGraph::classes_unloading_do(void f(Klass* const)) {
 416   assert_locked_or_safepoint(ClassLoaderDataGraph_lock);
 417   // Only walk the head until any clds not purged from prior unloading
 418   // (CMS doesn't purge right away).
 419   for (ClassLoaderData* cld = _unloading; cld != _saved_unloading; cld = cld->next()) {
 420     assert(cld->is_unloading(), "invariant");
 421     cld->classes_do(f);
 422   }
 423 }
 424 
 425 #define FOR_ALL_DICTIONARY(X)   ClassLoaderDataGraphIterator iter; \
 426                                 while (ClassLoaderData* X = iter.get_next()) \
 427                                   if (X->dictionary() != NULL)
 428 
 429 // Walk classes in the loaded class dictionaries in various forms.
 430 // Only walks the classes defined in this class loader.
 431 void ClassLoaderDataGraph::dictionary_classes_do(void f(InstanceKlass*)) {
 432   FOR_ALL_DICTIONARY(cld) {
 433     cld->dictionary()->classes_do(f);
 434   }
 435 }
 436 
 437 // Only walks the classes defined in this class loader.
 438 void ClassLoaderDataGraph::dictionary_classes_do(void f(InstanceKlass*, TRAPS), TRAPS) {
 439   FOR_ALL_DICTIONARY(cld) {
 440     cld->dictionary()->classes_do(f, CHECK);
 441   }
 442 }
 443 
 444 void ClassLoaderDataGraph::verify_dictionary() {
 445   FOR_ALL_DICTIONARY(cld) {
 446     cld->dictionary()->verify();
 447   }
 448 }
 449 
 450 void ClassLoaderDataGraph::print_dictionary(outputStream* st) {
 451   FOR_ALL_DICTIONARY(cld) {
 452     st->print("Dictionary for ");
 453     cld->print_value_on(st);
 454     st->cr();
 455     cld->dictionary()->print_on(st);
 456     st->cr();
 457   }
 458 }
 459 
 460 void ClassLoaderDataGraph::print_table_statistics(outputStream* st) {
 461   FOR_ALL_DICTIONARY(cld) {
 462     ResourceMark rm;
 463     stringStream tempst;
 464     tempst.print("System Dictionary for %s class loader", cld->loader_name_and_id());
 465     cld->dictionary()->print_table_statistics(st, tempst.as_string());
 466   }
 467 }
 468 
 469 GrowableArray<ClassLoaderData*>* ClassLoaderDataGraph::new_clds() {
 470   assert_locked_or_safepoint(ClassLoaderDataGraph_lock);
 471   assert(_head == NULL || _saved_head != NULL, "remember_new_clds(true) not called?");
 472 
 473   GrowableArray<ClassLoaderData*>* array = new GrowableArray<ClassLoaderData*>();
 474 
 475   // The CLDs in [_head, _saved_head] were all added during last call to remember_new_clds(true);
 476   ClassLoaderData* curr = _head;
 477   while (curr != _saved_head) {
 478     if (!curr->claimed(ClassLoaderData::_claim_strong)) {
 479       array->push(curr);
 480       LogTarget(Debug, class, loader, data) lt;
 481       if (lt.is_enabled()) {
 482         LogStream ls(lt);
 483         ls.print("found new CLD: ");
 484         curr->print_value_on(&ls);
 485         ls.cr();
 486       }
 487     }
 488 
 489     curr = curr->_next;
 490   }
 491 
 492   return array;
 493 }
 494 
 495 #ifndef PRODUCT
 496 bool ClassLoaderDataGraph::contains_loader_data(ClassLoaderData* loader_data) {
 497   assert_locked_or_safepoint(ClassLoaderDataGraph_lock);
 498   for (ClassLoaderData* data = _head; data != NULL; data = data->next()) {
 499     if (loader_data == data) {
 500       return true;
 501     }
 502   }
 503 
 504   return false;
 505 }
 506 #endif // PRODUCT
 507 
 508 bool ClassLoaderDataGraph::is_valid(ClassLoaderData* loader_data) {
 509   DEBUG_ONLY( if (!VMError::is_error_reported()) { assert_locked_or_safepoint(ClassLoaderDataGraph_lock); } )
 510   if (loader_data != NULL) {
 511     if (loader_data == ClassLoaderData::the_null_class_loader_data()) {
 512       return true;
 513     }
 514     for (ClassLoaderData* data = _head; data != NULL; data = data->next()) {
 515       if (loader_data == data) {
 516         return true;
 517       }
 518     }
 519   }
 520   return false;
 521 }
 522 
 523 // Move class loader data from main list to the unloaded list for unloading
 524 // and deallocation later.
 525 bool ClassLoaderDataGraph::do_unloading() {
 526   assert_locked_or_safepoint(ClassLoaderDataGraph_lock);
 527 
 528   // Indicate whether safepoint cleanup is needed.
 529   _safepoint_cleanup_needed = true;
 530 
 531   ClassLoaderData* data = _head;
 532   ClassLoaderData* prev = NULL;
 533   bool seen_dead_loader = false;
 534   uint loaders_processed = 0;
 535   uint loaders_removed = 0;
 536 
 537   // Save previous _unloading pointer for CMS which may add to unloading list before
 538   // purging and we don't want to rewalk the previously unloaded class loader data.
 539   _saved_unloading = _unloading;
 540 
 541   data = _head;
 542   while (data != NULL) {
 543     if (data->is_alive()) {
 544       prev = data;
 545       data = data->next();
 546       loaders_processed++;
 547       continue;
 548     }
 549     seen_dead_loader = true;
 550     loaders_removed++;
 551     ClassLoaderData* dead = data;
 552     dead->unload();
 553     data = data->next();
 554     // Remove from loader list.
 555     // This class loader data will no longer be found
 556     // in the ClassLoaderDataGraph.
 557     if (prev != NULL) {
 558       prev->set_next(data);
 559     } else {
 560       assert(dead == _head, "sanity check");
 561       _head = data;
 562     }
 563     dead->set_next(_unloading);
 564     _unloading = dead;
 565   }
 566 
 567   log_debug(class, loader, data)("do_unloading: loaders processed %u, loaders removed %u", loaders_processed, loaders_removed);
 568 
 569   return seen_dead_loader;
 570 }
 571 
 572 // There's at least one dead class loader.  Purge refererences of healthy module
 573 // reads lists and package export lists to modules belonging to dead loaders.
 574 void ClassLoaderDataGraph::clean_module_and_package_info() {
 575   assert_locked_or_safepoint(ClassLoaderDataGraph_lock);
 576 
 577   ClassLoaderData* data = _head;
 578   while (data != NULL) {
 579     // Walk a ModuleEntry's reads, and a PackageEntry's exports
 580     // lists to determine if there are modules on those lists that are now
 581     // dead and should be removed.  A module's life cycle is equivalent
 582     // to its defining class loader's life cycle.  Since a module is
 583     // considered dead if its class loader is dead, these walks must
 584     // occur after each class loader's aliveness is determined.
 585     if (data->packages() != NULL) {
 586       data->packages()->purge_all_package_exports();
 587     }
 588     if (data->modules_defined()) {
 589       data->modules()->purge_all_module_reads();
 590     }
 591     data = data->next();
 592   }
 593 }
 594 
 595 void ClassLoaderDataGraph::purge() {
 596   ClassLoaderData* list = _unloading;
 597   _unloading = NULL;
 598   ClassLoaderData* next = list;
 599   bool classes_unloaded = false;
 600   while (next != NULL) {
 601     ClassLoaderData* purge_me = next;
 602     next = purge_me->next();
 603     delete purge_me;
 604     classes_unloaded = true;
 605   }
 606   if (classes_unloaded) {
 607     Metaspace::purge();
 608     set_metaspace_oom(false);
 609   }
 610   DependencyContext::purge_dependency_contexts();
 611 }
 612 
 613 int ClassLoaderDataGraph::resize_dictionaries() {
 614   assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint!");
 615   int resized = 0;
 616   assert (Dictionary::does_any_dictionary_needs_resizing(), "some dictionary should need resizing");
 617   FOR_ALL_DICTIONARY(cld) {
 618     if (cld->dictionary()->resize_if_needed()) {
 619       resized++;
 620     }
 621   }
 622   return resized;
 623 }
 624 
 625 ClassLoaderDataGraphKlassIteratorAtomic::ClassLoaderDataGraphKlassIteratorAtomic()
 626     : _next_klass(NULL) {
 627   assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint!");
 628   ClassLoaderData* cld = ClassLoaderDataGraph::_head;
 629   Klass* klass = NULL;
 630 
 631   // Find the first klass in the CLDG.
 632   while (cld != NULL) {
 633     assert_locked_or_safepoint(cld->metaspace_lock());
 634     klass = cld->_klasses;
 635     if (klass != NULL) {
 636       _next_klass = klass;
 637       return;
 638     }
 639     cld = cld->next();
 640   }
 641 }
 642 
 643 Klass* ClassLoaderDataGraphKlassIteratorAtomic::next_klass_in_cldg(Klass* klass) {
 644   Klass* next = klass->next_link();
 645   if (next != NULL) {
 646     return next;
 647   }
 648 
 649   // No more klasses in the current CLD. Time to find a new CLD.
 650   ClassLoaderData* cld = klass->class_loader_data();
 651   assert_locked_or_safepoint(cld->metaspace_lock());
 652   while (next == NULL) {
 653     cld = cld->next();
 654     if (cld == NULL) {
 655       break;
 656     }
 657     next = cld->_klasses;
 658   }
 659 
 660   return next;
 661 }
 662 
 663 Klass* ClassLoaderDataGraphKlassIteratorAtomic::next_klass() {
 664   Klass* head = _next_klass;
 665 
 666   while (head != NULL) {
 667     Klass* next = next_klass_in_cldg(head);
 668 
 669     Klass* old_head = Atomic::cmpxchg(next, &_next_klass, head);
 670 
 671     if (old_head == head) {
 672       return head; // Won the CAS.
 673     }
 674 
 675     head = old_head;
 676   }
 677 
 678   // Nothing more for the iterator to hand out.
 679   assert(head == NULL, "head is " PTR_FORMAT ", expected not null:", p2i(head));
 680   return NULL;
 681 }
 682 
 683 ClassLoaderDataGraphMetaspaceIterator::ClassLoaderDataGraphMetaspaceIterator() {
 684   assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint!");
 685   _data = ClassLoaderDataGraph::_head;
 686 }
 687 
 688 ClassLoaderDataGraphMetaspaceIterator::~ClassLoaderDataGraphMetaspaceIterator() {}
 689 
 690 ClassLoaderMetaspace* ClassLoaderDataGraphMetaspaceIterator::get_next() {
 691   assert(_data != NULL, "Should not be NULL in call to the iterator");
 692   ClassLoaderMetaspace* result = _data->metaspace_or_null();
 693   _data = _data->next();
 694   // This result might be NULL for class loaders without metaspace
 695   // yet.  It would be nice to return only non-null results but
 696   // there is no guarantee that there will be a non-null result
 697   // down the list so the caller is going to have to check.
 698   return result;
 699 }
 700 
 701 #ifndef PRODUCT
 702 // callable from debugger
 703 extern "C" int print_loader_data_graph() {
 704   ResourceMark rm;
 705   ClassLoaderDataGraph::print_on(tty);
 706   return 0;
 707 }
 708 
 709 void ClassLoaderDataGraph::verify() {
 710   ClassLoaderDataGraphIterator iter;
 711   while (ClassLoaderData* cld = iter.get_next()) {
 712     cld->verify();
 713   }
 714 }
 715 
 716 void ClassLoaderDataGraph::print_on(outputStream * const out) {
 717   ClassLoaderDataGraphIterator iter;
 718   while (ClassLoaderData* cld = iter.get_next()) {
 719     cld->print_on(out);
 720   }
 721 }
 722 #endif // PRODUCT
 723 
 724 void ClassLoaderDataGraph::print() { print_on(tty); }