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