1 /*
   2  * Copyright (c) 2012, 2013, 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 // extension, 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/systemDictionary.hpp"
  55 #include "code/codeCache.hpp"
  56 #include "memory/gcLocker.hpp"
  57 #include "memory/metadataFactory.hpp"
  58 #include "memory/metaspaceShared.hpp"
  59 #include "memory/oopFactory.hpp"
  60 #include "runtime/jniHandles.hpp"
  61 #include "runtime/mutex.hpp"
  62 #include "runtime/safepoint.hpp"
  63 #include "runtime/synchronizer.hpp"
  64 #include "utilities/growableArray.hpp"
  65 #include "utilities/ostream.hpp"
  66 
  67 ClassLoaderData * ClassLoaderData::_the_null_class_loader_data = NULL;
  68 
  69 ClassLoaderData::ClassLoaderData(Handle h_class_loader, bool is_anonymous, Dependencies dependencies) :
  70   _class_loader(h_class_loader()),
  71   _is_anonymous(is_anonymous), _keep_alive(is_anonymous), // initially
  72   _metaspace(NULL), _unloading(false), _klasses(NULL),
  73   _claimed(0), _jmethod_ids(NULL), _handles(NULL), _deallocate_list(NULL),
  74   _next(NULL), _dependencies(dependencies),
  75   _metaspace_lock(new Mutex(Monitor::leaf+1, "Metaspace allocation lock", true)) {
  76     // empty
  77 }
  78 
  79 void ClassLoaderData::init_dependencies(TRAPS) {
  80   assert(!Universe::is_fully_initialized(), "should only be called when initializing");
  81   assert(is_the_null_class_loader_data(), "should only call this for the null class loader");
  82   _dependencies.init(CHECK);
  83 }
  84 
  85 void ClassLoaderData::Dependencies::init(TRAPS) {
  86   // Create empty dependencies array to add to. CMS requires this to be
  87   // an oop so that it can track additions via card marks.  We think.
  88   _list_head = oopFactory::new_objectArray(2, CHECK);
  89 }
  90 
  91 bool ClassLoaderData::claim() {
  92   if (_claimed == 1) {
  93     return false;
  94   }
  95 
  96   return (int) Atomic::cmpxchg(1, &_claimed, 0) == 0;
  97 }
  98 
  99 void ClassLoaderData::oops_do(OopClosure* f, KlassClosure* klass_closure, bool must_claim) {
 100   if (must_claim && !claim()) {
 101     return;
 102   }
 103 
 104   f->do_oop(&_class_loader);
 105   _dependencies.oops_do(f);
 106   _handles->oops_do(f);
 107   if (klass_closure != NULL) {
 108     classes_do(klass_closure);
 109   }
 110 }
 111 
 112 void ClassLoaderData::Dependencies::oops_do(OopClosure* f) {
 113   f->do_oop((oop*)&_list_head);
 114 }
 115 
 116 void ClassLoaderData::classes_do(KlassClosure* klass_closure) {
 117   for (Klass* k = _klasses; k != NULL; k = k->next_link()) {
 118     klass_closure->do_klass(k);
 119     assert(k != k->next_link(), "no loops!");
 120   }
 121 }
 122 
 123 void ClassLoaderData::classes_do(void f(InstanceKlass*)) {
 124   for (Klass* k = _klasses; k != NULL; k = k->next_link()) {
 125     if (k->oop_is_instance()) {
 126       f(InstanceKlass::cast(k));
 127     }
 128     assert(k != k->next_link(), "no loops!");
 129   }
 130 }
 131 
 132 void ClassLoaderData::record_dependency(Klass* k, TRAPS) {
 133   ClassLoaderData * const from_cld = this;
 134   ClassLoaderData * const to_cld = k->class_loader_data();
 135 
 136   // Dependency to the null class loader data doesn't need to be recorded
 137   // because the null class loader data never goes away.
 138   if (to_cld->is_the_null_class_loader_data()) {
 139     return;
 140   }
 141 
 142   oop to;
 143   if (to_cld->is_anonymous()) {
 144     // Anonymous class dependencies are through the mirror.
 145     to = k->java_mirror();
 146   } else {
 147     to = to_cld->class_loader();
 148 
 149     // If from_cld is anonymous, even if it's class_loader is a parent of 'to'
 150     // we still have to add it.  The class_loader won't keep from_cld alive.
 151     if (!from_cld->is_anonymous()) {
 152       // Check that this dependency isn't from the same or parent class_loader
 153       oop from = from_cld->class_loader();
 154 
 155       oop curr = from;
 156       while (curr != NULL) {
 157         if (curr == to) {
 158           return; // this class loader is in the parent list, no need to add it.
 159         }
 160         curr = java_lang_ClassLoader::parent(curr);
 161       }
 162     }
 163   }
 164 
 165   // It's a dependency we won't find through GC, add it. This is relatively rare
 166   // Must handle over GC point.
 167   Handle dependency(THREAD, to);
 168   from_cld->_dependencies.add(dependency, CHECK);
 169 }
 170 
 171 
 172 void ClassLoaderData::Dependencies::add(Handle dependency, TRAPS) {
 173   // Check first if this dependency is already in the list.
 174   // Save a pointer to the last to add to under the lock.
 175   objArrayOop ok = _list_head;
 176   objArrayOop last = NULL;
 177   while (ok != NULL) {
 178     last = ok;
 179     if (ok->obj_at(0) == dependency()) {
 180       // Don't need to add it
 181       return;
 182     }
 183     ok = (objArrayOop)ok->obj_at(1);
 184   }
 185 
 186   // Must handle over GC points
 187   assert (last != NULL, "dependencies should be initialized");
 188   objArrayHandle last_handle(THREAD, last);
 189 
 190   // Create a new dependency node with fields for (class_loader or mirror, next)
 191   objArrayOop deps = oopFactory::new_objectArray(2, CHECK);
 192   deps->obj_at_put(0, dependency());
 193 
 194   // Must handle over GC points
 195   objArrayHandle new_dependency(THREAD, deps);
 196 
 197   // Add the dependency under lock
 198   locked_add(last_handle, new_dependency, THREAD);
 199 }
 200 
 201 void ClassLoaderData::Dependencies::locked_add(objArrayHandle last_handle,
 202                                                objArrayHandle new_dependency,
 203                                                Thread* THREAD) {
 204 
 205   // Have to lock and put the new dependency on the end of the dependency
 206   // array so the card mark for CMS sees that this dependency is new.
 207   // Can probably do this lock free with some effort.
 208   ObjectLocker ol(Handle(THREAD, _list_head), THREAD);
 209 
 210   oop loader_or_mirror = new_dependency->obj_at(0);
 211 
 212   // Since the dependencies are only added, add to the end.
 213   objArrayOop end = last_handle();
 214   objArrayOop last = NULL;
 215   while (end != NULL) {
 216     last = end;
 217     // check again if another thread added it to the end.
 218     if (end->obj_at(0) == loader_or_mirror) {
 219       // Don't need to add it
 220       return;
 221     }
 222     end = (objArrayOop)end->obj_at(1);
 223   }
 224   assert (last != NULL, "dependencies should be initialized");
 225   // fill in the first element with the oop in new_dependency.
 226   if (last->obj_at(0) == NULL) {
 227     last->obj_at_put(0, new_dependency->obj_at(0));
 228   } else {
 229     last->obj_at_put(1, new_dependency());
 230   }
 231 }
 232 
 233 void ClassLoaderDataGraph::clear_claimed_marks() {
 234   for (ClassLoaderData* cld = _head; cld != NULL; cld = cld->next()) {
 235     cld->clear_claimed();
 236   }
 237 }
 238 
 239 void ClassLoaderData::add_class(Klass* k) {
 240   MutexLockerEx ml(metaspace_lock(),  Mutex::_no_safepoint_check_flag);
 241   Klass* old_value = _klasses;
 242   k->set_next_link(old_value);
 243   // link the new item into the list
 244   _klasses = k;
 245 
 246   if (TraceClassLoaderData && Verbose && k->class_loader_data() != NULL) {
 247     ResourceMark rm;
 248     tty->print_cr("[TraceClassLoaderData] Adding k: " PTR_FORMAT " %s to CLD: "
 249                   PTR_FORMAT " loader: " PTR_FORMAT " %s",
 250                   k,
 251                   k->external_name(),
 252                   k->class_loader_data(),
 253                   k->class_loader(),
 254                   loader_name());
 255   }
 256 }
 257 
 258 // This is called by InstanceKlass::deallocate_contents() to remove the
 259 // scratch_class for redefine classes.  We need a lock because there it may not
 260 // be called at a safepoint if there's an error.
 261 void ClassLoaderData::remove_class(Klass* scratch_class) {
 262   MutexLockerEx ml(metaspace_lock(),  Mutex::_no_safepoint_check_flag);
 263   Klass* prev = NULL;
 264   for (Klass* k = _klasses; k != NULL; k = k->next_link()) {
 265     if (k == scratch_class) {
 266       if (prev == NULL) {
 267         _klasses = k->next_link();
 268       } else {
 269         Klass* next = k->next_link();
 270         prev->set_next_link(next);
 271       }
 272       return;
 273     }
 274     prev = k;
 275     assert(k != k->next_link(), "no loops!");
 276   }
 277   ShouldNotReachHere();   // should have found this class!!
 278 }
 279 
 280 void ClassLoaderData::unload() {
 281   _unloading = true;
 282 
 283   // Tell serviceability tools these classes are unloading
 284   classes_do(InstanceKlass::notify_unload_class);
 285 
 286   if (TraceClassLoaderData) {
 287     ResourceMark rm;
 288     tty->print("[ClassLoaderData: unload loader data "PTR_FORMAT, this);
 289     tty->print(" for instance "PTR_FORMAT" of %s", class_loader(),
 290                loader_name());
 291     if (is_anonymous()) {
 292       tty->print(" for anonymous class  "PTR_FORMAT " ", _klasses);
 293     }
 294     tty->print_cr("]");
 295   }
 296 }
 297 
 298 bool ClassLoaderData::is_alive(BoolObjectClosure* is_alive_closure) const {
 299   bool alive =
 300     is_anonymous() ?
 301        is_alive_closure->do_object_b(_klasses->java_mirror()) :
 302        class_loader() == NULL || is_alive_closure->do_object_b(class_loader());
 303   assert(!alive || claimed(), "must be claimed");
 304   return alive;
 305 }
 306 
 307 
 308 ClassLoaderData::~ClassLoaderData() {
 309   // Release C heap structures for all the classes.
 310   classes_do(InstanceKlass::release_C_heap_structures);
 311 
 312   Metaspace *m = _metaspace;
 313   if (m != NULL) {
 314     _metaspace = NULL;
 315     // release the metaspace
 316     delete m;
 317     // release the handles
 318     if (_handles != NULL) {
 319       JNIHandleBlock::release_block(_handles);
 320       _handles = NULL;
 321     }
 322   }
 323 
 324   // Clear all the JNI handles for methods
 325   // These aren't deallocated and are going to look like a leak, but that's
 326   // needed because we can't really get rid of jmethodIDs because we don't
 327   // know when native code is going to stop using them.  The spec says that
 328   // they're "invalid" but existing programs likely rely on their being
 329   // NULL after class unloading.
 330   if (_jmethod_ids != NULL) {
 331     Method::clear_jmethod_ids(this);
 332   }
 333   // Delete lock
 334   delete _metaspace_lock;
 335 
 336   // Delete free list
 337   if (_deallocate_list != NULL) {
 338     delete _deallocate_list;
 339   }
 340 }
 341 
 342 /**
 343  * Returns true if this class loader data is for the extension class loader.
 344  */
 345 bool ClassLoaderData::is_ext_class_loader_data() const {
 346   return SystemDictionary::is_ext_class_loader(class_loader());
 347 }
 348 
 349 Metaspace* ClassLoaderData::metaspace_non_null() {
 350   assert(!DumpSharedSpaces, "wrong metaspace!");
 351   // If the metaspace has not been allocated, create a new one.  Might want
 352   // to create smaller arena for Reflection class loaders also.
 353   // The reason for the delayed allocation is because some class loaders are
 354   // simply for delegating with no metadata of their own.
 355   if (_metaspace == NULL) {
 356     MutexLockerEx ml(metaspace_lock(),  Mutex::_no_safepoint_check_flag);
 357     // Check again if metaspace has been allocated while we were getting this lock.
 358     if (_metaspace != NULL) {
 359       return _metaspace;
 360     }
 361     if (this == the_null_class_loader_data()) {
 362       assert (class_loader() == NULL, "Must be");
 363       set_metaspace(new Metaspace(_metaspace_lock, Metaspace::BootMetaspaceType));
 364     } else if (is_anonymous()) {
 365       if (TraceClassLoaderData && Verbose && class_loader() != NULL) {
 366         tty->print_cr("is_anonymous: %s", class_loader()->klass()->internal_name());
 367       }
 368       set_metaspace(new Metaspace(_metaspace_lock, Metaspace::AnonymousMetaspaceType));
 369     } else if (class_loader()->is_a(SystemDictionary::reflect_DelegatingClassLoader_klass())) {
 370       if (TraceClassLoaderData && Verbose && class_loader() != NULL) {
 371         tty->print_cr("is_reflection: %s", class_loader()->klass()->internal_name());
 372       }
 373       set_metaspace(new Metaspace(_metaspace_lock, Metaspace::ReflectionMetaspaceType));
 374     } else {
 375       set_metaspace(new Metaspace(_metaspace_lock, Metaspace::StandardMetaspaceType));
 376     }
 377   }
 378   return _metaspace;
 379 }
 380 
 381 JNIHandleBlock* ClassLoaderData::handles() const           { return _handles; }
 382 void ClassLoaderData::set_handles(JNIHandleBlock* handles) { _handles = handles; }
 383 
 384 jobject ClassLoaderData::add_handle(Handle h) {
 385   MutexLockerEx ml(metaspace_lock(),  Mutex::_no_safepoint_check_flag);
 386   if (handles() == NULL) {
 387     set_handles(JNIHandleBlock::allocate_block());
 388   }
 389   return handles()->allocate_handle(h());
 390 }
 391 
 392 // Add this metadata pointer to be freed when it's safe.  This is only during
 393 // class unloading because Handles might point to this metadata field.
 394 void ClassLoaderData::add_to_deallocate_list(Metadata* m) {
 395   // Metadata in shared region isn't deleted.
 396   if (!m->is_shared()) {
 397     MutexLockerEx ml(metaspace_lock(),  Mutex::_no_safepoint_check_flag);
 398     if (_deallocate_list == NULL) {
 399       _deallocate_list = new (ResourceObj::C_HEAP, mtClass) GrowableArray<Metadata*>(100, true);
 400     }
 401     _deallocate_list->append_if_missing(m);
 402   }
 403 }
 404 
 405 // Deallocate free metadata on the free list.  How useful the PermGen was!
 406 void ClassLoaderData::free_deallocate_list() {
 407   // Don't need lock, at safepoint
 408   assert(SafepointSynchronize::is_at_safepoint(), "only called at safepoint");
 409   if (_deallocate_list == NULL) {
 410     return;
 411   }
 412   // Go backwards because this removes entries that are freed.
 413   for (int i = _deallocate_list->length() - 1; i >= 0; i--) {
 414     Metadata* m = _deallocate_list->at(i);
 415     if (!m->on_stack()) {
 416       _deallocate_list->remove_at(i);
 417       // There are only three types of metadata that we deallocate directly.
 418       // Cast them so they can be used by the template function.
 419       if (m->is_method()) {
 420         MetadataFactory::free_metadata(this, (Method*)m);
 421       } else if (m->is_constantPool()) {
 422         MetadataFactory::free_metadata(this, (ConstantPool*)m);
 423       } else if (m->is_klass()) {
 424         MetadataFactory::free_metadata(this, (InstanceKlass*)m);
 425       } else {
 426         ShouldNotReachHere();
 427       }
 428     }
 429   }
 430 }
 431 
 432 // These anonymous class loaders are to contain classes used for JSR292
 433 ClassLoaderData* ClassLoaderData::anonymous_class_loader_data(oop loader, TRAPS) {
 434   // Add a new class loader data to the graph.
 435   return ClassLoaderDataGraph::add(loader, true, CHECK_NULL);
 436 }
 437 
 438 const char* ClassLoaderData::loader_name() {
 439   // Handles null class loader
 440   return SystemDictionary::loader_name(class_loader());
 441 }
 442 
 443 #ifndef PRODUCT
 444 // Define to dump klasses
 445 #undef CLD_DUMP_KLASSES
 446 
 447 void ClassLoaderData::dump(outputStream * const out) {
 448   ResourceMark rm;
 449   out->print("ClassLoaderData CLD: "PTR_FORMAT", loader: "PTR_FORMAT", loader_klass: "PTR_FORMAT" %s {",
 450       this, class_loader(),
 451       class_loader() != NULL ? class_loader()->klass() : NULL, loader_name());
 452   if (claimed()) out->print(" claimed ");
 453   if (is_unloading()) out->print(" unloading ");
 454   out->print(" handles " INTPTR_FORMAT, handles());
 455   out->cr();
 456   if (metaspace_or_null() != NULL) {
 457     out->print_cr("metaspace: " PTR_FORMAT, metaspace_or_null());
 458     metaspace_or_null()->dump(out);
 459   } else {
 460     out->print_cr("metaspace: NULL");
 461   }
 462 
 463 #ifdef CLD_DUMP_KLASSES
 464   if (Verbose) {
 465     ResourceMark rm;
 466     Klass* k = _klasses;
 467     while (k != NULL) {
 468       out->print_cr("klass "PTR_FORMAT", %s, CT: %d, MUT: %d", k, k->name()->as_C_string(),
 469           k->has_modified_oops(), k->has_accumulated_modified_oops());
 470       assert(k != k->next_link(), "no loops!");
 471       k = k->next_link();
 472     }
 473   }
 474 #endif  // CLD_DUMP_KLASSES
 475 #undef CLD_DUMP_KLASSES
 476   if (_jmethod_ids != NULL) {
 477     Method::print_jmethod_ids(this, out);
 478   }
 479   out->print_cr("}");
 480 }
 481 #endif // PRODUCT
 482 
 483 void ClassLoaderData::verify() {
 484   oop cl = class_loader();
 485 
 486   guarantee(this == class_loader_data(cl) || is_anonymous(), "Must be the same");
 487   guarantee(cl != NULL || this == ClassLoaderData::the_null_class_loader_data() || is_anonymous(), "must be");
 488 
 489   // Verify the integrity of the allocated space.
 490   if (metaspace_or_null() != NULL) {
 491     metaspace_or_null()->verify();
 492   }
 493 
 494   for (Klass* k = _klasses; k != NULL; k = k->next_link()) {
 495     guarantee(k->class_loader_data() == this, "Must be the same");
 496     k->verify();
 497     assert(k != k->next_link(), "no loops!");
 498   }
 499 }
 500 
 501 
 502 // GC root of class loader data created.
 503 ClassLoaderData* ClassLoaderDataGraph::_head = NULL;
 504 ClassLoaderData* ClassLoaderDataGraph::_unloading = NULL;
 505 ClassLoaderData* ClassLoaderDataGraph::_saved_head = NULL;
 506 
 507 // Add a new class loader data node to the list.  Assign the newly created
 508 // ClassLoaderData into the java/lang/ClassLoader object as a hidden field
 509 ClassLoaderData* ClassLoaderDataGraph::add(Handle loader, bool is_anonymous, TRAPS) {
 510   // We need to allocate all the oops for the ClassLoaderData before allocating the
 511   // actual ClassLoaderData object.
 512   ClassLoaderData::Dependencies dependencies(CHECK_NULL);
 513 
 514   No_Safepoint_Verifier no_safepoints; // we mustn't GC until we've installed the
 515                                        // ClassLoaderData in the graph since the CLD
 516                                        // contains unhandled oops
 517 
 518   ClassLoaderData* cld = new ClassLoaderData(loader, is_anonymous, dependencies);
 519 
 520 
 521   if (!is_anonymous) {
 522     ClassLoaderData** cld_addr = java_lang_ClassLoader::loader_data_addr(loader());
 523     // First, Atomically set it
 524     ClassLoaderData* old = (ClassLoaderData*) Atomic::cmpxchg_ptr(cld, cld_addr, NULL);
 525     if (old != NULL) {
 526       delete cld;
 527       // Returns the data.
 528       return old;
 529     }
 530   }
 531 
 532   // We won the race, and therefore the task of adding the data to the list of
 533   // class loader data
 534   ClassLoaderData** list_head = &_head;
 535   ClassLoaderData* next = _head;
 536 
 537   do {
 538     cld->set_next(next);
 539     ClassLoaderData* exchanged = (ClassLoaderData*)Atomic::cmpxchg_ptr(cld, list_head, next);
 540     if (exchanged == next) {
 541       if (TraceClassLoaderData) {
 542         ResourceMark rm;
 543         tty->print("[ClassLoaderData: ");
 544         tty->print("create class loader data "PTR_FORMAT, cld);
 545         tty->print(" for instance "PTR_FORMAT" of %s", cld->class_loader(),
 546                    cld->loader_name());
 547         tty->print_cr("]");
 548       }
 549       return cld;
 550     }
 551     next = exchanged;
 552   } while (true);
 553 
 554 }
 555 
 556 void ClassLoaderDataGraph::oops_do(OopClosure* f, KlassClosure* klass_closure, bool must_claim) {
 557   for (ClassLoaderData* cld = _head; cld != NULL; cld = cld->next()) {
 558     cld->oops_do(f, klass_closure, must_claim);
 559   }
 560 }
 561 
 562 void ClassLoaderDataGraph::keep_alive_oops_do(OopClosure* f, KlassClosure* klass_closure, bool must_claim) {
 563   for (ClassLoaderData* cld = _head; cld != NULL; cld = cld->next()) {
 564     if (cld->keep_alive()) {
 565       cld->oops_do(f, klass_closure, must_claim);
 566     }
 567   }
 568 }
 569 
 570 void ClassLoaderDataGraph::always_strong_oops_do(OopClosure* f, KlassClosure* klass_closure, bool must_claim) {
 571   if (ClassUnloading) {
 572     ClassLoaderData::the_null_class_loader_data()->oops_do(f, klass_closure, must_claim);
 573     // keep any special CLDs alive.
 574     ClassLoaderDataGraph::keep_alive_oops_do(f, klass_closure, must_claim);
 575   } else {
 576     ClassLoaderDataGraph::oops_do(f, klass_closure, must_claim);
 577   }
 578 }
 579 
 580 void ClassLoaderDataGraph::classes_do(KlassClosure* klass_closure) {
 581   for (ClassLoaderData* cld = _head; cld != NULL; cld = cld->next()) {
 582     cld->classes_do(klass_closure);
 583   }
 584 }
 585 
 586 GrowableArray<ClassLoaderData*>* ClassLoaderDataGraph::new_clds() {
 587   assert(_head == NULL || _saved_head != NULL, "remember_new_clds(true) not called?");
 588 
 589   GrowableArray<ClassLoaderData*>* array = new GrowableArray<ClassLoaderData*>();
 590 
 591   // The CLDs in [_head, _saved_head] were all added during last call to remember_new_clds(true);
 592   ClassLoaderData* curr = _head;
 593   while (curr != _saved_head) {
 594     if (!curr->claimed()) {
 595       array->push(curr);
 596 
 597       if (TraceClassLoaderData) {
 598         tty->print("[ClassLoaderData] found new CLD: ");
 599         curr->print_value_on(tty);
 600         tty->cr();
 601       }
 602     }
 603 
 604     curr = curr->_next;
 605   }
 606 
 607   return array;
 608 }
 609 
 610 #ifndef PRODUCT
 611 // for debugging and hsfind(x)
 612 bool ClassLoaderDataGraph::contains(address x) {
 613   // I think we need the _metaspace_lock taken here because the class loader
 614   // data graph could be changing while we are walking it (new entries added,
 615   // new entries being unloaded, etc).
 616   if (DumpSharedSpaces) {
 617     // There are only two metaspaces to worry about.
 618     ClassLoaderData* ncld = ClassLoaderData::the_null_class_loader_data();
 619     return (ncld->ro_metaspace()->contains(x) || ncld->rw_metaspace()->contains(x));
 620   }
 621 
 622   if (UseSharedSpaces && MetaspaceShared::is_in_shared_space(x)) {
 623     return true;
 624   }
 625 
 626   for (ClassLoaderData* cld = _head; cld != NULL; cld = cld->next()) {
 627     if (cld->metaspace_or_null() != NULL && cld->metaspace_or_null()->contains(x)) {
 628       return true;
 629     }
 630   }
 631 
 632   // Could also be on an unloading list which is okay, ie. still allocated
 633   // for a little while.
 634   for (ClassLoaderData* ucld = _unloading; ucld != NULL; ucld = ucld->next()) {
 635     if (ucld->metaspace_or_null() != NULL && ucld->metaspace_or_null()->contains(x)) {
 636       return true;
 637     }
 638   }
 639   return false;
 640 }
 641 
 642 bool ClassLoaderDataGraph::contains_loader_data(ClassLoaderData* loader_data) {
 643   for (ClassLoaderData* data = _head; data != NULL; data = data->next()) {
 644     if (loader_data == data) {
 645       return true;
 646     }
 647   }
 648 
 649   return false;
 650 }
 651 #endif // PRODUCT
 652 
 653 
 654 // Move class loader data from main list to the unloaded list for unloading
 655 // and deallocation later.
 656 bool ClassLoaderDataGraph::do_unloading(BoolObjectClosure* is_alive_closure) {
 657   ClassLoaderData* data = _head;
 658   ClassLoaderData* prev = NULL;
 659   bool seen_dead_loader = false;
 660   // mark metadata seen on the stack and code cache so we can delete
 661   // unneeded entries.
 662   bool has_redefined_a_class = JvmtiExport::has_redefined_a_class();
 663   MetadataOnStackMark md_on_stack;
 664   while (data != NULL) {
 665     if (data->keep_alive() || data->is_alive(is_alive_closure)) {
 666       if (has_redefined_a_class) {
 667         data->classes_do(InstanceKlass::purge_previous_versions);
 668       }
 669       data->free_deallocate_list();
 670       prev = data;
 671       data = data->next();
 672       continue;
 673     }
 674     seen_dead_loader = true;
 675     ClassLoaderData* dead = data;
 676     dead->unload();
 677     data = data->next();
 678     // Remove from loader list.
 679     // This class loader data will no longer be found
 680     // in the ClassLoaderDataGraph.
 681     if (prev != NULL) {
 682       prev->set_next(data);
 683     } else {
 684       assert(dead == _head, "sanity check");
 685       _head = data;
 686     }
 687     dead->set_next(_unloading);
 688     _unloading = dead;
 689   }
 690   return seen_dead_loader;
 691 }
 692 
 693 void ClassLoaderDataGraph::purge() {
 694   ClassLoaderData* list = _unloading;
 695   _unloading = NULL;
 696   ClassLoaderData* next = list;
 697   while (next != NULL) {
 698     ClassLoaderData* purge_me = next;
 699     next = purge_me->next();
 700     delete purge_me;
 701   }
 702   Metaspace::purge();
 703 }
 704 
 705 // CDS support
 706 
 707 // Global metaspaces for writing information to the shared archive.  When
 708 // application CDS is supported, we may need one per metaspace, so this
 709 // sort of looks like it.
 710 Metaspace* ClassLoaderData::_ro_metaspace = NULL;
 711 Metaspace* ClassLoaderData::_rw_metaspace = NULL;
 712 static bool _shared_metaspaces_initialized = false;
 713 
 714 // Initialize shared metaspaces (change to call from somewhere not lazily)
 715 void ClassLoaderData::initialize_shared_metaspaces() {
 716   assert(DumpSharedSpaces, "only use this for dumping shared spaces");
 717   assert(this == ClassLoaderData::the_null_class_loader_data(),
 718          "only supported for null loader data for now");
 719   assert (!_shared_metaspaces_initialized, "only initialize once");
 720   MutexLockerEx ml(metaspace_lock(),  Mutex::_no_safepoint_check_flag);
 721   _ro_metaspace = new Metaspace(_metaspace_lock, Metaspace::ROMetaspaceType);
 722   _rw_metaspace = new Metaspace(_metaspace_lock, Metaspace::ReadWriteMetaspaceType);
 723   _shared_metaspaces_initialized = true;
 724 }
 725 
 726 Metaspace* ClassLoaderData::ro_metaspace() {
 727   assert(_ro_metaspace != NULL, "should already be initialized");
 728   return _ro_metaspace;
 729 }
 730 
 731 Metaspace* ClassLoaderData::rw_metaspace() {
 732   assert(_rw_metaspace != NULL, "should already be initialized");
 733   return _rw_metaspace;
 734 }
 735 
 736 
 737 ClassLoaderDataGraphMetaspaceIterator::ClassLoaderDataGraphMetaspaceIterator() {
 738   _data = ClassLoaderDataGraph::_head;
 739 }
 740 
 741 ClassLoaderDataGraphMetaspaceIterator::~ClassLoaderDataGraphMetaspaceIterator() {}
 742 
 743 #ifndef PRODUCT
 744 // callable from debugger
 745 extern "C" int print_loader_data_graph() {
 746   ClassLoaderDataGraph::dump_on(tty);
 747   return 0;
 748 }
 749 
 750 void ClassLoaderDataGraph::verify() {
 751   for (ClassLoaderData* data = _head; data != NULL; data = data->next()) {
 752     data->verify();
 753   }
 754 }
 755 
 756 void ClassLoaderDataGraph::dump_on(outputStream * const out) {
 757   for (ClassLoaderData* data = _head; data != NULL; data = data->next()) {
 758     data->dump(out);
 759   }
 760   MetaspaceAux::dump(out);
 761 }
 762 #endif // PRODUCT
 763 
 764 void ClassLoaderData::print_value_on(outputStream* out) const {
 765   if (class_loader() == NULL) {
 766     out->print("NULL class_loader");
 767   } else {
 768     out->print("class loader "PTR_FORMAT, this);
 769     class_loader()->print_value_on(out);
 770   }
 771 }