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