1 /*
   2  * Copyright (c) 2012, 2017, 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/javaClasses.hpp"
  53 #include "classfile/metadataOnStackMark.hpp"
  54 #include "classfile/moduleEntry.hpp"
  55 #include "classfile/packageEntry.hpp"
  56 #include "classfile/systemDictionary.hpp"
  57 #include "code/codeCache.hpp"
  58 #include "gc/shared/gcLocker.hpp"
  59 #include "logging/log.hpp"
  60 #include "logging/logStream.hpp"
  61 #include "memory/metadataFactory.hpp"
  62 #include "memory/metaspaceShared.hpp"
  63 #include "memory/oopFactory.hpp"
  64 #include "memory/resourceArea.hpp"
  65 #include "oops/objArrayOop.inline.hpp"
  66 #include "oops/oop.inline.hpp"
  67 #include "runtime/atomic.hpp"
  68 #include "runtime/javaCalls.hpp"
  69 #include "runtime/jniHandles.hpp"
  70 #include "runtime/mutex.hpp"
  71 #include "runtime/orderAccess.hpp"
  72 #include "runtime/safepoint.hpp"
  73 #include "runtime/synchronizer.hpp"
  74 #include "utilities/growableArray.hpp"
  75 #include "utilities/macros.hpp"
  76 #include "utilities/ostream.hpp"
  77 #if INCLUDE_TRACE
  78 #include "trace/tracing.hpp"
  79 #endif
  80 
  81 // helper function to avoid in-line casts
  82 template <typename T> static T* load_ptr_acquire(T* volatile *p) {
  83   return static_cast<T*>(OrderAccess::load_ptr_acquire(p));
  84 }
  85 
  86 ClassLoaderData * ClassLoaderData::_the_null_class_loader_data = NULL;
  87 
  88 ClassLoaderData::ClassLoaderData(Handle h_class_loader, bool is_anonymous, Dependencies dependencies) :
  89   _class_loader(h_class_loader()),
  90   _is_anonymous(is_anonymous),
  91   // An anonymous class loader data doesn't have anything to keep
  92   // it from being unloaded during parsing of the anonymous class.
  93   // The null-class-loader should always be kept alive.
  94   _keep_alive((is_anonymous || h_class_loader.is_null()) ? 1 : 0),
  95   _metaspace(NULL), _unloading(false), _klasses(NULL),
  96   _modules(NULL), _packages(NULL),
  97   _claimed(0), _jmethod_ids(NULL), _handles(), _deallocate_list(NULL),
  98   _next(NULL), _dependencies(dependencies),
  99   _metaspace_lock(new Mutex(Monitor::leaf+1, "Metaspace allocation lock", true,
 100                             Monitor::_safepoint_check_never)) {
 101 
 102   // A ClassLoaderData created solely for an anonymous class should never have a
 103   // ModuleEntryTable or PackageEntryTable created for it. The defining package
 104   // and module for an anonymous class will be found in its host class.
 105   if (!is_anonymous) {
 106     _packages = new PackageEntryTable(PackageEntryTable::_packagetable_entry_size);
 107     if (h_class_loader.is_null()) {
 108       // Create unnamed module for boot loader
 109       _unnamed_module = ModuleEntry::create_boot_unnamed_module(this);
 110     } else {
 111       // Create unnamed module for all other loaders
 112       _unnamed_module = ModuleEntry::create_unnamed_module(this);
 113     }
 114   } else {
 115     _unnamed_module = NULL;
 116   }
 117   TRACE_INIT_ID(this);
 118 }
 119 
 120 void ClassLoaderData::init_dependencies(TRAPS) {
 121   assert(!Universe::is_fully_initialized(), "should only be called when initializing");
 122   assert(is_the_null_class_loader_data(), "should only call this for the null class loader");
 123   _dependencies.init(CHECK);
 124 }
 125 
 126 void ClassLoaderData::Dependencies::init(TRAPS) {
 127   // Create empty dependencies array to add to. CMS requires this to be
 128   // an oop so that it can track additions via card marks.  We think.
 129   _list_head = oopFactory::new_objectArray(2, CHECK);
 130 }
 131 
 132 ClassLoaderData::ChunkedHandleList::~ChunkedHandleList() {
 133   Chunk* c = _head;
 134   while (c != NULL) {
 135     Chunk* next = c->_next;
 136     delete c;
 137     c = next;
 138   }
 139 }
 140 
 141 oop* ClassLoaderData::ChunkedHandleList::add(oop o) {
 142   if (_head == NULL || _head->_size == Chunk::CAPACITY) {
 143     Chunk* next = new Chunk(_head);
 144     OrderAccess::release_store_ptr(&_head, next);
 145   }
 146   oop* handle = &_head->_data[_head->_size];
 147   *handle = o;
 148   OrderAccess::release_store(&_head->_size, _head->_size + 1);
 149   return handle;
 150 }
 151 
 152 inline void ClassLoaderData::ChunkedHandleList::oops_do_chunk(OopClosure* f, Chunk* c, const juint size) {
 153   for (juint i = 0; i < size; i++) {
 154     if (c->_data[i] != NULL) {
 155       f->do_oop(&c->_data[i]);
 156     }
 157   }
 158 }
 159 
 160 void ClassLoaderData::ChunkedHandleList::oops_do(OopClosure* f) {
 161   Chunk* head = (Chunk*) OrderAccess::load_ptr_acquire(&_head);
 162   if (head != NULL) {
 163     // Must be careful when reading size of head
 164     oops_do_chunk(f, head, OrderAccess::load_acquire(&head->_size));
 165     for (Chunk* c = head->_next; c != NULL; c = c->_next) {
 166       oops_do_chunk(f, c, c->_size);
 167     }
 168   }
 169 }
 170 
 171 #ifdef ASSERT
 172 class VerifyContainsOopClosure : public OopClosure {
 173   oop* _target;
 174   bool _found;
 175 
 176  public:
 177   VerifyContainsOopClosure(oop* target) : _target(target), _found(false) {}
 178 
 179   void do_oop(oop* p) {
 180     if (p == _target) {
 181       _found = true;
 182     }
 183   }
 184 
 185   void do_oop(narrowOop* p) {
 186     // The ChunkedHandleList should not contain any narrowOop
 187     ShouldNotReachHere();
 188   }
 189 
 190   bool found() const {
 191     return _found;
 192   }
 193 };
 194 
 195 bool ClassLoaderData::ChunkedHandleList::contains(oop* p) {
 196   VerifyContainsOopClosure cl(p);
 197   oops_do(&cl);
 198   return cl.found();
 199 }
 200 #endif
 201 
 202 bool ClassLoaderData::claim() {
 203   if (_claimed == 1) {
 204     return false;
 205   }
 206 
 207   return (int) Atomic::cmpxchg(1, &_claimed, 0) == 0;
 208 }
 209 
 210 // Anonymous classes have their own ClassLoaderData that is marked to keep alive
 211 // while the class is being parsed, and if the class appears on the module fixup list.
 212 // Due to the uniqueness that no other class shares the anonymous class' name or
 213 // ClassLoaderData, no other non-GC thread has knowledge of the anonymous class while
 214 // it is being defined, therefore _keep_alive is not volatile or atomic.
 215 void ClassLoaderData::inc_keep_alive() {
 216   if (is_anonymous()) {
 217     assert(_keep_alive >= 0, "Invalid keep alive increment count");
 218     _keep_alive++;
 219   }
 220 }
 221 
 222 void ClassLoaderData::dec_keep_alive() {
 223   if (is_anonymous()) {
 224     assert(_keep_alive > 0, "Invalid keep alive decrement count");
 225     _keep_alive--;
 226   }
 227 }
 228 
 229 void ClassLoaderData::oops_do(OopClosure* f, KlassClosure* klass_closure, bool must_claim) {
 230   if (must_claim && !claim()) {
 231     return;
 232   }
 233 
 234   f->do_oop(&_class_loader);
 235   _dependencies.oops_do(f);
 236 
 237   _handles.oops_do(f);
 238 
 239   if (klass_closure != NULL) {
 240     classes_do(klass_closure);
 241   }
 242 }
 243 
 244 void ClassLoaderData::Dependencies::oops_do(OopClosure* f) {
 245   f->do_oop((oop*)&_list_head);
 246 }
 247 
 248 void ClassLoaderData::classes_do(KlassClosure* klass_closure) {
 249   // Lock-free access requires load_ptr_acquire
 250   for (Klass* k = load_ptr_acquire(&_klasses); k != NULL; k = k->next_link()) {
 251     klass_closure->do_klass(k);
 252     assert(k != k->next_link(), "no loops!");
 253   }
 254 }
 255 
 256 void ClassLoaderData::classes_do(void f(Klass * const)) {
 257   // Lock-free access requires load_ptr_acquire
 258   for (Klass* k = load_ptr_acquire(&_klasses); k != NULL; k = k->next_link()) {
 259     f(k);
 260     assert(k != k->next_link(), "no loops!");
 261   }
 262 }
 263 
 264 void ClassLoaderData::methods_do(void f(Method*)) {
 265   // Lock-free access requires load_ptr_acquire
 266   for (Klass* k = load_ptr_acquire(&_klasses); k != NULL; k = k->next_link()) {
 267     if (k->is_instance_klass() && InstanceKlass::cast(k)->is_loaded()) {
 268       InstanceKlass::cast(k)->methods_do(f);
 269     }
 270   }
 271 }
 272 
 273 void ClassLoaderData::loaded_classes_do(KlassClosure* klass_closure) {
 274   // Lock-free access requires load_ptr_acquire
 275   for (Klass* k = load_ptr_acquire(&_klasses); k != NULL; k = k->next_link()) {
 276     // Do not filter ArrayKlass oops here...
 277     if (k->is_array_klass() || (k->is_instance_klass() && InstanceKlass::cast(k)->is_loaded())) {
 278       klass_closure->do_klass(k);
 279     }
 280   }
 281 }
 282 
 283 void ClassLoaderData::classes_do(void f(InstanceKlass*)) {
 284   // Lock-free access requires load_ptr_acquire
 285   for (Klass* k = load_ptr_acquire(&_klasses); k != NULL; k = k->next_link()) {
 286     if (k->is_instance_klass()) {
 287       f(InstanceKlass::cast(k));
 288     }
 289     assert(k != k->next_link(), "no loops!");
 290   }
 291 }
 292 
 293 void ClassLoaderData::modules_do(void f(ModuleEntry*)) {
 294   assert_locked_or_safepoint(Module_lock);
 295   if (_unnamed_module != NULL) {
 296     f(_unnamed_module);
 297   }
 298   if (_modules != NULL) {
 299     for (int i = 0; i < _modules->table_size(); i++) {
 300       for (ModuleEntry* entry = _modules->bucket(i);
 301            entry != NULL;
 302            entry = entry->next()) {
 303         f(entry);
 304       }
 305     }
 306   }
 307 }
 308 
 309 void ClassLoaderData::packages_do(void f(PackageEntry*)) {
 310   assert_locked_or_safepoint(Module_lock);
 311   if (_packages != NULL) {
 312     for (int i = 0; i < _packages->table_size(); i++) {
 313       for (PackageEntry* entry = _packages->bucket(i);
 314            entry != NULL;
 315            entry = entry->next()) {
 316         f(entry);
 317       }
 318     }
 319   }
 320 }
 321 
 322 void ClassLoaderData::record_dependency(const Klass* k, TRAPS) {
 323   assert(k != NULL, "invariant");
 324 
 325   ClassLoaderData * const from_cld = this;
 326   ClassLoaderData * const to_cld = k->class_loader_data();
 327 
 328   // Dependency to the null class loader data doesn't need to be recorded
 329   // because the null class loader data never goes away.
 330   if (to_cld->is_the_null_class_loader_data()) {
 331     return;
 332   }
 333 
 334   oop to;
 335   if (to_cld->is_anonymous()) {
 336     // Anonymous class dependencies are through the mirror.
 337     to = k->java_mirror();
 338   } else {
 339     to = to_cld->class_loader();
 340 
 341     // If from_cld is anonymous, even if it's class_loader is a parent of 'to'
 342     // we still have to add it.  The class_loader won't keep from_cld alive.
 343     if (!from_cld->is_anonymous()) {
 344       // Check that this dependency isn't from the same or parent class_loader
 345       oop from = from_cld->class_loader();
 346 
 347       oop curr = from;
 348       while (curr != NULL) {
 349         if (curr == to) {
 350           return; // this class loader is in the parent list, no need to add it.
 351         }
 352         curr = java_lang_ClassLoader::parent(curr);
 353       }
 354     }
 355   }
 356 
 357   // It's a dependency we won't find through GC, add it. This is relatively rare
 358   // Must handle over GC point.
 359   Handle dependency(THREAD, to);
 360   from_cld->_dependencies.add(dependency, CHECK);
 361 }
 362 
 363 
 364 void ClassLoaderData::Dependencies::add(Handle dependency, TRAPS) {
 365   // Check first if this dependency is already in the list.
 366   // Save a pointer to the last to add to under the lock.
 367   objArrayOop ok = _list_head;
 368   objArrayOop last = NULL;
 369   while (ok != NULL) {
 370     last = ok;
 371     if (ok->obj_at(0) == dependency()) {
 372       // Don't need to add it
 373       return;
 374     }
 375     ok = (objArrayOop)ok->obj_at(1);
 376   }
 377 
 378   // Must handle over GC points
 379   assert (last != NULL, "dependencies should be initialized");
 380   objArrayHandle last_handle(THREAD, last);
 381 
 382   // Create a new dependency node with fields for (class_loader or mirror, next)
 383   objArrayOop deps = oopFactory::new_objectArray(2, CHECK);
 384   deps->obj_at_put(0, dependency());
 385 
 386   // Must handle over GC points
 387   objArrayHandle new_dependency(THREAD, deps);
 388 
 389   // Add the dependency under lock
 390   locked_add(last_handle, new_dependency, THREAD);
 391 }
 392 
 393 void ClassLoaderData::Dependencies::locked_add(objArrayHandle last_handle,
 394                                                objArrayHandle new_dependency,
 395                                                Thread* THREAD) {
 396 
 397   // Have to lock and put the new dependency on the end of the dependency
 398   // array so the card mark for CMS sees that this dependency is new.
 399   // Can probably do this lock free with some effort.
 400   ObjectLocker ol(Handle(THREAD, _list_head), THREAD);
 401 
 402   oop loader_or_mirror = new_dependency->obj_at(0);
 403 
 404   // Since the dependencies are only added, add to the end.
 405   objArrayOop end = last_handle();
 406   objArrayOop last = NULL;
 407   while (end != NULL) {
 408     last = end;
 409     // check again if another thread added it to the end.
 410     if (end->obj_at(0) == loader_or_mirror) {
 411       // Don't need to add it
 412       return;
 413     }
 414     end = (objArrayOop)end->obj_at(1);
 415   }
 416   assert (last != NULL, "dependencies should be initialized");
 417   // fill in the first element with the oop in new_dependency.
 418   if (last->obj_at(0) == NULL) {
 419     last->obj_at_put(0, new_dependency->obj_at(0));
 420   } else {
 421     last->obj_at_put(1, new_dependency());
 422   }
 423 }
 424 
 425 void ClassLoaderDataGraph::clear_claimed_marks() {
 426   for (ClassLoaderData* cld = _head; cld != NULL; cld = cld->next()) {
 427     cld->clear_claimed();
 428   }
 429 }
 430 
 431 void ClassLoaderData::add_class(Klass* k, bool publicize /* true */) {
 432   {
 433     MutexLockerEx ml(metaspace_lock(), Mutex::_no_safepoint_check_flag);
 434     Klass* old_value = _klasses;
 435     k->set_next_link(old_value);
 436     // Link the new item into the list, making sure the linked class is stable
 437     // since the list can be walked without a lock
 438     OrderAccess::release_store_ptr(&_klasses, k);
 439   }
 440 
 441   if (publicize && k->class_loader_data() != NULL) {
 442     ResourceMark rm;
 443     log_trace(class, loader, data)("Adding k: " PTR_FORMAT " %s to CLD: "
 444                   PTR_FORMAT " loader: " PTR_FORMAT " %s",
 445                   p2i(k),
 446                   k->external_name(),
 447                   p2i(k->class_loader_data()),
 448                   p2i((void *)k->class_loader()),
 449                   loader_name());
 450   }
 451 }
 452 
 453 // Remove a klass from the _klasses list for scratch_class during redefinition
 454 // or parsed class in the case of an error.
 455 void ClassLoaderData::remove_class(Klass* scratch_class) {
 456   assert(SafepointSynchronize::is_at_safepoint(), "only called at safepoint");
 457   Klass* prev = NULL;
 458   for (Klass* k = _klasses; k != NULL; k = k->next_link()) {
 459     if (k == scratch_class) {
 460       if (prev == NULL) {
 461         _klasses = k->next_link();
 462       } else {
 463         Klass* next = k->next_link();
 464         prev->set_next_link(next);
 465       }
 466       return;
 467     }
 468     prev = k;
 469     assert(k != k->next_link(), "no loops!");
 470   }
 471   ShouldNotReachHere();   // should have found this class!!
 472 }
 473 
 474 void ClassLoaderData::unload() {
 475   _unloading = true;
 476 
 477   // Tell serviceability tools these classes are unloading
 478   classes_do(InstanceKlass::notify_unload_class);
 479 
 480   LogTarget(Debug, class, loader, data) lt;
 481   if (lt.is_enabled()) {
 482     ResourceMark rm;
 483     LogStream ls(lt);
 484     ls.print(": unload loader data " INTPTR_FORMAT, p2i(this));
 485     ls.print(" for instance " INTPTR_FORMAT " of %s", p2i((void *)class_loader()),
 486                loader_name());
 487     if (is_anonymous()) {
 488       ls.print(" for anonymous class  " INTPTR_FORMAT " ", p2i(_klasses));
 489     }
 490     ls.cr();
 491   }
 492 
 493   // In some rare cases items added to this list will not be freed elsewhere.
 494   // To keep it simple, just free everything in it here.
 495   free_deallocate_list();
 496 }
 497 
 498 ModuleEntryTable* ClassLoaderData::modules() {
 499   // Lazily create the module entry table at first request.
 500   // Lock-free access requires load_ptr_acquire.
 501   ModuleEntryTable* modules = load_ptr_acquire(&_modules);
 502   if (modules == NULL) {
 503     MutexLocker m1(Module_lock);
 504     // Check if _modules got allocated while we were waiting for this lock.
 505     if ((modules = _modules) == NULL) {
 506       modules = new ModuleEntryTable(ModuleEntryTable::_moduletable_entry_size);
 507 
 508       {
 509         MutexLockerEx m1(metaspace_lock(), Mutex::_no_safepoint_check_flag);
 510         // Ensure _modules is stable, since it is examined without a lock
 511         OrderAccess::release_store_ptr(&_modules, modules);
 512       }
 513     }
 514   }
 515   return modules;
 516 }
 517 
 518 oop ClassLoaderData::keep_alive_object() const {
 519   assert_locked_or_safepoint(_metaspace_lock);
 520   assert(!keep_alive(), "Don't use with CLDs that are artificially kept alive");
 521   return is_anonymous() ? _klasses->java_mirror() : class_loader();
 522 }
 523 
 524 bool ClassLoaderData::is_alive(BoolObjectClosure* is_alive_closure) const {
 525   bool alive = keep_alive() // null class loader and incomplete anonymous klasses.
 526       || is_alive_closure->do_object_b(keep_alive_object());
 527 
 528   return alive;
 529 }
 530 
 531 ClassLoaderData::~ClassLoaderData() {
 532   // Release C heap structures for all the classes.
 533   classes_do(InstanceKlass::release_C_heap_structures);
 534 
 535   // Release C heap allocated hashtable for all the packages.
 536   if (_packages != NULL) {
 537     // Destroy the table itself
 538     delete _packages;
 539     _packages = NULL;
 540   }
 541 
 542   // Release C heap allocated hashtable for all the modules.
 543   if (_modules != NULL) {
 544     // Destroy the table itself
 545     delete _modules;
 546     _modules = NULL;
 547   }
 548 
 549   if (_unnamed_module != NULL) {
 550     _unnamed_module->delete_unnamed_module();
 551     _unnamed_module = NULL;
 552   }
 553 
 554   // release the metaspace
 555   Metaspace *m = _metaspace;
 556   if (m != NULL) {
 557     _metaspace = NULL;
 558     delete m;
 559   }
 560   // Clear all the JNI handles for methods
 561   // These aren't deallocated and are going to look like a leak, but that's
 562   // needed because we can't really get rid of jmethodIDs because we don't
 563   // know when native code is going to stop using them.  The spec says that
 564   // they're "invalid" but existing programs likely rely on their being
 565   // NULL after class unloading.
 566   if (_jmethod_ids != NULL) {
 567     Method::clear_jmethod_ids(this);
 568   }
 569   // Delete lock
 570   delete _metaspace_lock;
 571 
 572   // Delete free list
 573   if (_deallocate_list != NULL) {
 574     delete _deallocate_list;
 575   }
 576 }
 577 
 578 // Returns true if this class loader data is for the system class loader.
 579 bool ClassLoaderData::is_system_class_loader_data() const {
 580   return SystemDictionary::is_system_class_loader(class_loader());
 581 }
 582 
 583 // Returns true if this class loader data is for the platform class loader.
 584 bool ClassLoaderData::is_platform_class_loader_data() const {
 585   return SystemDictionary::is_platform_class_loader(class_loader());
 586 }
 587 
 588 // Returns true if this class loader data is one of the 3 builtin
 589 // (boot, application/system or platform) class loaders. Note, the
 590 // builtin loaders are not freed by a GC.
 591 bool ClassLoaderData::is_builtin_class_loader_data() const {
 592   return (is_the_null_class_loader_data() ||
 593           SystemDictionary::is_system_class_loader(class_loader()) ||
 594           SystemDictionary::is_platform_class_loader(class_loader()));
 595 }
 596 
 597 Metaspace* ClassLoaderData::metaspace_non_null() {
 598   assert(!DumpSharedSpaces, "wrong metaspace!");
 599   // If the metaspace has not been allocated, create a new one.  Might want
 600   // to create smaller arena for Reflection class loaders also.
 601   // The reason for the delayed allocation is because some class loaders are
 602   // simply for delegating with no metadata of their own.
 603   // Lock-free access requires load_ptr_acquire.
 604   Metaspace* metaspace = load_ptr_acquire(&_metaspace);
 605   if (metaspace == NULL) {
 606     MutexLockerEx ml(_metaspace_lock,  Mutex::_no_safepoint_check_flag);
 607     // Check if _metaspace got allocated while we were waiting for this lock.
 608     if ((metaspace = _metaspace) == NULL) {
 609       if (this == the_null_class_loader_data()) {
 610         assert (class_loader() == NULL, "Must be");
 611         metaspace = new Metaspace(_metaspace_lock, Metaspace::BootMetaspaceType);
 612       } else if (is_anonymous()) {
 613         if (class_loader() != NULL) {
 614           log_trace(class, loader, data)("is_anonymous: %s", class_loader()->klass()->internal_name());
 615         }
 616         metaspace = new Metaspace(_metaspace_lock, Metaspace::AnonymousMetaspaceType);
 617       } else if (class_loader()->is_a(SystemDictionary::reflect_DelegatingClassLoader_klass())) {
 618         if (class_loader() != NULL) {
 619           log_trace(class, loader, data)("is_reflection: %s", class_loader()->klass()->internal_name());
 620         }
 621         metaspace = new Metaspace(_metaspace_lock, Metaspace::ReflectionMetaspaceType);
 622       } else {
 623         metaspace = new Metaspace(_metaspace_lock, Metaspace::StandardMetaspaceType);
 624       }
 625       // Ensure _metaspace is stable, since it is examined without a lock
 626       OrderAccess::release_store_ptr(&_metaspace, metaspace);
 627     }
 628   }
 629   return metaspace;
 630 }
 631 
 632 jobject ClassLoaderData::add_handle(Handle h) {
 633   MutexLockerEx ml(metaspace_lock(),  Mutex::_no_safepoint_check_flag);
 634   return (jobject) _handles.add(h());
 635 }
 636 
 637 void ClassLoaderData::remove_handle_unsafe(jobject h) {
 638   assert(_handles.contains((oop*) h), "Got unexpected handle " PTR_FORMAT, p2i((oop*) h));
 639   *((oop*) h) = NULL;
 640 }
 641 
 642 // Add this metadata pointer to be freed when it's safe.  This is only during
 643 // class unloading because Handles might point to this metadata field.
 644 void ClassLoaderData::add_to_deallocate_list(Metadata* m) {
 645   // Metadata in shared region isn't deleted.
 646   if (!m->is_shared()) {
 647     MutexLockerEx ml(metaspace_lock(),  Mutex::_no_safepoint_check_flag);
 648     if (_deallocate_list == NULL) {
 649       _deallocate_list = new (ResourceObj::C_HEAP, mtClass) GrowableArray<Metadata*>(100, true);
 650     }
 651     _deallocate_list->append_if_missing(m);
 652   }
 653 }
 654 
 655 // Deallocate free metadata on the free list.  How useful the PermGen was!
 656 void ClassLoaderData::free_deallocate_list() {
 657   // Don't need lock, at safepoint
 658   assert(SafepointSynchronize::is_at_safepoint(), "only called at safepoint");
 659   if (_deallocate_list == NULL) {
 660     return;
 661   }
 662   // Go backwards because this removes entries that are freed.
 663   for (int i = _deallocate_list->length() - 1; i >= 0; i--) {
 664     Metadata* m = _deallocate_list->at(i);
 665     if (!m->on_stack()) {
 666       _deallocate_list->remove_at(i);
 667       // There are only three types of metadata that we deallocate directly.
 668       // Cast them so they can be used by the template function.
 669       if (m->is_method()) {
 670         MetadataFactory::free_metadata(this, (Method*)m);
 671       } else if (m->is_constantPool()) {
 672         MetadataFactory::free_metadata(this, (ConstantPool*)m);
 673       } else if (m->is_klass()) {
 674         MetadataFactory::free_metadata(this, (InstanceKlass*)m);
 675       } else {
 676         ShouldNotReachHere();
 677       }
 678     } else {
 679       // Metadata is alive.
 680       // If scratch_class is on stack then it shouldn't be on this list!
 681       assert(!m->is_klass() || !((InstanceKlass*)m)->is_scratch_class(),
 682              "scratch classes on this list should be dead");
 683       // Also should assert that other metadata on the list was found in handles.
 684     }
 685   }
 686 }
 687 
 688 // These anonymous class loaders are to contain classes used for JSR292
 689 ClassLoaderData* ClassLoaderData::anonymous_class_loader_data(oop loader, TRAPS) {
 690   // Add a new class loader data to the graph.
 691   Handle lh(THREAD, loader);
 692   return ClassLoaderDataGraph::add(lh, true, THREAD);
 693 }
 694 
 695 const char* ClassLoaderData::loader_name() {
 696   // Handles null class loader
 697   return SystemDictionary::loader_name(class_loader());
 698 }
 699 
 700 #ifndef PRODUCT
 701 // Define to dump klasses
 702 #undef CLD_DUMP_KLASSES
 703 
 704 void ClassLoaderData::dump(outputStream * const out) {
 705   out->print("ClassLoaderData CLD: " PTR_FORMAT ", loader: " PTR_FORMAT ", loader_klass: " PTR_FORMAT " %s {",
 706       p2i(this), p2i((void *)class_loader()),
 707       p2i(class_loader() != NULL ? class_loader()->klass() : NULL), loader_name());
 708   if (claimed()) out->print(" claimed ");
 709   if (is_unloading()) out->print(" unloading ");
 710   out->cr();
 711   if (metaspace_or_null() != NULL) {
 712     out->print_cr("metaspace: " INTPTR_FORMAT, p2i(metaspace_or_null()));
 713     metaspace_or_null()->dump(out);
 714   } else {
 715     out->print_cr("metaspace: NULL");
 716   }
 717 
 718 #ifdef CLD_DUMP_KLASSES
 719   if (Verbose) {
 720     Klass* k = _klasses;
 721     while (k != NULL) {
 722       out->print_cr("klass " PTR_FORMAT ", %s, CT: %d, MUT: %d", k, k->name()->as_C_string(),
 723           k->has_modified_oops(), k->has_accumulated_modified_oops());
 724       assert(k != k->next_link(), "no loops!");
 725       k = k->next_link();
 726     }
 727   }
 728 #endif  // CLD_DUMP_KLASSES
 729 #undef CLD_DUMP_KLASSES
 730   if (_jmethod_ids != NULL) {
 731     Method::print_jmethod_ids(this, out);
 732   }
 733   out->print_cr("}");
 734 }
 735 #endif // PRODUCT
 736 
 737 void ClassLoaderData::verify() {
 738   assert_locked_or_safepoint(_metaspace_lock);
 739   oop cl = class_loader();
 740 
 741   guarantee(this == class_loader_data(cl) || is_anonymous(), "Must be the same");
 742   guarantee(cl != NULL || this == ClassLoaderData::the_null_class_loader_data() || is_anonymous(), "must be");
 743 
 744   // Verify the integrity of the allocated space.
 745   if (metaspace_or_null() != NULL) {
 746     metaspace_or_null()->verify();
 747   }
 748 
 749   for (Klass* k = _klasses; k != NULL; k = k->next_link()) {
 750     guarantee(k->class_loader_data() == this, "Must be the same");
 751     k->verify();
 752     assert(k != k->next_link(), "no loops!");
 753   }
 754 }
 755 
 756 bool ClassLoaderData::contains_klass(Klass* klass) {
 757   // Lock-free access requires load_ptr_acquire
 758   for (Klass* k = load_ptr_acquire(&_klasses); k != NULL; k = k->next_link()) {
 759     if (k == klass) return true;
 760   }
 761   return false;
 762 }
 763 
 764 
 765 // GC root of class loader data created.
 766 ClassLoaderData* ClassLoaderDataGraph::_head = NULL;
 767 ClassLoaderData* ClassLoaderDataGraph::_unloading = NULL;
 768 ClassLoaderData* ClassLoaderDataGraph::_saved_unloading = NULL;
 769 ClassLoaderData* ClassLoaderDataGraph::_saved_head = NULL;
 770 
 771 bool ClassLoaderDataGraph::_should_purge = false;
 772 bool ClassLoaderDataGraph::_metaspace_oom = false;
 773 
 774 // Add a new class loader data node to the list.  Assign the newly created
 775 // ClassLoaderData into the java/lang/ClassLoader object as a hidden field
 776 ClassLoaderData* ClassLoaderDataGraph::add(Handle loader, bool is_anonymous, TRAPS) {
 777   // We need to allocate all the oops for the ClassLoaderData before allocating the
 778   // actual ClassLoaderData object.
 779   ClassLoaderData::Dependencies dependencies(CHECK_NULL);
 780 
 781   NoSafepointVerifier no_safepoints; // we mustn't GC until we've installed the
 782                                      // ClassLoaderData in the graph since the CLD
 783                                      // contains unhandled oops
 784 
 785   ClassLoaderData* cld = new ClassLoaderData(loader, is_anonymous, dependencies);
 786 
 787 
 788   if (!is_anonymous) {
 789     ClassLoaderData** cld_addr = java_lang_ClassLoader::loader_data_addr(loader());
 790     // First, Atomically set it
 791     ClassLoaderData* old = (ClassLoaderData*) Atomic::cmpxchg_ptr(cld, cld_addr, NULL);
 792     if (old != NULL) {
 793       delete cld;
 794       // Returns the data.
 795       return old;
 796     }
 797   }
 798 
 799   // We won the race, and therefore the task of adding the data to the list of
 800   // class loader data
 801   ClassLoaderData** list_head = &_head;
 802   ClassLoaderData* next = _head;
 803 
 804   do {
 805     cld->set_next(next);
 806     ClassLoaderData* exchanged = (ClassLoaderData*)Atomic::cmpxchg_ptr(cld, list_head, next);
 807     if (exchanged == next) {
 808       LogTarget(Debug, class, loader, data) lt;
 809       if (lt.is_enabled()) {
 810        PauseNoSafepointVerifier pnsv(&no_safepoints); // Need safe points for JavaCalls::call_virtual
 811        LogStream ls(lt);
 812        print_creation(&ls, loader, cld, CHECK_NULL);
 813       }
 814       return cld;
 815     }
 816     next = exchanged;
 817   } while (true);
 818 }
 819 
 820 void ClassLoaderDataGraph::print_creation(outputStream* out, Handle loader, ClassLoaderData* cld, TRAPS) {
 821   Handle string;
 822   if (loader.not_null()) {
 823     // Include the result of loader.toString() in the output. This allows
 824     // the user of the log to identify the class loader instance.
 825     JavaValue result(T_OBJECT);
 826     Klass* spec_klass = SystemDictionary::ClassLoader_klass();
 827     JavaCalls::call_virtual(&result,
 828                             loader,
 829                             spec_klass,
 830                             vmSymbols::toString_name(),
 831                             vmSymbols::void_string_signature(),
 832                             CHECK);
 833     assert(result.get_type() == T_OBJECT, "just checking");
 834     string = Handle(THREAD, (oop)result.get_jobject());
 835   }
 836 
 837   ResourceMark rm;
 838   out->print("create class loader data " INTPTR_FORMAT, p2i(cld));
 839   out->print(" for instance " INTPTR_FORMAT " of %s", p2i((void *)cld->class_loader()),
 840              cld->loader_name());
 841 
 842   if (string.not_null()) {
 843     out->print(": ");
 844     java_lang_String::print(string(), out);
 845   }
 846   out->cr();
 847 }
 848 
 849 
 850 void ClassLoaderDataGraph::oops_do(OopClosure* f, KlassClosure* klass_closure, bool must_claim) {
 851   for (ClassLoaderData* cld = _head; cld != NULL; cld = cld->next()) {
 852     cld->oops_do(f, klass_closure, must_claim);
 853   }
 854 }
 855 
 856 void ClassLoaderDataGraph::keep_alive_oops_do(OopClosure* f, KlassClosure* klass_closure, bool must_claim) {
 857   for (ClassLoaderData* cld = _head; cld != NULL; cld = cld->next()) {
 858     if (cld->keep_alive()) {
 859       cld->oops_do(f, klass_closure, must_claim);
 860     }
 861   }
 862 }
 863 
 864 void ClassLoaderDataGraph::always_strong_oops_do(OopClosure* f, KlassClosure* klass_closure, bool must_claim) {
 865   if (ClassUnloading) {
 866     keep_alive_oops_do(f, klass_closure, must_claim);
 867   } else {
 868     oops_do(f, klass_closure, must_claim);
 869   }
 870 }
 871 
 872 void ClassLoaderDataGraph::cld_do(CLDClosure* cl) {
 873   for (ClassLoaderData* cld = _head; cl != NULL && cld != NULL; cld = cld->next()) {
 874     cl->do_cld(cld);
 875   }
 876 }
 877 
 878 void ClassLoaderDataGraph::cld_unloading_do(CLDClosure* cl) {
 879   assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint!");
 880   // Only walk the head until any clds not purged from prior unloading
 881   // (CMS doesn't purge right away).
 882   for (ClassLoaderData* cld = _unloading; cld != _saved_unloading; cld = cld->next()) {
 883     assert(cld->is_unloading(), "invariant");
 884     cl->do_cld(cld);
 885   }
 886 }
 887 
 888 void ClassLoaderDataGraph::roots_cld_do(CLDClosure* strong, CLDClosure* weak) {
 889   for (ClassLoaderData* cld = _head;  cld != NULL; cld = cld->_next) {
 890     CLDClosure* closure = cld->keep_alive() ? strong : weak;
 891     if (closure != NULL) {
 892       closure->do_cld(cld);
 893     }
 894   }
 895 }
 896 
 897 void ClassLoaderDataGraph::keep_alive_cld_do(CLDClosure* cl) {
 898   roots_cld_do(cl, NULL);
 899 }
 900 
 901 void ClassLoaderDataGraph::always_strong_cld_do(CLDClosure* cl) {
 902   if (ClassUnloading) {
 903     keep_alive_cld_do(cl);
 904   } else {
 905     cld_do(cl);
 906   }
 907 }
 908 
 909 void ClassLoaderDataGraph::classes_do(KlassClosure* klass_closure) {
 910   for (ClassLoaderData* cld = _head; cld != NULL; cld = cld->next()) {
 911     cld->classes_do(klass_closure);
 912   }
 913 }
 914 
 915 void ClassLoaderDataGraph::classes_do(void f(Klass* const)) {
 916   for (ClassLoaderData* cld = _head; cld != NULL; cld = cld->next()) {
 917     cld->classes_do(f);
 918   }
 919 }
 920 
 921 void ClassLoaderDataGraph::methods_do(void f(Method*)) {
 922   for (ClassLoaderData* cld = _head; cld != NULL; cld = cld->next()) {
 923     cld->methods_do(f);
 924   }
 925 }
 926 
 927 void ClassLoaderDataGraph::modules_do(void f(ModuleEntry*)) {
 928   assert_locked_or_safepoint(Module_lock);
 929   for (ClassLoaderData* cld = _head; cld != NULL; cld = cld->next()) {
 930     cld->modules_do(f);
 931   }
 932 }
 933 
 934 void ClassLoaderDataGraph::modules_unloading_do(void f(ModuleEntry*)) {
 935   assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint!");
 936   // Only walk the head until any clds not purged from prior unloading
 937   // (CMS doesn't purge right away).
 938   for (ClassLoaderData* cld = _unloading; cld != _saved_unloading; cld = cld->next()) {
 939     assert(cld->is_unloading(), "invariant");
 940     cld->modules_do(f);
 941   }
 942 }
 943 
 944 void ClassLoaderDataGraph::packages_do(void f(PackageEntry*)) {
 945   assert_locked_or_safepoint(Module_lock);
 946   for (ClassLoaderData* cld = _head; cld != NULL; cld = cld->next()) {
 947     cld->packages_do(f);
 948   }
 949 }
 950 
 951 void ClassLoaderDataGraph::packages_unloading_do(void f(PackageEntry*)) {
 952   assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint!");
 953   // Only walk the head until any clds not purged from prior unloading
 954   // (CMS doesn't purge right away).
 955   for (ClassLoaderData* cld = _unloading; cld != _saved_unloading; cld = cld->next()) {
 956     assert(cld->is_unloading(), "invariant");
 957     cld->packages_do(f);
 958   }
 959 }
 960 
 961 void ClassLoaderDataGraph::loaded_classes_do(KlassClosure* klass_closure) {
 962   for (ClassLoaderData* cld = _head; cld != NULL; cld = cld->next()) {
 963     cld->loaded_classes_do(klass_closure);
 964   }
 965 }
 966 
 967 void ClassLoaderDataGraph::classes_unloading_do(void f(Klass* const)) {
 968   assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint!");
 969   // Only walk the head until any clds not purged from prior unloading
 970   // (CMS doesn't purge right away).
 971   for (ClassLoaderData* cld = _unloading; cld != _saved_unloading; cld = cld->next()) {
 972     assert(cld->is_unloading(), "invariant");
 973     cld->classes_do(f);
 974   }
 975 }
 976 
 977 GrowableArray<ClassLoaderData*>* ClassLoaderDataGraph::new_clds() {
 978   assert(_head == NULL || _saved_head != NULL, "remember_new_clds(true) not called?");
 979 
 980   GrowableArray<ClassLoaderData*>* array = new GrowableArray<ClassLoaderData*>();
 981 
 982   // The CLDs in [_head, _saved_head] were all added during last call to remember_new_clds(true);
 983   ClassLoaderData* curr = _head;
 984   while (curr != _saved_head) {
 985     if (!curr->claimed()) {
 986       array->push(curr);
 987       LogTarget(Debug, class, loader, data) lt;
 988       if (lt.is_enabled()) {
 989         LogStream ls(lt);
 990         ls.print("found new CLD: ");
 991         curr->print_value_on(&ls);
 992         ls.cr();
 993       }
 994     }
 995 
 996     curr = curr->_next;
 997   }
 998 
 999   return array;
1000 }
1001 
1002 bool ClassLoaderDataGraph::unload_list_contains(const void* x) {
1003   assert(SafepointSynchronize::is_at_safepoint(), "only safe to call at safepoint");
1004   for (ClassLoaderData* cld = _unloading; cld != NULL; cld = cld->next()) {
1005     if (cld->metaspace_or_null() != NULL && cld->metaspace_or_null()->contains(x)) {
1006       return true;
1007     }
1008   }
1009   return false;
1010 }
1011 
1012 #ifndef PRODUCT
1013 bool ClassLoaderDataGraph::contains_loader_data(ClassLoaderData* loader_data) {
1014   for (ClassLoaderData* data = _head; data != NULL; data = data->next()) {
1015     if (loader_data == data) {
1016       return true;
1017     }
1018   }
1019 
1020   return false;
1021 }
1022 #endif // PRODUCT
1023 
1024 
1025 // Move class loader data from main list to the unloaded list for unloading
1026 // and deallocation later.
1027 bool ClassLoaderDataGraph::do_unloading(BoolObjectClosure* is_alive_closure,
1028                                         bool clean_previous_versions) {
1029 
1030   ClassLoaderData* data = _head;
1031   ClassLoaderData* prev = NULL;
1032   bool seen_dead_loader = false;
1033 
1034   // Mark metadata seen on the stack only so we can delete unneeded entries.
1035   // Only walk all metadata, including the expensive code cache walk, for Full GC
1036   // and only if class redefinition and if there's previous versions of
1037   // Klasses to delete.
1038   bool walk_all_metadata = clean_previous_versions &&
1039                            JvmtiExport::has_redefined_a_class() &&
1040                            InstanceKlass::has_previous_versions_and_reset();
1041   MetadataOnStackMark md_on_stack(walk_all_metadata);
1042 
1043   // Save previous _unloading pointer for CMS which may add to unloading list before
1044   // purging and we don't want to rewalk the previously unloaded class loader data.
1045   _saved_unloading = _unloading;
1046 
1047   data = _head;
1048   while (data != NULL) {
1049     if (data->is_alive(is_alive_closure)) {
1050       // clean metaspace
1051       if (walk_all_metadata) {
1052         data->classes_do(InstanceKlass::purge_previous_versions);
1053       }
1054       data->free_deallocate_list();
1055       prev = data;
1056       data = data->next();
1057       continue;
1058     }
1059     seen_dead_loader = true;
1060     ClassLoaderData* dead = data;
1061     dead->unload();
1062     data = data->next();
1063     // Remove from loader list.
1064     // This class loader data will no longer be found
1065     // in the ClassLoaderDataGraph.
1066     if (prev != NULL) {
1067       prev->set_next(data);
1068     } else {
1069       assert(dead == _head, "sanity check");
1070       _head = data;
1071     }
1072     dead->set_next(_unloading);
1073     _unloading = dead;
1074   }
1075 
1076   if (seen_dead_loader) {
1077     // Walk a ModuleEntry's reads and a PackageEntry's exports lists
1078     // to determine if there are modules on those lists that are now
1079     // dead and should be removed.  A module's life cycle is equivalent
1080     // to its defining class loader's life cycle.  Since a module is
1081     // considered dead if its class loader is dead, these walks must
1082     // occur after each class loader's aliveness is determined.
1083     data = _head;
1084     while (data != NULL) {
1085       if (data->packages() != NULL) {
1086         data->packages()->purge_all_package_exports();
1087       }
1088       if (data->modules_defined()) {
1089         data->modules()->purge_all_module_reads();
1090       }
1091       data = data->next();
1092     }
1093 
1094     post_class_unload_events();
1095   }
1096 
1097   return seen_dead_loader;
1098 }
1099 
1100 void ClassLoaderDataGraph::purge() {
1101   assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint!");
1102   ClassLoaderData* list = _unloading;
1103   _unloading = NULL;
1104   ClassLoaderData* next = list;
1105   bool classes_unloaded = false;
1106   while (next != NULL) {
1107     ClassLoaderData* purge_me = next;
1108     next = purge_me->next();
1109     delete purge_me;
1110     classes_unloaded = true;
1111   }
1112   if (classes_unloaded) {
1113     Metaspace::purge();
1114     set_metaspace_oom(false);
1115   }
1116 }
1117 
1118 void ClassLoaderDataGraph::post_class_unload_events() {
1119 #if INCLUDE_TRACE
1120   assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint!");
1121   if (Tracing::enabled()) {
1122     if (Tracing::is_event_enabled(TraceClassUnloadEvent)) {
1123       assert(_unloading != NULL, "need class loader data unload list!");
1124       _class_unload_time = Ticks::now();
1125       classes_unloading_do(&class_unload_event);
1126     }
1127     Tracing::on_unloading_classes();
1128   }
1129 #endif
1130 }
1131 
1132 // CDS support
1133 
1134 // Global metaspaces for writing information to the shared archive.  When
1135 // application CDS is supported, we may need one per metaspace, so this
1136 // sort of looks like it.
1137 Metaspace* ClassLoaderData::_ro_metaspace = NULL;
1138 Metaspace* ClassLoaderData::_rw_metaspace = NULL;
1139 static bool _shared_metaspaces_initialized = false;
1140 
1141 // Initialize shared metaspaces (change to call from somewhere not lazily)
1142 void ClassLoaderData::initialize_shared_metaspaces() {
1143   assert(DumpSharedSpaces, "only use this for dumping shared spaces");
1144   assert(this == ClassLoaderData::the_null_class_loader_data(),
1145          "only supported for null loader data for now");
1146   assert (!_shared_metaspaces_initialized, "only initialize once");
1147   MutexLockerEx ml(metaspace_lock(),  Mutex::_no_safepoint_check_flag);
1148   _ro_metaspace = new Metaspace(_metaspace_lock, Metaspace::ROMetaspaceType);
1149   _rw_metaspace = new Metaspace(_metaspace_lock, Metaspace::ReadWriteMetaspaceType);
1150   _shared_metaspaces_initialized = true;
1151 }
1152 
1153 Metaspace* ClassLoaderData::ro_metaspace() {
1154   assert(_ro_metaspace != NULL, "should already be initialized");
1155   return _ro_metaspace;
1156 }
1157 
1158 Metaspace* ClassLoaderData::rw_metaspace() {
1159   assert(_rw_metaspace != NULL, "should already be initialized");
1160   return _rw_metaspace;
1161 }
1162 
1163 ClassLoaderDataGraphKlassIteratorAtomic::ClassLoaderDataGraphKlassIteratorAtomic()
1164     : _next_klass(NULL) {
1165   ClassLoaderData* cld = ClassLoaderDataGraph::_head;
1166   Klass* klass = NULL;
1167 
1168   // Find the first klass in the CLDG.
1169   while (cld != NULL) {
1170     assert_locked_or_safepoint(cld->metaspace_lock());
1171     klass = cld->_klasses;
1172     if (klass != NULL) {
1173       _next_klass = klass;
1174       return;
1175     }
1176     cld = cld->next();
1177   }
1178 }
1179 
1180 Klass* ClassLoaderDataGraphKlassIteratorAtomic::next_klass_in_cldg(Klass* klass) {
1181   Klass* next = klass->next_link();
1182   if (next != NULL) {
1183     return next;
1184   }
1185 
1186   // No more klasses in the current CLD. Time to find a new CLD.
1187   ClassLoaderData* cld = klass->class_loader_data();
1188   assert_locked_or_safepoint(cld->metaspace_lock());
1189   while (next == NULL) {
1190     cld = cld->next();
1191     if (cld == NULL) {
1192       break;
1193     }
1194     next = cld->_klasses;
1195   }
1196 
1197   return next;
1198 }
1199 
1200 Klass* ClassLoaderDataGraphKlassIteratorAtomic::next_klass() {
1201   Klass* head = _next_klass;
1202 
1203   while (head != NULL) {
1204     Klass* next = next_klass_in_cldg(head);
1205 
1206     Klass* old_head = (Klass*)Atomic::cmpxchg_ptr(next, &_next_klass, head);
1207 
1208     if (old_head == head) {
1209       return head; // Won the CAS.
1210     }
1211 
1212     head = old_head;
1213   }
1214 
1215   // Nothing more for the iterator to hand out.
1216   assert(head == NULL, "head is " PTR_FORMAT ", expected not null:", p2i(head));
1217   return NULL;
1218 }
1219 
1220 ClassLoaderDataGraphMetaspaceIterator::ClassLoaderDataGraphMetaspaceIterator() {
1221   _data = ClassLoaderDataGraph::_head;
1222 }
1223 
1224 ClassLoaderDataGraphMetaspaceIterator::~ClassLoaderDataGraphMetaspaceIterator() {}
1225 
1226 #ifndef PRODUCT
1227 // callable from debugger
1228 extern "C" int print_loader_data_graph() {
1229   ClassLoaderDataGraph::dump_on(tty);
1230   return 0;
1231 }
1232 
1233 void ClassLoaderDataGraph::verify() {
1234   for (ClassLoaderData* data = _head; data != NULL; data = data->next()) {
1235     data->verify();
1236   }
1237 }
1238 
1239 void ClassLoaderDataGraph::dump_on(outputStream * const out) {
1240   for (ClassLoaderData* data = _head; data != NULL; data = data->next()) {
1241     data->dump(out);
1242   }
1243   MetaspaceAux::dump(out);
1244 }
1245 #endif // PRODUCT
1246 
1247 void ClassLoaderData::print_value_on(outputStream* out) const {
1248   if (class_loader() == NULL) {
1249     out->print("NULL class_loader");
1250   } else {
1251     out->print("class loader " INTPTR_FORMAT " ", p2i(this));
1252     class_loader()->print_value_on(out);
1253   }
1254 }
1255 
1256 #if INCLUDE_TRACE
1257 
1258 Ticks ClassLoaderDataGraph::_class_unload_time;
1259 
1260 void ClassLoaderDataGraph::class_unload_event(Klass* const k) {
1261   assert(k != NULL, "invariant");
1262 
1263   // post class unload event
1264   EventClassUnload event(UNTIMED);
1265   event.set_endtime(_class_unload_time);
1266   event.set_unloadedClass(k);
1267   event.set_definingClassLoader(k->class_loader_data());
1268   event.commit();
1269 }
1270 
1271 #endif // INCLUDE_TRACE