1  /*
   2  * Copyright (c) 2012, 2018, 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/symbolTable.hpp"
  58 #include "classfile/systemDictionary.hpp"
  59 #include "logging/log.hpp"
  60 #include "logging/logStream.hpp"
  61 #include "memory/allocation.inline.hpp"
  62 #include "memory/metadataFactory.hpp"
  63 #include "memory/metaspaceShared.hpp"
  64 #include "memory/resourceArea.hpp"
  65 #include "memory/universe.hpp"
  66 #include "oops/access.inline.hpp"
  67 #include "oops/oop.inline.hpp"
  68 #include "oops/oopHandle.inline.hpp"
  69 #include "oops/weakHandle.inline.hpp"
  70 #include "runtime/atomic.hpp"
  71 #include "runtime/handles.inline.hpp"
  72 #include "runtime/mutex.hpp"
  73 #include "runtime/orderAccess.hpp"
  74 #include "runtime/safepoint.hpp"
  75 #include "runtime/safepointVerifiers.hpp"
  76 #include "utilities/growableArray.hpp"
  77 #include "utilities/macros.hpp"
  78 #include "utilities/ostream.hpp"
  79 
  80 volatile size_t ClassLoaderDataGraph::_num_array_classes = 0;
  81 volatile size_t ClassLoaderDataGraph::_num_instance_classes = 0;
  82 
  83 ClassLoaderData * ClassLoaderData::_the_null_class_loader_data = NULL;
  84 
  85 void ClassLoaderData::init_null_class_loader_data() {
  86   assert(_the_null_class_loader_data == NULL, "cannot initialize twice");
  87   assert(ClassLoaderDataGraph::_head == NULL, "cannot initialize twice");
  88 
  89   _the_null_class_loader_data = new ClassLoaderData(Handle(), false);
  90   ClassLoaderDataGraph::_head = _the_null_class_loader_data;
  91   assert(_the_null_class_loader_data->is_the_null_class_loader_data(), "Must be");
  92 
  93   LogTarget(Trace, class, loader, data) lt;
  94   if (lt.is_enabled()) {
  95     ResourceMark rm;
  96     LogStream ls(lt);
  97     ls.print("create ");
  98     _the_null_class_loader_data->print_value_on(&ls);
  99     ls.cr();
 100   }
 101 }
 102 
 103 // Obtain and set the class loader's name within the ClassLoaderData so
 104 // it will be available for error messages, logging, JFR, etc.  The name
 105 // and klass are available after the class_loader oop is no longer alive,
 106 // during unloading.
 107 void ClassLoaderData::initialize_name(Handle class_loader) {
 108   Thread* THREAD = Thread::current();
 109   ResourceMark rm(THREAD);
 110 
 111   // Obtain the class loader's name.  If the class loader's name was not
 112   // explicitly set during construction, the CLD's _name field will be null.
 113   oop cl_name = java_lang_ClassLoader::name(class_loader());
 114   if (cl_name != NULL) {
 115     const char* cl_instance_name = java_lang_String::as_utf8_string(cl_name);
 116 
 117     if (cl_instance_name != NULL && cl_instance_name[0] != '\0') {
 118       // Can't throw InternalError and SymbolTable doesn't throw OOM anymore.
 119       _name = SymbolTable::new_symbol(cl_instance_name, CATCH);
 120     }
 121   }
 122 
 123   // Obtain the class loader's name and identity hash.  If the class loader's
 124   // name was not explicitly set during construction, the class loader's name and id
 125   // will be set to the qualified class name of the class loader along with its
 126   // identity hash.
 127   // If for some reason the ClassLoader's constructor has not been run, instead of
 128   // leaving the _name_and_id field null, fall back to the external qualified class
 129   // name.  Thus CLD's _name_and_id field should never have a null value.
 130   oop cl_name_and_id = java_lang_ClassLoader::nameAndId(class_loader());
 131   const char* cl_instance_name_and_id =
 132                   (cl_name_and_id == NULL) ? _class_loader_klass->external_name() :
 133                                              java_lang_String::as_utf8_string(cl_name_and_id);
 134   assert(cl_instance_name_and_id != NULL && cl_instance_name_and_id[0] != '\0', "class loader has no name and id");
 135   // Can't throw InternalError and SymbolTable doesn't throw OOM anymore.
 136   _name_and_id = SymbolTable::new_symbol(cl_instance_name_and_id, CATCH);
 137 }
 138 
 139 ClassLoaderData::ClassLoaderData(Handle h_class_loader, bool is_unsafe_anonymous) :
 140   _metaspace(NULL),
 141   _metaspace_lock(new Mutex(Monitor::leaf+1, "Metaspace allocation lock", true,
 142                             Monitor::_safepoint_check_never)),
 143   _unloading(false), _is_unsafe_anonymous(is_unsafe_anonymous),
 144   _modified_oops(true), _accumulated_modified_oops(false),
 145   // An unsafe anonymous class loader data doesn't have anything to keep
 146   // it from being unloaded during parsing of the unsafe anonymous class.
 147   // The null-class-loader should always be kept alive.
 148   _keep_alive((is_unsafe_anonymous || h_class_loader.is_null()) ? 1 : 0),
 149   _claimed(0),
 150   _handles(),
 151   _klasses(NULL), _packages(NULL), _modules(NULL), _unnamed_module(NULL), _dictionary(NULL),
 152   _jmethod_ids(NULL),
 153   _deallocate_list(NULL),
 154   _next(NULL),
 155   _class_loader_klass(NULL), _name(NULL), _name_and_id(NULL) {
 156 
 157   if (!h_class_loader.is_null()) {
 158     _class_loader = _handles.add(h_class_loader());
 159     _class_loader_klass = h_class_loader->klass();
 160   }
 161 
 162   if (!is_unsafe_anonymous) {
 163     // The holder is initialized later for unsafe anonymous classes, and before calling anything
 164     // that call class_loader().
 165     initialize_holder(h_class_loader);
 166 
 167     // A ClassLoaderData created solely for an unsafe anonymous class should never have a
 168     // ModuleEntryTable or PackageEntryTable created for it. The defining package
 169     // and module for an unsafe anonymous class will be found in its host class.
 170     _packages = new PackageEntryTable(PackageEntryTable::_packagetable_entry_size);
 171     if (h_class_loader.is_null()) {
 172       // Create unnamed module for boot loader
 173       _unnamed_module = ModuleEntry::create_boot_unnamed_module(this);
 174     } else {
 175       // Create unnamed module for all other loaders
 176       _unnamed_module = ModuleEntry::create_unnamed_module(this);
 177     }
 178     _dictionary = create_dictionary();
 179   }
 180 
 181   NOT_PRODUCT(_dependency_count = 0); // number of class loader dependencies
 182 
 183   JFR_ONLY(INIT_ID(this);)
 184 }
 185 
 186 ClassLoaderData::ChunkedHandleList::~ChunkedHandleList() {
 187   Chunk* c = _head;
 188   while (c != NULL) {
 189     Chunk* next = c->_next;
 190     delete c;
 191     c = next;
 192   }
 193 }
 194 
 195 oop* ClassLoaderData::ChunkedHandleList::add(oop o) {
 196   if (_head == NULL || _head->_size == Chunk::CAPACITY) {
 197     Chunk* next = new Chunk(_head);
 198     OrderAccess::release_store(&_head, next);
 199   }
 200   oop* handle = &_head->_data[_head->_size];
 201   *handle = o;
 202   OrderAccess::release_store(&_head->_size, _head->_size + 1);
 203   return handle;
 204 }
 205 
 206 int ClassLoaderData::ChunkedHandleList::count() const {
 207   int count = 0;
 208   Chunk* chunk = _head;
 209   while (chunk != NULL) {
 210     count += chunk->_size;
 211     chunk = chunk->_next;
 212   }
 213   return count;
 214 }
 215 
 216 inline void ClassLoaderData::ChunkedHandleList::oops_do_chunk(OopClosure* f, Chunk* c, const juint size) {
 217   for (juint i = 0; i < size; i++) {
 218     if (c->_data[i] != NULL) {
 219       f->do_oop(&c->_data[i]);
 220     }
 221   }
 222 }
 223 
 224 void ClassLoaderData::ChunkedHandleList::oops_do(OopClosure* f) {
 225   Chunk* head = OrderAccess::load_acquire(&_head);
 226   if (head != NULL) {
 227     // Must be careful when reading size of head
 228     oops_do_chunk(f, head, OrderAccess::load_acquire(&head->_size));
 229     for (Chunk* c = head->_next; c != NULL; c = c->_next) {
 230       oops_do_chunk(f, c, c->_size);
 231     }
 232   }
 233 }
 234 
 235 class VerifyContainsOopClosure : public OopClosure {
 236   oop  _target;
 237   bool _found;
 238 
 239  public:
 240   VerifyContainsOopClosure(oop target) : _target(target), _found(false) {}
 241 
 242   void do_oop(oop* p) {
 243     if (p != NULL && oopDesc::equals(RawAccess<>::oop_load(p), _target)) {
 244       _found = true;
 245     }
 246   }
 247 
 248   void do_oop(narrowOop* p) {
 249     // The ChunkedHandleList should not contain any narrowOop
 250     ShouldNotReachHere();
 251   }
 252 
 253   bool found() const {
 254     return _found;
 255   }
 256 };
 257 
 258 bool ClassLoaderData::ChunkedHandleList::contains(oop p) {
 259   VerifyContainsOopClosure cl(p);
 260   oops_do(&cl);
 261   return cl.found();
 262 }
 263 
 264 #ifndef PRODUCT
 265 bool ClassLoaderData::ChunkedHandleList::owner_of(oop* oop_handle) {
 266   Chunk* chunk = _head;
 267   while (chunk != NULL) {
 268     if (&(chunk->_data[0]) <= oop_handle && oop_handle < &(chunk->_data[chunk->_size])) {
 269       return true;
 270     }
 271     chunk = chunk->_next;
 272   }
 273   return false;
 274 }
 275 #endif // PRODUCT
 276 
 277 bool ClassLoaderData::claim() {
 278   if (_claimed == 1) {
 279     return false;
 280   }
 281 
 282   return (int) Atomic::cmpxchg(1, &_claimed, 0) == 0;
 283 }
 284 
 285 // Unsafe anonymous classes have their own ClassLoaderData that is marked to keep alive
 286 // while the class is being parsed, and if the class appears on the module fixup list.
 287 // Due to the uniqueness that no other class shares the unsafe anonymous class' name or
 288 // ClassLoaderData, no other non-GC thread has knowledge of the unsafe anonymous class while
 289 // it is being defined, therefore _keep_alive is not volatile or atomic.
 290 void ClassLoaderData::inc_keep_alive() {
 291   if (is_unsafe_anonymous()) {
 292     assert(_keep_alive >= 0, "Invalid keep alive increment count");
 293     _keep_alive++;
 294   }
 295 }
 296 
 297 void ClassLoaderData::dec_keep_alive() {
 298   if (is_unsafe_anonymous()) {
 299     assert(_keep_alive > 0, "Invalid keep alive decrement count");
 300     _keep_alive--;
 301   }
 302 }
 303 
 304 void ClassLoaderData::oops_do(OopClosure* f, bool must_claim, bool clear_mod_oops) {
 305   if (must_claim && !claim()) {
 306     return;
 307   }
 308 
 309   // Only clear modified_oops after the ClassLoaderData is claimed.
 310   if (clear_mod_oops) {
 311     clear_modified_oops();
 312   }
 313 
 314   _handles.oops_do(f);
 315 }
 316 
 317 void ClassLoaderData::classes_do(KlassClosure* klass_closure) {
 318   // Lock-free access requires load_acquire
 319   for (Klass* k = OrderAccess::load_acquire(&_klasses); k != NULL; k = k->next_link()) {
 320     klass_closure->do_klass(k);
 321     assert(k != k->next_link(), "no loops!");
 322   }
 323 }
 324 
 325 void ClassLoaderData::classes_do(void f(Klass * const)) {
 326   // Lock-free access requires load_acquire
 327   for (Klass* k = OrderAccess::load_acquire(&_klasses); k != NULL; k = k->next_link()) {
 328     f(k);
 329     assert(k != k->next_link(), "no loops!");
 330   }
 331 }
 332 
 333 void ClassLoaderData::methods_do(void f(Method*)) {
 334   // Lock-free access requires load_acquire
 335   for (Klass* k = OrderAccess::load_acquire(&_klasses); k != NULL; k = k->next_link()) {
 336     if (k->is_instance_klass() && InstanceKlass::cast(k)->is_loaded()) {
 337       InstanceKlass::cast(k)->methods_do(f);
 338     }
 339   }
 340 }
 341 
 342 void ClassLoaderData::loaded_classes_do(KlassClosure* klass_closure) {
 343   // Lock-free access requires load_acquire
 344   for (Klass* k = OrderAccess::load_acquire(&_klasses); k != NULL; k = k->next_link()) {
 345     // Do not filter ArrayKlass oops here...
 346     if (k->is_array_klass() || (k->is_instance_klass() && InstanceKlass::cast(k)->is_loaded())) {
 347       klass_closure->do_klass(k);
 348     }
 349   }
 350 }
 351 
 352 void ClassLoaderData::classes_do(void f(InstanceKlass*)) {
 353   // Lock-free access requires load_acquire
 354   for (Klass* k = OrderAccess::load_acquire(&_klasses); k != NULL; k = k->next_link()) {
 355     if (k->is_instance_klass()) {
 356       f(InstanceKlass::cast(k));
 357     }
 358     assert(k != k->next_link(), "no loops!");
 359   }
 360 }
 361 
 362 void ClassLoaderData::modules_do(void f(ModuleEntry*)) {
 363   assert_locked_or_safepoint(Module_lock);
 364   if (_unnamed_module != NULL) {
 365     f(_unnamed_module);
 366   }
 367   if (_modules != NULL) {
 368     for (int i = 0; i < _modules->table_size(); i++) {
 369       for (ModuleEntry* entry = _modules->bucket(i);
 370            entry != NULL;
 371            entry = entry->next()) {
 372         f(entry);
 373       }
 374     }
 375   }
 376 }
 377 
 378 void ClassLoaderData::packages_do(void f(PackageEntry*)) {
 379   assert_locked_or_safepoint(Module_lock);
 380   if (_packages != NULL) {
 381     for (int i = 0; i < _packages->table_size(); i++) {
 382       for (PackageEntry* entry = _packages->bucket(i);
 383            entry != NULL;
 384            entry = entry->next()) {
 385         f(entry);
 386       }
 387     }
 388   }
 389 }
 390 
 391 void ClassLoaderData::record_dependency(const Klass* k) {
 392   assert(k != NULL, "invariant");
 393 
 394   ClassLoaderData * const from_cld = this;
 395   ClassLoaderData * const to_cld = k->class_loader_data();
 396 
 397   // Do not need to record dependency if the dependency is to a class whose
 398   // class loader data is never freed.  (i.e. the dependency's class loader
 399   // is one of the three builtin class loaders and the dependency is not
 400   // unsafe anonymous.)
 401   if (to_cld->is_permanent_class_loader_data()) {
 402     return;
 403   }
 404 
 405   oop to;
 406   if (to_cld->is_unsafe_anonymous()) {
 407     // Just return if an unsafe anonymous class is attempting to record a dependency
 408     // to itself.  (Note that every unsafe anonymous class has its own unique class
 409     // loader data.)
 410     if (to_cld == from_cld) {
 411       return;
 412     }
 413     // Unsafe anonymous class dependencies are through the mirror.
 414     to = k->java_mirror();
 415   } else {
 416     to = to_cld->class_loader();
 417     oop from = from_cld->class_loader();
 418 
 419     // Just return if this dependency is to a class with the same or a parent
 420     // class_loader.
 421     if (oopDesc::equals(from, to) || java_lang_ClassLoader::isAncestor(from, to)) {
 422       return; // this class loader is in the parent list, no need to add it.
 423     }
 424   }
 425 
 426   // It's a dependency we won't find through GC, add it.
 427   if (!_handles.contains(to)) {
 428     NOT_PRODUCT(Atomic::inc(&_dependency_count));
 429     LogTarget(Trace, class, loader, data) lt;
 430     if (lt.is_enabled()) {
 431       ResourceMark rm;
 432       LogStream ls(lt);
 433       ls.print("adding dependency from ");
 434       print_value_on(&ls);
 435       ls.print(" to ");
 436       to_cld->print_value_on(&ls);
 437       ls.cr();
 438     }
 439     Handle dependency(Thread::current(), to);
 440     add_handle(dependency);
 441     // Added a potentially young gen oop to the ClassLoaderData
 442     record_modified_oops();
 443   }
 444 }
 445 
 446 
 447 void ClassLoaderDataGraph::clear_claimed_marks() {
 448   for (ClassLoaderData* cld = _head; cld != NULL; cld = cld->next()) {
 449     cld->clear_claimed();
 450   }
 451 }
 452 
 453 void ClassLoaderData::add_class(Klass* k, bool publicize /* true */) {
 454   {
 455     MutexLockerEx ml(metaspace_lock(), Mutex::_no_safepoint_check_flag);
 456     Klass* old_value = _klasses;
 457     k->set_next_link(old_value);
 458     // Link the new item into the list, making sure the linked class is stable
 459     // since the list can be walked without a lock
 460     OrderAccess::release_store(&_klasses, k);
 461     if (k->is_array_klass()) {
 462       ClassLoaderDataGraph::inc_array_classes(1);
 463     } else {
 464       ClassLoaderDataGraph::inc_instance_classes(1);
 465     }
 466   }
 467 
 468   if (publicize) {
 469     LogTarget(Trace, class, loader, data) lt;
 470     if (lt.is_enabled()) {
 471       ResourceMark rm;
 472       LogStream ls(lt);
 473       ls.print("Adding k: " PTR_FORMAT " %s to ", p2i(k), k->external_name());
 474       print_value_on(&ls);
 475       ls.cr();
 476     }
 477   }
 478 }
 479 
 480 // Class iterator used by the compiler.  It gets some number of classes at
 481 // a safepoint to decay invocation counters on the methods.
 482 class ClassLoaderDataGraphKlassIteratorStatic {
 483   ClassLoaderData* _current_loader_data;
 484   Klass*           _current_class_entry;
 485  public:
 486 
 487   ClassLoaderDataGraphKlassIteratorStatic() : _current_loader_data(NULL), _current_class_entry(NULL) {}
 488 
 489   InstanceKlass* try_get_next_class() {
 490     assert(SafepointSynchronize::is_at_safepoint(), "only called at safepoint");
 491     size_t max_classes = ClassLoaderDataGraph::num_instance_classes();
 492     assert(max_classes > 0, "should not be called with no instance classes");
 493     for (size_t i = 0; i < max_classes; ) {
 494 
 495       if (_current_class_entry != NULL) {
 496         Klass* k = _current_class_entry;
 497         _current_class_entry = _current_class_entry->next_link();
 498 
 499         if (k->is_instance_klass()) {
 500           InstanceKlass* ik = InstanceKlass::cast(k);
 501           i++;  // count all instance classes found
 502           // Not yet loaded classes are counted in max_classes
 503           // but only return loaded classes.
 504           if (ik->is_loaded()) {
 505             return ik;
 506           }
 507         }
 508       } else {
 509         // Go to next CLD
 510         if (_current_loader_data != NULL) {
 511           _current_loader_data = _current_loader_data->next();
 512         }
 513         // Start at the beginning
 514         if (_current_loader_data == NULL) {
 515           _current_loader_data = ClassLoaderDataGraph::_head;
 516         }
 517 
 518         _current_class_entry = _current_loader_data->klasses();
 519       }
 520     }
 521     // Should never be reached unless all instance classes have failed or are not fully loaded.
 522     // Caller handles NULL.
 523     return NULL;
 524   }
 525 
 526   // If the current class for the static iterator is a class being unloaded or
 527   // deallocated, adjust the current class.
 528   void adjust_saved_class(ClassLoaderData* cld) {
 529     if (_current_loader_data == cld) {
 530       _current_loader_data = cld->next();
 531       if (_current_loader_data != NULL) {
 532         _current_class_entry = _current_loader_data->klasses();
 533       }  // else try_get_next_class will start at the head
 534     }
 535   }
 536 
 537   void adjust_saved_class(Klass* klass) {
 538     if (_current_class_entry == klass) {
 539       _current_class_entry = klass->next_link();
 540     }
 541   }
 542 };
 543 
 544 static ClassLoaderDataGraphKlassIteratorStatic static_klass_iterator;
 545 
 546 InstanceKlass* ClassLoaderDataGraph::try_get_next_class() {
 547   assert(SafepointSynchronize::is_at_safepoint(), "only called at safepoint");
 548   return static_klass_iterator.try_get_next_class();
 549 }
 550 
 551 
 552 void ClassLoaderData::initialize_holder(Handle loader_or_mirror) {
 553   if (loader_or_mirror() != NULL) {
 554     assert(_holder.is_null(), "never replace holders");
 555     _holder = WeakHandle<vm_class_loader_data>::create(loader_or_mirror);
 556   }
 557 }
 558 
 559 // Remove a klass from the _klasses list for scratch_class during redefinition
 560 // or parsed class in the case of an error.
 561 void ClassLoaderData::remove_class(Klass* scratch_class) {
 562   assert(SafepointSynchronize::is_at_safepoint(), "only called at safepoint");
 563 
 564   // Adjust global class iterator.
 565   static_klass_iterator.adjust_saved_class(scratch_class);
 566 
 567   Klass* prev = NULL;
 568   for (Klass* k = _klasses; k != NULL; k = k->next_link()) {
 569     if (k == scratch_class) {
 570       if (prev == NULL) {
 571         _klasses = k->next_link();
 572       } else {
 573         Klass* next = k->next_link();
 574         prev->set_next_link(next);
 575       }
 576 
 577       if (k->is_array_klass()) {
 578         ClassLoaderDataGraph::dec_array_classes(1);
 579       } else {
 580         ClassLoaderDataGraph::dec_instance_classes(1);
 581       }
 582 
 583       return;
 584     }
 585     prev = k;
 586     assert(k != k->next_link(), "no loops!");
 587   }
 588   ShouldNotReachHere();   // should have found this class!!
 589 }
 590 
 591 void ClassLoaderData::unload() {
 592   _unloading = true;
 593 
 594   LogTarget(Trace, class, loader, data) lt;
 595   if (lt.is_enabled()) {
 596     ResourceMark rm;
 597     LogStream ls(lt);
 598     ls.print("unload");
 599     print_value_on(&ls);
 600     ls.cr();
 601   }
 602 
 603   // Some items on the _deallocate_list need to free their C heap structures
 604   // if they are not already on the _klasses list.
 605   free_deallocate_list_C_heap_structures();
 606 
 607   // Tell serviceability tools these classes are unloading
 608   // after erroneous classes are released.
 609   classes_do(InstanceKlass::notify_unload_class);
 610 
 611   // Clean up global class iterator for compiler
 612   static_klass_iterator.adjust_saved_class(this);
 613 }
 614 
 615 ModuleEntryTable* ClassLoaderData::modules() {
 616   // Lazily create the module entry table at first request.
 617   // Lock-free access requires load_acquire.
 618   ModuleEntryTable* modules = OrderAccess::load_acquire(&_modules);
 619   if (modules == NULL) {
 620     MutexLocker m1(Module_lock);
 621     // Check if _modules got allocated while we were waiting for this lock.
 622     if ((modules = _modules) == NULL) {
 623       modules = new ModuleEntryTable(ModuleEntryTable::_moduletable_entry_size);
 624 
 625       {
 626         MutexLockerEx m1(metaspace_lock(), Mutex::_no_safepoint_check_flag);
 627         // Ensure _modules is stable, since it is examined without a lock
 628         OrderAccess::release_store(&_modules, modules);
 629       }
 630     }
 631   }
 632   return modules;
 633 }
 634 
 635 const int _boot_loader_dictionary_size    = 1009;
 636 const int _default_loader_dictionary_size = 107;
 637 
 638 Dictionary* ClassLoaderData::create_dictionary() {
 639   assert(!is_unsafe_anonymous(), "unsafe anonymous class loader data do not have a dictionary");
 640   int size;
 641   bool resizable = false;
 642   if (_the_null_class_loader_data == NULL) {
 643     size = _boot_loader_dictionary_size;
 644     resizable = true;
 645   } else if (class_loader()->is_a(SystemDictionary::reflect_DelegatingClassLoader_klass())) {
 646     size = 1;  // there's only one class in relection class loader and no initiated classes
 647   } else if (is_system_class_loader_data()) {
 648     size = _boot_loader_dictionary_size;
 649     resizable = true;
 650   } else {
 651     size = _default_loader_dictionary_size;
 652     resizable = true;
 653   }
 654   if (!DynamicallyResizeSystemDictionaries || DumpSharedSpaces) {
 655     resizable = false;
 656   }
 657   return new Dictionary(this, size, resizable);
 658 }
 659 
 660 // Tell the GC to keep this klass alive while iterating ClassLoaderDataGraph
 661 oop ClassLoaderData::holder_phantom() const {
 662   // A klass that was previously considered dead can be looked up in the
 663   // CLD/SD, and its _java_mirror or _class_loader can be stored in a root
 664   // or a reachable object making it alive again. The SATB part of G1 needs
 665   // to get notified about this potential resurrection, otherwise the marking
 666   // might not find the object.
 667   if (!_holder.is_null()) {  // NULL class_loader
 668     return _holder.resolve();
 669   } else {
 670     return NULL;
 671   }
 672 }
 673 
 674 // Let the GC read the holder without keeping it alive.
 675 oop ClassLoaderData::holder_no_keepalive() const {
 676   if (!_holder.is_null()) {  // NULL class_loader
 677     return _holder.peek();
 678   } else {
 679     return NULL;
 680   }
 681 }
 682 
 683 // Unloading support
 684 bool ClassLoaderData::is_alive() const {
 685   bool alive = keep_alive()         // null class loader and incomplete unsafe anonymous klasses.
 686       || (_holder.peek() != NULL);  // and not cleaned by the GC weak handle processing.
 687 
 688   return alive;
 689 }
 690 
 691 class ReleaseKlassClosure: public KlassClosure {
 692 private:
 693   size_t  _instance_class_released;
 694   size_t  _array_class_released;
 695 public:
 696   ReleaseKlassClosure() : _instance_class_released(0), _array_class_released(0) { }
 697 
 698   size_t instance_class_released() const { return _instance_class_released; }
 699   size_t array_class_released()    const { return _array_class_released;    }
 700 
 701   void do_klass(Klass* k) {
 702     if (k->is_array_klass()) {
 703       _array_class_released ++;
 704     } else {
 705       assert(k->is_instance_klass(), "Must be");
 706       _instance_class_released ++;
 707       InstanceKlass::release_C_heap_structures(InstanceKlass::cast(k));
 708     }
 709   }
 710 };
 711 
 712 ClassLoaderData::~ClassLoaderData() {
 713   // Release C heap structures for all the classes.
 714   ReleaseKlassClosure cl;
 715   classes_do(&cl);
 716 
 717   ClassLoaderDataGraph::dec_array_classes(cl.array_class_released());
 718   ClassLoaderDataGraph::dec_instance_classes(cl.instance_class_released());
 719 
 720   // Release the WeakHandle
 721   _holder.release();
 722 
 723   // Release C heap allocated hashtable for all the packages.
 724   if (_packages != NULL) {
 725     // Destroy the table itself
 726     delete _packages;
 727     _packages = NULL;
 728   }
 729 
 730   // Release C heap allocated hashtable for all the modules.
 731   if (_modules != NULL) {
 732     // Destroy the table itself
 733     delete _modules;
 734     _modules = NULL;
 735   }
 736 
 737   // Release C heap allocated hashtable for the dictionary
 738   if (_dictionary != NULL) {
 739     // Destroy the table itself
 740     delete _dictionary;
 741     _dictionary = NULL;
 742   }
 743 
 744   if (_unnamed_module != NULL) {
 745     _unnamed_module->delete_unnamed_module();
 746     _unnamed_module = NULL;
 747   }
 748 
 749   // release the metaspace
 750   ClassLoaderMetaspace *m = _metaspace;
 751   if (m != NULL) {
 752     _metaspace = NULL;
 753     delete m;
 754   }
 755   // Clear all the JNI handles for methods
 756   // These aren't deallocated and are going to look like a leak, but that's
 757   // needed because we can't really get rid of jmethodIDs because we don't
 758   // know when native code is going to stop using them.  The spec says that
 759   // they're "invalid" but existing programs likely rely on their being
 760   // NULL after class unloading.
 761   if (_jmethod_ids != NULL) {
 762     Method::clear_jmethod_ids(this);
 763   }
 764   // Delete lock
 765   delete _metaspace_lock;
 766 
 767   // Delete free list
 768   if (_deallocate_list != NULL) {
 769     delete _deallocate_list;
 770   }
 771 }
 772 
 773 // Returns true if this class loader data is for the app class loader
 774 // or a user defined system class loader.  (Note that the class loader
 775 // data may be unsafe anonymous.)
 776 bool ClassLoaderData::is_system_class_loader_data() const {
 777   return SystemDictionary::is_system_class_loader(class_loader());
 778 }
 779 
 780 // Returns true if this class loader data is for the platform class loader.
 781 // (Note that the class loader data may be unsafe anonymous.)
 782 bool ClassLoaderData::is_platform_class_loader_data() const {
 783   return SystemDictionary::is_platform_class_loader(class_loader());
 784 }
 785 
 786 // Returns true if the class loader for this class loader data is one of
 787 // the 3 builtin (boot application/system or platform) class loaders,
 788 // including a user-defined system class loader.  Note that if the class
 789 // loader data is for an unsafe anonymous class then it may get freed by a GC
 790 // even if its class loader is one of these loaders.
 791 bool ClassLoaderData::is_builtin_class_loader_data() const {
 792   return (is_boot_class_loader_data() ||
 793           SystemDictionary::is_system_class_loader(class_loader()) ||
 794           SystemDictionary::is_platform_class_loader(class_loader()));
 795 }
 796 
 797 // Returns true if this class loader data is a class loader data
 798 // that is not ever freed by a GC.  It must be the CLD for one of the builtin
 799 // class loaders and not the CLD for an unsafe anonymous class.
 800 bool ClassLoaderData::is_permanent_class_loader_data() const {
 801   return is_builtin_class_loader_data() && !is_unsafe_anonymous();
 802 }
 803 
 804 ClassLoaderMetaspace* ClassLoaderData::metaspace_non_null() {
 805   // If the metaspace has not been allocated, create a new one.  Might want
 806   // to create smaller arena for Reflection class loaders also.
 807   // The reason for the delayed allocation is because some class loaders are
 808   // simply for delegating with no metadata of their own.
 809   // Lock-free access requires load_acquire.
 810   ClassLoaderMetaspace* metaspace = OrderAccess::load_acquire(&_metaspace);
 811   if (metaspace == NULL) {
 812     MutexLockerEx ml(_metaspace_lock,  Mutex::_no_safepoint_check_flag);
 813     // Check if _metaspace got allocated while we were waiting for this lock.
 814     if ((metaspace = _metaspace) == NULL) {
 815       if (this == the_null_class_loader_data()) {
 816         assert (class_loader() == NULL, "Must be");
 817         metaspace = new ClassLoaderMetaspace(_metaspace_lock, Metaspace::BootMetaspaceType);
 818       } else if (is_unsafe_anonymous()) {
 819         metaspace = new ClassLoaderMetaspace(_metaspace_lock, Metaspace::UnsafeAnonymousMetaspaceType);
 820       } else if (class_loader()->is_a(SystemDictionary::reflect_DelegatingClassLoader_klass())) {
 821         metaspace = new ClassLoaderMetaspace(_metaspace_lock, Metaspace::ReflectionMetaspaceType);
 822       } else {
 823         metaspace = new ClassLoaderMetaspace(_metaspace_lock, Metaspace::StandardMetaspaceType);
 824       }
 825       // Ensure _metaspace is stable, since it is examined without a lock
 826       OrderAccess::release_store(&_metaspace, metaspace);
 827     }
 828   }
 829   return metaspace;
 830 }
 831 
 832 OopHandle ClassLoaderData::add_handle(Handle h) {
 833   MutexLockerEx ml(metaspace_lock(),  Mutex::_no_safepoint_check_flag);
 834   record_modified_oops();
 835   return OopHandle(_handles.add(h()));
 836 }
 837 
 838 void ClassLoaderData::remove_handle(OopHandle h) {
 839   assert(!is_unloading(), "Do not remove a handle for a CLD that is unloading");
 840   oop* ptr = h.ptr_raw();
 841   if (ptr != NULL) {
 842     assert(_handles.owner_of(ptr), "Got unexpected handle " PTR_FORMAT, p2i(ptr));
 843     NativeAccess<>::oop_store(ptr, oop(NULL));
 844   }
 845 }
 846 
 847 void ClassLoaderData::init_handle_locked(OopHandle& dest, Handle h) {
 848   MutexLockerEx ml(metaspace_lock(),  Mutex::_no_safepoint_check_flag);
 849   if (dest.resolve() != NULL) {
 850     return;
 851   } else {
 852     dest = _handles.add(h());
 853   }
 854 }
 855 
 856 // Add this metadata pointer to be freed when it's safe.  This is only during
 857 // a safepoint which checks if handles point to this metadata field.
 858 void ClassLoaderData::add_to_deallocate_list(Metadata* m) {
 859   // Metadata in shared region isn't deleted.
 860   if (!m->is_shared()) {
 861     MutexLockerEx ml(metaspace_lock(),  Mutex::_no_safepoint_check_flag);
 862     if (_deallocate_list == NULL) {
 863       _deallocate_list = new (ResourceObj::C_HEAP, mtClass) GrowableArray<Metadata*>(100, true);
 864     }
 865     _deallocate_list->append_if_missing(m);
 866     log_debug(class, loader, data)("deallocate added for %s", m->print_value_string());
 867     ClassLoaderDataGraph::set_should_clean_deallocate_lists();
 868   }
 869 }
 870 
 871 // Deallocate free metadata on the free list.  How useful the PermGen was!
 872 void ClassLoaderData::free_deallocate_list() {
 873   // Don't need lock, at safepoint
 874   assert(SafepointSynchronize::is_at_safepoint(), "only called at safepoint");
 875   assert(!is_unloading(), "only called for ClassLoaderData that are not unloading");
 876   if (_deallocate_list == NULL) {
 877     return;
 878   }
 879   // Go backwards because this removes entries that are freed.
 880   for (int i = _deallocate_list->length() - 1; i >= 0; i--) {
 881     Metadata* m = _deallocate_list->at(i);
 882     if (!m->on_stack()) {
 883       _deallocate_list->remove_at(i);
 884       // There are only three types of metadata that we deallocate directly.
 885       // Cast them so they can be used by the template function.
 886       if (m->is_method()) {
 887         MetadataFactory::free_metadata(this, (Method*)m);
 888       } else if (m->is_constantPool()) {
 889         MetadataFactory::free_metadata(this, (ConstantPool*)m);
 890       } else if (m->is_klass()) {
 891         MetadataFactory::free_metadata(this, (InstanceKlass*)m);
 892       } else {
 893         ShouldNotReachHere();
 894       }
 895     } else {
 896       // Metadata is alive.
 897       // If scratch_class is on stack then it shouldn't be on this list!
 898       assert(!m->is_klass() || !((InstanceKlass*)m)->is_scratch_class(),
 899              "scratch classes on this list should be dead");
 900       // Also should assert that other metadata on the list was found in handles.
 901       // Some cleaning remains.
 902       ClassLoaderDataGraph::set_should_clean_deallocate_lists();
 903     }
 904   }
 905 }
 906 
 907 void ClassLoaderDataGraph::clean_deallocate_lists(bool walk_previous_versions) {
 908   assert(SafepointSynchronize::is_at_safepoint(), "must only be called at safepoint");
 909   uint loaders_processed = 0;
 910   for (ClassLoaderData* cld = _head; cld != NULL; cld = cld->next()) {
 911     // is_alive check will be necessary for concurrent class unloading.
 912     if (cld->is_alive()) {
 913       // clean metaspace
 914       if (walk_previous_versions) {
 915         cld->classes_do(InstanceKlass::purge_previous_versions);
 916       }
 917       cld->free_deallocate_list();
 918       loaders_processed++;
 919     }
 920   }
 921   log_debug(class, loader, data)("clean_deallocate_lists: loaders processed %u %s",
 922                                  loaders_processed, walk_previous_versions ? "walk_previous_versions" : "");
 923 }
 924 
 925 void ClassLoaderDataGraph::walk_metadata_and_clean_metaspaces() {
 926   assert(SafepointSynchronize::is_at_safepoint(), "must only be called at safepoint");
 927 
 928   _should_clean_deallocate_lists = false; // assume everything gets cleaned
 929 
 930   // Mark metadata seen on the stack so we can delete unreferenced entries.
 931   // Walk all metadata, including the expensive code cache walk, only for class redefinition.
 932   // The MetadataOnStackMark walk during redefinition saves previous versions if it finds old methods
 933   // on the stack or in the code cache, so we only have to repeat the full walk if
 934   // they were found at that time.
 935   // TODO: have redefinition clean old methods out of the code cache.  They still exist in some places.
 936   bool walk_all_metadata = InstanceKlass::has_previous_versions_and_reset();
 937 
 938   MetadataOnStackMark md_on_stack(walk_all_metadata);
 939   clean_deallocate_lists(walk_all_metadata);
 940 }
 941 
 942 // This is distinct from free_deallocate_list.  For class loader data that are
 943 // unloading, this frees the C heap memory for items on the list, and unlinks
 944 // scratch or error classes so that unloading events aren't triggered for these
 945 // classes. The metadata is removed with the unloading metaspace.
 946 // There isn't C heap memory allocated for methods, so nothing is done for them.
 947 void ClassLoaderData::free_deallocate_list_C_heap_structures() {
 948   // Don't need lock, at safepoint
 949   assert(SafepointSynchronize::is_at_safepoint(), "only called at safepoint");
 950   assert(is_unloading(), "only called for ClassLoaderData that are unloading");
 951   if (_deallocate_list == NULL) {
 952     return;
 953   }
 954   // Go backwards because this removes entries that are freed.
 955   for (int i = _deallocate_list->length() - 1; i >= 0; i--) {
 956     Metadata* m = _deallocate_list->at(i);
 957     _deallocate_list->remove_at(i);
 958     if (m->is_constantPool()) {
 959       ((ConstantPool*)m)->release_C_heap_structures();
 960     } else if (m->is_klass()) {
 961       InstanceKlass* ik = (InstanceKlass*)m;
 962       // also releases ik->constants() C heap memory
 963       InstanceKlass::release_C_heap_structures(ik);
 964       // Remove the class so unloading events aren't triggered for
 965       // this class (scratch or error class) in do_unloading().
 966       remove_class(ik);
 967     }
 968   }
 969 }
 970 
 971 // These CLDs are to contain unsafe anonymous classes used for JSR292
 972 ClassLoaderData* ClassLoaderData::unsafe_anonymous_class_loader_data(Handle loader) {
 973   // Add a new class loader data to the graph.
 974   return ClassLoaderDataGraph::add(loader, true);
 975 }
 976 
 977 // Caller needs ResourceMark
 978 // If the class loader's _name has not been explicitly set, the class loader's
 979 // qualified class name is returned.
 980 const char* ClassLoaderData::loader_name() const {
 981    if (_class_loader_klass == NULL) {
 982      return BOOTSTRAP_LOADER_NAME;
 983    } else if (_name != NULL) {
 984      return _name->as_C_string();
 985    } else {
 986      return _class_loader_klass->external_name();
 987    }
 988 }
 989 
 990 // Caller needs ResourceMark
 991 // Format of the _name_and_id is as follows:
 992 //   If the defining loader has a name explicitly set then '<loader-name>' @<id>
 993 //   If the defining loader has no name then <qualified-class-name> @<id>
 994 //   If built-in loader, then omit '@<id>' as there is only one instance.
 995 const char* ClassLoaderData::loader_name_and_id() const {
 996   if (_class_loader_klass == NULL) {
 997     return "'" BOOTSTRAP_LOADER_NAME "'";
 998   } else if (_name_and_id != NULL) {
 999     return _name_and_id->as_C_string();
1000   } else {
1001     // May be called in a race before _name_and_id is initialized.
1002     return _class_loader_klass->external_name();
1003   }
1004 }
1005 
1006 void ClassLoaderData::print_value_on(outputStream* out) const {
1007   if (!is_unloading() && class_loader() != NULL) {
1008     out->print("loader data: " INTPTR_FORMAT " for instance ", p2i(this));
1009     class_loader()->print_value_on(out);  // includes loader_name_and_id() and address of class loader instance
1010   } else {
1011     // loader data: 0xsomeaddr of 'bootstrap'
1012     out->print("loader data: " INTPTR_FORMAT " of %s", p2i(this), loader_name_and_id());
1013   }
1014   if (is_unsafe_anonymous()) {
1015     out->print(" unsafe anonymous");
1016   }
1017 }
1018 
1019 #ifndef PRODUCT
1020 void ClassLoaderData::print_on(outputStream* out) const {
1021   out->print("ClassLoaderData CLD: " PTR_FORMAT ", loader: " PTR_FORMAT ", loader_klass: %s {",
1022               p2i(this), p2i(_class_loader.ptr_raw()), loader_name_and_id());
1023   if (is_unsafe_anonymous()) out->print(" unsafe anonymous");
1024   if (claimed()) out->print(" claimed");
1025   if (is_unloading()) out->print(" unloading");
1026   out->print(" metaspace: " INTPTR_FORMAT, p2i(metaspace_or_null()));
1027 
1028   if (_jmethod_ids != NULL) {
1029     Method::print_jmethod_ids(this, out);
1030   }
1031   out->print(" handles count %d", _handles.count());
1032   out->print(" dependencies %d", _dependency_count);
1033   out->print_cr("}");
1034 }
1035 #endif // PRODUCT
1036 
1037 void ClassLoaderData::verify() {
1038   assert_locked_or_safepoint(_metaspace_lock);
1039   oop cl = class_loader();
1040 
1041   guarantee(this == class_loader_data(cl) || is_unsafe_anonymous(), "Must be the same");
1042   guarantee(cl != NULL || this == ClassLoaderData::the_null_class_loader_data() || is_unsafe_anonymous(), "must be");
1043 
1044   // Verify the integrity of the allocated space.
1045   if (metaspace_or_null() != NULL) {
1046     metaspace_or_null()->verify();
1047   }
1048 
1049   for (Klass* k = _klasses; k != NULL; k = k->next_link()) {
1050     guarantee(k->class_loader_data() == this, "Must be the same");
1051     k->verify();
1052     assert(k != k->next_link(), "no loops!");
1053   }
1054 }
1055 
1056 bool ClassLoaderData::contains_klass(Klass* klass) {
1057   // Lock-free access requires load_acquire
1058   for (Klass* k = OrderAccess::load_acquire(&_klasses); k != NULL; k = k->next_link()) {
1059     if (k == klass) return true;
1060   }
1061   return false;
1062 }
1063 
1064 
1065 // GC root of class loader data created.
1066 ClassLoaderData* ClassLoaderDataGraph::_head = NULL;
1067 ClassLoaderData* ClassLoaderDataGraph::_unloading = NULL;
1068 ClassLoaderData* ClassLoaderDataGraph::_saved_unloading = NULL;
1069 ClassLoaderData* ClassLoaderDataGraph::_saved_head = NULL;
1070 
1071 bool ClassLoaderDataGraph::_should_purge = false;
1072 bool ClassLoaderDataGraph::_should_clean_deallocate_lists = false;
1073 bool ClassLoaderDataGraph::_safepoint_cleanup_needed = false;
1074 bool ClassLoaderDataGraph::_metaspace_oom = false;
1075 
1076 // Add a new class loader data node to the list.  Assign the newly created
1077 // ClassLoaderData into the java/lang/ClassLoader object as a hidden field
1078 ClassLoaderData* ClassLoaderDataGraph::add_to_graph(Handle loader, bool is_unsafe_anonymous) {
1079 
1080   assert_lock_strong(ClassLoaderDataGraph_lock);
1081 
1082   ClassLoaderData* cld;
1083 
1084   // First check if another thread beat us to creating the CLD and installing
1085   // it into the loader while we were waiting for the lock.
1086   if (!is_unsafe_anonymous && loader.not_null()) {
1087     cld = java_lang_ClassLoader::loader_data_acquire(loader());
1088     if (cld != NULL) {
1089       return cld;
1090     }
1091   }
1092 
1093   // We mustn't GC until we've installed the ClassLoaderData in the Graph since the CLD
1094   // contains oops in _handles that must be walked.  GC doesn't walk CLD from the
1095   // loader oop in all collections, particularly young collections.
1096   NoSafepointVerifier no_safepoints;
1097 
1098   cld = new ClassLoaderData(loader, is_unsafe_anonymous);
1099 
1100   // First install the new CLD to the Graph.
1101   cld->set_next(_head);
1102   _head = cld;
1103 
1104   // Next associate with the class_loader.
1105   if (!is_unsafe_anonymous) {
1106     // Use OrderAccess, since readers need to get the loader_data only after
1107     // it's added to the Graph
1108     java_lang_ClassLoader::release_set_loader_data(loader(), cld);
1109   }
1110 
1111   // Lastly log, if requested
1112   LogTarget(Trace, class, loader, data) lt;
1113   if (lt.is_enabled()) {
1114     ResourceMark rm;
1115     LogStream ls(lt);
1116     ls.print("create ");
1117     cld->print_value_on(&ls);
1118     ls.cr();
1119   }
1120   return cld;
1121 }
1122 
1123 ClassLoaderData* ClassLoaderDataGraph::add(Handle loader, bool is_unsafe_anonymous) {
1124   MutexLocker ml(ClassLoaderDataGraph_lock);
1125   ClassLoaderData* loader_data = add_to_graph(loader, is_unsafe_anonymous);
1126   // Initialize _name and _name_and_id after the loader data is added to the
1127   // CLDG.
1128   if (loader.not_null()) {
1129     loader_data->initialize_name(loader);
1130   }
1131   return loader_data;
1132 }
1133 
1134 void ClassLoaderDataGraph::cld_do(CLDClosure* cl) {
1135   assert_locked_or_safepoint(ClassLoaderDataGraph_lock);
1136   for (ClassLoaderData* cld = _head;  cld != NULL; cld = cld->_next) {
1137     cl->do_cld(cld);
1138   }
1139 }
1140 
1141 void ClassLoaderDataGraph::cld_unloading_do(CLDClosure* cl) {
1142   assert_locked_or_safepoint(ClassLoaderDataGraph_lock);
1143   // Only walk the head until any clds not purged from prior unloading
1144   // (CMS doesn't purge right away).
1145   for (ClassLoaderData* cld = _unloading; cld != _saved_unloading; cld = cld->next()) {
1146     assert(cld->is_unloading(), "invariant");
1147     cl->do_cld(cld);
1148   }
1149 }
1150 
1151 void ClassLoaderDataGraph::roots_cld_do(CLDClosure* strong, CLDClosure* weak) {
1152   assert_locked_or_safepoint(ClassLoaderDataGraph_lock);
1153   for (ClassLoaderData* cld = _head;  cld != NULL; cld = cld->_next) {
1154     CLDClosure* closure = cld->keep_alive() ? strong : weak;
1155     if (closure != NULL) {
1156       closure->do_cld(cld);
1157     }
1158   }
1159 }
1160 
1161 void ClassLoaderDataGraph::always_strong_cld_do(CLDClosure* cl) {
1162   assert_locked_or_safepoint(ClassLoaderDataGraph_lock);
1163   if (ClassUnloading) {
1164     roots_cld_do(cl, NULL);
1165   } else {
1166     cld_do(cl);
1167   }
1168 }
1169 
1170 // Closure for locking and iterating through classes.
1171 LockedClassesDo::LockedClassesDo(classes_do_func_t f) : _function(f) {
1172   ClassLoaderDataGraph_lock->lock();
1173 }
1174 
1175 LockedClassesDo::LockedClassesDo() : _function(NULL) {
1176   // callers provide their own do_klass
1177   ClassLoaderDataGraph_lock->lock();
1178 }
1179 
1180 LockedClassesDo::~LockedClassesDo() { ClassLoaderDataGraph_lock->unlock(); }
1181 
1182 
1183 // Iterating over the CLDG needs to be locked because
1184 // unloading can remove entries concurrently soon.
1185 class ClassLoaderDataGraphIterator : public StackObj {
1186   ClassLoaderData* _next;
1187   HandleMark       _hm;  // clean up handles when this is done.
1188   Handle           _holder;
1189   Thread*          _thread;
1190 
1191   void hold_next() {
1192     if (_next != NULL) {
1193       _holder = Handle(_thread, _next->holder_phantom());
1194     }
1195   }
1196 public:
1197   ClassLoaderDataGraphIterator() : _next(ClassLoaderDataGraph::_head) {
1198     _thread = Thread::current();
1199     assert_locked_or_safepoint(ClassLoaderDataGraph_lock);
1200     hold_next();
1201   }
1202 
1203   bool repeat() const {
1204     return _next != NULL;
1205   }
1206 
1207   ClassLoaderData* get_next() {
1208     ClassLoaderData* next = _next;
1209     if (_next != NULL) {
1210       _next = _next->next();
1211       hold_next();
1212     }
1213     return next;
1214   }
1215 };
1216 
1217 // These functions assume that the caller has locked the ClassLoaderDataGraph_lock
1218 // if they are not calling the function from a safepoint.
1219 void ClassLoaderDataGraph::classes_do(KlassClosure* klass_closure) {
1220   ClassLoaderDataGraphIterator iter;
1221   while (iter.repeat()) {
1222     ClassLoaderData* cld = iter.get_next();
1223     cld->classes_do(klass_closure);
1224   }
1225 }
1226 
1227 void ClassLoaderDataGraph::classes_do(void f(Klass* const)) {
1228   ClassLoaderDataGraphIterator iter;
1229   while (iter.repeat()) {
1230     ClassLoaderData* cld = iter.get_next();
1231     cld->classes_do(f);
1232   }
1233 }
1234 
1235 void ClassLoaderDataGraph::methods_do(void f(Method*)) {
1236   ClassLoaderDataGraphIterator iter;
1237   while (iter.repeat()) {
1238     ClassLoaderData* cld = iter.get_next();
1239     cld->methods_do(f);
1240   }
1241 }
1242 
1243 void ClassLoaderDataGraph::modules_do(void f(ModuleEntry*)) {
1244   assert_locked_or_safepoint(Module_lock);
1245   ClassLoaderDataGraphIterator iter;
1246   while (iter.repeat()) {
1247     ClassLoaderData* cld = iter.get_next();
1248     cld->modules_do(f);
1249   }
1250 }
1251 
1252 void ClassLoaderDataGraph::modules_unloading_do(void f(ModuleEntry*)) {
1253   assert_locked_or_safepoint(ClassLoaderDataGraph_lock);
1254   // Only walk the head until any clds not purged from prior unloading
1255   // (CMS doesn't purge right away).
1256   for (ClassLoaderData* cld = _unloading; cld != _saved_unloading; cld = cld->next()) {
1257     assert(cld->is_unloading(), "invariant");
1258     cld->modules_do(f);
1259   }
1260 }
1261 
1262 void ClassLoaderDataGraph::packages_do(void f(PackageEntry*)) {
1263   assert_locked_or_safepoint(Module_lock);
1264   ClassLoaderDataGraphIterator iter;
1265   while (iter.repeat()) {
1266     ClassLoaderData* cld = iter.get_next();
1267     cld->packages_do(f);
1268   }
1269 }
1270 
1271 void ClassLoaderDataGraph::packages_unloading_do(void f(PackageEntry*)) {
1272   assert_locked_or_safepoint(ClassLoaderDataGraph_lock);
1273   // Only walk the head until any clds not purged from prior unloading
1274   // (CMS doesn't purge right away).
1275   for (ClassLoaderData* cld = _unloading; cld != _saved_unloading; cld = cld->next()) {
1276     assert(cld->is_unloading(), "invariant");
1277     cld->packages_do(f);
1278   }
1279 }
1280 
1281 void ClassLoaderDataGraph::loaded_classes_do(KlassClosure* klass_closure) {
1282   ClassLoaderDataGraphIterator iter;
1283   while (iter.repeat()) {
1284     ClassLoaderData* cld = iter.get_next();
1285     cld->loaded_classes_do(klass_closure);
1286   }
1287 }
1288 
1289 // This case can block but cannot do unloading (called from CDS)
1290 void ClassLoaderDataGraph::unlocked_loaded_classes_do(KlassClosure* klass_closure) {
1291   for (ClassLoaderData* cld = _head; cld != NULL; cld = cld->next()) {
1292     cld->loaded_classes_do(klass_closure);
1293   }
1294 }
1295 
1296 
1297 void ClassLoaderDataGraph::classes_unloading_do(void f(Klass* const)) {
1298   assert_locked_or_safepoint(ClassLoaderDataGraph_lock);
1299   // Only walk the head until any clds not purged from prior unloading
1300   // (CMS doesn't purge right away).
1301   for (ClassLoaderData* cld = _unloading; cld != _saved_unloading; cld = cld->next()) {
1302     assert(cld->is_unloading(), "invariant");
1303     cld->classes_do(f);
1304   }
1305 }
1306 
1307 #define FOR_ALL_DICTIONARY(X)   ClassLoaderDataGraphIterator iter; \
1308                                 ClassLoaderData* X; \
1309                                 while ((X = iter.get_next()) != NULL) \
1310                                   if (X->dictionary() != NULL)
1311 
1312 // Walk classes in the loaded class dictionaries in various forms.
1313 // Only walks the classes defined in this class loader.
1314 void ClassLoaderDataGraph::dictionary_classes_do(void f(InstanceKlass*)) {
1315   FOR_ALL_DICTIONARY(cld) {
1316     cld->dictionary()->classes_do(f);
1317   }
1318 }
1319 
1320 // Only walks the classes defined in this class loader.
1321 void ClassLoaderDataGraph::dictionary_classes_do(void f(InstanceKlass*, TRAPS), TRAPS) {
1322   FOR_ALL_DICTIONARY(cld) {
1323     cld->dictionary()->classes_do(f, CHECK);
1324   }
1325 }
1326 
1327 void ClassLoaderDataGraph::verify_dictionary() {
1328   FOR_ALL_DICTIONARY(cld) {
1329     cld->dictionary()->verify();
1330   }
1331 }
1332 
1333 void ClassLoaderDataGraph::print_dictionary(outputStream* st) {
1334   FOR_ALL_DICTIONARY(cld) {
1335     st->print("Dictionary for ");
1336     cld->print_value_on(st);
1337     st->cr();
1338     cld->dictionary()->print_on(st);
1339     st->cr();
1340   }
1341 }
1342 
1343 void ClassLoaderDataGraph::print_dictionary_statistics(outputStream* st) {
1344   FOR_ALL_DICTIONARY(cld) {
1345     ResourceMark rm;
1346     stringStream tempst;
1347     tempst.print("System Dictionary for %s class loader", cld->loader_name_and_id());
1348     cld->dictionary()->print_table_statistics(st, tempst.as_string());
1349   }
1350 }
1351 
1352 GrowableArray<ClassLoaderData*>* ClassLoaderDataGraph::new_clds() {
1353   assert_locked_or_safepoint(ClassLoaderDataGraph_lock);
1354   assert(_head == NULL || _saved_head != NULL, "remember_new_clds(true) not called?");
1355 
1356   GrowableArray<ClassLoaderData*>* array = new GrowableArray<ClassLoaderData*>();
1357 
1358   // The CLDs in [_head, _saved_head] were all added during last call to remember_new_clds(true);
1359   ClassLoaderData* curr = _head;
1360   while (curr != _saved_head) {
1361     if (!curr->claimed()) {
1362       array->push(curr);
1363       LogTarget(Debug, class, loader, data) lt;
1364       if (lt.is_enabled()) {
1365         LogStream ls(lt);
1366         ls.print("found new CLD: ");
1367         curr->print_value_on(&ls);
1368         ls.cr();
1369       }
1370     }
1371 
1372     curr = curr->_next;
1373   }
1374 
1375   return array;
1376 }
1377 
1378 #ifndef PRODUCT
1379 bool ClassLoaderDataGraph::contains_loader_data(ClassLoaderData* loader_data) {
1380   assert_locked_or_safepoint(ClassLoaderDataGraph_lock);
1381   for (ClassLoaderData* data = _head; data != NULL; data = data->next()) {
1382     if (loader_data == data) {
1383       return true;
1384     }
1385   }
1386 
1387   return false;
1388 }
1389 #endif // PRODUCT
1390 
1391 // Move class loader data from main list to the unloaded list for unloading
1392 // and deallocation later.
1393 bool ClassLoaderDataGraph::do_unloading(bool do_cleaning) {
1394   assert_locked_or_safepoint(ClassLoaderDataGraph_lock);
1395 
1396   // Indicate whether safepoint cleanup is needed.
1397   _safepoint_cleanup_needed |= do_cleaning;
1398 
1399   ClassLoaderData* data = _head;
1400   ClassLoaderData* prev = NULL;
1401   bool seen_dead_loader = false;
1402   uint loaders_processed = 0;
1403   uint loaders_removed = 0;
1404 
1405   // Save previous _unloading pointer for CMS which may add to unloading list before
1406   // purging and we don't want to rewalk the previously unloaded class loader data.
1407   _saved_unloading = _unloading;
1408 
1409   data = _head;
1410   while (data != NULL) {
1411     if (data->is_alive()) {
1412       prev = data;
1413       data = data->next();
1414       loaders_processed++;
1415       continue;
1416     }
1417     seen_dead_loader = true;
1418     loaders_removed++;
1419     ClassLoaderData* dead = data;
1420     dead->unload();
1421     data = data->next();
1422     // Remove from loader list.
1423     // This class loader data will no longer be found
1424     // in the ClassLoaderDataGraph.
1425     if (prev != NULL) {
1426       prev->set_next(data);
1427     } else {
1428       assert(dead == _head, "sanity check");
1429       _head = data;
1430     }
1431     dead->set_next(_unloading);
1432     _unloading = dead;
1433   }
1434 
1435   log_debug(class, loader, data)("do_unloading: loaders processed %u, loaders removed %u", loaders_processed, loaders_removed);
1436 
1437   return seen_dead_loader;
1438 }
1439 
1440 // There's at least one dead class loader.  Purge refererences of healthy module
1441 // reads lists and package export lists to modules belonging to dead loaders.
1442 void ClassLoaderDataGraph::clean_module_and_package_info() {
1443   assert_locked_or_safepoint(ClassLoaderDataGraph_lock);
1444 
1445   ClassLoaderData* data = _head;
1446   while (data != NULL) {
1447     // Remove entries in the dictionary of live class loader that have
1448     // initiated loading classes in a dead class loader.
1449     if (data->dictionary() != NULL) {
1450       data->dictionary()->do_unloading();
1451     }
1452     // Walk a ModuleEntry's reads, and a PackageEntry's exports
1453     // lists to determine if there are modules on those lists that are now
1454     // dead and should be removed.  A module's life cycle is equivalent
1455     // to its defining class loader's life cycle.  Since a module is
1456     // considered dead if its class loader is dead, these walks must
1457     // occur after each class loader's aliveness is determined.
1458     if (data->packages() != NULL) {
1459       data->packages()->purge_all_package_exports();
1460     }
1461     if (data->modules_defined()) {
1462       data->modules()->purge_all_module_reads();
1463     }
1464     data = data->next();
1465   }
1466 }
1467 
1468 void ClassLoaderDataGraph::purge() {
1469   assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint!");
1470   ClassLoaderData* list = _unloading;
1471   _unloading = NULL;
1472   ClassLoaderData* next = list;
1473   bool classes_unloaded = false;
1474   while (next != NULL) {
1475     ClassLoaderData* purge_me = next;
1476     next = purge_me->next();
1477     delete purge_me;
1478     classes_unloaded = true;
1479   }
1480   if (classes_unloaded) {
1481     Metaspace::purge();
1482     set_metaspace_oom(false);
1483   }
1484 }
1485 
1486 int ClassLoaderDataGraph::resize_if_needed() {
1487   assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint!");
1488   int resized = 0;
1489   if (Dictionary::does_any_dictionary_needs_resizing()) {
1490     FOR_ALL_DICTIONARY(cld) {
1491       if (cld->dictionary()->resize_if_needed()) {
1492         resized++;
1493       }
1494     }
1495   }
1496   return resized;
1497 }
1498 
1499 ClassLoaderDataGraphKlassIteratorAtomic::ClassLoaderDataGraphKlassIteratorAtomic()
1500     : _next_klass(NULL) {
1501   assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint!");
1502   ClassLoaderData* cld = ClassLoaderDataGraph::_head;
1503   Klass* klass = NULL;
1504 
1505   // Find the first klass in the CLDG.
1506   while (cld != NULL) {
1507     assert_locked_or_safepoint(cld->metaspace_lock());
1508     klass = cld->_klasses;
1509     if (klass != NULL) {
1510       _next_klass = klass;
1511       return;
1512     }
1513     cld = cld->next();
1514   }
1515 }
1516 
1517 Klass* ClassLoaderDataGraphKlassIteratorAtomic::next_klass_in_cldg(Klass* klass) {
1518   Klass* next = klass->next_link();
1519   if (next != NULL) {
1520     return next;
1521   }
1522 
1523   // No more klasses in the current CLD. Time to find a new CLD.
1524   ClassLoaderData* cld = klass->class_loader_data();
1525   assert_locked_or_safepoint(cld->metaspace_lock());
1526   while (next == NULL) {
1527     cld = cld->next();
1528     if (cld == NULL) {
1529       break;
1530     }
1531     next = cld->_klasses;
1532   }
1533 
1534   return next;
1535 }
1536 
1537 Klass* ClassLoaderDataGraphKlassIteratorAtomic::next_klass() {
1538   Klass* head = _next_klass;
1539 
1540   while (head != NULL) {
1541     Klass* next = next_klass_in_cldg(head);
1542 
1543     Klass* old_head = Atomic::cmpxchg(next, &_next_klass, head);
1544 
1545     if (old_head == head) {
1546       return head; // Won the CAS.
1547     }
1548 
1549     head = old_head;
1550   }
1551 
1552   // Nothing more for the iterator to hand out.
1553   assert(head == NULL, "head is " PTR_FORMAT ", expected not null:", p2i(head));
1554   return NULL;
1555 }
1556 
1557 ClassLoaderDataGraphMetaspaceIterator::ClassLoaderDataGraphMetaspaceIterator() {
1558   assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint!");
1559   _data = ClassLoaderDataGraph::_head;
1560 }
1561 
1562 ClassLoaderDataGraphMetaspaceIterator::~ClassLoaderDataGraphMetaspaceIterator() {}
1563 
1564 #ifndef PRODUCT
1565 // callable from debugger
1566 extern "C" int print_loader_data_graph() {
1567   ResourceMark rm;
1568   ClassLoaderDataGraph::print_on(tty);
1569   return 0;
1570 }
1571 
1572 void ClassLoaderDataGraph::verify() {
1573   ClassLoaderDataGraphIterator iter;
1574   while (iter.repeat()) {
1575     ClassLoaderData* cld = iter.get_next();
1576     cld->verify();
1577   }
1578 }
1579 
1580 void ClassLoaderDataGraph::print_on(outputStream * const out) {
1581   ClassLoaderDataGraphIterator iter;
1582   while (iter.repeat()) {
1583     ClassLoaderData* cld = iter.get_next();
1584     cld->print_on(out);
1585   }
1586 }
1587 #endif // PRODUCT