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