1 /*
   2  * Copyright (c) 2012, 2016, 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/javaClasses.hpp"
  53 #include "classfile/metadataOnStackMark.hpp"
  54 #include "classfile/moduleEntry.hpp"
  55 #include "classfile/packageEntry.hpp"
  56 #include "classfile/systemDictionary.hpp"
  57 #include "code/codeCache.hpp"
  58 #include "gc/shared/gcLocker.hpp"
  59 #include "logging/log.hpp"
  60 #include "memory/metadataFactory.hpp"
  61 #include "memory/metaspaceShared.hpp"
  62 #include "memory/oopFactory.hpp"
  63 #include "memory/resourceArea.hpp"
  64 #include "oops/objArrayOop.inline.hpp"
  65 #include "oops/oop.inline.hpp"
  66 #include "runtime/atomic.inline.hpp"
  67 #include "runtime/javaCalls.hpp"
  68 #include "runtime/jniHandles.hpp"
  69 #include "runtime/mutex.hpp"
  70 #include "runtime/orderAccess.hpp"
  71 #include "runtime/safepoint.hpp"
  72 #include "runtime/synchronizer.hpp"
  73 #include "utilities/growableArray.hpp"
  74 #include "utilities/macros.hpp"
  75 #include "utilities/ostream.hpp"
  76 #if INCLUDE_TRACE
  77 #include "trace/tracing.hpp"
  78 #endif
  79 
  80 // helper function to avoid in-line casts
  81 template <typename T> static T* load_ptr_acquire(T* volatile *p) {
  82   return static_cast<T*>(OrderAccess::load_ptr_acquire(p));
  83 }
  84 
  85 ClassLoaderData * ClassLoaderData::_the_null_class_loader_data = NULL;
  86 
  87 ClassLoaderData::ClassLoaderData(Handle h_class_loader, bool is_anonymous, Dependencies dependencies) :
  88   _class_loader(h_class_loader()),
  89   _is_anonymous(is_anonymous),
  90   // An anonymous class loader data doesn't have anything to keep
  91   // it from being unloaded during parsing of the anonymous class.
  92   // The null-class-loader should always be kept alive.
  93   _keep_alive((is_anonymous || h_class_loader.is_null()) ? 1 : 0),
  94   _metaspace(NULL), _unloading(false), _klasses(NULL),
  95   _modules(NULL), _packages(NULL),
  96   _claimed(0), _jmethod_ids(NULL), _handles(NULL), _deallocate_list(NULL),
  97   _next(NULL), _dependencies(dependencies), _shared_class_loader_id(-1),
  98   _metaspace_lock(new Mutex(Monitor::leaf+1, "Metaspace allocation lock", true,
  99                             Monitor::_safepoint_check_never)) {
 100     // empty
 101 }
 102 
 103 void ClassLoaderData::init_dependencies(TRAPS) {
 104   assert(!Universe::is_fully_initialized(), "should only be called when initializing");
 105   assert(is_the_null_class_loader_data(), "should only call this for the null class loader");
 106   _dependencies.init(CHECK);
 107 }
 108 
 109 void ClassLoaderData::Dependencies::init(TRAPS) {
 110   // Create empty dependencies array to add to. CMS requires this to be
 111   // an oop so that it can track additions via card marks.  We think.
 112   _list_head = oopFactory::new_objectArray(2, CHECK);
 113 }
 114 
 115 bool ClassLoaderData::claim() {
 116   if (_claimed == 1) {
 117     return false;
 118   }
 119 
 120   return (int) Atomic::cmpxchg(1, &_claimed, 0) == 0;
 121 }
 122 
 123 // Anonymous classes have their own ClassLoaderData that is marked to keep alive
 124 // while the class is being parsed, and if the class appears on the module fixup list.
 125 // Due to the uniqueness that no other class shares the anonymous class' name or
 126 // ClassLoaderData, no other non-GC thread has knowledge of the anonymous class while
 127 // it is being defined, therefore _keep_alive is not volatile or atomic.
 128 void ClassLoaderData::inc_keep_alive() {
 129   assert(_keep_alive >= 0, "Invalid keep alive count");
 130   _keep_alive++;
 131 }
 132 
 133 void ClassLoaderData::dec_keep_alive() {
 134   assert(_keep_alive > 0, "Invalid keep alive count");
 135   _keep_alive--;
 136 }
 137 
 138 void ClassLoaderData::oops_do(OopClosure* f, KlassClosure* klass_closure, bool must_claim) {
 139   if (must_claim && !claim()) {
 140     return;
 141   }
 142 
 143   f->do_oop(&_class_loader);
 144   _dependencies.oops_do(f);
 145   _handles->oops_do(f);
 146   if (klass_closure != NULL) {
 147     classes_do(klass_closure);
 148   }
 149 }
 150 
 151 void ClassLoaderData::Dependencies::oops_do(OopClosure* f) {
 152   f->do_oop((oop*)&_list_head);
 153 }
 154 
 155 void ClassLoaderData::classes_do(KlassClosure* klass_closure) {
 156   // Lock-free access requires load_ptr_acquire
 157   for (Klass* k = load_ptr_acquire(&_klasses); k != NULL; k = k->next_link()) {
 158     klass_closure->do_klass(k);
 159     assert(k != k->next_link(), "no loops!");
 160   }
 161 }
 162 
 163 void ClassLoaderData::classes_do(void f(Klass * const)) {
 164   assert_locked_or_safepoint(_metaspace_lock);
 165   for (Klass* k = _klasses; k != NULL; k = k->next_link()) {
 166     f(k);
 167   }
 168 }
 169 
 170 void ClassLoaderData::methods_do(void f(Method*)) {
 171   // Lock-free access requires load_ptr_acquire
 172   for (Klass* k = load_ptr_acquire(&_klasses); k != NULL; k = k->next_link()) {
 173     if (k->is_instance_klass()) {
 174       InstanceKlass::cast(k)->methods_do(f);
 175     }
 176   }
 177 }
 178 
 179 void ClassLoaderData::loaded_classes_do(KlassClosure* klass_closure) {
 180   // Lock to avoid classes being modified/added/removed during iteration
 181   MutexLockerEx ml(metaspace_lock(),  Mutex::_no_safepoint_check_flag);
 182   for (Klass* k = _klasses; k != NULL; k = k->next_link()) {
 183     // Do not filter ArrayKlass oops here...
 184     if (k->is_array_klass() || (k->is_instance_klass() && InstanceKlass::cast(k)->is_loaded())) {
 185       klass_closure->do_klass(k);
 186     }
 187   }
 188 }
 189 
 190 void ClassLoaderData::classes_do(void f(InstanceKlass*)) {
 191   // Lock-free access requires load_ptr_acquire
 192   for (Klass* k = load_ptr_acquire(&_klasses); k != NULL; k = k->next_link()) {
 193     if (k->is_instance_klass()) {
 194       f(InstanceKlass::cast(k));
 195     }
 196     assert(k != k->next_link(), "no loops!");
 197   }
 198 }
 199 
 200 void ClassLoaderData::modules_do(void f(ModuleEntry*)) {
 201   assert_locked_or_safepoint(Module_lock);
 202   if (_modules != NULL) {
 203     for (int i = 0; i < _modules->table_size(); i++) {
 204       for (ModuleEntry* entry = _modules->bucket(i);
 205                               entry != NULL;
 206                               entry = entry->next()) {
 207         f(entry);
 208       }
 209     }
 210   }
 211 }
 212 
 213 void ClassLoaderData::packages_do(void f(PackageEntry*)) {
 214   // Lock-free access requires load_ptr_acquire
 215   PackageEntryTable* packages = load_ptr_acquire(&_packages);
 216   if (packages != NULL) {
 217     for (int i = 0; i < packages->table_size(); i++) {
 218       for (PackageEntry* entry = packages->bucket(i);
 219                               entry != NULL;
 220                               entry = entry->next()) {
 221         f(entry);
 222       }
 223     }
 224   }
 225 }
 226 
 227 void ClassLoaderData::record_dependency(const Klass* k, TRAPS) {
 228   assert(k != NULL, "invariant");
 229 
 230   ClassLoaderData * const from_cld = this;
 231   ClassLoaderData * const to_cld = k->class_loader_data();
 232 
 233   // Dependency to the null class loader data doesn't need to be recorded
 234   // because the null class loader data never goes away.
 235   if (to_cld->is_the_null_class_loader_data()) {
 236     return;
 237   }
 238 
 239   oop to;
 240   if (to_cld->is_anonymous()) {
 241     // Anonymous class dependencies are through the mirror.
 242     to = k->java_mirror();
 243   } else {
 244     to = to_cld->class_loader();
 245 
 246     // If from_cld is anonymous, even if it's class_loader is a parent of 'to'
 247     // we still have to add it.  The class_loader won't keep from_cld alive.
 248     if (!from_cld->is_anonymous()) {
 249       // Check that this dependency isn't from the same or parent class_loader
 250       oop from = from_cld->class_loader();
 251 
 252       oop curr = from;
 253       while (curr != NULL) {
 254         if (curr == to) {
 255           return; // this class loader is in the parent list, no need to add it.
 256         }
 257         curr = java_lang_ClassLoader::parent(curr);
 258       }
 259     }
 260   }
 261 
 262   // It's a dependency we won't find through GC, add it. This is relatively rare
 263   // Must handle over GC point.
 264   Handle dependency(THREAD, to);
 265   from_cld->_dependencies.add(dependency, CHECK);
 266 }
 267 
 268 
 269 void ClassLoaderData::Dependencies::add(Handle dependency, TRAPS) {
 270   // Check first if this dependency is already in the list.
 271   // Save a pointer to the last to add to under the lock.
 272   objArrayOop ok = _list_head;
 273   objArrayOop last = NULL;
 274   while (ok != NULL) {
 275     last = ok;
 276     if (ok->obj_at(0) == dependency()) {
 277       // Don't need to add it
 278       return;
 279     }
 280     ok = (objArrayOop)ok->obj_at(1);
 281   }
 282 
 283   // Must handle over GC points
 284   assert (last != NULL, "dependencies should be initialized");
 285   objArrayHandle last_handle(THREAD, last);
 286 
 287   // Create a new dependency node with fields for (class_loader or mirror, next)
 288   objArrayOop deps = oopFactory::new_objectArray(2, CHECK);
 289   deps->obj_at_put(0, dependency());
 290 
 291   // Must handle over GC points
 292   objArrayHandle new_dependency(THREAD, deps);
 293 
 294   // Add the dependency under lock
 295   locked_add(last_handle, new_dependency, THREAD);
 296 }
 297 
 298 void ClassLoaderData::Dependencies::locked_add(objArrayHandle last_handle,
 299                                                objArrayHandle new_dependency,
 300                                                Thread* THREAD) {
 301 
 302   // Have to lock and put the new dependency on the end of the dependency
 303   // array so the card mark for CMS sees that this dependency is new.
 304   // Can probably do this lock free with some effort.
 305   ObjectLocker ol(Handle(THREAD, _list_head), THREAD);
 306 
 307   oop loader_or_mirror = new_dependency->obj_at(0);
 308 
 309   // Since the dependencies are only added, add to the end.
 310   objArrayOop end = last_handle();
 311   objArrayOop last = NULL;
 312   while (end != NULL) {
 313     last = end;
 314     // check again if another thread added it to the end.
 315     if (end->obj_at(0) == loader_or_mirror) {
 316       // Don't need to add it
 317       return;
 318     }
 319     end = (objArrayOop)end->obj_at(1);
 320   }
 321   assert (last != NULL, "dependencies should be initialized");
 322   // fill in the first element with the oop in new_dependency.
 323   if (last->obj_at(0) == NULL) {
 324     last->obj_at_put(0, new_dependency->obj_at(0));
 325   } else {
 326     last->obj_at_put(1, new_dependency());
 327   }
 328 }
 329 
 330 void ClassLoaderDataGraph::clear_claimed_marks() {
 331   for (ClassLoaderData* cld = _head; cld != NULL; cld = cld->next()) {
 332     cld->clear_claimed();
 333   }
 334 }
 335 
 336 void ClassLoaderData::add_class(Klass* k, bool publicize /* true */) {
 337   {
 338     MutexLockerEx ml(metaspace_lock(), Mutex::_no_safepoint_check_flag);
 339     Klass* old_value = _klasses;
 340     k->set_next_link(old_value);
 341     // Link the new item into the list, making sure the linked class is stable
 342     // since the list can be walked without a lock
 343     OrderAccess::release_store_ptr(&_klasses, k);
 344   }
 345 
 346   if (publicize && k->class_loader_data() != NULL) {
 347     ResourceMark rm;
 348     log_trace(class, loader, data)("Adding k: " PTR_FORMAT " %s to CLD: "
 349                   PTR_FORMAT " loader: " PTR_FORMAT " %s",
 350                   p2i(k),
 351                   k->external_name(),
 352                   p2i(k->class_loader_data()),
 353                   p2i((void *)k->class_loader()),
 354                   loader_name());
 355   }
 356 }
 357 
 358 // Remove a klass from the _klasses list for scratch_class during redefinition
 359 // or parsed class in the case of an error.
 360 void ClassLoaderData::remove_class(Klass* scratch_class) {
 361   assert(SafepointSynchronize::is_at_safepoint(), "only called at safepoint");
 362   Klass* prev = NULL;
 363   for (Klass* k = _klasses; k != NULL; k = k->next_link()) {
 364     if (k == scratch_class) {
 365       if (prev == NULL) {
 366         _klasses = k->next_link();
 367       } else {
 368         Klass* next = k->next_link();
 369         prev->set_next_link(next);
 370       }
 371       return;
 372     }
 373     prev = k;
 374     assert(k != k->next_link(), "no loops!");
 375   }
 376   ShouldNotReachHere();   // should have found this class!!
 377 }
 378 
 379 void ClassLoaderData::unload() {
 380   _unloading = true;
 381 
 382   // Tell serviceability tools these classes are unloading
 383   classes_do(InstanceKlass::notify_unload_class);
 384 
 385   if (log_is_enabled(Debug, class, loader, data)) {
 386     ResourceMark rm;
 387     outputStream* log = Log(class, loader, data)::debug_stream();
 388     log->print(": unload loader data " INTPTR_FORMAT, p2i(this));
 389     log->print(" for instance " INTPTR_FORMAT " of %s", p2i((void *)class_loader()),
 390                loader_name());
 391     if (is_anonymous()) {
 392       log->print(" for anonymous class  " INTPTR_FORMAT " ", p2i(_klasses));
 393     }
 394     log->cr();
 395   }
 396 
 397   // In some rare cases items added to this list will not be freed elsewhere.
 398   // To keep it simple, just free everything in it here.
 399   free_deallocate_list();
 400 }
 401 
 402 PackageEntryTable* ClassLoaderData::packages() {
 403   // Lazily create the package entry table at first request.
 404   // Lock-free access requires load_ptr_acquire.
 405   PackageEntryTable* packages = load_ptr_acquire(&_packages);
 406   if (packages == NULL) {
 407     MutexLockerEx m1(metaspace_lock(), Mutex::_no_safepoint_check_flag);
 408     // Check if _packages got allocated while we were waiting for this lock.
 409     if ((packages = _packages) == NULL) {
 410       packages = new PackageEntryTable(PackageEntryTable::_packagetable_entry_size);
 411       // Ensure _packages is stable, since it is examined without a lock
 412       OrderAccess::release_store_ptr(&_packages, packages);
 413     }
 414   }
 415   return packages;
 416 }
 417 
 418 ModuleEntryTable* ClassLoaderData::modules() {
 419   // Lazily create the module entry table at first request.
 420   // Lock-free access requires load_ptr_acquire.
 421   ModuleEntryTable* modules = load_ptr_acquire(&_modules);
 422   if (modules == NULL) {
 423     MutexLocker m1(Module_lock);
 424     // Check if _modules got allocated while we were waiting for this lock.
 425     if ((modules = _modules) == NULL) {
 426       modules = new ModuleEntryTable(ModuleEntryTable::_moduletable_entry_size);
 427       // Each loader has one unnamed module entry. Create it before
 428       // any classes, loaded by this loader, are defined in case
 429       // they end up being defined in loader's unnamed module.
 430       modules->create_unnamed_module(this);
 431 
 432       {
 433         MutexLockerEx m1(metaspace_lock(), Mutex::_no_safepoint_check_flag);
 434         // Ensure _modules is stable, since it is examined without a lock
 435         OrderAccess::release_store_ptr(&_modules, modules);
 436       }
 437     }
 438   }
 439   return modules;
 440 }
 441 
 442 oop ClassLoaderData::keep_alive_object() const {
 443   assert_locked_or_safepoint(_metaspace_lock);
 444   assert(!keep_alive(), "Don't use with CLDs that are artificially kept alive");
 445   return is_anonymous() ? _klasses->java_mirror() : class_loader();
 446 }
 447 
 448 bool ClassLoaderData::is_alive(BoolObjectClosure* is_alive_closure) const {
 449   bool alive = keep_alive() // null class loader and incomplete anonymous klasses.
 450       || is_alive_closure->do_object_b(keep_alive_object());
 451 
 452   return alive;
 453 }
 454 
 455 
 456 ClassLoaderData::~ClassLoaderData() {
 457   // Release C heap structures for all the classes.
 458   classes_do(InstanceKlass::release_C_heap_structures);
 459 
 460   // Release C heap allocated hashtable for all the packages.
 461   if (_packages != NULL) {
 462     // Destroy the table itself
 463     delete _packages;
 464     _packages = NULL;
 465   }
 466 
 467   // Release C heap allocated hashtable for all the modules.
 468   if (_modules != NULL) {
 469     // Destroy the table itself
 470     delete _modules;
 471     _modules = NULL;
 472   }
 473 
 474   // release the metaspace
 475   Metaspace *m = _metaspace;
 476   if (m != NULL) {
 477     _metaspace = NULL;
 478     delete m;
 479   }
 480   // release the handles
 481   if (_handles != NULL) {
 482     JNIHandleBlock::release_block(_handles);
 483     _handles = NULL;
 484   }
 485 
 486   // Clear all the JNI handles for methods
 487   // These aren't deallocated and are going to look like a leak, but that's
 488   // needed because we can't really get rid of jmethodIDs because we don't
 489   // know when native code is going to stop using them.  The spec says that
 490   // they're "invalid" but existing programs likely rely on their being
 491   // NULL after class unloading.
 492   if (_jmethod_ids != NULL) {
 493     Method::clear_jmethod_ids(this);
 494   }
 495   // Delete lock
 496   delete _metaspace_lock;
 497 
 498   // Delete free list
 499   if (_deallocate_list != NULL) {
 500     delete _deallocate_list;
 501   }
 502 }
 503 
 504 /**
 505  * Returns true if this class loader data is for the platform class loader.
 506  */
 507 bool ClassLoaderData::is_platform_class_loader_data() const {
 508   return SystemDictionary::is_platform_class_loader(class_loader());
 509 }
 510 
 511 Metaspace* ClassLoaderData::metaspace_non_null() {
 512   assert(!DumpSharedSpaces, "wrong metaspace!");
 513   // If the metaspace has not been allocated, create a new one.  Might want
 514   // to create smaller arena for Reflection class loaders also.
 515   // The reason for the delayed allocation is because some class loaders are
 516   // simply for delegating with no metadata of their own.
 517   // Lock-free access requires load_ptr_acquire.
 518   Metaspace* metaspace = load_ptr_acquire(&_metaspace);
 519   if (metaspace == NULL) {
 520     MutexLockerEx ml(_metaspace_lock,  Mutex::_no_safepoint_check_flag);
 521     // Check if _metaspace got allocated while we were waiting for this lock.
 522     if ((metaspace = _metaspace) == NULL) {
 523       if (this == the_null_class_loader_data()) {
 524         assert (class_loader() == NULL, "Must be");
 525         metaspace = new Metaspace(_metaspace_lock, Metaspace::BootMetaspaceType);
 526       } else if (is_anonymous()) {
 527         if (class_loader() != NULL) {
 528           log_trace(class, loader, data)("is_anonymous: %s", class_loader()->klass()->internal_name());
 529         }
 530         metaspace = new Metaspace(_metaspace_lock, Metaspace::AnonymousMetaspaceType);
 531       } else if (class_loader()->is_a(SystemDictionary::reflect_DelegatingClassLoader_klass())) {
 532         if (class_loader() != NULL) {
 533           log_trace(class, loader, data)("is_reflection: %s", class_loader()->klass()->internal_name());
 534         }
 535         metaspace = new Metaspace(_metaspace_lock, Metaspace::ReflectionMetaspaceType);
 536       } else {
 537         metaspace = new Metaspace(_metaspace_lock, Metaspace::StandardMetaspaceType);
 538       }
 539       // Ensure _metaspace is stable, since it is examined without a lock
 540       OrderAccess::release_store_ptr(&_metaspace, metaspace);
 541     }
 542   }
 543   return metaspace;
 544 }
 545 
 546 JNIHandleBlock* ClassLoaderData::handles() const           { return _handles; }
 547 void ClassLoaderData::set_handles(JNIHandleBlock* handles) { _handles = handles; }
 548 
 549 jobject ClassLoaderData::add_handle(Handle h) {
 550   MutexLockerEx ml(metaspace_lock(),  Mutex::_no_safepoint_check_flag);
 551   if (handles() == NULL) {
 552     set_handles(JNIHandleBlock::allocate_block());
 553   }
 554   return handles()->allocate_handle(h());
 555 }
 556 
 557 void ClassLoaderData::remove_handle(jobject h) {
 558   _handles->release_handle(h);
 559 }
 560 
 561 // Add this metadata pointer to be freed when it's safe.  This is only during
 562 // class unloading because Handles might point to this metadata field.
 563 void ClassLoaderData::add_to_deallocate_list(Metadata* m) {
 564   // Metadata in shared region isn't deleted.
 565   if (!m->is_shared()) {
 566     MutexLockerEx ml(metaspace_lock(),  Mutex::_no_safepoint_check_flag);
 567     if (_deallocate_list == NULL) {
 568       _deallocate_list = new (ResourceObj::C_HEAP, mtClass) GrowableArray<Metadata*>(100, true);
 569     }
 570     _deallocate_list->append_if_missing(m);
 571   }
 572 }
 573 
 574 // Deallocate free metadata on the free list.  How useful the PermGen was!
 575 void ClassLoaderData::free_deallocate_list() {
 576   // Don't need lock, at safepoint
 577   assert(SafepointSynchronize::is_at_safepoint(), "only called at safepoint");
 578   if (_deallocate_list == NULL) {
 579     return;
 580   }
 581   // Go backwards because this removes entries that are freed.
 582   for (int i = _deallocate_list->length() - 1; i >= 0; i--) {
 583     Metadata* m = _deallocate_list->at(i);
 584     if (!m->on_stack()) {
 585       _deallocate_list->remove_at(i);
 586       // There are only three types of metadata that we deallocate directly.
 587       // Cast them so they can be used by the template function.
 588       if (m->is_method()) {
 589         MetadataFactory::free_metadata(this, (Method*)m);
 590       } else if (m->is_constantPool()) {
 591         MetadataFactory::free_metadata(this, (ConstantPool*)m);
 592       } else if (m->is_klass()) {
 593         MetadataFactory::free_metadata(this, (InstanceKlass*)m);
 594       } else {
 595         ShouldNotReachHere();
 596       }
 597     } else {
 598       // Metadata is alive.
 599       // If scratch_class is on stack then it shouldn't be on this list!
 600       assert(!m->is_klass() || !((InstanceKlass*)m)->is_scratch_class(),
 601              "scratch classes on this list should be dead");
 602       // Also should assert that other metadata on the list was found in handles.
 603     }
 604   }
 605 }
 606 
 607 // These anonymous class loaders are to contain classes used for JSR292
 608 ClassLoaderData* ClassLoaderData::anonymous_class_loader_data(oop loader, TRAPS) {
 609   // Add a new class loader data to the graph.
 610   return ClassLoaderDataGraph::add(loader, true, THREAD);
 611 }
 612 
 613 const char* ClassLoaderData::loader_name() {
 614   // Handles null class loader
 615   return SystemDictionary::loader_name(class_loader());
 616 }
 617 
 618 #ifndef PRODUCT
 619 // Define to dump klasses
 620 #undef CLD_DUMP_KLASSES
 621 
 622 void ClassLoaderData::dump(outputStream * const out) {
 623   ResourceMark rm;
 624   out->print("ClassLoaderData CLD: " PTR_FORMAT ", loader: " PTR_FORMAT ", loader_klass: " PTR_FORMAT " %s {",
 625       p2i(this), p2i((void *)class_loader()),
 626       p2i(class_loader() != NULL ? class_loader()->klass() : NULL), loader_name());
 627   if (claimed()) out->print(" claimed ");
 628   if (is_unloading()) out->print(" unloading ");
 629   out->print(" handles " INTPTR_FORMAT, p2i(handles()));
 630   out->cr();
 631   if (metaspace_or_null() != NULL) {
 632     out->print_cr("metaspace: " INTPTR_FORMAT, p2i(metaspace_or_null()));
 633     metaspace_or_null()->dump(out);
 634   } else {
 635     out->print_cr("metaspace: NULL");
 636   }
 637 
 638 #ifdef CLD_DUMP_KLASSES
 639   if (Verbose) {
 640     ResourceMark rm;
 641     Klass* k = _klasses;
 642     while (k != NULL) {
 643       out->print_cr("klass " PTR_FORMAT ", %s, CT: %d, MUT: %d", k, k->name()->as_C_string(),
 644           k->has_modified_oops(), k->has_accumulated_modified_oops());
 645       assert(k != k->next_link(), "no loops!");
 646       k = k->next_link();
 647     }
 648   }
 649 #endif  // CLD_DUMP_KLASSES
 650 #undef CLD_DUMP_KLASSES
 651   if (_jmethod_ids != NULL) {
 652     Method::print_jmethod_ids(this, out);
 653   }
 654   out->print_cr("}");
 655 }
 656 #endif // PRODUCT
 657 
 658 void ClassLoaderData::verify() {
 659   assert_locked_or_safepoint(_metaspace_lock);
 660   oop cl = class_loader();
 661 
 662   guarantee(this == class_loader_data(cl) || is_anonymous(), "Must be the same");
 663   guarantee(cl != NULL || this == ClassLoaderData::the_null_class_loader_data() || is_anonymous(), "must be");
 664 
 665   // Verify the integrity of the allocated space.
 666   if (metaspace_or_null() != NULL) {
 667     metaspace_or_null()->verify();
 668   }
 669 
 670   for (Klass* k = _klasses; k != NULL; k = k->next_link()) {
 671     guarantee(k->class_loader_data() == this, "Must be the same");
 672     k->verify();
 673     assert(k != k->next_link(), "no loops!");
 674   }
 675 }
 676 
 677 bool ClassLoaderData::contains_klass(Klass* klass) {
 678   // Lock-free access requires load_ptr_acquire
 679   for (Klass* k = load_ptr_acquire(&_klasses); k != NULL; k = k->next_link()) {
 680     if (k == klass) return true;
 681   }
 682   return false;
 683 }
 684 
 685 
 686 // GC root of class loader data created.
 687 ClassLoaderData* ClassLoaderDataGraph::_head = NULL;
 688 ClassLoaderData* ClassLoaderDataGraph::_unloading = NULL;
 689 ClassLoaderData* ClassLoaderDataGraph::_saved_unloading = NULL;
 690 ClassLoaderData* ClassLoaderDataGraph::_saved_head = NULL;
 691 
 692 bool ClassLoaderDataGraph::_should_purge = false;
 693 bool ClassLoaderDataGraph::_metaspace_oom = false;
 694 
 695 // Add a new class loader data node to the list.  Assign the newly created
 696 // ClassLoaderData into the java/lang/ClassLoader object as a hidden field
 697 ClassLoaderData* ClassLoaderDataGraph::add(Handle loader, bool is_anonymous, TRAPS) {
 698   // We need to allocate all the oops for the ClassLoaderData before allocating the
 699   // actual ClassLoaderData object.
 700   ClassLoaderData::Dependencies dependencies(CHECK_NULL);
 701 
 702   NoSafepointVerifier no_safepoints; // we mustn't GC until we've installed the
 703                                      // ClassLoaderData in the graph since the CLD
 704                                      // contains unhandled oops
 705 
 706   ClassLoaderData* cld = new ClassLoaderData(loader, is_anonymous, dependencies);
 707 
 708 
 709   if (!is_anonymous) {
 710     ClassLoaderData** cld_addr = java_lang_ClassLoader::loader_data_addr(loader());
 711     // First, Atomically set it
 712     ClassLoaderData* old = (ClassLoaderData*) Atomic::cmpxchg_ptr(cld, cld_addr, NULL);
 713     if (old != NULL) {
 714       delete cld;
 715       // Returns the data.
 716       return old;
 717     }
 718   }
 719 
 720   // We won the race, and therefore the task of adding the data to the list of
 721   // class loader data
 722   ClassLoaderData** list_head = &_head;
 723   ClassLoaderData* next = _head;
 724 
 725   do {
 726     cld->set_next(next);
 727     ClassLoaderData* exchanged = (ClassLoaderData*)Atomic::cmpxchg_ptr(cld, list_head, next);
 728     if (exchanged == next) {
 729       if (log_is_enabled(Debug, class, loader, data)) {
 730        PauseNoSafepointVerifier pnsv(&no_safepoints); // Need safe points for JavaCalls::call_virtual
 731        log_creation(loader, cld, CHECK_NULL);
 732       }
 733       return cld;
 734     }
 735     next = exchanged;
 736   } while (true);
 737 }
 738 
 739 void ClassLoaderDataGraph::log_creation(Handle loader, ClassLoaderData* cld, TRAPS) {
 740   Handle string;
 741   if (loader.not_null()) {
 742     // Include the result of loader.toString() in the output. This allows
 743     // the user of the log to identify the class loader instance.
 744     JavaValue result(T_OBJECT);
 745     KlassHandle spec_klass(THREAD, SystemDictionary::ClassLoader_klass());
 746     JavaCalls::call_virtual(&result,
 747                             loader,
 748                             spec_klass,
 749                             vmSymbols::toString_name(),
 750                             vmSymbols::void_string_signature(),
 751                             CHECK);
 752     assert(result.get_type() == T_OBJECT, "just checking");
 753     string = (oop)result.get_jobject();
 754   }
 755 
 756   ResourceMark rm;
 757   outputStream* log = Log(class, loader, data)::debug_stream();
 758   log->print("create class loader data " INTPTR_FORMAT, p2i(cld));
 759   log->print(" for instance " INTPTR_FORMAT " of %s", p2i((void *)cld->class_loader()),
 760              cld->loader_name());
 761 
 762   if (string.not_null()) {
 763     log->print(": ");
 764     java_lang_String::print(string(), log);
 765   }
 766   log->cr();
 767 }
 768 
 769 
 770 void ClassLoaderDataGraph::oops_do(OopClosure* f, KlassClosure* klass_closure, bool must_claim) {
 771   for (ClassLoaderData* cld = _head; cld != NULL; cld = cld->next()) {
 772     cld->oops_do(f, klass_closure, must_claim);
 773   }
 774 }
 775 
 776 void ClassLoaderDataGraph::keep_alive_oops_do(OopClosure* f, KlassClosure* klass_closure, bool must_claim) {
 777   for (ClassLoaderData* cld = _head; cld != NULL; cld = cld->next()) {
 778     if (cld->keep_alive()) {
 779       cld->oops_do(f, klass_closure, must_claim);
 780     }
 781   }
 782 }
 783 
 784 void ClassLoaderDataGraph::always_strong_oops_do(OopClosure* f, KlassClosure* klass_closure, bool must_claim) {
 785   if (ClassUnloading) {
 786     keep_alive_oops_do(f, klass_closure, must_claim);
 787   } else {
 788     oops_do(f, klass_closure, must_claim);
 789   }
 790 }
 791 
 792 void ClassLoaderDataGraph::cld_do(CLDClosure* cl) {
 793   for (ClassLoaderData* cld = _head; cl != NULL && cld != NULL; cld = cld->next()) {
 794     cl->do_cld(cld);
 795   }
 796 }
 797 
 798 void ClassLoaderDataGraph::roots_cld_do(CLDClosure* strong, CLDClosure* weak) {
 799   for (ClassLoaderData* cld = _head;  cld != NULL; cld = cld->_next) {
 800     CLDClosure* closure = cld->keep_alive() ? strong : weak;
 801     if (closure != NULL) {
 802       closure->do_cld(cld);
 803     }
 804   }
 805 }
 806 
 807 void ClassLoaderDataGraph::keep_alive_cld_do(CLDClosure* cl) {
 808   roots_cld_do(cl, NULL);
 809 }
 810 
 811 void ClassLoaderDataGraph::always_strong_cld_do(CLDClosure* cl) {
 812   if (ClassUnloading) {
 813     keep_alive_cld_do(cl);
 814   } else {
 815     cld_do(cl);
 816   }
 817 }
 818 
 819 void ClassLoaderDataGraph::classes_do(KlassClosure* klass_closure) {
 820   for (ClassLoaderData* cld = _head; cld != NULL; cld = cld->next()) {
 821     cld->classes_do(klass_closure);
 822   }
 823 }
 824 
 825 void ClassLoaderDataGraph::classes_do(void f(Klass* const)) {
 826   for (ClassLoaderData* cld = _head; cld != NULL; cld = cld->next()) {
 827     cld->classes_do(f);
 828   }
 829 }
 830 
 831 void ClassLoaderDataGraph::methods_do(void f(Method*)) {
 832   for (ClassLoaderData* cld = _head; cld != NULL; cld = cld->next()) {
 833     cld->methods_do(f);
 834   }
 835 }
 836 
 837 void ClassLoaderDataGraph::modules_do(void f(ModuleEntry*)) {
 838   assert_locked_or_safepoint(Module_lock);
 839   for (ClassLoaderData* cld = _head; cld != NULL; cld = cld->next()) {
 840     cld->modules_do(f);
 841   }
 842 }
 843 
 844 void ClassLoaderDataGraph::modules_unloading_do(void f(ModuleEntry*)) {
 845   assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint!");
 846   // Only walk the head until any clds not purged from prior unloading
 847   // (CMS doesn't purge right away).
 848   for (ClassLoaderData* cld = _unloading; cld != _saved_unloading; cld = cld->next()) {
 849     assert(cld->is_unloading(), "invariant");
 850     cld->modules_do(f);
 851   }
 852 }
 853 
 854 void ClassLoaderDataGraph::packages_do(void f(PackageEntry*)) {
 855   assert_locked_or_safepoint(Module_lock);
 856   for (ClassLoaderData* cld = _head; cld != NULL; cld = cld->next()) {
 857     cld->packages_do(f);
 858   }
 859 }
 860 
 861 void ClassLoaderDataGraph::packages_unloading_do(void f(PackageEntry*)) {
 862   assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint!");
 863   // Only walk the head until any clds not purged from prior unloading
 864   // (CMS doesn't purge right away).
 865   for (ClassLoaderData* cld = _unloading; cld != _saved_unloading; cld = cld->next()) {
 866     assert(cld->is_unloading(), "invariant");
 867     cld->packages_do(f);
 868   }
 869 }
 870 
 871 void ClassLoaderDataGraph::loaded_classes_do(KlassClosure* klass_closure) {
 872   for (ClassLoaderData* cld = _head; cld != NULL; cld = cld->next()) {
 873     cld->loaded_classes_do(klass_closure);
 874   }
 875 }
 876 
 877 void ClassLoaderDataGraph::classes_unloading_do(void f(Klass* const)) {
 878   assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint!");
 879   // Only walk the head until any clds not purged from prior unloading
 880   // (CMS doesn't purge right away).
 881   for (ClassLoaderData* cld = _unloading; cld != _saved_unloading; cld = cld->next()) {
 882     assert(cld->is_unloading(), "invariant");
 883     cld->classes_do(f);
 884   }
 885 }
 886 
 887 GrowableArray<ClassLoaderData*>* ClassLoaderDataGraph::new_clds() {
 888   assert(_head == NULL || _saved_head != NULL, "remember_new_clds(true) not called?");
 889 
 890   GrowableArray<ClassLoaderData*>* array = new GrowableArray<ClassLoaderData*>();
 891 
 892   // The CLDs in [_head, _saved_head] were all added during last call to remember_new_clds(true);
 893   ClassLoaderData* curr = _head;
 894   while (curr != _saved_head) {
 895     if (!curr->claimed()) {
 896       array->push(curr);
 897 
 898       if (log_is_enabled(Debug, class, loader, data)) {
 899         outputStream* log = Log(class, loader, data)::debug_stream();
 900         log->print("found new CLD: ");
 901         curr->print_value_on(log);
 902         log->cr();
 903       }
 904     }
 905 
 906     curr = curr->_next;
 907   }
 908 
 909   return array;
 910 }
 911 
 912 bool ClassLoaderDataGraph::unload_list_contains(const void* x) {
 913   assert(SafepointSynchronize::is_at_safepoint(), "only safe to call at safepoint");
 914   for (ClassLoaderData* cld = _unloading; cld != NULL; cld = cld->next()) {
 915     if (cld->metaspace_or_null() != NULL && cld->metaspace_or_null()->contains(x)) {
 916       return true;
 917     }
 918   }
 919   return false;
 920 }
 921 
 922 #ifndef PRODUCT
 923 bool ClassLoaderDataGraph::contains_loader_data(ClassLoaderData* loader_data) {
 924   for (ClassLoaderData* data = _head; data != NULL; data = data->next()) {
 925     if (loader_data == data) {
 926       return true;
 927     }
 928   }
 929 
 930   return false;
 931 }
 932 #endif // PRODUCT
 933 
 934 
 935 // Move class loader data from main list to the unloaded list for unloading
 936 // and deallocation later.
 937 bool ClassLoaderDataGraph::do_unloading(BoolObjectClosure* is_alive_closure,
 938                                         bool clean_previous_versions) {
 939 
 940   ClassLoaderData* data = _head;
 941   ClassLoaderData* prev = NULL;
 942   bool seen_dead_loader = false;
 943 
 944   // Mark metadata seen on the stack only so we can delete unneeded entries.
 945   // Only walk all metadata, including the expensive code cache walk, for Full GC
 946   // and only if class redefinition and if there's previous versions of
 947   // Klasses to delete.
 948   bool walk_all_metadata = clean_previous_versions &&
 949                            JvmtiExport::has_redefined_a_class() &&
 950                            InstanceKlass::has_previous_versions();
 951   MetadataOnStackMark md_on_stack(walk_all_metadata);
 952 
 953   // Save previous _unloading pointer for CMS which may add to unloading list before
 954   // purging and we don't want to rewalk the previously unloaded class loader data.
 955   _saved_unloading = _unloading;
 956 
 957   data = _head;
 958   while (data != NULL) {
 959     if (data->is_alive(is_alive_closure)) {
 960       if (data->packages_defined()) {
 961         data->packages()->purge_all_package_exports();
 962       }
 963       if (data->modules_defined()) {
 964         data->modules()->purge_all_module_reads();
 965       }
 966       // clean metaspace
 967       if (walk_all_metadata) {
 968         data->classes_do(InstanceKlass::purge_previous_versions);
 969       }
 970       data->free_deallocate_list();
 971       prev = data;
 972       data = data->next();
 973       continue;
 974     }
 975     seen_dead_loader = true;
 976     ClassLoaderData* dead = data;
 977     dead->unload();
 978     data = data->next();
 979     // Remove from loader list.
 980     // This class loader data will no longer be found
 981     // in the ClassLoaderDataGraph.
 982     if (prev != NULL) {
 983       prev->set_next(data);
 984     } else {
 985       assert(dead == _head, "sanity check");
 986       _head = data;
 987     }
 988     dead->set_next(_unloading);
 989     _unloading = dead;
 990   }
 991 
 992   if (seen_dead_loader) {
 993     post_class_unload_events();
 994   }
 995 
 996   return seen_dead_loader;
 997 }
 998 
 999 void ClassLoaderDataGraph::purge() {
1000   assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint!");
1001   ClassLoaderData* list = _unloading;
1002   _unloading = NULL;
1003   ClassLoaderData* next = list;
1004   bool classes_unloaded = false;
1005   while (next != NULL) {
1006     ClassLoaderData* purge_me = next;
1007     next = purge_me->next();
1008     delete purge_me;
1009     classes_unloaded = true;
1010   }
1011   if (classes_unloaded) {
1012     Metaspace::purge();
1013     set_metaspace_oom(false);
1014   }
1015 }
1016 
1017 void ClassLoaderDataGraph::post_class_unload_events(void) {
1018 #if INCLUDE_TRACE
1019   assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint!");
1020   if (Tracing::enabled()) {
1021     if (Tracing::is_event_enabled(TraceClassUnloadEvent)) {
1022       assert(_unloading != NULL, "need class loader data unload list!");
1023       _class_unload_time = Ticks::now();
1024       classes_unloading_do(&class_unload_event);
1025     }
1026     Tracing::on_unloading_classes();
1027   }
1028 #endif
1029 }
1030 
1031 // CDS support
1032 
1033 // Global metaspaces for writing information to the shared archive.  When
1034 // application CDS is supported, we may need one per metaspace, so this
1035 // sort of looks like it.
1036 Metaspace* ClassLoaderData::_ro_metaspace = NULL;
1037 Metaspace* ClassLoaderData::_rw_metaspace = NULL;
1038 static bool _shared_metaspaces_initialized = false;
1039 
1040 // Initialize shared metaspaces (change to call from somewhere not lazily)
1041 void ClassLoaderData::initialize_shared_metaspaces() {
1042   assert(DumpSharedSpaces, "only use this for dumping shared spaces");
1043   assert(this == ClassLoaderData::the_null_class_loader_data(),
1044          "only supported for null loader data for now");
1045   assert (!_shared_metaspaces_initialized, "only initialize once");
1046   MutexLockerEx ml(metaspace_lock(),  Mutex::_no_safepoint_check_flag);
1047   _ro_metaspace = new Metaspace(_metaspace_lock, Metaspace::ROMetaspaceType);
1048   _rw_metaspace = new Metaspace(_metaspace_lock, Metaspace::ReadWriteMetaspaceType);
1049   _shared_metaspaces_initialized = true;
1050 }
1051 
1052 Metaspace* ClassLoaderData::ro_metaspace() {
1053   assert(_ro_metaspace != NULL, "should already be initialized");
1054   return _ro_metaspace;
1055 }
1056 
1057 Metaspace* ClassLoaderData::rw_metaspace() {
1058   assert(_rw_metaspace != NULL, "should already be initialized");
1059   return _rw_metaspace;
1060 }
1061 
1062 ClassLoaderDataGraphKlassIteratorAtomic::ClassLoaderDataGraphKlassIteratorAtomic()
1063     : _next_klass(NULL) {
1064   ClassLoaderData* cld = ClassLoaderDataGraph::_head;
1065   Klass* klass = NULL;
1066 
1067   // Find the first klass in the CLDG.
1068   while (cld != NULL) {
1069     assert_locked_or_safepoint(cld->metaspace_lock());
1070     klass = cld->_klasses;
1071     if (klass != NULL) {
1072       _next_klass = klass;
1073       return;
1074     }
1075     cld = cld->next();
1076   }
1077 }
1078 
1079 Klass* ClassLoaderDataGraphKlassIteratorAtomic::next_klass_in_cldg(Klass* klass) {
1080   Klass* next = klass->next_link();
1081   if (next != NULL) {
1082     return next;
1083   }
1084 
1085   // No more klasses in the current CLD. Time to find a new CLD.
1086   ClassLoaderData* cld = klass->class_loader_data();
1087   assert_locked_or_safepoint(cld->metaspace_lock());
1088   while (next == NULL) {
1089     cld = cld->next();
1090     if (cld == NULL) {
1091       break;
1092     }
1093     next = cld->_klasses;
1094   }
1095 
1096   return next;
1097 }
1098 
1099 Klass* ClassLoaderDataGraphKlassIteratorAtomic::next_klass() {
1100   Klass* head = _next_klass;
1101 
1102   while (head != NULL) {
1103     Klass* next = next_klass_in_cldg(head);
1104 
1105     Klass* old_head = (Klass*)Atomic::cmpxchg_ptr(next, &_next_klass, head);
1106 
1107     if (old_head == head) {
1108       return head; // Won the CAS.
1109     }
1110 
1111     head = old_head;
1112   }
1113 
1114   // Nothing more for the iterator to hand out.
1115   assert(head == NULL, "head is " PTR_FORMAT ", expected not null:", p2i(head));
1116   return NULL;
1117 }
1118 
1119 ClassLoaderDataGraphMetaspaceIterator::ClassLoaderDataGraphMetaspaceIterator() {
1120   _data = ClassLoaderDataGraph::_head;
1121 }
1122 
1123 ClassLoaderDataGraphMetaspaceIterator::~ClassLoaderDataGraphMetaspaceIterator() {}
1124 
1125 #ifndef PRODUCT
1126 // callable from debugger
1127 extern "C" int print_loader_data_graph() {
1128   ClassLoaderDataGraph::dump_on(tty);
1129   return 0;
1130 }
1131 
1132 void ClassLoaderDataGraph::verify() {
1133   for (ClassLoaderData* data = _head; data != NULL; data = data->next()) {
1134     data->verify();
1135   }
1136 }
1137 
1138 void ClassLoaderDataGraph::dump_on(outputStream * const out) {
1139   for (ClassLoaderData* data = _head; data != NULL; data = data->next()) {
1140     data->dump(out);
1141   }
1142   MetaspaceAux::dump(out);
1143 }
1144 #endif // PRODUCT
1145 
1146 void ClassLoaderData::print_value_on(outputStream* out) const {
1147   if (class_loader() == NULL) {
1148     out->print("NULL class_loader");
1149   } else {
1150     out->print("class loader " INTPTR_FORMAT, p2i(this));
1151     class_loader()->print_value_on(out);
1152   }
1153 }
1154 
1155 #if INCLUDE_TRACE
1156 
1157 Ticks ClassLoaderDataGraph::_class_unload_time;
1158 
1159 void ClassLoaderDataGraph::class_unload_event(Klass* const k) {
1160   assert(k != NULL, "invariant");
1161 
1162   // post class unload event
1163   EventClassUnload event(UNTIMED);
1164   event.set_endtime(_class_unload_time);
1165   event.set_unloadedClass(k);
1166   oop defining_class_loader = k->class_loader();
1167   event.set_definingClassLoader(defining_class_loader != NULL ?
1168                                 defining_class_loader->klass() : (Klass*)NULL);
1169   event.commit();
1170 }
1171 
1172 #endif // INCLUDE_TRACE