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