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