52 #include "jvmtifiles/jvmti.h"
53 #include "logging/log.hpp"
54 #include "klass.inline.hpp"
55 #include "logging/logMessage.hpp"
56 #include "logging/logStream.hpp"
57 #include "memory/allocation.inline.hpp"
58 #include "memory/iterator.inline.hpp"
59 #include "memory/metadataFactory.hpp"
60 #include "memory/metaspaceClosure.hpp"
61 #include "memory/oopFactory.hpp"
62 #include "memory/resourceArea.hpp"
63 #include "memory/universe.hpp"
64 #include "oops/fieldStreams.inline.hpp"
65 #include "oops/constantPool.hpp"
66 #include "oops/instanceClassLoaderKlass.hpp"
67 #include "oops/instanceKlass.inline.hpp"
68 #include "oops/instanceMirrorKlass.hpp"
69 #include "oops/instanceOop.hpp"
70 #include "oops/instanceStackChunkKlass.hpp"
71 #include "oops/klass.inline.hpp"
72 #include "oops/method.hpp"
73 #include "oops/oop.inline.hpp"
74 #include "oops/recordComponent.hpp"
75 #include "oops/symbol.hpp"
76 #include "prims/jvmtiExport.hpp"
77 #include "prims/jvmtiRedefineClasses.hpp"
78 #include "prims/jvmtiThreadState.hpp"
79 #include "prims/methodComparator.hpp"
80 #include "runtime/arguments.hpp"
81 #include "runtime/deoptimization.hpp"
82 #include "runtime/atomic.hpp"
83 #include "runtime/fieldDescriptor.inline.hpp"
84 #include "runtime/handles.inline.hpp"
85 #include "runtime/javaCalls.hpp"
86 #include "runtime/javaThread.inline.hpp"
87 #include "runtime/mutexLocker.hpp"
88 #include "runtime/orderAccess.hpp"
89 #include "runtime/os.inline.hpp"
90 #include "runtime/reflection.hpp"
91 #include "runtime/synchronizer.hpp"
92 #include "runtime/threads.hpp"
93 #include "services/classLoadingService.hpp"
94 #include "services/finalizerService.hpp"
95 #include "services/threadService.hpp"
132 #define DTRACE_CLASSINIT_PROBE_WAIT(type, thread_type, wait) \
133 { \
134 char* data = nullptr; \
135 int len = 0; \
136 Symbol* clss_name = name(); \
137 if (clss_name != nullptr) { \
138 data = (char*)clss_name->bytes(); \
139 len = clss_name->utf8_length(); \
140 } \
141 HOTSPOT_CLASS_INITIALIZATION_##type( \
142 data, len, (void*)class_loader(), thread_type, wait); \
143 }
144
145 #else // ndef DTRACE_ENABLED
146
147 #define DTRACE_CLASSINIT_PROBE(type, thread_type)
148 #define DTRACE_CLASSINIT_PROBE_WAIT(type, thread_type, wait)
149
150 #endif // ndef DTRACE_ENABLED
151
152 bool InstanceKlass::_finalization_enabled = true;
153
154 static inline bool is_class_loader(const Symbol* class_name,
155 const ClassFileParser& parser) {
156 assert(class_name != nullptr, "invariant");
157
158 if (class_name == vmSymbols::java_lang_ClassLoader()) {
159 return true;
160 }
161
162 if (vmClasses::ClassLoader_klass_loaded()) {
163 const Klass* const super_klass = parser.super_klass();
164 if (super_klass != nullptr) {
165 if (super_klass->is_subtype_of(vmClasses::ClassLoader_klass())) {
166 return true;
167 }
168 }
169 }
170 return false;
171 }
172
173 static inline bool is_stack_chunk_class(const Symbol* class_name,
174 const ClassLoaderData* loader_data) {
175 return (class_name == vmSymbols::jdk_internal_vm_StackChunk() &&
176 loader_data->is_the_null_class_loader_data());
177 }
178
179 // private: called to verify that k is a static member of this nest.
180 // We know that k is an instance class in the same package and hence the
181 // same classloader.
182 bool InstanceKlass::has_nest_member(JavaThread* current, InstanceKlass* k) const {
183 assert(!is_hidden(), "unexpected hidden class");
184 if (_nest_members == nullptr || _nest_members == Universe::the_empty_short_array()) {
185 if (log_is_enabled(Trace, class, nestmates)) {
186 ResourceMark rm(current);
187 log_trace(class, nestmates)("Checked nest membership of %s in non-nest-host class %s",
188 k->external_name(), this->external_name());
189 }
190 return false;
191 }
192
447 }
448
449 const char* InstanceKlass::nest_host_error() {
450 if (_nest_host_index == 0) {
451 return nullptr;
452 } else {
453 constantPoolHandle cph(Thread::current(), constants());
454 return SystemDictionary::find_nest_host_error(cph, (int)_nest_host_index);
455 }
456 }
457
458 void* InstanceKlass::operator new(size_t size, ClassLoaderData* loader_data, size_t word_size,
459 bool use_class_space, TRAPS) throw() {
460 return Metaspace::allocate(loader_data, word_size, ClassType, use_class_space, THREAD);
461 }
462
463 InstanceKlass* InstanceKlass::allocate_instance_klass(const ClassFileParser& parser, TRAPS) {
464 const int size = InstanceKlass::size(parser.vtable_size(),
465 parser.itable_size(),
466 nonstatic_oop_map_size(parser.total_oop_map_count()),
467 parser.is_interface());
468
469 const Symbol* const class_name = parser.class_name();
470 assert(class_name != nullptr, "invariant");
471 ClassLoaderData* loader_data = parser.loader_data();
472 assert(loader_data != nullptr, "invariant");
473
474 InstanceKlass* ik;
475 const bool use_class_space = parser.klass_needs_narrow_id();
476
477 // Allocation
478 if (parser.is_instance_ref_klass()) {
479 // java.lang.ref.Reference
480 ik = new (loader_data, size, use_class_space, THREAD) InstanceRefKlass(parser);
481 } else if (class_name == vmSymbols::java_lang_Class()) {
482 // mirror - java.lang.Class
483 ik = new (loader_data, size, use_class_space, THREAD) InstanceMirrorKlass(parser);
484 } else if (is_stack_chunk_class(class_name, loader_data)) {
485 // stack chunk
486 ik = new (loader_data, size, use_class_space, THREAD) InstanceStackChunkKlass(parser);
487 } else if (is_class_loader(class_name, parser)) {
488 // class loader - java.lang.ClassLoader
489 ik = new (loader_data, size, use_class_space, THREAD) InstanceClassLoaderKlass(parser);
490 } else {
491 // normal
492 ik = new (loader_data, size, use_class_space, THREAD) InstanceKlass(parser);
493 }
494
495 if (ik != nullptr && UseCompressedClassPointers && use_class_space) {
496 assert(CompressedKlassPointers::is_encodable(ik),
497 "Klass " PTR_FORMAT "needs a narrow Klass ID, but is not encodable", p2i(ik));
498 }
499
500 // Check for pending exception before adding to the loader data and incrementing
501 // class count. Can get OOM here.
502 if (HAS_PENDING_EXCEPTION) {
503 return nullptr;
504 }
505
506 return ik;
507 }
508
509
510 // copy method ordering from resource area to Metaspace
511 void InstanceKlass::copy_method_ordering(const intArray* m, TRAPS) {
512 if (m != nullptr) {
513 // allocate a new array and copy contents (memcpy?)
514 _method_ordering = MetadataFactory::new_array<int>(class_loader_data(), m->length(), CHECK);
515 for (int i = 0; i < m->length(); i++) {
516 _method_ordering->at_put(i, m->at(i));
517 }
518 } else {
519 _method_ordering = Universe::the_empty_int_array();
520 }
521 }
522
523 // create a new array of vtable_indices for default methods
524 Array<int>* InstanceKlass::create_new_default_vtable_indices(int len, TRAPS) {
525 Array<int>* vtable_indices = MetadataFactory::new_array<int>(class_loader_data(), len, CHECK_NULL);
526 assert(default_vtable_indices() == nullptr, "only create once");
527 set_default_vtable_indices(vtable_indices);
528 return vtable_indices;
529 }
530
531
532 InstanceKlass::InstanceKlass() {
533 assert(CDSConfig::is_dumping_static_archive() || CDSConfig::is_using_archive(), "only for CDS");
534 }
535
536 InstanceKlass::InstanceKlass(const ClassFileParser& parser, KlassKind kind, ReferenceType reference_type) :
537 Klass(kind),
538 _nest_members(nullptr),
539 _nest_host(nullptr),
540 _permitted_subclasses(nullptr),
541 _record_components(nullptr),
542 _static_field_size(parser.static_field_size()),
543 _nonstatic_oop_map_size(nonstatic_oop_map_size(parser.total_oop_map_count())),
544 _itable_len(parser.itable_size()),
545 _nest_host_index(0),
546 _init_state(allocated),
547 _reference_type(reference_type),
548 _init_thread(nullptr)
549 {
550 set_vtable_length(parser.vtable_size());
551 set_access_flags(parser.access_flags());
552 if (parser.is_hidden()) set_is_hidden();
553 set_layout_helper(Klass::instance_layout_helper(parser.layout_size(),
554 false));
555
556 assert(nullptr == _methods, "underlying memory not zeroed?");
557 assert(is_instance_klass(), "is layout incorrect?");
558 assert(size_helper() == parser.layout_size(), "incorrect size_helper?");
559 }
560
561 void InstanceKlass::deallocate_methods(ClassLoaderData* loader_data,
562 Array<Method*>* methods) {
563 if (methods != nullptr && methods != Universe::the_empty_method_array() &&
564 !methods->is_shared()) {
565 for (int i = 0; i < methods->length(); i++) {
566 Method* method = methods->at(i);
567 if (method == nullptr) continue; // maybe null if error processing
568 // Only want to delete methods that are not executing for RedefineClasses.
569 // The previous version will point to them so they're not totally dangling
570 assert (!method->on_stack(), "shouldn't be called with methods on stack");
571 MetadataFactory::free_metadata(loader_data, method);
572 }
573 MetadataFactory::free_array<Method*>(loader_data, methods);
574 }
674 (address)(secondary_supers()) != (address)(transitive_interfaces()) &&
675 !secondary_supers()->is_shared()) {
676 MetadataFactory::free_array<Klass*>(loader_data, secondary_supers());
677 }
678 set_secondary_supers(nullptr, SECONDARY_SUPERS_BITMAP_EMPTY);
679
680 deallocate_interfaces(loader_data, super(), local_interfaces(), transitive_interfaces());
681 set_transitive_interfaces(nullptr);
682 set_local_interfaces(nullptr);
683
684 if (fieldinfo_stream() != nullptr && !fieldinfo_stream()->is_shared()) {
685 MetadataFactory::free_array<u1>(loader_data, fieldinfo_stream());
686 }
687 set_fieldinfo_stream(nullptr);
688
689 if (fields_status() != nullptr && !fields_status()->is_shared()) {
690 MetadataFactory::free_array<FieldStatus>(loader_data, fields_status());
691 }
692 set_fields_status(nullptr);
693
694 // If a method from a redefined class is using this constant pool, don't
695 // delete it, yet. The new class's previous version will point to this.
696 if (constants() != nullptr) {
697 assert (!constants()->on_stack(), "shouldn't be called if anything is onstack");
698 if (!constants()->is_shared()) {
699 MetadataFactory::free_metadata(loader_data, constants());
700 }
701 // Delete any cached resolution errors for the constant pool
702 SystemDictionary::delete_resolution_error(constants());
703
704 set_constants(nullptr);
705 }
706
707 if (inner_classes() != nullptr &&
708 inner_classes() != Universe::the_empty_short_array() &&
709 !inner_classes()->is_shared()) {
710 MetadataFactory::free_array<jushort>(loader_data, inner_classes());
711 }
712 set_inner_classes(nullptr);
713
714 if (nest_members() != nullptr &&
715 nest_members() != Universe::the_empty_short_array() &&
716 !nest_members()->is_shared()) {
717 MetadataFactory::free_array<jushort>(loader_data, nest_members());
718 }
719 set_nest_members(nullptr);
720
721 if (permitted_subclasses() != nullptr &&
722 permitted_subclasses() != Universe::the_empty_short_array() &&
723 !permitted_subclasses()->is_shared()) {
724 MetadataFactory::free_array<jushort>(loader_data, permitted_subclasses());
725 }
726 set_permitted_subclasses(nullptr);
727
728 // We should deallocate the Annotations instance if it's not in shared spaces.
729 if (annotations() != nullptr && !annotations()->is_shared()) {
730 MetadataFactory::free_metadata(loader_data, annotations());
731 }
732 set_annotations(nullptr);
733
734 SystemDictionaryShared::handle_class_unloading(this);
735
736 #if INCLUDE_CDS_JAVA_HEAP
737 if (CDSConfig::is_dumping_heap()) {
738 HeapShared::remove_scratch_objects(this);
739 }
740 #endif
741 }
742
743 bool InstanceKlass::is_record() const {
744 return _record_components != nullptr &&
745 is_final() &&
746 java_super() == vmClasses::Record_klass();
747 }
942 vmSymbols::java_lang_IncompatibleClassChangeError(),
943 "class %s has interface %s as super class",
944 external_name(),
945 super_klass->external_name()
946 );
947 return false;
948 }
949
950 InstanceKlass* ik_super = InstanceKlass::cast(super_klass);
951 ik_super->link_class_impl(CHECK_false);
952 }
953
954 // link all interfaces implemented by this class before linking this class
955 Array<InstanceKlass*>* interfaces = local_interfaces();
956 int num_interfaces = interfaces->length();
957 for (int index = 0; index < num_interfaces; index++) {
958 InstanceKlass* interk = interfaces->at(index);
959 interk->link_class_impl(CHECK_false);
960 }
961
962 // in case the class is linked in the process of linking its superclasses
963 if (is_linked()) {
964 return true;
965 }
966
967 // trace only the link time for this klass that includes
968 // the verification time
969 PerfClassTraceTime vmtimer(ClassLoader::perf_class_link_time(),
970 ClassLoader::perf_class_link_selftime(),
971 ClassLoader::perf_classes_linked(),
972 jt->get_thread_stat()->perf_recursion_counts_addr(),
973 jt->get_thread_stat()->perf_timers_addr(),
974 PerfClassTraceTime::CLASS_LINK);
975
976 // verification & rewriting
977 {
978 HandleMark hm(THREAD);
979 Handle h_init_lock(THREAD, init_lock());
980 ObjectLocker ol(h_init_lock, jt);
981 // rewritten will have been set if loader constraint error found
1246 ss.print("Could not initialize class %s", external_name());
1247 if (cause.is_null()) {
1248 THROW_MSG(vmSymbols::java_lang_NoClassDefFoundError(), ss.as_string());
1249 } else {
1250 THROW_MSG_CAUSE(vmSymbols::java_lang_NoClassDefFoundError(),
1251 ss.as_string(), cause);
1252 }
1253 } else {
1254
1255 // Step 6
1256 set_init_state(being_initialized);
1257 set_init_thread(jt);
1258 if (debug_logging_enabled) {
1259 ResourceMark rm(jt);
1260 log_debug(class, init)("Thread \"%s\" is initializing %s",
1261 jt->name(), external_name());
1262 }
1263 }
1264 }
1265
1266 // Step 7
1267 // Next, if C is a class rather than an interface, initialize it's super class and super
1268 // interfaces.
1269 if (!is_interface()) {
1270 Klass* super_klass = super();
1271 if (super_klass != nullptr && super_klass->should_be_initialized()) {
1272 super_klass->initialize(THREAD);
1273 }
1274 // If C implements any interface that declares a non-static, concrete method,
1275 // the initialization of C triggers initialization of its super interfaces.
1276 // Only need to recurse if has_nonstatic_concrete_methods which includes declaring and
1277 // having a superinterface that declares, non-static, concrete methods
1278 if (!HAS_PENDING_EXCEPTION && has_nonstatic_concrete_methods()) {
1279 initialize_super_interfaces(THREAD);
1280 }
1281
1282 // If any exceptions, complete abruptly, throwing the same exception as above.
1283 if (HAS_PENDING_EXCEPTION) {
1284 Handle e(THREAD, PENDING_EXCEPTION);
1285 CLEAR_PENDING_EXCEPTION;
1286 {
1287 EXCEPTION_MARK;
1288 add_initialization_error(THREAD, e);
1289 // Locks object, set state, and notify all waiting threads
1290 set_initialization_state_and_notify(initialization_error, THREAD);
1291 CLEAR_PENDING_EXCEPTION;
1292 }
1293 DTRACE_CLASSINIT_PROBE_WAIT(super__failed, -1, wait);
1294 THROW_OOP(e());
1295 }
1296 }
1297
1298
1299 // Step 8
1300 {
1301 DTRACE_CLASSINIT_PROBE_WAIT(clinit, -1, wait);
1302 if (class_initializer() != nullptr) {
1303 // Timer includes any side effects of class initialization (resolution,
1304 // etc), but not recursive entry into call_class_initializer().
1305 PerfClassTraceTime timer(ClassLoader::perf_class_init_time(),
1306 ClassLoader::perf_class_init_selftime(),
1307 ClassLoader::perf_classes_inited(),
1308 jt->get_thread_stat()->perf_recursion_counts_addr(),
1309 jt->get_thread_stat()->perf_timers_addr(),
1310 PerfClassTraceTime::CLASS_CLINIT);
1311 call_class_initializer(THREAD);
1312 } else {
1313 // The elapsed time is so small it's not worth counting.
1314 if (UsePerfData) {
1315 ClassLoader::perf_classes_inited()->inc();
1316 }
1317 call_class_initializer(THREAD);
1318 }
1319 }
1320
1321 // Step 9
1322 if (!HAS_PENDING_EXCEPTION) {
1323 set_initialization_state_and_notify(fully_initialized, CHECK);
1324 debug_only(vtable().verify(tty, true);)
1325 }
1326 else {
1327 // Step 10 and 11
1328 Handle e(THREAD, PENDING_EXCEPTION);
1329 CLEAR_PENDING_EXCEPTION;
1330 // JVMTI has already reported the pending exception
1331 // JVMTI internal flag reset is needed in order to report ExceptionInInitializerError
1332 JvmtiExport::clear_detected_exception(jt);
1333 {
1334 EXCEPTION_MARK;
1335 add_initialization_error(THREAD, e);
1336 set_initialization_state_and_notify(initialization_error, THREAD);
1337 CLEAR_PENDING_EXCEPTION; // ignore any exception thrown, class initialization error is thrown below
1338 // JVMTI has already reported the pending exception
1351 }
1352 DTRACE_CLASSINIT_PROBE_WAIT(end, -1, wait);
1353 }
1354
1355
1356 void InstanceKlass::set_initialization_state_and_notify(ClassState state, TRAPS) {
1357 Handle h_init_lock(THREAD, init_lock());
1358 if (h_init_lock() != nullptr) {
1359 ObjectLocker ol(h_init_lock, THREAD);
1360 set_init_thread(nullptr); // reset _init_thread before changing _init_state
1361 set_init_state(state);
1362 fence_and_clear_init_lock();
1363 ol.notify_all(CHECK);
1364 } else {
1365 assert(h_init_lock() != nullptr, "The initialization state should never be set twice");
1366 set_init_thread(nullptr); // reset _init_thread before changing _init_state
1367 set_init_state(state);
1368 }
1369 }
1370
1371 // Update hierarchy. This is done before the new klass has been added to the SystemDictionary. The Compile_lock
1372 // is grabbed, to ensure that the compiler is not using the class hierarchy.
1373 void InstanceKlass::add_to_hierarchy(JavaThread* current) {
1374 assert(!SafepointSynchronize::is_at_safepoint(), "must NOT be at safepoint");
1375
1376 DeoptimizationScope deopt_scope;
1377 {
1378 MutexLocker ml(current, Compile_lock);
1379
1380 set_init_state(InstanceKlass::loaded);
1381 // make sure init_state store is already done.
1382 // The compiler reads the hierarchy outside of the Compile_lock.
1383 // Access ordering is used to add to hierarchy.
1384
1385 // Link into hierarchy.
1386 append_to_sibling_list(); // add to superklass/sibling list
1387 process_interfaces(); // handle all "implements" declarations
1388
1389 // Now mark all code that depended on old class hierarchy.
1390 // Note: must be done *after* linking k into the hierarchy (was bug 12/9/97)
1603 ResourceMark rm(THREAD);
1604 THROW_MSG(throwError ? vmSymbols::java_lang_InstantiationError()
1605 : vmSymbols::java_lang_InstantiationException(), external_name());
1606 }
1607 if (this == vmClasses::Class_klass()) {
1608 ResourceMark rm(THREAD);
1609 THROW_MSG(throwError ? vmSymbols::java_lang_IllegalAccessError()
1610 : vmSymbols::java_lang_IllegalAccessException(), external_name());
1611 }
1612 }
1613
1614 ArrayKlass* InstanceKlass::array_klass(int n, TRAPS) {
1615 // Need load-acquire for lock-free read
1616 if (array_klasses_acquire() == nullptr) {
1617
1618 // Recursively lock array allocation
1619 RecursiveLocker rl(MultiArray_lock, THREAD);
1620
1621 // Check if another thread created the array klass while we were waiting for the lock.
1622 if (array_klasses() == nullptr) {
1623 ObjArrayKlass* k = ObjArrayKlass::allocate_objArray_klass(class_loader_data(), 1, this, CHECK_NULL);
1624 // use 'release' to pair with lock-free load
1625 release_set_array_klasses(k);
1626 }
1627 }
1628
1629 // array_klasses() will always be set at this point
1630 ObjArrayKlass* ak = array_klasses();
1631 assert(ak != nullptr, "should be set");
1632 return ak->array_klass(n, THREAD);
1633 }
1634
1635 ArrayKlass* InstanceKlass::array_klass_or_null(int n) {
1636 // Need load-acquire for lock-free read
1637 ObjArrayKlass* oak = array_klasses_acquire();
1638 if (oak == nullptr) {
1639 return nullptr;
1640 } else {
1641 return oak->array_klass_or_null(n);
1642 }
1643 }
1644
1645 ArrayKlass* InstanceKlass::array_klass(TRAPS) {
1646 return array_klass(1, THREAD);
1647 }
1648
1649 ArrayKlass* InstanceKlass::array_klass_or_null() {
1650 return array_klass_or_null(1);
1651 }
1652
1653 static int call_class_initializer_counter = 0; // for debugging
1654
1655 Method* InstanceKlass::class_initializer() const {
1656 Method* clinit = find_method(
1657 vmSymbols::class_initializer_name(), vmSymbols::void_method_signature());
1658 if (clinit != nullptr && clinit->has_valid_initializer_flags()) {
1659 return clinit;
1660 }
1661 return nullptr;
1662 }
1663
1664 void InstanceKlass::call_class_initializer(TRAPS) {
1665 if (ReplayCompiles &&
1666 (ReplaySuppressInitializers == 1 ||
1667 (ReplaySuppressInitializers >= 2 && class_loader() != nullptr))) {
1668 // Hide the existence of the initializer for the purpose of replaying the compile
1669 return;
1670 }
1671
1672 #if INCLUDE_CDS
1673 // This is needed to ensure the consistency of the archived heap objects.
1674 if (has_aot_initialized_mirror() && CDSConfig::is_loading_heap()) {
1675 AOTClassInitializer::call_runtime_setup(THREAD, this);
1676 return;
1677 } else if (has_archived_enum_objs()) {
1678 assert(is_shared(), "must be");
1747
1748 void InstanceKlass::mask_for(const methodHandle& method, int bci,
1749 InterpreterOopMap* entry_for) {
1750 // Lazily create the _oop_map_cache at first request.
1751 // Load_acquire is needed to safely get instance published with CAS by another thread.
1752 OopMapCache* oop_map_cache = Atomic::load_acquire(&_oop_map_cache);
1753 if (oop_map_cache == nullptr) {
1754 // Try to install new instance atomically.
1755 oop_map_cache = new OopMapCache();
1756 OopMapCache* other = Atomic::cmpxchg(&_oop_map_cache, (OopMapCache*)nullptr, oop_map_cache);
1757 if (other != nullptr) {
1758 // Someone else managed to install before us, ditch local copy and use the existing one.
1759 delete oop_map_cache;
1760 oop_map_cache = other;
1761 }
1762 }
1763 // _oop_map_cache is constant after init; lookup below does its own locking.
1764 oop_map_cache->lookup(method, bci, entry_for);
1765 }
1766
1767 bool InstanceKlass::contains_field_offset(int offset) {
1768 fieldDescriptor fd;
1769 return find_field_from_offset(offset, false, &fd);
1770 }
1771
1772 FieldInfo InstanceKlass::field(int index) const {
1773 for (AllFieldStream fs(this); !fs.done(); fs.next()) {
1774 if (fs.index() == index) {
1775 return fs.to_FieldInfo();
1776 }
1777 }
1778 fatal("Field not found");
1779 return FieldInfo();
1780 }
1781
1782 bool InstanceKlass::find_local_field(Symbol* name, Symbol* sig, fieldDescriptor* fd) const {
1783 for (JavaFieldStream fs(this); !fs.done(); fs.next()) {
1784 Symbol* f_name = fs.name();
1785 Symbol* f_sig = fs.signature();
1786 if (f_name == name && f_sig == sig) {
1787 fd->reinitialize(const_cast<InstanceKlass*>(this), fs.to_FieldInfo());
1788 return true;
1789 }
1790 }
1832
1833 Klass* InstanceKlass::find_field(Symbol* name, Symbol* sig, bool is_static, fieldDescriptor* fd) const {
1834 // search order according to newest JVM spec (5.4.3.2, p.167).
1835 // 1) search for field in current klass
1836 if (find_local_field(name, sig, fd)) {
1837 if (fd->is_static() == is_static) return const_cast<InstanceKlass*>(this);
1838 }
1839 // 2) search for field recursively in direct superinterfaces
1840 if (is_static) {
1841 Klass* intf = find_interface_field(name, sig, fd);
1842 if (intf != nullptr) return intf;
1843 }
1844 // 3) apply field lookup recursively if superclass exists
1845 { Klass* supr = super();
1846 if (supr != nullptr) return InstanceKlass::cast(supr)->find_field(name, sig, is_static, fd);
1847 }
1848 // 4) otherwise field lookup fails
1849 return nullptr;
1850 }
1851
1852
1853 bool InstanceKlass::find_local_field_from_offset(int offset, bool is_static, fieldDescriptor* fd) const {
1854 for (JavaFieldStream fs(this); !fs.done(); fs.next()) {
1855 if (fs.offset() == offset) {
1856 fd->reinitialize(const_cast<InstanceKlass*>(this), fs.to_FieldInfo());
1857 if (fd->is_static() == is_static) return true;
1858 }
1859 }
1860 return false;
1861 }
1862
1863
1864 bool InstanceKlass::find_field_from_offset(int offset, bool is_static, fieldDescriptor* fd) const {
1865 Klass* klass = const_cast<InstanceKlass*>(this);
1866 while (klass != nullptr) {
1867 if (InstanceKlass::cast(klass)->find_local_field_from_offset(offset, is_static, fd)) {
1868 return true;
1869 }
1870 klass = klass->super();
1871 }
2215 }
2216
2217 // uncached_lookup_method searches both the local class methods array and all
2218 // superclasses methods arrays, skipping any overpass methods in superclasses,
2219 // and possibly skipping private methods.
2220 Method* InstanceKlass::uncached_lookup_method(const Symbol* name,
2221 const Symbol* signature,
2222 OverpassLookupMode overpass_mode,
2223 PrivateLookupMode private_mode) const {
2224 OverpassLookupMode overpass_local_mode = overpass_mode;
2225 const Klass* klass = this;
2226 while (klass != nullptr) {
2227 Method* const method = InstanceKlass::cast(klass)->find_method_impl(name,
2228 signature,
2229 overpass_local_mode,
2230 StaticLookupMode::find,
2231 private_mode);
2232 if (method != nullptr) {
2233 return method;
2234 }
2235 klass = klass->super();
2236 overpass_local_mode = OverpassLookupMode::skip; // Always ignore overpass methods in superclasses
2237 }
2238 return nullptr;
2239 }
2240
2241 #ifdef ASSERT
2242 // search through class hierarchy and return true if this class or
2243 // one of the superclasses was redefined
2244 bool InstanceKlass::has_redefined_this_or_super() const {
2245 const Klass* klass = this;
2246 while (klass != nullptr) {
2247 if (InstanceKlass::cast(klass)->has_been_redefined()) {
2248 return true;
2249 }
2250 klass = klass->super();
2251 }
2252 return false;
2253 }
2254 #endif
2612 int itable_offset_in_words = (int)(start_of_itable() - (intptr_t*)this);
2613
2614 int nof_interfaces = (method_table_offset_in_words - itable_offset_in_words)
2615 / itableOffsetEntry::size();
2616
2617 for (int i = 0; i < nof_interfaces; i ++, ioe ++) {
2618 if (ioe->interface_klass() != nullptr) {
2619 it->push(ioe->interface_klass_addr());
2620 itableMethodEntry* ime = ioe->first_method_entry(this);
2621 int n = klassItable::method_count_for_interface(ioe->interface_klass());
2622 for (int index = 0; index < n; index ++) {
2623 it->push(ime[index].method_addr());
2624 }
2625 }
2626 }
2627 }
2628
2629 it->push(&_nest_host);
2630 it->push(&_nest_members);
2631 it->push(&_permitted_subclasses);
2632 it->push(&_record_components);
2633 }
2634
2635 #if INCLUDE_CDS
2636 void InstanceKlass::remove_unshareable_info() {
2637
2638 if (is_linked()) {
2639 assert(can_be_verified_at_dumptime(), "must be");
2640 // Remember this so we can avoid walking the hierarchy at runtime.
2641 set_verified_at_dump_time();
2642 }
2643
2644 Klass::remove_unshareable_info();
2645
2646 if (SystemDictionaryShared::has_class_failed_verification(this)) {
2647 // Classes are attempted to link during dumping and may fail,
2648 // but these classes are still in the dictionary and class list in CLD.
2649 // If the class has failed verification, there is nothing else to remove.
2650 return;
2651 }
2652
2658
2659 { // Otherwise this needs to take out the Compile_lock.
2660 assert(SafepointSynchronize::is_at_safepoint(), "only called at safepoint");
2661 init_implementor();
2662 }
2663
2664 // Call remove_unshareable_info() on other objects that belong to this class, except
2665 // for constants()->remove_unshareable_info(), which is called in a separate pass in
2666 // ArchiveBuilder::make_klasses_shareable(),
2667
2668 for (int i = 0; i < methods()->length(); i++) {
2669 Method* m = methods()->at(i);
2670 m->remove_unshareable_info();
2671 }
2672
2673 // do array classes also.
2674 if (array_klasses() != nullptr) {
2675 array_klasses()->remove_unshareable_info();
2676 }
2677
2678 // These are not allocated from metaspace. They are safe to set to null.
2679 _source_debug_extension = nullptr;
2680 _dep_context = nullptr;
2681 _osr_nmethods_head = nullptr;
2682 #if INCLUDE_JVMTI
2683 _breakpoints = nullptr;
2684 _previous_versions = nullptr;
2685 _cached_class_file = nullptr;
2686 _jvmti_cached_class_field_map = nullptr;
2687 #endif
2688
2689 _init_thread = nullptr;
2690 _methods_jmethod_ids = nullptr;
2691 _jni_ids = nullptr;
2692 _oop_map_cache = nullptr;
2693 if (CDSConfig::is_dumping_method_handles() && HeapShared::is_lambda_proxy_klass(this)) {
2694 // keep _nest_host
2695 } else {
2696 // clear _nest_host to ensure re-load at runtime
2697 _nest_host = nullptr;
2698 }
2747 void InstanceKlass::compute_has_loops_flag_for_methods() {
2748 Array<Method*>* methods = this->methods();
2749 for (int index = 0; index < methods->length(); ++index) {
2750 Method* m = methods->at(index);
2751 if (!m->is_overpass()) { // work around JDK-8305771
2752 m->compute_has_loops_flag();
2753 }
2754 }
2755 }
2756
2757 void InstanceKlass::restore_unshareable_info(ClassLoaderData* loader_data, Handle protection_domain,
2758 PackageEntry* pkg_entry, TRAPS) {
2759 // InstanceKlass::add_to_hierarchy() sets the init_state to loaded
2760 // before the InstanceKlass is added to the SystemDictionary. Make
2761 // sure the current state is <loaded.
2762 assert(!is_loaded(), "invalid init state");
2763 assert(!shared_loading_failed(), "Must not try to load failed class again");
2764 set_package(loader_data, pkg_entry, CHECK);
2765 Klass::restore_unshareable_info(loader_data, protection_domain, CHECK);
2766
2767 Array<Method*>* methods = this->methods();
2768 int num_methods = methods->length();
2769 for (int index = 0; index < num_methods; ++index) {
2770 methods->at(index)->restore_unshareable_info(CHECK);
2771 }
2772 #if INCLUDE_JVMTI
2773 if (JvmtiExport::has_redefined_a_class()) {
2774 // Reinitialize vtable because RedefineClasses may have changed some
2775 // entries in this vtable for super classes so the CDS vtable might
2776 // point to old or obsolete entries. RedefineClasses doesn't fix up
2777 // vtables in the shared system dictionary, only the main one.
2778 // It also redefines the itable too so fix that too.
2779 // First fix any default methods that point to a super class that may
2780 // have been redefined.
2781 bool trace_name_printed = false;
2782 adjust_default_methods(&trace_name_printed);
2783 if (verified_at_dump_time()) {
2784 // Initialize vtable and itable for classes which can be verified at dump time.
2785 // Unlinked classes such as old classes with major version < 50 cannot be verified
2786 // at dump time.
2787 vtable().initialize_vtable();
2788 itable().initialize_itable();
2789 }
2790 }
2791 #endif // INCLUDE_JVMTI
2792
2793 // restore constant pool resolved references
2794 constants()->restore_unshareable_info(CHECK);
2795
2796 if (array_klasses() != nullptr) {
2797 // To get a consistent list of classes we need MultiArray_lock to ensure
2798 // array classes aren't observed while they are being restored.
2799 RecursiveLocker rl(MultiArray_lock, THREAD);
2800 assert(this == array_klasses()->bottom_klass(), "sanity");
2801 // Array classes have null protection domain.
2802 // --> see ArrayKlass::complete_create_array_klass()
2803 array_klasses()->restore_unshareable_info(class_loader_data(), Handle(), CHECK);
2804 }
2805
2806 // Initialize @ValueBased class annotation if not already set in the archived klass.
2807 if (DiagnoseSyncOnValueBasedClasses && has_value_based_class_annotation() && !is_value_based()) {
2808 set_is_value_based();
2809 }
2810 }
2811
2812 // Check if a class or any of its supertypes has a version older than 50.
2813 // CDS will not perform verification of old classes during dump time because
2814 // without changing the old verifier, the verification constraint cannot be
2815 // retrieved during dump time.
2816 // Verification of archived old classes will be performed during run time.
2817 bool InstanceKlass::can_be_verified_at_dumptime() const {
2818 if (MetaspaceShared::is_in_shared_metaspace(this)) {
2819 // This is a class that was dumped into the base archive, so we know
2820 // it was verified at dump time.
2977 } else {
2978 // Adding one to the attribute length in order to store a null terminator
2979 // character could cause an overflow because the attribute length is
2980 // already coded with an u4 in the classfile, but in practice, it's
2981 // unlikely to happen.
2982 assert((length+1) > length, "Overflow checking");
2983 char* sde = NEW_C_HEAP_ARRAY(char, (length + 1), mtClass);
2984 for (int i = 0; i < length; i++) {
2985 sde[i] = array[i];
2986 }
2987 sde[length] = '\0';
2988 _source_debug_extension = sde;
2989 }
2990 }
2991
2992 Symbol* InstanceKlass::generic_signature() const { return _constants->generic_signature(); }
2993 u2 InstanceKlass::generic_signature_index() const { return _constants->generic_signature_index(); }
2994 void InstanceKlass::set_generic_signature_index(u2 sig_index) { _constants->set_generic_signature_index(sig_index); }
2995
2996 const char* InstanceKlass::signature_name() const {
2997
2998 // Get the internal name as a c string
2999 const char* src = (const char*) (name()->as_C_string());
3000 const int src_length = (int)strlen(src);
3001
3002 char* dest = NEW_RESOURCE_ARRAY(char, src_length + 3);
3003
3004 // Add L as type indicator
3005 int dest_index = 0;
3006 dest[dest_index++] = JVM_SIGNATURE_CLASS;
3007
3008 // Add the actual class name
3009 for (int src_index = 0; src_index < src_length; ) {
3010 dest[dest_index++] = src[src_index++];
3011 }
3012
3013 if (is_hidden()) { // Replace the last '+' with a '.'.
3014 for (int index = (int)src_length; index > 0; index--) {
3015 if (dest[index] == '+') {
3016 dest[index] = JVM_SIGNATURE_DOT;
3017 break;
3018 }
3019 }
3020 }
3021
3022 // Add the semicolon and the null
3023 dest[dest_index++] = JVM_SIGNATURE_ENDCLASS;
3024 dest[dest_index] = '\0';
3025 return dest;
3026 }
3333 u2 InstanceKlass::compute_modifier_flags() const {
3334 u2 access = access_flags().as_unsigned_short();
3335
3336 // But check if it happens to be member class.
3337 InnerClassesIterator iter(this);
3338 for (; !iter.done(); iter.next()) {
3339 int ioff = iter.inner_class_info_index();
3340 // Inner class attribute can be zero, skip it.
3341 // Strange but true: JVM spec. allows null inner class refs.
3342 if (ioff == 0) continue;
3343
3344 // only look at classes that are already loaded
3345 // since we are looking for the flags for our self.
3346 Symbol* inner_name = constants()->klass_name_at(ioff);
3347 if (name() == inner_name) {
3348 // This is really a member class.
3349 access = iter.inner_access_flags();
3350 break;
3351 }
3352 }
3353 // Remember to strip ACC_SUPER bit
3354 return (access & (~JVM_ACC_SUPER));
3355 }
3356
3357 jint InstanceKlass::jvmti_class_status() const {
3358 jint result = 0;
3359
3360 if (is_linked()) {
3361 result |= JVMTI_CLASS_STATUS_VERIFIED | JVMTI_CLASS_STATUS_PREPARED;
3362 }
3363
3364 if (is_initialized()) {
3365 assert(is_linked(), "Class status is not consistent");
3366 result |= JVMTI_CLASS_STATUS_INITIALIZED;
3367 }
3368 if (is_in_error_state()) {
3369 result |= JVMTI_CLASS_STATUS_ERROR;
3370 }
3371 return result;
3372 }
3373
3374 Method* InstanceKlass::method_at_itable(InstanceKlass* holder, int index, TRAPS) {
3588 }
3589 osr = osr->osr_link();
3590 }
3591
3592 assert(match_level == false || best == nullptr, "shouldn't pick up anything if match_level is set");
3593 if (best != nullptr && best->comp_level() >= comp_level) {
3594 return best;
3595 }
3596 return nullptr;
3597 }
3598
3599 // -----------------------------------------------------------------------------------------------------
3600 // Printing
3601
3602 #define BULLET " - "
3603
3604 static const char* state_names[] = {
3605 "allocated", "loaded", "linked", "being_initialized", "fully_initialized", "initialization_error"
3606 };
3607
3608 static void print_vtable(intptr_t* start, int len, outputStream* st) {
3609 for (int i = 0; i < len; i++) {
3610 intptr_t e = start[i];
3611 st->print("%d : " INTPTR_FORMAT, i, e);
3612 if (MetaspaceObj::is_valid((Metadata*)e)) {
3613 st->print(" ");
3614 ((Metadata*)e)->print_value_on(st);
3615 }
3616 st->cr();
3617 }
3618 }
3619
3620 static void print_vtable(vtableEntry* start, int len, outputStream* st) {
3621 return print_vtable(reinterpret_cast<intptr_t*>(start), len, st);
3622 }
3623
3624 const char* InstanceKlass::init_state_name() const {
3625 return state_names[init_state()];
3626 }
3627
3628 void InstanceKlass::print_on(outputStream* st) const {
3629 assert(is_klass(), "must be klass");
3630 Klass::print_on(st);
3631
3632 st->print(BULLET"instance size: %d", size_helper()); st->cr();
3633 st->print(BULLET"klass size: %d", size()); st->cr();
3634 st->print(BULLET"access: "); access_flags().print_on(st); st->cr();
3635 st->print(BULLET"flags: "); _misc_flags.print_on(st); st->cr();
3636 st->print(BULLET"state: "); st->print_cr("%s", init_state_name());
3637 st->print(BULLET"name: "); name()->print_value_on(st); st->cr();
3638 st->print(BULLET"super: "); Metadata::print_value_on_maybe_null(st, super()); st->cr();
3639 st->print(BULLET"sub: ");
3640 Klass* sub = subklass();
3641 int n;
3642 for (n = 0; sub != nullptr; n++, sub = sub->next_sibling()) {
3643 if (n < MaxSubklassPrintSize) {
3644 sub->print_value_on(st);
3645 st->print(" ");
3646 }
3647 }
3648 if (n >= MaxSubklassPrintSize) st->print("(%zd more klasses...)", n - MaxSubklassPrintSize);
3649 st->cr();
3650
3651 if (is_interface()) {
3652 st->print_cr(BULLET"nof implementors: %d", nof_implementors());
3653 if (nof_implementors() == 1) {
3654 st->print_cr(BULLET"implementor: ");
3655 st->print(" ");
3656 implementor()->print_value_on(st);
3657 st->cr();
3658 }
3659 }
3660
3661 st->print(BULLET"arrays: "); Metadata::print_value_on_maybe_null(st, array_klasses()); st->cr();
3662 st->print(BULLET"methods: "); methods()->print_value_on(st); st->cr();
3663 if (Verbose || WizardMode) {
3664 Array<Method*>* method_array = methods();
3665 for (int i = 0; i < method_array->length(); i++) {
3666 st->print("%d : ", i); method_array->at(i)->print_value(); st->cr();
3667 }
3668 }
3669 st->print(BULLET"method ordering: "); method_ordering()->print_value_on(st); st->cr();
3670 if (default_methods() != nullptr) {
3671 st->print(BULLET"default_methods: "); default_methods()->print_value_on(st); st->cr();
3672 if (Verbose) {
3673 Array<Method*>* method_array = default_methods();
3674 for (int i = 0; i < method_array->length(); i++) {
3675 st->print("%d : ", i); method_array->at(i)->print_value(); st->cr();
3676 }
3677 }
3678 }
3679 print_on_maybe_null(st, BULLET"default vtable indices: ", default_vtable_indices());
3680 st->print(BULLET"local interfaces: "); local_interfaces()->print_value_on(st); st->cr();
3681 st->print(BULLET"trans. interfaces: "); transitive_interfaces()->print_value_on(st); st->cr();
3682
3683 st->print(BULLET"secondary supers: "); secondary_supers()->print_value_on(st); st->cr();
3684
3685 st->print(BULLET"hash_slot: %d", hash_slot()); st->cr();
3686 st->print(BULLET"secondary bitmap: " UINTX_FORMAT_X_0, _secondary_supers_bitmap); st->cr();
3687
3688 if (secondary_supers() != nullptr) {
3689 if (Verbose) {
3690 bool is_hashed = (_secondary_supers_bitmap != SECONDARY_SUPERS_BITMAP_FULL);
3691 st->print_cr(BULLET"---- secondary supers (%d words):", _secondary_supers->length());
3692 for (int i = 0; i < _secondary_supers->length(); i++) {
3693 ResourceMark rm; // for external_name()
3694 Klass* secondary_super = _secondary_supers->at(i);
3695 st->print(BULLET"%2d:", i);
3696 if (is_hashed) {
3697 int home_slot = compute_home_slot(secondary_super, _secondary_supers_bitmap);
3717 print_on_maybe_null(st, BULLET"field type annotations: ", fields_type_annotations());
3718 {
3719 bool have_pv = false;
3720 // previous versions are linked together through the InstanceKlass
3721 for (InstanceKlass* pv_node = previous_versions();
3722 pv_node != nullptr;
3723 pv_node = pv_node->previous_versions()) {
3724 if (!have_pv)
3725 st->print(BULLET"previous version: ");
3726 have_pv = true;
3727 pv_node->constants()->print_value_on(st);
3728 }
3729 if (have_pv) st->cr();
3730 }
3731
3732 print_on_maybe_null(st, BULLET"generic signature: ", generic_signature());
3733 st->print(BULLET"inner classes: "); inner_classes()->print_value_on(st); st->cr();
3734 st->print(BULLET"nest members: "); nest_members()->print_value_on(st); st->cr();
3735 print_on_maybe_null(st, BULLET"record components: ", record_components());
3736 st->print(BULLET"permitted subclasses: "); permitted_subclasses()->print_value_on(st); st->cr();
3737 if (java_mirror() != nullptr) {
3738 st->print(BULLET"java mirror: ");
3739 java_mirror()->print_value_on(st);
3740 st->cr();
3741 } else {
3742 st->print_cr(BULLET"java mirror: null");
3743 }
3744 st->print(BULLET"vtable length %d (start addr: " PTR_FORMAT ")", vtable_length(), p2i(start_of_vtable())); st->cr();
3745 if (vtable_length() > 0 && (Verbose || WizardMode)) print_vtable(start_of_vtable(), vtable_length(), st);
3746 st->print(BULLET"itable length %d (start addr: " PTR_FORMAT ")", itable_length(), p2i(start_of_itable())); st->cr();
3747 if (itable_length() > 0 && (Verbose || WizardMode)) print_vtable(start_of_itable(), itable_length(), st);
3748 st->print_cr(BULLET"---- static fields (%d words):", static_field_size());
3749
3750 FieldPrinter print_static_field(st);
3751 ((InstanceKlass*)this)->do_local_static_fields(&print_static_field);
3752 st->print_cr(BULLET"---- non-static fields (%d words):", nonstatic_field_size());
3753 FieldPrinter print_nonstatic_field(st);
3754 InstanceKlass* ik = const_cast<InstanceKlass*>(this);
3755 ik->print_nonstatic_fields(&print_nonstatic_field);
3756
3757 st->print(BULLET"non-static oop maps (%d entries): ", nonstatic_oop_map_count());
3758 OopMapBlock* map = start_of_nonstatic_oop_maps();
3759 OopMapBlock* end_map = map + nonstatic_oop_map_count();
3760 while (map < end_map) {
3761 st->print("%d-%d ", map->offset(), map->offset() + heapOopSize*(map->count() - 1));
3762 map++;
3763 }
3764 st->cr();
3765 }
3766
3767 void InstanceKlass::print_value_on(outputStream* st) const {
3768 assert(is_klass(), "must be klass");
3769 if (Verbose || WizardMode) access_flags().print_on(st);
3770 name()->print_value_on(st);
3771 }
3772
3773 void FieldPrinter::do_field(fieldDescriptor* fd) {
3774 _st->print(BULLET);
3775 if (_obj == nullptr) {
3776 fd->print_on(_st);
3777 _st->cr();
3778 } else {
3779 fd->print_on_for(_st, _obj);
3780 _st->cr();
3781 }
3782 }
3783
3784
3785 void InstanceKlass::oop_print_on(oop obj, outputStream* st) {
3786 Klass::oop_print_on(obj, st);
3787
3788 if (this == vmClasses::String_klass()) {
3789 typeArrayOop value = java_lang_String::value(obj);
3790 juint length = java_lang_String::length(obj);
3791 if (value != nullptr &&
3792 value->is_typeArray() &&
3793 length <= (juint) value->length()) {
3794 st->print(BULLET"string: ");
3795 java_lang_String::print(obj, st);
3796 st->cr();
3797 }
3798 }
3799
3800 st->print_cr(BULLET"---- fields (total size %zu words):", oop_size(obj));
3801 FieldPrinter print_field(st, obj);
3802 print_nonstatic_fields(&print_field);
3803
3804 if (this == vmClasses::Class_klass()) {
3805 st->print(BULLET"signature: ");
3806 java_lang_Class::print_signature(obj, st);
3807 st->cr();
3808 Klass* real_klass = java_lang_Class::as_Klass(obj);
3809 if (real_klass != nullptr && real_klass->is_instance_klass()) {
3810 st->print_cr(BULLET"---- static fields (%d):", java_lang_Class::static_oop_field_count(obj));
3811 InstanceKlass::cast(real_klass)->do_local_static_fields(&print_field);
3812 }
3813 } else if (this == vmClasses::MethodType_klass()) {
3814 st->print(BULLET"signature: ");
3815 java_lang_invoke_MethodType::print_signature(obj, st);
3816 st->cr();
3817 }
3818 }
3819
3820 #ifndef PRODUCT
3821
|
52 #include "jvmtifiles/jvmti.h"
53 #include "logging/log.hpp"
54 #include "klass.inline.hpp"
55 #include "logging/logMessage.hpp"
56 #include "logging/logStream.hpp"
57 #include "memory/allocation.inline.hpp"
58 #include "memory/iterator.inline.hpp"
59 #include "memory/metadataFactory.hpp"
60 #include "memory/metaspaceClosure.hpp"
61 #include "memory/oopFactory.hpp"
62 #include "memory/resourceArea.hpp"
63 #include "memory/universe.hpp"
64 #include "oops/fieldStreams.inline.hpp"
65 #include "oops/constantPool.hpp"
66 #include "oops/instanceClassLoaderKlass.hpp"
67 #include "oops/instanceKlass.inline.hpp"
68 #include "oops/instanceMirrorKlass.hpp"
69 #include "oops/instanceOop.hpp"
70 #include "oops/instanceStackChunkKlass.hpp"
71 #include "oops/klass.inline.hpp"
72 #include "oops/markWord.hpp"
73 #include "oops/method.hpp"
74 #include "oops/oop.inline.hpp"
75 #include "oops/recordComponent.hpp"
76 #include "oops/symbol.hpp"
77 #include "oops/inlineKlass.hpp"
78 #include "prims/jvmtiExport.hpp"
79 #include "prims/jvmtiRedefineClasses.hpp"
80 #include "prims/jvmtiThreadState.hpp"
81 #include "prims/methodComparator.hpp"
82 #include "runtime/arguments.hpp"
83 #include "runtime/deoptimization.hpp"
84 #include "runtime/atomic.hpp"
85 #include "runtime/fieldDescriptor.inline.hpp"
86 #include "runtime/handles.inline.hpp"
87 #include "runtime/javaCalls.hpp"
88 #include "runtime/javaThread.inline.hpp"
89 #include "runtime/mutexLocker.hpp"
90 #include "runtime/orderAccess.hpp"
91 #include "runtime/os.inline.hpp"
92 #include "runtime/reflection.hpp"
93 #include "runtime/synchronizer.hpp"
94 #include "runtime/threads.hpp"
95 #include "services/classLoadingService.hpp"
96 #include "services/finalizerService.hpp"
97 #include "services/threadService.hpp"
134 #define DTRACE_CLASSINIT_PROBE_WAIT(type, thread_type, wait) \
135 { \
136 char* data = nullptr; \
137 int len = 0; \
138 Symbol* clss_name = name(); \
139 if (clss_name != nullptr) { \
140 data = (char*)clss_name->bytes(); \
141 len = clss_name->utf8_length(); \
142 } \
143 HOTSPOT_CLASS_INITIALIZATION_##type( \
144 data, len, (void*)class_loader(), thread_type, wait); \
145 }
146
147 #else // ndef DTRACE_ENABLED
148
149 #define DTRACE_CLASSINIT_PROBE(type, thread_type)
150 #define DTRACE_CLASSINIT_PROBE_WAIT(type, thread_type, wait)
151
152 #endif // ndef DTRACE_ENABLED
153
154 void InlineLayoutInfo::metaspace_pointers_do(MetaspaceClosure* it) {
155 log_trace(cds)("Iter(InlineFieldInfo): %p", this);
156 it->push(&_klass);
157 }
158
159 bool InstanceKlass::_finalization_enabled = true;
160
161 static inline bool is_class_loader(const Symbol* class_name,
162 const ClassFileParser& parser) {
163 assert(class_name != nullptr, "invariant");
164
165 if (class_name == vmSymbols::java_lang_ClassLoader()) {
166 return true;
167 }
168
169 if (vmClasses::ClassLoader_klass_loaded()) {
170 const Klass* const super_klass = parser.super_klass();
171 if (super_klass != nullptr) {
172 if (super_klass->is_subtype_of(vmClasses::ClassLoader_klass())) {
173 return true;
174 }
175 }
176 }
177 return false;
178 }
179
180 bool InstanceKlass::field_is_null_free_inline_type(int index) const {
181 return field(index).field_flags().is_null_free_inline_type();
182 }
183
184 bool InstanceKlass::is_class_in_loadable_descriptors_attribute(Symbol* name) const {
185 if (_loadable_descriptors == nullptr) return false;
186 for (int i = 0; i < _loadable_descriptors->length(); i++) {
187 Symbol* class_name = _constants->symbol_at(_loadable_descriptors->at(i));
188 if (class_name == name) return true;
189 }
190 return false;
191 }
192
193 static inline bool is_stack_chunk_class(const Symbol* class_name,
194 const ClassLoaderData* loader_data) {
195 return (class_name == vmSymbols::jdk_internal_vm_StackChunk() &&
196 loader_data->is_the_null_class_loader_data());
197 }
198
199 // private: called to verify that k is a static member of this nest.
200 // We know that k is an instance class in the same package and hence the
201 // same classloader.
202 bool InstanceKlass::has_nest_member(JavaThread* current, InstanceKlass* k) const {
203 assert(!is_hidden(), "unexpected hidden class");
204 if (_nest_members == nullptr || _nest_members == Universe::the_empty_short_array()) {
205 if (log_is_enabled(Trace, class, nestmates)) {
206 ResourceMark rm(current);
207 log_trace(class, nestmates)("Checked nest membership of %s in non-nest-host class %s",
208 k->external_name(), this->external_name());
209 }
210 return false;
211 }
212
467 }
468
469 const char* InstanceKlass::nest_host_error() {
470 if (_nest_host_index == 0) {
471 return nullptr;
472 } else {
473 constantPoolHandle cph(Thread::current(), constants());
474 return SystemDictionary::find_nest_host_error(cph, (int)_nest_host_index);
475 }
476 }
477
478 void* InstanceKlass::operator new(size_t size, ClassLoaderData* loader_data, size_t word_size,
479 bool use_class_space, TRAPS) throw() {
480 return Metaspace::allocate(loader_data, word_size, ClassType, use_class_space, THREAD);
481 }
482
483 InstanceKlass* InstanceKlass::allocate_instance_klass(const ClassFileParser& parser, TRAPS) {
484 const int size = InstanceKlass::size(parser.vtable_size(),
485 parser.itable_size(),
486 nonstatic_oop_map_size(parser.total_oop_map_count()),
487 parser.is_interface(),
488 parser.is_inline_type());
489
490 const Symbol* const class_name = parser.class_name();
491 assert(class_name != nullptr, "invariant");
492 ClassLoaderData* loader_data = parser.loader_data();
493 assert(loader_data != nullptr, "invariant");
494
495 InstanceKlass* ik;
496 const bool use_class_space = parser.klass_needs_narrow_id();
497
498 // Allocation
499 if (parser.is_instance_ref_klass()) {
500 // java.lang.ref.Reference
501 ik = new (loader_data, size, use_class_space, THREAD) InstanceRefKlass(parser);
502 } else if (class_name == vmSymbols::java_lang_Class()) {
503 // mirror - java.lang.Class
504 ik = new (loader_data, size, use_class_space, THREAD) InstanceMirrorKlass(parser);
505 } else if (is_stack_chunk_class(class_name, loader_data)) {
506 // stack chunk
507 ik = new (loader_data, size, use_class_space, THREAD) InstanceStackChunkKlass(parser);
508 } else if (is_class_loader(class_name, parser)) {
509 // class loader - java.lang.ClassLoader
510 ik = new (loader_data, size, use_class_space, THREAD) InstanceClassLoaderKlass(parser);
511 } else if (parser.is_inline_type()) {
512 // inline type
513 ik = new (loader_data, size, use_class_space, THREAD) InlineKlass(parser);
514 } else {
515 // normal
516 ik = new (loader_data, size, use_class_space, THREAD) InstanceKlass(parser);
517 }
518
519 if (ik != nullptr && UseCompressedClassPointers && use_class_space) {
520 assert(CompressedKlassPointers::is_encodable(ik),
521 "Klass " PTR_FORMAT "needs a narrow Klass ID, but is not encodable", p2i(ik));
522 }
523
524 // Check for pending exception before adding to the loader data and incrementing
525 // class count. Can get OOM here.
526 if (HAS_PENDING_EXCEPTION) {
527 return nullptr;
528 }
529
530 #ifdef ASSERT
531 ik->bounds_check((address) ik->start_of_vtable(), false, size);
532 ik->bounds_check((address) ik->start_of_itable(), false, size);
533 ik->bounds_check((address) ik->end_of_itable(), true, size);
534 ik->bounds_check((address) ik->end_of_nonstatic_oop_maps(), true, size);
535 #endif //ASSERT
536 return ik;
537 }
538
539 #ifndef PRODUCT
540 bool InstanceKlass::bounds_check(address addr, bool edge_ok, intptr_t size_in_bytes) const {
541 const char* bad = nullptr;
542 address end = nullptr;
543 if (addr < (address)this) {
544 bad = "before";
545 } else if (addr == (address)this) {
546 if (edge_ok) return true;
547 bad = "just before";
548 } else if (addr == (end = (address)this + sizeof(intptr_t) * (size_in_bytes < 0 ? size() : size_in_bytes))) {
549 if (edge_ok) return true;
550 bad = "just after";
551 } else if (addr > end) {
552 bad = "after";
553 } else {
554 return true;
555 }
556 tty->print_cr("%s object bounds: " INTPTR_FORMAT " [" INTPTR_FORMAT ".." INTPTR_FORMAT "]",
557 bad, (intptr_t)addr, (intptr_t)this, (intptr_t)end);
558 Verbose = WizardMode = true; this->print(); //@@
559 return false;
560 }
561 #endif //PRODUCT
562
563 // copy method ordering from resource area to Metaspace
564 void InstanceKlass::copy_method_ordering(const intArray* m, TRAPS) {
565 if (m != nullptr) {
566 // allocate a new array and copy contents (memcpy?)
567 _method_ordering = MetadataFactory::new_array<int>(class_loader_data(), m->length(), CHECK);
568 for (int i = 0; i < m->length(); i++) {
569 _method_ordering->at_put(i, m->at(i));
570 }
571 } else {
572 _method_ordering = Universe::the_empty_int_array();
573 }
574 }
575
576 // create a new array of vtable_indices for default methods
577 Array<int>* InstanceKlass::create_new_default_vtable_indices(int len, TRAPS) {
578 Array<int>* vtable_indices = MetadataFactory::new_array<int>(class_loader_data(), len, CHECK_NULL);
579 assert(default_vtable_indices() == nullptr, "only create once");
580 set_default_vtable_indices(vtable_indices);
581 return vtable_indices;
582 }
583
584
585 InstanceKlass::InstanceKlass() {
586 assert(CDSConfig::is_dumping_static_archive() || CDSConfig::is_using_archive(), "only for CDS");
587 }
588
589 InstanceKlass::InstanceKlass(const ClassFileParser& parser, KlassKind kind, markWord prototype_header, ReferenceType reference_type) :
590 Klass(kind, prototype_header),
591 _nest_members(nullptr),
592 _nest_host(nullptr),
593 _permitted_subclasses(nullptr),
594 _record_components(nullptr),
595 _static_field_size(parser.static_field_size()),
596 _nonstatic_oop_map_size(nonstatic_oop_map_size(parser.total_oop_map_count())),
597 _itable_len(parser.itable_size()),
598 _nest_host_index(0),
599 _init_state(allocated),
600 _reference_type(reference_type),
601 _init_thread(nullptr),
602 _inline_layout_info_array(nullptr),
603 _loadable_descriptors(nullptr),
604 _adr_inlineklass_fixed_block(nullptr)
605 {
606 set_vtable_length(parser.vtable_size());
607 set_access_flags(parser.access_flags());
608 if (parser.is_hidden()) set_is_hidden();
609 set_layout_helper(Klass::instance_layout_helper(parser.layout_size(),
610 false));
611 if (parser.has_inline_fields()) {
612 set_has_inline_type_fields();
613 }
614
615 assert(nullptr == _methods, "underlying memory not zeroed?");
616 assert(is_instance_klass(), "is layout incorrect?");
617 assert(size_helper() == parser.layout_size(), "incorrect size_helper?");
618 }
619
620 void InstanceKlass::deallocate_methods(ClassLoaderData* loader_data,
621 Array<Method*>* methods) {
622 if (methods != nullptr && methods != Universe::the_empty_method_array() &&
623 !methods->is_shared()) {
624 for (int i = 0; i < methods->length(); i++) {
625 Method* method = methods->at(i);
626 if (method == nullptr) continue; // maybe null if error processing
627 // Only want to delete methods that are not executing for RedefineClasses.
628 // The previous version will point to them so they're not totally dangling
629 assert (!method->on_stack(), "shouldn't be called with methods on stack");
630 MetadataFactory::free_metadata(loader_data, method);
631 }
632 MetadataFactory::free_array<Method*>(loader_data, methods);
633 }
733 (address)(secondary_supers()) != (address)(transitive_interfaces()) &&
734 !secondary_supers()->is_shared()) {
735 MetadataFactory::free_array<Klass*>(loader_data, secondary_supers());
736 }
737 set_secondary_supers(nullptr, SECONDARY_SUPERS_BITMAP_EMPTY);
738
739 deallocate_interfaces(loader_data, super(), local_interfaces(), transitive_interfaces());
740 set_transitive_interfaces(nullptr);
741 set_local_interfaces(nullptr);
742
743 if (fieldinfo_stream() != nullptr && !fieldinfo_stream()->is_shared()) {
744 MetadataFactory::free_array<u1>(loader_data, fieldinfo_stream());
745 }
746 set_fieldinfo_stream(nullptr);
747
748 if (fields_status() != nullptr && !fields_status()->is_shared()) {
749 MetadataFactory::free_array<FieldStatus>(loader_data, fields_status());
750 }
751 set_fields_status(nullptr);
752
753 if (inline_layout_info_array() != nullptr) {
754 MetadataFactory::free_array<InlineLayoutInfo>(loader_data, inline_layout_info_array());
755 }
756 set_inline_layout_info_array(nullptr);
757
758 // If a method from a redefined class is using this constant pool, don't
759 // delete it, yet. The new class's previous version will point to this.
760 if (constants() != nullptr) {
761 assert (!constants()->on_stack(), "shouldn't be called if anything is onstack");
762 if (!constants()->is_shared()) {
763 MetadataFactory::free_metadata(loader_data, constants());
764 }
765 // Delete any cached resolution errors for the constant pool
766 SystemDictionary::delete_resolution_error(constants());
767
768 set_constants(nullptr);
769 }
770
771 if (inner_classes() != nullptr &&
772 inner_classes() != Universe::the_empty_short_array() &&
773 !inner_classes()->is_shared()) {
774 MetadataFactory::free_array<jushort>(loader_data, inner_classes());
775 }
776 set_inner_classes(nullptr);
777
778 if (nest_members() != nullptr &&
779 nest_members() != Universe::the_empty_short_array() &&
780 !nest_members()->is_shared()) {
781 MetadataFactory::free_array<jushort>(loader_data, nest_members());
782 }
783 set_nest_members(nullptr);
784
785 if (permitted_subclasses() != nullptr &&
786 permitted_subclasses() != Universe::the_empty_short_array() &&
787 !permitted_subclasses()->is_shared()) {
788 MetadataFactory::free_array<jushort>(loader_data, permitted_subclasses());
789 }
790 set_permitted_subclasses(nullptr);
791
792 if (loadable_descriptors() != nullptr &&
793 loadable_descriptors() != Universe::the_empty_short_array() &&
794 !loadable_descriptors()->is_shared()) {
795 MetadataFactory::free_array<jushort>(loader_data, loadable_descriptors());
796 }
797 set_loadable_descriptors(nullptr);
798
799 // We should deallocate the Annotations instance if it's not in shared spaces.
800 if (annotations() != nullptr && !annotations()->is_shared()) {
801 MetadataFactory::free_metadata(loader_data, annotations());
802 }
803 set_annotations(nullptr);
804
805 SystemDictionaryShared::handle_class_unloading(this);
806
807 #if INCLUDE_CDS_JAVA_HEAP
808 if (CDSConfig::is_dumping_heap()) {
809 HeapShared::remove_scratch_objects(this);
810 }
811 #endif
812 }
813
814 bool InstanceKlass::is_record() const {
815 return _record_components != nullptr &&
816 is_final() &&
817 java_super() == vmClasses::Record_klass();
818 }
1013 vmSymbols::java_lang_IncompatibleClassChangeError(),
1014 "class %s has interface %s as super class",
1015 external_name(),
1016 super_klass->external_name()
1017 );
1018 return false;
1019 }
1020
1021 InstanceKlass* ik_super = InstanceKlass::cast(super_klass);
1022 ik_super->link_class_impl(CHECK_false);
1023 }
1024
1025 // link all interfaces implemented by this class before linking this class
1026 Array<InstanceKlass*>* interfaces = local_interfaces();
1027 int num_interfaces = interfaces->length();
1028 for (int index = 0; index < num_interfaces; index++) {
1029 InstanceKlass* interk = interfaces->at(index);
1030 interk->link_class_impl(CHECK_false);
1031 }
1032
1033
1034 // If a class declares a method that uses an inline class as an argument
1035 // type or return inline type, this inline class must be loaded during the
1036 // linking of this class because size and properties of the inline class
1037 // must be known in order to be able to perform inline type optimizations.
1038 // The implementation below is an approximation of this rule, the code
1039 // iterates over all methods of the current class (including overridden
1040 // methods), not only the methods declared by this class. This
1041 // approximation makes the code simpler, and doesn't change the semantic
1042 // because classes declaring methods overridden by the current class are
1043 // linked (and have performed their own pre-loading) before the linking
1044 // of the current class.
1045
1046
1047 // Note:
1048 // Inline class types are loaded during
1049 // the loading phase (see ClassFileParser::post_process_parsed_stream()).
1050 // Inline class types used as element types for array creation
1051 // are not pre-loaded. Their loading is triggered by either anewarray
1052 // or multianewarray bytecodes.
1053
1054 // Could it be possible to do the following processing only if the
1055 // class uses inline types?
1056 if (EnableValhalla) {
1057 ResourceMark rm(THREAD);
1058 for (AllFieldStream fs(this); !fs.done(); fs.next()) {
1059 if (fs.is_null_free_inline_type() && fs.access_flags().is_static()) {
1060 assert(fs.access_flags().is_strict(), "null-free fields must be strict");
1061 Symbol* sig = fs.signature();
1062 TempNewSymbol s = Signature::strip_envelope(sig);
1063 if (s != name()) {
1064 log_info(class, preload)("Preloading class %s during linking of class %s. Cause: a null-free static field is declared with this type", s->as_C_string(), name()->as_C_string());
1065 Klass* klass = SystemDictionary::resolve_or_fail(s,
1066 Handle(THREAD, class_loader()), true,
1067 CHECK_false);
1068 if (HAS_PENDING_EXCEPTION) {
1069 log_warning(class, preload)("Preloading of class %s during linking of class %s (cause: null-free static field) failed: %s",
1070 s->as_C_string(), name()->as_C_string(), PENDING_EXCEPTION->klass()->name()->as_C_string());
1071 return false; // Exception is still pending
1072 }
1073 log_info(class, preload)("Preloading of class %s during linking of class %s (cause: null-free static field) succeeded",
1074 s->as_C_string(), name()->as_C_string());
1075 assert(klass != nullptr, "Sanity check");
1076 if (klass->is_abstract()) {
1077 THROW_MSG_(vmSymbols::java_lang_IncompatibleClassChangeError(),
1078 err_msg("Class %s expects class %s to be concrete value class, but it is an abstract class",
1079 name()->as_C_string(),
1080 InstanceKlass::cast(klass)->external_name()), false);
1081 }
1082 if (!klass->is_inline_klass()) {
1083 THROW_MSG_(vmSymbols::java_lang_IncompatibleClassChangeError(),
1084 err_msg("class %s expects class %s to be a value class but it is an identity class",
1085 name()->as_C_string(), klass->external_name()), false);
1086 }
1087 InlineKlass* vk = InlineKlass::cast(klass);
1088 // the inline_type_field_klasses_array might have been loaded with CDS, so update only if not already set and check consistency
1089 InlineLayoutInfo* li = inline_layout_info_adr(fs.index());
1090 if (li->klass() == nullptr) {
1091 li->set_klass(InlineKlass::cast(vk));
1092 li->set_kind(LayoutKind::REFERENCE);
1093 }
1094 assert(get_inline_type_field_klass(fs.index()) == vk, "Must match");
1095 } else {
1096 InlineLayoutInfo* li = inline_layout_info_adr(fs.index());
1097 if (li->klass() == nullptr) {
1098 li->set_klass(InlineKlass::cast(this));
1099 li->set_kind(LayoutKind::REFERENCE);
1100 }
1101 assert(get_inline_type_field_klass(fs.index()) == this, "Must match");
1102 }
1103 }
1104 }
1105
1106 // Aggressively preloading all classes from the LoadableDescriptors attribute
1107 if (loadable_descriptors() != nullptr) {
1108 HandleMark hm(THREAD);
1109 for (int i = 0; i < loadable_descriptors()->length(); i++) {
1110 Symbol* sig = constants()->symbol_at(loadable_descriptors()->at(i));
1111 if (!Signature::has_envelope(sig)) continue;
1112 TempNewSymbol class_name = Signature::strip_envelope(sig);
1113 if (class_name == name()) continue;
1114 log_info(class, preload)("Preloading class %s during linking of class %s because of the class is listed in the LoadableDescriptors attribute", sig->as_C_string(), name()->as_C_string());
1115 oop loader = class_loader();
1116 Klass* klass = SystemDictionary::resolve_or_null(class_name,
1117 Handle(THREAD, loader), THREAD);
1118 if (HAS_PENDING_EXCEPTION) {
1119 CLEAR_PENDING_EXCEPTION;
1120 }
1121 if (klass != nullptr) {
1122 log_info(class, preload)("Preloading of class %s during linking of class %s (cause: LoadableDescriptors attribute) succeeded", class_name->as_C_string(), name()->as_C_string());
1123 if (!klass->is_inline_klass()) {
1124 // Non value class are allowed by the current spec, but it could be an indication of an issue so let's log a warning
1125 log_warning(class, preload)("Preloading class %s during linking of class %s (cause: LoadableDescriptors attribute) but loaded class is not a value class", class_name->as_C_string(), name()->as_C_string());
1126 }
1127 } else {
1128 log_warning(class, preload)("Preloading of class %s during linking of class %s (cause: LoadableDescriptors attribute) failed", class_name->as_C_string(), name()->as_C_string());
1129 }
1130 }
1131 }
1132 }
1133
1134 // in case the class is linked in the process of linking its superclasses
1135 if (is_linked()) {
1136 return true;
1137 }
1138
1139 // trace only the link time for this klass that includes
1140 // the verification time
1141 PerfClassTraceTime vmtimer(ClassLoader::perf_class_link_time(),
1142 ClassLoader::perf_class_link_selftime(),
1143 ClassLoader::perf_classes_linked(),
1144 jt->get_thread_stat()->perf_recursion_counts_addr(),
1145 jt->get_thread_stat()->perf_timers_addr(),
1146 PerfClassTraceTime::CLASS_LINK);
1147
1148 // verification & rewriting
1149 {
1150 HandleMark hm(THREAD);
1151 Handle h_init_lock(THREAD, init_lock());
1152 ObjectLocker ol(h_init_lock, jt);
1153 // rewritten will have been set if loader constraint error found
1418 ss.print("Could not initialize class %s", external_name());
1419 if (cause.is_null()) {
1420 THROW_MSG(vmSymbols::java_lang_NoClassDefFoundError(), ss.as_string());
1421 } else {
1422 THROW_MSG_CAUSE(vmSymbols::java_lang_NoClassDefFoundError(),
1423 ss.as_string(), cause);
1424 }
1425 } else {
1426
1427 // Step 6
1428 set_init_state(being_initialized);
1429 set_init_thread(jt);
1430 if (debug_logging_enabled) {
1431 ResourceMark rm(jt);
1432 log_debug(class, init)("Thread \"%s\" is initializing %s",
1433 jt->name(), external_name());
1434 }
1435 }
1436 }
1437
1438 // Pre-allocating an all-zero value to be used to reset nullable flat storages
1439 if (is_inline_klass()) {
1440 InlineKlass* vk = InlineKlass::cast(this);
1441 if (vk->has_nullable_atomic_layout()) {
1442 oop val = vk->allocate_instance(THREAD);
1443 if (HAS_PENDING_EXCEPTION) {
1444 Handle e(THREAD, PENDING_EXCEPTION);
1445 CLEAR_PENDING_EXCEPTION;
1446 {
1447 EXCEPTION_MARK;
1448 add_initialization_error(THREAD, e);
1449 // Locks object, set state, and notify all waiting threads
1450 set_initialization_state_and_notify(initialization_error, THREAD);
1451 CLEAR_PENDING_EXCEPTION;
1452 }
1453 THROW_OOP(e());
1454 }
1455 vk->set_null_reset_value(val);
1456 }
1457 }
1458
1459 // Step 7
1460 // Next, if C is a class rather than an interface, initialize it's super class and super
1461 // interfaces.
1462 if (!is_interface()) {
1463 Klass* super_klass = super();
1464 if (super_klass != nullptr && super_klass->should_be_initialized()) {
1465 super_klass->initialize(THREAD);
1466 }
1467 // If C implements any interface that declares a non-static, concrete method,
1468 // the initialization of C triggers initialization of its super interfaces.
1469 // Only need to recurse if has_nonstatic_concrete_methods which includes declaring and
1470 // having a superinterface that declares, non-static, concrete methods
1471 if (!HAS_PENDING_EXCEPTION && has_nonstatic_concrete_methods()) {
1472 initialize_super_interfaces(THREAD);
1473 }
1474
1475 // If any exceptions, complete abruptly, throwing the same exception as above.
1476 if (HAS_PENDING_EXCEPTION) {
1477 Handle e(THREAD, PENDING_EXCEPTION);
1478 CLEAR_PENDING_EXCEPTION;
1479 {
1480 EXCEPTION_MARK;
1481 add_initialization_error(THREAD, e);
1482 // Locks object, set state, and notify all waiting threads
1483 set_initialization_state_and_notify(initialization_error, THREAD);
1484 CLEAR_PENDING_EXCEPTION;
1485 }
1486 DTRACE_CLASSINIT_PROBE_WAIT(super__failed, -1, wait);
1487 THROW_OOP(e());
1488 }
1489 }
1490
1491 // Step 8
1492 {
1493 DTRACE_CLASSINIT_PROBE_WAIT(clinit, -1, wait);
1494 if (class_initializer() != nullptr) {
1495 // Timer includes any side effects of class initialization (resolution,
1496 // etc), but not recursive entry into call_class_initializer().
1497 PerfClassTraceTime timer(ClassLoader::perf_class_init_time(),
1498 ClassLoader::perf_class_init_selftime(),
1499 ClassLoader::perf_classes_inited(),
1500 jt->get_thread_stat()->perf_recursion_counts_addr(),
1501 jt->get_thread_stat()->perf_timers_addr(),
1502 PerfClassTraceTime::CLASS_CLINIT);
1503 call_class_initializer(THREAD);
1504 } else {
1505 // The elapsed time is so small it's not worth counting.
1506 if (UsePerfData) {
1507 ClassLoader::perf_classes_inited()->inc();
1508 }
1509 call_class_initializer(THREAD);
1510 }
1511
1512 if (has_strict_static_fields() && !HAS_PENDING_EXCEPTION) {
1513 // Step 9 also verifies that strict static fields have been initialized.
1514 // Status bits were set in ClassFileParser::post_process_parsed_stream.
1515 // After <clinit>, bits must all be clear, or else we must throw an error.
1516 // This is an extremely fast check, so we won't bother with a timer.
1517 assert(fields_status() != nullptr, "");
1518 Symbol* bad_strict_static = nullptr;
1519 for (int index = 0; index < fields_status()->length(); index++) {
1520 // Very fast loop over single byte array looking for a set bit.
1521 if (fields_status()->adr_at(index)->is_strict_static_unset()) {
1522 // This strict static field has not been set by the class initializer.
1523 // Note that in the common no-error case, we read no field metadata.
1524 // We only unpack it when we need to report an error.
1525 FieldInfo fi = field(index);
1526 bad_strict_static = fi.name(constants());
1527 if (debug_logging_enabled) {
1528 ResourceMark rm(jt);
1529 const char* msg = format_strict_static_message(bad_strict_static);
1530 log_debug(class, init)("%s", msg);
1531 } else {
1532 // If we are not logging, do not bother to look for a second offense.
1533 break;
1534 }
1535 }
1536 }
1537 if (bad_strict_static != nullptr) {
1538 throw_strict_static_exception(bad_strict_static, "is unset after initialization of", THREAD);
1539 }
1540 }
1541 }
1542
1543 // Step 9
1544 if (!HAS_PENDING_EXCEPTION) {
1545 set_initialization_state_and_notify(fully_initialized, CHECK);
1546 debug_only(vtable().verify(tty, true);)
1547 }
1548 else {
1549 // Step 10 and 11
1550 Handle e(THREAD, PENDING_EXCEPTION);
1551 CLEAR_PENDING_EXCEPTION;
1552 // JVMTI has already reported the pending exception
1553 // JVMTI internal flag reset is needed in order to report ExceptionInInitializerError
1554 JvmtiExport::clear_detected_exception(jt);
1555 {
1556 EXCEPTION_MARK;
1557 add_initialization_error(THREAD, e);
1558 set_initialization_state_and_notify(initialization_error, THREAD);
1559 CLEAR_PENDING_EXCEPTION; // ignore any exception thrown, class initialization error is thrown below
1560 // JVMTI has already reported the pending exception
1573 }
1574 DTRACE_CLASSINIT_PROBE_WAIT(end, -1, wait);
1575 }
1576
1577
1578 void InstanceKlass::set_initialization_state_and_notify(ClassState state, TRAPS) {
1579 Handle h_init_lock(THREAD, init_lock());
1580 if (h_init_lock() != nullptr) {
1581 ObjectLocker ol(h_init_lock, THREAD);
1582 set_init_thread(nullptr); // reset _init_thread before changing _init_state
1583 set_init_state(state);
1584 fence_and_clear_init_lock();
1585 ol.notify_all(CHECK);
1586 } else {
1587 assert(h_init_lock() != nullptr, "The initialization state should never be set twice");
1588 set_init_thread(nullptr); // reset _init_thread before changing _init_state
1589 set_init_state(state);
1590 }
1591 }
1592
1593 void InstanceKlass::notify_strict_static_access(int field_index, bool is_writing, TRAPS) {
1594 guarantee(field_index >= 0 && field_index < fields_status()->length(), "valid field index");
1595 DEBUG_ONLY(FieldInfo debugfi = field(field_index));
1596 assert(debugfi.access_flags().is_strict(), "");
1597 assert(debugfi.access_flags().is_static(), "");
1598 FieldStatus& fs = *fields_status()->adr_at(field_index);
1599 LogTarget(Trace, class, init) lt;
1600 if (lt.is_enabled()) {
1601 ResourceMark rm(THREAD);
1602 LogStream ls(lt);
1603 FieldInfo fi = field(field_index);
1604 ls.print("notify %s %s %s%s ",
1605 external_name(), is_writing? "Write" : "Read",
1606 fs.is_strict_static_unset() ? "Unset" : "(set)",
1607 fs.is_strict_static_unread() ? "+Unread" : "");
1608 fi.print(&ls, constants());
1609 }
1610 if (fs.is_strict_static_unset()) {
1611 assert(fs.is_strict_static_unread(), "ClassFileParser resp.");
1612 // If it is not set, there are only two reasonable things we can do here:
1613 // - mark it set if this is putstatic
1614 // - throw an error (Read-Before-Write) if this is getstatic
1615
1616 // The unset state is (or should be) transient, and observable only in one
1617 // thread during the execution of <clinit>. Something is wrong here as this
1618 // should not be possible
1619 guarantee(is_reentrant_initialization(THREAD), "unscoped access to strict static");
1620 if (is_writing) {
1621 // clear the "unset" bit, since the field is actually going to be written
1622 fs.update_strict_static_unset(false);
1623 } else {
1624 // throw an IllegalStateException, since we are reading before writing
1625 // see also InstanceKlass::initialize_impl, Step 8 (at end)
1626 Symbol* bad_strict_static = field(field_index).name(constants());
1627 throw_strict_static_exception(bad_strict_static, "is unset before first read in", CHECK);
1628 }
1629 } else {
1630 // Ensure no write after read for final strict statics
1631 FieldInfo fi = field(field_index);
1632 bool is_final = fi.access_flags().is_final();
1633 if (is_final) {
1634 // no final write after read, so observing a constant freezes it, as if <clinit> ended early
1635 // (maybe we could trust the constant a little earlier, before <clinit> ends)
1636 if (is_writing && !fs.is_strict_static_unread()) {
1637 Symbol* bad_strict_static = fi.name(constants());
1638 throw_strict_static_exception(bad_strict_static, "is set after read (as final) in", CHECK);
1639 } else if (!is_writing && fs.is_strict_static_unread()) {
1640 fs.update_strict_static_unread(false);
1641 }
1642 }
1643 }
1644 }
1645
1646 void InstanceKlass::throw_strict_static_exception(Symbol* field_name, const char* when, TRAPS) {
1647 ResourceMark rm(THREAD);
1648 const char* msg = format_strict_static_message(field_name, when);
1649 THROW_MSG(vmSymbols::java_lang_IllegalStateException(), msg);
1650 }
1651
1652 const char* InstanceKlass::format_strict_static_message(Symbol* field_name, const char* when) {
1653 stringStream ss;
1654 ss.print("Strict static \"%s\" %s %s",
1655 field_name->as_C_string(),
1656 when == nullptr ? "is unset in" : when,
1657 external_name());
1658 return ss.as_string();
1659 }
1660
1661 // Update hierarchy. This is done before the new klass has been added to the SystemDictionary. The Compile_lock
1662 // is grabbed, to ensure that the compiler is not using the class hierarchy.
1663 void InstanceKlass::add_to_hierarchy(JavaThread* current) {
1664 assert(!SafepointSynchronize::is_at_safepoint(), "must NOT be at safepoint");
1665
1666 DeoptimizationScope deopt_scope;
1667 {
1668 MutexLocker ml(current, Compile_lock);
1669
1670 set_init_state(InstanceKlass::loaded);
1671 // make sure init_state store is already done.
1672 // The compiler reads the hierarchy outside of the Compile_lock.
1673 // Access ordering is used to add to hierarchy.
1674
1675 // Link into hierarchy.
1676 append_to_sibling_list(); // add to superklass/sibling list
1677 process_interfaces(); // handle all "implements" declarations
1678
1679 // Now mark all code that depended on old class hierarchy.
1680 // Note: must be done *after* linking k into the hierarchy (was bug 12/9/97)
1893 ResourceMark rm(THREAD);
1894 THROW_MSG(throwError ? vmSymbols::java_lang_InstantiationError()
1895 : vmSymbols::java_lang_InstantiationException(), external_name());
1896 }
1897 if (this == vmClasses::Class_klass()) {
1898 ResourceMark rm(THREAD);
1899 THROW_MSG(throwError ? vmSymbols::java_lang_IllegalAccessError()
1900 : vmSymbols::java_lang_IllegalAccessException(), external_name());
1901 }
1902 }
1903
1904 ArrayKlass* InstanceKlass::array_klass(int n, TRAPS) {
1905 // Need load-acquire for lock-free read
1906 if (array_klasses_acquire() == nullptr) {
1907
1908 // Recursively lock array allocation
1909 RecursiveLocker rl(MultiArray_lock, THREAD);
1910
1911 // Check if another thread created the array klass while we were waiting for the lock.
1912 if (array_klasses() == nullptr) {
1913 ObjArrayKlass* k = ObjArrayKlass::allocate_objArray_klass(class_loader_data(), 1, this, false, CHECK_NULL);
1914 // use 'release' to pair with lock-free load
1915 release_set_array_klasses(k);
1916 }
1917 }
1918
1919 // array_klasses() will always be set at this point
1920 ArrayKlass* ak = array_klasses();
1921 assert(ak != nullptr, "should be set");
1922 return ak->array_klass(n, THREAD);
1923 }
1924
1925 ArrayKlass* InstanceKlass::array_klass_or_null(int n) {
1926 // Need load-acquire for lock-free read
1927 ArrayKlass* ak = array_klasses_acquire();
1928 if (ak == nullptr) {
1929 return nullptr;
1930 } else {
1931 return ak->array_klass_or_null(n);
1932 }
1933 }
1934
1935 ArrayKlass* InstanceKlass::array_klass(TRAPS) {
1936 return array_klass(1, THREAD);
1937 }
1938
1939 ArrayKlass* InstanceKlass::array_klass_or_null() {
1940 return array_klass_or_null(1);
1941 }
1942
1943 static int call_class_initializer_counter = 0; // for debugging
1944
1945 Method* InstanceKlass::class_initializer() const {
1946 Method* clinit = find_method(
1947 vmSymbols::class_initializer_name(), vmSymbols::void_method_signature());
1948 if (clinit != nullptr && clinit->is_class_initializer()) {
1949 return clinit;
1950 }
1951 return nullptr;
1952 }
1953
1954 void InstanceKlass::call_class_initializer(TRAPS) {
1955 if (ReplayCompiles &&
1956 (ReplaySuppressInitializers == 1 ||
1957 (ReplaySuppressInitializers >= 2 && class_loader() != nullptr))) {
1958 // Hide the existence of the initializer for the purpose of replaying the compile
1959 return;
1960 }
1961
1962 #if INCLUDE_CDS
1963 // This is needed to ensure the consistency of the archived heap objects.
1964 if (has_aot_initialized_mirror() && CDSConfig::is_loading_heap()) {
1965 AOTClassInitializer::call_runtime_setup(THREAD, this);
1966 return;
1967 } else if (has_archived_enum_objs()) {
1968 assert(is_shared(), "must be");
2037
2038 void InstanceKlass::mask_for(const methodHandle& method, int bci,
2039 InterpreterOopMap* entry_for) {
2040 // Lazily create the _oop_map_cache at first request.
2041 // Load_acquire is needed to safely get instance published with CAS by another thread.
2042 OopMapCache* oop_map_cache = Atomic::load_acquire(&_oop_map_cache);
2043 if (oop_map_cache == nullptr) {
2044 // Try to install new instance atomically.
2045 oop_map_cache = new OopMapCache();
2046 OopMapCache* other = Atomic::cmpxchg(&_oop_map_cache, (OopMapCache*)nullptr, oop_map_cache);
2047 if (other != nullptr) {
2048 // Someone else managed to install before us, ditch local copy and use the existing one.
2049 delete oop_map_cache;
2050 oop_map_cache = other;
2051 }
2052 }
2053 // _oop_map_cache is constant after init; lookup below does its own locking.
2054 oop_map_cache->lookup(method, bci, entry_for);
2055 }
2056
2057
2058 FieldInfo InstanceKlass::field(int index) const {
2059 for (AllFieldStream fs(this); !fs.done(); fs.next()) {
2060 if (fs.index() == index) {
2061 return fs.to_FieldInfo();
2062 }
2063 }
2064 fatal("Field not found");
2065 return FieldInfo();
2066 }
2067
2068 bool InstanceKlass::find_local_field(Symbol* name, Symbol* sig, fieldDescriptor* fd) const {
2069 for (JavaFieldStream fs(this); !fs.done(); fs.next()) {
2070 Symbol* f_name = fs.name();
2071 Symbol* f_sig = fs.signature();
2072 if (f_name == name && f_sig == sig) {
2073 fd->reinitialize(const_cast<InstanceKlass*>(this), fs.to_FieldInfo());
2074 return true;
2075 }
2076 }
2118
2119 Klass* InstanceKlass::find_field(Symbol* name, Symbol* sig, bool is_static, fieldDescriptor* fd) const {
2120 // search order according to newest JVM spec (5.4.3.2, p.167).
2121 // 1) search for field in current klass
2122 if (find_local_field(name, sig, fd)) {
2123 if (fd->is_static() == is_static) return const_cast<InstanceKlass*>(this);
2124 }
2125 // 2) search for field recursively in direct superinterfaces
2126 if (is_static) {
2127 Klass* intf = find_interface_field(name, sig, fd);
2128 if (intf != nullptr) return intf;
2129 }
2130 // 3) apply field lookup recursively if superclass exists
2131 { Klass* supr = super();
2132 if (supr != nullptr) return InstanceKlass::cast(supr)->find_field(name, sig, is_static, fd);
2133 }
2134 // 4) otherwise field lookup fails
2135 return nullptr;
2136 }
2137
2138 bool InstanceKlass::contains_field_offset(int offset) {
2139 if (this->is_inline_klass()) {
2140 InlineKlass* vk = InlineKlass::cast(this);
2141 return offset >= vk->payload_offset() && offset < (vk->payload_offset() + vk->payload_size_in_bytes());
2142 } else {
2143 fieldDescriptor fd;
2144 return find_field_from_offset(offset, false, &fd);
2145 }
2146 }
2147
2148 bool InstanceKlass::find_local_field_from_offset(int offset, bool is_static, fieldDescriptor* fd) const {
2149 for (JavaFieldStream fs(this); !fs.done(); fs.next()) {
2150 if (fs.offset() == offset) {
2151 fd->reinitialize(const_cast<InstanceKlass*>(this), fs.to_FieldInfo());
2152 if (fd->is_static() == is_static) return true;
2153 }
2154 }
2155 return false;
2156 }
2157
2158
2159 bool InstanceKlass::find_field_from_offset(int offset, bool is_static, fieldDescriptor* fd) const {
2160 Klass* klass = const_cast<InstanceKlass*>(this);
2161 while (klass != nullptr) {
2162 if (InstanceKlass::cast(klass)->find_local_field_from_offset(offset, is_static, fd)) {
2163 return true;
2164 }
2165 klass = klass->super();
2166 }
2510 }
2511
2512 // uncached_lookup_method searches both the local class methods array and all
2513 // superclasses methods arrays, skipping any overpass methods in superclasses,
2514 // and possibly skipping private methods.
2515 Method* InstanceKlass::uncached_lookup_method(const Symbol* name,
2516 const Symbol* signature,
2517 OverpassLookupMode overpass_mode,
2518 PrivateLookupMode private_mode) const {
2519 OverpassLookupMode overpass_local_mode = overpass_mode;
2520 const Klass* klass = this;
2521 while (klass != nullptr) {
2522 Method* const method = InstanceKlass::cast(klass)->find_method_impl(name,
2523 signature,
2524 overpass_local_mode,
2525 StaticLookupMode::find,
2526 private_mode);
2527 if (method != nullptr) {
2528 return method;
2529 }
2530 if (name == vmSymbols::object_initializer_name()) {
2531 break; // <init> is never inherited
2532 }
2533 klass = klass->super();
2534 overpass_local_mode = OverpassLookupMode::skip; // Always ignore overpass methods in superclasses
2535 }
2536 return nullptr;
2537 }
2538
2539 #ifdef ASSERT
2540 // search through class hierarchy and return true if this class or
2541 // one of the superclasses was redefined
2542 bool InstanceKlass::has_redefined_this_or_super() const {
2543 const Klass* klass = this;
2544 while (klass != nullptr) {
2545 if (InstanceKlass::cast(klass)->has_been_redefined()) {
2546 return true;
2547 }
2548 klass = klass->super();
2549 }
2550 return false;
2551 }
2552 #endif
2910 int itable_offset_in_words = (int)(start_of_itable() - (intptr_t*)this);
2911
2912 int nof_interfaces = (method_table_offset_in_words - itable_offset_in_words)
2913 / itableOffsetEntry::size();
2914
2915 for (int i = 0; i < nof_interfaces; i ++, ioe ++) {
2916 if (ioe->interface_klass() != nullptr) {
2917 it->push(ioe->interface_klass_addr());
2918 itableMethodEntry* ime = ioe->first_method_entry(this);
2919 int n = klassItable::method_count_for_interface(ioe->interface_klass());
2920 for (int index = 0; index < n; index ++) {
2921 it->push(ime[index].method_addr());
2922 }
2923 }
2924 }
2925 }
2926
2927 it->push(&_nest_host);
2928 it->push(&_nest_members);
2929 it->push(&_permitted_subclasses);
2930 it->push(&_loadable_descriptors);
2931 it->push(&_record_components);
2932 it->push(&_inline_layout_info_array, MetaspaceClosure::_writable);
2933 }
2934
2935 #if INCLUDE_CDS
2936 void InstanceKlass::remove_unshareable_info() {
2937
2938 if (is_linked()) {
2939 assert(can_be_verified_at_dumptime(), "must be");
2940 // Remember this so we can avoid walking the hierarchy at runtime.
2941 set_verified_at_dump_time();
2942 }
2943
2944 Klass::remove_unshareable_info();
2945
2946 if (SystemDictionaryShared::has_class_failed_verification(this)) {
2947 // Classes are attempted to link during dumping and may fail,
2948 // but these classes are still in the dictionary and class list in CLD.
2949 // If the class has failed verification, there is nothing else to remove.
2950 return;
2951 }
2952
2958
2959 { // Otherwise this needs to take out the Compile_lock.
2960 assert(SafepointSynchronize::is_at_safepoint(), "only called at safepoint");
2961 init_implementor();
2962 }
2963
2964 // Call remove_unshareable_info() on other objects that belong to this class, except
2965 // for constants()->remove_unshareable_info(), which is called in a separate pass in
2966 // ArchiveBuilder::make_klasses_shareable(),
2967
2968 for (int i = 0; i < methods()->length(); i++) {
2969 Method* m = methods()->at(i);
2970 m->remove_unshareable_info();
2971 }
2972
2973 // do array classes also.
2974 if (array_klasses() != nullptr) {
2975 array_klasses()->remove_unshareable_info();
2976 }
2977
2978 // These are not allocated from metaspace. They are safe to set to nullptr.
2979 _source_debug_extension = nullptr;
2980 _dep_context = nullptr;
2981 _osr_nmethods_head = nullptr;
2982 #if INCLUDE_JVMTI
2983 _breakpoints = nullptr;
2984 _previous_versions = nullptr;
2985 _cached_class_file = nullptr;
2986 _jvmti_cached_class_field_map = nullptr;
2987 #endif
2988
2989 _init_thread = nullptr;
2990 _methods_jmethod_ids = nullptr;
2991 _jni_ids = nullptr;
2992 _oop_map_cache = nullptr;
2993 if (CDSConfig::is_dumping_method_handles() && HeapShared::is_lambda_proxy_klass(this)) {
2994 // keep _nest_host
2995 } else {
2996 // clear _nest_host to ensure re-load at runtime
2997 _nest_host = nullptr;
2998 }
3047 void InstanceKlass::compute_has_loops_flag_for_methods() {
3048 Array<Method*>* methods = this->methods();
3049 for (int index = 0; index < methods->length(); ++index) {
3050 Method* m = methods->at(index);
3051 if (!m->is_overpass()) { // work around JDK-8305771
3052 m->compute_has_loops_flag();
3053 }
3054 }
3055 }
3056
3057 void InstanceKlass::restore_unshareable_info(ClassLoaderData* loader_data, Handle protection_domain,
3058 PackageEntry* pkg_entry, TRAPS) {
3059 // InstanceKlass::add_to_hierarchy() sets the init_state to loaded
3060 // before the InstanceKlass is added to the SystemDictionary. Make
3061 // sure the current state is <loaded.
3062 assert(!is_loaded(), "invalid init state");
3063 assert(!shared_loading_failed(), "Must not try to load failed class again");
3064 set_package(loader_data, pkg_entry, CHECK);
3065 Klass::restore_unshareable_info(loader_data, protection_domain, CHECK);
3066
3067 if (is_inline_klass()) {
3068 InlineKlass::cast(this)->initialize_calling_convention(CHECK);
3069 }
3070
3071 Array<Method*>* methods = this->methods();
3072 int num_methods = methods->length();
3073 for (int index = 0; index < num_methods; ++index) {
3074 methods->at(index)->restore_unshareable_info(CHECK);
3075 }
3076 #if INCLUDE_JVMTI
3077 if (JvmtiExport::has_redefined_a_class()) {
3078 // Reinitialize vtable because RedefineClasses may have changed some
3079 // entries in this vtable for super classes so the CDS vtable might
3080 // point to old or obsolete entries. RedefineClasses doesn't fix up
3081 // vtables in the shared system dictionary, only the main one.
3082 // It also redefines the itable too so fix that too.
3083 // First fix any default methods that point to a super class that may
3084 // have been redefined.
3085 bool trace_name_printed = false;
3086 adjust_default_methods(&trace_name_printed);
3087 if (verified_at_dump_time()) {
3088 // Initialize vtable and itable for classes which can be verified at dump time.
3089 // Unlinked classes such as old classes with major version < 50 cannot be verified
3090 // at dump time.
3091 vtable().initialize_vtable();
3092 itable().initialize_itable();
3093 }
3094 }
3095 #endif // INCLUDE_JVMTI
3096
3097 // restore constant pool resolved references
3098 constants()->restore_unshareable_info(CHECK);
3099
3100 if (array_klasses() != nullptr) {
3101 // To get a consistent list of classes we need MultiArray_lock to ensure
3102 // array classes aren't observed while they are being restored.
3103 RecursiveLocker rl(MultiArray_lock, THREAD);
3104 assert(this == ObjArrayKlass::cast(array_klasses())->bottom_klass(), "sanity");
3105 // Array classes have null protection domain.
3106 // --> see ArrayKlass::complete_create_array_klass()
3107 array_klasses()->restore_unshareable_info(class_loader_data(), Handle(), CHECK);
3108 }
3109
3110 // Initialize @ValueBased class annotation if not already set in the archived klass.
3111 if (DiagnoseSyncOnValueBasedClasses && has_value_based_class_annotation() && !is_value_based()) {
3112 set_is_value_based();
3113 }
3114 }
3115
3116 // Check if a class or any of its supertypes has a version older than 50.
3117 // CDS will not perform verification of old classes during dump time because
3118 // without changing the old verifier, the verification constraint cannot be
3119 // retrieved during dump time.
3120 // Verification of archived old classes will be performed during run time.
3121 bool InstanceKlass::can_be_verified_at_dumptime() const {
3122 if (MetaspaceShared::is_in_shared_metaspace(this)) {
3123 // This is a class that was dumped into the base archive, so we know
3124 // it was verified at dump time.
3281 } else {
3282 // Adding one to the attribute length in order to store a null terminator
3283 // character could cause an overflow because the attribute length is
3284 // already coded with an u4 in the classfile, but in practice, it's
3285 // unlikely to happen.
3286 assert((length+1) > length, "Overflow checking");
3287 char* sde = NEW_C_HEAP_ARRAY(char, (length + 1), mtClass);
3288 for (int i = 0; i < length; i++) {
3289 sde[i] = array[i];
3290 }
3291 sde[length] = '\0';
3292 _source_debug_extension = sde;
3293 }
3294 }
3295
3296 Symbol* InstanceKlass::generic_signature() const { return _constants->generic_signature(); }
3297 u2 InstanceKlass::generic_signature_index() const { return _constants->generic_signature_index(); }
3298 void InstanceKlass::set_generic_signature_index(u2 sig_index) { _constants->set_generic_signature_index(sig_index); }
3299
3300 const char* InstanceKlass::signature_name() const {
3301 return signature_name_of_carrier(JVM_SIGNATURE_CLASS);
3302 }
3303
3304 const char* InstanceKlass::signature_name_of_carrier(char c) const {
3305 // Get the internal name as a c string
3306 const char* src = (const char*) (name()->as_C_string());
3307 const int src_length = (int)strlen(src);
3308
3309 char* dest = NEW_RESOURCE_ARRAY(char, src_length + 3);
3310
3311 // Add L or Q as type indicator
3312 int dest_index = 0;
3313 dest[dest_index++] = c;
3314
3315 // Add the actual class name
3316 for (int src_index = 0; src_index < src_length; ) {
3317 dest[dest_index++] = src[src_index++];
3318 }
3319
3320 if (is_hidden()) { // Replace the last '+' with a '.'.
3321 for (int index = (int)src_length; index > 0; index--) {
3322 if (dest[index] == '+') {
3323 dest[index] = JVM_SIGNATURE_DOT;
3324 break;
3325 }
3326 }
3327 }
3328
3329 // Add the semicolon and the null
3330 dest[dest_index++] = JVM_SIGNATURE_ENDCLASS;
3331 dest[dest_index] = '\0';
3332 return dest;
3333 }
3640 u2 InstanceKlass::compute_modifier_flags() const {
3641 u2 access = access_flags().as_unsigned_short();
3642
3643 // But check if it happens to be member class.
3644 InnerClassesIterator iter(this);
3645 for (; !iter.done(); iter.next()) {
3646 int ioff = iter.inner_class_info_index();
3647 // Inner class attribute can be zero, skip it.
3648 // Strange but true: JVM spec. allows null inner class refs.
3649 if (ioff == 0) continue;
3650
3651 // only look at classes that are already loaded
3652 // since we are looking for the flags for our self.
3653 Symbol* inner_name = constants()->klass_name_at(ioff);
3654 if (name() == inner_name) {
3655 // This is really a member class.
3656 access = iter.inner_access_flags();
3657 break;
3658 }
3659 }
3660 return access;
3661 }
3662
3663 jint InstanceKlass::jvmti_class_status() const {
3664 jint result = 0;
3665
3666 if (is_linked()) {
3667 result |= JVMTI_CLASS_STATUS_VERIFIED | JVMTI_CLASS_STATUS_PREPARED;
3668 }
3669
3670 if (is_initialized()) {
3671 assert(is_linked(), "Class status is not consistent");
3672 result |= JVMTI_CLASS_STATUS_INITIALIZED;
3673 }
3674 if (is_in_error_state()) {
3675 result |= JVMTI_CLASS_STATUS_ERROR;
3676 }
3677 return result;
3678 }
3679
3680 Method* InstanceKlass::method_at_itable(InstanceKlass* holder, int index, TRAPS) {
3894 }
3895 osr = osr->osr_link();
3896 }
3897
3898 assert(match_level == false || best == nullptr, "shouldn't pick up anything if match_level is set");
3899 if (best != nullptr && best->comp_level() >= comp_level) {
3900 return best;
3901 }
3902 return nullptr;
3903 }
3904
3905 // -----------------------------------------------------------------------------------------------------
3906 // Printing
3907
3908 #define BULLET " - "
3909
3910 static const char* state_names[] = {
3911 "allocated", "loaded", "linked", "being_initialized", "fully_initialized", "initialization_error"
3912 };
3913
3914 static void print_vtable(address self, intptr_t* start, int len, outputStream* st) {
3915 ResourceMark rm;
3916 int* forward_refs = NEW_RESOURCE_ARRAY(int, len);
3917 for (int i = 0; i < len; i++) forward_refs[i] = 0;
3918 for (int i = 0; i < len; i++) {
3919 intptr_t e = start[i];
3920 st->print("%d : " INTPTR_FORMAT, i, e);
3921 if (forward_refs[i] != 0) {
3922 int from = forward_refs[i];
3923 int off = (int) start[from];
3924 st->print(" (offset %d <= [%d])", off, from);
3925 }
3926 if (MetaspaceObj::is_valid((Metadata*)e)) {
3927 st->print(" ");
3928 ((Metadata*)e)->print_value_on(st);
3929 } else if (self != nullptr && e > 0 && e < 0x10000) {
3930 address location = self + e;
3931 int index = (int)((intptr_t*)location - start);
3932 st->print(" (offset %d => [%d])", (int)e, index);
3933 if (index >= 0 && index < len)
3934 forward_refs[index] = i;
3935 }
3936 st->cr();
3937 }
3938 }
3939
3940 static void print_vtable(vtableEntry* start, int len, outputStream* st) {
3941 return print_vtable(nullptr, reinterpret_cast<intptr_t*>(start), len, st);
3942 }
3943
3944 template<typename T>
3945 static void print_array_on(outputStream* st, Array<T>* array) {
3946 if (array == nullptr) { st->print_cr("nullptr"); return; }
3947 array->print_value_on(st); st->cr();
3948 if (Verbose || WizardMode) {
3949 for (int i = 0; i < array->length(); i++) {
3950 st->print("%d : ", i); array->at(i)->print_value_on(st); st->cr();
3951 }
3952 }
3953 }
3954
3955 static void print_array_on(outputStream* st, Array<int>* array) {
3956 if (array == nullptr) { st->print_cr("nullptr"); return; }
3957 array->print_value_on(st); st->cr();
3958 if (Verbose || WizardMode) {
3959 for (int i = 0; i < array->length(); i++) {
3960 st->print("%d : %d", i, array->at(i)); st->cr();
3961 }
3962 }
3963 }
3964
3965 const char* InstanceKlass::init_state_name() const {
3966 return state_names[init_state()];
3967 }
3968
3969 void InstanceKlass::print_on(outputStream* st) const {
3970 assert(is_klass(), "must be klass");
3971 Klass::print_on(st);
3972
3973 st->print(BULLET"instance size: %d", size_helper()); st->cr();
3974 st->print(BULLET"klass size: %d", size()); st->cr();
3975 st->print(BULLET"access: "); access_flags().print_on(st); st->cr();
3976 st->print(BULLET"flags: "); _misc_flags.print_on(st); st->cr();
3977 st->print(BULLET"state: "); st->print_cr("%s", init_state_name());
3978 st->print(BULLET"name: "); name()->print_value_on(st); st->cr();
3979 st->print(BULLET"super: "); Metadata::print_value_on_maybe_null(st, super()); st->cr();
3980 st->print(BULLET"sub: ");
3981 Klass* sub = subklass();
3982 int n;
3983 for (n = 0; sub != nullptr; n++, sub = sub->next_sibling()) {
3984 if (n < MaxSubklassPrintSize) {
3985 sub->print_value_on(st);
3986 st->print(" ");
3987 }
3988 }
3989 if (n >= MaxSubklassPrintSize) st->print("(%zd more klasses...)", n - MaxSubklassPrintSize);
3990 st->cr();
3991
3992 if (is_interface()) {
3993 st->print_cr(BULLET"nof implementors: %d", nof_implementors());
3994 if (nof_implementors() == 1) {
3995 st->print_cr(BULLET"implementor: ");
3996 st->print(" ");
3997 implementor()->print_value_on(st);
3998 st->cr();
3999 }
4000 }
4001
4002 st->print(BULLET"arrays: "); Metadata::print_value_on_maybe_null(st, array_klasses()); st->cr();
4003 st->print(BULLET"methods: "); print_array_on(st, methods());
4004 st->print(BULLET"method ordering: "); print_array_on(st, method_ordering());
4005 if (default_methods() != nullptr) {
4006 st->print(BULLET"default_methods: "); print_array_on(st, default_methods());
4007 }
4008 print_on_maybe_null(st, BULLET"default vtable indices: ", default_vtable_indices());
4009 st->print(BULLET"local interfaces: "); local_interfaces()->print_value_on(st); st->cr();
4010 st->print(BULLET"trans. interfaces: "); transitive_interfaces()->print_value_on(st); st->cr();
4011
4012 st->print(BULLET"secondary supers: "); secondary_supers()->print_value_on(st); st->cr();
4013
4014 st->print(BULLET"hash_slot: %d", hash_slot()); st->cr();
4015 st->print(BULLET"secondary bitmap: " UINTX_FORMAT_X_0, _secondary_supers_bitmap); st->cr();
4016
4017 if (secondary_supers() != nullptr) {
4018 if (Verbose) {
4019 bool is_hashed = (_secondary_supers_bitmap != SECONDARY_SUPERS_BITMAP_FULL);
4020 st->print_cr(BULLET"---- secondary supers (%d words):", _secondary_supers->length());
4021 for (int i = 0; i < _secondary_supers->length(); i++) {
4022 ResourceMark rm; // for external_name()
4023 Klass* secondary_super = _secondary_supers->at(i);
4024 st->print(BULLET"%2d:", i);
4025 if (is_hashed) {
4026 int home_slot = compute_home_slot(secondary_super, _secondary_supers_bitmap);
4046 print_on_maybe_null(st, BULLET"field type annotations: ", fields_type_annotations());
4047 {
4048 bool have_pv = false;
4049 // previous versions are linked together through the InstanceKlass
4050 for (InstanceKlass* pv_node = previous_versions();
4051 pv_node != nullptr;
4052 pv_node = pv_node->previous_versions()) {
4053 if (!have_pv)
4054 st->print(BULLET"previous version: ");
4055 have_pv = true;
4056 pv_node->constants()->print_value_on(st);
4057 }
4058 if (have_pv) st->cr();
4059 }
4060
4061 print_on_maybe_null(st, BULLET"generic signature: ", generic_signature());
4062 st->print(BULLET"inner classes: "); inner_classes()->print_value_on(st); st->cr();
4063 st->print(BULLET"nest members: "); nest_members()->print_value_on(st); st->cr();
4064 print_on_maybe_null(st, BULLET"record components: ", record_components());
4065 st->print(BULLET"permitted subclasses: "); permitted_subclasses()->print_value_on(st); st->cr();
4066 st->print(BULLET"loadable descriptors: "); loadable_descriptors()->print_value_on(st); st->cr();
4067 if (java_mirror() != nullptr) {
4068 st->print(BULLET"java mirror: ");
4069 java_mirror()->print_value_on(st);
4070 st->cr();
4071 } else {
4072 st->print_cr(BULLET"java mirror: null");
4073 }
4074 st->print(BULLET"vtable length %d (start addr: " PTR_FORMAT ")", vtable_length(), p2i(start_of_vtable())); st->cr();
4075 if (vtable_length() > 0 && (Verbose || WizardMode)) print_vtable(start_of_vtable(), vtable_length(), st);
4076 st->print(BULLET"itable length %d (start addr: " PTR_FORMAT ")", itable_length(), p2i(start_of_itable())); st->cr();
4077 if (itable_length() > 0 && (Verbose || WizardMode)) print_vtable(nullptr, start_of_itable(), itable_length(), st);
4078 st->print_cr(BULLET"---- static fields (%d words):", static_field_size());
4079
4080 FieldPrinter print_static_field(st);
4081 ((InstanceKlass*)this)->do_local_static_fields(&print_static_field);
4082 st->print_cr(BULLET"---- non-static fields (%d words):", nonstatic_field_size());
4083 FieldPrinter print_nonstatic_field(st);
4084 InstanceKlass* ik = const_cast<InstanceKlass*>(this);
4085 ik->print_nonstatic_fields(&print_nonstatic_field);
4086
4087 st->print(BULLET"non-static oop maps (%d entries): ", nonstatic_oop_map_count());
4088 OopMapBlock* map = start_of_nonstatic_oop_maps();
4089 OopMapBlock* end_map = map + nonstatic_oop_map_count();
4090 while (map < end_map) {
4091 st->print("%d-%d ", map->offset(), map->offset() + heapOopSize*(map->count() - 1));
4092 map++;
4093 }
4094 st->cr();
4095 }
4096
4097 void InstanceKlass::print_value_on(outputStream* st) const {
4098 assert(is_klass(), "must be klass");
4099 if (Verbose || WizardMode) access_flags().print_on(st);
4100 name()->print_value_on(st);
4101 }
4102
4103 void FieldPrinter::do_field(fieldDescriptor* fd) {
4104 for (int i = 0; i < _indent; i++) _st->print(" ");
4105 _st->print(BULLET);
4106 if (_obj == nullptr) {
4107 fd->print_on(_st, _base_offset);
4108 _st->cr();
4109 } else {
4110 fd->print_on_for(_st, _obj, _indent, _base_offset);
4111 if (!fd->field_flags().is_flat()) _st->cr();
4112 }
4113 }
4114
4115
4116 void InstanceKlass::oop_print_on(oop obj, outputStream* st, int indent, int base_offset) {
4117 Klass::oop_print_on(obj, st);
4118
4119 if (this == vmClasses::String_klass()) {
4120 typeArrayOop value = java_lang_String::value(obj);
4121 juint length = java_lang_String::length(obj);
4122 if (value != nullptr &&
4123 value->is_typeArray() &&
4124 length <= (juint) value->length()) {
4125 st->print(BULLET"string: ");
4126 java_lang_String::print(obj, st);
4127 st->cr();
4128 }
4129 }
4130
4131 st->print_cr(BULLET"---- fields (total size %zu words):", oop_size(obj));
4132 FieldPrinter print_field(st, obj, indent, base_offset);
4133 print_nonstatic_fields(&print_field);
4134
4135 if (this == vmClasses::Class_klass()) {
4136 st->print(BULLET"signature: ");
4137 java_lang_Class::print_signature(obj, st);
4138 st->cr();
4139 Klass* real_klass = java_lang_Class::as_Klass(obj);
4140 if (real_klass != nullptr && real_klass->is_instance_klass()) {
4141 st->print_cr(BULLET"---- static fields (%d):", java_lang_Class::static_oop_field_count(obj));
4142 InstanceKlass::cast(real_klass)->do_local_static_fields(&print_field);
4143 }
4144 } else if (this == vmClasses::MethodType_klass()) {
4145 st->print(BULLET"signature: ");
4146 java_lang_invoke_MethodType::print_signature(obj, st);
4147 st->cr();
4148 }
4149 }
4150
4151 #ifndef PRODUCT
4152
|