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