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