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.inline.hpp"
  51 #include "classfile/classLoaderDataGraph.inline.hpp"
  52 #include "classfile/dictionary.hpp"
  53 #include "classfile/javaClasses.hpp"
  54 #include "classfile/moduleEntry.hpp"
  55 #include "classfile/packageEntry.hpp"
  56 #include "classfile/symbolTable.hpp"
  57 #include "classfile/systemDictionary.hpp"
  58 #include "logging/log.hpp"
  59 #include "logging/logStream.hpp"
  60 #include "memory/allocation.inline.hpp"
  61 #include "memory/metadataFactory.hpp"
  62 #include "memory/resourceArea.hpp"
  63 #include "oops/access.inline.hpp"
  64 #include "oops/oop.inline.hpp"
  65 #include "oops/oopHandle.inline.hpp"
  66 #include "oops/weakHandle.inline.hpp"
  67 #include "runtime/atomic.hpp"
  68 #include "runtime/handles.inline.hpp"
  69 #include "runtime/mutex.hpp"
  70 #include "runtime/orderAccess.hpp"
  71 #include "runtime/safepoint.hpp"
  72 #include "utilities/growableArray.hpp"
  73 #include "utilities/macros.hpp"
  74 #include "utilities/ostream.hpp"
  75 
  76 ClassLoaderData * ClassLoaderData::_the_null_class_loader_data = NULL;
  77 
  78 void ClassLoaderData::init_null_class_loader_data() {
  79   assert(_the_null_class_loader_data == NULL, "cannot initialize twice");
  80   assert(ClassLoaderDataGraph::_head == NULL, "cannot initialize twice");
  81 
  82   _the_null_class_loader_data = new ClassLoaderData(Handle(), false);
  83   ClassLoaderDataGraph::_head = _the_null_class_loader_data;
  84   assert(_the_null_class_loader_data->is_the_null_class_loader_data(), "Must be");
  85 
  86   LogTarget(Trace, class, loader, data) lt;
  87   if (lt.is_enabled()) {
  88     ResourceMark rm;
  89     LogStream ls(lt);
  90     ls.print("create ");
  91     _the_null_class_loader_data->print_value_on(&ls);
  92     ls.cr();
  93   }
  94 }
  95 
  96 // Obtain and set the class loader's name within the ClassLoaderData so
  97 // it will be available for error messages, logging, JFR, etc.  The name
  98 // and klass are available after the class_loader oop is no longer alive,
  99 // during unloading.
 100 void ClassLoaderData::initialize_name(Handle class_loader) {
 101   Thread* THREAD = Thread::current();
 102   ResourceMark rm(THREAD);
 103 
 104   // Obtain the class loader's name.  If the class loader's name was not
 105   // explicitly set during construction, the CLD's _name field will be null.
 106   oop cl_name = java_lang_ClassLoader::name(class_loader());
 107   if (cl_name != NULL) {
 108     const char* cl_instance_name = java_lang_String::as_utf8_string(cl_name);
 109 
 110     if (cl_instance_name != NULL && cl_instance_name[0] != '\0') {
 111       // Can't throw InternalError and SymbolTable doesn't throw OOM anymore.
 112       _name = SymbolTable::new_symbol(cl_instance_name, CATCH);
 113     }
 114   }
 115 
 116   // Obtain the class loader's name and identity hash.  If the class loader's
 117   // name was not explicitly set during construction, the class loader's name and id
 118   // will be set to the qualified class name of the class loader along with its
 119   // identity hash.
 120   // If for some reason the ClassLoader's constructor has not been run, instead of
 121   // leaving the _name_and_id field null, fall back to the external qualified class
 122   // name.  Thus CLD's _name_and_id field should never have a null value.
 123   oop cl_name_and_id = java_lang_ClassLoader::nameAndId(class_loader());
 124   const char* cl_instance_name_and_id =
 125                   (cl_name_and_id == NULL) ? _class_loader_klass->external_name() :
 126                                              java_lang_String::as_utf8_string(cl_name_and_id);
 127   assert(cl_instance_name_and_id != NULL && cl_instance_name_and_id[0] != '\0', "class loader has no name and id");
 128   // Can't throw InternalError and SymbolTable doesn't throw OOM anymore.
 129   _name_and_id = SymbolTable::new_symbol(cl_instance_name_and_id, CATCH);
 130 }
 131 
 132 ClassLoaderData::ClassLoaderData(Handle h_class_loader, bool is_unsafe_anonymous) :
 133   _metaspace(NULL),
 134   _metaspace_lock(new Mutex(Monitor::leaf+1, "Metaspace allocation lock", true,
 135                             Monitor::_safepoint_check_never)),
 136   _unloading(false), _is_unsafe_anonymous(is_unsafe_anonymous),
 137   _modified_oops(true), _accumulated_modified_oops(false),
 138   // An unsafe anonymous class loader data doesn't have anything to keep
 139   // it from being unloaded during parsing of the unsafe anonymous class.
 140   // The null-class-loader should always be kept alive.
 141   _keep_alive((is_unsafe_anonymous || h_class_loader.is_null()) ? 1 : 0),
 142   _claimed(0),
 143   _handles(),
 144   _klasses(NULL), _packages(NULL), _modules(NULL), _unnamed_module(NULL), _dictionary(NULL),
 145   _jmethod_ids(NULL),
 146   _deallocate_list(NULL),
 147   _next(NULL),
 148   _class_loader_klass(NULL), _name(NULL), _name_and_id(NULL) {
 149 
 150   if (!h_class_loader.is_null()) {
 151     _class_loader = _handles.add(h_class_loader());
 152     _class_loader_klass = h_class_loader->klass();
 153     initialize_name(h_class_loader);
 154   }
 155 
 156   if (!is_unsafe_anonymous) {
 157     // The holder is initialized later for unsafe anonymous classes, and before calling anything
 158     // that call class_loader().
 159     initialize_holder(h_class_loader);
 160 
 161     // A ClassLoaderData created solely for an unsafe anonymous class should never have a
 162     // ModuleEntryTable or PackageEntryTable created for it. The defining package
 163     // and module for an unsafe anonymous class will be found in its host class.
 164     _packages = new PackageEntryTable(PackageEntryTable::_packagetable_entry_size);
 165     if (h_class_loader.is_null()) {
 166       // Create unnamed module for boot loader
 167       _unnamed_module = ModuleEntry::create_boot_unnamed_module(this);
 168     } else {
 169       // Create unnamed module for all other loaders
 170       _unnamed_module = ModuleEntry::create_unnamed_module(this);
 171     }
 172     _dictionary = create_dictionary();
 173   }
 174 
 175   NOT_PRODUCT(_dependency_count = 0); // number of class loader dependencies
 176 
 177   JFR_ONLY(INIT_ID(this);)
 178 }
 179 
 180 ClassLoaderData::ChunkedHandleList::~ChunkedHandleList() {
 181   Chunk* c = _head;
 182   while (c != NULL) {
 183     Chunk* next = c->_next;
 184     delete c;
 185     c = next;
 186   }
 187 }
 188 
 189 oop* ClassLoaderData::ChunkedHandleList::add(oop o) {
 190   if (_head == NULL || _head->_size == Chunk::CAPACITY) {
 191     Chunk* next = new Chunk(_head);
 192     OrderAccess::release_store(&_head, next);
 193   }
 194   oop* handle = &_head->_data[_head->_size];
 195   *handle = o;
 196   OrderAccess::release_store(&_head->_size, _head->_size + 1);
 197   return handle;
 198 }
 199 
 200 int ClassLoaderData::ChunkedHandleList::count() const {
 201   int count = 0;
 202   Chunk* chunk = _head;
 203   while (chunk != NULL) {
 204     count += chunk->_size;
 205     chunk = chunk->_next;
 206   }
 207   return count;
 208 }
 209 
 210 inline void ClassLoaderData::ChunkedHandleList::oops_do_chunk(OopClosure* f, Chunk* c, const juint size) {
 211   for (juint i = 0; i < size; i++) {
 212     if (c->_data[i] != NULL) {
 213       f->do_oop(&c->_data[i]);
 214     }
 215   }
 216 }
 217 
 218 void ClassLoaderData::ChunkedHandleList::oops_do(OopClosure* f) {
 219   Chunk* head = OrderAccess::load_acquire(&_head);
 220   if (head != NULL) {
 221     // Must be careful when reading size of head
 222     oops_do_chunk(f, head, OrderAccess::load_acquire(&head->_size));
 223     for (Chunk* c = head->_next; c != NULL; c = c->_next) {
 224       oops_do_chunk(f, c, c->_size);
 225     }
 226   }
 227 }
 228 
 229 class VerifyContainsOopClosure : public OopClosure {
 230   oop  _target;
 231   bool _found;
 232 
 233  public:
 234   VerifyContainsOopClosure(oop target) : _target(target), _found(false) {}
 235 
 236   void do_oop(oop* p) {
 237     if (p != NULL && oopDesc::equals(RawAccess<>::oop_load(p), _target)) {
 238       _found = true;
 239     }
 240   }
 241 
 242   void do_oop(narrowOop* p) {
 243     // The ChunkedHandleList should not contain any narrowOop
 244     ShouldNotReachHere();
 245   }
 246 
 247   bool found() const {
 248     return _found;
 249   }
 250 };
 251 
 252 bool ClassLoaderData::ChunkedHandleList::contains(oop p) {
 253   VerifyContainsOopClosure cl(p);
 254   oops_do(&cl);
 255   return cl.found();
 256 }
 257 
 258 #ifndef PRODUCT
 259 bool ClassLoaderData::ChunkedHandleList::owner_of(oop* oop_handle) {
 260   Chunk* chunk = _head;
 261   while (chunk != NULL) {
 262     if (&(chunk->_data[0]) <= oop_handle && oop_handle < &(chunk->_data[chunk->_size])) {
 263       return true;
 264     }
 265     chunk = chunk->_next;
 266   }
 267   return false;
 268 }
 269 #endif // PRODUCT
 270 
 271 bool ClassLoaderData::claim() {
 272   if (_claimed == 1) {
 273     return false;
 274   }
 275 
 276   return (int) Atomic::cmpxchg(1, &_claimed, 0) == 0;
 277 }
 278 
 279 // Unsafe anonymous classes have their own ClassLoaderData that is marked to keep alive
 280 // while the class is being parsed, and if the class appears on the module fixup list.
 281 // Due to the uniqueness that no other class shares the unsafe anonymous class' name or
 282 // ClassLoaderData, no other non-GC thread has knowledge of the unsafe anonymous class while
 283 // it is being defined, therefore _keep_alive is not volatile or atomic.
 284 void ClassLoaderData::inc_keep_alive() {
 285   if (is_unsafe_anonymous()) {
 286     assert(_keep_alive >= 0, "Invalid keep alive increment count");
 287     _keep_alive++;
 288   }
 289 }
 290 
 291 void ClassLoaderData::dec_keep_alive() {
 292   if (is_unsafe_anonymous()) {
 293     assert(_keep_alive > 0, "Invalid keep alive decrement count");
 294     _keep_alive--;
 295   }
 296 }
 297 
 298 void ClassLoaderData::oops_do(OopClosure* f, bool must_claim, bool clear_mod_oops) {
 299   if (must_claim && !claim()) {
 300     return;
 301   }
 302 
 303   // Only clear modified_oops after the ClassLoaderData is claimed.
 304   if (clear_mod_oops) {
 305     clear_modified_oops();
 306   }
 307 
 308   _handles.oops_do(f);
 309 }
 310 
 311 void ClassLoaderData::classes_do(KlassClosure* klass_closure) {
 312   // Lock-free access requires load_acquire
 313   for (Klass* k = OrderAccess::load_acquire(&_klasses); k != NULL; k = k->next_link()) {
 314     klass_closure->do_klass(k);
 315     assert(k != k->next_link(), "no loops!");
 316   }
 317 }
 318 
 319 void ClassLoaderData::classes_do(void f(Klass * const)) {
 320   // Lock-free access requires load_acquire
 321   for (Klass* k = OrderAccess::load_acquire(&_klasses); k != NULL; k = k->next_link()) {
 322     f(k);
 323     assert(k != k->next_link(), "no loops!");
 324   }
 325 }
 326 
 327 void ClassLoaderData::methods_do(void f(Method*)) {
 328   // Lock-free access requires load_acquire
 329   for (Klass* k = OrderAccess::load_acquire(&_klasses); k != NULL; k = k->next_link()) {
 330     if (k->is_instance_klass() && InstanceKlass::cast(k)->is_loaded()) {
 331       InstanceKlass::cast(k)->methods_do(f);
 332     }
 333   }
 334 }
 335 
 336 void ClassLoaderData::loaded_classes_do(KlassClosure* klass_closure) {
 337   // Lock-free access requires load_acquire
 338   for (Klass* k = OrderAccess::load_acquire(&_klasses); k != NULL; k = k->next_link()) {
 339     // Do not filter ArrayKlass oops here...
 340     if (k->is_array_klass() || (k->is_instance_klass() && InstanceKlass::cast(k)->is_loaded())) {
 341 #ifdef ASSERT
 342       oop m = k->java_mirror();
 343       assert(m != NULL, "NULL mirror"); 
 344       assert(m->is_a(SystemDictionary::Class_klass()), "invalid mirror");
 345 #endif
 346       klass_closure->do_klass(k);
 347     }
 348   }
 349 }
 350 
 351 void ClassLoaderData::classes_do(void f(InstanceKlass*)) {
 352   // Lock-free access requires load_acquire
 353   for (Klass* k = OrderAccess::load_acquire(&_klasses); k != NULL; k = k->next_link()) {
 354     if (k->is_instance_klass()) {
 355       f(InstanceKlass::cast(k));
 356     }
 357     assert(k != k->next_link(), "no loops!");
 358   }
 359 }
 360 
 361 void ClassLoaderData::modules_do(void f(ModuleEntry*)) {
 362   assert_locked_or_safepoint(Module_lock);
 363   if (_unnamed_module != NULL) {
 364     f(_unnamed_module);
 365   }
 366   if (_modules != NULL) {
 367     for (int i = 0; i < _modules->table_size(); i++) {
 368       for (ModuleEntry* entry = _modules->bucket(i);
 369            entry != NULL;
 370            entry = entry->next()) {
 371         f(entry);
 372       }
 373     }
 374   }
 375 }
 376 
 377 void ClassLoaderData::packages_do(void f(PackageEntry*)) {
 378   assert_locked_or_safepoint(Module_lock);
 379   if (_packages != NULL) {
 380     for (int i = 0; i < _packages->table_size(); i++) {
 381       for (PackageEntry* entry = _packages->bucket(i);
 382            entry != NULL;
 383            entry = entry->next()) {
 384         f(entry);
 385       }
 386     }
 387   }
 388 }
 389 
 390 void ClassLoaderData::record_dependency(const Klass* k) {
 391   assert(k != NULL, "invariant");
 392 
 393   ClassLoaderData * const from_cld = this;
 394   ClassLoaderData * const to_cld = k->class_loader_data();
 395 
 396   // Do not need to record dependency if the dependency is to a class whose
 397   // class loader data is never freed.  (i.e. the dependency's class loader
 398   // is one of the three builtin class loaders and the dependency is not
 399   // unsafe anonymous.)
 400   if (to_cld->is_permanent_class_loader_data()) {
 401     return;
 402   }
 403 
 404   oop to;
 405   if (to_cld->is_unsafe_anonymous()) {
 406     // Just return if an unsafe anonymous class is attempting to record a dependency
 407     // to itself.  (Note that every unsafe anonymous class has its own unique class
 408     // loader data.)
 409     if (to_cld == from_cld) {
 410       return;
 411     }
 412     // Unsafe anonymous class dependencies are through the mirror.
 413     to = k->java_mirror();
 414   } else {
 415     to = to_cld->class_loader();
 416     oop from = from_cld->class_loader();
 417 
 418     // Just return if this dependency is to a class with the same or a parent
 419     // class_loader.
 420     if (oopDesc::equals(from, to) || java_lang_ClassLoader::isAncestor(from, to)) {
 421       return; // this class loader is in the parent list, no need to add it.
 422     }
 423   }
 424 
 425   // It's a dependency we won't find through GC, add it.
 426   if (!_handles.contains(to)) {
 427     NOT_PRODUCT(Atomic::inc(&_dependency_count));
 428     LogTarget(Trace, class, loader, data) lt;
 429     if (lt.is_enabled()) {
 430       ResourceMark rm;
 431       LogStream ls(lt);
 432       ls.print("adding dependency from ");
 433       print_value_on(&ls);
 434       ls.print(" to ");
 435       to_cld->print_value_on(&ls);
 436       ls.cr();
 437     }
 438     Handle dependency(Thread::current(), to);
 439     add_handle(dependency);
 440     // Added a potentially young gen oop to the ClassLoaderData
 441     record_modified_oops();
 442   }
 443 }
 444 
 445 void ClassLoaderData::add_class(Klass* k, bool publicize /* true */) {
 446   {
 447     MutexLockerEx ml(metaspace_lock(), Mutex::_no_safepoint_check_flag);
 448     Klass* old_value = _klasses;
 449     k->set_next_link(old_value);
 450     // Link the new item into the list, making sure the linked class is stable
 451     // since the list can be walked without a lock
 452     OrderAccess::release_store(&_klasses, k);
 453     if (k->is_array_klass()) {
 454       ClassLoaderDataGraph::inc_array_classes(1);
 455     } else {
 456       ClassLoaderDataGraph::inc_instance_classes(1);
 457     }
 458   }
 459 
 460   if (publicize) {
 461     LogTarget(Trace, class, loader, data) lt;
 462     if (lt.is_enabled()) {
 463       ResourceMark rm;
 464       LogStream ls(lt);
 465       ls.print("Adding k: " PTR_FORMAT " %s to ", p2i(k), k->external_name());
 466       print_value_on(&ls);
 467       ls.cr();
 468     }
 469   }
 470 }
 471 
 472 void ClassLoaderData::initialize_holder(Handle loader_or_mirror) {
 473   if (loader_or_mirror() != NULL) {
 474     assert(_holder.is_null(), "never replace holders");
 475     _holder = WeakHandle<vm_class_loader_data>::create(loader_or_mirror);
 476   }
 477 }
 478 
 479 // Remove a klass from the _klasses list for scratch_class during redefinition
 480 // or parsed class in the case of an error.
 481 void ClassLoaderData::remove_class(Klass* scratch_class) {
 482   assert(SafepointSynchronize::is_at_safepoint(), "only called at safepoint");
 483 
 484   // Adjust global class iterator.
 485   ClassLoaderDataGraph::adjust_saved_class(scratch_class);
 486 
 487   Klass* prev = NULL;
 488   for (Klass* k = _klasses; k != NULL; k = k->next_link()) {
 489     if (k == scratch_class) {
 490       if (prev == NULL) {
 491         _klasses = k->next_link();
 492       } else {
 493         Klass* next = k->next_link();
 494         prev->set_next_link(next);
 495       }
 496 
 497       if (k->is_array_klass()) {
 498         ClassLoaderDataGraph::dec_array_classes(1);
 499       } else {
 500         ClassLoaderDataGraph::dec_instance_classes(1);
 501       }
 502 
 503       return;
 504     }
 505     prev = k;
 506     assert(k != k->next_link(), "no loops!");
 507   }
 508   ShouldNotReachHere();   // should have found this class!!
 509 }
 510 
 511 void ClassLoaderData::unload() {
 512   _unloading = true;
 513 
 514   LogTarget(Trace, class, loader, data) lt;
 515   if (lt.is_enabled()) {
 516     ResourceMark rm;
 517     LogStream ls(lt);
 518     ls.print("unload");
 519     print_value_on(&ls);
 520     ls.cr();
 521   }
 522 
 523   // Some items on the _deallocate_list need to free their C heap structures
 524   // if they are not already on the _klasses list.
 525   free_deallocate_list_C_heap_structures();
 526 
 527   // Clean up class dependencies and tell serviceability tools
 528   // these classes are unloading.  Must be called
 529   // after erroneous classes are released.
 530   classes_do(InstanceKlass::unload_class);
 531 
 532   // Clean up global class iterator for compiler
 533   ClassLoaderDataGraph::adjust_saved_class(this);
 534 }
 535 
 536 ModuleEntryTable* ClassLoaderData::modules() {
 537   // Lazily create the module entry table at first request.
 538   // Lock-free access requires load_acquire.
 539   ModuleEntryTable* modules = OrderAccess::load_acquire(&_modules);
 540   if (modules == NULL) {
 541     MutexLocker m1(Module_lock);
 542     // Check if _modules got allocated while we were waiting for this lock.
 543     if ((modules = _modules) == NULL) {
 544       modules = new ModuleEntryTable(ModuleEntryTable::_moduletable_entry_size);
 545 
 546       {
 547         MutexLockerEx m1(metaspace_lock(), Mutex::_no_safepoint_check_flag);
 548         // Ensure _modules is stable, since it is examined without a lock
 549         OrderAccess::release_store(&_modules, modules);
 550       }
 551     }
 552   }
 553   return modules;
 554 }
 555 
 556 const int _boot_loader_dictionary_size    = 1009;
 557 const int _default_loader_dictionary_size = 107;
 558 
 559 Dictionary* ClassLoaderData::create_dictionary() {
 560   assert(!is_unsafe_anonymous(), "unsafe anonymous class loader data do not have a dictionary");
 561   int size;
 562   bool resizable = false;
 563   if (_the_null_class_loader_data == NULL) {
 564     size = _boot_loader_dictionary_size;
 565     resizable = true;
 566   } else if (class_loader()->is_a(SystemDictionary::reflect_DelegatingClassLoader_klass())) {
 567     size = 1;  // there's only one class in relection class loader and no initiated classes
 568   } else if (is_system_class_loader_data()) {
 569     size = _boot_loader_dictionary_size;
 570     resizable = true;
 571   } else {
 572     size = _default_loader_dictionary_size;
 573     resizable = true;
 574   }
 575   if (!DynamicallyResizeSystemDictionaries || DumpSharedSpaces) {
 576     resizable = false;
 577   }
 578   return new Dictionary(this, size, resizable);
 579 }
 580 
 581 // Tell the GC to keep this klass alive while iterating ClassLoaderDataGraph
 582 oop ClassLoaderData::holder_phantom() const {
 583   // A klass that was previously considered dead can be looked up in the
 584   // CLD/SD, and its _java_mirror or _class_loader can be stored in a root
 585   // or a reachable object making it alive again. The SATB part of G1 needs
 586   // to get notified about this potential resurrection, otherwise the marking
 587   // might not find the object.
 588   if (!_holder.is_null()) {  // NULL class_loader
 589     return _holder.resolve();
 590   } else {
 591     return NULL;
 592   }
 593 }
 594 
 595 // Let the GC read the holder without keeping it alive.
 596 oop ClassLoaderData::holder_no_keepalive() const {
 597   if (!_holder.is_null()) {  // NULL class_loader
 598     return _holder.peek();
 599   } else {
 600     return NULL;
 601   }
 602 }
 603 
 604 // Unloading support
 605 bool ClassLoaderData::is_alive() const {
 606   bool alive = keep_alive()         // null class loader and incomplete unsafe anonymous klasses.
 607       || (_holder.peek() != NULL);  // and not cleaned by the GC weak handle processing.
 608 
 609   return alive;
 610 }
 611 
 612 class ReleaseKlassClosure: public KlassClosure {
 613 private:
 614   size_t  _instance_class_released;
 615   size_t  _array_class_released;
 616 public:
 617   ReleaseKlassClosure() : _instance_class_released(0), _array_class_released(0) { }
 618 
 619   size_t instance_class_released() const { return _instance_class_released; }
 620   size_t array_class_released()    const { return _array_class_released;    }
 621 
 622   void do_klass(Klass* k) {
 623     if (k->is_array_klass()) {
 624       _array_class_released ++;
 625     } else {
 626       assert(k->is_instance_klass(), "Must be");
 627       _instance_class_released ++;
 628       InstanceKlass::release_C_heap_structures(InstanceKlass::cast(k));
 629     }
 630   }
 631 };
 632 
 633 ClassLoaderData::~ClassLoaderData() {
 634   // Release C heap structures for all the classes.
 635   ReleaseKlassClosure cl;
 636   classes_do(&cl);
 637 
 638   ClassLoaderDataGraph::dec_array_classes(cl.array_class_released());
 639   ClassLoaderDataGraph::dec_instance_classes(cl.instance_class_released());
 640 
 641   // Release the WeakHandle
 642   _holder.release();
 643 
 644   // Release C heap allocated hashtable for all the packages.
 645   if (_packages != NULL) {
 646     // Destroy the table itself
 647     delete _packages;
 648     _packages = NULL;
 649   }
 650 
 651   // Release C heap allocated hashtable for all the modules.
 652   if (_modules != NULL) {
 653     // Destroy the table itself
 654     delete _modules;
 655     _modules = NULL;
 656   }
 657 
 658   // Release C heap allocated hashtable for the dictionary
 659   if (_dictionary != NULL) {
 660     // Destroy the table itself
 661     delete _dictionary;
 662     _dictionary = NULL;
 663   }
 664 
 665   if (_unnamed_module != NULL) {
 666     _unnamed_module->delete_unnamed_module();
 667     _unnamed_module = NULL;
 668   }
 669 
 670   // release the metaspace
 671   ClassLoaderMetaspace *m = _metaspace;
 672   if (m != NULL) {
 673     _metaspace = NULL;
 674     delete m;
 675   }
 676   // Clear all the JNI handles for methods
 677   // These aren't deallocated and are going to look like a leak, but that's
 678   // needed because we can't really get rid of jmethodIDs because we don't
 679   // know when native code is going to stop using them.  The spec says that
 680   // they're "invalid" but existing programs likely rely on their being
 681   // NULL after class unloading.
 682   if (_jmethod_ids != NULL) {
 683     Method::clear_jmethod_ids(this);
 684   }
 685   // Delete lock
 686   delete _metaspace_lock;
 687 
 688   // Delete free list
 689   if (_deallocate_list != NULL) {
 690     delete _deallocate_list;
 691   }
 692 
 693   // Decrement refcounts of Symbols if created.
 694   if (_name != NULL) {
 695     _name->decrement_refcount();
 696   }
 697   if (_name_and_id != NULL) {
 698     _name_and_id->decrement_refcount();
 699   }
 700 }
 701 
 702 // Returns true if this class loader data is for the app class loader
 703 // or a user defined system class loader.  (Note that the class loader
 704 // data may be unsafe anonymous.)
 705 bool ClassLoaderData::is_system_class_loader_data() const {
 706   return SystemDictionary::is_system_class_loader(class_loader());
 707 }
 708 
 709 // Returns true if this class loader data is for the platform class loader.
 710 // (Note that the class loader data may be unsafe anonymous.)
 711 bool ClassLoaderData::is_platform_class_loader_data() const {
 712   return SystemDictionary::is_platform_class_loader(class_loader());
 713 }
 714 
 715 // Returns true if the class loader for this class loader data is one of
 716 // the 3 builtin (boot application/system or platform) class loaders,
 717 // including a user-defined system class loader.  Note that if the class
 718 // loader data is for an unsafe anonymous class then it may get freed by a GC
 719 // even if its class loader is one of these loaders.
 720 bool ClassLoaderData::is_builtin_class_loader_data() const {
 721   return (is_boot_class_loader_data() ||
 722           SystemDictionary::is_system_class_loader(class_loader()) ||
 723           SystemDictionary::is_platform_class_loader(class_loader()));
 724 }
 725 
 726 // Returns true if this class loader data is a class loader data
 727 // that is not ever freed by a GC.  It must be the CLD for one of the builtin
 728 // class loaders and not the CLD for an unsafe anonymous class.
 729 bool ClassLoaderData::is_permanent_class_loader_data() const {
 730   return is_builtin_class_loader_data() && !is_unsafe_anonymous();
 731 }
 732 
 733 ClassLoaderMetaspace* ClassLoaderData::metaspace_non_null() {
 734   // If the metaspace has not been allocated, create a new one.  Might want
 735   // to create smaller arena for Reflection class loaders also.
 736   // The reason for the delayed allocation is because some class loaders are
 737   // simply for delegating with no metadata of their own.
 738   // Lock-free access requires load_acquire.
 739   ClassLoaderMetaspace* metaspace = OrderAccess::load_acquire(&_metaspace);
 740   if (metaspace == NULL) {
 741     MutexLockerEx ml(_metaspace_lock,  Mutex::_no_safepoint_check_flag);
 742     // Check if _metaspace got allocated while we were waiting for this lock.
 743     if ((metaspace = _metaspace) == NULL) {
 744       if (this == the_null_class_loader_data()) {
 745         assert (class_loader() == NULL, "Must be");
 746         metaspace = new ClassLoaderMetaspace(_metaspace_lock, Metaspace::BootMetaspaceType);
 747       } else if (is_unsafe_anonymous()) {
 748         metaspace = new ClassLoaderMetaspace(_metaspace_lock, Metaspace::UnsafeAnonymousMetaspaceType);
 749       } else if (class_loader()->is_a(SystemDictionary::reflect_DelegatingClassLoader_klass())) {
 750         metaspace = new ClassLoaderMetaspace(_metaspace_lock, Metaspace::ReflectionMetaspaceType);
 751       } else {
 752         metaspace = new ClassLoaderMetaspace(_metaspace_lock, Metaspace::StandardMetaspaceType);
 753       }
 754       // Ensure _metaspace is stable, since it is examined without a lock
 755       OrderAccess::release_store(&_metaspace, metaspace);
 756     }
 757   }
 758   return metaspace;
 759 }
 760 
 761 OopHandle ClassLoaderData::add_handle(Handle h) {
 762   MutexLockerEx ml(metaspace_lock(),  Mutex::_no_safepoint_check_flag);
 763   record_modified_oops();
 764   return OopHandle(_handles.add(h()));
 765 }
 766 
 767 void ClassLoaderData::remove_handle(OopHandle h) {
 768   assert(!is_unloading(), "Do not remove a handle for a CLD that is unloading");
 769   oop* ptr = h.ptr_raw();
 770   if (ptr != NULL) {
 771     assert(_handles.owner_of(ptr), "Got unexpected handle " PTR_FORMAT, p2i(ptr));
 772     NativeAccess<>::oop_store(ptr, oop(NULL));
 773   }
 774 }
 775 
 776 void ClassLoaderData::init_handle_locked(OopHandle& dest, Handle h) {
 777   MutexLockerEx ml(metaspace_lock(),  Mutex::_no_safepoint_check_flag);
 778   if (dest.resolve() != NULL) {
 779     return;
 780   } else {
 781     dest = _handles.add(h());
 782   }
 783 }
 784 
 785 // Add this metadata pointer to be freed when it's safe.  This is only during
 786 // a safepoint which checks if handles point to this metadata field.
 787 void ClassLoaderData::add_to_deallocate_list(Metadata* m) {
 788   // Metadata in shared region isn't deleted.
 789   if (!m->is_shared()) {
 790     MutexLockerEx ml(metaspace_lock(),  Mutex::_no_safepoint_check_flag);
 791     if (_deallocate_list == NULL) {
 792       _deallocate_list = new (ResourceObj::C_HEAP, mtClass) GrowableArray<Metadata*>(100, true);
 793     }
 794     _deallocate_list->append_if_missing(m);
 795     log_debug(class, loader, data)("deallocate added for %s", m->print_value_string());
 796     ClassLoaderDataGraph::set_should_clean_deallocate_lists();
 797   }
 798 }
 799 
 800 // Deallocate free metadata on the free list.  How useful the PermGen was!
 801 void ClassLoaderData::free_deallocate_list() {
 802   // Don't need lock, at safepoint
 803   assert(SafepointSynchronize::is_at_safepoint(), "only called at safepoint");
 804   assert(!is_unloading(), "only called for ClassLoaderData that are not unloading");
 805   if (_deallocate_list == NULL) {
 806     return;
 807   }
 808   // Go backwards because this removes entries that are freed.
 809   for (int i = _deallocate_list->length() - 1; i >= 0; i--) {
 810     Metadata* m = _deallocate_list->at(i);
 811     if (!m->on_stack()) {
 812       _deallocate_list->remove_at(i);
 813       // There are only three types of metadata that we deallocate directly.
 814       // Cast them so they can be used by the template function.
 815       if (m->is_method()) {
 816         MetadataFactory::free_metadata(this, (Method*)m);
 817       } else if (m->is_constantPool()) {
 818         MetadataFactory::free_metadata(this, (ConstantPool*)m);
 819       } else if (m->is_klass()) {
 820         MetadataFactory::free_metadata(this, (InstanceKlass*)m);
 821       } else {
 822         ShouldNotReachHere();
 823       }
 824     } else {
 825       // Metadata is alive.
 826       // If scratch_class is on stack then it shouldn't be on this list!
 827       assert(!m->is_klass() || !((InstanceKlass*)m)->is_scratch_class(),
 828              "scratch classes on this list should be dead");
 829       // Also should assert that other metadata on the list was found in handles.
 830       // Some cleaning remains.
 831       ClassLoaderDataGraph::set_should_clean_deallocate_lists();
 832     }
 833   }
 834 }
 835 
 836 // This is distinct from free_deallocate_list.  For class loader data that are
 837 // unloading, this frees the C heap memory for items on the list, and unlinks
 838 // scratch or error classes so that unloading events aren't triggered for these
 839 // classes. The metadata is removed with the unloading metaspace.
 840 // There isn't C heap memory allocated for methods, so nothing is done for them.
 841 void ClassLoaderData::free_deallocate_list_C_heap_structures() {
 842   // Don't need lock, at safepoint
 843   assert(SafepointSynchronize::is_at_safepoint(), "only called at safepoint");
 844   assert(is_unloading(), "only called for ClassLoaderData that are unloading");
 845   if (_deallocate_list == NULL) {
 846     return;
 847   }
 848   // Go backwards because this removes entries that are freed.
 849   for (int i = _deallocate_list->length() - 1; i >= 0; i--) {
 850     Metadata* m = _deallocate_list->at(i);
 851     _deallocate_list->remove_at(i);
 852     if (m->is_constantPool()) {
 853       ((ConstantPool*)m)->release_C_heap_structures();
 854     } else if (m->is_klass()) {
 855       InstanceKlass* ik = (InstanceKlass*)m;
 856       // also releases ik->constants() C heap memory
 857       InstanceKlass::release_C_heap_structures(ik);
 858       // Remove the class so unloading events aren't triggered for
 859       // this class (scratch or error class) in do_unloading().
 860       remove_class(ik);
 861     }
 862   }
 863 }
 864 
 865 // These CLDs are to contain unsafe anonymous classes used for JSR292
 866 ClassLoaderData* ClassLoaderData::unsafe_anonymous_class_loader_data(Handle loader) {
 867   // Add a new class loader data to the graph.
 868   return ClassLoaderDataGraph::add(loader, true);
 869 }
 870 
 871 // Caller needs ResourceMark
 872 // If the class loader's _name has not been explicitly set, the class loader's
 873 // qualified class name is returned.
 874 const char* ClassLoaderData::loader_name() const {
 875    if (_class_loader_klass == NULL) {
 876      return BOOTSTRAP_LOADER_NAME;
 877    } else if (_name != NULL) {
 878      return _name->as_C_string();
 879    } else {
 880      return _class_loader_klass->external_name();
 881    }
 882 }
 883 
 884 // Caller needs ResourceMark
 885 // Format of the _name_and_id is as follows:
 886 //   If the defining loader has a name explicitly set then '<loader-name>' @<id>
 887 //   If the defining loader has no name then <qualified-class-name> @<id>
 888 //   If built-in loader, then omit '@<id>' as there is only one instance.
 889 const char* ClassLoaderData::loader_name_and_id() const {
 890   if (_class_loader_klass == NULL) {
 891     return "'" BOOTSTRAP_LOADER_NAME "'";
 892   } else if (_name_and_id != NULL) {
 893     return _name_and_id->as_C_string();
 894   } else {
 895     // May be called in a race before _name_and_id is initialized.
 896     return _class_loader_klass->external_name();
 897   }
 898 }
 899 
 900 void ClassLoaderData::print_value_on(outputStream* out) const {
 901   if (!is_unloading() && class_loader() != NULL) {
 902     out->print("loader data: " INTPTR_FORMAT " for instance ", p2i(this));
 903     class_loader()->print_value_on(out);  // includes loader_name_and_id() and address of class loader instance
 904   } else {
 905     // loader data: 0xsomeaddr of 'bootstrap'
 906     out->print("loader data: " INTPTR_FORMAT " of %s", p2i(this), loader_name_and_id());
 907   }
 908   if (is_unsafe_anonymous()) {
 909     out->print(" unsafe anonymous");
 910   }
 911 }
 912 
 913 #ifndef PRODUCT
 914 void ClassLoaderData::print_on(outputStream* out) const {
 915   out->print("ClassLoaderData CLD: " PTR_FORMAT ", loader: " PTR_FORMAT ", loader_klass: %s {",
 916               p2i(this), p2i(_class_loader.ptr_raw()), loader_name_and_id());
 917   if (is_unsafe_anonymous()) out->print(" unsafe anonymous");
 918   if (claimed()) out->print(" claimed");
 919   if (is_unloading()) out->print(" unloading");
 920   out->print(" metaspace: " INTPTR_FORMAT, p2i(metaspace_or_null()));
 921 
 922   if (_jmethod_ids != NULL) {
 923     Method::print_jmethod_ids(this, out);
 924   }
 925   out->print(" handles count %d", _handles.count());
 926   out->print(" dependencies %d", _dependency_count);
 927   out->print_cr("}");
 928 }
 929 #endif // PRODUCT
 930 
 931 void ClassLoaderData::verify() {
 932   assert_locked_or_safepoint(_metaspace_lock);
 933   oop cl = class_loader();
 934 
 935   guarantee(this == class_loader_data(cl) || is_unsafe_anonymous(), "Must be the same");
 936   guarantee(cl != NULL || this == ClassLoaderData::the_null_class_loader_data() || is_unsafe_anonymous(), "must be");
 937 
 938   // Verify the integrity of the allocated space.
 939   if (metaspace_or_null() != NULL) {
 940     metaspace_or_null()->verify();
 941   }
 942 
 943   for (Klass* k = _klasses; k != NULL; k = k->next_link()) {
 944     guarantee(k->class_loader_data() == this, "Must be the same");
 945     k->verify();
 946     assert(k != k->next_link(), "no loops!");
 947   }
 948 }
 949 
 950 bool ClassLoaderData::contains_klass(Klass* klass) {
 951   // Lock-free access requires load_acquire
 952   for (Klass* k = OrderAccess::load_acquire(&_klasses); k != NULL; k = k->next_link()) {
 953     if (k == klass) return true;
 954   }
 955   return false;
 956 }