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