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