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