1 /*
2 * Copyright (c) 2012, 2017, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.
8 *
9 * This code is distributed in the hope that it will be useful, but WITHOUT
10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
12 * version 2 for more details (a copy is included in the LICENSE file that
13 * accompanied this code).
14 *
15 * You should have received a copy of the GNU General Public License version
16 * 2 along with this work; if not, write to the Free Software Foundation,
17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18 *
19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20 * or visit www.oracle.com if you need additional information or have any
21 * questions.
22 *
23 */
24
25 // A ClassLoaderData identifies the full set of class types that a class
26 // loader's name resolution strategy produces for a given configuration of the
27 // class loader.
28 // Class types in the ClassLoaderData may be defined by from class file binaries
29 // provided by the class loader, or from other class loader it interacts with
30 // according to its name resolution strategy.
31 //
32 // Class loaders that implement a deterministic name resolution strategy
33 // (including with respect to their delegation behavior), such as the boot, the
34 // platform, and the system loaders of the JDK's built-in class loader
35 // hierarchy, always produce the same linkset for a given configuration.
36 //
37 // ClassLoaderData carries information related to a linkset (e.g.,
38 // metaspace holding its klass definitions).
39 // The System Dictionary and related data structures (e.g., placeholder table,
40 // loader constraints table) as well as the runtime representation of classes
41 // only reference ClassLoaderData.
42 //
43 // Instances of java.lang.ClassLoader holds a pointer to a ClassLoaderData that
44 // that represent the loader's "linking domain" in the JVM.
45 //
46 // The bootstrap loader (represented by NULL) also has a ClassLoaderData,
47 // the singleton class the_null_class_loader_data().
48
49 #include "precompiled.hpp"
50 #include "classfile/classLoaderData.hpp"
51 #include "classfile/classLoaderData.inline.hpp"
52 #include "classfile/javaClasses.hpp"
53 #include "classfile/metadataOnStackMark.hpp"
54 #include "classfile/moduleEntry.hpp"
55 #include "classfile/packageEntry.hpp"
56 #include "classfile/systemDictionary.hpp"
57 #include "code/codeCache.hpp"
58 #include "gc/shared/gcLocker.hpp"
59 #include "logging/log.hpp"
60 #include "memory/metadataFactory.hpp"
61 #include "memory/metaspaceShared.hpp"
62 #include "memory/oopFactory.hpp"
63 #include "memory/resourceArea.hpp"
64 #include "oops/objArrayOop.inline.hpp"
65 #include "oops/oop.inline.hpp"
66 #include "runtime/atomic.hpp"
67 #include "runtime/javaCalls.hpp"
68 #include "runtime/jniHandles.hpp"
69 #include "runtime/mutex.hpp"
70 #include "runtime/orderAccess.hpp"
71 #include "runtime/safepoint.hpp"
72 #include "runtime/synchronizer.hpp"
73 #include "utilities/growableArray.hpp"
74 #include "utilities/macros.hpp"
75 #include "utilities/ostream.hpp"
76 #if INCLUDE_TRACE
77 #include "trace/tracing.hpp"
78 #endif
79
80 // helper function to avoid in-line casts
81 template <typename T> static T* load_ptr_acquire(T* volatile *p) {
82 return static_cast<T*>(OrderAccess::load_ptr_acquire(p));
83 }
84
85 ClassLoaderData * ClassLoaderData::_the_null_class_loader_data = NULL;
86
87 ClassLoaderData::ClassLoaderData(Handle h_class_loader, bool is_anonymous, Dependencies dependencies) :
88 _class_loader(h_class_loader()),
89 _is_anonymous(is_anonymous),
90 // An anonymous class loader data doesn't have anything to keep
91 // it from being unloaded during parsing of the anonymous class.
92 // The null-class-loader should always be kept alive.
93 _keep_alive((is_anonymous || h_class_loader.is_null()) ? 1 : 0),
94 _metaspace(NULL), _unloading(false), _klasses(NULL),
95 _modules(NULL), _packages(NULL),
96 _claimed(0), _jmethod_ids(NULL), _handles(NULL), _deallocate_list(NULL),
97 _next(NULL), _dependencies(dependencies),
98 _metaspace_lock(new Mutex(Monitor::leaf+1, "Metaspace allocation lock", true,
99 Monitor::_safepoint_check_never)) {
100 TRACE_INIT_ID(this);
101 }
102
103 void ClassLoaderData::init_dependencies(TRAPS) {
104 assert(!Universe::is_fully_initialized(), "should only be called when initializing");
105 assert(is_the_null_class_loader_data(), "should only call this for the null class loader");
106 _dependencies.init(CHECK);
107 }
108
109 void ClassLoaderData::Dependencies::init(TRAPS) {
110 // Create empty dependencies array to add to. CMS requires this to be
111 // an oop so that it can track additions via card marks. We think.
112 _list_head = oopFactory::new_objectArray(2, CHECK);
113 }
114
115 bool ClassLoaderData::claim() {
116 if (_claimed == 1) {
117 return false;
118 }
119
120 return (int) Atomic::cmpxchg(1, &_claimed, 0) == 0;
121 }
122
123 // Anonymous classes have their own ClassLoaderData that is marked to keep alive
124 // while the class is being parsed, and if the class appears on the module fixup list.
125 // Due to the uniqueness that no other class shares the anonymous class' name or
126 // ClassLoaderData, no other non-GC thread has knowledge of the anonymous class while
127 // it is being defined, therefore _keep_alive is not volatile or atomic.
128 void ClassLoaderData::inc_keep_alive() {
129 if (is_anonymous()) {
130 assert(_keep_alive >= 0, "Invalid keep alive increment count");
131 _keep_alive++;
132 }
133 }
134
135 void ClassLoaderData::dec_keep_alive() {
136 if (is_anonymous()) {
137 assert(_keep_alive > 0, "Invalid keep alive decrement count");
138 _keep_alive--;
139 }
140 }
141
142 void ClassLoaderData::oops_do(OopClosure* f, KlassClosure* klass_closure, bool must_claim) {
143 if (must_claim && !claim()) {
144 return;
145 }
146
147 f->do_oop(&_class_loader);
148 _dependencies.oops_do(f);
149 if (_handles != NULL) {
150 _handles->oops_do(f);
151 }
152 if (klass_closure != NULL) {
153 classes_do(klass_closure);
154 }
155 }
156
157 void ClassLoaderData::Dependencies::oops_do(OopClosure* f) {
158 f->do_oop((oop*)&_list_head);
159 }
160
161 void ClassLoaderData::classes_do(KlassClosure* klass_closure) {
162 // Lock-free access requires load_ptr_acquire
163 for (Klass* k = load_ptr_acquire(&_klasses); k != NULL; k = k->next_link()) {
164 klass_closure->do_klass(k);
165 assert(k != k->next_link(), "no loops!");
166 }
167 }
168
169 void ClassLoaderData::classes_do(void f(Klass * const)) {
170 // Lock-free access requires load_ptr_acquire
171 for (Klass* k = load_ptr_acquire(&_klasses); k != NULL; k = k->next_link()) {
172 f(k);
173 assert(k != k->next_link(), "no loops!");
174 }
175 }
176
177 void ClassLoaderData::methods_do(void f(Method*)) {
178 // Lock-free access requires load_ptr_acquire
179 for (Klass* k = load_ptr_acquire(&_klasses); k != NULL; k = k->next_link()) {
180 if (k->is_instance_klass()) {
181 InstanceKlass::cast(k)->methods_do(f);
182 }
183 }
184 }
185
186 void ClassLoaderData::loaded_classes_do(KlassClosure* klass_closure) {
187 // Lock to avoid classes being modified/added/removed during iteration
188 MutexLockerEx ml(metaspace_lock(), Mutex::_no_safepoint_check_flag);
189 for (Klass* k = _klasses; k != NULL; k = k->next_link()) {
190 // Do not filter ArrayKlass oops here...
191 if (k->is_array_klass() || (k->is_instance_klass() && InstanceKlass::cast(k)->is_loaded())) {
192 klass_closure->do_klass(k);
193 }
194 }
195 }
196
197 void ClassLoaderData::classes_do(void f(InstanceKlass*)) {
198 // Lock-free access requires load_ptr_acquire
199 for (Klass* k = load_ptr_acquire(&_klasses); k != NULL; k = k->next_link()) {
200 if (k->is_instance_klass()) {
201 f(InstanceKlass::cast(k));
202 }
203 assert(k != k->next_link(), "no loops!");
204 }
205 }
206
207 void ClassLoaderData::modules_do(void f(ModuleEntry*)) {
208 assert_locked_or_safepoint(Module_lock);
209 if (_modules != NULL) {
210 for (int i = 0; i < _modules->table_size(); i++) {
211 for (ModuleEntry* entry = _modules->bucket(i);
212 entry != NULL;
213 entry = entry->next()) {
214 f(entry);
215 }
216 }
217 }
218 }
219
220 void ClassLoaderData::packages_do(void f(PackageEntry*)) {
221 // Lock-free access requires load_ptr_acquire
222 PackageEntryTable* packages = load_ptr_acquire(&_packages);
223 if (packages != NULL) {
224 for (int i = 0; i < packages->table_size(); i++) {
225 for (PackageEntry* entry = packages->bucket(i);
226 entry != NULL;
227 entry = entry->next()) {
228 f(entry);
229 }
230 }
231 }
232 }
233
234 void ClassLoaderData::record_dependency(const Klass* k, TRAPS) {
235 assert(k != NULL, "invariant");
236
237 ClassLoaderData * const from_cld = this;
238 ClassLoaderData * const to_cld = k->class_loader_data();
239
240 // Dependency to the null class loader data doesn't need to be recorded
241 // because the null class loader data never goes away.
242 if (to_cld->is_the_null_class_loader_data()) {
243 return;
244 }
245
246 oop to;
247 if (to_cld->is_anonymous()) {
248 // Anonymous class dependencies are through the mirror.
249 to = k->java_mirror();
250 } else {
251 to = to_cld->class_loader();
252
253 // If from_cld is anonymous, even if it's class_loader is a parent of 'to'
254 // we still have to add it. The class_loader won't keep from_cld alive.
255 if (!from_cld->is_anonymous()) {
256 // Check that this dependency isn't from the same or parent class_loader
257 oop from = from_cld->class_loader();
258
259 oop curr = from;
260 while (curr != NULL) {
261 if (curr == to) {
262 return; // this class loader is in the parent list, no need to add it.
263 }
264 curr = java_lang_ClassLoader::parent(curr);
265 }
266 }
267 }
268
269 // It's a dependency we won't find through GC, add it. This is relatively rare
270 // Must handle over GC point.
271 Handle dependency(THREAD, to);
272 from_cld->_dependencies.add(dependency, CHECK);
273 }
274
275
276 void ClassLoaderData::Dependencies::add(Handle dependency, TRAPS) {
277 // Check first if this dependency is already in the list.
278 // Save a pointer to the last to add to under the lock.
279 objArrayOop ok = _list_head;
280 objArrayOop last = NULL;
281 while (ok != NULL) {
282 last = ok;
283 if (ok->obj_at(0) == dependency()) {
284 // Don't need to add it
285 return;
286 }
287 ok = (objArrayOop)ok->obj_at(1);
288 }
289
290 // Must handle over GC points
291 assert (last != NULL, "dependencies should be initialized");
292 objArrayHandle last_handle(THREAD, last);
293
294 // Create a new dependency node with fields for (class_loader or mirror, next)
295 objArrayOop deps = oopFactory::new_objectArray(2, CHECK);
296 deps->obj_at_put(0, dependency());
297
298 // Must handle over GC points
299 objArrayHandle new_dependency(THREAD, deps);
300
301 // Add the dependency under lock
302 locked_add(last_handle, new_dependency, THREAD);
303 }
304
305 void ClassLoaderData::Dependencies::locked_add(objArrayHandle last_handle,
306 objArrayHandle new_dependency,
307 Thread* THREAD) {
308
309 // Have to lock and put the new dependency on the end of the dependency
310 // array so the card mark for CMS sees that this dependency is new.
311 // Can probably do this lock free with some effort.
312 ObjectLocker ol(Handle(THREAD, _list_head), THREAD);
313
314 oop loader_or_mirror = new_dependency->obj_at(0);
315
316 // Since the dependencies are only added, add to the end.
317 objArrayOop end = last_handle();
318 objArrayOop last = NULL;
319 while (end != NULL) {
320 last = end;
321 // check again if another thread added it to the end.
322 if (end->obj_at(0) == loader_or_mirror) {
323 // Don't need to add it
324 return;
325 }
326 end = (objArrayOop)end->obj_at(1);
327 }
328 assert (last != NULL, "dependencies should be initialized");
329 // fill in the first element with the oop in new_dependency.
330 if (last->obj_at(0) == NULL) {
331 last->obj_at_put(0, new_dependency->obj_at(0));
332 } else {
333 last->obj_at_put(1, new_dependency());
334 }
335 }
336
337 void ClassLoaderDataGraph::clear_claimed_marks() {
338 for (ClassLoaderData* cld = _head; cld != NULL; cld = cld->next()) {
339 cld->clear_claimed();
340 }
341 }
342
343 void ClassLoaderData::add_class(Klass* k, bool publicize /* true */) {
344 {
345 MutexLockerEx ml(metaspace_lock(), Mutex::_no_safepoint_check_flag);
346 Klass* old_value = _klasses;
347 k->set_next_link(old_value);
348 // Link the new item into the list, making sure the linked class is stable
349 // since the list can be walked without a lock
350 OrderAccess::release_store_ptr(&_klasses, k);
351 }
352
353 if (publicize && k->class_loader_data() != NULL) {
354 ResourceMark rm;
355 log_trace(class, loader, data)("Adding k: " PTR_FORMAT " %s to CLD: "
356 PTR_FORMAT " loader: " PTR_FORMAT " %s",
357 p2i(k),
358 k->external_name(),
359 p2i(k->class_loader_data()),
360 p2i((void *)k->class_loader()),
361 loader_name());
362 }
363 }
364
365 // Remove a klass from the _klasses list for scratch_class during redefinition
366 // or parsed class in the case of an error.
367 void ClassLoaderData::remove_class(Klass* scratch_class) {
368 assert(SafepointSynchronize::is_at_safepoint(), "only called at safepoint");
369 Klass* prev = NULL;
370 for (Klass* k = _klasses; k != NULL; k = k->next_link()) {
371 if (k == scratch_class) {
372 if (prev == NULL) {
373 _klasses = k->next_link();
374 } else {
375 Klass* next = k->next_link();
376 prev->set_next_link(next);
377 }
378 return;
379 }
380 prev = k;
381 assert(k != k->next_link(), "no loops!");
382 }
383 ShouldNotReachHere(); // should have found this class!!
384 }
385
386 void ClassLoaderData::unload() {
387 _unloading = true;
388
389 // Tell serviceability tools these classes are unloading
390 classes_do(InstanceKlass::notify_unload_class);
391
392 if (log_is_enabled(Debug, class, loader, data)) {
393 ResourceMark rm;
394 outputStream* log = Log(class, loader, data)::debug_stream();
395 log->print(": unload loader data " INTPTR_FORMAT, p2i(this));
396 log->print(" for instance " INTPTR_FORMAT " of %s", p2i((void *)class_loader()),
397 loader_name());
398 if (is_anonymous()) {
399 log->print(" for anonymous class " INTPTR_FORMAT " ", p2i(_klasses));
400 }
401 log->cr();
402 }
403
404 // In some rare cases items added to this list will not be freed elsewhere.
405 // To keep it simple, just free everything in it here.
406 free_deallocate_list();
407 }
408
409 PackageEntryTable* ClassLoaderData::packages() {
410 // Lazily create the package entry table at first request.
411 // Lock-free access requires load_ptr_acquire.
412 PackageEntryTable* packages = load_ptr_acquire(&_packages);
413 if (packages == NULL) {
414 MutexLockerEx m1(metaspace_lock(), Mutex::_no_safepoint_check_flag);
415 // Check if _packages got allocated while we were waiting for this lock.
416 if ((packages = _packages) == NULL) {
417 packages = new PackageEntryTable(PackageEntryTable::_packagetable_entry_size);
418 // Ensure _packages is stable, since it is examined without a lock
419 OrderAccess::release_store_ptr(&_packages, packages);
420 }
421 }
422 return packages;
423 }
424
425 ModuleEntryTable* ClassLoaderData::modules() {
426 // Lazily create the module entry table at first request.
427 // Lock-free access requires load_ptr_acquire.
428 ModuleEntryTable* modules = load_ptr_acquire(&_modules);
429 if (modules == NULL) {
430 MutexLocker m1(Module_lock);
431 // Check if _modules got allocated while we were waiting for this lock.
432 if ((modules = _modules) == NULL) {
433 modules = new ModuleEntryTable(ModuleEntryTable::_moduletable_entry_size);
434 // Each loader has one unnamed module entry. Create it before
435 // any classes, loaded by this loader, are defined in case
436 // they end up being defined in loader's unnamed module.
437 modules->create_unnamed_module(this);
438
439 {
440 MutexLockerEx m1(metaspace_lock(), Mutex::_no_safepoint_check_flag);
441 // Ensure _modules is stable, since it is examined without a lock
442 OrderAccess::release_store_ptr(&_modules, modules);
443 }
444 }
445 }
446 return modules;
447 }
448
449 oop ClassLoaderData::keep_alive_object() const {
450 assert_locked_or_safepoint(_metaspace_lock);
451 assert(!keep_alive(), "Don't use with CLDs that are artificially kept alive");
452 return is_anonymous() ? _klasses->java_mirror() : class_loader();
453 }
454
455 bool ClassLoaderData::is_alive(BoolObjectClosure* is_alive_closure) const {
456 bool alive = keep_alive() // null class loader and incomplete anonymous klasses.
457 || is_alive_closure->do_object_b(keep_alive_object());
458
459 return alive;
460 }
461
462
463 ClassLoaderData::~ClassLoaderData() {
464 // Release C heap structures for all the classes.
465 classes_do(InstanceKlass::release_C_heap_structures);
466
467 // Release C heap allocated hashtable for all the packages.
468 if (_packages != NULL) {
469 // Destroy the table itself
470 delete _packages;
471 _packages = NULL;
472 }
473
474 // Release C heap allocated hashtable for all the modules.
475 if (_modules != NULL) {
476 // Destroy the table itself
477 delete _modules;
478 _modules = NULL;
479 }
480
481 // release the metaspace
482 Metaspace *m = _metaspace;
483 if (m != NULL) {
484 _metaspace = NULL;
485 delete m;
486 }
487 // release the handles
488 if (_handles != NULL) {
489 JNIHandleBlock::release_block(_handles);
490 _handles = NULL;
491 }
492
493 // Clear all the JNI handles for methods
494 // These aren't deallocated and are going to look like a leak, but that's
495 // needed because we can't really get rid of jmethodIDs because we don't
496 // know when native code is going to stop using them. The spec says that
497 // they're "invalid" but existing programs likely rely on their being
498 // NULL after class unloading.
499 if (_jmethod_ids != NULL) {
500 Method::clear_jmethod_ids(this);
501 }
502 // Delete lock
503 delete _metaspace_lock;
504
505 // Delete free list
506 if (_deallocate_list != NULL) {
507 delete _deallocate_list;
508 }
509 }
510
511 // Returns true if this class loader data is for the system class loader.
512 bool ClassLoaderData::is_system_class_loader_data() const {
513 return SystemDictionary::is_system_class_loader(class_loader());
514 }
515
516 // Returns true if this class loader data is for the platform class loader.
517 bool ClassLoaderData::is_platform_class_loader_data() const {
518 return SystemDictionary::is_platform_class_loader(class_loader());
519 }
520
521 // Returns true if this class loader data is one of the 3 builtin
522 // (boot, application/system or platform) class loaders. Note, the
523 // builtin loaders are not freed by a GC.
524 bool ClassLoaderData::is_builtin_class_loader_data() const {
525 return (is_the_null_class_loader_data() ||
526 SystemDictionary::is_system_class_loader(class_loader()) ||
527 SystemDictionary::is_platform_class_loader(class_loader()));
528 }
529
530 Metaspace* ClassLoaderData::metaspace_non_null() {
531 assert(!DumpSharedSpaces, "wrong metaspace!");
532 // If the metaspace has not been allocated, create a new one. Might want
533 // to create smaller arena for Reflection class loaders also.
534 // The reason for the delayed allocation is because some class loaders are
535 // simply for delegating with no metadata of their own.
536 // Lock-free access requires load_ptr_acquire.
537 Metaspace* metaspace = load_ptr_acquire(&_metaspace);
538 if (metaspace == NULL) {
539 MutexLockerEx ml(_metaspace_lock, Mutex::_no_safepoint_check_flag);
540 // Check if _metaspace got allocated while we were waiting for this lock.
541 if ((metaspace = _metaspace) == NULL) {
542 if (this == the_null_class_loader_data()) {
543 assert (class_loader() == NULL, "Must be");
544 metaspace = new Metaspace(_metaspace_lock, Metaspace::BootMetaspaceType);
545 } else if (is_anonymous()) {
546 if (class_loader() != NULL) {
547 log_trace(class, loader, data)("is_anonymous: %s", class_loader()->klass()->internal_name());
548 }
549 metaspace = new Metaspace(_metaspace_lock, Metaspace::AnonymousMetaspaceType);
550 } else if (class_loader()->is_a(SystemDictionary::reflect_DelegatingClassLoader_klass())) {
551 if (class_loader() != NULL) {
552 log_trace(class, loader, data)("is_reflection: %s", class_loader()->klass()->internal_name());
553 }
554 metaspace = new Metaspace(_metaspace_lock, Metaspace::ReflectionMetaspaceType);
555 } else {
556 metaspace = new Metaspace(_metaspace_lock, Metaspace::StandardMetaspaceType);
557 }
558 // Ensure _metaspace is stable, since it is examined without a lock
559 OrderAccess::release_store_ptr(&_metaspace, metaspace);
560 }
561 }
562 return metaspace;
563 }
564
565 JNIHandleBlock* ClassLoaderData::handles() const { return _handles; }
566 void ClassLoaderData::set_handles(JNIHandleBlock* handles) { _handles = handles; }
567
568 jobject ClassLoaderData::add_handle(Handle h) {
569 MutexLockerEx ml(metaspace_lock(), Mutex::_no_safepoint_check_flag);
570 if (handles() == NULL) {
571 set_handles(JNIHandleBlock::allocate_block());
572 }
573 return handles()->allocate_handle(h());
574 }
575
576 void ClassLoaderData::remove_handle(jobject h) {
577 _handles->release_handle(h);
578 }
579
580 // Add this metadata pointer to be freed when it's safe. This is only during
581 // class unloading because Handles might point to this metadata field.
582 void ClassLoaderData::add_to_deallocate_list(Metadata* m) {
583 // Metadata in shared region isn't deleted.
584 if (!m->is_shared()) {
585 MutexLockerEx ml(metaspace_lock(), Mutex::_no_safepoint_check_flag);
586 if (_deallocate_list == NULL) {
587 _deallocate_list = new (ResourceObj::C_HEAP, mtClass) GrowableArray<Metadata*>(100, true);
588 }
589 _deallocate_list->append_if_missing(m);
590 }
591 }
592
593 // Deallocate free metadata on the free list. How useful the PermGen was!
594 void ClassLoaderData::free_deallocate_list() {
595 // Don't need lock, at safepoint
596 assert(SafepointSynchronize::is_at_safepoint(), "only called at safepoint");
597 if (_deallocate_list == NULL) {
598 return;
599 }
600 // Go backwards because this removes entries that are freed.
601 for (int i = _deallocate_list->length() - 1; i >= 0; i--) {
602 Metadata* m = _deallocate_list->at(i);
603 if (!m->on_stack()) {
604 _deallocate_list->remove_at(i);
605 // There are only three types of metadata that we deallocate directly.
606 // Cast them so they can be used by the template function.
607 if (m->is_method()) {
608 MetadataFactory::free_metadata(this, (Method*)m);
609 } else if (m->is_constantPool()) {
610 MetadataFactory::free_metadata(this, (ConstantPool*)m);
611 } else if (m->is_klass()) {
612 MetadataFactory::free_metadata(this, (InstanceKlass*)m);
613 } else {
614 ShouldNotReachHere();
615 }
616 } else {
617 // Metadata is alive.
618 // If scratch_class is on stack then it shouldn't be on this list!
619 assert(!m->is_klass() || !((InstanceKlass*)m)->is_scratch_class(),
620 "scratch classes on this list should be dead");
621 // Also should assert that other metadata on the list was found in handles.
622 }
623 }
624 }
625
626 // These anonymous class loaders are to contain classes used for JSR292
627 ClassLoaderData* ClassLoaderData::anonymous_class_loader_data(oop loader, TRAPS) {
628 // Add a new class loader data to the graph.
629 Handle lh(THREAD, loader);
630 return ClassLoaderDataGraph::add(lh, true, THREAD);
631 }
632
633 const char* ClassLoaderData::loader_name() {
634 // Handles null class loader
635 return SystemDictionary::loader_name(class_loader());
636 }
637
638 #ifndef PRODUCT
639 // Define to dump klasses
640 #undef CLD_DUMP_KLASSES
641
642 void ClassLoaderData::dump(outputStream * const out) {
643 out->print("ClassLoaderData CLD: " PTR_FORMAT ", loader: " PTR_FORMAT ", loader_klass: " PTR_FORMAT " %s {",
644 p2i(this), p2i((void *)class_loader()),
645 p2i(class_loader() != NULL ? class_loader()->klass() : NULL), loader_name());
646 if (claimed()) out->print(" claimed ");
647 if (is_unloading()) out->print(" unloading ");
648 out->print(" handles " INTPTR_FORMAT, p2i(handles()));
649 out->cr();
650 if (metaspace_or_null() != NULL) {
651 out->print_cr("metaspace: " INTPTR_FORMAT, p2i(metaspace_or_null()));
652 metaspace_or_null()->dump(out);
653 } else {
654 out->print_cr("metaspace: NULL");
655 }
656
657 #ifdef CLD_DUMP_KLASSES
658 if (Verbose) {
659 Klass* k = _klasses;
660 while (k != NULL) {
661 out->print_cr("klass " PTR_FORMAT ", %s, CT: %d, MUT: %d", k, k->name()->as_C_string(),
662 k->has_modified_oops(), k->has_accumulated_modified_oops());
663 assert(k != k->next_link(), "no loops!");
664 k = k->next_link();
665 }
666 }
667 #endif // CLD_DUMP_KLASSES
668 #undef CLD_DUMP_KLASSES
669 if (_jmethod_ids != NULL) {
670 Method::print_jmethod_ids(this, out);
671 }
672 out->print_cr("}");
673 }
674 #endif // PRODUCT
675
676 void ClassLoaderData::verify() {
677 assert_locked_or_safepoint(_metaspace_lock);
678 oop cl = class_loader();
679
680 guarantee(this == class_loader_data(cl) || is_anonymous(), "Must be the same");
681 guarantee(cl != NULL || this == ClassLoaderData::the_null_class_loader_data() || is_anonymous(), "must be");
682
683 // Verify the integrity of the allocated space.
684 if (metaspace_or_null() != NULL) {
685 metaspace_or_null()->verify();
686 }
687
688 for (Klass* k = _klasses; k != NULL; k = k->next_link()) {
689 guarantee(k->class_loader_data() == this, "Must be the same");
690 k->verify();
691 assert(k != k->next_link(), "no loops!");
692 }
693 }
694
695 bool ClassLoaderData::contains_klass(Klass* klass) {
696 // Lock-free access requires load_ptr_acquire
697 for (Klass* k = load_ptr_acquire(&_klasses); k != NULL; k = k->next_link()) {
698 if (k == klass) return true;
699 }
700 return false;
701 }
702
703
704 // GC root of class loader data created.
705 ClassLoaderData* ClassLoaderDataGraph::_head = NULL;
706 ClassLoaderData* ClassLoaderDataGraph::_unloading = NULL;
707 ClassLoaderData* ClassLoaderDataGraph::_saved_unloading = NULL;
708 ClassLoaderData* ClassLoaderDataGraph::_saved_head = NULL;
709
710 bool ClassLoaderDataGraph::_should_purge = false;
711 bool ClassLoaderDataGraph::_metaspace_oom = false;
712
713 // Add a new class loader data node to the list. Assign the newly created
714 // ClassLoaderData into the java/lang/ClassLoader object as a hidden field
715 ClassLoaderData* ClassLoaderDataGraph::add(Handle loader, bool is_anonymous, TRAPS) {
716 // We need to allocate all the oops for the ClassLoaderData before allocating the
717 // actual ClassLoaderData object.
718 ClassLoaderData::Dependencies dependencies(CHECK_NULL);
719
720 NoSafepointVerifier no_safepoints; // we mustn't GC until we've installed the
721 // ClassLoaderData in the graph since the CLD
722 // contains unhandled oops
723
724 ClassLoaderData* cld = new ClassLoaderData(loader, is_anonymous, dependencies);
725
726
727 if (!is_anonymous) {
728 ClassLoaderData** cld_addr = java_lang_ClassLoader::loader_data_addr(loader());
729 // First, Atomically set it
730 ClassLoaderData* old = (ClassLoaderData*) Atomic::cmpxchg_ptr(cld, cld_addr, NULL);
731 if (old != NULL) {
732 delete cld;
733 // Returns the data.
734 return old;
735 }
736 }
737
738 // We won the race, and therefore the task of adding the data to the list of
739 // class loader data
740 ClassLoaderData** list_head = &_head;
741 ClassLoaderData* next = _head;
742
743 do {
744 cld->set_next(next);
745 ClassLoaderData* exchanged = (ClassLoaderData*)Atomic::cmpxchg_ptr(cld, list_head, next);
746 if (exchanged == next) {
747 if (log_is_enabled(Debug, class, loader, data)) {
748 PauseNoSafepointVerifier pnsv(&no_safepoints); // Need safe points for JavaCalls::call_virtual
749 log_creation(loader, cld, CHECK_NULL);
750 }
751 return cld;
752 }
753 next = exchanged;
754 } while (true);
755 }
756
757 void ClassLoaderDataGraph::log_creation(Handle loader, ClassLoaderData* cld, TRAPS) {
758 Handle string;
759 if (loader.not_null()) {
760 // Include the result of loader.toString() in the output. This allows
761 // the user of the log to identify the class loader instance.
762 JavaValue result(T_OBJECT);
763 Klass* spec_klass = SystemDictionary::ClassLoader_klass();
764 JavaCalls::call_virtual(&result,
765 loader,
766 spec_klass,
767 vmSymbols::toString_name(),
768 vmSymbols::void_string_signature(),
769 CHECK);
770 assert(result.get_type() == T_OBJECT, "just checking");
771 string = Handle(THREAD, (oop)result.get_jobject());
772 }
773
774 ResourceMark rm;
775 outputStream* log = Log(class, loader, data)::debug_stream();
776 log->print("create class loader data " INTPTR_FORMAT, p2i(cld));
777 log->print(" for instance " INTPTR_FORMAT " of %s", p2i((void *)cld->class_loader()),
778 cld->loader_name());
779
780 if (string.not_null()) {
781 log->print(": ");
782 java_lang_String::print(string(), log);
783 }
784 log->cr();
785 }
786
787
788 void ClassLoaderDataGraph::oops_do(OopClosure* f, KlassClosure* klass_closure, bool must_claim) {
789 for (ClassLoaderData* cld = _head; cld != NULL; cld = cld->next()) {
790 cld->oops_do(f, klass_closure, must_claim);
791 }
792 }
793
794 void ClassLoaderDataGraph::keep_alive_oops_do(OopClosure* f, KlassClosure* klass_closure, bool must_claim) {
795 for (ClassLoaderData* cld = _head; cld != NULL; cld = cld->next()) {
796 if (cld->keep_alive()) {
797 cld->oops_do(f, klass_closure, must_claim);
798 }
799 }
800 }
801
802 void ClassLoaderDataGraph::always_strong_oops_do(OopClosure* f, KlassClosure* klass_closure, bool must_claim) {
803 if (ClassUnloading) {
804 keep_alive_oops_do(f, klass_closure, must_claim);
805 } else {
806 oops_do(f, klass_closure, must_claim);
807 }
808 }
809
810 void ClassLoaderDataGraph::cld_do(CLDClosure* cl) {
811 for (ClassLoaderData* cld = _head; cl != NULL && cld != NULL; cld = cld->next()) {
812 cl->do_cld(cld);
813 }
814 }
815
816 void ClassLoaderDataGraph::cld_unloading_do(CLDClosure* cl) {
817 assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint!");
818 // Only walk the head until any clds not purged from prior unloading
819 // (CMS doesn't purge right away).
820 for (ClassLoaderData* cld = _unloading; cld != _saved_unloading; cld = cld->next()) {
821 assert(cld->is_unloading(), "invariant");
822 cl->do_cld(cld);
823 }
824 }
825
826 void ClassLoaderDataGraph::roots_cld_do(CLDClosure* strong, CLDClosure* weak) {
827 for (ClassLoaderData* cld = _head; cld != NULL; cld = cld->_next) {
828 CLDClosure* closure = cld->keep_alive() ? strong : weak;
829 if (closure != NULL) {
830 closure->do_cld(cld);
831 }
832 }
833 }
834
835 void ClassLoaderDataGraph::keep_alive_cld_do(CLDClosure* cl) {
836 roots_cld_do(cl, NULL);
837 }
838
839 void ClassLoaderDataGraph::always_strong_cld_do(CLDClosure* cl) {
840 if (ClassUnloading) {
841 keep_alive_cld_do(cl);
842 } else {
843 cld_do(cl);
844 }
845 }
846
847 void ClassLoaderDataGraph::classes_do(KlassClosure* klass_closure) {
848 for (ClassLoaderData* cld = _head; cld != NULL; cld = cld->next()) {
849 cld->classes_do(klass_closure);
850 }
851 }
852
853 void ClassLoaderDataGraph::classes_do(void f(Klass* const)) {
854 for (ClassLoaderData* cld = _head; cld != NULL; cld = cld->next()) {
855 cld->classes_do(f);
856 }
857 }
858
859 void ClassLoaderDataGraph::methods_do(void f(Method*)) {
860 for (ClassLoaderData* cld = _head; cld != NULL; cld = cld->next()) {
861 cld->methods_do(f);
862 }
863 }
864
865 void ClassLoaderDataGraph::modules_do(void f(ModuleEntry*)) {
866 assert_locked_or_safepoint(Module_lock);
867 for (ClassLoaderData* cld = _head; cld != NULL; cld = cld->next()) {
868 cld->modules_do(f);
869 }
870 }
871
872 void ClassLoaderDataGraph::modules_unloading_do(void f(ModuleEntry*)) {
873 assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint!");
874 // Only walk the head until any clds not purged from prior unloading
875 // (CMS doesn't purge right away).
876 for (ClassLoaderData* cld = _unloading; cld != _saved_unloading; cld = cld->next()) {
877 assert(cld->is_unloading(), "invariant");
878 cld->modules_do(f);
879 }
880 }
881
882 void ClassLoaderDataGraph::packages_do(void f(PackageEntry*)) {
883 assert_locked_or_safepoint(Module_lock);
884 for (ClassLoaderData* cld = _head; cld != NULL; cld = cld->next()) {
885 cld->packages_do(f);
886 }
887 }
888
889 void ClassLoaderDataGraph::packages_unloading_do(void f(PackageEntry*)) {
890 assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint!");
891 // Only walk the head until any clds not purged from prior unloading
892 // (CMS doesn't purge right away).
893 for (ClassLoaderData* cld = _unloading; cld != _saved_unloading; cld = cld->next()) {
894 assert(cld->is_unloading(), "invariant");
895 cld->packages_do(f);
896 }
897 }
898
899 void ClassLoaderDataGraph::loaded_classes_do(KlassClosure* klass_closure) {
900 for (ClassLoaderData* cld = _head; cld != NULL; cld = cld->next()) {
901 cld->loaded_classes_do(klass_closure);
902 }
903 }
904
905 void ClassLoaderDataGraph::classes_unloading_do(void f(Klass* const)) {
906 assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint!");
907 // Only walk the head until any clds not purged from prior unloading
908 // (CMS doesn't purge right away).
909 for (ClassLoaderData* cld = _unloading; cld != _saved_unloading; cld = cld->next()) {
910 assert(cld->is_unloading(), "invariant");
911 cld->classes_do(f);
912 }
913 }
914
915 GrowableArray<ClassLoaderData*>* ClassLoaderDataGraph::new_clds() {
916 assert(_head == NULL || _saved_head != NULL, "remember_new_clds(true) not called?");
917
918 GrowableArray<ClassLoaderData*>* array = new GrowableArray<ClassLoaderData*>();
919
920 // The CLDs in [_head, _saved_head] were all added during last call to remember_new_clds(true);
921 ClassLoaderData* curr = _head;
922 while (curr != _saved_head) {
923 if (!curr->claimed()) {
924 array->push(curr);
925
926 if (log_is_enabled(Debug, class, loader, data)) {
927 outputStream* log = Log(class, loader, data)::debug_stream();
928 log->print("found new CLD: ");
929 curr->print_value_on(log);
930 log->cr();
931 }
932 }
933
934 curr = curr->_next;
935 }
936
937 return array;
938 }
939
940 bool ClassLoaderDataGraph::unload_list_contains(const void* x) {
941 assert(SafepointSynchronize::is_at_safepoint(), "only safe to call at safepoint");
942 for (ClassLoaderData* cld = _unloading; cld != NULL; cld = cld->next()) {
943 if (cld->metaspace_or_null() != NULL && cld->metaspace_or_null()->contains(x)) {
944 return true;
945 }
946 }
947 return false;
948 }
949
950 #ifndef PRODUCT
951 bool ClassLoaderDataGraph::contains_loader_data(ClassLoaderData* loader_data) {
952 for (ClassLoaderData* data = _head; data != NULL; data = data->next()) {
953 if (loader_data == data) {
954 return true;
955 }
956 }
957
958 return false;
959 }
960 #endif // PRODUCT
961
962
963 // Move class loader data from main list to the unloaded list for unloading
964 // and deallocation later.
965 bool ClassLoaderDataGraph::do_unloading(BoolObjectClosure* is_alive_closure,
966 bool clean_previous_versions) {
967
968 ClassLoaderData* data = _head;
969 ClassLoaderData* prev = NULL;
970 bool seen_dead_loader = false;
971
972 // Mark metadata seen on the stack only so we can delete unneeded entries.
973 // Only walk all metadata, including the expensive code cache walk, for Full GC
974 // and only if class redefinition and if there's previous versions of
975 // Klasses to delete.
976 bool walk_all_metadata = clean_previous_versions &&
977 JvmtiExport::has_redefined_a_class() &&
978 InstanceKlass::has_previous_versions_and_reset();
979 MetadataOnStackMark md_on_stack(walk_all_metadata);
980
981 // Save previous _unloading pointer for CMS which may add to unloading list before
982 // purging and we don't want to rewalk the previously unloaded class loader data.
983 _saved_unloading = _unloading;
984
985 data = _head;
986 while (data != NULL) {
987 if (data->is_alive(is_alive_closure)) {
988 // clean metaspace
989 if (walk_all_metadata) {
990 data->classes_do(InstanceKlass::purge_previous_versions);
991 }
992 data->free_deallocate_list();
993 prev = data;
994 data = data->next();
995 continue;
996 }
997 seen_dead_loader = true;
998 ClassLoaderData* dead = data;
999 dead->unload();
1000 data = data->next();
1001 // Remove from loader list.
1002 // This class loader data will no longer be found
1003 // in the ClassLoaderDataGraph.
1004 if (prev != NULL) {
1005 prev->set_next(data);
1006 } else {
1007 assert(dead == _head, "sanity check");
1008 _head = data;
1009 }
1010 dead->set_next(_unloading);
1011 _unloading = dead;
1012 }
1013
1014 if (seen_dead_loader) {
1015 // Walk a ModuleEntry's reads and a PackageEntry's exports lists
1016 // to determine if there are modules on those lists that are now
1017 // dead and should be removed. A module's life cycle is equivalent
1018 // to its defining class loader's life cycle. Since a module is
1019 // considered dead if its class loader is dead, these walks must
1020 // occur after each class loader's aliveness is determined.
1021 data = _head;
1022 while (data != NULL) {
1023 if (data->packages_defined()) {
1024 data->packages()->purge_all_package_exports();
1025 }
1026 if (data->modules_defined()) {
1027 data->modules()->purge_all_module_reads();
1028 }
1029 data = data->next();
1030 }
1031
1032 post_class_unload_events();
1033 }
1034
1035 return seen_dead_loader;
1036 }
1037
1038 void ClassLoaderDataGraph::purge() {
1039 assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint!");
1040 ClassLoaderData* list = _unloading;
1041 _unloading = NULL;
1042 ClassLoaderData* next = list;
1043 bool classes_unloaded = false;
1044 while (next != NULL) {
1045 ClassLoaderData* purge_me = next;
1046 next = purge_me->next();
1047 delete purge_me;
1048 classes_unloaded = true;
1049 }
1050 if (classes_unloaded) {
1051 Metaspace::purge();
1052 set_metaspace_oom(false);
1053 }
1054 }
1055
1056 void ClassLoaderDataGraph::post_class_unload_events() {
1057 #if INCLUDE_TRACE
1058 assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint!");
1059 if (Tracing::enabled()) {
1060 if (Tracing::is_event_enabled(TraceClassUnloadEvent)) {
1061 assert(_unloading != NULL, "need class loader data unload list!");
1062 _class_unload_time = Ticks::now();
1063 classes_unloading_do(&class_unload_event);
1064 }
1065 Tracing::on_unloading_classes();
1066 }
1067 #endif
1068 }
1069
1070 // CDS support
1071
1072 // Global metaspaces for writing information to the shared archive. When
1073 // application CDS is supported, we may need one per metaspace, so this
1074 // sort of looks like it.
1075 Metaspace* ClassLoaderData::_ro_metaspace = NULL;
1076 Metaspace* ClassLoaderData::_rw_metaspace = NULL;
1077 static bool _shared_metaspaces_initialized = false;
1078
1079 // Initialize shared metaspaces (change to call from somewhere not lazily)
1080 void ClassLoaderData::initialize_shared_metaspaces() {
1081 assert(DumpSharedSpaces, "only use this for dumping shared spaces");
1082 assert(this == ClassLoaderData::the_null_class_loader_data(),
1083 "only supported for null loader data for now");
1084 assert (!_shared_metaspaces_initialized, "only initialize once");
1085 MutexLockerEx ml(metaspace_lock(), Mutex::_no_safepoint_check_flag);
1086 _ro_metaspace = new Metaspace(_metaspace_lock, Metaspace::ROMetaspaceType);
1087 _rw_metaspace = new Metaspace(_metaspace_lock, Metaspace::ReadWriteMetaspaceType);
1088 _shared_metaspaces_initialized = true;
1089 }
1090
1091 Metaspace* ClassLoaderData::ro_metaspace() {
1092 assert(_ro_metaspace != NULL, "should already be initialized");
1093 return _ro_metaspace;
1094 }
1095
1096 Metaspace* ClassLoaderData::rw_metaspace() {
1097 assert(_rw_metaspace != NULL, "should already be initialized");
1098 return _rw_metaspace;
1099 }
1100
1101 ClassLoaderDataGraphKlassIteratorAtomic::ClassLoaderDataGraphKlassIteratorAtomic()
1102 : _next_klass(NULL) {
1103 ClassLoaderData* cld = ClassLoaderDataGraph::_head;
1104 Klass* klass = NULL;
1105
1106 // Find the first klass in the CLDG.
1107 while (cld != NULL) {
1108 assert_locked_or_safepoint(cld->metaspace_lock());
1109 klass = cld->_klasses;
1110 if (klass != NULL) {
1111 _next_klass = klass;
1112 return;
1113 }
1114 cld = cld->next();
1115 }
1116 }
1117
1118 Klass* ClassLoaderDataGraphKlassIteratorAtomic::next_klass_in_cldg(Klass* klass) {
1119 Klass* next = klass->next_link();
1120 if (next != NULL) {
1121 return next;
1122 }
1123
1124 // No more klasses in the current CLD. Time to find a new CLD.
1125 ClassLoaderData* cld = klass->class_loader_data();
1126 assert_locked_or_safepoint(cld->metaspace_lock());
1127 while (next == NULL) {
1128 cld = cld->next();
1129 if (cld == NULL) {
1130 break;
1131 }
1132 next = cld->_klasses;
1133 }
1134
1135 return next;
1136 }
1137
1138 Klass* ClassLoaderDataGraphKlassIteratorAtomic::next_klass() {
1139 Klass* head = _next_klass;
1140
1141 while (head != NULL) {
1142 Klass* next = next_klass_in_cldg(head);
1143
1144 Klass* old_head = (Klass*)Atomic::cmpxchg_ptr(next, &_next_klass, head);
1145
1146 if (old_head == head) {
1147 return head; // Won the CAS.
1148 }
1149
1150 head = old_head;
1151 }
1152
1153 // Nothing more for the iterator to hand out.
1154 assert(head == NULL, "head is " PTR_FORMAT ", expected not null:", p2i(head));
1155 return NULL;
1156 }
1157
1158 ClassLoaderDataGraphMetaspaceIterator::ClassLoaderDataGraphMetaspaceIterator() {
1159 _data = ClassLoaderDataGraph::_head;
1160 }
1161
1162 ClassLoaderDataGraphMetaspaceIterator::~ClassLoaderDataGraphMetaspaceIterator() {}
1163
1164 #ifndef PRODUCT
1165 // callable from debugger
1166 extern "C" int print_loader_data_graph() {
1167 ClassLoaderDataGraph::dump_on(tty);
1168 return 0;
1169 }
1170
1171 void ClassLoaderDataGraph::verify() {
1172 for (ClassLoaderData* data = _head; data != NULL; data = data->next()) {
1173 data->verify();
1174 }
1175 }
1176
1177 void ClassLoaderDataGraph::dump_on(outputStream * const out) {
1178 for (ClassLoaderData* data = _head; data != NULL; data = data->next()) {
1179 data->dump(out);
1180 }
1181 MetaspaceAux::dump(out);
1182 }
1183 #endif // PRODUCT
1184
1185 void ClassLoaderData::print_value_on(outputStream* out) const {
1186 if (class_loader() == NULL) {
1187 out->print("NULL class_loader");
1188 } else {
1189 out->print("class loader " INTPTR_FORMAT " ", p2i(this));
1190 class_loader()->print_value_on(out);
1191 }
1192 }
1193
1194 #if INCLUDE_TRACE
1195
1196 Ticks ClassLoaderDataGraph::_class_unload_time;
1197
1198 void ClassLoaderDataGraph::class_unload_event(Klass* const k) {
1199 assert(k != NULL, "invariant");
1200
1201 // post class unload event
1202 EventClassUnload event(UNTIMED);
1203 event.set_endtime(_class_unload_time);
1204 event.set_unloadedClass(k);
1205 event.set_definingClassLoader(k->class_loader_data());
1206 event.commit();
1207 }
1208
1209 #endif // INCLUDE_TRACE
--- EOF ---