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