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