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