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