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