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