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