1  /*
   2  * Copyright (c) 2012, 2017, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 // A ClassLoaderData identifies the full set of class types that a class
  26 // loader's name resolution strategy produces for a given configuration of the
  27 // class loader.
  28 // Class types in the ClassLoaderData may be defined by from class file binaries
  29 // provided by the class loader, or from other class loader it interacts with
  30 // according to its name resolution strategy.
  31 //
  32 // Class loaders that implement a deterministic name resolution strategy
  33 // (including with respect to their delegation behavior), such as the boot, the
  34 // platform, and the system loaders of the JDK's built-in class loader
  35 // hierarchy, always produce the same linkset for a given configuration.
  36 //
  37 // ClassLoaderData carries information related to a linkset (e.g.,
  38 // metaspace holding its klass definitions).
  39 // The System Dictionary and related data structures (e.g., placeholder table,
  40 // loader constraints table) as well as the runtime representation of classes
  41 // only reference ClassLoaderData.
  42 //
  43 // Instances of java.lang.ClassLoader holds a pointer to a ClassLoaderData that
  44 // that represent the loader's "linking domain" in the JVM.
  45 //
  46 // The bootstrap loader (represented by NULL) also has a ClassLoaderData,
  47 // the singleton class the_null_class_loader_data().
  48 
  49 #include "precompiled.hpp"
  50 #include "classfile/classLoaderData.hpp"
  51 #include "classfile/classLoaderData.inline.hpp"
  52 #include "classfile/dictionary.hpp"
  53 #include "classfile/javaClasses.hpp"
  54 #include "classfile/metadataOnStackMark.hpp"
  55 #include "classfile/moduleEntry.hpp"
  56 #include "classfile/packageEntry.hpp"
  57 #include "classfile/systemDictionary.hpp"
  58 #include "code/codeCache.hpp"
  59 #include "gc/shared/gcLocker.hpp"
  60 #include "logging/log.hpp"
  61 #include "logging/logStream.hpp"
  62 #include "memory/metadataFactory.hpp"
  63 #include "memory/metaspaceShared.hpp"
  64 #include "memory/oopFactory.hpp"
  65 #include "memory/resourceArea.hpp"
  66 #include "oops/access.inline.hpp"
  67 #include "oops/objArrayOop.inline.hpp"
  68 #include "oops/oop.inline.hpp"
  69 #include "runtime/atomic.hpp"
  70 #include "runtime/javaCalls.hpp"
  71 #include "runtime/jniHandles.hpp"
  72 #include "runtime/mutex.hpp"
  73 #include "runtime/orderAccess.hpp"
  74 #include "runtime/safepoint.hpp"
  75 #include "runtime/synchronizer.hpp"
  76 #include "utilities/growableArray.hpp"
  77 #include "utilities/macros.hpp"
  78 #include "utilities/ostream.hpp"
  79 #if INCLUDE_TRACE
  80 #include "trace/tracing.hpp"
  81 #endif
  82 
  83 ClassLoaderData * ClassLoaderData::_the_null_class_loader_data = NULL;
  84 
  85 ClassLoaderData::ClassLoaderData(Handle h_class_loader, bool is_anonymous, Dependencies dependencies) :
  86   _class_loader(h_class_loader()),
  87   _is_anonymous(is_anonymous),
  88   // An anonymous class loader data doesn't have anything to keep
  89   // it from being unloaded during parsing of the anonymous class.
  90   // The null-class-loader should always be kept alive.
  91   _keep_alive((is_anonymous || h_class_loader.is_null()) ? 1 : 0),
  92   _metaspace(NULL), _unloading(false), _klasses(NULL),
  93   _modules(NULL), _packages(NULL),
  94   _claimed(0), _modified_oops(true), _accumulated_modified_oops(false),
  95   _jmethod_ids(NULL), _handles(), _deallocate_list(NULL),
  96   _next(NULL), _dependencies(dependencies),
  97   _metaspace_lock(new Mutex(Monitor::leaf+1, "Metaspace allocation lock", true,
  98                             Monitor::_safepoint_check_never)) {
  99 
 100   // A ClassLoaderData created solely for an anonymous class should never have a
 101   // ModuleEntryTable or PackageEntryTable created for it. The defining package
 102   // and module for an anonymous class will be found in its host class.
 103   if (!is_anonymous) {
 104     _packages = new PackageEntryTable(PackageEntryTable::_packagetable_entry_size);
 105     if (h_class_loader.is_null()) {
 106       // Create unnamed module for boot loader
 107       _unnamed_module = ModuleEntry::create_boot_unnamed_module(this);
 108     } else {
 109       // Create unnamed module for all other loaders
 110       _unnamed_module = ModuleEntry::create_unnamed_module(this);
 111     }
 112   } else {
 113     _unnamed_module = NULL;
 114   }
 115 
 116   if (!is_anonymous) {
 117     _dictionary = create_dictionary();
 118   } else {
 119     _dictionary = NULL;
 120   }
 121   TRACE_INIT_ID(this);
 122 }
 123 
 124 void ClassLoaderData::init_dependencies(TRAPS) {
 125   assert(!Universe::is_fully_initialized(), "should only be called when initializing");
 126   assert(is_the_null_class_loader_data(), "should only call this for the null class loader");
 127   _dependencies.init(CHECK);
 128 }
 129 
 130 void ClassLoaderData::Dependencies::init(TRAPS) {
 131   // Create empty dependencies array to add to. CMS requires this to be
 132   // an oop so that it can track additions via card marks.  We think.
 133   _list_head = oopFactory::new_objectArray(2, CHECK);
 134 }
 135 
 136 ClassLoaderData::ChunkedHandleList::~ChunkedHandleList() {
 137   Chunk* c = _head;
 138   while (c != NULL) {
 139     Chunk* next = c->_next;
 140     delete c;
 141     c = next;
 142   }
 143 }
 144 
 145 oop* ClassLoaderData::ChunkedHandleList::add(oop o) {
 146   if (_head == NULL || _head->_size == Chunk::CAPACITY) {
 147     Chunk* next = new Chunk(_head);
 148     OrderAccess::release_store(&_head, next);
 149   }
 150   oop* handle = &_head->_data[_head->_size];
 151   *handle = o;
 152   OrderAccess::release_store(&_head->_size, _head->_size + 1);
 153   return handle;
 154 }
 155 
 156 inline void ClassLoaderData::ChunkedHandleList::oops_do_chunk(OopClosure* f, Chunk* c, const juint size) {
 157   for (juint i = 0; i < size; i++) {
 158     if (c->_data[i] != NULL) {
 159       f->do_oop(&c->_data[i]);
 160     }
 161   }
 162 }
 163 
 164 void ClassLoaderData::ChunkedHandleList::oops_do(OopClosure* f) {
 165   Chunk* head = OrderAccess::load_acquire(&_head);
 166   if (head != NULL) {
 167     // Must be careful when reading size of head
 168     oops_do_chunk(f, head, OrderAccess::load_acquire(&head->_size));
 169     for (Chunk* c = head->_next; c != NULL; c = c->_next) {
 170       oops_do_chunk(f, c, c->_size);
 171     }
 172   }
 173 }
 174 
 175 #ifdef ASSERT
 176 class VerifyContainsOopClosure : public OopClosure {
 177   oop* _target;
 178   bool _found;
 179 
 180  public:
 181   VerifyContainsOopClosure(oop* target) : _target(target), _found(false) {}
 182 
 183   void do_oop(oop* p) {
 184     if (p == _target) {
 185       _found = true;
 186     }
 187   }
 188 
 189   void do_oop(narrowOop* p) {
 190     // The ChunkedHandleList should not contain any narrowOop
 191     ShouldNotReachHere();
 192   }
 193 
 194   bool found() const {
 195     return _found;
 196   }
 197 };
 198 
 199 bool ClassLoaderData::ChunkedHandleList::contains(oop* p) {
 200   VerifyContainsOopClosure cl(p);
 201   oops_do(&cl);
 202   return cl.found();
 203 }
 204 #endif // ASSERT
 205 
 206 bool ClassLoaderData::claim() {
 207   if (_claimed == 1) {
 208     return false;
 209   }
 210 
 211   return (int) Atomic::cmpxchg(1, &_claimed, 0) == 0;
 212 }
 213 
 214 // Anonymous classes have their own ClassLoaderData that is marked to keep alive
 215 // while the class is being parsed, and if the class appears on the module fixup list.
 216 // Due to the uniqueness that no other class shares the anonymous class' name or
 217 // ClassLoaderData, no other non-GC thread has knowledge of the anonymous class while
 218 // it is being defined, therefore _keep_alive is not volatile or atomic.
 219 void ClassLoaderData::inc_keep_alive() {
 220   if (is_anonymous()) {
 221     assert(_keep_alive >= 0, "Invalid keep alive increment count");
 222     _keep_alive++;
 223   }
 224 }
 225 
 226 void ClassLoaderData::dec_keep_alive() {
 227   if (is_anonymous()) {
 228     assert(_keep_alive > 0, "Invalid keep alive decrement count");
 229     _keep_alive--;
 230   }
 231 }
 232 
 233 void ClassLoaderData::oops_do(OopClosure* f, bool must_claim, bool clear_mod_oops) {
 234   if (must_claim && !claim()) {
 235     return;
 236   }
 237 
 238   // Only clear modified_oops after the ClassLoaderData is claimed.
 239   if (clear_mod_oops) {
 240     clear_modified_oops();
 241   }
 242 
 243   f->do_oop(&_class_loader);
 244   _dependencies.oops_do(f);
 245   _handles.oops_do(f);
 246 }
 247 
 248 void ClassLoaderData::Dependencies::oops_do(OopClosure* f) {
 249   f->do_oop((oop*)&_list_head);
 250 }
 251 
 252 void ClassLoaderData::classes_do(KlassClosure* klass_closure) {
 253   // Lock-free access requires load_acquire
 254   for (Klass* k = OrderAccess::load_acquire(&_klasses); k != NULL; k = k->next_link()) {
 255     klass_closure->do_klass(k);
 256     assert(k != k->next_link(), "no loops!");
 257   }
 258 }
 259 
 260 void ClassLoaderData::classes_do(void f(Klass * const)) {
 261   // Lock-free access requires load_acquire
 262   for (Klass* k = OrderAccess::load_acquire(&_klasses); k != NULL; k = k->next_link()) {
 263     f(k);
 264     assert(k != k->next_link(), "no loops!");
 265   }
 266 }
 267 
 268 void ClassLoaderData::methods_do(void f(Method*)) {
 269   // Lock-free access requires load_acquire
 270   for (Klass* k = OrderAccess::load_acquire(&_klasses); k != NULL; k = k->next_link()) {
 271     if (k->is_instance_klass() && InstanceKlass::cast(k)->is_loaded()) {
 272       InstanceKlass::cast(k)->methods_do(f);
 273     }
 274   }
 275 }
 276 
 277 void ClassLoaderData::loaded_classes_do(KlassClosure* klass_closure) {
 278   // Lock-free access requires load_acquire
 279   for (Klass* k = OrderAccess::load_acquire(&_klasses); k != NULL; k = k->next_link()) {
 280     // Do not filter ArrayKlass oops here...
 281     if (k->is_array_klass() || (k->is_instance_klass() && InstanceKlass::cast(k)->is_loaded())) {
 282       klass_closure->do_klass(k);
 283     }
 284   }
 285 }
 286 
 287 void ClassLoaderData::classes_do(void f(InstanceKlass*)) {
 288   // Lock-free access requires load_acquire
 289   for (Klass* k = OrderAccess::load_acquire(&_klasses); k != NULL; k = k->next_link()) {
 290     if (k->is_instance_klass()) {
 291       f(InstanceKlass::cast(k));
 292     }
 293     assert(k != k->next_link(), "no loops!");
 294   }
 295 }
 296 
 297 void ClassLoaderData::modules_do(void f(ModuleEntry*)) {
 298   assert_locked_or_safepoint(Module_lock);
 299   if (_unnamed_module != NULL) {
 300     f(_unnamed_module);
 301   }
 302   if (_modules != NULL) {
 303     for (int i = 0; i < _modules->table_size(); i++) {
 304       for (ModuleEntry* entry = _modules->bucket(i);
 305            entry != NULL;
 306            entry = entry->next()) {
 307         f(entry);
 308       }
 309     }
 310   }
 311 }
 312 
 313 void ClassLoaderData::packages_do(void f(PackageEntry*)) {
 314   assert_locked_or_safepoint(Module_lock);
 315   if (_packages != NULL) {
 316     for (int i = 0; i < _packages->table_size(); i++) {
 317       for (PackageEntry* entry = _packages->bucket(i);
 318            entry != NULL;
 319            entry = entry->next()) {
 320         f(entry);
 321       }
 322     }
 323   }
 324 }
 325 
 326 void ClassLoaderData::record_dependency(const Klass* k, TRAPS) {
 327   assert(k != NULL, "invariant");
 328 
 329   ClassLoaderData * const from_cld = this;
 330   ClassLoaderData * const to_cld = k->class_loader_data();
 331 
 332   // Dependency to the null class loader data doesn't need to be recorded
 333   // because the null class loader data never goes away.
 334   if (to_cld->is_the_null_class_loader_data()) {
 335     return;
 336   }
 337 
 338   oop to;
 339   if (to_cld->is_anonymous()) {
 340     // Anonymous class dependencies are through the mirror.
 341     to = k->java_mirror();
 342   } else {
 343     to = to_cld->class_loader();
 344 
 345     // If from_cld is anonymous, even if it's class_loader is a parent of 'to'
 346     // we still have to add it.  The class_loader won't keep from_cld alive.
 347     if (!from_cld->is_anonymous()) {
 348       // Check that this dependency isn't from the same or parent class_loader
 349       oop from = from_cld->class_loader();
 350 
 351       oop curr = from;
 352       while (curr != NULL) {
 353         if (curr == to) {
 354           return; // this class loader is in the parent list, no need to add it.
 355         }
 356         curr = java_lang_ClassLoader::parent(curr);
 357       }
 358     }
 359   }
 360 
 361   // It's a dependency we won't find through GC, add it. This is relatively rare
 362   // Must handle over GC point.
 363   Handle dependency(THREAD, to);
 364   from_cld->_dependencies.add(dependency, CHECK);
 365 
 366   // Added a potentially young gen oop to the ClassLoaderData
 367   record_modified_oops();
 368 }
 369 
 370 
 371 void ClassLoaderData::Dependencies::add(Handle dependency, TRAPS) {
 372   // Check first if this dependency is already in the list.
 373   // Save a pointer to the last to add to under the lock.
 374   objArrayOop ok = _list_head;
 375   objArrayOop last = NULL;
 376   while (ok != NULL) {
 377     last = ok;
 378     if (ok->obj_at(0) == dependency()) {
 379       // Don't need to add it
 380       return;
 381     }
 382     ok = (objArrayOop)ok->obj_at(1);
 383   }
 384 
 385   // Must handle over GC points
 386   assert (last != NULL, "dependencies should be initialized");
 387   objArrayHandle last_handle(THREAD, last);
 388 
 389   // Create a new dependency node with fields for (class_loader or mirror, next)
 390   objArrayOop deps = oopFactory::new_objectArray(2, CHECK);
 391   deps->obj_at_put(0, dependency());
 392 
 393   // Must handle over GC points
 394   objArrayHandle new_dependency(THREAD, deps);
 395 
 396   // Add the dependency under lock
 397   locked_add(last_handle, new_dependency, THREAD);
 398 }
 399 
 400 void ClassLoaderData::Dependencies::locked_add(objArrayHandle last_handle,
 401                                                objArrayHandle new_dependency,
 402                                                Thread* THREAD) {
 403 
 404   // Have to lock and put the new dependency on the end of the dependency
 405   // array so the card mark for CMS sees that this dependency is new.
 406   // Can probably do this lock free with some effort.
 407   ObjectLocker ol(Handle(THREAD, _list_head), THREAD);
 408 
 409   oop loader_or_mirror = new_dependency->obj_at(0);
 410 
 411   // Since the dependencies are only added, add to the end.
 412   objArrayOop end = last_handle();
 413   objArrayOop last = NULL;
 414   while (end != NULL) {
 415     last = end;
 416     // check again if another thread added it to the end.
 417     if (end->obj_at(0) == loader_or_mirror) {
 418       // Don't need to add it
 419       return;
 420     }
 421     end = (objArrayOop)end->obj_at(1);
 422   }
 423   assert (last != NULL, "dependencies should be initialized");
 424   // fill in the first element with the oop in new_dependency.
 425   if (last->obj_at(0) == NULL) {
 426     last->obj_at_put(0, new_dependency->obj_at(0));
 427   } else {
 428     last->obj_at_put(1, new_dependency());
 429   }
 430 }
 431 
 432 void ClassLoaderDataGraph::clear_claimed_marks() {
 433   for (ClassLoaderData* cld = _head; cld != NULL; cld = cld->next()) {
 434     cld->clear_claimed();
 435   }
 436 }
 437 
 438 void ClassLoaderData::add_class(Klass* k, bool publicize /* true */) {
 439   {
 440     MutexLockerEx ml(metaspace_lock(), Mutex::_no_safepoint_check_flag);
 441     Klass* old_value = _klasses;
 442     k->set_next_link(old_value);
 443     // Link the new item into the list, making sure the linked class is stable
 444     // since the list can be walked without a lock
 445     OrderAccess::release_store(&_klasses, k);
 446   }
 447 
 448   if (publicize && k->class_loader_data() != NULL) {
 449     ResourceMark rm;
 450     log_trace(class, loader, data)("Adding k: " PTR_FORMAT " %s to CLD: "
 451                   PTR_FORMAT " loader: " PTR_FORMAT " %s",
 452                   p2i(k),
 453                   k->external_name(),
 454                   p2i(k->class_loader_data()),
 455                   p2i((void *)k->class_loader()),
 456                   loader_name());
 457   }
 458 }
 459 
 460 // Class iterator used by the compiler.  It gets some number of classes at
 461 // a safepoint to decay invocation counters on the methods.
 462 class ClassLoaderDataGraphKlassIteratorStatic {
 463   ClassLoaderData* _current_loader_data;
 464   Klass*           _current_class_entry;
 465  public:
 466 
 467   ClassLoaderDataGraphKlassIteratorStatic() : _current_loader_data(NULL), _current_class_entry(NULL) {}
 468 
 469   InstanceKlass* try_get_next_class() {
 470     assert(SafepointSynchronize::is_at_safepoint(), "only called at safepoint");
 471     int max_classes = InstanceKlass::number_of_instance_classes();
 472     assert(max_classes > 0, "should not be called with no instance classes");
 473     for (int i = 0; i < max_classes; ) {
 474 
 475       if (_current_class_entry != NULL) {
 476         Klass* k = _current_class_entry;
 477         _current_class_entry = _current_class_entry->next_link();
 478 
 479         if (k->is_instance_klass()) {
 480           InstanceKlass* ik = InstanceKlass::cast(k);
 481           i++;  // count all instance classes found
 482           // Not yet loaded classes are counted in max_classes
 483           // but only return loaded classes.
 484           if (ik->is_loaded()) {
 485             return ik;
 486           }
 487         }
 488       } else {
 489         // Go to next CLD
 490         if (_current_loader_data != NULL) {
 491           _current_loader_data = _current_loader_data->next();
 492         }
 493         // Start at the beginning
 494         if (_current_loader_data == NULL) {
 495           _current_loader_data = ClassLoaderDataGraph::_head;
 496         }
 497 
 498         _current_class_entry = _current_loader_data->klasses();
 499       }
 500     }
 501     // Should never be reached unless all instance classes have failed or are not fully loaded.
 502     // Caller handles NULL.
 503     return NULL;
 504   }
 505 
 506   // If the current class for the static iterator is a class being unloaded or
 507   // deallocated, adjust the current class.
 508   void adjust_saved_class(ClassLoaderData* cld) {
 509     if (_current_loader_data == cld) {
 510       _current_loader_data = cld->next();
 511       if (_current_loader_data != NULL) {
 512         _current_class_entry = _current_loader_data->klasses();
 513       }  // else try_get_next_class will start at the head
 514     }
 515   }
 516 
 517   void adjust_saved_class(Klass* klass) {
 518     if (_current_class_entry == klass) {
 519       _current_class_entry = klass->next_link();
 520     }
 521   }
 522 };
 523 
 524 static ClassLoaderDataGraphKlassIteratorStatic static_klass_iterator;
 525 
 526 InstanceKlass* ClassLoaderDataGraph::try_get_next_class() {
 527   return static_klass_iterator.try_get_next_class();
 528 }
 529 
 530 
 531 // Remove a klass from the _klasses list for scratch_class during redefinition
 532 // or parsed class in the case of an error.
 533 void ClassLoaderData::remove_class(Klass* scratch_class) {
 534   assert(SafepointSynchronize::is_at_safepoint(), "only called at safepoint");
 535 
 536   // Adjust global class iterator.
 537   static_klass_iterator.adjust_saved_class(scratch_class);
 538 
 539   Klass* prev = NULL;
 540   for (Klass* k = _klasses; k != NULL; k = k->next_link()) {
 541     if (k == scratch_class) {
 542       if (prev == NULL) {
 543         _klasses = k->next_link();
 544       } else {
 545         Klass* next = k->next_link();
 546         prev->set_next_link(next);
 547       }
 548       return;
 549     }
 550     prev = k;
 551     assert(k != k->next_link(), "no loops!");
 552   }
 553   ShouldNotReachHere();   // should have found this class!!
 554 }
 555 
 556 void ClassLoaderData::unload() {
 557   _unloading = true;
 558 
 559   // Tell serviceability tools these classes are unloading
 560   classes_do(InstanceKlass::notify_unload_class);
 561 
 562   LogTarget(Debug, class, loader, data) lt;
 563   if (lt.is_enabled()) {
 564     ResourceMark rm;
 565     LogStream ls(lt);
 566     ls.print(": unload loader data " INTPTR_FORMAT, p2i(this));
 567     ls.print(" for instance " INTPTR_FORMAT " of %s", p2i((void *)class_loader()),
 568                loader_name());
 569     if (is_anonymous()) {
 570       ls.print(" for anonymous class  " INTPTR_FORMAT " ", p2i(_klasses));
 571     }
 572     ls.cr();
 573   }
 574 
 575   // In some rare cases items added to this list will not be freed elsewhere.
 576   // To keep it simple, just free everything in it here.
 577   free_deallocate_list();
 578 
 579   // Clean up global class iterator for compiler
 580   static_klass_iterator.adjust_saved_class(this);
 581 }
 582 
 583 ModuleEntryTable* ClassLoaderData::modules() {
 584   // Lazily create the module entry table at first request.
 585   // Lock-free access requires load_acquire.
 586   ModuleEntryTable* modules = OrderAccess::load_acquire(&_modules);
 587   if (modules == NULL) {
 588     MutexLocker m1(Module_lock);
 589     // Check if _modules got allocated while we were waiting for this lock.
 590     if ((modules = _modules) == NULL) {
 591       modules = new ModuleEntryTable(ModuleEntryTable::_moduletable_entry_size);
 592 
 593       {
 594         MutexLockerEx m1(metaspace_lock(), Mutex::_no_safepoint_check_flag);
 595         // Ensure _modules is stable, since it is examined without a lock
 596         OrderAccess::release_store(&_modules, modules);
 597       }
 598     }
 599   }
 600   return modules;
 601 }
 602 
 603 const int _boot_loader_dictionary_size    = 1009;
 604 const int _default_loader_dictionary_size = 107;
 605 
 606 Dictionary* ClassLoaderData::create_dictionary() {
 607   assert(!is_anonymous(), "anonymous class loader data do not have a dictionary");
 608   int size;
 609   bool resizable = false;
 610   if (_the_null_class_loader_data == NULL) {
 611     size = _boot_loader_dictionary_size;
 612     resizable = true;
 613   } else if (class_loader()->is_a(SystemDictionary::reflect_DelegatingClassLoader_klass())) {
 614     size = 1;  // there's only one class in relection class loader and no initiated classes
 615   } else if (is_system_class_loader_data()) {
 616     size = _boot_loader_dictionary_size;
 617     resizable = true;
 618   } else {
 619     size = _default_loader_dictionary_size;
 620     resizable = true;
 621   }
 622   if (!DynamicallyResizeSystemDictionaries || DumpSharedSpaces || UseSharedSpaces) {
 623     resizable = false;
 624   }
 625   return new Dictionary(this, size, resizable);
 626 }
 627 
 628 // Unloading support
 629 oop ClassLoaderData::keep_alive_object() const {
 630   assert_locked_or_safepoint(_metaspace_lock);
 631   assert(!keep_alive(), "Don't use with CLDs that are artificially kept alive");
 632   return is_anonymous() ? _klasses->java_mirror() : class_loader();
 633 }
 634 
 635 bool ClassLoaderData::is_alive(BoolObjectClosure* is_alive_closure) const {
 636   bool alive = keep_alive() // null class loader and incomplete anonymous klasses.
 637       || is_alive_closure->do_object_b(keep_alive_object());
 638 
 639   return alive;
 640 }
 641 
 642 ClassLoaderData::~ClassLoaderData() {
 643   // Release C heap structures for all the classes.
 644   classes_do(InstanceKlass::release_C_heap_structures);
 645 
 646   // Release C heap allocated hashtable for all the packages.
 647   if (_packages != NULL) {
 648     // Destroy the table itself
 649     delete _packages;
 650     _packages = NULL;
 651   }
 652 
 653   // Release C heap allocated hashtable for all the modules.
 654   if (_modules != NULL) {
 655     // Destroy the table itself
 656     delete _modules;
 657     _modules = NULL;
 658   }
 659 
 660   // Release C heap allocated hashtable for the dictionary
 661   if (_dictionary != NULL) {
 662     // Destroy the table itself
 663     delete _dictionary;
 664     _dictionary = NULL;
 665   }
 666 
 667   if (_unnamed_module != NULL) {
 668     _unnamed_module->delete_unnamed_module();
 669     _unnamed_module = NULL;
 670   }
 671 
 672   // release the metaspace
 673   Metaspace *m = _metaspace;
 674   if (m != NULL) {
 675     _metaspace = NULL;
 676     delete m;
 677   }
 678   // Clear all the JNI handles for methods
 679   // These aren't deallocated and are going to look like a leak, but that's
 680   // needed because we can't really get rid of jmethodIDs because we don't
 681   // know when native code is going to stop using them.  The spec says that
 682   // they're "invalid" but existing programs likely rely on their being
 683   // NULL after class unloading.
 684   if (_jmethod_ids != NULL) {
 685     Method::clear_jmethod_ids(this);
 686   }
 687   // Delete lock
 688   delete _metaspace_lock;
 689 
 690   // Delete free list
 691   if (_deallocate_list != NULL) {
 692     delete _deallocate_list;
 693   }
 694 }
 695 
 696 // Returns true if this class loader data is for the system class loader.
 697 bool ClassLoaderData::is_system_class_loader_data() const {
 698   return SystemDictionary::is_system_class_loader(class_loader());
 699 }
 700 
 701 // Returns true if this class loader data is for the platform class loader.
 702 bool ClassLoaderData::is_platform_class_loader_data() const {
 703   return SystemDictionary::is_platform_class_loader(class_loader());
 704 }
 705 
 706 // Returns true if this class loader data is one of the 3 builtin
 707 // (boot, application/system or platform) class loaders. Note, the
 708 // builtin loaders are not freed by a GC.
 709 bool ClassLoaderData::is_builtin_class_loader_data() const {
 710   return (is_the_null_class_loader_data() ||
 711           SystemDictionary::is_system_class_loader(class_loader()) ||
 712           SystemDictionary::is_platform_class_loader(class_loader()));
 713 }
 714 
 715 Metaspace* ClassLoaderData::metaspace_non_null() {
 716   // If the metaspace has not been allocated, create a new one.  Might want
 717   // to create smaller arena for Reflection class loaders also.
 718   // The reason for the delayed allocation is because some class loaders are
 719   // simply for delegating with no metadata of their own.
 720   // Lock-free access requires load_acquire.
 721   Metaspace* metaspace = OrderAccess::load_acquire(&_metaspace);
 722   if (metaspace == NULL) {
 723     MutexLockerEx ml(_metaspace_lock,  Mutex::_no_safepoint_check_flag);
 724     // Check if _metaspace got allocated while we were waiting for this lock.
 725     if ((metaspace = _metaspace) == NULL) {
 726       if (this == the_null_class_loader_data()) {
 727         assert (class_loader() == NULL, "Must be");
 728         metaspace = new Metaspace(_metaspace_lock, Metaspace::BootMetaspaceType);
 729       } else if (is_anonymous()) {
 730         if (class_loader() != NULL) {
 731           log_trace(class, loader, data)("is_anonymous: %s", class_loader()->klass()->internal_name());
 732         }
 733         metaspace = new Metaspace(_metaspace_lock, Metaspace::AnonymousMetaspaceType);
 734       } else if (class_loader()->is_a(SystemDictionary::reflect_DelegatingClassLoader_klass())) {
 735         if (class_loader() != NULL) {
 736           log_trace(class, loader, data)("is_reflection: %s", class_loader()->klass()->internal_name());
 737         }
 738         metaspace = new Metaspace(_metaspace_lock, Metaspace::ReflectionMetaspaceType);
 739       } else {
 740         metaspace = new Metaspace(_metaspace_lock, Metaspace::StandardMetaspaceType);
 741       }
 742       // Ensure _metaspace is stable, since it is examined without a lock
 743       OrderAccess::release_store(&_metaspace, metaspace);
 744     }
 745   }
 746   return metaspace;
 747 }
 748 
 749 OopHandle ClassLoaderData::add_handle(Handle h) {
 750   MutexLockerEx ml(metaspace_lock(),  Mutex::_no_safepoint_check_flag);
 751   record_modified_oops();
 752   return OopHandle(_handles.add(h()));
 753 }
 754 
 755 void ClassLoaderData::remove_handle(OopHandle h) {
 756   oop* ptr = h.ptr_raw();
 757   if (ptr != NULL) {
 758     assert(_handles.contains(ptr), "Got unexpected handle " PTR_FORMAT, p2i(ptr));
 759     // This root is not walked in safepoints, and hence requires an appropriate
 760     // decorator that e.g. maintains the SATB invariant in SATB collectors.
 761     RootAccess<IN_CONCURRENT_ROOT>::oop_store(ptr, oop(NULL));
 762   }
 763 }
 764 
 765 void ClassLoaderData::init_handle_locked(OopHandle& dest, Handle h) {
 766   MutexLockerEx ml(metaspace_lock(),  Mutex::_no_safepoint_check_flag);
 767   if (dest.resolve() != NULL) {
 768     return;
 769   } else {
 770     dest = _handles.add(h());
 771   }
 772 }
 773 
 774 // Add this metadata pointer to be freed when it's safe.  This is only during
 775 // class unloading because Handles might point to this metadata field.
 776 void ClassLoaderData::add_to_deallocate_list(Metadata* m) {
 777   // Metadata in shared region isn't deleted.
 778   if (!m->is_shared()) {
 779     MutexLockerEx ml(metaspace_lock(),  Mutex::_no_safepoint_check_flag);
 780     if (_deallocate_list == NULL) {
 781       _deallocate_list = new (ResourceObj::C_HEAP, mtClass) GrowableArray<Metadata*>(100, true);
 782     }
 783     _deallocate_list->append_if_missing(m);
 784   }
 785 }
 786 
 787 // Deallocate free metadata on the free list.  How useful the PermGen was!
 788 void ClassLoaderData::free_deallocate_list() {
 789   // Don't need lock, at safepoint
 790   assert(SafepointSynchronize::is_at_safepoint(), "only called at safepoint");
 791   if (_deallocate_list == NULL) {
 792     return;
 793   }
 794   // Go backwards because this removes entries that are freed.
 795   for (int i = _deallocate_list->length() - 1; i >= 0; i--) {
 796     Metadata* m = _deallocate_list->at(i);
 797     if (!m->on_stack()) {
 798       _deallocate_list->remove_at(i);
 799       // There are only three types of metadata that we deallocate directly.
 800       // Cast them so they can be used by the template function.
 801       if (m->is_method()) {
 802         MetadataFactory::free_metadata(this, (Method*)m);
 803       } else if (m->is_constantPool()) {
 804         MetadataFactory::free_metadata(this, (ConstantPool*)m);
 805       } else if (m->is_klass()) {
 806         MetadataFactory::free_metadata(this, (InstanceKlass*)m);
 807       } else {
 808         ShouldNotReachHere();
 809       }
 810     } else {
 811       // Metadata is alive.
 812       // If scratch_class is on stack then it shouldn't be on this list!
 813       assert(!m->is_klass() || !((InstanceKlass*)m)->is_scratch_class(),
 814              "scratch classes on this list should be dead");
 815       // Also should assert that other metadata on the list was found in handles.
 816     }
 817   }
 818 }
 819 
 820 // These anonymous class loaders are to contain classes used for JSR292
 821 ClassLoaderData* ClassLoaderData::anonymous_class_loader_data(oop loader, TRAPS) {
 822   // Add a new class loader data to the graph.
 823   Handle lh(THREAD, loader);
 824   return ClassLoaderDataGraph::add(lh, true, THREAD);
 825 }
 826 
 827 const char* ClassLoaderData::loader_name() {
 828   // Handles null class loader
 829   return SystemDictionary::loader_name(class_loader());
 830 }
 831 
 832 #ifndef PRODUCT
 833 // Define to dump klasses
 834 #undef CLD_DUMP_KLASSES
 835 
 836 void ClassLoaderData::dump(outputStream * const out) {
 837   out->print("ClassLoaderData CLD: " PTR_FORMAT ", loader: " PTR_FORMAT ", loader_klass: " PTR_FORMAT " %s {",
 838       p2i(this), p2i((void *)class_loader()),
 839       p2i(class_loader() != NULL ? class_loader()->klass() : NULL), loader_name());
 840   if (claimed()) out->print(" claimed ");
 841   if (is_unloading()) out->print(" unloading ");
 842   out->cr();
 843   if (metaspace_or_null() != NULL) {
 844     out->print_cr("metaspace: " INTPTR_FORMAT, p2i(metaspace_or_null()));
 845     metaspace_or_null()->dump(out);
 846   } else {
 847     out->print_cr("metaspace: NULL");
 848   }
 849 
 850 #ifdef CLD_DUMP_KLASSES
 851   if (Verbose) {
 852     Klass* k = _klasses;
 853     while (k != NULL) {
 854       out->print_cr("klass " PTR_FORMAT ", %s", p2i(k), k->name()->as_C_string());
 855       assert(k != k->next_link(), "no loops!");
 856       k = k->next_link();
 857     }
 858   }
 859 #endif  // CLD_DUMP_KLASSES
 860 #undef CLD_DUMP_KLASSES
 861   if (_jmethod_ids != NULL) {
 862     Method::print_jmethod_ids(this, out);
 863   }
 864   out->print_cr("}");
 865 }
 866 #endif // PRODUCT
 867 
 868 void ClassLoaderData::verify() {
 869   assert_locked_or_safepoint(_metaspace_lock);
 870   oop cl = class_loader();
 871 
 872   guarantee(this == class_loader_data(cl) || is_anonymous(), "Must be the same");
 873   guarantee(cl != NULL || this == ClassLoaderData::the_null_class_loader_data() || is_anonymous(), "must be");
 874 
 875   // Verify the integrity of the allocated space.
 876   if (metaspace_or_null() != NULL) {
 877     metaspace_or_null()->verify();
 878   }
 879 
 880   for (Klass* k = _klasses; k != NULL; k = k->next_link()) {
 881     guarantee(k->class_loader_data() == this, "Must be the same");
 882     k->verify();
 883     assert(k != k->next_link(), "no loops!");
 884   }
 885 }
 886 
 887 bool ClassLoaderData::contains_klass(Klass* klass) {
 888   // Lock-free access requires load_acquire
 889   for (Klass* k = OrderAccess::load_acquire(&_klasses); k != NULL; k = k->next_link()) {
 890     if (k == klass) return true;
 891   }
 892   return false;
 893 }
 894 
 895 
 896 // GC root of class loader data created.
 897 ClassLoaderData* ClassLoaderDataGraph::_head = NULL;
 898 ClassLoaderData* ClassLoaderDataGraph::_unloading = NULL;
 899 ClassLoaderData* ClassLoaderDataGraph::_saved_unloading = NULL;
 900 ClassLoaderData* ClassLoaderDataGraph::_saved_head = NULL;
 901 
 902 bool ClassLoaderDataGraph::_should_purge = false;
 903 bool ClassLoaderDataGraph::_metaspace_oom = false;
 904 
 905 // Add a new class loader data node to the list.  Assign the newly created
 906 // ClassLoaderData into the java/lang/ClassLoader object as a hidden field
 907 ClassLoaderData* ClassLoaderDataGraph::add(Handle loader, bool is_anonymous, TRAPS) {
 908   // We need to allocate all the oops for the ClassLoaderData before allocating the
 909   // actual ClassLoaderData object.
 910   ClassLoaderData::Dependencies dependencies(CHECK_NULL);
 911 
 912   NoSafepointVerifier no_safepoints; // we mustn't GC until we've installed the
 913                                      // ClassLoaderData in the graph since the CLD
 914                                      // contains unhandled oops
 915 
 916   ClassLoaderData* cld = new ClassLoaderData(loader, is_anonymous, dependencies);
 917 
 918 
 919   if (!is_anonymous) {
 920     ClassLoaderData** cld_addr = java_lang_ClassLoader::loader_data_addr(loader());
 921     // First, Atomically set it
 922     ClassLoaderData* old = Atomic::cmpxchg(cld, cld_addr, (ClassLoaderData*)NULL);
 923     if (old != NULL) {
 924       delete cld;
 925       // Returns the data.
 926       return old;
 927     }
 928   }
 929 
 930   // We won the race, and therefore the task of adding the data to the list of
 931   // class loader data
 932   ClassLoaderData** list_head = &_head;
 933   ClassLoaderData* next = _head;
 934 
 935   do {
 936     cld->set_next(next);
 937     ClassLoaderData* exchanged = Atomic::cmpxchg(cld, list_head, next);
 938     if (exchanged == next) {
 939       LogTarget(Debug, class, loader, data) lt;
 940       if (lt.is_enabled()) {
 941        PauseNoSafepointVerifier pnsv(&no_safepoints); // Need safe points for JavaCalls::call_virtual
 942        LogStream ls(lt);
 943        print_creation(&ls, loader, cld, CHECK_NULL);
 944       }
 945       return cld;
 946     }
 947     next = exchanged;
 948   } while (true);
 949 }
 950 
 951 void ClassLoaderDataGraph::print_creation(outputStream* out, Handle loader, ClassLoaderData* cld, TRAPS) {
 952   Handle string;
 953   if (loader.not_null()) {
 954     // Include the result of loader.toString() in the output. This allows
 955     // the user of the log to identify the class loader instance.
 956     JavaValue result(T_OBJECT);
 957     Klass* spec_klass = SystemDictionary::ClassLoader_klass();
 958     JavaCalls::call_virtual(&result,
 959                             loader,
 960                             spec_klass,
 961                             vmSymbols::toString_name(),
 962                             vmSymbols::void_string_signature(),
 963                             CHECK);
 964     assert(result.get_type() == T_OBJECT, "just checking");
 965     string = Handle(THREAD, (oop)result.get_jobject());
 966   }
 967 
 968   ResourceMark rm;
 969   out->print("create class loader data " INTPTR_FORMAT, p2i(cld));
 970   out->print(" for instance " INTPTR_FORMAT " of %s", p2i((void *)cld->class_loader()),
 971              cld->loader_name());
 972 
 973   if (string.not_null()) {
 974     out->print(": ");
 975     java_lang_String::print(string(), out);
 976   }
 977   out->cr();
 978 }
 979 
 980 
 981 void ClassLoaderDataGraph::oops_do(OopClosure* f, bool must_claim) {
 982   for (ClassLoaderData* cld = _head; cld != NULL; cld = cld->next()) {
 983     cld->oops_do(f, must_claim);
 984   }
 985 }
 986 
 987 void ClassLoaderDataGraph::keep_alive_oops_do(OopClosure* f, bool must_claim) {
 988   for (ClassLoaderData* cld = _head; cld != NULL; cld = cld->next()) {
 989     if (cld->keep_alive()) {
 990       cld->oops_do(f, must_claim);
 991     }
 992   }
 993 }
 994 
 995 void ClassLoaderDataGraph::always_strong_oops_do(OopClosure* f, bool must_claim) {
 996   if (ClassUnloading) {
 997     keep_alive_oops_do(f, must_claim);
 998   } else {
 999     oops_do(f, must_claim);
1000   }
1001 }
1002 
1003 void ClassLoaderDataGraph::cld_do(CLDClosure* cl) {
1004   for (ClassLoaderData* cld = _head; cl != NULL && cld != NULL; cld = cld->next()) {
1005     cl->do_cld(cld);
1006   }
1007 }
1008 
1009 void ClassLoaderDataGraph::cld_unloading_do(CLDClosure* cl) {
1010   assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint!");
1011   // Only walk the head until any clds not purged from prior unloading
1012   // (CMS doesn't purge right away).
1013   for (ClassLoaderData* cld = _unloading; cld != _saved_unloading; cld = cld->next()) {
1014     assert(cld->is_unloading(), "invariant");
1015     cl->do_cld(cld);
1016   }
1017 }
1018 
1019 void ClassLoaderDataGraph::roots_cld_do(CLDClosure* strong, CLDClosure* weak) {
1020   for (ClassLoaderData* cld = _head;  cld != NULL; cld = cld->_next) {
1021     CLDClosure* closure = cld->keep_alive() ? strong : weak;
1022     if (closure != NULL) {
1023       closure->do_cld(cld);
1024     }
1025   }
1026 }
1027 
1028 void ClassLoaderDataGraph::keep_alive_cld_do(CLDClosure* cl) {
1029   roots_cld_do(cl, NULL);
1030 }
1031 
1032 void ClassLoaderDataGraph::always_strong_cld_do(CLDClosure* cl) {
1033   if (ClassUnloading) {
1034     keep_alive_cld_do(cl);
1035   } else {
1036     cld_do(cl);
1037   }
1038 }
1039 
1040 void ClassLoaderDataGraph::classes_do(KlassClosure* klass_closure) {
1041   for (ClassLoaderData* cld = _head; cld != NULL; cld = cld->next()) {
1042     cld->classes_do(klass_closure);
1043   }
1044 }
1045 
1046 void ClassLoaderDataGraph::classes_do(void f(Klass* const)) {
1047   for (ClassLoaderData* cld = _head; cld != NULL; cld = cld->next()) {
1048     cld->classes_do(f);
1049   }
1050 }
1051 
1052 void ClassLoaderDataGraph::methods_do(void f(Method*)) {
1053   for (ClassLoaderData* cld = _head; cld != NULL; cld = cld->next()) {
1054     cld->methods_do(f);
1055   }
1056 }
1057 
1058 void ClassLoaderDataGraph::modules_do(void f(ModuleEntry*)) {
1059   assert_locked_or_safepoint(Module_lock);
1060   for (ClassLoaderData* cld = _head; cld != NULL; cld = cld->next()) {
1061     cld->modules_do(f);
1062   }
1063 }
1064 
1065 void ClassLoaderDataGraph::modules_unloading_do(void f(ModuleEntry*)) {
1066   assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint!");
1067   // Only walk the head until any clds not purged from prior unloading
1068   // (CMS doesn't purge right away).
1069   for (ClassLoaderData* cld = _unloading; cld != _saved_unloading; cld = cld->next()) {
1070     assert(cld->is_unloading(), "invariant");
1071     cld->modules_do(f);
1072   }
1073 }
1074 
1075 void ClassLoaderDataGraph::packages_do(void f(PackageEntry*)) {
1076   assert_locked_or_safepoint(Module_lock);
1077   for (ClassLoaderData* cld = _head; cld != NULL; cld = cld->next()) {
1078     cld->packages_do(f);
1079   }
1080 }
1081 
1082 void ClassLoaderDataGraph::packages_unloading_do(void f(PackageEntry*)) {
1083   assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint!");
1084   // Only walk the head until any clds not purged from prior unloading
1085   // (CMS doesn't purge right away).
1086   for (ClassLoaderData* cld = _unloading; cld != _saved_unloading; cld = cld->next()) {
1087     assert(cld->is_unloading(), "invariant");
1088     cld->packages_do(f);
1089   }
1090 }
1091 
1092 void ClassLoaderDataGraph::loaded_classes_do(KlassClosure* klass_closure) {
1093   for (ClassLoaderData* cld = _head; cld != NULL; cld = cld->next()) {
1094     cld->loaded_classes_do(klass_closure);
1095   }
1096 }
1097 
1098 void ClassLoaderDataGraph::classes_unloading_do(void f(Klass* const)) {
1099   assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint!");
1100   // Only walk the head until any clds not purged from prior unloading
1101   // (CMS doesn't purge right away).
1102   for (ClassLoaderData* cld = _unloading; cld != _saved_unloading; cld = cld->next()) {
1103     assert(cld->is_unloading(), "invariant");
1104     cld->classes_do(f);
1105   }
1106 }
1107 
1108 #define FOR_ALL_DICTIONARY(X) for (ClassLoaderData* X = _head; X != NULL; X = X->next()) \
1109                                 if (X->dictionary() != NULL)
1110 
1111 // Walk classes in the loaded class dictionaries in various forms.
1112 // Only walks the classes defined in this class loader.
1113 void ClassLoaderDataGraph::dictionary_classes_do(void f(InstanceKlass*)) {
1114   FOR_ALL_DICTIONARY(cld) {
1115     cld->dictionary()->classes_do(f);
1116   }
1117 }
1118 
1119 // Only walks the classes defined in this class loader.
1120 void ClassLoaderDataGraph::dictionary_classes_do(void f(InstanceKlass*, TRAPS), TRAPS) {
1121   FOR_ALL_DICTIONARY(cld) {
1122     cld->dictionary()->classes_do(f, CHECK);
1123   }
1124 }
1125 
1126 // Walks all entries in the dictionary including entries initiated by this class loader.
1127 void ClassLoaderDataGraph::dictionary_all_entries_do(void f(InstanceKlass*, ClassLoaderData*)) {
1128   FOR_ALL_DICTIONARY(cld) {
1129     cld->dictionary()->all_entries_do(f);
1130   }
1131 }
1132 
1133 void ClassLoaderDataGraph::verify_dictionary() {
1134   FOR_ALL_DICTIONARY(cld) {
1135     cld->dictionary()->verify();
1136   }
1137 }
1138 
1139 void ClassLoaderDataGraph::print_dictionary(outputStream* st) {
1140   FOR_ALL_DICTIONARY(cld) {
1141     st->print("Dictionary for ");
1142     cld->print_value_on(st);
1143     st->cr();
1144     cld->dictionary()->print_on(st);
1145     st->cr();
1146   }
1147 }
1148 
1149 void ClassLoaderDataGraph::print_dictionary_statistics(outputStream* st) {
1150   FOR_ALL_DICTIONARY(cld) {
1151     ResourceMark rm;
1152     stringStream tempst;
1153     tempst.print("System Dictionary for %s", cld->loader_name());
1154     cld->dictionary()->print_table_statistics(st, tempst.as_string());
1155   }
1156 }
1157 
1158 GrowableArray<ClassLoaderData*>* ClassLoaderDataGraph::new_clds() {
1159   assert(_head == NULL || _saved_head != NULL, "remember_new_clds(true) not called?");
1160 
1161   GrowableArray<ClassLoaderData*>* array = new GrowableArray<ClassLoaderData*>();
1162 
1163   // The CLDs in [_head, _saved_head] were all added during last call to remember_new_clds(true);
1164   ClassLoaderData* curr = _head;
1165   while (curr != _saved_head) {
1166     if (!curr->claimed()) {
1167       array->push(curr);
1168       LogTarget(Debug, class, loader, data) lt;
1169       if (lt.is_enabled()) {
1170         LogStream ls(lt);
1171         ls.print("found new CLD: ");
1172         curr->print_value_on(&ls);
1173         ls.cr();
1174       }
1175     }
1176 
1177     curr = curr->_next;
1178   }
1179 
1180   return array;
1181 }
1182 
1183 bool ClassLoaderDataGraph::unload_list_contains(const void* x) {
1184   assert(SafepointSynchronize::is_at_safepoint(), "only safe to call at safepoint");
1185   for (ClassLoaderData* cld = _unloading; cld != NULL; cld = cld->next()) {
1186     if (cld->metaspace_or_null() != NULL && cld->metaspace_or_null()->contains(x)) {
1187       return true;
1188     }
1189   }
1190   return false;
1191 }
1192 
1193 #ifndef PRODUCT
1194 bool ClassLoaderDataGraph::contains_loader_data(ClassLoaderData* loader_data) {
1195   for (ClassLoaderData* data = _head; data != NULL; data = data->next()) {
1196     if (loader_data == data) {
1197       return true;
1198     }
1199   }
1200 
1201   return false;
1202 }
1203 #endif // PRODUCT
1204 
1205 
1206 // Move class loader data from main list to the unloaded list for unloading
1207 // and deallocation later.
1208 bool ClassLoaderDataGraph::do_unloading(BoolObjectClosure* is_alive_closure,
1209                                         bool clean_previous_versions) {
1210 
1211   ClassLoaderData* data = _head;
1212   ClassLoaderData* prev = NULL;
1213   bool seen_dead_loader = false;
1214 
1215   // Mark metadata seen on the stack only so we can delete unneeded entries.
1216   // Only walk all metadata, including the expensive code cache walk, for Full GC
1217   // and only if class redefinition and if there's previous versions of
1218   // Klasses to delete.
1219   bool walk_all_metadata = clean_previous_versions &&
1220                            JvmtiExport::has_redefined_a_class() &&
1221                            InstanceKlass::has_previous_versions_and_reset();
1222   MetadataOnStackMark md_on_stack(walk_all_metadata);
1223 
1224   // Save previous _unloading pointer for CMS which may add to unloading list before
1225   // purging and we don't want to rewalk the previously unloaded class loader data.
1226   _saved_unloading = _unloading;
1227 
1228   data = _head;
1229   while (data != NULL) {
1230     if (data->is_alive(is_alive_closure)) {
1231       // clean metaspace
1232       if (walk_all_metadata) {
1233         data->classes_do(InstanceKlass::purge_previous_versions);
1234       }
1235       data->free_deallocate_list();
1236       prev = data;
1237       data = data->next();
1238       continue;
1239     }
1240     seen_dead_loader = true;
1241     ClassLoaderData* dead = data;
1242     dead->unload();
1243     data = data->next();
1244     // Remove from loader list.
1245     // This class loader data will no longer be found
1246     // in the ClassLoaderDataGraph.
1247     if (prev != NULL) {
1248       prev->set_next(data);
1249     } else {
1250       assert(dead == _head, "sanity check");
1251       _head = data;
1252     }
1253     dead->set_next(_unloading);
1254     _unloading = dead;
1255   }
1256 
1257   if (seen_dead_loader) {
1258     data = _head;
1259     while (data != NULL) {
1260       // Remove entries in the dictionary of live class loader that have
1261       // initiated loading classes in a dead class loader.
1262       if (data->dictionary() != NULL) {
1263         data->dictionary()->do_unloading();
1264       }
1265       // Walk a ModuleEntry's reads, and a PackageEntry's exports
1266       // lists to determine if there are modules on those lists that are now
1267       // dead and should be removed.  A module's life cycle is equivalent
1268       // to its defining class loader's life cycle.  Since a module is
1269       // considered dead if its class loader is dead, these walks must
1270       // occur after each class loader's aliveness is determined.
1271       if (data->packages() != NULL) {
1272         data->packages()->purge_all_package_exports();
1273       }
1274       if (data->modules_defined()) {
1275         data->modules()->purge_all_module_reads();
1276       }
1277       data = data->next();
1278     }
1279 
1280     post_class_unload_events();
1281   }
1282 
1283   return seen_dead_loader;
1284 }
1285 
1286 void ClassLoaderDataGraph::purge() {
1287   assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint!");
1288   ClassLoaderData* list = _unloading;
1289   _unloading = NULL;
1290   ClassLoaderData* next = list;
1291   bool classes_unloaded = false;
1292   while (next != NULL) {
1293     ClassLoaderData* purge_me = next;
1294     next = purge_me->next();
1295     delete purge_me;
1296     classes_unloaded = true;
1297   }
1298   if (classes_unloaded) {
1299     Metaspace::purge();
1300     set_metaspace_oom(false);
1301   }
1302 }
1303 
1304 int ClassLoaderDataGraph::resize_if_needed() {
1305   assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint!");
1306   int resized = 0;
1307   if (Dictionary::does_any_dictionary_needs_resizing()) {
1308     FOR_ALL_DICTIONARY(cld) {
1309       if (cld->dictionary()->resize_if_needed()) {
1310         resized++;
1311       }
1312     }
1313   }
1314   return resized;
1315 }
1316 
1317 void ClassLoaderDataGraph::post_class_unload_events() {
1318 #if INCLUDE_TRACE
1319   assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint!");
1320   if (Tracing::enabled()) {
1321     if (Tracing::is_event_enabled(TraceClassUnloadEvent)) {
1322       assert(_unloading != NULL, "need class loader data unload list!");
1323       _class_unload_time = Ticks::now();
1324       classes_unloading_do(&class_unload_event);
1325     }
1326     Tracing::on_unloading_classes();
1327   }
1328 #endif
1329 }
1330 
1331 ClassLoaderDataGraphKlassIteratorAtomic::ClassLoaderDataGraphKlassIteratorAtomic()
1332     : _next_klass(NULL) {
1333   ClassLoaderData* cld = ClassLoaderDataGraph::_head;
1334   Klass* klass = NULL;
1335 
1336   // Find the first klass in the CLDG.
1337   while (cld != NULL) {
1338     assert_locked_or_safepoint(cld->metaspace_lock());
1339     klass = cld->_klasses;
1340     if (klass != NULL) {
1341       _next_klass = klass;
1342       return;
1343     }
1344     cld = cld->next();
1345   }
1346 }
1347 
1348 Klass* ClassLoaderDataGraphKlassIteratorAtomic::next_klass_in_cldg(Klass* klass) {
1349   Klass* next = klass->next_link();
1350   if (next != NULL) {
1351     return next;
1352   }
1353 
1354   // No more klasses in the current CLD. Time to find a new CLD.
1355   ClassLoaderData* cld = klass->class_loader_data();
1356   assert_locked_or_safepoint(cld->metaspace_lock());
1357   while (next == NULL) {
1358     cld = cld->next();
1359     if (cld == NULL) {
1360       break;
1361     }
1362     next = cld->_klasses;
1363   }
1364 
1365   return next;
1366 }
1367 
1368 Klass* ClassLoaderDataGraphKlassIteratorAtomic::next_klass() {
1369   Klass* head = _next_klass;
1370 
1371   while (head != NULL) {
1372     Klass* next = next_klass_in_cldg(head);
1373 
1374     Klass* old_head = Atomic::cmpxchg(next, &_next_klass, head);
1375 
1376     if (old_head == head) {
1377       return head; // Won the CAS.
1378     }
1379 
1380     head = old_head;
1381   }
1382 
1383   // Nothing more for the iterator to hand out.
1384   assert(head == NULL, "head is " PTR_FORMAT ", expected not null:", p2i(head));
1385   return NULL;
1386 }
1387 
1388 ClassLoaderDataGraphMetaspaceIterator::ClassLoaderDataGraphMetaspaceIterator() {
1389   _data = ClassLoaderDataGraph::_head;
1390 }
1391 
1392 ClassLoaderDataGraphMetaspaceIterator::~ClassLoaderDataGraphMetaspaceIterator() {}
1393 
1394 #ifndef PRODUCT
1395 // callable from debugger
1396 extern "C" int print_loader_data_graph() {
1397   ClassLoaderDataGraph::dump_on(tty);
1398   return 0;
1399 }
1400 
1401 void ClassLoaderDataGraph::verify() {
1402   for (ClassLoaderData* data = _head; data != NULL; data = data->next()) {
1403     data->verify();
1404   }
1405 }
1406 
1407 void ClassLoaderDataGraph::dump_on(outputStream * const out) {
1408   for (ClassLoaderData* data = _head; data != NULL; data = data->next()) {
1409     data->dump(out);
1410   }
1411   MetaspaceAux::dump(out);
1412 }
1413 #endif // PRODUCT
1414 
1415 void ClassLoaderData::print_value_on(outputStream* out) const {
1416   if (class_loader() == NULL) {
1417     out->print("NULL class loader");
1418   } else {
1419     out->print("class loader " INTPTR_FORMAT " ", p2i(this));
1420     class_loader()->print_value_on(out);
1421   }
1422 }
1423 
1424 void ClassLoaderData::print_on(outputStream* out) const {
1425   if (class_loader() == NULL) {
1426     out->print("NULL class loader");
1427   } else {
1428     out->print("class loader " INTPTR_FORMAT " ", p2i(this));
1429     class_loader()->print_on(out);
1430   }
1431 }
1432 
1433 #if INCLUDE_TRACE
1434 
1435 Ticks ClassLoaderDataGraph::_class_unload_time;
1436 
1437 void ClassLoaderDataGraph::class_unload_event(Klass* const k) {
1438   assert(k != NULL, "invariant");
1439 
1440   // post class unload event
1441   EventClassUnload event(UNTIMED);
1442   event.set_endtime(_class_unload_time);
1443   event.set_unloadedClass(k);
1444   event.set_definingClassLoader(k->class_loader_data());
1445   event.commit();
1446 }
1447 
1448 #endif // INCLUDE_TRACE