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