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