1  /*
   2  * Copyright (c) 2012, 2018, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 // A ClassLoaderData identifies the full set of class types that a class
  26 // loader's name resolution strategy produces for a given configuration of the
  27 // class loader.
  28 // Class types in the ClassLoaderData may be defined by from class file binaries
  29 // provided by the class loader, or from other class loader it interacts with
  30 // according to its name resolution strategy.
  31 //
  32 // Class loaders that implement a deterministic name resolution strategy
  33 // (including with respect to their delegation behavior), such as the boot, the
  34 // platform, and the system loaders of the JDK's built-in class loader
  35 // hierarchy, always produce the same linkset for a given configuration.
  36 //
  37 // ClassLoaderData carries information related to a linkset (e.g.,
  38 // metaspace holding its klass definitions).
  39 // The System Dictionary and related data structures (e.g., placeholder table,
  40 // loader constraints table) as well as the runtime representation of classes
  41 // only reference ClassLoaderData.
  42 //
  43 // Instances of java.lang.ClassLoader holds a pointer to a ClassLoaderData that
  44 // that represent the loader's "linking domain" in the JVM.
  45 //
  46 // The bootstrap loader (represented by NULL) also has a ClassLoaderData,
  47 // the singleton class the_null_class_loader_data().
  48 
  49 #include "precompiled.hpp"
  50 #include "classfile/classLoaderData.hpp"
  51 #include "classfile/classLoaderData.inline.hpp"
  52 #include "classfile/dictionary.hpp"
  53 #include "classfile/javaClasses.hpp"
  54 #include "classfile/metadataOnStackMark.hpp"
  55 #include "classfile/moduleEntry.hpp"
  56 #include "classfile/packageEntry.hpp"
  57 #include "classfile/systemDictionary.hpp"
  58 #include "code/codeCache.hpp"
  59 #include "gc/shared/gcLocker.hpp"
  60 #include "logging/log.hpp"
  61 #include "logging/logStream.hpp"
  62 #include "memory/allocation.inline.hpp"
  63 #include "memory/metadataFactory.hpp"
  64 #include "memory/metaspaceShared.hpp"
  65 #include "memory/oopFactory.hpp"
  66 #include "memory/resourceArea.hpp"
  67 #include "oops/access.inline.hpp"
  68 #include "oops/objArrayOop.inline.hpp"
  69 #include "oops/oop.inline.hpp"
  70 #include "runtime/atomic.hpp"
  71 #include "runtime/javaCalls.hpp"
  72 #include "runtime/jniHandles.hpp"
  73 #include "runtime/mutex.hpp"
  74 #include "runtime/orderAccess.hpp"
  75 #include "runtime/safepoint.hpp"
  76 #include "runtime/synchronizer.hpp"
  77 #include "utilities/growableArray.hpp"
  78 #include "utilities/macros.hpp"
  79 #include "utilities/ostream.hpp"
  80 #if INCLUDE_TRACE
  81 #include "trace/tracing.hpp"
  82 #endif
  83 
  84 volatile size_t ClassLoaderDataGraph::_num_array_classes = 0;
  85 volatile size_t ClassLoaderDataGraph::_num_instance_classes = 0;
  86 
  87 ClassLoaderData * ClassLoaderData::_the_null_class_loader_data = NULL;
  88 
  89 void ClassLoaderData::init_null_class_loader_data() {
  90   assert(_the_null_class_loader_data == NULL, "cannot initialize twice");
  91   assert(ClassLoaderDataGraph::_head == NULL, "cannot initialize twice");
  92 
  93   _the_null_class_loader_data = new ClassLoaderData(Handle(), false);
  94   ClassLoaderDataGraph::_head = _the_null_class_loader_data;
  95   assert(_the_null_class_loader_data->is_the_null_class_loader_data(), "Must be");
  96 
  97   LogTarget(Debug, class, loader, data) lt;
  98   if (lt.is_enabled()) {
  99     ResourceMark rm;
 100     LogStream ls(lt);
 101     ls.print("create ");
 102     _the_null_class_loader_data->print_value_on(&ls);
 103     ls.cr();
 104   }
 105 }
 106 
 107 ClassLoaderData::ClassLoaderData(Handle h_class_loader, bool is_anonymous) :
 108   _class_loader(h_class_loader()),
 109   _is_anonymous(is_anonymous),
 110   // An anonymous class loader data doesn't have anything to keep
 111   // it from being unloaded during parsing of the anonymous class.
 112   // The null-class-loader should always be kept alive.
 113   _keep_alive((is_anonymous || h_class_loader.is_null()) ? 1 : 0),
 114   _metaspace(NULL), _unloading(false), _klasses(NULL),
 115   _modules(NULL), _packages(NULL),
 116   _claimed(0), _modified_oops(true), _accumulated_modified_oops(false),
 117   _jmethod_ids(NULL), _handles(), _deallocate_list(NULL),
 118   _next(NULL),
 119   _metaspace_lock(new Mutex(Monitor::leaf+1, "Metaspace allocation lock", true,
 120                             Monitor::_safepoint_check_never)) {
 121 
 122   // A ClassLoaderData created solely for an anonymous class should never have a
 123   // ModuleEntryTable or PackageEntryTable created for it. The defining package
 124   // and module for an anonymous class will be found in its host class.
 125   if (!is_anonymous) {
 126     _packages = new PackageEntryTable(PackageEntryTable::_packagetable_entry_size);
 127     if (h_class_loader.is_null()) {
 128       // Create unnamed module for boot loader
 129       _unnamed_module = ModuleEntry::create_boot_unnamed_module(this);
 130     } else {
 131       // Create unnamed module for all other loaders
 132       _unnamed_module = ModuleEntry::create_unnamed_module(this);
 133     }
 134     _dictionary = create_dictionary();
 135   } else {
 136     _packages = NULL;
 137     _unnamed_module = NULL;
 138     _dictionary = NULL;
 139   }
 140 
 141   NOT_PRODUCT(_dependency_count = 0); // number of class loader dependencies
 142 
 143   TRACE_INIT_ID(this);
 144 }
 145 
 146 ClassLoaderData::ChunkedHandleList::~ChunkedHandleList() {
 147   Chunk* c = _head;
 148   while (c != NULL) {
 149     Chunk* next = c->_next;
 150     delete c;
 151     c = next;
 152   }
 153 }
 154 
 155 oop* ClassLoaderData::ChunkedHandleList::add(oop o) {
 156   if (_head == NULL || _head->_size == Chunk::CAPACITY) {
 157     Chunk* next = new Chunk(_head);
 158     OrderAccess::release_store(&_head, next);
 159   }
 160   oop* handle = &_head->_data[_head->_size];
 161   *handle = o;
 162   OrderAccess::release_store(&_head->_size, _head->_size + 1);
 163   return handle;
 164 }
 165 
 166 int ClassLoaderData::ChunkedHandleList::count() const {
 167   int count = 0;
 168   Chunk* chunk = _head;
 169   while (chunk != NULL) {
 170     count += chunk->_size;
 171     chunk = chunk->_next;
 172   }
 173   return count;
 174 }
 175 
 176 inline void ClassLoaderData::ChunkedHandleList::oops_do_chunk(OopClosure* f, Chunk* c, const juint size) {
 177   for (juint i = 0; i < size; i++) {
 178     if (c->_data[i] != NULL) {
 179       f->do_oop(&c->_data[i]);
 180     }
 181   }
 182 }
 183 
 184 void ClassLoaderData::ChunkedHandleList::oops_do(OopClosure* f) {
 185   Chunk* head = OrderAccess::load_acquire(&_head);
 186   if (head != NULL) {
 187     // Must be careful when reading size of head
 188     oops_do_chunk(f, head, OrderAccess::load_acquire(&head->_size));
 189     for (Chunk* c = head->_next; c != NULL; c = c->_next) {
 190       oops_do_chunk(f, c, c->_size);
 191     }
 192   }
 193 }
 194 
 195 class VerifyContainsOopClosure : public OopClosure {
 196   oop  _target;
 197   bool _found;
 198 
 199  public:
 200   VerifyContainsOopClosure(oop target) : _target(target), _found(false) {}
 201 
 202   void do_oop(oop* p) {
 203     if (p != NULL && *p == _target) {
 204       _found = true;
 205     }
 206   }
 207 
 208   void do_oop(narrowOop* p) {
 209     // The ChunkedHandleList should not contain any narrowOop
 210     ShouldNotReachHere();
 211   }
 212 
 213   bool found() const {
 214     return _found;
 215   }
 216 };
 217 
 218 bool ClassLoaderData::ChunkedHandleList::contains(oop p) {
 219   VerifyContainsOopClosure cl(p);
 220   oops_do(&cl);
 221   return cl.found();
 222 }
 223 
 224 bool ClassLoaderData::claim() {
 225   if (_claimed == 1) {
 226     return false;
 227   }
 228 
 229   return (int) Atomic::cmpxchg(1, &_claimed, 0) == 0;
 230 }
 231 
 232 // Anonymous classes have their own ClassLoaderData that is marked to keep alive
 233 // while the class is being parsed, and if the class appears on the module fixup list.
 234 // Due to the uniqueness that no other class shares the anonymous class' name or
 235 // ClassLoaderData, no other non-GC thread has knowledge of the anonymous class while
 236 // it is being defined, therefore _keep_alive is not volatile or atomic.
 237 void ClassLoaderData::inc_keep_alive() {
 238   if (is_anonymous()) {
 239     assert(_keep_alive >= 0, "Invalid keep alive increment count");
 240     _keep_alive++;
 241   }
 242 }
 243 
 244 void ClassLoaderData::dec_keep_alive() {
 245   if (is_anonymous()) {
 246     assert(_keep_alive > 0, "Invalid keep alive decrement count");
 247     _keep_alive--;
 248   }
 249 }
 250 
 251 void ClassLoaderData::oops_do(OopClosure* f, bool must_claim, bool clear_mod_oops) {
 252   if (must_claim && !claim()) {
 253     return;
 254   }
 255 
 256   // Only clear modified_oops after the ClassLoaderData is claimed.
 257   if (clear_mod_oops) {
 258     clear_modified_oops();
 259   }
 260 
 261   f->do_oop(&_class_loader);
 262   _handles.oops_do(f);
 263 }
 264 
 265 void ClassLoaderData::classes_do(KlassClosure* klass_closure) {
 266   // Lock-free access requires load_acquire
 267   for (Klass* k = OrderAccess::load_acquire(&_klasses); k != NULL; k = k->next_link()) {
 268     klass_closure->do_klass(k);
 269     assert(k != k->next_link(), "no loops!");
 270   }
 271 }
 272 
 273 void ClassLoaderData::classes_do(void f(Klass * const)) {
 274   // Lock-free access requires load_acquire
 275   for (Klass* k = OrderAccess::load_acquire(&_klasses); k != NULL; k = k->next_link()) {
 276     f(k);
 277     assert(k != k->next_link(), "no loops!");
 278   }
 279 }
 280 
 281 void ClassLoaderData::methods_do(void f(Method*)) {
 282   // Lock-free access requires load_acquire
 283   for (Klass* k = OrderAccess::load_acquire(&_klasses); k != NULL; k = k->next_link()) {
 284     if (k->is_instance_klass() && InstanceKlass::cast(k)->is_loaded()) {
 285       InstanceKlass::cast(k)->methods_do(f);
 286     }
 287   }
 288 }
 289 
 290 void ClassLoaderData::loaded_classes_do(KlassClosure* klass_closure) {
 291   // Lock-free access requires load_acquire
 292   for (Klass* k = OrderAccess::load_acquire(&_klasses); k != NULL; k = k->next_link()) {
 293     // Do not filter ArrayKlass oops here...
 294     if (k->is_array_klass() || (k->is_instance_klass() && InstanceKlass::cast(k)->is_loaded())) {
 295       klass_closure->do_klass(k);
 296     }
 297   }
 298 }
 299 
 300 void ClassLoaderData::classes_do(void f(InstanceKlass*)) {
 301   // Lock-free access requires load_acquire
 302   for (Klass* k = OrderAccess::load_acquire(&_klasses); k != NULL; k = k->next_link()) {
 303     if (k->is_instance_klass()) {
 304       f(InstanceKlass::cast(k));
 305     }
 306     assert(k != k->next_link(), "no loops!");
 307   }
 308 }
 309 
 310 void ClassLoaderData::modules_do(void f(ModuleEntry*)) {
 311   assert_locked_or_safepoint(Module_lock);
 312   if (_unnamed_module != NULL) {
 313     f(_unnamed_module);
 314   }
 315   if (_modules != NULL) {
 316     for (int i = 0; i < _modules->table_size(); i++) {
 317       for (ModuleEntry* entry = _modules->bucket(i);
 318            entry != NULL;
 319            entry = entry->next()) {
 320         f(entry);
 321       }
 322     }
 323   }
 324 }
 325 
 326 void ClassLoaderData::packages_do(void f(PackageEntry*)) {
 327   assert_locked_or_safepoint(Module_lock);
 328   if (_packages != NULL) {
 329     for (int i = 0; i < _packages->table_size(); i++) {
 330       for (PackageEntry* entry = _packages->bucket(i);
 331            entry != NULL;
 332            entry = entry->next()) {
 333         f(entry);
 334       }
 335     }
 336   }
 337 }
 338 
 339 void ClassLoaderData::record_dependency(const Klass* k) {
 340   assert(k != NULL, "invariant");
 341 
 342   ClassLoaderData * const from_cld = this;
 343   ClassLoaderData * const to_cld = k->class_loader_data();
 344 
 345   // Do not need to record dependency if the dependency is to a class whose
 346   // class loader data is never freed.  (i.e. the dependency's class loader
 347   // is one of the three builtin class loaders and the dependency is not
 348   // anonymous.)
 349   if (to_cld->is_permanent_class_loader_data()) {
 350     return;
 351   }
 352 
 353   oop to;
 354   if (to_cld->is_anonymous()) {
 355     // Just return if an anonymous class is attempting to record a dependency
 356     // to itself.  (Note that every anonymous class has its own unique class
 357     // loader data.)
 358     if (to_cld == from_cld) {
 359       return;
 360     }
 361     // Anonymous class dependencies are through the mirror.
 362     to = k->java_mirror();
 363   } else {
 364     to = to_cld->class_loader();
 365     oop from = from_cld->class_loader();
 366 
 367     // Just return if this dependency is to a class with the same or a parent
 368     // class_loader.
 369     if (from == to || java_lang_ClassLoader::isAncestor(from, to)) {
 370       return; // this class loader is in the parent list, no need to add it.
 371     }
 372   }
 373 
 374   // It's a dependency we won't find through GC, add it.
 375   if (!_handles.contains(to)) {
 376     NOT_PRODUCT(Atomic::inc(&_dependency_count));
 377     LogTarget(Trace, class, loader, data) lt;
 378     if (lt.is_enabled()) {
 379       ResourceMark rm;
 380       LogStream ls(lt);
 381       ls.print("adding dependency from ");
 382       print_value_on(&ls);
 383       ls.print(" to ");
 384       to_cld->print_value_on(&ls);
 385       ls.cr();
 386     }
 387     Handle dependency(Thread::current(), to);
 388     add_handle(dependency);
 389     // Added a potentially young gen oop to the ClassLoaderData
 390     record_modified_oops();
 391   }
 392 }
 393 
 394 
 395 void ClassLoaderDataGraph::clear_claimed_marks() {
 396   for (ClassLoaderData* cld = _head; cld != NULL; cld = cld->next()) {
 397     cld->clear_claimed();
 398   }
 399 }
 400 
 401 void ClassLoaderData::add_class(Klass* k, bool publicize /* true */) {
 402   {
 403     MutexLockerEx ml(metaspace_lock(), Mutex::_no_safepoint_check_flag);
 404     Klass* old_value = _klasses;
 405     k->set_next_link(old_value);
 406     // Link the new item into the list, making sure the linked class is stable
 407     // since the list can be walked without a lock
 408     OrderAccess::release_store(&_klasses, k);
 409     if (k->is_array_klass()) {
 410       ClassLoaderDataGraph::inc_array_classes(1);
 411     } else {
 412       ClassLoaderDataGraph::inc_instance_classes(1);
 413     }
 414   }
 415 
 416   if (publicize) {
 417     LogTarget(Trace, class, loader, data) lt;
 418     if (lt.is_enabled()) {
 419       ResourceMark rm;
 420       LogStream ls(lt);
 421       ls.print("Adding k: " PTR_FORMAT " %s to ", p2i(k), k->external_name());
 422       print_value_on(&ls);
 423       ls.cr();
 424     }
 425   }
 426 }
 427 
 428 // Class iterator used by the compiler.  It gets some number of classes at
 429 // a safepoint to decay invocation counters on the methods.
 430 class ClassLoaderDataGraphKlassIteratorStatic {
 431   ClassLoaderData* _current_loader_data;
 432   Klass*           _current_class_entry;
 433  public:
 434 
 435   ClassLoaderDataGraphKlassIteratorStatic() : _current_loader_data(NULL), _current_class_entry(NULL) {}
 436 
 437   InstanceKlass* try_get_next_class() {
 438     assert(SafepointSynchronize::is_at_safepoint(), "only called at safepoint");
 439     size_t max_classes = ClassLoaderDataGraph::num_instance_classes();
 440     assert(max_classes > 0, "should not be called with no instance classes");
 441     for (size_t i = 0; i < max_classes; ) {
 442 
 443       if (_current_class_entry != NULL) {
 444         Klass* k = _current_class_entry;
 445         _current_class_entry = _current_class_entry->next_link();
 446 
 447         if (k->is_instance_klass()) {
 448           InstanceKlass* ik = InstanceKlass::cast(k);
 449           i++;  // count all instance classes found
 450           // Not yet loaded classes are counted in max_classes
 451           // but only return loaded classes.
 452           if (ik->is_loaded()) {
 453             return ik;
 454           }
 455         }
 456       } else {
 457         // Go to next CLD
 458         if (_current_loader_data != NULL) {
 459           _current_loader_data = _current_loader_data->next();
 460         }
 461         // Start at the beginning
 462         if (_current_loader_data == NULL) {
 463           _current_loader_data = ClassLoaderDataGraph::_head;
 464         }
 465 
 466         _current_class_entry = _current_loader_data->klasses();
 467       }
 468     }
 469     // Should never be reached unless all instance classes have failed or are not fully loaded.
 470     // Caller handles NULL.
 471     return NULL;
 472   }
 473 
 474   // If the current class for the static iterator is a class being unloaded or
 475   // deallocated, adjust the current class.
 476   void adjust_saved_class(ClassLoaderData* cld) {
 477     if (_current_loader_data == cld) {
 478       _current_loader_data = cld->next();
 479       if (_current_loader_data != NULL) {
 480         _current_class_entry = _current_loader_data->klasses();
 481       }  // else try_get_next_class will start at the head
 482     }
 483   }
 484 
 485   void adjust_saved_class(Klass* klass) {
 486     if (_current_class_entry == klass) {
 487       _current_class_entry = klass->next_link();
 488     }
 489   }
 490 };
 491 
 492 static ClassLoaderDataGraphKlassIteratorStatic static_klass_iterator;
 493 
 494 InstanceKlass* ClassLoaderDataGraph::try_get_next_class() {
 495   return static_klass_iterator.try_get_next_class();
 496 }
 497 
 498 
 499 // Remove a klass from the _klasses list for scratch_class during redefinition
 500 // or parsed class in the case of an error.
 501 void ClassLoaderData::remove_class(Klass* scratch_class) {
 502   assert(SafepointSynchronize::is_at_safepoint(), "only called at safepoint");
 503 
 504   // Adjust global class iterator.
 505   static_klass_iterator.adjust_saved_class(scratch_class);
 506 
 507   Klass* prev = NULL;
 508   for (Klass* k = _klasses; k != NULL; k = k->next_link()) {
 509     if (k == scratch_class) {
 510       if (prev == NULL) {
 511         _klasses = k->next_link();
 512       } else {
 513         Klass* next = k->next_link();
 514         prev->set_next_link(next);
 515       }
 516 
 517       if (k->is_array_klass()) {
 518         ClassLoaderDataGraph::dec_array_classes(1);
 519       } else {
 520         ClassLoaderDataGraph::dec_instance_classes(1);
 521       }
 522 
 523       return;
 524     }
 525     prev = k;
 526     assert(k != k->next_link(), "no loops!");
 527   }
 528   ShouldNotReachHere();   // should have found this class!!
 529 }
 530 
 531 void ClassLoaderData::unload() {
 532   _unloading = true;
 533 
 534   // Tell serviceability tools these classes are unloading
 535   classes_do(InstanceKlass::notify_unload_class);
 536 
 537   LogTarget(Debug, class, loader, data) lt;
 538   if (lt.is_enabled()) {
 539     ResourceMark rm;
 540     LogStream ls(lt);
 541     ls.print("unload ");
 542     print_value_on(&ls);
 543     ls.cr();
 544   }
 545 
 546   // Some items on the _deallocate_list need to free their C heap structures
 547   // if they are not already on the _klasses list.
 548   unload_deallocate_list();
 549 
 550   // Clean up global class iterator for compiler
 551   static_klass_iterator.adjust_saved_class(this);
 552 }
 553 
 554 ModuleEntryTable* ClassLoaderData::modules() {
 555   // Lazily create the module entry table at first request.
 556   // Lock-free access requires load_acquire.
 557   ModuleEntryTable* modules = OrderAccess::load_acquire(&_modules);
 558   if (modules == NULL) {
 559     MutexLocker m1(Module_lock);
 560     // Check if _modules got allocated while we were waiting for this lock.
 561     if ((modules = _modules) == NULL) {
 562       modules = new ModuleEntryTable(ModuleEntryTable::_moduletable_entry_size);
 563 
 564       {
 565         MutexLockerEx m1(metaspace_lock(), Mutex::_no_safepoint_check_flag);
 566         // Ensure _modules is stable, since it is examined without a lock
 567         OrderAccess::release_store(&_modules, modules);
 568       }
 569     }
 570   }
 571   return modules;
 572 }
 573 
 574 const int _boot_loader_dictionary_size    = 1009;
 575 const int _default_loader_dictionary_size = 107;
 576 
 577 Dictionary* ClassLoaderData::create_dictionary() {
 578   assert(!is_anonymous(), "anonymous class loader data do not have a dictionary");
 579   int size;
 580   bool resizable = false;
 581   if (_the_null_class_loader_data == NULL) {
 582     size = _boot_loader_dictionary_size;
 583     resizable = true;
 584   } else if (class_loader()->is_a(SystemDictionary::reflect_DelegatingClassLoader_klass())) {
 585     size = 1;  // there's only one class in relection class loader and no initiated classes
 586   } else if (is_system_class_loader_data()) {
 587     size = _boot_loader_dictionary_size;
 588     resizable = true;
 589   } else {
 590     size = _default_loader_dictionary_size;
 591     resizable = true;
 592   }
 593   if (!DynamicallyResizeSystemDictionaries || DumpSharedSpaces || UseSharedSpaces) {
 594     resizable = false;
 595   }
 596   return new Dictionary(this, size, resizable);
 597 }
 598 
 599 // Unloading support
 600 oop ClassLoaderData::keep_alive_object() const {
 601   assert_locked_or_safepoint(_metaspace_lock);
 602   assert(!keep_alive(), "Don't use with CLDs that are artificially kept alive");
 603   return is_anonymous() ? _klasses->java_mirror() : class_loader();
 604 }
 605 
 606 bool ClassLoaderData::is_alive(BoolObjectClosure* is_alive_closure) const {
 607   bool alive = keep_alive() // null class loader and incomplete anonymous klasses.
 608       || is_alive_closure->do_object_b(keep_alive_object());
 609 
 610   return alive;
 611 }
 612 
 613 class ReleaseKlassClosure: public KlassClosure {
 614 private:
 615   size_t  _instance_class_released;
 616   size_t  _array_class_released;
 617 public:
 618   ReleaseKlassClosure() : _instance_class_released(0), _array_class_released(0) { }
 619 
 620   size_t instance_class_released() const { return _instance_class_released; }
 621   size_t array_class_released()    const { return _array_class_released;    }
 622 
 623   void do_klass(Klass* k) {
 624     if (k->is_array_klass()) {
 625       _array_class_released ++;
 626     } else {
 627       assert(k->is_instance_klass(), "Must be");
 628       _instance_class_released ++;
 629       InstanceKlass::release_C_heap_structures(InstanceKlass::cast(k));
 630     }
 631   }
 632 };
 633 
 634 ClassLoaderData::~ClassLoaderData() {
 635   // Release C heap structures for all the classes.
 636   ReleaseKlassClosure cl;
 637   classes_do(&cl);
 638 
 639   ClassLoaderDataGraph::dec_array_classes(cl.array_class_released());
 640   ClassLoaderDataGraph::dec_instance_classes(cl.instance_class_released());
 641 
 642   // Release C heap allocated hashtable for all the packages.
 643   if (_packages != NULL) {
 644     // Destroy the table itself
 645     delete _packages;
 646     _packages = NULL;
 647   }
 648 
 649   // Release C heap allocated hashtable for all the modules.
 650   if (_modules != NULL) {
 651     // Destroy the table itself
 652     delete _modules;
 653     _modules = NULL;
 654   }
 655 
 656   // Release C heap allocated hashtable for the dictionary
 657   if (_dictionary != NULL) {
 658     // Destroy the table itself
 659     delete _dictionary;
 660     _dictionary = NULL;
 661   }
 662 
 663   if (_unnamed_module != NULL) {
 664     _unnamed_module->delete_unnamed_module();
 665     _unnamed_module = NULL;
 666   }
 667 
 668   // release the metaspace
 669   Metaspace *m = _metaspace;
 670   if (m != NULL) {
 671     _metaspace = NULL;
 672     delete m;
 673   }
 674   // Clear all the JNI handles for methods
 675   // These aren't deallocated and are going to look like a leak, but that's
 676   // needed because we can't really get rid of jmethodIDs because we don't
 677   // know when native code is going to stop using them.  The spec says that
 678   // they're "invalid" but existing programs likely rely on their being
 679   // NULL after class unloading.
 680   if (_jmethod_ids != NULL) {
 681     Method::clear_jmethod_ids(this);
 682   }
 683   // Delete lock
 684   delete _metaspace_lock;
 685 
 686   // Delete free list
 687   if (_deallocate_list != NULL) {
 688     delete _deallocate_list;
 689   }
 690 }
 691 
 692 // Returns true if this class loader data is for the app class loader
 693 // or a user defined system class loader.  (Note that the class loader
 694 // data may be anonymous.)
 695 bool ClassLoaderData::is_system_class_loader_data() const {
 696   return SystemDictionary::is_system_class_loader(class_loader());
 697 }
 698 
 699 // Returns true if this class loader data is for the platform class loader.
 700 // (Note that the class loader data may be anonymous.)
 701 bool ClassLoaderData::is_platform_class_loader_data() const {
 702   return SystemDictionary::is_platform_class_loader(class_loader());
 703 }
 704 
 705 // Returns true if the class loader for this class loader data is one of
 706 // the 3 builtin (boot application/system or platform) class loaders,
 707 // including a user-defined system class loader.  Note that if the class
 708 // loader data is for an anonymous class then it may get freed by a GC
 709 // even if its class loader is one of these loaders.
 710 bool ClassLoaderData::is_builtin_class_loader_data() const {
 711   return (is_boot_class_loader_data() ||
 712           SystemDictionary::is_system_class_loader(class_loader()) ||
 713           SystemDictionary::is_platform_class_loader(class_loader()));
 714 }
 715 
 716 // Returns true if this class loader data is a class loader data
 717 // that is not ever freed by a GC.  It must be one of the builtin
 718 // class loaders and not anonymous.
 719 bool ClassLoaderData::is_permanent_class_loader_data() const {
 720   return is_builtin_class_loader_data() && !is_anonymous();
 721 }
 722 
 723 Metaspace* ClassLoaderData::metaspace_non_null() {
 724   // If the metaspace has not been allocated, create a new one.  Might want
 725   // to create smaller arena for Reflection class loaders also.
 726   // The reason for the delayed allocation is because some class loaders are
 727   // simply for delegating with no metadata of their own.
 728   // Lock-free access requires load_acquire.
 729   Metaspace* metaspace = OrderAccess::load_acquire(&_metaspace);
 730   if (metaspace == NULL) {
 731     MutexLockerEx ml(_metaspace_lock,  Mutex::_no_safepoint_check_flag);
 732     // Check if _metaspace got allocated while we were waiting for this lock.
 733     if ((metaspace = _metaspace) == NULL) {
 734       if (this == the_null_class_loader_data()) {
 735         assert (class_loader() == NULL, "Must be");
 736         metaspace = new Metaspace(_metaspace_lock, Metaspace::BootMetaspaceType);
 737       } else if (is_anonymous()) {
 738         metaspace = new Metaspace(_metaspace_lock, Metaspace::AnonymousMetaspaceType);
 739       } else if (class_loader()->is_a(SystemDictionary::reflect_DelegatingClassLoader_klass())) {
 740         metaspace = new Metaspace(_metaspace_lock, Metaspace::ReflectionMetaspaceType);
 741       } else {
 742         metaspace = new Metaspace(_metaspace_lock, Metaspace::StandardMetaspaceType);
 743       }
 744       // Ensure _metaspace is stable, since it is examined without a lock
 745       OrderAccess::release_store(&_metaspace, metaspace);
 746     }
 747   }
 748   return metaspace;
 749 }
 750 
 751 OopHandle ClassLoaderData::add_handle(Handle h) {
 752   MutexLockerEx ml(metaspace_lock(),  Mutex::_no_safepoint_check_flag);
 753   record_modified_oops();
 754   return OopHandle(_handles.add(h()));
 755 }
 756 
 757 void ClassLoaderData::remove_handle(OopHandle h) {
 758   assert(!is_unloading(), "Do not remove a handle for a CLD that is unloading");
 759   oop* ptr = h.ptr_raw();
 760   if (ptr != NULL) {
 761     assert(_handles.contains(*ptr), "Got unexpected handle " PTR_FORMAT, p2i(ptr));
 762     // This root is not walked in safepoints, and hence requires an appropriate
 763     // decorator that e.g. maintains the SATB invariant in SATB collectors.
 764     RootAccess<IN_CONCURRENT_ROOT>::oop_store(ptr, oop(NULL));
 765   }
 766 }
 767 
 768 void ClassLoaderData::init_handle_locked(OopHandle& dest, Handle h) {
 769   MutexLockerEx ml(metaspace_lock(),  Mutex::_no_safepoint_check_flag);
 770   if (dest.resolve() != NULL) {
 771     return;
 772   } else {
 773     dest = _handles.add(h());
 774   }
 775 }
 776 
 777 // Add this metadata pointer to be freed when it's safe.  This is only during
 778 // class unloading because Handles might point to this metadata field.
 779 void ClassLoaderData::add_to_deallocate_list(Metadata* m) {
 780   // Metadata in shared region isn't deleted.
 781   if (!m->is_shared()) {
 782     MutexLockerEx ml(metaspace_lock(),  Mutex::_no_safepoint_check_flag);
 783     if (_deallocate_list == NULL) {
 784       _deallocate_list = new (ResourceObj::C_HEAP, mtClass) GrowableArray<Metadata*>(100, true);
 785     }
 786     _deallocate_list->append_if_missing(m);
 787   }
 788 }
 789 
 790 // Deallocate free metadata on the free list.  How useful the PermGen was!
 791 void ClassLoaderData::free_deallocate_list() {
 792   // Don't need lock, at safepoint
 793   assert(SafepointSynchronize::is_at_safepoint(), "only called at safepoint");
 794   assert(!is_unloading(), "only called for ClassLoaderData that are not unloading");
 795   if (_deallocate_list == NULL) {
 796     return;
 797   }
 798   // Go backwards because this removes entries that are freed.
 799   for (int i = _deallocate_list->length() - 1; i >= 0; i--) {
 800     Metadata* m = _deallocate_list->at(i);
 801     if (!m->on_stack()) {
 802       _deallocate_list->remove_at(i);
 803       // There are only three types of metadata that we deallocate directly.
 804       // Cast them so they can be used by the template function.
 805       if (m->is_method()) {
 806         MetadataFactory::free_metadata(this, (Method*)m);
 807       } else if (m->is_constantPool()) {
 808         MetadataFactory::free_metadata(this, (ConstantPool*)m);
 809       } else if (m->is_klass()) {
 810         MetadataFactory::free_metadata(this, (InstanceKlass*)m);
 811       } else {
 812         ShouldNotReachHere();
 813       }
 814     } else {
 815       // Metadata is alive.
 816       // If scratch_class is on stack then it shouldn't be on this list!
 817       assert(!m->is_klass() || !((InstanceKlass*)m)->is_scratch_class(),
 818              "scratch classes on this list should be dead");
 819       // Also should assert that other metadata on the list was found in handles.
 820     }
 821   }
 822 }
 823 
 824 // This is distinct from free_deallocate_list.  For class loader data that are
 825 // unloading, this frees the C heap memory for items on the list, and unlinks
 826 // scratch or error classes so that unloading events aren't triggered for these
 827 // classes. The metadata is removed with the unloading metaspace.
 828 // There isn't C heap memory allocated for methods, so nothing is done for them.
 829 void ClassLoaderData::unload_deallocate_list() {
 830   // Don't need lock, at safepoint
 831   assert(SafepointSynchronize::is_at_safepoint(), "only called at safepoint");
 832   assert(is_unloading(), "only called for ClassLoaderData that are unloading");
 833   if (_deallocate_list == NULL) {
 834     return;
 835   }
 836   // Go backwards because this removes entries that are freed.
 837   for (int i = _deallocate_list->length() - 1; i >= 0; i--) {
 838     Metadata* m = _deallocate_list->at(i);
 839     assert (!m->on_stack(), "wouldn't be unloading if this were so");
 840     _deallocate_list->remove_at(i);
 841     if (m->is_constantPool()) {
 842       ((ConstantPool*)m)->release_C_heap_structures();
 843     } else if (m->is_klass()) {
 844       InstanceKlass* ik = (InstanceKlass*)m;
 845       // also releases ik->constants() C heap memory
 846       InstanceKlass::release_C_heap_structures(ik);
 847       // Remove the class so unloading events aren't triggered for
 848       // this class (scratch or error class) in do_unloading().
 849       remove_class(ik);
 850     }
 851   }
 852 }
 853 
 854 // These anonymous class loaders are to contain classes used for JSR292
 855 ClassLoaderData* ClassLoaderData::anonymous_class_loader_data(Handle loader) {
 856   // Add a new class loader data to the graph.
 857   return ClassLoaderDataGraph::add(loader, true);
 858 }
 859 
 860 const char* ClassLoaderData::loader_name() const {
 861   // Handles null class loader
 862   return SystemDictionary::loader_name(class_loader());
 863 }
 864 
 865 
 866 void ClassLoaderData::print_value_on(outputStream* out) const {
 867   if (class_loader() != NULL) {
 868     out->print("loader data: " INTPTR_FORMAT " for instance ", p2i(this));
 869     class_loader()->print_value_on(out);  // includes loader_name() and address of class loader instance
 870   } else {
 871     // loader data: 0xsomeaddr of <bootloader>
 872     out->print("loader data: " INTPTR_FORMAT " of %s", p2i(this), loader_name());
 873   }
 874   if (is_anonymous()) {
 875     out->print(" anonymous");
 876   }
 877 }
 878 
 879 #ifndef PRODUCT
 880 void ClassLoaderData::print_on(outputStream* out) const {
 881   out->print("ClassLoaderData CLD: " PTR_FORMAT ", loader: " PTR_FORMAT ", loader_klass: %s {",
 882               p2i(this), p2i((void *)class_loader()), loader_name());
 883   if (is_anonymous()) out->print(" anonymous");
 884   if (claimed()) out->print(" claimed");
 885   if (is_unloading()) out->print(" unloading");
 886   out->print(" metaspace: " INTPTR_FORMAT, p2i(metaspace_or_null()));
 887 
 888   if (_jmethod_ids != NULL) {
 889     Method::print_jmethod_ids(this, out);
 890   }
 891   out->print(" handles count %d", _handles.count());
 892   out->print(" dependencies %d", _dependency_count);
 893   out->print_cr("}");
 894 }
 895 #endif // PRODUCT
 896 
 897 void ClassLoaderData::verify() {
 898   assert_locked_or_safepoint(_metaspace_lock);
 899   oop cl = class_loader();
 900 
 901   guarantee(this == class_loader_data(cl) || is_anonymous(), "Must be the same");
 902   guarantee(cl != NULL || this == ClassLoaderData::the_null_class_loader_data() || is_anonymous(), "must be");
 903 
 904   // Verify the integrity of the allocated space.
 905   if (metaspace_or_null() != NULL) {
 906     metaspace_or_null()->verify();
 907   }
 908 
 909   for (Klass* k = _klasses; k != NULL; k = k->next_link()) {
 910     guarantee(k->class_loader_data() == this, "Must be the same");
 911     k->verify();
 912     assert(k != k->next_link(), "no loops!");
 913   }
 914 }
 915 
 916 bool ClassLoaderData::contains_klass(Klass* klass) {
 917   // Lock-free access requires load_acquire
 918   for (Klass* k = OrderAccess::load_acquire(&_klasses); k != NULL; k = k->next_link()) {
 919     if (k == klass) return true;
 920   }
 921   return false;
 922 }
 923 
 924 
 925 // GC root of class loader data created.
 926 ClassLoaderData* ClassLoaderDataGraph::_head = NULL;
 927 ClassLoaderData* ClassLoaderDataGraph::_unloading = NULL;
 928 ClassLoaderData* ClassLoaderDataGraph::_saved_unloading = NULL;
 929 ClassLoaderData* ClassLoaderDataGraph::_saved_head = NULL;
 930 
 931 bool ClassLoaderDataGraph::_should_purge = false;
 932 bool ClassLoaderDataGraph::_metaspace_oom = false;
 933 
 934 // Add a new class loader data node to the list.  Assign the newly created
 935 // ClassLoaderData into the java/lang/ClassLoader object as a hidden field
 936 ClassLoaderData* ClassLoaderDataGraph::add(Handle loader, bool is_anonymous) {
 937   NoSafepointVerifier no_safepoints; // we mustn't GC until we've installed the
 938                                      // ClassLoaderData in the graph since the CLD
 939                                      // contains unhandled oops
 940 
 941   ClassLoaderData* cld = new ClassLoaderData(loader, is_anonymous);
 942 
 943 
 944   if (!is_anonymous) {
 945     // First, Atomically set it
 946     ClassLoaderData* old = java_lang_ClassLoader::cmpxchg_loader_data(cld, loader(), NULL);
 947     if (old != NULL) {
 948       delete cld;
 949       // Returns the data.
 950       return old;
 951     }
 952   }
 953 
 954   // We won the race, and therefore the task of adding the data to the list of
 955   // class loader data
 956   ClassLoaderData** list_head = &_head;
 957   ClassLoaderData* next = _head;
 958 
 959   do {
 960     cld->set_next(next);
 961     ClassLoaderData* exchanged = Atomic::cmpxchg(cld, list_head, next);
 962     if (exchanged == next) {
 963       LogTarget(Debug, class, loader, data) lt;
 964       if (lt.is_enabled()) {
 965         ResourceMark rm;
 966         LogStream ls(lt);
 967         ls.print("create ");
 968         cld->print_value_on(&ls);
 969         ls.cr();
 970       }
 971       return cld;
 972     }
 973     next = exchanged;
 974   } while (true);
 975 }
 976 
 977 void ClassLoaderDataGraph::oops_do(OopClosure* f, bool must_claim) {
 978   for (ClassLoaderData* cld = _head; cld != NULL; cld = cld->next()) {
 979     cld->oops_do(f, must_claim);
 980   }
 981 }
 982 
 983 void ClassLoaderDataGraph::keep_alive_oops_do(OopClosure* f, bool must_claim) {
 984   for (ClassLoaderData* cld = _head; cld != NULL; cld = cld->next()) {
 985     if (cld->keep_alive()) {
 986       cld->oops_do(f, must_claim);
 987     }
 988   }
 989 }
 990 
 991 void ClassLoaderDataGraph::always_strong_oops_do(OopClosure* f, bool must_claim) {
 992   if (ClassUnloading) {
 993     keep_alive_oops_do(f, must_claim);
 994   } else {
 995     oops_do(f, must_claim);
 996   }
 997 }
 998 
 999 void ClassLoaderDataGraph::cld_do(CLDClosure* cl) {
1000   for (ClassLoaderData* cld = _head; cl != NULL && cld != NULL; cld = cld->next()) {
1001     cl->do_cld(cld);
1002   }
1003 }
1004 
1005 void ClassLoaderDataGraph::cld_unloading_do(CLDClosure* cl) {
1006   assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint!");
1007   // Only walk the head until any clds not purged from prior unloading
1008   // (CMS doesn't purge right away).
1009   for (ClassLoaderData* cld = _unloading; cld != _saved_unloading; cld = cld->next()) {
1010     assert(cld->is_unloading(), "invariant");
1011     cl->do_cld(cld);
1012   }
1013 }
1014 
1015 void ClassLoaderDataGraph::roots_cld_do(CLDClosure* strong, CLDClosure* weak) {
1016   for (ClassLoaderData* cld = _head;  cld != NULL; cld = cld->_next) {
1017     CLDClosure* closure = cld->keep_alive() ? strong : weak;
1018     if (closure != NULL) {
1019       closure->do_cld(cld);
1020     }
1021   }
1022 }
1023 
1024 void ClassLoaderDataGraph::keep_alive_cld_do(CLDClosure* cl) {
1025   roots_cld_do(cl, NULL);
1026 }
1027 
1028 void ClassLoaderDataGraph::always_strong_cld_do(CLDClosure* cl) {
1029   if (ClassUnloading) {
1030     keep_alive_cld_do(cl);
1031   } else {
1032     cld_do(cl);
1033   }
1034 }
1035 
1036 void ClassLoaderDataGraph::classes_do(KlassClosure* klass_closure) {
1037   for (ClassLoaderData* cld = _head; cld != NULL; cld = cld->next()) {
1038     cld->classes_do(klass_closure);
1039   }
1040 }
1041 
1042 void ClassLoaderDataGraph::classes_do(void f(Klass* const)) {
1043   for (ClassLoaderData* cld = _head; cld != NULL; cld = cld->next()) {
1044     cld->classes_do(f);
1045   }
1046 }
1047 
1048 void ClassLoaderDataGraph::methods_do(void f(Method*)) {
1049   for (ClassLoaderData* cld = _head; cld != NULL; cld = cld->next()) {
1050     cld->methods_do(f);
1051   }
1052 }
1053 
1054 void ClassLoaderDataGraph::modules_do(void f(ModuleEntry*)) {
1055   assert_locked_or_safepoint(Module_lock);
1056   for (ClassLoaderData* cld = _head; cld != NULL; cld = cld->next()) {
1057     cld->modules_do(f);
1058   }
1059 }
1060 
1061 void ClassLoaderDataGraph::modules_unloading_do(void f(ModuleEntry*)) {
1062   assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint!");
1063   // Only walk the head until any clds not purged from prior unloading
1064   // (CMS doesn't purge right away).
1065   for (ClassLoaderData* cld = _unloading; cld != _saved_unloading; cld = cld->next()) {
1066     assert(cld->is_unloading(), "invariant");
1067     cld->modules_do(f);
1068   }
1069 }
1070 
1071 void ClassLoaderDataGraph::packages_do(void f(PackageEntry*)) {
1072   assert_locked_or_safepoint(Module_lock);
1073   for (ClassLoaderData* cld = _head; cld != NULL; cld = cld->next()) {
1074     cld->packages_do(f);
1075   }
1076 }
1077 
1078 void ClassLoaderDataGraph::packages_unloading_do(void f(PackageEntry*)) {
1079   assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint!");
1080   // Only walk the head until any clds not purged from prior unloading
1081   // (CMS doesn't purge right away).
1082   for (ClassLoaderData* cld = _unloading; cld != _saved_unloading; cld = cld->next()) {
1083     assert(cld->is_unloading(), "invariant");
1084     cld->packages_do(f);
1085   }
1086 }
1087 
1088 void ClassLoaderDataGraph::loaded_classes_do(KlassClosure* klass_closure) {
1089   for (ClassLoaderData* cld = _head; cld != NULL; cld = cld->next()) {
1090     cld->loaded_classes_do(klass_closure);
1091   }
1092 }
1093 
1094 void ClassLoaderDataGraph::classes_unloading_do(void f(Klass* const)) {
1095   assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint!");
1096   // Only walk the head until any clds not purged from prior unloading
1097   // (CMS doesn't purge right away).
1098   for (ClassLoaderData* cld = _unloading; cld != _saved_unloading; cld = cld->next()) {
1099     assert(cld->is_unloading(), "invariant");
1100     cld->classes_do(f);
1101   }
1102 }
1103 
1104 #define FOR_ALL_DICTIONARY(X) for (ClassLoaderData* X = _head; X != NULL; X = X->next()) \
1105                                 if (X->dictionary() != NULL)
1106 
1107 // Walk classes in the loaded class dictionaries in various forms.
1108 // Only walks the classes defined in this class loader.
1109 void ClassLoaderDataGraph::dictionary_classes_do(void f(InstanceKlass*)) {
1110   FOR_ALL_DICTIONARY(cld) {
1111     cld->dictionary()->classes_do(f);
1112   }
1113 }
1114 
1115 // Only walks the classes defined in this class loader.
1116 void ClassLoaderDataGraph::dictionary_classes_do(void f(InstanceKlass*, TRAPS), TRAPS) {
1117   FOR_ALL_DICTIONARY(cld) {
1118     cld->dictionary()->classes_do(f, CHECK);
1119   }
1120 }
1121 
1122 // Walks all entries in the dictionary including entries initiated by this class loader.
1123 void ClassLoaderDataGraph::dictionary_all_entries_do(void f(InstanceKlass*, ClassLoaderData*)) {
1124   FOR_ALL_DICTIONARY(cld) {
1125     cld->dictionary()->all_entries_do(f);
1126   }
1127 }
1128 
1129 void ClassLoaderDataGraph::verify_dictionary() {
1130   FOR_ALL_DICTIONARY(cld) {
1131     cld->dictionary()->verify();
1132   }
1133 }
1134 
1135 void ClassLoaderDataGraph::print_dictionary(outputStream* st) {
1136   FOR_ALL_DICTIONARY(cld) {
1137     st->print("Dictionary for ");
1138     cld->print_value_on(st);
1139     st->cr();
1140     cld->dictionary()->print_on(st);
1141     st->cr();
1142   }
1143 }
1144 
1145 void ClassLoaderDataGraph::print_dictionary_statistics(outputStream* st) {
1146   FOR_ALL_DICTIONARY(cld) {
1147     ResourceMark rm;
1148     stringStream tempst;
1149     tempst.print("System Dictionary for %s", cld->loader_name());
1150     cld->dictionary()->print_table_statistics(st, tempst.as_string());
1151   }
1152 }
1153 
1154 GrowableArray<ClassLoaderData*>* ClassLoaderDataGraph::new_clds() {
1155   assert(_head == NULL || _saved_head != NULL, "remember_new_clds(true) not called?");
1156 
1157   GrowableArray<ClassLoaderData*>* array = new GrowableArray<ClassLoaderData*>();
1158 
1159   // The CLDs in [_head, _saved_head] were all added during last call to remember_new_clds(true);
1160   ClassLoaderData* curr = _head;
1161   while (curr != _saved_head) {
1162     if (!curr->claimed()) {
1163       array->push(curr);
1164       LogTarget(Debug, class, loader, data) lt;
1165       if (lt.is_enabled()) {
1166         LogStream ls(lt);
1167         ls.print("found new CLD: ");
1168         curr->print_value_on(&ls);
1169         ls.cr();
1170       }
1171     }
1172 
1173     curr = curr->_next;
1174   }
1175 
1176   return array;
1177 }
1178 
1179 bool ClassLoaderDataGraph::unload_list_contains(const void* x) {
1180   assert(SafepointSynchronize::is_at_safepoint(), "only safe to call at safepoint");
1181   for (ClassLoaderData* cld = _unloading; cld != NULL; cld = cld->next()) {
1182     if (cld->metaspace_or_null() != NULL && cld->metaspace_or_null()->contains(x)) {
1183       return true;
1184     }
1185   }
1186   return false;
1187 }
1188 
1189 #ifndef PRODUCT
1190 bool ClassLoaderDataGraph::contains_loader_data(ClassLoaderData* loader_data) {
1191   for (ClassLoaderData* data = _head; data != NULL; data = data->next()) {
1192     if (loader_data == data) {
1193       return true;
1194     }
1195   }
1196 
1197   return false;
1198 }
1199 #endif // PRODUCT
1200 
1201 
1202 // Move class loader data from main list to the unloaded list for unloading
1203 // and deallocation later.
1204 bool ClassLoaderDataGraph::do_unloading(BoolObjectClosure* is_alive_closure,
1205                                         bool clean_previous_versions) {
1206 
1207   ClassLoaderData* data = _head;
1208   ClassLoaderData* prev = NULL;
1209   bool seen_dead_loader = false;
1210 
1211   // Mark metadata seen on the stack only so we can delete unneeded entries.
1212   // Only walk all metadata, including the expensive code cache walk, for Full GC
1213   // and only if class redefinition and if there's previous versions of
1214   // Klasses to delete.
1215   bool walk_all_metadata = clean_previous_versions &&
1216                            JvmtiExport::has_redefined_a_class() &&
1217                            InstanceKlass::has_previous_versions_and_reset();
1218   MetadataOnStackMark md_on_stack(walk_all_metadata);
1219 
1220   // Save previous _unloading pointer for CMS which may add to unloading list before
1221   // purging and we don't want to rewalk the previously unloaded class loader data.
1222   _saved_unloading = _unloading;
1223 
1224   data = _head;
1225   while (data != NULL) {
1226     if (data->is_alive(is_alive_closure)) {
1227       // clean metaspace
1228       if (walk_all_metadata) {
1229         data->classes_do(InstanceKlass::purge_previous_versions);
1230       }
1231       data->free_deallocate_list();
1232       prev = data;
1233       data = data->next();
1234       continue;
1235     }
1236     seen_dead_loader = true;
1237     ClassLoaderData* dead = data;
1238     dead->unload();
1239     data = data->next();
1240     // Remove from loader list.
1241     // This class loader data will no longer be found
1242     // in the ClassLoaderDataGraph.
1243     if (prev != NULL) {
1244       prev->set_next(data);
1245     } else {
1246       assert(dead == _head, "sanity check");
1247       _head = data;
1248     }
1249     dead->set_next(_unloading);
1250     _unloading = dead;
1251   }
1252 
1253   if (seen_dead_loader) {
1254     data = _head;
1255     while (data != NULL) {
1256       // Remove entries in the dictionary of live class loader that have
1257       // initiated loading classes in a dead class loader.
1258       if (data->dictionary() != NULL) {
1259         data->dictionary()->do_unloading(is_alive_closure);
1260       }
1261       // Walk a ModuleEntry's reads, and a PackageEntry's exports
1262       // lists to determine if there are modules on those lists that are now
1263       // dead and should be removed.  A module's life cycle is equivalent
1264       // to its defining class loader's life cycle.  Since a module is
1265       // considered dead if its class loader is dead, these walks must
1266       // occur after each class loader's aliveness is determined.
1267       if (data->packages() != NULL) {
1268         data->packages()->purge_all_package_exports();
1269       }
1270       if (data->modules_defined()) {
1271         data->modules()->purge_all_module_reads();
1272       }
1273       data = data->next();
1274     }
1275 
1276     post_class_unload_events();
1277   }
1278 
1279   return seen_dead_loader;
1280 }
1281 
1282 void ClassLoaderDataGraph::purge() {
1283   assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint!");
1284   ClassLoaderData* list = _unloading;
1285   _unloading = NULL;
1286   ClassLoaderData* next = list;
1287   bool classes_unloaded = false;
1288   while (next != NULL) {
1289     ClassLoaderData* purge_me = next;
1290     next = purge_me->next();
1291     delete purge_me;
1292     classes_unloaded = true;
1293   }
1294   if (classes_unloaded) {
1295     Metaspace::purge();
1296     set_metaspace_oom(false);
1297   }
1298 }
1299 
1300 int ClassLoaderDataGraph::resize_if_needed() {
1301   assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint!");
1302   int resized = 0;
1303   if (Dictionary::does_any_dictionary_needs_resizing()) {
1304     FOR_ALL_DICTIONARY(cld) {
1305       if (cld->dictionary()->resize_if_needed()) {
1306         resized++;
1307       }
1308     }
1309   }
1310   return resized;
1311 }
1312 
1313 void ClassLoaderDataGraph::post_class_unload_events() {
1314 #if INCLUDE_TRACE
1315   assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint!");
1316   if (Tracing::enabled()) {
1317     if (Tracing::is_event_enabled(TraceClassUnloadEvent)) {
1318       assert(_unloading != NULL, "need class loader data unload list!");
1319       _class_unload_time = Ticks::now();
1320       classes_unloading_do(&class_unload_event);
1321     }
1322     Tracing::on_unloading_classes();
1323   }
1324 #endif
1325 }
1326 
1327 ClassLoaderDataGraphKlassIteratorAtomic::ClassLoaderDataGraphKlassIteratorAtomic()
1328     : _next_klass(NULL) {
1329   ClassLoaderData* cld = ClassLoaderDataGraph::_head;
1330   Klass* klass = NULL;
1331 
1332   // Find the first klass in the CLDG.
1333   while (cld != NULL) {
1334     assert_locked_or_safepoint(cld->metaspace_lock());
1335     klass = cld->_klasses;
1336     if (klass != NULL) {
1337       _next_klass = klass;
1338       return;
1339     }
1340     cld = cld->next();
1341   }
1342 }
1343 
1344 Klass* ClassLoaderDataGraphKlassIteratorAtomic::next_klass_in_cldg(Klass* klass) {
1345   Klass* next = klass->next_link();
1346   if (next != NULL) {
1347     return next;
1348   }
1349 
1350   // No more klasses in the current CLD. Time to find a new CLD.
1351   ClassLoaderData* cld = klass->class_loader_data();
1352   assert_locked_or_safepoint(cld->metaspace_lock());
1353   while (next == NULL) {
1354     cld = cld->next();
1355     if (cld == NULL) {
1356       break;
1357     }
1358     next = cld->_klasses;
1359   }
1360 
1361   return next;
1362 }
1363 
1364 Klass* ClassLoaderDataGraphKlassIteratorAtomic::next_klass() {
1365   Klass* head = _next_klass;
1366 
1367   while (head != NULL) {
1368     Klass* next = next_klass_in_cldg(head);
1369 
1370     Klass* old_head = Atomic::cmpxchg(next, &_next_klass, head);
1371 
1372     if (old_head == head) {
1373       return head; // Won the CAS.
1374     }
1375 
1376     head = old_head;
1377   }
1378 
1379   // Nothing more for the iterator to hand out.
1380   assert(head == NULL, "head is " PTR_FORMAT ", expected not null:", p2i(head));
1381   return NULL;
1382 }
1383 
1384 ClassLoaderDataGraphMetaspaceIterator::ClassLoaderDataGraphMetaspaceIterator() {
1385   _data = ClassLoaderDataGraph::_head;
1386 }
1387 
1388 ClassLoaderDataGraphMetaspaceIterator::~ClassLoaderDataGraphMetaspaceIterator() {}
1389 
1390 #ifndef PRODUCT
1391 // callable from debugger
1392 extern "C" int print_loader_data_graph() {
1393   ResourceMark rm;
1394   ClassLoaderDataGraph::print_on(tty);
1395   return 0;
1396 }
1397 
1398 void ClassLoaderDataGraph::verify() {
1399   for (ClassLoaderData* data = _head; data != NULL; data = data->next()) {
1400     data->verify();
1401   }
1402 }
1403 
1404 void ClassLoaderDataGraph::print_on(outputStream * const out) {
1405   for (ClassLoaderData* data = _head; data != NULL; data = data->next()) {
1406     data->print_on(out);
1407   }
1408 }
1409 #endif // PRODUCT
1410 
1411 #if INCLUDE_TRACE
1412 
1413 Ticks ClassLoaderDataGraph::_class_unload_time;
1414 
1415 void ClassLoaderDataGraph::class_unload_event(Klass* const k) {
1416   assert(k != NULL, "invariant");
1417 
1418   // post class unload event
1419   EventClassUnload event(UNTIMED);
1420   event.set_endtime(_class_unload_time);
1421   event.set_unloadedClass(k);
1422   event.set_definingClassLoader(k->class_loader_data());
1423   event.commit();
1424 }
1425 
1426 #endif // INCLUDE_TRACE