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