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