1 /* 2 * Copyright (c) 2012, 2019, 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.inline.hpp" 51 #include "classfile/classLoaderDataGraph.inline.hpp" 52 #include "classfile/dictionary.hpp" 53 #include "classfile/javaClasses.hpp" 54 #include "classfile/moduleEntry.hpp" 55 #include "classfile/packageEntry.hpp" 56 #include "classfile/symbolTable.hpp" 57 #include "classfile/systemDictionary.hpp" 58 #include "logging/log.hpp" 59 #include "logging/logStream.hpp" 60 #include "memory/allocation.inline.hpp" 61 #include "memory/metadataFactory.hpp" 62 #include "memory/resourceArea.hpp" 63 #include "oops/access.inline.hpp" 64 #include "oops/oop.inline.hpp" 65 #include "oops/oopHandle.inline.hpp" 66 #include "oops/valueKlass.hpp" 67 #include "oops/weakHandle.inline.hpp" 68 #include "runtime/atomic.hpp" 69 #include "runtime/handles.inline.hpp" 70 #include "runtime/mutex.hpp" 71 #include "runtime/orderAccess.hpp" 72 #include "runtime/safepoint.hpp" 73 #include "utilities/growableArray.hpp" 74 #include "utilities/macros.hpp" 75 #include "utilities/ostream.hpp" 76 77 ClassLoaderData * ClassLoaderData::_the_null_class_loader_data = NULL; 78 79 void ClassLoaderData::init_null_class_loader_data() { 80 assert(_the_null_class_loader_data == NULL, "cannot initialize twice"); 81 assert(ClassLoaderDataGraph::_head == NULL, "cannot initialize twice"); 82 83 _the_null_class_loader_data = new ClassLoaderData(Handle(), false); 84 ClassLoaderDataGraph::_head = _the_null_class_loader_data; 85 assert(_the_null_class_loader_data->is_the_null_class_loader_data(), "Must be"); 86 87 LogTarget(Trace, class, loader, data) lt; 88 if (lt.is_enabled()) { 89 ResourceMark rm; 90 LogStream ls(lt); 91 ls.print("create "); 92 _the_null_class_loader_data->print_value_on(&ls); 93 ls.cr(); 94 } 95 } 96 97 // Obtain and set the class loader's name within the ClassLoaderData so 98 // it will be available for error messages, logging, JFR, etc. The name 99 // and klass are available after the class_loader oop is no longer alive, 100 // during unloading. 101 void ClassLoaderData::initialize_name(Handle class_loader) { 102 Thread* THREAD = Thread::current(); 103 ResourceMark rm(THREAD); 104 105 // Obtain the class loader's name. If the class loader's name was not 106 // explicitly set during construction, the CLD's _name field will be null. 107 oop cl_name = java_lang_ClassLoader::name(class_loader()); 108 if (cl_name != NULL) { 109 const char* cl_instance_name = java_lang_String::as_utf8_string(cl_name); 110 111 if (cl_instance_name != NULL && cl_instance_name[0] != '\0') { 112 _name = SymbolTable::new_symbol(cl_instance_name); 113 } 114 } 115 116 // Obtain the class loader's name and identity hash. If the class loader's 117 // name was not explicitly set during construction, the class loader's name and id 118 // will be set to the qualified class name of the class loader along with its 119 // identity hash. 120 // If for some reason the ClassLoader's constructor has not been run, instead of 121 // leaving the _name_and_id field null, fall back to the external qualified class 122 // name. Thus CLD's _name_and_id field should never have a null value. 123 oop cl_name_and_id = java_lang_ClassLoader::nameAndId(class_loader()); 124 const char* cl_instance_name_and_id = 125 (cl_name_and_id == NULL) ? _class_loader_klass->external_name() : 126 java_lang_String::as_utf8_string(cl_name_and_id); 127 assert(cl_instance_name_and_id != NULL && cl_instance_name_and_id[0] != '\0', "class loader has no name and id"); 128 _name_and_id = SymbolTable::new_symbol(cl_instance_name_and_id); 129 } 130 131 ClassLoaderData::ClassLoaderData(Handle h_class_loader, bool is_unsafe_anonymous) : 132 _metaspace(NULL), 133 _metaspace_lock(new Mutex(Monitor::leaf+1, "Metaspace allocation lock", true, 134 Monitor::_safepoint_check_never)), 135 _unloading(false), _is_unsafe_anonymous(is_unsafe_anonymous), 136 _modified_oops(true), _accumulated_modified_oops(false), 137 // An unsafe anonymous class loader data doesn't have anything to keep 138 // it from being unloaded during parsing of the unsafe anonymous class. 139 // The null-class-loader should always be kept alive. 140 _keep_alive((is_unsafe_anonymous || h_class_loader.is_null()) ? 1 : 0), 141 _claim(0), 142 _handles(), 143 _klasses(NULL), _packages(NULL), _modules(NULL), _unnamed_module(NULL), _dictionary(NULL), 144 _jmethod_ids(NULL), 145 _deallocate_list(NULL), 146 _next(NULL), 147 _class_loader_klass(NULL), _name(NULL), _name_and_id(NULL) { 148 149 if (!h_class_loader.is_null()) { 150 _class_loader = _handles.add(h_class_loader()); 151 _class_loader_klass = h_class_loader->klass(); 152 initialize_name(h_class_loader); 153 } 154 155 if (!is_unsafe_anonymous) { 156 // The holder is initialized later for unsafe anonymous classes, and before calling anything 157 // that call class_loader(). 158 initialize_holder(h_class_loader); 159 160 // A ClassLoaderData created solely for an unsafe anonymous class should never have a 161 // ModuleEntryTable or PackageEntryTable created for it. The defining package 162 // and module for an unsafe anonymous class will be found in its host class. 163 _packages = new PackageEntryTable(PackageEntryTable::_packagetable_entry_size); 164 if (h_class_loader.is_null()) { 165 // Create unnamed module for boot loader 166 _unnamed_module = ModuleEntry::create_boot_unnamed_module(this); 167 } else { 168 // Create unnamed module for all other loaders 169 _unnamed_module = ModuleEntry::create_unnamed_module(this); 170 } 171 _dictionary = create_dictionary(); 172 } 173 174 NOT_PRODUCT(_dependency_count = 0); // number of class loader dependencies 175 176 JFR_ONLY(INIT_ID(this);) 177 } 178 179 ClassLoaderData::ChunkedHandleList::~ChunkedHandleList() { 180 Chunk* c = _head; 181 while (c != NULL) { 182 Chunk* next = c->_next; 183 delete c; 184 c = next; 185 } 186 } 187 188 oop* ClassLoaderData::ChunkedHandleList::add(oop o) { 189 if (_head == NULL || _head->_size == Chunk::CAPACITY) { 190 Chunk* next = new Chunk(_head); 191 OrderAccess::release_store(&_head, next); 192 } 193 oop* handle = &_head->_data[_head->_size]; 194 NativeAccess<IS_DEST_UNINITIALIZED>::oop_store(handle, o); 195 OrderAccess::release_store(&_head->_size, _head->_size + 1); 196 return handle; 197 } 198 199 int ClassLoaderData::ChunkedHandleList::count() const { 200 int count = 0; 201 Chunk* chunk = _head; 202 while (chunk != NULL) { 203 count += chunk->_size; 204 chunk = chunk->_next; 205 } 206 return count; 207 } 208 209 inline void ClassLoaderData::ChunkedHandleList::oops_do_chunk(OopClosure* f, Chunk* c, const juint size) { 210 for (juint i = 0; i < size; i++) { 211 if (c->_data[i] != NULL) { 212 f->do_oop(&c->_data[i]); 213 } 214 } 215 } 216 217 void ClassLoaderData::ChunkedHandleList::oops_do(OopClosure* f) { 218 Chunk* head = OrderAccess::load_acquire(&_head); 219 if (head != NULL) { 220 // Must be careful when reading size of head 221 oops_do_chunk(f, head, OrderAccess::load_acquire(&head->_size)); 222 for (Chunk* c = head->_next; c != NULL; c = c->_next) { 223 oops_do_chunk(f, c, c->_size); 224 } 225 } 226 } 227 228 class VerifyContainsOopClosure : public OopClosure { 229 oop _target; 230 bool _found; 231 232 public: 233 VerifyContainsOopClosure(oop target) : _target(target), _found(false) {} 234 235 void do_oop(oop* p) { 236 if (p != NULL && NativeAccess<AS_NO_KEEPALIVE>::oop_load(p) == _target) { 237 _found = true; 238 } 239 } 240 241 void do_oop(narrowOop* p) { 242 // The ChunkedHandleList should not contain any narrowOop 243 ShouldNotReachHere(); 244 } 245 246 bool found() const { 247 return _found; 248 } 249 }; 250 251 bool ClassLoaderData::ChunkedHandleList::contains(oop p) { 252 VerifyContainsOopClosure cl(p); 253 oops_do(&cl); 254 return cl.found(); 255 } 256 257 #ifndef PRODUCT 258 bool ClassLoaderData::ChunkedHandleList::owner_of(oop* oop_handle) { 259 Chunk* chunk = _head; 260 while (chunk != NULL) { 261 if (&(chunk->_data[0]) <= oop_handle && oop_handle < &(chunk->_data[chunk->_size])) { 262 return true; 263 } 264 chunk = chunk->_next; 265 } 266 return false; 267 } 268 #endif // PRODUCT 269 270 void ClassLoaderData::clear_claim(int claim) { 271 for (;;) { 272 int old_claim = Atomic::load(&_claim); 273 if ((old_claim & claim) == 0) { 274 return; 275 } 276 int new_claim = old_claim & ~claim; 277 if (Atomic::cmpxchg(new_claim, &_claim, old_claim) == old_claim) { 278 return; 279 } 280 } 281 } 282 283 bool ClassLoaderData::try_claim(int claim) { 284 for (;;) { 285 int old_claim = Atomic::load(&_claim); 286 if ((old_claim & claim) == claim) { 287 return false; 288 } 289 int new_claim = old_claim | claim; 290 if (Atomic::cmpxchg(new_claim, &_claim, old_claim) == old_claim) { 291 return true; 292 } 293 } 294 } 295 296 // Unsafe anonymous classes have their own ClassLoaderData that is marked to keep alive 297 // while the class is being parsed, and if the class appears on the module fixup list. 298 // Due to the uniqueness that no other class shares the unsafe anonymous class' name or 299 // ClassLoaderData, no other non-GC thread has knowledge of the unsafe anonymous class while 300 // it is being defined, therefore _keep_alive is not volatile or atomic. 301 void ClassLoaderData::inc_keep_alive() { 302 if (is_unsafe_anonymous()) { 303 assert(_keep_alive > 0, "Invalid keep alive increment count"); 304 _keep_alive++; 305 } 306 } 307 308 void ClassLoaderData::dec_keep_alive() { 309 if (is_unsafe_anonymous()) { 310 assert(_keep_alive > 0, "Invalid keep alive decrement count"); 311 _keep_alive--; 312 } 313 } 314 315 void ClassLoaderData::oops_do(OopClosure* f, int claim_value, bool clear_mod_oops) { 316 if (claim_value != ClassLoaderData::_claim_none && !try_claim(claim_value)) { 317 return; 318 } 319 320 // Only clear modified_oops after the ClassLoaderData is claimed. 321 if (clear_mod_oops) { 322 clear_modified_oops(); 323 } 324 325 _handles.oops_do(f); 326 } 327 328 void ClassLoaderData::classes_do(KlassClosure* klass_closure) { 329 // Lock-free access requires load_acquire 330 for (Klass* k = OrderAccess::load_acquire(&_klasses); k != NULL; k = k->next_link()) { 331 klass_closure->do_klass(k); 332 assert(k != k->next_link(), "no loops!"); 333 } 334 } 335 336 void ClassLoaderData::classes_do(void f(Klass * const)) { 337 // Lock-free access requires load_acquire 338 for (Klass* k = OrderAccess::load_acquire(&_klasses); k != NULL; k = k->next_link()) { 339 f(k); 340 assert(k != k->next_link(), "no loops!"); 341 } 342 } 343 344 void ClassLoaderData::methods_do(void f(Method*)) { 345 // Lock-free access requires load_acquire 346 for (Klass* k = OrderAccess::load_acquire(&_klasses); k != NULL; k = k->next_link()) { 347 if (k->is_instance_klass() && InstanceKlass::cast(k)->is_loaded()) { 348 InstanceKlass::cast(k)->methods_do(f); 349 } 350 } 351 } 352 353 void ClassLoaderData::loaded_classes_do(KlassClosure* klass_closure) { 354 // Lock-free access requires load_acquire 355 for (Klass* k = OrderAccess::load_acquire(&_klasses); k != NULL; k = k->next_link()) { 356 // Do not filter ArrayKlass oops here... 357 if (k->is_array_klass() || (k->is_instance_klass() && InstanceKlass::cast(k)->is_loaded())) { 358 #ifdef ASSERT 359 oop m = k->java_mirror(); 360 assert(m != NULL, "NULL mirror"); 361 assert(m->is_a(SystemDictionary::Class_klass()), "invalid mirror"); 362 #endif 363 klass_closure->do_klass(k); 364 } 365 } 366 } 367 368 void ClassLoaderData::classes_do(void f(InstanceKlass*)) { 369 // Lock-free access requires load_acquire 370 for (Klass* k = OrderAccess::load_acquire(&_klasses); k != NULL; k = k->next_link()) { 371 if (k->is_instance_klass()) { 372 f(InstanceKlass::cast(k)); 373 } 374 assert(k != k->next_link(), "no loops!"); 375 } 376 } 377 378 void ClassLoaderData::value_classes_do(void f(ValueKlass*)) { 379 // Lock-free access requires load_acquire 380 for (Klass* k = OrderAccess::load_acquire(&_klasses); k != NULL; k = k->next_link()) { 381 if (k->is_value()) { 382 f(ValueKlass::cast(k)); 383 } 384 assert(k != k->next_link(), "no loops!"); 385 } 386 } 387 388 void ClassLoaderData::modules_do(void f(ModuleEntry*)) { 389 assert_locked_or_safepoint(Module_lock); 390 if (_unnamed_module != NULL) { 391 f(_unnamed_module); 392 } 393 if (_modules != NULL) { 394 for (int i = 0; i < _modules->table_size(); i++) { 395 for (ModuleEntry* entry = _modules->bucket(i); 396 entry != NULL; 397 entry = entry->next()) { 398 f(entry); 399 } 400 } 401 } 402 } 403 404 void ClassLoaderData::packages_do(void f(PackageEntry*)) { 405 assert_locked_or_safepoint(Module_lock); 406 if (_packages != NULL) { 407 for (int i = 0; i < _packages->table_size(); i++) { 408 for (PackageEntry* entry = _packages->bucket(i); 409 entry != NULL; 410 entry = entry->next()) { 411 f(entry); 412 } 413 } 414 } 415 } 416 417 void ClassLoaderData::record_dependency(const Klass* k) { 418 assert(k != NULL, "invariant"); 419 420 ClassLoaderData * const from_cld = this; 421 ClassLoaderData * const to_cld = k->class_loader_data(); 422 423 // Do not need to record dependency if the dependency is to a class whose 424 // class loader data is never freed. (i.e. the dependency's class loader 425 // is one of the three builtin class loaders and the dependency is not 426 // unsafe anonymous.) 427 if (to_cld->is_permanent_class_loader_data()) { 428 return; 429 } 430 431 oop to; 432 if (to_cld->is_unsafe_anonymous()) { 433 // Just return if an unsafe anonymous class is attempting to record a dependency 434 // to itself. (Note that every unsafe anonymous class has its own unique class 435 // loader data.) 436 if (to_cld == from_cld) { 437 return; 438 } 439 // Unsafe anonymous class dependencies are through the mirror. 440 to = k->java_mirror(); 441 } else { 442 to = to_cld->class_loader(); 443 oop from = from_cld->class_loader(); 444 445 // Just return if this dependency is to a class with the same or a parent 446 // class_loader. 447 if (from == to || java_lang_ClassLoader::isAncestor(from, to)) { 448 return; // this class loader is in the parent list, no need to add it. 449 } 450 } 451 452 // It's a dependency we won't find through GC, add it. 453 if (!_handles.contains(to)) { 454 NOT_PRODUCT(Atomic::inc(&_dependency_count)); 455 LogTarget(Trace, class, loader, data) lt; 456 if (lt.is_enabled()) { 457 ResourceMark rm; 458 LogStream ls(lt); 459 ls.print("adding dependency from "); 460 print_value_on(&ls); 461 ls.print(" to "); 462 to_cld->print_value_on(&ls); 463 ls.cr(); 464 } 465 Handle dependency(Thread::current(), to); 466 add_handle(dependency); 467 // Added a potentially young gen oop to the ClassLoaderData 468 record_modified_oops(); 469 } 470 } 471 472 void ClassLoaderData::add_class(Klass* k, bool publicize /* true */) { 473 { 474 MutexLocker ml(metaspace_lock(), Mutex::_no_safepoint_check_flag); 475 Klass* old_value = _klasses; 476 k->set_next_link(old_value); 477 // Link the new item into the list, making sure the linked class is stable 478 // since the list can be walked without a lock 479 OrderAccess::release_store(&_klasses, k); 480 if (k->is_array_klass()) { 481 ClassLoaderDataGraph::inc_array_classes(1); 482 } else { 483 ClassLoaderDataGraph::inc_instance_classes(1); 484 } 485 } 486 487 if (publicize) { 488 LogTarget(Trace, class, loader, data) lt; 489 if (lt.is_enabled()) { 490 ResourceMark rm; 491 LogStream ls(lt); 492 ls.print("Adding k: " PTR_FORMAT " %s to ", p2i(k), k->external_name()); 493 print_value_on(&ls); 494 ls.cr(); 495 } 496 } 497 } 498 499 void ClassLoaderData::initialize_holder(Handle loader_or_mirror) { 500 if (loader_or_mirror() != NULL) { 501 assert(_holder.is_null(), "never replace holders"); 502 _holder = WeakHandle<vm_class_loader_data>::create(loader_or_mirror); 503 } 504 } 505 506 // Remove a klass from the _klasses list for scratch_class during redefinition 507 // or parsed class in the case of an error. 508 void ClassLoaderData::remove_class(Klass* scratch_class) { 509 assert_locked_or_safepoint(ClassLoaderDataGraph_lock); 510 511 // Adjust global class iterator. 512 ClassLoaderDataGraph::adjust_saved_class(scratch_class); 513 514 Klass* prev = NULL; 515 for (Klass* k = _klasses; k != NULL; k = k->next_link()) { 516 if (k == scratch_class) { 517 if (prev == NULL) { 518 _klasses = k->next_link(); 519 } else { 520 Klass* next = k->next_link(); 521 prev->set_next_link(next); 522 } 523 524 if (k->is_array_klass()) { 525 ClassLoaderDataGraph::dec_array_classes(1); 526 } else { 527 ClassLoaderDataGraph::dec_instance_classes(1); 528 } 529 530 return; 531 } 532 prev = k; 533 assert(k != k->next_link(), "no loops!"); 534 } 535 ShouldNotReachHere(); // should have found this class!! 536 } 537 538 void ClassLoaderData::unload() { 539 _unloading = true; 540 541 LogTarget(Trace, class, loader, data) lt; 542 if (lt.is_enabled()) { 543 ResourceMark rm; 544 LogStream ls(lt); 545 ls.print("unload"); 546 print_value_on(&ls); 547 ls.cr(); 548 } 549 550 // Some items on the _deallocate_list need to free their C heap structures 551 // if they are not already on the _klasses list. 552 free_deallocate_list_C_heap_structures(); 553 554 value_classes_do(ValueKlass::cleanup); 555 556 // Clean up class dependencies and tell serviceability tools 557 // these classes are unloading. Must be called 558 // after erroneous classes are released. 559 classes_do(InstanceKlass::unload_class); 560 561 // Clean up global class iterator for compiler 562 ClassLoaderDataGraph::adjust_saved_class(this); 563 } 564 565 ModuleEntryTable* ClassLoaderData::modules() { 566 // Lazily create the module entry table at first request. 567 // Lock-free access requires load_acquire. 568 ModuleEntryTable* modules = OrderAccess::load_acquire(&_modules); 569 if (modules == NULL) { 570 MutexLocker m1(Module_lock); 571 // Check if _modules got allocated while we were waiting for this lock. 572 if ((modules = _modules) == NULL) { 573 modules = new ModuleEntryTable(ModuleEntryTable::_moduletable_entry_size); 574 575 { 576 MutexLocker m1(metaspace_lock(), Mutex::_no_safepoint_check_flag); 577 // Ensure _modules is stable, since it is examined without a lock 578 OrderAccess::release_store(&_modules, modules); 579 } 580 } 581 } 582 return modules; 583 } 584 585 const int _boot_loader_dictionary_size = 1009; 586 const int _default_loader_dictionary_size = 107; 587 588 Dictionary* ClassLoaderData::create_dictionary() { 589 assert(!is_unsafe_anonymous(), "unsafe anonymous class loader data do not have a dictionary"); 590 int size; 591 bool resizable = false; 592 if (_the_null_class_loader_data == NULL) { 593 size = _boot_loader_dictionary_size; 594 resizable = true; 595 } else if (class_loader()->is_a(SystemDictionary::reflect_DelegatingClassLoader_klass())) { 596 size = 1; // there's only one class in relection class loader and no initiated classes 597 } else if (is_system_class_loader_data()) { 598 size = _boot_loader_dictionary_size; 599 resizable = true; 600 } else { 601 size = _default_loader_dictionary_size; 602 resizable = true; 603 } 604 if (!DynamicallyResizeSystemDictionaries || DumpSharedSpaces) { 605 resizable = false; 606 } 607 return new Dictionary(this, size, resizable); 608 } 609 610 // Tell the GC to keep this klass alive while iterating ClassLoaderDataGraph 611 oop ClassLoaderData::holder_phantom() const { 612 // A klass that was previously considered dead can be looked up in the 613 // CLD/SD, and its _java_mirror or _class_loader can be stored in a root 614 // or a reachable object making it alive again. The SATB part of G1 needs 615 // to get notified about this potential resurrection, otherwise the marking 616 // might not find the object. 617 if (!_holder.is_null()) { // NULL class_loader 618 return _holder.resolve(); 619 } else { 620 return NULL; 621 } 622 } 623 624 // Let the GC read the holder without keeping it alive. 625 oop ClassLoaderData::holder_no_keepalive() const { 626 if (!_holder.is_null()) { // NULL class_loader 627 return _holder.peek(); 628 } else { 629 return NULL; 630 } 631 } 632 633 // Unloading support 634 bool ClassLoaderData::is_alive() const { 635 bool alive = keep_alive() // null class loader and incomplete unsafe anonymous klasses. 636 || (_holder.peek() != NULL); // and not cleaned by the GC weak handle processing. 637 638 return alive; 639 } 640 641 class ReleaseKlassClosure: public KlassClosure { 642 private: 643 size_t _instance_class_released; 644 size_t _array_class_released; 645 public: 646 ReleaseKlassClosure() : _instance_class_released(0), _array_class_released(0) { } 647 648 size_t instance_class_released() const { return _instance_class_released; } 649 size_t array_class_released() const { return _array_class_released; } 650 651 void do_klass(Klass* k) { 652 if (k->is_array_klass()) { 653 _array_class_released ++; 654 } else { 655 assert(k->is_instance_klass(), "Must be"); 656 _instance_class_released ++; 657 InstanceKlass::release_C_heap_structures(InstanceKlass::cast(k)); 658 } 659 } 660 }; 661 662 ClassLoaderData::~ClassLoaderData() { 663 // Release C heap structures for all the classes. 664 ReleaseKlassClosure cl; 665 classes_do(&cl); 666 667 ClassLoaderDataGraph::dec_array_classes(cl.array_class_released()); 668 ClassLoaderDataGraph::dec_instance_classes(cl.instance_class_released()); 669 670 // Release the WeakHandle 671 _holder.release(); 672 673 // Release C heap allocated hashtable for all the packages. 674 if (_packages != NULL) { 675 // Destroy the table itself 676 delete _packages; 677 _packages = NULL; 678 } 679 680 // Release C heap allocated hashtable for all the modules. 681 if (_modules != NULL) { 682 // Destroy the table itself 683 delete _modules; 684 _modules = NULL; 685 } 686 687 // Release C heap allocated hashtable for the dictionary 688 if (_dictionary != NULL) { 689 // Destroy the table itself 690 delete _dictionary; 691 _dictionary = NULL; 692 } 693 694 if (_unnamed_module != NULL) { 695 _unnamed_module->delete_unnamed_module(); 696 _unnamed_module = NULL; 697 } 698 699 // release the metaspace 700 ClassLoaderMetaspace *m = _metaspace; 701 if (m != NULL) { 702 _metaspace = NULL; 703 delete m; 704 } 705 // Clear all the JNI handles for methods 706 // These aren't deallocated and are going to look like a leak, but that's 707 // needed because we can't really get rid of jmethodIDs because we don't 708 // know when native code is going to stop using them. The spec says that 709 // they're "invalid" but existing programs likely rely on their being 710 // NULL after class unloading. 711 if (_jmethod_ids != NULL) { 712 Method::clear_jmethod_ids(this); 713 } 714 // Delete lock 715 delete _metaspace_lock; 716 717 // Delete free list 718 if (_deallocate_list != NULL) { 719 delete _deallocate_list; 720 } 721 722 // Decrement refcounts of Symbols if created. 723 if (_name != NULL) { 724 _name->decrement_refcount(); 725 } 726 if (_name_and_id != NULL) { 727 _name_and_id->decrement_refcount(); 728 } 729 } 730 731 // Returns true if this class loader data is for the app class loader 732 // or a user defined system class loader. (Note that the class loader 733 // data may be unsafe anonymous.) 734 bool ClassLoaderData::is_system_class_loader_data() const { 735 return SystemDictionary::is_system_class_loader(class_loader()); 736 } 737 738 // Returns true if this class loader data is for the platform class loader. 739 // (Note that the class loader data may be unsafe anonymous.) 740 bool ClassLoaderData::is_platform_class_loader_data() const { 741 return SystemDictionary::is_platform_class_loader(class_loader()); 742 } 743 744 // Returns true if the class loader for this class loader data is one of 745 // the 3 builtin (boot application/system or platform) class loaders, 746 // including a user-defined system class loader. Note that if the class 747 // loader data is for an unsafe anonymous class then it may get freed by a GC 748 // even if its class loader is one of these loaders. 749 bool ClassLoaderData::is_builtin_class_loader_data() const { 750 return (is_boot_class_loader_data() || 751 SystemDictionary::is_system_class_loader(class_loader()) || 752 SystemDictionary::is_platform_class_loader(class_loader())); 753 } 754 755 // Returns true if this class loader data is a class loader data 756 // that is not ever freed by a GC. It must be the CLD for one of the builtin 757 // class loaders and not the CLD for an unsafe anonymous class. 758 bool ClassLoaderData::is_permanent_class_loader_data() const { 759 return is_builtin_class_loader_data() && !is_unsafe_anonymous(); 760 } 761 762 ClassLoaderMetaspace* ClassLoaderData::metaspace_non_null() { 763 // If the metaspace has not been allocated, create a new one. Might want 764 // to create smaller arena for Reflection class loaders also. 765 // The reason for the delayed allocation is because some class loaders are 766 // simply for delegating with no metadata of their own. 767 // Lock-free access requires load_acquire. 768 ClassLoaderMetaspace* metaspace = OrderAccess::load_acquire(&_metaspace); 769 if (metaspace == NULL) { 770 MutexLocker ml(_metaspace_lock, Mutex::_no_safepoint_check_flag); 771 // Check if _metaspace got allocated while we were waiting for this lock. 772 if ((metaspace = _metaspace) == NULL) { 773 if (this == the_null_class_loader_data()) { 774 assert (class_loader() == NULL, "Must be"); 775 metaspace = new ClassLoaderMetaspace(_metaspace_lock, Metaspace::BootMetaspaceType); 776 } else if (is_unsafe_anonymous()) { 777 metaspace = new ClassLoaderMetaspace(_metaspace_lock, Metaspace::UnsafeAnonymousMetaspaceType); 778 } else if (class_loader()->is_a(SystemDictionary::reflect_DelegatingClassLoader_klass())) { 779 metaspace = new ClassLoaderMetaspace(_metaspace_lock, Metaspace::ReflectionMetaspaceType); 780 } else { 781 metaspace = new ClassLoaderMetaspace(_metaspace_lock, Metaspace::StandardMetaspaceType); 782 } 783 // Ensure _metaspace is stable, since it is examined without a lock 784 OrderAccess::release_store(&_metaspace, metaspace); 785 } 786 } 787 return metaspace; 788 } 789 790 OopHandle ClassLoaderData::add_handle(Handle h) { 791 MutexLocker ml(metaspace_lock(), Mutex::_no_safepoint_check_flag); 792 record_modified_oops(); 793 return OopHandle(_handles.add(h())); 794 } 795 796 void ClassLoaderData::remove_handle(OopHandle h) { 797 assert(!is_unloading(), "Do not remove a handle for a CLD that is unloading"); 798 oop* ptr = h.ptr_raw(); 799 if (ptr != NULL) { 800 assert(_handles.owner_of(ptr), "Got unexpected handle " PTR_FORMAT, p2i(ptr)); 801 NativeAccess<>::oop_store(ptr, oop(NULL)); 802 } 803 } 804 805 void ClassLoaderData::init_handle_locked(OopHandle& dest, Handle h) { 806 MutexLocker ml(metaspace_lock(), Mutex::_no_safepoint_check_flag); 807 if (dest.resolve() != NULL) { 808 return; 809 } else { 810 dest = _handles.add(h()); 811 } 812 } 813 814 // Add this metadata pointer to be freed when it's safe. This is only during 815 // a safepoint which checks if handles point to this metadata field. 816 void ClassLoaderData::add_to_deallocate_list(Metadata* m) { 817 // Metadata in shared region isn't deleted. 818 if (!m->is_shared()) { 819 MutexLocker ml(metaspace_lock(), Mutex::_no_safepoint_check_flag); 820 if (_deallocate_list == NULL) { 821 _deallocate_list = new (ResourceObj::C_HEAP, mtClass) GrowableArray<Metadata*>(100, true); 822 } 823 _deallocate_list->append_if_missing(m); 824 log_debug(class, loader, data)("deallocate added for %s", m->print_value_string()); 825 ClassLoaderDataGraph::set_should_clean_deallocate_lists(); 826 } 827 } 828 829 // Deallocate free metadata on the free list. How useful the PermGen was! 830 void ClassLoaderData::free_deallocate_list() { 831 // This must be called at a safepoint because it depends on metadata walking at 832 // safepoint cleanup time. 833 assert(SafepointSynchronize::is_at_safepoint(), "only called at safepoint"); 834 assert(!is_unloading(), "only called for ClassLoaderData that are not unloading"); 835 if (_deallocate_list == NULL) { 836 return; 837 } 838 // Go backwards because this removes entries that are freed. 839 for (int i = _deallocate_list->length() - 1; i >= 0; i--) { 840 Metadata* m = _deallocate_list->at(i); 841 if (!m->on_stack()) { 842 _deallocate_list->remove_at(i); 843 // There are only three types of metadata that we deallocate directly. 844 // Cast them so they can be used by the template function. 845 if (m->is_method()) { 846 MetadataFactory::free_metadata(this, (Method*)m); 847 } else if (m->is_constantPool()) { 848 MetadataFactory::free_metadata(this, (ConstantPool*)m); 849 } else if (m->is_klass()) { 850 if (!((Klass*)m)->is_value()) { 851 MetadataFactory::free_metadata(this, (InstanceKlass*)m); 852 } else { 853 MetadataFactory::free_metadata(this, (ValueKlass*)m); 854 } 855 } else { 856 ShouldNotReachHere(); 857 } 858 } else { 859 // Metadata is alive. 860 // If scratch_class is on stack then it shouldn't be on this list! 861 assert(!m->is_klass() || !((InstanceKlass*)m)->is_scratch_class(), 862 "scratch classes on this list should be dead"); 863 // Also should assert that other metadata on the list was found in handles. 864 // Some cleaning remains. 865 ClassLoaderDataGraph::set_should_clean_deallocate_lists(); 866 } 867 } 868 } 869 870 // This is distinct from free_deallocate_list. For class loader data that are 871 // unloading, this frees the C heap memory for items on the list, and unlinks 872 // scratch or error classes so that unloading events aren't triggered for these 873 // classes. The metadata is removed with the unloading metaspace. 874 // There isn't C heap memory allocated for methods, so nothing is done for them. 875 void ClassLoaderData::free_deallocate_list_C_heap_structures() { 876 assert_locked_or_safepoint(ClassLoaderDataGraph_lock); 877 assert(is_unloading(), "only called for ClassLoaderData that are unloading"); 878 if (_deallocate_list == NULL) { 879 return; 880 } 881 // Go backwards because this removes entries that are freed. 882 for (int i = _deallocate_list->length() - 1; i >= 0; i--) { 883 Metadata* m = _deallocate_list->at(i); 884 _deallocate_list->remove_at(i); 885 if (m->is_constantPool()) { 886 ((ConstantPool*)m)->release_C_heap_structures(); 887 } else if (m->is_klass()) { 888 InstanceKlass* ik = (InstanceKlass*)m; 889 // also releases ik->constants() C heap memory 890 InstanceKlass::release_C_heap_structures(ik); 891 // Remove the class so unloading events aren't triggered for 892 // this class (scratch or error class) in do_unloading(). 893 remove_class(ik); 894 } 895 } 896 } 897 898 // These CLDs are to contain unsafe anonymous classes used for JSR292 899 ClassLoaderData* ClassLoaderData::unsafe_anonymous_class_loader_data(Handle loader) { 900 // Add a new class loader data to the graph. 901 return ClassLoaderDataGraph::add(loader, true); 902 } 903 904 // Caller needs ResourceMark 905 // If the class loader's _name has not been explicitly set, the class loader's 906 // qualified class name is returned. 907 const char* ClassLoaderData::loader_name() const { 908 if (_class_loader_klass == NULL) { 909 return BOOTSTRAP_LOADER_NAME; 910 } else if (_name != NULL) { 911 return _name->as_C_string(); 912 } else { 913 return _class_loader_klass->external_name(); 914 } 915 } 916 917 // Caller needs ResourceMark 918 // Format of the _name_and_id is as follows: 919 // If the defining loader has a name explicitly set then '<loader-name>' @<id> 920 // If the defining loader has no name then <qualified-class-name> @<id> 921 // If built-in loader, then omit '@<id>' as there is only one instance. 922 const char* ClassLoaderData::loader_name_and_id() const { 923 if (_class_loader_klass == NULL) { 924 return "'" BOOTSTRAP_LOADER_NAME "'"; 925 } else if (_name_and_id != NULL) { 926 return _name_and_id->as_C_string(); 927 } else { 928 // May be called in a race before _name_and_id is initialized. 929 return _class_loader_klass->external_name(); 930 } 931 } 932 933 void ClassLoaderData::print_value_on(outputStream* out) const { 934 if (!is_unloading() && class_loader() != NULL) { 935 out->print("loader data: " INTPTR_FORMAT " for instance ", p2i(this)); 936 class_loader()->print_value_on(out); // includes loader_name_and_id() and address of class loader instance 937 } else { 938 // loader data: 0xsomeaddr of 'bootstrap' 939 out->print("loader data: " INTPTR_FORMAT " of %s", p2i(this), loader_name_and_id()); 940 } 941 if (is_unsafe_anonymous()) { 942 out->print(" unsafe anonymous"); 943 } 944 } 945 946 void ClassLoaderData::print_value() const { print_value_on(tty); } 947 948 #ifndef PRODUCT 949 void ClassLoaderData::print_on(outputStream* out) const { 950 out->print("ClassLoaderData CLD: " PTR_FORMAT ", loader: " PTR_FORMAT ", loader_klass: %s {", 951 p2i(this), p2i(_class_loader.ptr_raw()), loader_name_and_id()); 952 if (is_unsafe_anonymous()) out->print(" unsafe anonymous"); 953 if (claimed()) out->print(" claimed"); 954 if (is_unloading()) out->print(" unloading"); 955 out->print(" metaspace: " INTPTR_FORMAT, p2i(metaspace_or_null())); 956 957 if (_jmethod_ids != NULL) { 958 Method::print_jmethod_ids(this, out); 959 } 960 out->print(" handles count %d", _handles.count()); 961 out->print(" dependencies %d", _dependency_count); 962 out->print_cr("}"); 963 } 964 #endif // PRODUCT 965 966 void ClassLoaderData::print() const { print_on(tty); } 967 968 void ClassLoaderData::verify() { 969 assert_locked_or_safepoint(_metaspace_lock); 970 oop cl = class_loader(); 971 972 guarantee(this == class_loader_data(cl) || is_unsafe_anonymous(), "Must be the same"); 973 guarantee(cl != NULL || this == ClassLoaderData::the_null_class_loader_data() || is_unsafe_anonymous(), "must be"); 974 975 // Verify the integrity of the allocated space. 976 if (metaspace_or_null() != NULL) { 977 metaspace_or_null()->verify(); 978 } 979 980 for (Klass* k = _klasses; k != NULL; k = k->next_link()) { 981 guarantee(k->class_loader_data() == this, "Must be the same"); 982 k->verify(); 983 assert(k != k->next_link(), "no loops!"); 984 } 985 } 986 987 bool ClassLoaderData::contains_klass(Klass* klass) { 988 // Lock-free access requires load_acquire 989 for (Klass* k = OrderAccess::load_acquire(&_klasses); k != NULL; k = k->next_link()) { 990 if (k == klass) return true; 991 } 992 return false; 993 }