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