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