1 /*
   2  * Copyright (c) 2012, 2014, 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/macros.hpp"
  66 #include "utilities/ostream.hpp"
  67 #include "evtrace/traceEvents.hpp"
  68 #if INCLUDE_TRACE
  69 #include "trace/tracing.hpp"
  70 #endif
  71 
  72 ClassLoaderData * ClassLoaderData::_the_null_class_loader_data = NULL;
  73 
  74 ClassLoaderData::ClassLoaderData(Handle h_class_loader, bool is_anonymous, Dependencies dependencies) :
  75   _class_loader(h_class_loader()),
  76   _is_anonymous(is_anonymous),
  77   // An anonymous class loader data doesn't have anything to keep
  78   // it from being unloaded during parsing of the anonymous class.
  79   // The null-class-loader should always be kept alive.
  80   _keep_alive(is_anonymous || h_class_loader.is_null()),
  81   _metaspace(NULL), _unloading(false), _klasses(NULL),
  82   _claimed(0), _jmethod_ids(NULL), _handles(NULL), _deallocate_list(NULL),
  83   _next(NULL), _dependencies(dependencies),
  84   _metaspace_lock(new Mutex(Monitor::leaf+1, "Metaspace allocation lock", true)) {
  85     // empty
  86 }
  87 
  88 void ClassLoaderData::init_dependencies(TRAPS) {
  89   assert(!Universe::is_fully_initialized(), "should only be called when initializing");
  90   assert(is_the_null_class_loader_data(), "should only call this for the null class loader");
  91   _dependencies.init(CHECK);
  92 }
  93 
  94 void ClassLoaderData::Dependencies::init(TRAPS) {
  95   // Create empty dependencies array to add to. CMS requires this to be
  96   // an oop so that it can track additions via card marks.  We think.
  97   _list_head = oopFactory::new_objectArray(2, CHECK);
  98 }
  99 
 100 bool ClassLoaderData::claim() {
 101   if (_claimed == 1) {
 102     return false;
 103   }
 104 
 105   return (int) Atomic::cmpxchg(1, &_claimed, 0) == 0;
 106 }
 107 
 108 void ClassLoaderData::oops_do(OopClosure* f, KlassClosure* klass_closure, bool must_claim) {
 109   if (must_claim && !claim()) {
 110     return;
 111   }
 112 
 113   f->do_oop(&_class_loader);
 114   _dependencies.oops_do(f);
 115   _handles->oops_do(f);
 116   if (klass_closure != NULL) {
 117     classes_do(klass_closure);
 118   }
 119 }
 120 
 121 void ClassLoaderData::Dependencies::oops_do(OopClosure* f) {
 122   f->do_oop((oop*)&_list_head);
 123 }
 124 
 125 void ClassLoaderData::classes_do(KlassClosure* klass_closure) {
 126   for (Klass* k = _klasses; k != NULL; k = k->next_link()) {
 127     klass_closure->do_klass(k);
 128     assert(k != k->next_link(), "no loops!");
 129   }
 130 }
 131 
 132 void ClassLoaderData::classes_do(void f(Klass * const)) {
 133   for (Klass* k = _klasses; k != NULL; k = k->next_link()) {
 134     f(k);
 135   }
 136 }
 137 
 138 void ClassLoaderData::loaded_classes_do(KlassClosure* klass_closure) {
 139   // Lock to avoid classes being modified/added/removed during iteration
 140   MutexLockerEx ml(metaspace_lock(),  Mutex::_no_safepoint_check_flag);
 141   for (Klass* k = _klasses; k != NULL; k = k->next_link()) {
 142     // Do not filter ArrayKlass oops here...
 143     if (k->oop_is_array() || (k->oop_is_instance() && InstanceKlass::cast(k)->is_loaded())) {
 144       klass_closure->do_klass(k);
 145     }
 146   }
 147 }
 148 
 149 void ClassLoaderData::classes_do(void f(InstanceKlass*)) {
 150   for (Klass* k = _klasses; k != NULL; k = k->next_link()) {
 151     if (k->oop_is_instance()) {
 152       f(InstanceKlass::cast(k));
 153     }
 154     assert(k != k->next_link(), "no loops!");
 155   }
 156 }
 157 
 158 void ClassLoaderData::record_dependency(Klass* k, TRAPS) {
 159   ClassLoaderData * const from_cld = this;
 160   ClassLoaderData * const to_cld = k->class_loader_data();
 161 
 162   // Dependency to the null class loader data doesn't need to be recorded
 163   // because the null class loader data never goes away.
 164   if (to_cld->is_the_null_class_loader_data()) {
 165     return;
 166   }
 167 
 168   oop to;
 169   if (to_cld->is_anonymous()) {
 170     // Anonymous class dependencies are through the mirror.
 171     to = k->java_mirror();
 172   } else {
 173     to = to_cld->class_loader();
 174 
 175     // If from_cld is anonymous, even if it's class_loader is a parent of 'to'
 176     // we still have to add it.  The class_loader won't keep from_cld alive.
 177     if (!from_cld->is_anonymous()) {
 178       // Check that this dependency isn't from the same or parent class_loader
 179       oop from = from_cld->class_loader();
 180 
 181       oop curr = from;
 182       while (curr != NULL) {
 183         if (curr == to) {
 184           return; // this class loader is in the parent list, no need to add it.
 185         }
 186         curr = java_lang_ClassLoader::parent(curr);
 187       }
 188     }
 189   }
 190 
 191   // It's a dependency we won't find through GC, add it. This is relatively rare
 192   // Must handle over GC point.
 193   Handle dependency(THREAD, to);
 194   from_cld->_dependencies.add(dependency, CHECK);
 195 }
 196 
 197 
 198 void ClassLoaderData::Dependencies::add(Handle dependency, TRAPS) {
 199   // Check first if this dependency is already in the list.
 200   // Save a pointer to the last to add to under the lock.
 201   objArrayOop ok = _list_head;
 202   objArrayOop last = NULL;
 203   while (ok != NULL) {
 204     last = ok;
 205     if (ok->obj_at(0) == dependency()) {
 206       // Don't need to add it
 207       return;
 208     }
 209     ok = (objArrayOop)ok->obj_at(1);
 210   }
 211 
 212   // Must handle over GC points
 213   assert (last != NULL, "dependencies should be initialized");
 214   objArrayHandle last_handle(THREAD, last);
 215 
 216   // Create a new dependency node with fields for (class_loader or mirror, next)
 217   objArrayOop deps = oopFactory::new_objectArray(2, CHECK);
 218   deps->obj_at_put(0, dependency());
 219 
 220   // Must handle over GC points
 221   objArrayHandle new_dependency(THREAD, deps);
 222 
 223   // Add the dependency under lock
 224   locked_add(last_handle, new_dependency, THREAD);
 225 }
 226 
 227 void ClassLoaderData::Dependencies::locked_add(objArrayHandle last_handle,
 228                                                objArrayHandle new_dependency,
 229                                                Thread* THREAD) {
 230 
 231   // Have to lock and put the new dependency on the end of the dependency
 232   // array so the card mark for CMS sees that this dependency is new.
 233   // Can probably do this lock free with some effort.
 234   ObjectLocker ol(Handle(THREAD, _list_head), THREAD);
 235 
 236   oop loader_or_mirror = new_dependency->obj_at(0);
 237 
 238   // Since the dependencies are only added, add to the end.
 239   objArrayOop end = last_handle();
 240   objArrayOop last = NULL;
 241   while (end != NULL) {
 242     last = end;
 243     // check again if another thread added it to the end.
 244     if (end->obj_at(0) == loader_or_mirror) {
 245       // Don't need to add it
 246       return;
 247     }
 248     end = (objArrayOop)end->obj_at(1);
 249   }
 250   assert (last != NULL, "dependencies should be initialized");
 251   // fill in the first element with the oop in new_dependency.
 252   if (last->obj_at(0) == NULL) {
 253     last->obj_at_put(0, new_dependency->obj_at(0));
 254   } else {
 255     last->obj_at_put(1, new_dependency());
 256   }
 257 }
 258 
 259 void ClassLoaderDataGraph::clear_claimed_marks() {
 260   for (ClassLoaderData* cld = _head; cld != NULL; cld = cld->next()) {
 261     cld->clear_claimed();
 262   }
 263 }
 264 
 265 void ClassLoaderData::add_class(Klass* k) {
 266   MutexLockerEx ml(metaspace_lock(),  Mutex::_no_safepoint_check_flag);
 267   Klass* old_value = _klasses;
 268   k->set_next_link(old_value);
 269   // link the new item into the list
 270   _klasses = k;
 271 
 272   if (TraceClassLoaderData && Verbose && k->class_loader_data() != NULL) {
 273     ResourceMark rm;
 274     tty->print_cr("[TraceClassLoaderData] Adding k: " PTR_FORMAT " %s to CLD: "
 275                   PTR_FORMAT " loader: " PTR_FORMAT " %s",
 276                   p2i(k),
 277                   k->external_name(),
 278                   p2i(k->class_loader_data()),
 279                   p2i((void *)k->class_loader()),
 280                   loader_name());
 281   }
 282 }
 283 
 284 // This is called by InstanceKlass::deallocate_contents() to remove the
 285 // scratch_class for redefine classes.  We need a lock because there it may not
 286 // be called at a safepoint if there's an error.
 287 void ClassLoaderData::remove_class(Klass* scratch_class) {
 288   MutexLockerEx ml(metaspace_lock(),  Mutex::_no_safepoint_check_flag);
 289   Klass* prev = NULL;
 290   for (Klass* k = _klasses; k != NULL; k = k->next_link()) {
 291     if (k == scratch_class) {
 292       if (prev == NULL) {
 293         _klasses = k->next_link();
 294       } else {
 295         Klass* next = k->next_link();
 296         prev->set_next_link(next);
 297       }
 298       return;
 299     }
 300     prev = k;
 301     assert(k != k->next_link(), "no loops!");
 302   }
 303   ShouldNotReachHere();   // should have found this class!!
 304 }
 305 
 306 void ClassLoaderData::unload() {
 307   _unloading = true;
 308 
 309   // Tell serviceability tools these classes are unloading
 310   if (EnableEventTracing) {
 311     TraceManager::class_loader_is_unloading(this); // also writes an event
 312   }
 313   classes_do(InstanceKlass::notify_unload_class);
 314 
 315   if (TraceClassLoaderData) {
 316     ResourceMark rm;
 317     tty->print("[ClassLoaderData: unload loader data " INTPTR_FORMAT, p2i(this));
 318     tty->print(" for instance " INTPTR_FORMAT " of %s", p2i((void *)class_loader()),
 319                loader_name());
 320     if (is_anonymous()) {
 321       tty->print(" for anonymous class  " INTPTR_FORMAT " ", p2i(_klasses));
 322     }
 323     tty->print_cr("]");
 324   }
 325 }
 326 
 327 oop ClassLoaderData::keep_alive_object() const {
 328   assert(!keep_alive(), "Don't use with CLDs that are artificially kept alive");
 329   return is_anonymous() ? _klasses->java_mirror() : class_loader();
 330 }
 331 
 332 bool ClassLoaderData::is_alive(BoolObjectClosure* is_alive_closure) const {
 333   bool alive = keep_alive() // null class loader and incomplete anonymous klasses.
 334       || is_alive_closure->do_object_b(keep_alive_object());
 335 
 336   return alive;
 337 }
 338 
 339 
 340 ClassLoaderData::~ClassLoaderData() {
 341   // Release C heap structures for all the classes.
 342   classes_do(InstanceKlass::release_C_heap_structures);
 343 
 344   Metaspace *m = _metaspace;
 345   if (m != NULL) {
 346     _metaspace = NULL;
 347     // release the metaspace
 348     delete m;
 349     // release the handles
 350     if (_handles != NULL) {
 351       JNIHandleBlock::release_block(_handles);
 352       _handles = NULL;
 353     }
 354   }
 355 
 356   // Clear all the JNI handles for methods
 357   // These aren't deallocated and are going to look like a leak, but that's
 358   // needed because we can't really get rid of jmethodIDs because we don't
 359   // know when native code is going to stop using them.  The spec says that
 360   // they're "invalid" but existing programs likely rely on their being
 361   // NULL after class unloading.
 362   if (_jmethod_ids != NULL) {
 363     Method::clear_jmethod_ids(this);
 364   }
 365   // Delete lock
 366   delete _metaspace_lock;
 367 
 368   // Delete free list
 369   if (_deallocate_list != NULL) {
 370     delete _deallocate_list;
 371   }
 372 }
 373 
 374 /**
 375  * Returns true if this class loader data is for the extension class loader.
 376  */
 377 bool ClassLoaderData::is_ext_class_loader_data() const {
 378   return SystemDictionary::is_ext_class_loader(class_loader());
 379 }
 380 
 381 Metaspace* ClassLoaderData::metaspace_non_null() {
 382   assert(!DumpSharedSpaces, "wrong metaspace!");
 383   // If the metaspace has not been allocated, create a new one.  Might want
 384   // to create smaller arena for Reflection class loaders also.
 385   // The reason for the delayed allocation is because some class loaders are
 386   // simply for delegating with no metadata of their own.
 387   if (_metaspace == NULL) {
 388     MutexLockerEx ml(metaspace_lock(),  Mutex::_no_safepoint_check_flag);
 389     // Check again if metaspace has been allocated while we were getting this lock.
 390     if (_metaspace != NULL) {
 391       return _metaspace;
 392     }
 393     if (this == the_null_class_loader_data()) {
 394       assert (class_loader() == NULL, "Must be");
 395       set_metaspace(new Metaspace(_metaspace_lock, Metaspace::BootMetaspaceType));
 396     } else if (is_anonymous()) {
 397       if (TraceClassLoaderData && Verbose && class_loader() != NULL) {
 398         tty->print_cr("is_anonymous: %s", class_loader()->klass()->internal_name());
 399       }
 400       set_metaspace(new Metaspace(_metaspace_lock, Metaspace::AnonymousMetaspaceType));
 401     } else if (class_loader()->is_a(SystemDictionary::reflect_DelegatingClassLoader_klass())) {
 402       if (TraceClassLoaderData && Verbose && class_loader() != NULL) {
 403         tty->print_cr("is_reflection: %s", class_loader()->klass()->internal_name());
 404       }
 405       set_metaspace(new Metaspace(_metaspace_lock, Metaspace::ReflectionMetaspaceType));
 406     } else {
 407       set_metaspace(new Metaspace(_metaspace_lock, Metaspace::StandardMetaspaceType));
 408     }
 409   }
 410   return _metaspace;
 411 }
 412 
 413 JNIHandleBlock* ClassLoaderData::handles() const           { return _handles; }
 414 void ClassLoaderData::set_handles(JNIHandleBlock* handles) { _handles = handles; }
 415 
 416 jobject ClassLoaderData::add_handle(Handle h) {
 417   MutexLockerEx ml(metaspace_lock(),  Mutex::_no_safepoint_check_flag);
 418   if (handles() == NULL) {
 419     set_handles(JNIHandleBlock::allocate_block());
 420   }
 421   return handles()->allocate_handle(h());
 422 }
 423 
 424 // Add this metadata pointer to be freed when it's safe.  This is only during
 425 // class unloading because Handles might point to this metadata field.
 426 void ClassLoaderData::add_to_deallocate_list(Metadata* m) {
 427   // Metadata in shared region isn't deleted.
 428   if (!m->is_shared()) {
 429     MutexLockerEx ml(metaspace_lock(),  Mutex::_no_safepoint_check_flag);
 430     if (_deallocate_list == NULL) {
 431       _deallocate_list = new (ResourceObj::C_HEAP, mtClass) GrowableArray<Metadata*>(100, true);
 432     }
 433     _deallocate_list->append_if_missing(m);
 434   }
 435 }
 436 
 437 // Deallocate free metadata on the free list.  How useful the PermGen was!
 438 void ClassLoaderData::free_deallocate_list() {
 439   // Don't need lock, at safepoint
 440   assert(SafepointSynchronize::is_at_safepoint(), "only called at safepoint");
 441   if (_deallocate_list == NULL) {
 442     return;
 443   }
 444   // Go backwards because this removes entries that are freed.
 445   for (int i = _deallocate_list->length() - 1; i >= 0; i--) {
 446     Metadata* m = _deallocate_list->at(i);
 447     if (!m->on_stack()) {
 448       _deallocate_list->remove_at(i);
 449       // There are only three types of metadata that we deallocate directly.
 450       // Cast them so they can be used by the template function.
 451       if (m->is_method()) {
 452         MetadataFactory::free_metadata(this, (Method*)m);
 453       } else if (m->is_constantPool()) {
 454         MetadataFactory::free_metadata(this, (ConstantPool*)m);
 455       } else if (m->is_klass()) {
 456         MetadataFactory::free_metadata(this, (InstanceKlass*)m);
 457       } else {
 458         ShouldNotReachHere();
 459       }
 460     }
 461   }
 462 }
 463 
 464 // These anonymous class loaders are to contain classes used for JSR292
 465 ClassLoaderData* ClassLoaderData::anonymous_class_loader_data(oop loader, TRAPS) {
 466   // Add a new class loader data to the graph.
 467   return ClassLoaderDataGraph::add(loader, true, CHECK_NULL);
 468 }
 469 
 470 const char* ClassLoaderData::loader_name() {
 471   // Handles null class loader
 472   return SystemDictionary::loader_name(class_loader());
 473 }
 474 
 475 #ifndef PRODUCT
 476 // Define to dump klasses
 477 #undef CLD_DUMP_KLASSES
 478 
 479 void ClassLoaderData::dump(outputStream * const out) {
 480   ResourceMark rm;
 481   out->print("ClassLoaderData CLD: "PTR_FORMAT", loader: "PTR_FORMAT", loader_klass: "PTR_FORMAT" %s {",
 482       p2i(this), p2i((void *)class_loader()),
 483       p2i(class_loader() != NULL ? class_loader()->klass() : NULL), loader_name());
 484   if (claimed()) out->print(" claimed ");
 485   if (is_unloading()) out->print(" unloading ");
 486   out->print(" handles " INTPTR_FORMAT, p2i(handles()));
 487   out->cr();
 488   if (metaspace_or_null() != NULL) {
 489     out->print_cr("metaspace: " INTPTR_FORMAT, p2i(metaspace_or_null()));
 490     metaspace_or_null()->dump(out);
 491   } else {
 492     out->print_cr("metaspace: NULL");
 493   }
 494 
 495 #ifdef CLD_DUMP_KLASSES
 496   if (Verbose) {
 497     ResourceMark rm;
 498     Klass* k = _klasses;
 499     while (k != NULL) {
 500       out->print_cr("klass "PTR_FORMAT", %s, CT: %d, MUT: %d", k, k->name()->as_C_string(),
 501           k->has_modified_oops(), k->has_accumulated_modified_oops());
 502       assert(k != k->next_link(), "no loops!");
 503       k = k->next_link();
 504     }
 505   }
 506 #endif  // CLD_DUMP_KLASSES
 507 #undef CLD_DUMP_KLASSES
 508   if (_jmethod_ids != NULL) {
 509     Method::print_jmethod_ids(this, out);
 510   }
 511   out->print_cr("}");
 512 }
 513 #endif // PRODUCT
 514 
 515 void ClassLoaderData::verify() {
 516   oop cl = class_loader();
 517 
 518   guarantee(this == class_loader_data(cl) || is_anonymous(), "Must be the same");
 519   guarantee(cl != NULL || this == ClassLoaderData::the_null_class_loader_data() || is_anonymous(), "must be");
 520 
 521   // Verify the integrity of the allocated space.
 522   if (metaspace_or_null() != NULL) {
 523     metaspace_or_null()->verify();
 524   }
 525 
 526   for (Klass* k = _klasses; k != NULL; k = k->next_link()) {
 527     guarantee(k->class_loader_data() == this, "Must be the same");
 528     k->verify();
 529     assert(k != k->next_link(), "no loops!");
 530   }
 531 }
 532 
 533 bool ClassLoaderData::contains_klass(Klass* klass) {
 534   for (Klass* k = _klasses; k != NULL; k = k->next_link()) {
 535     if (k == klass) return true;
 536   }
 537   return false;
 538 }
 539 
 540 
 541 // GC root of class loader data created.
 542 ClassLoaderData* ClassLoaderDataGraph::_head = NULL;
 543 ClassLoaderData* ClassLoaderDataGraph::_unloading = NULL;
 544 ClassLoaderData* ClassLoaderDataGraph::_saved_unloading = NULL;
 545 ClassLoaderData* ClassLoaderDataGraph::_saved_head = NULL;
 546 
 547 bool ClassLoaderDataGraph::_should_purge = false;
 548 
 549 // Add a new class loader data node to the list.  Assign the newly created
 550 // ClassLoaderData into the java/lang/ClassLoader object as a hidden field
 551 ClassLoaderData* ClassLoaderDataGraph::add(Handle loader, bool is_anonymous, TRAPS) {
 552   // We need to allocate all the oops for the ClassLoaderData before allocating the
 553   // actual ClassLoaderData object.
 554   ClassLoaderData::Dependencies dependencies(CHECK_NULL);
 555 
 556   No_Safepoint_Verifier no_safepoints; // we mustn't GC until we've installed the
 557                                        // ClassLoaderData in the graph since the CLD
 558                                        // contains unhandled oops
 559 
 560   ClassLoaderData* cld = new ClassLoaderData(loader, is_anonymous, dependencies);
 561 
 562 
 563   if (!is_anonymous) {
 564     ClassLoaderData** cld_addr = java_lang_ClassLoader::loader_data_addr(loader());
 565     // First, Atomically set it
 566     ClassLoaderData* old = (ClassLoaderData*) Atomic::cmpxchg_ptr(cld, cld_addr, NULL);
 567     if (old != NULL) {
 568       delete cld;
 569       // Returns the data.
 570       return old;
 571     }
 572   }
 573 
 574   // We won the race, and therefore the task of adding the data to the list of
 575   // class loader data
 576   ClassLoaderData** list_head = &_head;
 577   ClassLoaderData* next = _head;
 578 
 579   do {
 580     cld->set_next(next);
 581     ClassLoaderData* exchanged = (ClassLoaderData*)Atomic::cmpxchg_ptr(cld, list_head, next);
 582     if (exchanged == next) {
 583       if (TraceClassLoaderData) {
 584         ResourceMark rm;
 585         tty->print("[ClassLoaderData: ");
 586         tty->print("create class loader data " INTPTR_FORMAT, p2i(cld));
 587         tty->print(" for instance " INTPTR_FORMAT " of %s", p2i((void *)cld->class_loader()),
 588                    cld->loader_name());
 589         tty->print_cr("]");
 590       }
 591       return cld;
 592     }
 593     next = exchanged;
 594   } while (true);
 595 
 596 }
 597 
 598 void ClassLoaderDataGraph::oops_do(OopClosure* f, KlassClosure* klass_closure, bool must_claim) {
 599   for (ClassLoaderData* cld = _head; cld != NULL; cld = cld->next()) {
 600     cld->oops_do(f, klass_closure, must_claim);
 601   }
 602 }
 603 
 604 void ClassLoaderDataGraph::keep_alive_oops_do(OopClosure* f, KlassClosure* klass_closure, bool must_claim) {
 605   for (ClassLoaderData* cld = _head; cld != NULL; cld = cld->next()) {
 606     if (cld->keep_alive()) {
 607       cld->oops_do(f, klass_closure, must_claim);
 608     }
 609   }
 610 }
 611 
 612 void ClassLoaderDataGraph::always_strong_oops_do(OopClosure* f, KlassClosure* klass_closure, bool must_claim) {
 613   if (ClassUnloading) {
 614     keep_alive_oops_do(f, klass_closure, must_claim);
 615   } else {
 616     oops_do(f, klass_closure, must_claim);
 617   }
 618 }
 619 
 620 void ClassLoaderDataGraph::cld_do(CLDClosure* cl) {
 621   for (ClassLoaderData* cld = _head; cl != NULL && cld != NULL; cld = cld->next()) {
 622     cl->do_cld(cld);
 623   }
 624 }
 625 
 626 void ClassLoaderDataGraph::roots_cld_do(CLDClosure* strong, CLDClosure* weak) {
 627   for (ClassLoaderData* cld = _head;  cld != NULL; cld = cld->_next) {
 628     CLDClosure* closure = cld->keep_alive() ? strong : weak;
 629     if (closure != NULL) {
 630       closure->do_cld(cld);
 631     }
 632   }
 633 }
 634 
 635 void ClassLoaderDataGraph::keep_alive_cld_do(CLDClosure* cl) {
 636   roots_cld_do(cl, NULL);
 637 }
 638 
 639 void ClassLoaderDataGraph::always_strong_cld_do(CLDClosure* cl) {
 640   if (ClassUnloading) {
 641     keep_alive_cld_do(cl);
 642   } else {
 643     cld_do(cl);
 644   }
 645 }
 646 
 647 void ClassLoaderDataGraph::classes_do(KlassClosure* klass_closure) {
 648   for (ClassLoaderData* cld = _head; cld != NULL; cld = cld->next()) {
 649     cld->classes_do(klass_closure);
 650   }
 651 }
 652 
 653 void ClassLoaderDataGraph::classes_do(void f(Klass* const)) {
 654   for (ClassLoaderData* cld = _head; cld != NULL; cld = cld->next()) {
 655     cld->classes_do(f);
 656   }
 657 }
 658 
 659 void ClassLoaderDataGraph::loaded_classes_do(KlassClosure* klass_closure) {
 660   for (ClassLoaderData* cld = _head; cld != NULL; cld = cld->next()) {
 661     cld->loaded_classes_do(klass_closure);
 662   }
 663 }
 664 
 665 void ClassLoaderDataGraph::classes_unloading_do(void f(Klass* const)) {
 666   assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint!");
 667   // Only walk the head until any clds not purged from prior unloading
 668   // (CMS doesn't purge right away).
 669   for (ClassLoaderData* cld = _unloading; cld != _saved_unloading; cld = cld->next()) {
 670     cld->classes_do(f);
 671   }
 672 }
 673 
 674 GrowableArray<ClassLoaderData*>* ClassLoaderDataGraph::new_clds() {
 675   assert(_head == NULL || _saved_head != NULL, "remember_new_clds(true) not called?");
 676 
 677   GrowableArray<ClassLoaderData*>* array = new GrowableArray<ClassLoaderData*>();
 678 
 679   // The CLDs in [_head, _saved_head] were all added during last call to remember_new_clds(true);
 680   ClassLoaderData* curr = _head;
 681   while (curr != _saved_head) {
 682     if (!curr->claimed()) {
 683       array->push(curr);
 684 
 685       if (TraceClassLoaderData) {
 686         tty->print("[ClassLoaderData] found new CLD: ");
 687         curr->print_value_on(tty);
 688         tty->cr();
 689       }
 690     }
 691 
 692     curr = curr->_next;
 693   }
 694 
 695   return array;
 696 }
 697 
 698 bool ClassLoaderDataGraph::unload_list_contains(const void* x) {
 699   assert(SafepointSynchronize::is_at_safepoint(), "only safe to call at safepoint");
 700   for (ClassLoaderData* cld = _unloading; cld != NULL; cld = cld->next()) {
 701     if (cld->metaspace_or_null() != NULL && cld->metaspace_or_null()->contains(x)) {
 702       return true;
 703     }
 704   }
 705   return false;
 706 }
 707 
 708 #ifndef PRODUCT
 709 bool ClassLoaderDataGraph::contains_loader_data(ClassLoaderData* loader_data) {
 710   for (ClassLoaderData* data = _head; data != NULL; data = data->next()) {
 711     if (loader_data == data) {
 712       return true;
 713     }
 714   }
 715 
 716   return false;
 717 }
 718 #endif // PRODUCT
 719 
 720 
 721 // Move class loader data from main list to the unloaded list for unloading
 722 // and deallocation later.
 723 bool ClassLoaderDataGraph::do_unloading(BoolObjectClosure* is_alive_closure, bool clean_alive) {
 724   ClassLoaderData* data = _head;
 725   ClassLoaderData* prev = NULL;
 726   bool seen_dead_loader = false;
 727 
 728   // Save previous _unloading pointer for CMS which may add to unloading list before
 729   // purging and we don't want to rewalk the previously unloaded class loader data.
 730   _saved_unloading = _unloading;
 731 
 732   while (data != NULL) {
 733     if (data->is_alive(is_alive_closure)) {
 734       prev = data;
 735       data = data->next();
 736       continue;
 737     }
 738     seen_dead_loader = true;
 739     ClassLoaderData* dead = data;
 740     dead->unload();
 741     data = data->next();
 742     // Remove from loader list.
 743     // This class loader data will no longer be found
 744     // in the ClassLoaderDataGraph.
 745     if (prev != NULL) {
 746       prev->set_next(data);
 747     } else {
 748       assert(dead == _head, "sanity check");
 749       _head = data;
 750     }
 751     dead->set_next(_unloading);
 752     _unloading = dead;
 753   }
 754 
 755   if (clean_alive) {
 756     // Clean previous versions and the deallocate list.
 757     ClassLoaderDataGraph::clean_metaspaces();
 758   }
 759 
 760   if (seen_dead_loader) {
 761     post_class_unload_events();
 762   }
 763 
 764   return seen_dead_loader;
 765 }
 766 
 767 void ClassLoaderDataGraph::clean_metaspaces() {
 768   // mark metadata seen on the stack and code cache so we can delete unneeded entries.
 769   bool has_redefined_a_class = JvmtiExport::has_redefined_a_class();
 770   MetadataOnStackMark md_on_stack(has_redefined_a_class);
 771 
 772   if (has_redefined_a_class) {
 773     // purge_previous_versions also cleans weak method links. Because
 774     // one method's MDO can reference another method from another
 775     // class loader, we need to first clean weak method links for all
 776     // class loaders here. Below, we can then free redefined methods
 777     // for all class loaders.
 778     for (ClassLoaderData* data = _head; data != NULL; data = data->next()) {
 779       data->classes_do(InstanceKlass::purge_previous_versions);
 780     }
 781   }
 782 
 783   // Need to purge the previous version before deallocating.
 784   free_deallocate_lists();
 785 }
 786 
 787 void ClassLoaderDataGraph::purge() {
 788   assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint!");
 789   ClassLoaderData* list = _unloading;
 790   _unloading = NULL;
 791   ClassLoaderData* next = list;
 792   while (next != NULL) {
 793     ClassLoaderData* purge_me = next;
 794     next = purge_me->next();
 795     delete purge_me;
 796   }
 797   Metaspace::purge();
 798 }
 799 
 800 void ClassLoaderDataGraph::post_class_unload_events(void) {
 801 #if INCLUDE_TRACE
 802   assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint!");
 803   if (Tracing::enabled()) {
 804     if (Tracing::is_event_enabled(TraceClassUnloadEvent)) {
 805       assert(_unloading != NULL, "need class loader data unload list!");
 806       _class_unload_time = Ticks::now();
 807       classes_unloading_do(&class_unload_event);
 808     }
 809     Tracing::on_unloading_classes();
 810   }
 811 #endif
 812 }
 813 
 814 void ClassLoaderDataGraph::free_deallocate_lists() {
 815   for (ClassLoaderData* cld = _head; cld != NULL; cld = cld->next()) {
 816     // We need to keep this data until InstanceKlass::purge_previous_version has been
 817     // called on all alive classes. See the comment in ClassLoaderDataGraph::clean_metaspaces.
 818     cld->free_deallocate_list();
 819   }
 820 }
 821 
 822 // CDS support
 823 
 824 // Global metaspaces for writing information to the shared archive.  When
 825 // application CDS is supported, we may need one per metaspace, so this
 826 // sort of looks like it.
 827 Metaspace* ClassLoaderData::_ro_metaspace = NULL;
 828 Metaspace* ClassLoaderData::_rw_metaspace = NULL;
 829 static bool _shared_metaspaces_initialized = false;
 830 
 831 // Initialize shared metaspaces (change to call from somewhere not lazily)
 832 void ClassLoaderData::initialize_shared_metaspaces() {
 833   assert(DumpSharedSpaces, "only use this for dumping shared spaces");
 834   assert(this == ClassLoaderData::the_null_class_loader_data(),
 835          "only supported for null loader data for now");
 836   assert (!_shared_metaspaces_initialized, "only initialize once");
 837   MutexLockerEx ml(metaspace_lock(),  Mutex::_no_safepoint_check_flag);
 838   _ro_metaspace = new Metaspace(_metaspace_lock, Metaspace::ROMetaspaceType);
 839   _rw_metaspace = new Metaspace(_metaspace_lock, Metaspace::ReadWriteMetaspaceType);
 840   _shared_metaspaces_initialized = true;
 841 }
 842 
 843 Metaspace* ClassLoaderData::ro_metaspace() {
 844   assert(_ro_metaspace != NULL, "should already be initialized");
 845   return _ro_metaspace;
 846 }
 847 
 848 Metaspace* ClassLoaderData::rw_metaspace() {
 849   assert(_rw_metaspace != NULL, "should already be initialized");
 850   return _rw_metaspace;
 851 }
 852 
 853 ClassLoaderDataGraphKlassIteratorAtomic::ClassLoaderDataGraphKlassIteratorAtomic()
 854     : _next_klass(NULL) {
 855   ClassLoaderData* cld = ClassLoaderDataGraph::_head;
 856   Klass* klass = NULL;
 857 
 858   // Find the first klass in the CLDG.
 859   while (cld != NULL) {
 860     klass = cld->_klasses;
 861     if (klass != NULL) {
 862       _next_klass = klass;
 863       return;
 864     }
 865     cld = cld->next();
 866   }
 867 }
 868 
 869 Klass* ClassLoaderDataGraphKlassIteratorAtomic::next_klass_in_cldg(Klass* klass) {
 870   Klass* next = klass->next_link();
 871   if (next != NULL) {
 872     return next;
 873   }
 874 
 875   // No more klasses in the current CLD. Time to find a new CLD.
 876   ClassLoaderData* cld = klass->class_loader_data();
 877   while (next == NULL) {
 878     cld = cld->next();
 879     if (cld == NULL) {
 880       break;
 881     }
 882     next = cld->_klasses;
 883   }
 884 
 885   return next;
 886 }
 887 
 888 Klass* ClassLoaderDataGraphKlassIteratorAtomic::next_klass() {
 889   Klass* head = _next_klass;
 890 
 891   while (head != NULL) {
 892     Klass* next = next_klass_in_cldg(head);
 893 
 894     Klass* old_head = (Klass*)Atomic::cmpxchg_ptr(next, &_next_klass, head);
 895 
 896     if (old_head == head) {
 897       return head; // Won the CAS.
 898     }
 899 
 900     head = old_head;
 901   }
 902 
 903   // Nothing more for the iterator to hand out.
 904   assert(head == NULL, err_msg("head is " PTR_FORMAT ", expected not null:", p2i(head)));
 905   return NULL;
 906 }
 907 
 908 ClassLoaderDataGraphMetaspaceIterator::ClassLoaderDataGraphMetaspaceIterator() {
 909   _data = ClassLoaderDataGraph::_head;
 910 }
 911 
 912 ClassLoaderDataGraphMetaspaceIterator::~ClassLoaderDataGraphMetaspaceIterator() {}
 913 
 914 #ifndef PRODUCT
 915 // callable from debugger
 916 extern "C" int print_loader_data_graph() {
 917   ClassLoaderDataGraph::dump_on(tty);
 918   return 0;
 919 }
 920 
 921 void ClassLoaderDataGraph::verify() {
 922   for (ClassLoaderData* data = _head; data != NULL; data = data->next()) {
 923     data->verify();
 924   }
 925 }
 926 
 927 void ClassLoaderDataGraph::dump_on(outputStream * const out) {
 928   for (ClassLoaderData* data = _head; data != NULL; data = data->next()) {
 929     data->dump(out);
 930   }
 931   MetaspaceAux::dump(out);
 932 }
 933 #endif // PRODUCT
 934 
 935 void ClassLoaderData::print_value_on(outputStream* out) const {
 936   if (class_loader() == NULL) {
 937     out->print("NULL class_loader");
 938   } else {
 939     out->print("class loader " INTPTR_FORMAT, p2i(this));
 940     class_loader()->print_value_on(out);
 941   }
 942 }
 943 
 944 #if INCLUDE_TRACE
 945 
 946 Ticks ClassLoaderDataGraph::_class_unload_time;
 947 
 948 void ClassLoaderDataGraph::class_unload_event(Klass* const k) {
 949 
 950   // post class unload event
 951   EventClassUnload event(UNTIMED);
 952   event.set_endtime(_class_unload_time);
 953   event.set_unloadedClass(k);
 954   oop defining_class_loader = k->class_loader();
 955   event.set_definingClassLoader(defining_class_loader != NULL ?
 956                                 defining_class_loader->klass() : (Klass*)NULL);
 957   event.commit();
 958 }
 959 
 960 #endif // INCLUDE_TRACE