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 to avoid classes being modified/added/removed during iteration
 274   MutexLockerEx ml(metaspace_lock(),  Mutex::_no_safepoint_check_flag);
 275   for (Klass* k = _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   if (log_is_enabled(Debug, class, loader, data)) {
 481     ResourceMark rm;
 482     outputStream* log = Log(class, loader, data)::debug_stream();
 483     log->print(": unload loader data " INTPTR_FORMAT, p2i(this));
 484     log->print(" for instance " INTPTR_FORMAT " of %s", p2i((void *)class_loader()),
 485                loader_name());
 486     if (is_anonymous()) {
 487       log->print(" for anonymous class  " INTPTR_FORMAT " ", p2i(_klasses));
 488     }
 489     log->cr();
 490   }
 491 
 492   // In some rare cases items added to this list will not be freed elsewhere.
 493   // To keep it simple, just free everything in it here.
 494   free_deallocate_list();
 495 }
 496 
 497 ModuleEntryTable* ClassLoaderData::modules() {
 498   // Lazily create the module entry table at first request.
 499   // Lock-free access requires load_ptr_acquire.
 500   ModuleEntryTable* modules = load_ptr_acquire(&_modules);
 501   if (modules == NULL) {
 502     MutexLocker m1(Module_lock);
 503     // Check if _modules got allocated while we were waiting for this lock.
 504     if ((modules = _modules) == NULL) {
 505       modules = new ModuleEntryTable(ModuleEntryTable::_moduletable_entry_size);
 506 
 507       {
 508         MutexLockerEx m1(metaspace_lock(), Mutex::_no_safepoint_check_flag);
 509         // Ensure _modules is stable, since it is examined without a lock
 510         OrderAccess::release_store_ptr(&_modules, modules);
 511       }
 512     }
 513   }
 514   return modules;
 515 }
 516 
 517 oop ClassLoaderData::keep_alive_object() const {
 518   assert_locked_or_safepoint(_metaspace_lock);
 519   assert(!keep_alive(), "Don't use with CLDs that are artificially kept alive");
 520   return is_anonymous() ? _klasses->java_mirror() : class_loader();
 521 }
 522 
 523 bool ClassLoaderData::is_alive(BoolObjectClosure* is_alive_closure) const {
 524   bool alive = keep_alive() // null class loader and incomplete anonymous klasses.
 525       || is_alive_closure->do_object_b(keep_alive_object());
 526 
 527   return alive;
 528 }
 529 
 530 ClassLoaderData::~ClassLoaderData() {
 531   // Release C heap structures for all the classes.
 532   classes_do(InstanceKlass::release_C_heap_structures);
 533 
 534   // Release C heap allocated hashtable for all the packages.
 535   if (_packages != NULL) {
 536     // Destroy the table itself
 537     delete _packages;
 538     _packages = NULL;
 539   }
 540 
 541   // Release C heap allocated hashtable for all the modules.
 542   if (_modules != NULL) {
 543     // Destroy the table itself
 544     delete _modules;
 545     _modules = NULL;
 546   }
 547 
 548   if (_unnamed_module != NULL) {
 549     _unnamed_module->delete_unnamed_module();
 550     _unnamed_module = NULL;
 551   }
 552 
 553   // release the metaspace
 554   Metaspace *m = _metaspace;
 555   if (m != NULL) {
 556     _metaspace = NULL;
 557     delete m;
 558   }
 559   // Clear all the JNI handles for methods
 560   // These aren't deallocated and are going to look like a leak, but that's
 561   // needed because we can't really get rid of jmethodIDs because we don't
 562   // know when native code is going to stop using them.  The spec says that
 563   // they're "invalid" but existing programs likely rely on their being
 564   // NULL after class unloading.
 565   if (_jmethod_ids != NULL) {
 566     Method::clear_jmethod_ids(this);
 567   }
 568   // Delete lock
 569   delete _metaspace_lock;
 570 
 571   // Delete free list
 572   if (_deallocate_list != NULL) {
 573     delete _deallocate_list;
 574   }
 575 }
 576 
 577 // Returns true if this class loader data is for the system class loader.
 578 bool ClassLoaderData::is_system_class_loader_data() const {
 579   return SystemDictionary::is_system_class_loader(class_loader());
 580 }
 581 
 582 // Returns true if this class loader data is for the platform class loader.
 583 bool ClassLoaderData::is_platform_class_loader_data() const {
 584   return SystemDictionary::is_platform_class_loader(class_loader());
 585 }
 586 
 587 // Returns true if this class loader data is one of the 3 builtin
 588 // (boot, application/system or platform) class loaders. Note, the
 589 // builtin loaders are not freed by a GC.
 590 bool ClassLoaderData::is_builtin_class_loader_data() const {
 591   return (is_the_null_class_loader_data() ||
 592           SystemDictionary::is_system_class_loader(class_loader()) ||
 593           SystemDictionary::is_platform_class_loader(class_loader()));
 594 }
 595 
 596 Metaspace* ClassLoaderData::metaspace_non_null() {
 597   assert(!DumpSharedSpaces, "wrong metaspace!");
 598   // If the metaspace has not been allocated, create a new one.  Might want
 599   // to create smaller arena for Reflection class loaders also.
 600   // The reason for the delayed allocation is because some class loaders are
 601   // simply for delegating with no metadata of their own.
 602   // Lock-free access requires load_ptr_acquire.
 603   Metaspace* metaspace = load_ptr_acquire(&_metaspace);
 604   if (metaspace == NULL) {
 605     MutexLockerEx ml(_metaspace_lock,  Mutex::_no_safepoint_check_flag);
 606     // Check if _metaspace got allocated while we were waiting for this lock.
 607     if ((metaspace = _metaspace) == NULL) {
 608       if (this == the_null_class_loader_data()) {
 609         assert (class_loader() == NULL, "Must be");
 610         metaspace = new Metaspace(_metaspace_lock, Metaspace::BootMetaspaceType);
 611       } else if (is_anonymous()) {
 612         if (class_loader() != NULL) {
 613           log_trace(class, loader, data)("is_anonymous: %s", class_loader()->klass()->internal_name());
 614         }
 615         metaspace = new Metaspace(_metaspace_lock, Metaspace::AnonymousMetaspaceType);
 616       } else if (class_loader()->is_a(SystemDictionary::reflect_DelegatingClassLoader_klass())) {
 617         if (class_loader() != NULL) {
 618           log_trace(class, loader, data)("is_reflection: %s", class_loader()->klass()->internal_name());
 619         }
 620         metaspace = new Metaspace(_metaspace_lock, Metaspace::ReflectionMetaspaceType);
 621       } else {
 622         metaspace = new Metaspace(_metaspace_lock, Metaspace::StandardMetaspaceType);
 623       }
 624       // Ensure _metaspace is stable, since it is examined without a lock
 625       OrderAccess::release_store_ptr(&_metaspace, metaspace);
 626     }
 627   }
 628   return metaspace;
 629 }
 630 
 631 jobject ClassLoaderData::add_handle(Handle h) {
 632   MutexLockerEx ml(metaspace_lock(),  Mutex::_no_safepoint_check_flag);
 633   return (jobject) _handles.add(h());
 634 }
 635 
 636 void ClassLoaderData::remove_handle_unsafe(jobject h) {
 637   assert(_handles.contains((oop*) h), "Got unexpected handle " PTR_FORMAT, p2i((oop*) h));
 638   *((oop*) h) = NULL;
 639 }
 640 
 641 // Add this metadata pointer to be freed when it's safe.  This is only during
 642 // class unloading because Handles might point to this metadata field.
 643 void ClassLoaderData::add_to_deallocate_list(Metadata* m) {
 644   // Metadata in shared region isn't deleted.
 645   if (!m->is_shared()) {
 646     MutexLockerEx ml(metaspace_lock(),  Mutex::_no_safepoint_check_flag);
 647     if (_deallocate_list == NULL) {
 648       _deallocate_list = new (ResourceObj::C_HEAP, mtClass) GrowableArray<Metadata*>(100, true);
 649     }
 650     _deallocate_list->append_if_missing(m);
 651   }
 652 }
 653 
 654 // Deallocate free metadata on the free list.  How useful the PermGen was!
 655 void ClassLoaderData::free_deallocate_list() {
 656   // Don't need lock, at safepoint
 657   assert(SafepointSynchronize::is_at_safepoint(), "only called at safepoint");
 658   if (_deallocate_list == NULL) {
 659     return;
 660   }
 661   // Go backwards because this removes entries that are freed.
 662   for (int i = _deallocate_list->length() - 1; i >= 0; i--) {
 663     Metadata* m = _deallocate_list->at(i);
 664     if (!m->on_stack()) {
 665       _deallocate_list->remove_at(i);
 666       // There are only three types of metadata that we deallocate directly.
 667       // Cast them so they can be used by the template function.
 668       if (m->is_method()) {
 669         MetadataFactory::free_metadata(this, (Method*)m);
 670       } else if (m->is_constantPool()) {
 671         MetadataFactory::free_metadata(this, (ConstantPool*)m);
 672       } else if (m->is_klass()) {
 673         MetadataFactory::free_metadata(this, (InstanceKlass*)m);
 674       } else {
 675         ShouldNotReachHere();
 676       }
 677     } else {
 678       // Metadata is alive.
 679       // If scratch_class is on stack then it shouldn't be on this list!
 680       assert(!m->is_klass() || !((InstanceKlass*)m)->is_scratch_class(),
 681              "scratch classes on this list should be dead");
 682       // Also should assert that other metadata on the list was found in handles.
 683     }
 684   }
 685 }
 686 
 687 // These anonymous class loaders are to contain classes used for JSR292
 688 ClassLoaderData* ClassLoaderData::anonymous_class_loader_data(oop loader, TRAPS) {
 689   // Add a new class loader data to the graph.
 690   Handle lh(THREAD, loader);
 691   return ClassLoaderDataGraph::add(lh, true, THREAD);
 692 }
 693 
 694 const char* ClassLoaderData::loader_name() {
 695   // Handles null class loader
 696   return SystemDictionary::loader_name(class_loader());
 697 }
 698 
 699 #ifndef PRODUCT
 700 // Define to dump klasses
 701 #undef CLD_DUMP_KLASSES
 702 
 703 void ClassLoaderData::dump(outputStream * const out) {
 704   out->print("ClassLoaderData CLD: " PTR_FORMAT ", loader: " PTR_FORMAT ", loader_klass: " PTR_FORMAT " %s {",
 705       p2i(this), p2i((void *)class_loader()),
 706       p2i(class_loader() != NULL ? class_loader()->klass() : NULL), loader_name());
 707   if (claimed()) out->print(" claimed ");
 708   if (is_unloading()) out->print(" unloading ");
 709   out->cr();
 710   if (metaspace_or_null() != NULL) {
 711     out->print_cr("metaspace: " INTPTR_FORMAT, p2i(metaspace_or_null()));
 712     metaspace_or_null()->dump(out);
 713   } else {
 714     out->print_cr("metaspace: NULL");
 715   }
 716 
 717 #ifdef CLD_DUMP_KLASSES
 718   if (Verbose) {
 719     Klass* k = _klasses;
 720     while (k != NULL) {
 721       out->print_cr("klass " PTR_FORMAT ", %s, CT: %d, MUT: %d", k, k->name()->as_C_string(),
 722           k->has_modified_oops(), k->has_accumulated_modified_oops());
 723       assert(k != k->next_link(), "no loops!");
 724       k = k->next_link();
 725     }
 726   }
 727 #endif  // CLD_DUMP_KLASSES
 728 #undef CLD_DUMP_KLASSES
 729   if (_jmethod_ids != NULL) {
 730     Method::print_jmethod_ids(this, out);
 731   }
 732   out->print_cr("}");
 733 }
 734 #endif // PRODUCT
 735 
 736 void ClassLoaderData::verify() {
 737   assert_locked_or_safepoint(_metaspace_lock);
 738   oop cl = class_loader();
 739 
 740   guarantee(this == class_loader_data(cl) || is_anonymous(), "Must be the same");
 741   guarantee(cl != NULL || this == ClassLoaderData::the_null_class_loader_data() || is_anonymous(), "must be");
 742 
 743   // Verify the integrity of the allocated space.
 744   if (metaspace_or_null() != NULL) {
 745     metaspace_or_null()->verify();
 746   }
 747 
 748   for (Klass* k = _klasses; k != NULL; k = k->next_link()) {
 749     guarantee(k->class_loader_data() == this, "Must be the same");
 750     k->verify();
 751     assert(k != k->next_link(), "no loops!");
 752   }
 753 }
 754 
 755 bool ClassLoaderData::contains_klass(Klass* klass) {
 756   // Lock-free access requires load_ptr_acquire
 757   for (Klass* k = load_ptr_acquire(&_klasses); k != NULL; k = k->next_link()) {
 758     if (k == klass) return true;
 759   }
 760   return false;
 761 }
 762 
 763 
 764 // GC root of class loader data created.
 765 ClassLoaderData* ClassLoaderDataGraph::_head = NULL;
 766 ClassLoaderData* ClassLoaderDataGraph::_unloading = NULL;
 767 ClassLoaderData* ClassLoaderDataGraph::_saved_unloading = NULL;
 768 ClassLoaderData* ClassLoaderDataGraph::_saved_head = NULL;
 769 
 770 bool ClassLoaderDataGraph::_should_purge = false;
 771 bool ClassLoaderDataGraph::_metaspace_oom = false;
 772 
 773 // Add a new class loader data node to the list.  Assign the newly created
 774 // ClassLoaderData into the java/lang/ClassLoader object as a hidden field
 775 ClassLoaderData* ClassLoaderDataGraph::add(Handle loader, bool is_anonymous, TRAPS) {
 776   // We need to allocate all the oops for the ClassLoaderData before allocating the
 777   // actual ClassLoaderData object.
 778   ClassLoaderData::Dependencies dependencies(CHECK_NULL);
 779 
 780   NoSafepointVerifier no_safepoints; // we mustn't GC until we've installed the
 781                                      // ClassLoaderData in the graph since the CLD
 782                                      // contains unhandled oops
 783 
 784   ClassLoaderData* cld = new ClassLoaderData(loader, is_anonymous, dependencies);
 785 
 786 
 787   if (!is_anonymous) {
 788     ClassLoaderData** cld_addr = java_lang_ClassLoader::loader_data_addr(loader());
 789     // First, Atomically set it
 790     ClassLoaderData* old = (ClassLoaderData*) Atomic::cmpxchg_ptr(cld, cld_addr, NULL);
 791     if (old != NULL) {
 792       delete cld;
 793       // Returns the data.
 794       return old;
 795     }
 796   }
 797 
 798   // We won the race, and therefore the task of adding the data to the list of
 799   // class loader data
 800   ClassLoaderData** list_head = &_head;
 801   ClassLoaderData* next = _head;
 802 
 803   do {
 804     cld->set_next(next);
 805     ClassLoaderData* exchanged = (ClassLoaderData*)Atomic::cmpxchg_ptr(cld, list_head, next);
 806     if (exchanged == next) {
 807       if (log_is_enabled(Debug, class, loader, data)) {
 808        PauseNoSafepointVerifier pnsv(&no_safepoints); // Need safe points for JavaCalls::call_virtual
 809        log_creation(loader, cld, CHECK_NULL);
 810       }
 811       return cld;
 812     }
 813     next = exchanged;
 814   } while (true);
 815 }
 816 
 817 void ClassLoaderDataGraph::log_creation(Handle loader, ClassLoaderData* cld, TRAPS) {
 818   Handle string;
 819   if (loader.not_null()) {
 820     // Include the result of loader.toString() in the output. This allows
 821     // the user of the log to identify the class loader instance.
 822     JavaValue result(T_OBJECT);
 823     Klass* spec_klass = SystemDictionary::ClassLoader_klass();
 824     JavaCalls::call_virtual(&result,
 825                             loader,
 826                             spec_klass,
 827                             vmSymbols::toString_name(),
 828                             vmSymbols::void_string_signature(),
 829                             CHECK);
 830     assert(result.get_type() == T_OBJECT, "just checking");
 831     string = Handle(THREAD, (oop)result.get_jobject());
 832   }
 833 
 834   ResourceMark rm;
 835   outputStream* log = Log(class, loader, data)::debug_stream();
 836   log->print("create class loader data " INTPTR_FORMAT, p2i(cld));
 837   log->print(" for instance " INTPTR_FORMAT " of %s", p2i((void *)cld->class_loader()),
 838              cld->loader_name());
 839 
 840   if (string.not_null()) {
 841     log->print(": ");
 842     java_lang_String::print(string(), log);
 843   }
 844   log->cr();
 845 }
 846 
 847 
 848 void ClassLoaderDataGraph::oops_do(OopClosure* f, KlassClosure* klass_closure, bool must_claim) {
 849   for (ClassLoaderData* cld = _head; cld != NULL; cld = cld->next()) {
 850     cld->oops_do(f, klass_closure, must_claim);
 851   }
 852 }
 853 
 854 void ClassLoaderDataGraph::keep_alive_oops_do(OopClosure* f, KlassClosure* klass_closure, bool must_claim) {
 855   for (ClassLoaderData* cld = _head; cld != NULL; cld = cld->next()) {
 856     if (cld->keep_alive()) {
 857       cld->oops_do(f, klass_closure, must_claim);
 858     }
 859   }
 860 }
 861 
 862 void ClassLoaderDataGraph::always_strong_oops_do(OopClosure* f, KlassClosure* klass_closure, bool must_claim) {
 863   if (ClassUnloading) {
 864     keep_alive_oops_do(f, klass_closure, must_claim);
 865   } else {
 866     oops_do(f, klass_closure, must_claim);
 867   }
 868 }
 869 
 870 void ClassLoaderDataGraph::cld_do(CLDClosure* cl) {
 871   for (ClassLoaderData* cld = _head; cl != NULL && cld != NULL; cld = cld->next()) {
 872     cl->do_cld(cld);
 873   }
 874 }
 875 
 876 void ClassLoaderDataGraph::cld_unloading_do(CLDClosure* cl) {
 877   assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint!");
 878   // Only walk the head until any clds not purged from prior unloading
 879   // (CMS doesn't purge right away).
 880   for (ClassLoaderData* cld = _unloading; cld != _saved_unloading; cld = cld->next()) {
 881     assert(cld->is_unloading(), "invariant");
 882     cl->do_cld(cld);
 883   }
 884 }
 885 
 886 void ClassLoaderDataGraph::roots_cld_do(CLDClosure* strong, CLDClosure* weak) {
 887   for (ClassLoaderData* cld = _head;  cld != NULL; cld = cld->_next) {
 888     CLDClosure* closure = cld->keep_alive() ? strong : weak;
 889     if (closure != NULL) {
 890       closure->do_cld(cld);
 891     }
 892   }
 893 }
 894 
 895 void ClassLoaderDataGraph::keep_alive_cld_do(CLDClosure* cl) {
 896   roots_cld_do(cl, NULL);
 897 }
 898 
 899 void ClassLoaderDataGraph::always_strong_cld_do(CLDClosure* cl) {
 900   if (ClassUnloading) {
 901     keep_alive_cld_do(cl);
 902   } else {
 903     cld_do(cl);
 904   }
 905 }
 906 
 907 void ClassLoaderDataGraph::classes_do(KlassClosure* klass_closure) {
 908   for (ClassLoaderData* cld = _head; cld != NULL; cld = cld->next()) {
 909     cld->classes_do(klass_closure);
 910   }
 911 }
 912 
 913 void ClassLoaderDataGraph::classes_do(void f(Klass* const)) {
 914   for (ClassLoaderData* cld = _head; cld != NULL; cld = cld->next()) {
 915     cld->classes_do(f);
 916   }
 917 }
 918 
 919 void ClassLoaderDataGraph::methods_do(void f(Method*)) {
 920   for (ClassLoaderData* cld = _head; cld != NULL; cld = cld->next()) {
 921     cld->methods_do(f);
 922   }
 923 }
 924 
 925 void ClassLoaderDataGraph::modules_do(void f(ModuleEntry*)) {
 926   assert_locked_or_safepoint(Module_lock);
 927   for (ClassLoaderData* cld = _head; cld != NULL; cld = cld->next()) {
 928     cld->modules_do(f);
 929   }
 930 }
 931 
 932 void ClassLoaderDataGraph::modules_unloading_do(void f(ModuleEntry*)) {
 933   assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint!");
 934   // Only walk the head until any clds not purged from prior unloading
 935   // (CMS doesn't purge right away).
 936   for (ClassLoaderData* cld = _unloading; cld != _saved_unloading; cld = cld->next()) {
 937     assert(cld->is_unloading(), "invariant");
 938     cld->modules_do(f);
 939   }
 940 }
 941 
 942 void ClassLoaderDataGraph::packages_do(void f(PackageEntry*)) {
 943   assert_locked_or_safepoint(Module_lock);
 944   for (ClassLoaderData* cld = _head; cld != NULL; cld = cld->next()) {
 945     cld->packages_do(f);
 946   }
 947 }
 948 
 949 void ClassLoaderDataGraph::packages_unloading_do(void f(PackageEntry*)) {
 950   assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint!");
 951   // Only walk the head until any clds not purged from prior unloading
 952   // (CMS doesn't purge right away).
 953   for (ClassLoaderData* cld = _unloading; cld != _saved_unloading; cld = cld->next()) {
 954     assert(cld->is_unloading(), "invariant");
 955     cld->packages_do(f);
 956   }
 957 }
 958 
 959 void ClassLoaderDataGraph::loaded_classes_do(KlassClosure* klass_closure) {
 960   for (ClassLoaderData* cld = _head; cld != NULL; cld = cld->next()) {
 961     cld->loaded_classes_do(klass_closure);
 962   }
 963 }
 964 
 965 void ClassLoaderDataGraph::classes_unloading_do(void f(Klass* const)) {
 966   assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint!");
 967   // Only walk the head until any clds not purged from prior unloading
 968   // (CMS doesn't purge right away).
 969   for (ClassLoaderData* cld = _unloading; cld != _saved_unloading; cld = cld->next()) {
 970     assert(cld->is_unloading(), "invariant");
 971     cld->classes_do(f);
 972   }
 973 }
 974 
 975 GrowableArray<ClassLoaderData*>* ClassLoaderDataGraph::new_clds() {
 976   assert(_head == NULL || _saved_head != NULL, "remember_new_clds(true) not called?");
 977 
 978   GrowableArray<ClassLoaderData*>* array = new GrowableArray<ClassLoaderData*>();
 979 
 980   // The CLDs in [_head, _saved_head] were all added during last call to remember_new_clds(true);
 981   ClassLoaderData* curr = _head;
 982   while (curr != _saved_head) {
 983     if (!curr->claimed()) {
 984       array->push(curr);
 985 
 986       if (log_is_enabled(Debug, class, loader, data)) {
 987         outputStream* log = Log(class, loader, data)::debug_stream();
 988         log->print("found new CLD: ");
 989         curr->print_value_on(log);
 990         log->cr();
 991       }
 992     }
 993 
 994     curr = curr->_next;
 995   }
 996 
 997   return array;
 998 }
 999 
1000 bool ClassLoaderDataGraph::unload_list_contains(const void* x) {
1001   assert(SafepointSynchronize::is_at_safepoint(), "only safe to call at safepoint");
1002   for (ClassLoaderData* cld = _unloading; cld != NULL; cld = cld->next()) {
1003     if (cld->metaspace_or_null() != NULL && cld->metaspace_or_null()->contains(x)) {
1004       return true;
1005     }
1006   }
1007   return false;
1008 }
1009 
1010 #ifndef PRODUCT
1011 bool ClassLoaderDataGraph::contains_loader_data(ClassLoaderData* loader_data) {
1012   for (ClassLoaderData* data = _head; data != NULL; data = data->next()) {
1013     if (loader_data == data) {
1014       return true;
1015     }
1016   }
1017 
1018   return false;
1019 }
1020 #endif // PRODUCT
1021 
1022 
1023 // Move class loader data from main list to the unloaded list for unloading
1024 // and deallocation later.
1025 bool ClassLoaderDataGraph::do_unloading(BoolObjectClosure* is_alive_closure,
1026                                         bool clean_previous_versions) {
1027 
1028   ClassLoaderData* data = _head;
1029   ClassLoaderData* prev = NULL;
1030   bool seen_dead_loader = false;
1031 
1032   // Mark metadata seen on the stack only so we can delete unneeded entries.
1033   // Only walk all metadata, including the expensive code cache walk, for Full GC
1034   // and only if class redefinition and if there's previous versions of
1035   // Klasses to delete.
1036   bool walk_all_metadata = clean_previous_versions &&
1037                            JvmtiExport::has_redefined_a_class() &&
1038                            InstanceKlass::has_previous_versions_and_reset();
1039   MetadataOnStackMark md_on_stack(walk_all_metadata);
1040 
1041   // Save previous _unloading pointer for CMS which may add to unloading list before
1042   // purging and we don't want to rewalk the previously unloaded class loader data.
1043   _saved_unloading = _unloading;
1044 
1045   data = _head;
1046   while (data != NULL) {
1047     if (data->is_alive(is_alive_closure)) {
1048       // clean metaspace
1049       if (walk_all_metadata) {
1050         data->classes_do(InstanceKlass::purge_previous_versions);
1051       }
1052       data->free_deallocate_list();
1053       prev = data;
1054       data = data->next();
1055       continue;
1056     }
1057     seen_dead_loader = true;
1058     ClassLoaderData* dead = data;
1059     dead->unload();
1060     data = data->next();
1061     // Remove from loader list.
1062     // This class loader data will no longer be found
1063     // in the ClassLoaderDataGraph.
1064     if (prev != NULL) {
1065       prev->set_next(data);
1066     } else {
1067       assert(dead == _head, "sanity check");
1068       _head = data;
1069     }
1070     dead->set_next(_unloading);
1071     _unloading = dead;
1072   }
1073 
1074   if (seen_dead_loader) {
1075     // Walk a ModuleEntry's reads and a PackageEntry's exports lists
1076     // to determine if there are modules on those lists that are now
1077     // dead and should be removed.  A module's life cycle is equivalent
1078     // to its defining class loader's life cycle.  Since a module is
1079     // considered dead if its class loader is dead, these walks must
1080     // occur after each class loader's aliveness is determined.
1081     data = _head;
1082     while (data != NULL) {
1083       if (data->packages() != NULL) {
1084         data->packages()->purge_all_package_exports();
1085       }
1086       if (data->modules_defined()) {
1087         data->modules()->purge_all_module_reads();
1088       }
1089       data = data->next();
1090     }
1091 
1092     post_class_unload_events();
1093   }
1094 
1095   return seen_dead_loader;
1096 }
1097 
1098 void ClassLoaderDataGraph::purge() {
1099   assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint!");
1100   ClassLoaderData* list = _unloading;
1101   _unloading = NULL;
1102   ClassLoaderData* next = list;
1103   bool classes_unloaded = false;
1104   while (next != NULL) {
1105     ClassLoaderData* purge_me = next;
1106     next = purge_me->next();
1107     delete purge_me;
1108     classes_unloaded = true;
1109   }
1110   if (classes_unloaded) {
1111     Metaspace::purge();
1112     set_metaspace_oom(false);
1113   }
1114 }
1115 
1116 void ClassLoaderDataGraph::post_class_unload_events() {
1117 #if INCLUDE_TRACE
1118   assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint!");
1119   if (Tracing::enabled()) {
1120     if (Tracing::is_event_enabled(TraceClassUnloadEvent)) {
1121       assert(_unloading != NULL, "need class loader data unload list!");
1122       _class_unload_time = Ticks::now();
1123       classes_unloading_do(&class_unload_event);
1124     }
1125     Tracing::on_unloading_classes();
1126   }
1127 #endif
1128 }
1129 
1130 // CDS support
1131 
1132 // Global metaspaces for writing information to the shared archive.  When
1133 // application CDS is supported, we may need one per metaspace, so this
1134 // sort of looks like it.
1135 Metaspace* ClassLoaderData::_ro_metaspace = NULL;
1136 Metaspace* ClassLoaderData::_rw_metaspace = NULL;
1137 static bool _shared_metaspaces_initialized = false;
1138 
1139 // Initialize shared metaspaces (change to call from somewhere not lazily)
1140 void ClassLoaderData::initialize_shared_metaspaces() {
1141   assert(DumpSharedSpaces, "only use this for dumping shared spaces");
1142   assert(this == ClassLoaderData::the_null_class_loader_data(),
1143          "only supported for null loader data for now");
1144   assert (!_shared_metaspaces_initialized, "only initialize once");
1145   MutexLockerEx ml(metaspace_lock(),  Mutex::_no_safepoint_check_flag);
1146   _ro_metaspace = new Metaspace(_metaspace_lock, Metaspace::ROMetaspaceType);
1147   _rw_metaspace = new Metaspace(_metaspace_lock, Metaspace::ReadWriteMetaspaceType);
1148   _shared_metaspaces_initialized = true;
1149 }
1150 
1151 Metaspace* ClassLoaderData::ro_metaspace() {
1152   assert(_ro_metaspace != NULL, "should already be initialized");
1153   return _ro_metaspace;
1154 }
1155 
1156 Metaspace* ClassLoaderData::rw_metaspace() {
1157   assert(_rw_metaspace != NULL, "should already be initialized");
1158   return _rw_metaspace;
1159 }
1160 
1161 ClassLoaderDataGraphKlassIteratorAtomic::ClassLoaderDataGraphKlassIteratorAtomic()
1162     : _next_klass(NULL) {
1163   ClassLoaderData* cld = ClassLoaderDataGraph::_head;
1164   Klass* klass = NULL;
1165 
1166   // Find the first klass in the CLDG.
1167   while (cld != NULL) {
1168     assert_locked_or_safepoint(cld->metaspace_lock());
1169     klass = cld->_klasses;
1170     if (klass != NULL) {
1171       _next_klass = klass;
1172       return;
1173     }
1174     cld = cld->next();
1175   }
1176 }
1177 
1178 Klass* ClassLoaderDataGraphKlassIteratorAtomic::next_klass_in_cldg(Klass* klass) {
1179   Klass* next = klass->next_link();
1180   if (next != NULL) {
1181     return next;
1182   }
1183 
1184   // No more klasses in the current CLD. Time to find a new CLD.
1185   ClassLoaderData* cld = klass->class_loader_data();
1186   assert_locked_or_safepoint(cld->metaspace_lock());
1187   while (next == NULL) {
1188     cld = cld->next();
1189     if (cld == NULL) {
1190       break;
1191     }
1192     next = cld->_klasses;
1193   }
1194 
1195   return next;
1196 }
1197 
1198 Klass* ClassLoaderDataGraphKlassIteratorAtomic::next_klass() {
1199   Klass* head = _next_klass;
1200 
1201   while (head != NULL) {
1202     Klass* next = next_klass_in_cldg(head);
1203 
1204     Klass* old_head = (Klass*)Atomic::cmpxchg_ptr(next, &_next_klass, head);
1205 
1206     if (old_head == head) {
1207       return head; // Won the CAS.
1208     }
1209 
1210     head = old_head;
1211   }
1212 
1213   // Nothing more for the iterator to hand out.
1214   assert(head == NULL, "head is " PTR_FORMAT ", expected not null:", p2i(head));
1215   return NULL;
1216 }
1217 
1218 ClassLoaderDataGraphMetaspaceIterator::ClassLoaderDataGraphMetaspaceIterator() {
1219   _data = ClassLoaderDataGraph::_head;
1220 }
1221 
1222 ClassLoaderDataGraphMetaspaceIterator::~ClassLoaderDataGraphMetaspaceIterator() {}
1223 
1224 #ifndef PRODUCT
1225 // callable from debugger
1226 extern "C" int print_loader_data_graph() {
1227   ClassLoaderDataGraph::dump_on(tty);
1228   return 0;
1229 }
1230 
1231 void ClassLoaderDataGraph::verify() {
1232   for (ClassLoaderData* data = _head; data != NULL; data = data->next()) {
1233     data->verify();
1234   }
1235 }
1236 
1237 void ClassLoaderDataGraph::dump_on(outputStream * const out) {
1238   for (ClassLoaderData* data = _head; data != NULL; data = data->next()) {
1239     data->dump(out);
1240   }
1241   MetaspaceAux::dump(out);
1242 }
1243 #endif // PRODUCT
1244 
1245 void ClassLoaderData::print_value_on(outputStream* out) const {
1246   if (class_loader() == NULL) {
1247     out->print("NULL class_loader");
1248   } else {
1249     out->print("class loader " INTPTR_FORMAT " ", p2i(this));
1250     class_loader()->print_value_on(out);
1251   }
1252 }
1253 
1254 #if INCLUDE_TRACE
1255 
1256 Ticks ClassLoaderDataGraph::_class_unload_time;
1257 
1258 void ClassLoaderDataGraph::class_unload_event(Klass* const k) {
1259   assert(k != NULL, "invariant");
1260 
1261   // post class unload event
1262   EventClassUnload event(UNTIMED);
1263   event.set_endtime(_class_unload_time);
1264   event.set_unloadedClass(k);
1265   event.set_definingClassLoader(k->class_loader_data());
1266   event.commit();
1267 }
1268 
1269 #endif // INCLUDE_TRACE