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 }
947 vmSymbols::java_lang_IncompatibleClassChangeError(),
948 "class %s has interface %s as super class",
949 external_name(),
950 super_klass->external_name()
951 );
952 return false;
953 }
954
955 InstanceKlass* ik_super = InstanceKlass::cast(super_klass);
956 ik_super->link_class_impl(CHECK_false);
957 }
958
959 // link all interfaces implemented by this class before linking this class
960 Array<InstanceKlass*>* interfaces = local_interfaces();
961 int num_interfaces = interfaces->length();
962 for (int index = 0; index < num_interfaces; index++) {
963 InstanceKlass* interk = interfaces->at(index);
964 interk->link_class_impl(CHECK_false);
965 }
966
967 // in case the class is linked in the process of linking its superclasses
968 if (is_linked()) {
969 return true;
970 }
971
972 // trace only the link time for this klass that includes
973 // the verification time
974 PerfClassTraceTime vmtimer(ClassLoader::perf_class_link_time(),
975 ClassLoader::perf_class_link_selftime(),
976 ClassLoader::perf_classes_linked(),
977 jt->get_thread_stat()->perf_recursion_counts_addr(),
978 jt->get_thread_stat()->perf_timers_addr(),
979 PerfClassTraceTime::CLASS_LINK);
980
981 // verification & rewriting
982 {
983 HandleMark hm(THREAD);
984 Handle h_init_lock(THREAD, init_lock());
985 ObjectLocker ol(h_init_lock, jt);
986 // rewritten will have been set if loader constraint error found
1251 ss.print("Could not initialize class %s", external_name());
1252 if (cause.is_null()) {
1253 THROW_MSG(vmSymbols::java_lang_NoClassDefFoundError(), ss.as_string());
1254 } else {
1255 THROW_MSG_CAUSE(vmSymbols::java_lang_NoClassDefFoundError(),
1256 ss.as_string(), cause);
1257 }
1258 } else {
1259
1260 // Step 6
1261 set_init_state(being_initialized);
1262 set_init_thread(jt);
1263 if (debug_logging_enabled) {
1264 ResourceMark rm(jt);
1265 log_debug(class, init)("Thread \"%s\" is initializing %s",
1266 jt->name(), external_name());
1267 }
1268 }
1269 }
1270
1271 // Step 7
1272 // Next, if C is a class rather than an interface, initialize it's super class and super
1273 // interfaces.
1274 if (!is_interface()) {
1275 Klass* super_klass = super();
1276 if (super_klass != nullptr && super_klass->should_be_initialized()) {
1277 super_klass->initialize(THREAD);
1278 }
1279 // If C implements any interface that declares a non-static, concrete method,
1280 // the initialization of C triggers initialization of its super interfaces.
1281 // Only need to recurse if has_nonstatic_concrete_methods which includes declaring and
1282 // having a superinterface that declares, non-static, concrete methods
1283 if (!HAS_PENDING_EXCEPTION && has_nonstatic_concrete_methods()) {
1284 initialize_super_interfaces(THREAD);
1285 }
1286
1287 // If any exceptions, complete abruptly, throwing the same exception as above.
1288 if (HAS_PENDING_EXCEPTION) {
1289 Handle e(THREAD, PENDING_EXCEPTION);
1290 CLEAR_PENDING_EXCEPTION;
1291 {
1292 EXCEPTION_MARK;
1293 add_initialization_error(THREAD, e);
1294 // Locks object, set state, and notify all waiting threads
1295 set_initialization_state_and_notify(initialization_error, THREAD);
1296 CLEAR_PENDING_EXCEPTION;
1297 }
1298 DTRACE_CLASSINIT_PROBE_WAIT(super__failed, -1, wait);
1299 THROW_OOP(e());
1300 }
1301 }
1302
1303
1304 // Step 8
1305 {
1306 DTRACE_CLASSINIT_PROBE_WAIT(clinit, -1, wait);
1307 if (class_initializer() != nullptr) {
1308 // Timer includes any side effects of class initialization (resolution,
1309 // etc), but not recursive entry into call_class_initializer().
1310 PerfClassTraceTime timer(ClassLoader::perf_class_init_time(),
1311 ClassLoader::perf_class_init_selftime(),
1312 ClassLoader::perf_classes_inited(),
1313 jt->get_thread_stat()->perf_recursion_counts_addr(),
1314 jt->get_thread_stat()->perf_timers_addr(),
1315 PerfClassTraceTime::CLASS_CLINIT);
1316 call_class_initializer(THREAD);
1317 } else {
1318 // The elapsed time is so small it's not worth counting.
1319 if (UsePerfData) {
1320 ClassLoader::perf_classes_inited()->inc();
1321 }
1322 call_class_initializer(THREAD);
1323 }
1324 }
1325
1326 // Step 9
1327 if (!HAS_PENDING_EXCEPTION) {
1328 set_initialization_state_and_notify(fully_initialized, CHECK);
1329 DEBUG_ONLY(vtable().verify(tty, true);)
1330 }
1331 else {
1332 // Step 10 and 11
1333 Handle e(THREAD, PENDING_EXCEPTION);
1334 CLEAR_PENDING_EXCEPTION;
1335 // JVMTI has already reported the pending exception
1336 // JVMTI internal flag reset is needed in order to report ExceptionInInitializerError
1337 JvmtiExport::clear_detected_exception(jt);
1338 {
1339 EXCEPTION_MARK;
1340 add_initialization_error(THREAD, e);
1341 set_initialization_state_and_notify(initialization_error, THREAD);
1342 CLEAR_PENDING_EXCEPTION; // ignore any exception thrown, class initialization error is thrown below
1343 // JVMTI has already reported the pending exception
1356 }
1357 DTRACE_CLASSINIT_PROBE_WAIT(end, -1, wait);
1358 }
1359
1360
1361 void InstanceKlass::set_initialization_state_and_notify(ClassState state, TRAPS) {
1362 Handle h_init_lock(THREAD, init_lock());
1363 if (h_init_lock() != nullptr) {
1364 ObjectLocker ol(h_init_lock, THREAD);
1365 set_init_thread(nullptr); // reset _init_thread before changing _init_state
1366 set_init_state(state);
1367 fence_and_clear_init_lock();
1368 ol.notify_all(CHECK);
1369 } else {
1370 assert(h_init_lock() != nullptr, "The initialization state should never be set twice");
1371 set_init_thread(nullptr); // reset _init_thread before changing _init_state
1372 set_init_state(state);
1373 }
1374 }
1375
1376 // Update hierarchy. This is done before the new klass has been added to the SystemDictionary. The Compile_lock
1377 // is grabbed, to ensure that the compiler is not using the class hierarchy.
1378 void InstanceKlass::add_to_hierarchy(JavaThread* current) {
1379 assert(!SafepointSynchronize::is_at_safepoint(), "must NOT be at safepoint");
1380
1381 DeoptimizationScope deopt_scope;
1382 {
1383 MutexLocker ml(current, Compile_lock);
1384
1385 set_init_state(InstanceKlass::loaded);
1386 // make sure init_state store is already done.
1387 // The compiler reads the hierarchy outside of the Compile_lock.
1388 // Access ordering is used to add to hierarchy.
1389
1390 // Link into hierarchy.
1391 append_to_sibling_list(); // add to superklass/sibling list
1392 process_interfaces(); // handle all "implements" declarations
1393
1394 // Now mark all code that depended on old class hierarchy.
1395 // Note: must be done *after* linking k into the hierarchy (was bug 12/9/97)
1608 ResourceMark rm(THREAD);
1609 THROW_MSG(throwError ? vmSymbols::java_lang_InstantiationError()
1610 : vmSymbols::java_lang_InstantiationException(), external_name());
1611 }
1612 if (this == vmClasses::Class_klass()) {
1613 ResourceMark rm(THREAD);
1614 THROW_MSG(throwError ? vmSymbols::java_lang_IllegalAccessError()
1615 : vmSymbols::java_lang_IllegalAccessException(), external_name());
1616 }
1617 }
1618
1619 ArrayKlass* InstanceKlass::array_klass(int n, TRAPS) {
1620 // Need load-acquire for lock-free read
1621 if (array_klasses_acquire() == nullptr) {
1622
1623 // Recursively lock array allocation
1624 RecursiveLocker rl(MultiArray_lock, THREAD);
1625
1626 // Check if another thread created the array klass while we were waiting for the lock.
1627 if (array_klasses() == nullptr) {
1628 ObjArrayKlass* k = ObjArrayKlass::allocate_objArray_klass(class_loader_data(), 1, this, CHECK_NULL);
1629 // use 'release' to pair with lock-free load
1630 release_set_array_klasses(k);
1631 }
1632 }
1633
1634 // array_klasses() will always be set at this point
1635 ObjArrayKlass* ak = array_klasses();
1636 assert(ak != nullptr, "should be set");
1637 return ak->array_klass(n, THREAD);
1638 }
1639
1640 ArrayKlass* InstanceKlass::array_klass_or_null(int n) {
1641 // Need load-acquire for lock-free read
1642 ObjArrayKlass* oak = array_klasses_acquire();
1643 if (oak == nullptr) {
1644 return nullptr;
1645 } else {
1646 return oak->array_klass_or_null(n);
1647 }
1648 }
1649
1650 ArrayKlass* InstanceKlass::array_klass(TRAPS) {
1651 return array_klass(1, THREAD);
1652 }
1653
1654 ArrayKlass* InstanceKlass::array_klass_or_null() {
1655 return array_klass_or_null(1);
1656 }
1657
1658 static int call_class_initializer_counter = 0; // for debugging
1659
1660 Method* InstanceKlass::class_initializer() const {
1661 Method* clinit = find_method(
1662 vmSymbols::class_initializer_name(), vmSymbols::void_method_signature());
1663 if (clinit != nullptr && clinit->has_valid_initializer_flags()) {
1664 return clinit;
1665 }
1666 return nullptr;
1667 }
1668
1669 void InstanceKlass::call_class_initializer(TRAPS) {
1670 if (ReplayCompiles &&
1671 (ReplaySuppressInitializers == 1 ||
1672 (ReplaySuppressInitializers >= 2 && class_loader() != nullptr))) {
1673 // Hide the existence of the initializer for the purpose of replaying the compile
1674 return;
1675 }
1676
1677 #if INCLUDE_CDS
1678 // This is needed to ensure the consistency of the archived heap objects.
1679 if (has_aot_initialized_mirror() && CDSConfig::is_loading_heap()) {
1680 AOTClassInitializer::call_runtime_setup(THREAD, this);
1681 return;
1682 } else if (has_archived_enum_objs()) {
1683 assert(is_shared(), "must be");
1752
1753 void InstanceKlass::mask_for(const methodHandle& method, int bci,
1754 InterpreterOopMap* entry_for) {
1755 // Lazily create the _oop_map_cache at first request.
1756 // Load_acquire is needed to safely get instance published with CAS by another thread.
1757 OopMapCache* oop_map_cache = Atomic::load_acquire(&_oop_map_cache);
1758 if (oop_map_cache == nullptr) {
1759 // Try to install new instance atomically.
1760 oop_map_cache = new OopMapCache();
1761 OopMapCache* other = Atomic::cmpxchg(&_oop_map_cache, (OopMapCache*)nullptr, oop_map_cache);
1762 if (other != nullptr) {
1763 // Someone else managed to install before us, ditch local copy and use the existing one.
1764 delete oop_map_cache;
1765 oop_map_cache = other;
1766 }
1767 }
1768 // _oop_map_cache is constant after init; lookup below does its own locking.
1769 oop_map_cache->lookup(method, bci, entry_for);
1770 }
1771
1772 bool InstanceKlass::contains_field_offset(int offset) {
1773 fieldDescriptor fd;
1774 return find_field_from_offset(offset, false, &fd);
1775 }
1776
1777 FieldInfo InstanceKlass::field(int index) const {
1778 for (AllFieldStream fs(this); !fs.done(); fs.next()) {
1779 if (fs.index() == index) {
1780 return fs.to_FieldInfo();
1781 }
1782 }
1783 fatal("Field not found");
1784 return FieldInfo();
1785 }
1786
1787 bool InstanceKlass::find_local_field(Symbol* name, Symbol* sig, fieldDescriptor* fd) const {
1788 for (JavaFieldStream fs(this); !fs.done(); fs.next()) {
1789 Symbol* f_name = fs.name();
1790 Symbol* f_sig = fs.signature();
1791 if (f_name == name && f_sig == sig) {
1792 fd->reinitialize(const_cast<InstanceKlass*>(this), fs.to_FieldInfo());
1793 return true;
1794 }
1795 }
1837
1838 Klass* InstanceKlass::find_field(Symbol* name, Symbol* sig, bool is_static, fieldDescriptor* fd) const {
1839 // search order according to newest JVM spec (5.4.3.2, p.167).
1840 // 1) search for field in current klass
1841 if (find_local_field(name, sig, fd)) {
1842 if (fd->is_static() == is_static) return const_cast<InstanceKlass*>(this);
1843 }
1844 // 2) search for field recursively in direct superinterfaces
1845 if (is_static) {
1846 Klass* intf = find_interface_field(name, sig, fd);
1847 if (intf != nullptr) return intf;
1848 }
1849 // 3) apply field lookup recursively if superclass exists
1850 { Klass* supr = super();
1851 if (supr != nullptr) return InstanceKlass::cast(supr)->find_field(name, sig, is_static, fd);
1852 }
1853 // 4) otherwise field lookup fails
1854 return nullptr;
1855 }
1856
1857
1858 bool InstanceKlass::find_local_field_from_offset(int offset, bool is_static, fieldDescriptor* fd) const {
1859 for (JavaFieldStream fs(this); !fs.done(); fs.next()) {
1860 if (fs.offset() == offset) {
1861 fd->reinitialize(const_cast<InstanceKlass*>(this), fs.to_FieldInfo());
1862 if (fd->is_static() == is_static) return true;
1863 }
1864 }
1865 return false;
1866 }
1867
1868
1869 bool InstanceKlass::find_field_from_offset(int offset, bool is_static, fieldDescriptor* fd) const {
1870 Klass* klass = const_cast<InstanceKlass*>(this);
1871 while (klass != nullptr) {
1872 if (InstanceKlass::cast(klass)->find_local_field_from_offset(offset, is_static, fd)) {
1873 return true;
1874 }
1875 klass = klass->super();
1876 }
2220 }
2221
2222 // uncached_lookup_method searches both the local class methods array and all
2223 // superclasses methods arrays, skipping any overpass methods in superclasses,
2224 // and possibly skipping private methods.
2225 Method* InstanceKlass::uncached_lookup_method(const Symbol* name,
2226 const Symbol* signature,
2227 OverpassLookupMode overpass_mode,
2228 PrivateLookupMode private_mode) const {
2229 OverpassLookupMode overpass_local_mode = overpass_mode;
2230 const Klass* klass = this;
2231 while (klass != nullptr) {
2232 Method* const method = InstanceKlass::cast(klass)->find_method_impl(name,
2233 signature,
2234 overpass_local_mode,
2235 StaticLookupMode::find,
2236 private_mode);
2237 if (method != nullptr) {
2238 return method;
2239 }
2240 klass = klass->super();
2241 overpass_local_mode = OverpassLookupMode::skip; // Always ignore overpass methods in superclasses
2242 }
2243 return nullptr;
2244 }
2245
2246 #ifdef ASSERT
2247 // search through class hierarchy and return true if this class or
2248 // one of the superclasses was redefined
2249 bool InstanceKlass::has_redefined_this_or_super() const {
2250 const Klass* klass = this;
2251 while (klass != nullptr) {
2252 if (InstanceKlass::cast(klass)->has_been_redefined()) {
2253 return true;
2254 }
2255 klass = klass->super();
2256 }
2257 return false;
2258 }
2259 #endif
2618 int itable_offset_in_words = (int)(start_of_itable() - (intptr_t*)this);
2619
2620 int nof_interfaces = (method_table_offset_in_words - itable_offset_in_words)
2621 / itableOffsetEntry::size();
2622
2623 for (int i = 0; i < nof_interfaces; i ++, ioe ++) {
2624 if (ioe->interface_klass() != nullptr) {
2625 it->push(ioe->interface_klass_addr());
2626 itableMethodEntry* ime = ioe->first_method_entry(this);
2627 int n = klassItable::method_count_for_interface(ioe->interface_klass());
2628 for (int index = 0; index < n; index ++) {
2629 it->push(ime[index].method_addr());
2630 }
2631 }
2632 }
2633 }
2634
2635 it->push(&_nest_host);
2636 it->push(&_nest_members);
2637 it->push(&_permitted_subclasses);
2638 it->push(&_record_components);
2639 }
2640
2641 #if INCLUDE_CDS
2642 void InstanceKlass::remove_unshareable_info() {
2643
2644 if (is_linked()) {
2645 assert(can_be_verified_at_dumptime(), "must be");
2646 // Remember this so we can avoid walking the hierarchy at runtime.
2647 set_verified_at_dump_time();
2648 }
2649
2650 Klass::remove_unshareable_info();
2651
2652 if (SystemDictionaryShared::has_class_failed_verification(this)) {
2653 // Classes are attempted to link during dumping and may fail,
2654 // but these classes are still in the dictionary and class list in CLD.
2655 // If the class has failed verification, there is nothing else to remove.
2656 return;
2657 }
2658
2664
2665 { // Otherwise this needs to take out the Compile_lock.
2666 assert(SafepointSynchronize::is_at_safepoint(), "only called at safepoint");
2667 init_implementor();
2668 }
2669
2670 // Call remove_unshareable_info() on other objects that belong to this class, except
2671 // for constants()->remove_unshareable_info(), which is called in a separate pass in
2672 // ArchiveBuilder::make_klasses_shareable(),
2673
2674 for (int i = 0; i < methods()->length(); i++) {
2675 Method* m = methods()->at(i);
2676 m->remove_unshareable_info();
2677 }
2678
2679 // do array classes also.
2680 if (array_klasses() != nullptr) {
2681 array_klasses()->remove_unshareable_info();
2682 }
2683
2684 // These are not allocated from metaspace. They are safe to set to null.
2685 _source_debug_extension = nullptr;
2686 _dep_context = nullptr;
2687 _osr_nmethods_head = nullptr;
2688 #if INCLUDE_JVMTI
2689 _breakpoints = nullptr;
2690 _previous_versions = nullptr;
2691 _cached_class_file = nullptr;
2692 _jvmti_cached_class_field_map = nullptr;
2693 #endif
2694
2695 _init_thread = nullptr;
2696 _methods_jmethod_ids = nullptr;
2697 _jni_ids = nullptr;
2698 _oop_map_cache = nullptr;
2699 if (CDSConfig::is_dumping_method_handles() && HeapShared::is_lambda_proxy_klass(this)) {
2700 // keep _nest_host
2701 } else {
2702 // clear _nest_host to ensure re-load at runtime
2703 _nest_host = nullptr;
2704 }
2753 void InstanceKlass::compute_has_loops_flag_for_methods() {
2754 Array<Method*>* methods = this->methods();
2755 for (int index = 0; index < methods->length(); ++index) {
2756 Method* m = methods->at(index);
2757 if (!m->is_overpass()) { // work around JDK-8305771
2758 m->compute_has_loops_flag();
2759 }
2760 }
2761 }
2762
2763 void InstanceKlass::restore_unshareable_info(ClassLoaderData* loader_data, Handle protection_domain,
2764 PackageEntry* pkg_entry, TRAPS) {
2765 // InstanceKlass::add_to_hierarchy() sets the init_state to loaded
2766 // before the InstanceKlass is added to the SystemDictionary. Make
2767 // sure the current state is <loaded.
2768 assert(!is_loaded(), "invalid init state");
2769 assert(!shared_loading_failed(), "Must not try to load failed class again");
2770 set_package(loader_data, pkg_entry, CHECK);
2771 Klass::restore_unshareable_info(loader_data, protection_domain, CHECK);
2772
2773 Array<Method*>* methods = this->methods();
2774 int num_methods = methods->length();
2775 for (int index = 0; index < num_methods; ++index) {
2776 methods->at(index)->restore_unshareable_info(CHECK);
2777 }
2778 #if INCLUDE_JVMTI
2779 if (JvmtiExport::has_redefined_a_class()) {
2780 // Reinitialize vtable because RedefineClasses may have changed some
2781 // entries in this vtable for super classes so the CDS vtable might
2782 // point to old or obsolete entries. RedefineClasses doesn't fix up
2783 // vtables in the shared system dictionary, only the main one.
2784 // It also redefines the itable too so fix that too.
2785 // First fix any default methods that point to a super class that may
2786 // have been redefined.
2787 bool trace_name_printed = false;
2788 adjust_default_methods(&trace_name_printed);
2789 if (verified_at_dump_time()) {
2790 // Initialize vtable and itable for classes which can be verified at dump time.
2791 // Unlinked classes such as old classes with major version < 50 cannot be verified
2792 // at dump time.
2793 vtable().initialize_vtable();
2794 itable().initialize_itable();
2795 }
2796 }
2797 #endif // INCLUDE_JVMTI
2798
2799 // restore constant pool resolved references
2800 constants()->restore_unshareable_info(CHECK);
2801
2802 if (array_klasses() != nullptr) {
2803 // To get a consistent list of classes we need MultiArray_lock to ensure
2804 // array classes aren't observed while they are being restored.
2805 RecursiveLocker rl(MultiArray_lock, THREAD);
2806 assert(this == array_klasses()->bottom_klass(), "sanity");
2807 // Array classes have null protection domain.
2808 // --> see ArrayKlass::complete_create_array_klass()
2809 array_klasses()->restore_unshareable_info(class_loader_data(), Handle(), CHECK);
2810 }
2811
2812 // Initialize @ValueBased class annotation if not already set in the archived klass.
2813 if (DiagnoseSyncOnValueBasedClasses && has_value_based_class_annotation() && !is_value_based()) {
2814 set_is_value_based();
2815 }
2816 }
2817
2818 // Check if a class or any of its supertypes has a version older than 50.
2819 // CDS will not perform verification of old classes during dump time because
2820 // without changing the old verifier, the verification constraint cannot be
2821 // retrieved during dump time.
2822 // Verification of archived old classes will be performed during run time.
2823 bool InstanceKlass::can_be_verified_at_dumptime() const {
2824 if (MetaspaceShared::is_in_shared_metaspace(this)) {
2825 // This is a class that was dumped into the base archive, so we know
2826 // it was verified at dump time.
2972 } else {
2973 // Adding one to the attribute length in order to store a null terminator
2974 // character could cause an overflow because the attribute length is
2975 // already coded with an u4 in the classfile, but in practice, it's
2976 // unlikely to happen.
2977 assert((length+1) > length, "Overflow checking");
2978 char* sde = NEW_C_HEAP_ARRAY(char, (length + 1), mtClass);
2979 for (int i = 0; i < length; i++) {
2980 sde[i] = array[i];
2981 }
2982 sde[length] = '\0';
2983 _source_debug_extension = sde;
2984 }
2985 }
2986
2987 Symbol* InstanceKlass::generic_signature() const { return _constants->generic_signature(); }
2988 u2 InstanceKlass::generic_signature_index() const { return _constants->generic_signature_index(); }
2989 void InstanceKlass::set_generic_signature_index(u2 sig_index) { _constants->set_generic_signature_index(sig_index); }
2990
2991 const char* InstanceKlass::signature_name() const {
2992
2993 // Get the internal name as a c string
2994 const char* src = (const char*) (name()->as_C_string());
2995 const int src_length = (int)strlen(src);
2996
2997 char* dest = NEW_RESOURCE_ARRAY(char, src_length + 3);
2998
2999 // Add L as type indicator
3000 int dest_index = 0;
3001 dest[dest_index++] = JVM_SIGNATURE_CLASS;
3002
3003 // Add the actual class name
3004 for (int src_index = 0; src_index < src_length; ) {
3005 dest[dest_index++] = src[src_index++];
3006 }
3007
3008 if (is_hidden()) { // Replace the last '+' with a '.'.
3009 for (int index = (int)src_length; index > 0; index--) {
3010 if (dest[index] == '+') {
3011 dest[index] = JVM_SIGNATURE_DOT;
3012 break;
3013 }
3014 }
3015 }
3016
3017 // Add the semicolon and the null
3018 dest[dest_index++] = JVM_SIGNATURE_ENDCLASS;
3019 dest[dest_index] = '\0';
3020 return dest;
3021 }
3262 bool InstanceKlass::find_inner_classes_attr(int* ooff, int* noff, TRAPS) const {
3263 constantPoolHandle i_cp(THREAD, constants());
3264 for (InnerClassesIterator iter(this); !iter.done(); iter.next()) {
3265 int ioff = iter.inner_class_info_index();
3266 if (ioff != 0) {
3267 // Check to see if the name matches the class we're looking for
3268 // before attempting to find the class.
3269 if (i_cp->klass_name_at_matches(this, ioff)) {
3270 Klass* inner_klass = i_cp->klass_at(ioff, CHECK_false);
3271 if (this == inner_klass) {
3272 *ooff = iter.outer_class_info_index();
3273 *noff = iter.inner_name_index();
3274 return true;
3275 }
3276 }
3277 }
3278 }
3279 return false;
3280 }
3281
3282 InstanceKlass* InstanceKlass::compute_enclosing_class(bool* inner_is_member, TRAPS) const {
3283 InstanceKlass* outer_klass = nullptr;
3284 *inner_is_member = false;
3285 int ooff = 0, noff = 0;
3286 bool has_inner_classes_attr = find_inner_classes_attr(&ooff, &noff, THREAD);
3287 if (has_inner_classes_attr) {
3288 constantPoolHandle i_cp(THREAD, constants());
3289 if (ooff != 0) {
3290 Klass* ok = i_cp->klass_at(ooff, CHECK_NULL);
3291 if (!ok->is_instance_klass()) {
3292 // If the outer class is not an instance klass then it cannot have
3293 // declared any inner classes.
3294 ResourceMark rm(THREAD);
3295 // Names are all known to be < 64k so we know this formatted message is not excessively large.
3296 Exceptions::fthrow(
3297 THREAD_AND_LOCATION,
3298 vmSymbols::java_lang_IncompatibleClassChangeError(),
3299 "%s and %s disagree on InnerClasses attribute",
3300 ok->external_name(),
3301 external_name());
3328 u2 InstanceKlass::compute_modifier_flags() const {
3329 u2 access = access_flags().as_unsigned_short();
3330
3331 // But check if it happens to be member class.
3332 InnerClassesIterator iter(this);
3333 for (; !iter.done(); iter.next()) {
3334 int ioff = iter.inner_class_info_index();
3335 // Inner class attribute can be zero, skip it.
3336 // Strange but true: JVM spec. allows null inner class refs.
3337 if (ioff == 0) continue;
3338
3339 // only look at classes that are already loaded
3340 // since we are looking for the flags for our self.
3341 Symbol* inner_name = constants()->klass_name_at(ioff);
3342 if (name() == inner_name) {
3343 // This is really a member class.
3344 access = iter.inner_access_flags();
3345 break;
3346 }
3347 }
3348 // Remember to strip ACC_SUPER bit
3349 return (access & (~JVM_ACC_SUPER));
3350 }
3351
3352 jint InstanceKlass::jvmti_class_status() const {
3353 jint result = 0;
3354
3355 if (is_linked()) {
3356 result |= JVMTI_CLASS_STATUS_VERIFIED | JVMTI_CLASS_STATUS_PREPARED;
3357 }
3358
3359 if (is_initialized()) {
3360 assert(is_linked(), "Class status is not consistent");
3361 result |= JVMTI_CLASS_STATUS_INITIALIZED;
3362 }
3363 if (is_in_error_state()) {
3364 result |= JVMTI_CLASS_STATUS_ERROR;
3365 }
3366 return result;
3367 }
3368
3369 Method* InstanceKlass::method_at_itable(InstanceKlass* holder, int index, TRAPS) {
3583 }
3584 osr = osr->osr_link();
3585 }
3586
3587 assert(match_level == false || best == nullptr, "shouldn't pick up anything if match_level is set");
3588 if (best != nullptr && best->comp_level() >= comp_level) {
3589 return best;
3590 }
3591 return nullptr;
3592 }
3593
3594 // -----------------------------------------------------------------------------------------------------
3595 // Printing
3596
3597 #define BULLET " - "
3598
3599 static const char* state_names[] = {
3600 "allocated", "loaded", "linked", "being_initialized", "fully_initialized", "initialization_error"
3601 };
3602
3603 static void print_vtable(intptr_t* start, int len, outputStream* st) {
3604 for (int i = 0; i < len; i++) {
3605 intptr_t e = start[i];
3606 st->print("%d : " INTPTR_FORMAT, i, e);
3607 if (MetaspaceObj::is_valid((Metadata*)e)) {
3608 st->print(" ");
3609 ((Metadata*)e)->print_value_on(st);
3610 }
3611 st->cr();
3612 }
3613 }
3614
3615 static void print_vtable(vtableEntry* start, int len, outputStream* st) {
3616 return print_vtable(reinterpret_cast<intptr_t*>(start), len, st);
3617 }
3618
3619 const char* InstanceKlass::init_state_name() const {
3620 return state_names[init_state()];
3621 }
3622
3623 void InstanceKlass::print_on(outputStream* st) const {
3624 assert(is_klass(), "must be klass");
3625 Klass::print_on(st);
3626
3627 st->print(BULLET"instance size: %d", size_helper()); st->cr();
3628 st->print(BULLET"klass size: %d", size()); st->cr();
3629 st->print(BULLET"access: "); access_flags().print_on(st); st->cr();
3630 st->print(BULLET"flags: "); _misc_flags.print_on(st); st->cr();
3631 st->print(BULLET"state: "); st->print_cr("%s", init_state_name());
3632 st->print(BULLET"name: "); name()->print_value_on(st); st->cr();
3633 st->print(BULLET"super: "); Metadata::print_value_on_maybe_null(st, super()); st->cr();
3634 st->print(BULLET"sub: ");
3635 Klass* sub = subklass();
3636 int n;
3637 for (n = 0; sub != nullptr; n++, sub = sub->next_sibling()) {
3638 if (n < MaxSubklassPrintSize) {
3639 sub->print_value_on(st);
3640 st->print(" ");
3641 }
3642 }
3643 if (n >= MaxSubklassPrintSize) st->print("(%zd more klasses...)", n - MaxSubklassPrintSize);
3644 st->cr();
3645
3646 if (is_interface()) {
3647 st->print_cr(BULLET"nof implementors: %d", nof_implementors());
3648 if (nof_implementors() == 1) {
3649 st->print_cr(BULLET"implementor: ");
3650 st->print(" ");
3651 implementor()->print_value_on(st);
3652 st->cr();
3653 }
3654 }
3655
3656 st->print(BULLET"arrays: "); Metadata::print_value_on_maybe_null(st, array_klasses()); st->cr();
3657 st->print(BULLET"methods: "); methods()->print_value_on(st); st->cr();
3658 if (Verbose || WizardMode) {
3659 Array<Method*>* method_array = methods();
3660 for (int i = 0; i < method_array->length(); i++) {
3661 st->print("%d : ", i); method_array->at(i)->print_value(); st->cr();
3662 }
3663 }
3664 st->print(BULLET"method ordering: "); method_ordering()->print_value_on(st); st->cr();
3665 if (default_methods() != nullptr) {
3666 st->print(BULLET"default_methods: "); default_methods()->print_value_on(st); st->cr();
3667 if (Verbose) {
3668 Array<Method*>* method_array = default_methods();
3669 for (int i = 0; i < method_array->length(); i++) {
3670 st->print("%d : ", i); method_array->at(i)->print_value(); st->cr();
3671 }
3672 }
3673 }
3674 print_on_maybe_null(st, BULLET"default vtable indices: ", default_vtable_indices());
3675 st->print(BULLET"local interfaces: "); local_interfaces()->print_value_on(st); st->cr();
3676 st->print(BULLET"trans. interfaces: "); transitive_interfaces()->print_value_on(st); st->cr();
3677
3678 st->print(BULLET"secondary supers: "); secondary_supers()->print_value_on(st); st->cr();
3679
3680 st->print(BULLET"hash_slot: %d", hash_slot()); st->cr();
3681 st->print(BULLET"secondary bitmap: " UINTX_FORMAT_X_0, _secondary_supers_bitmap); st->cr();
3682
3683 if (secondary_supers() != nullptr) {
3684 if (Verbose) {
3685 bool is_hashed = (_secondary_supers_bitmap != SECONDARY_SUPERS_BITMAP_FULL);
3686 st->print_cr(BULLET"---- secondary supers (%d words):", _secondary_supers->length());
3687 for (int i = 0; i < _secondary_supers->length(); i++) {
3688 ResourceMark rm; // for external_name()
3689 Klass* secondary_super = _secondary_supers->at(i);
3690 st->print(BULLET"%2d:", i);
3691 if (is_hashed) {
3692 int home_slot = compute_home_slot(secondary_super, _secondary_supers_bitmap);
3712 print_on_maybe_null(st, BULLET"field type annotations: ", fields_type_annotations());
3713 {
3714 bool have_pv = false;
3715 // previous versions are linked together through the InstanceKlass
3716 for (InstanceKlass* pv_node = previous_versions();
3717 pv_node != nullptr;
3718 pv_node = pv_node->previous_versions()) {
3719 if (!have_pv)
3720 st->print(BULLET"previous version: ");
3721 have_pv = true;
3722 pv_node->constants()->print_value_on(st);
3723 }
3724 if (have_pv) st->cr();
3725 }
3726
3727 print_on_maybe_null(st, BULLET"generic signature: ", generic_signature());
3728 st->print(BULLET"inner classes: "); inner_classes()->print_value_on(st); st->cr();
3729 st->print(BULLET"nest members: "); nest_members()->print_value_on(st); st->cr();
3730 print_on_maybe_null(st, BULLET"record components: ", record_components());
3731 st->print(BULLET"permitted subclasses: "); permitted_subclasses()->print_value_on(st); st->cr();
3732 if (java_mirror() != nullptr) {
3733 st->print(BULLET"java mirror: ");
3734 java_mirror()->print_value_on(st);
3735 st->cr();
3736 } else {
3737 st->print_cr(BULLET"java mirror: null");
3738 }
3739 st->print(BULLET"vtable length %d (start addr: " PTR_FORMAT ")", vtable_length(), p2i(start_of_vtable())); st->cr();
3740 if (vtable_length() > 0 && (Verbose || WizardMode)) print_vtable(start_of_vtable(), vtable_length(), st);
3741 st->print(BULLET"itable length %d (start addr: " PTR_FORMAT ")", itable_length(), p2i(start_of_itable())); st->cr();
3742 if (itable_length() > 0 && (Verbose || WizardMode)) print_vtable(start_of_itable(), itable_length(), st);
3743 st->print_cr(BULLET"---- static fields (%d words):", static_field_size());
3744
3745 FieldPrinter print_static_field(st);
3746 ((InstanceKlass*)this)->do_local_static_fields(&print_static_field);
3747 st->print_cr(BULLET"---- non-static fields (%d words):", nonstatic_field_size());
3748 FieldPrinter print_nonstatic_field(st);
3749 InstanceKlass* ik = const_cast<InstanceKlass*>(this);
3750 ik->print_nonstatic_fields(&print_nonstatic_field);
3751
3752 st->print(BULLET"non-static oop maps (%d entries): ", nonstatic_oop_map_count());
3753 OopMapBlock* map = start_of_nonstatic_oop_maps();
3754 OopMapBlock* end_map = map + nonstatic_oop_map_count();
3755 while (map < end_map) {
3756 st->print("%d-%d ", map->offset(), map->offset() + heapOopSize*(map->count() - 1));
3757 map++;
3758 }
3759 st->cr();
3760 }
3761
3762 void InstanceKlass::print_value_on(outputStream* st) const {
3763 assert(is_klass(), "must be klass");
3764 if (Verbose || WizardMode) access_flags().print_on(st);
3765 name()->print_value_on(st);
3766 }
3767
3768 void FieldPrinter::do_field(fieldDescriptor* fd) {
3769 _st->print(BULLET);
3770 if (_obj == nullptr) {
3771 fd->print_on(_st);
3772 _st->cr();
3773 } else {
3774 fd->print_on_for(_st, _obj);
3775 _st->cr();
3776 }
3777 }
3778
3779
3780 void InstanceKlass::oop_print_on(oop obj, outputStream* st) {
3781 Klass::oop_print_on(obj, st);
3782
3783 if (this == vmClasses::String_klass()) {
3784 typeArrayOop value = java_lang_String::value(obj);
3785 juint length = java_lang_String::length(obj);
3786 if (value != nullptr &&
3787 value->is_typeArray() &&
3788 length <= (juint) value->length()) {
3789 st->print(BULLET"string: ");
3790 java_lang_String::print(obj, st);
3791 st->cr();
3792 }
3793 }
3794
3795 st->print_cr(BULLET"---- fields (total size %zu words):", oop_size(obj));
3796 FieldPrinter print_field(st, obj);
3797 print_nonstatic_fields(&print_field);
3798
3799 if (this == vmClasses::Class_klass()) {
3800 st->print(BULLET"signature: ");
3801 java_lang_Class::print_signature(obj, st);
3802 st->cr();
3803 Klass* real_klass = java_lang_Class::as_Klass(obj);
3804 if (real_klass != nullptr && real_klass->is_instance_klass()) {
3805 st->print_cr(BULLET"---- static fields (%d):", java_lang_Class::static_oop_field_count(obj));
3806 InstanceKlass::cast(real_klass)->do_local_static_fields(&print_field);
3807 }
3808 } else if (this == vmClasses::MethodType_klass()) {
3809 st->print(BULLET"signature: ");
3810 java_lang_invoke_MethodType::print_signature(obj, st);
3811 st->cr();
3812 }
3813 }
3814
3815 #ifndef PRODUCT
3816
|
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 }
1018 vmSymbols::java_lang_IncompatibleClassChangeError(),
1019 "class %s has interface %s as super class",
1020 external_name(),
1021 super_klass->external_name()
1022 );
1023 return false;
1024 }
1025
1026 InstanceKlass* ik_super = InstanceKlass::cast(super_klass);
1027 ik_super->link_class_impl(CHECK_false);
1028 }
1029
1030 // link all interfaces implemented by this class before linking this class
1031 Array<InstanceKlass*>* interfaces = local_interfaces();
1032 int num_interfaces = interfaces->length();
1033 for (int index = 0; index < num_interfaces; index++) {
1034 InstanceKlass* interk = interfaces->at(index);
1035 interk->link_class_impl(CHECK_false);
1036 }
1037
1038
1039 // If a class declares a method that uses an inline class as an argument
1040 // type or return inline type, this inline class must be loaded during the
1041 // linking of this class because size and properties of the inline class
1042 // must be known in order to be able to perform inline type optimizations.
1043 // The implementation below is an approximation of this rule, the code
1044 // iterates over all methods of the current class (including overridden
1045 // methods), not only the methods declared by this class. This
1046 // approximation makes the code simpler, and doesn't change the semantic
1047 // because classes declaring methods overridden by the current class are
1048 // linked (and have performed their own pre-loading) before the linking
1049 // of the current class.
1050
1051
1052 // Note:
1053 // Inline class types are loaded during
1054 // the loading phase (see ClassFileParser::post_process_parsed_stream()).
1055 // Inline class types used as element types for array creation
1056 // are not pre-loaded. Their loading is triggered by either anewarray
1057 // or multianewarray bytecodes.
1058
1059 // Could it be possible to do the following processing only if the
1060 // class uses inline types?
1061 if (EnableValhalla) {
1062 ResourceMark rm(THREAD);
1063 for (AllFieldStream fs(this); !fs.done(); fs.next()) {
1064 if (fs.is_null_free_inline_type() && fs.access_flags().is_static()) {
1065 assert(fs.access_flags().is_strict(), "null-free fields must be strict");
1066 Symbol* sig = fs.signature();
1067 TempNewSymbol s = Signature::strip_envelope(sig);
1068 if (s != name()) {
1069 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());
1070 Klass* klass = SystemDictionary::resolve_or_fail(s,
1071 Handle(THREAD, class_loader()), true,
1072 CHECK_false);
1073 if (HAS_PENDING_EXCEPTION) {
1074 log_warning(class, preload)("Preloading of class %s during linking of class %s (cause: null-free static field) failed: %s",
1075 s->as_C_string(), name()->as_C_string(), PENDING_EXCEPTION->klass()->name()->as_C_string());
1076 return false; // Exception is still pending
1077 }
1078 log_info(class, preload)("Preloading of class %s during linking of class %s (cause: null-free static field) succeeded",
1079 s->as_C_string(), name()->as_C_string());
1080 assert(klass != nullptr, "Sanity check");
1081 if (klass->is_abstract()) {
1082 THROW_MSG_(vmSymbols::java_lang_IncompatibleClassChangeError(),
1083 err_msg("Class %s expects class %s to be concrete value class, but it is an abstract class",
1084 name()->as_C_string(),
1085 InstanceKlass::cast(klass)->external_name()), false);
1086 }
1087 if (!klass->is_inline_klass()) {
1088 THROW_MSG_(vmSymbols::java_lang_IncompatibleClassChangeError(),
1089 err_msg("class %s expects class %s to be a value class but it is an identity class",
1090 name()->as_C_string(), klass->external_name()), false);
1091 }
1092 InlineKlass* vk = InlineKlass::cast(klass);
1093 // the inline_type_field_klasses_array might have been loaded with CDS, so update only if not already set and check consistency
1094 InlineLayoutInfo* li = inline_layout_info_adr(fs.index());
1095 if (li->klass() == nullptr) {
1096 li->set_klass(InlineKlass::cast(vk));
1097 li->set_kind(LayoutKind::REFERENCE);
1098 }
1099 assert(get_inline_type_field_klass(fs.index()) == vk, "Must match");
1100 } else {
1101 InlineLayoutInfo* li = inline_layout_info_adr(fs.index());
1102 if (li->klass() == nullptr) {
1103 li->set_klass(InlineKlass::cast(this));
1104 li->set_kind(LayoutKind::REFERENCE);
1105 }
1106 assert(get_inline_type_field_klass(fs.index()) == this, "Must match");
1107 }
1108 }
1109 }
1110
1111 // Aggressively preloading all classes from the LoadableDescriptors attribute
1112 if (loadable_descriptors() != nullptr) {
1113 HandleMark hm(THREAD);
1114 for (int i = 0; i < loadable_descriptors()->length(); i++) {
1115 Symbol* sig = constants()->symbol_at(loadable_descriptors()->at(i));
1116 if (!Signature::has_envelope(sig)) continue;
1117 TempNewSymbol class_name = Signature::strip_envelope(sig);
1118 if (class_name == name()) continue;
1119 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());
1120 oop loader = class_loader();
1121 Klass* klass = SystemDictionary::resolve_or_null(class_name,
1122 Handle(THREAD, loader), THREAD);
1123 if (HAS_PENDING_EXCEPTION) {
1124 CLEAR_PENDING_EXCEPTION;
1125 }
1126 if (klass != nullptr) {
1127 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());
1128 if (!klass->is_inline_klass()) {
1129 // Non value class are allowed by the current spec, but it could be an indication of an issue so let's log a warning
1130 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());
1131 }
1132 } else {
1133 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());
1134 }
1135 }
1136 }
1137 }
1138
1139 // in case the class is linked in the process of linking its superclasses
1140 if (is_linked()) {
1141 return true;
1142 }
1143
1144 // trace only the link time for this klass that includes
1145 // the verification time
1146 PerfClassTraceTime vmtimer(ClassLoader::perf_class_link_time(),
1147 ClassLoader::perf_class_link_selftime(),
1148 ClassLoader::perf_classes_linked(),
1149 jt->get_thread_stat()->perf_recursion_counts_addr(),
1150 jt->get_thread_stat()->perf_timers_addr(),
1151 PerfClassTraceTime::CLASS_LINK);
1152
1153 // verification & rewriting
1154 {
1155 HandleMark hm(THREAD);
1156 Handle h_init_lock(THREAD, init_lock());
1157 ObjectLocker ol(h_init_lock, jt);
1158 // rewritten will have been set if loader constraint error found
1423 ss.print("Could not initialize class %s", external_name());
1424 if (cause.is_null()) {
1425 THROW_MSG(vmSymbols::java_lang_NoClassDefFoundError(), ss.as_string());
1426 } else {
1427 THROW_MSG_CAUSE(vmSymbols::java_lang_NoClassDefFoundError(),
1428 ss.as_string(), cause);
1429 }
1430 } else {
1431
1432 // Step 6
1433 set_init_state(being_initialized);
1434 set_init_thread(jt);
1435 if (debug_logging_enabled) {
1436 ResourceMark rm(jt);
1437 log_debug(class, init)("Thread \"%s\" is initializing %s",
1438 jt->name(), external_name());
1439 }
1440 }
1441 }
1442
1443 // Pre-allocating an all-zero value to be used to reset nullable flat storages
1444 if (is_inline_klass()) {
1445 InlineKlass* vk = InlineKlass::cast(this);
1446 if (vk->has_nullable_atomic_layout()) {
1447 oop val = vk->allocate_instance(THREAD);
1448 if (HAS_PENDING_EXCEPTION) {
1449 Handle e(THREAD, PENDING_EXCEPTION);
1450 CLEAR_PENDING_EXCEPTION;
1451 {
1452 EXCEPTION_MARK;
1453 add_initialization_error(THREAD, e);
1454 // Locks object, set state, and notify all waiting threads
1455 set_initialization_state_and_notify(initialization_error, THREAD);
1456 CLEAR_PENDING_EXCEPTION;
1457 }
1458 THROW_OOP(e());
1459 }
1460 vk->set_null_reset_value(val);
1461 }
1462 }
1463
1464 // Step 7
1465 // Next, if C is a class rather than an interface, initialize it's super class and super
1466 // interfaces.
1467 if (!is_interface()) {
1468 Klass* super_klass = super();
1469 if (super_klass != nullptr && super_klass->should_be_initialized()) {
1470 super_klass->initialize(THREAD);
1471 }
1472 // If C implements any interface that declares a non-static, concrete method,
1473 // the initialization of C triggers initialization of its super interfaces.
1474 // Only need to recurse if has_nonstatic_concrete_methods which includes declaring and
1475 // having a superinterface that declares, non-static, concrete methods
1476 if (!HAS_PENDING_EXCEPTION && has_nonstatic_concrete_methods()) {
1477 initialize_super_interfaces(THREAD);
1478 }
1479
1480 // If any exceptions, complete abruptly, throwing the same exception as above.
1481 if (HAS_PENDING_EXCEPTION) {
1482 Handle e(THREAD, PENDING_EXCEPTION);
1483 CLEAR_PENDING_EXCEPTION;
1484 {
1485 EXCEPTION_MARK;
1486 add_initialization_error(THREAD, e);
1487 // Locks object, set state, and notify all waiting threads
1488 set_initialization_state_and_notify(initialization_error, THREAD);
1489 CLEAR_PENDING_EXCEPTION;
1490 }
1491 DTRACE_CLASSINIT_PROBE_WAIT(super__failed, -1, wait);
1492 THROW_OOP(e());
1493 }
1494 }
1495
1496 // Step 8
1497 {
1498 DTRACE_CLASSINIT_PROBE_WAIT(clinit, -1, wait);
1499 if (class_initializer() != nullptr) {
1500 // Timer includes any side effects of class initialization (resolution,
1501 // etc), but not recursive entry into call_class_initializer().
1502 PerfClassTraceTime timer(ClassLoader::perf_class_init_time(),
1503 ClassLoader::perf_class_init_selftime(),
1504 ClassLoader::perf_classes_inited(),
1505 jt->get_thread_stat()->perf_recursion_counts_addr(),
1506 jt->get_thread_stat()->perf_timers_addr(),
1507 PerfClassTraceTime::CLASS_CLINIT);
1508 call_class_initializer(THREAD);
1509 } else {
1510 // The elapsed time is so small it's not worth counting.
1511 if (UsePerfData) {
1512 ClassLoader::perf_classes_inited()->inc();
1513 }
1514 call_class_initializer(THREAD);
1515 }
1516
1517 if (has_strict_static_fields() && !HAS_PENDING_EXCEPTION) {
1518 // Step 9 also verifies that strict static fields have been initialized.
1519 // Status bits were set in ClassFileParser::post_process_parsed_stream.
1520 // After <clinit>, bits must all be clear, or else we must throw an error.
1521 // This is an extremely fast check, so we won't bother with a timer.
1522 assert(fields_status() != nullptr, "");
1523 Symbol* bad_strict_static = nullptr;
1524 for (int index = 0; index < fields_status()->length(); index++) {
1525 // Very fast loop over single byte array looking for a set bit.
1526 if (fields_status()->adr_at(index)->is_strict_static_unset()) {
1527 // This strict static field has not been set by the class initializer.
1528 // Note that in the common no-error case, we read no field metadata.
1529 // We only unpack it when we need to report an error.
1530 FieldInfo fi = field(index);
1531 bad_strict_static = fi.name(constants());
1532 if (debug_logging_enabled) {
1533 ResourceMark rm(jt);
1534 const char* msg = format_strict_static_message(bad_strict_static);
1535 log_debug(class, init)("%s", msg);
1536 } else {
1537 // If we are not logging, do not bother to look for a second offense.
1538 break;
1539 }
1540 }
1541 }
1542 if (bad_strict_static != nullptr) {
1543 throw_strict_static_exception(bad_strict_static, "is unset after initialization of", THREAD);
1544 }
1545 }
1546 }
1547
1548 // Step 9
1549 if (!HAS_PENDING_EXCEPTION) {
1550 set_initialization_state_and_notify(fully_initialized, CHECK);
1551 DEBUG_ONLY(vtable().verify(tty, true);)
1552 }
1553 else {
1554 // Step 10 and 11
1555 Handle e(THREAD, PENDING_EXCEPTION);
1556 CLEAR_PENDING_EXCEPTION;
1557 // JVMTI has already reported the pending exception
1558 // JVMTI internal flag reset is needed in order to report ExceptionInInitializerError
1559 JvmtiExport::clear_detected_exception(jt);
1560 {
1561 EXCEPTION_MARK;
1562 add_initialization_error(THREAD, e);
1563 set_initialization_state_and_notify(initialization_error, THREAD);
1564 CLEAR_PENDING_EXCEPTION; // ignore any exception thrown, class initialization error is thrown below
1565 // JVMTI has already reported the pending exception
1578 }
1579 DTRACE_CLASSINIT_PROBE_WAIT(end, -1, wait);
1580 }
1581
1582
1583 void InstanceKlass::set_initialization_state_and_notify(ClassState state, TRAPS) {
1584 Handle h_init_lock(THREAD, init_lock());
1585 if (h_init_lock() != nullptr) {
1586 ObjectLocker ol(h_init_lock, THREAD);
1587 set_init_thread(nullptr); // reset _init_thread before changing _init_state
1588 set_init_state(state);
1589 fence_and_clear_init_lock();
1590 ol.notify_all(CHECK);
1591 } else {
1592 assert(h_init_lock() != nullptr, "The initialization state should never be set twice");
1593 set_init_thread(nullptr); // reset _init_thread before changing _init_state
1594 set_init_state(state);
1595 }
1596 }
1597
1598 void InstanceKlass::notify_strict_static_access(int field_index, bool is_writing, TRAPS) {
1599 guarantee(field_index >= 0 && field_index < fields_status()->length(), "valid field index");
1600 DEBUG_ONLY(FieldInfo debugfi = field(field_index));
1601 assert(debugfi.access_flags().is_strict(), "");
1602 assert(debugfi.access_flags().is_static(), "");
1603 FieldStatus& fs = *fields_status()->adr_at(field_index);
1604 LogTarget(Trace, class, init) lt;
1605 if (lt.is_enabled()) {
1606 ResourceMark rm(THREAD);
1607 LogStream ls(lt);
1608 FieldInfo fi = field(field_index);
1609 ls.print("notify %s %s %s%s ",
1610 external_name(), is_writing? "Write" : "Read",
1611 fs.is_strict_static_unset() ? "Unset" : "(set)",
1612 fs.is_strict_static_unread() ? "+Unread" : "");
1613 fi.print(&ls, constants());
1614 }
1615 if (fs.is_strict_static_unset()) {
1616 assert(fs.is_strict_static_unread(), "ClassFileParser resp.");
1617 // If it is not set, there are only two reasonable things we can do here:
1618 // - mark it set if this is putstatic
1619 // - throw an error (Read-Before-Write) if this is getstatic
1620
1621 // The unset state is (or should be) transient, and observable only in one
1622 // thread during the execution of <clinit>. Something is wrong here as this
1623 // should not be possible
1624 guarantee(is_reentrant_initialization(THREAD), "unscoped access to strict static");
1625 if (is_writing) {
1626 // clear the "unset" bit, since the field is actually going to be written
1627 fs.update_strict_static_unset(false);
1628 } else {
1629 // throw an IllegalStateException, since we are reading before writing
1630 // see also InstanceKlass::initialize_impl, Step 8 (at end)
1631 Symbol* bad_strict_static = field(field_index).name(constants());
1632 throw_strict_static_exception(bad_strict_static, "is unset before first read in", CHECK);
1633 }
1634 } else {
1635 // Ensure no write after read for final strict statics
1636 FieldInfo fi = field(field_index);
1637 bool is_final = fi.access_flags().is_final();
1638 if (is_final) {
1639 // no final write after read, so observing a constant freezes it, as if <clinit> ended early
1640 // (maybe we could trust the constant a little earlier, before <clinit> ends)
1641 if (is_writing && !fs.is_strict_static_unread()) {
1642 Symbol* bad_strict_static = fi.name(constants());
1643 throw_strict_static_exception(bad_strict_static, "is set after read (as final) in", CHECK);
1644 } else if (!is_writing && fs.is_strict_static_unread()) {
1645 fs.update_strict_static_unread(false);
1646 }
1647 }
1648 }
1649 }
1650
1651 void InstanceKlass::throw_strict_static_exception(Symbol* field_name, const char* when, TRAPS) {
1652 ResourceMark rm(THREAD);
1653 const char* msg = format_strict_static_message(field_name, when);
1654 THROW_MSG(vmSymbols::java_lang_IllegalStateException(), msg);
1655 }
1656
1657 const char* InstanceKlass::format_strict_static_message(Symbol* field_name, const char* when) {
1658 stringStream ss;
1659 ss.print("Strict static \"%s\" %s %s",
1660 field_name->as_C_string(),
1661 when == nullptr ? "is unset in" : when,
1662 external_name());
1663 return ss.as_string();
1664 }
1665
1666 // Update hierarchy. This is done before the new klass has been added to the SystemDictionary. The Compile_lock
1667 // is grabbed, to ensure that the compiler is not using the class hierarchy.
1668 void InstanceKlass::add_to_hierarchy(JavaThread* current) {
1669 assert(!SafepointSynchronize::is_at_safepoint(), "must NOT be at safepoint");
1670
1671 DeoptimizationScope deopt_scope;
1672 {
1673 MutexLocker ml(current, Compile_lock);
1674
1675 set_init_state(InstanceKlass::loaded);
1676 // make sure init_state store is already done.
1677 // The compiler reads the hierarchy outside of the Compile_lock.
1678 // Access ordering is used to add to hierarchy.
1679
1680 // Link into hierarchy.
1681 append_to_sibling_list(); // add to superklass/sibling list
1682 process_interfaces(); // handle all "implements" declarations
1683
1684 // Now mark all code that depended on old class hierarchy.
1685 // Note: must be done *after* linking k into the hierarchy (was bug 12/9/97)
1898 ResourceMark rm(THREAD);
1899 THROW_MSG(throwError ? vmSymbols::java_lang_InstantiationError()
1900 : vmSymbols::java_lang_InstantiationException(), external_name());
1901 }
1902 if (this == vmClasses::Class_klass()) {
1903 ResourceMark rm(THREAD);
1904 THROW_MSG(throwError ? vmSymbols::java_lang_IllegalAccessError()
1905 : vmSymbols::java_lang_IllegalAccessException(), external_name());
1906 }
1907 }
1908
1909 ArrayKlass* InstanceKlass::array_klass(int n, TRAPS) {
1910 // Need load-acquire for lock-free read
1911 if (array_klasses_acquire() == nullptr) {
1912
1913 // Recursively lock array allocation
1914 RecursiveLocker rl(MultiArray_lock, THREAD);
1915
1916 // Check if another thread created the array klass while we were waiting for the lock.
1917 if (array_klasses() == nullptr) {
1918 ObjArrayKlass* k = ObjArrayKlass::allocate_objArray_klass(class_loader_data(), 1, this, false, CHECK_NULL);
1919 // use 'release' to pair with lock-free load
1920 release_set_array_klasses(k);
1921 }
1922 }
1923
1924 // array_klasses() will always be set at this point
1925 ArrayKlass* ak = array_klasses();
1926 assert(ak != nullptr, "should be set");
1927 return ak->array_klass(n, THREAD);
1928 }
1929
1930 ArrayKlass* InstanceKlass::array_klass_or_null(int n) {
1931 // Need load-acquire for lock-free read
1932 ArrayKlass* ak = array_klasses_acquire();
1933 if (ak == nullptr) {
1934 return nullptr;
1935 } else {
1936 return ak->array_klass_or_null(n);
1937 }
1938 }
1939
1940 ArrayKlass* InstanceKlass::array_klass(TRAPS) {
1941 return array_klass(1, THREAD);
1942 }
1943
1944 ArrayKlass* InstanceKlass::array_klass_or_null() {
1945 return array_klass_or_null(1);
1946 }
1947
1948 static int call_class_initializer_counter = 0; // for debugging
1949
1950 Method* InstanceKlass::class_initializer() const {
1951 Method* clinit = find_method(
1952 vmSymbols::class_initializer_name(), vmSymbols::void_method_signature());
1953 if (clinit != nullptr && clinit->is_class_initializer()) {
1954 return clinit;
1955 }
1956 return nullptr;
1957 }
1958
1959 void InstanceKlass::call_class_initializer(TRAPS) {
1960 if (ReplayCompiles &&
1961 (ReplaySuppressInitializers == 1 ||
1962 (ReplaySuppressInitializers >= 2 && class_loader() != nullptr))) {
1963 // Hide the existence of the initializer for the purpose of replaying the compile
1964 return;
1965 }
1966
1967 #if INCLUDE_CDS
1968 // This is needed to ensure the consistency of the archived heap objects.
1969 if (has_aot_initialized_mirror() && CDSConfig::is_loading_heap()) {
1970 AOTClassInitializer::call_runtime_setup(THREAD, this);
1971 return;
1972 } else if (has_archived_enum_objs()) {
1973 assert(is_shared(), "must be");
2042
2043 void InstanceKlass::mask_for(const methodHandle& method, int bci,
2044 InterpreterOopMap* entry_for) {
2045 // Lazily create the _oop_map_cache at first request.
2046 // Load_acquire is needed to safely get instance published with CAS by another thread.
2047 OopMapCache* oop_map_cache = Atomic::load_acquire(&_oop_map_cache);
2048 if (oop_map_cache == nullptr) {
2049 // Try to install new instance atomically.
2050 oop_map_cache = new OopMapCache();
2051 OopMapCache* other = Atomic::cmpxchg(&_oop_map_cache, (OopMapCache*)nullptr, oop_map_cache);
2052 if (other != nullptr) {
2053 // Someone else managed to install before us, ditch local copy and use the existing one.
2054 delete oop_map_cache;
2055 oop_map_cache = other;
2056 }
2057 }
2058 // _oop_map_cache is constant after init; lookup below does its own locking.
2059 oop_map_cache->lookup(method, bci, entry_for);
2060 }
2061
2062
2063 FieldInfo InstanceKlass::field(int index) const {
2064 for (AllFieldStream fs(this); !fs.done(); fs.next()) {
2065 if (fs.index() == index) {
2066 return fs.to_FieldInfo();
2067 }
2068 }
2069 fatal("Field not found");
2070 return FieldInfo();
2071 }
2072
2073 bool InstanceKlass::find_local_field(Symbol* name, Symbol* sig, fieldDescriptor* fd) const {
2074 for (JavaFieldStream fs(this); !fs.done(); fs.next()) {
2075 Symbol* f_name = fs.name();
2076 Symbol* f_sig = fs.signature();
2077 if (f_name == name && f_sig == sig) {
2078 fd->reinitialize(const_cast<InstanceKlass*>(this), fs.to_FieldInfo());
2079 return true;
2080 }
2081 }
2123
2124 Klass* InstanceKlass::find_field(Symbol* name, Symbol* sig, bool is_static, fieldDescriptor* fd) const {
2125 // search order according to newest JVM spec (5.4.3.2, p.167).
2126 // 1) search for field in current klass
2127 if (find_local_field(name, sig, fd)) {
2128 if (fd->is_static() == is_static) return const_cast<InstanceKlass*>(this);
2129 }
2130 // 2) search for field recursively in direct superinterfaces
2131 if (is_static) {
2132 Klass* intf = find_interface_field(name, sig, fd);
2133 if (intf != nullptr) return intf;
2134 }
2135 // 3) apply field lookup recursively if superclass exists
2136 { Klass* supr = super();
2137 if (supr != nullptr) return InstanceKlass::cast(supr)->find_field(name, sig, is_static, fd);
2138 }
2139 // 4) otherwise field lookup fails
2140 return nullptr;
2141 }
2142
2143 bool InstanceKlass::contains_field_offset(int offset) {
2144 if (this->is_inline_klass()) {
2145 InlineKlass* vk = InlineKlass::cast(this);
2146 return offset >= vk->payload_offset() && offset < (vk->payload_offset() + vk->payload_size_in_bytes());
2147 } else {
2148 fieldDescriptor fd;
2149 return find_field_from_offset(offset, false, &fd);
2150 }
2151 }
2152
2153 bool InstanceKlass::find_local_field_from_offset(int offset, bool is_static, fieldDescriptor* fd) const {
2154 for (JavaFieldStream fs(this); !fs.done(); fs.next()) {
2155 if (fs.offset() == offset) {
2156 fd->reinitialize(const_cast<InstanceKlass*>(this), fs.to_FieldInfo());
2157 if (fd->is_static() == is_static) return true;
2158 }
2159 }
2160 return false;
2161 }
2162
2163
2164 bool InstanceKlass::find_field_from_offset(int offset, bool is_static, fieldDescriptor* fd) const {
2165 Klass* klass = const_cast<InstanceKlass*>(this);
2166 while (klass != nullptr) {
2167 if (InstanceKlass::cast(klass)->find_local_field_from_offset(offset, is_static, fd)) {
2168 return true;
2169 }
2170 klass = klass->super();
2171 }
2515 }
2516
2517 // uncached_lookup_method searches both the local class methods array and all
2518 // superclasses methods arrays, skipping any overpass methods in superclasses,
2519 // and possibly skipping private methods.
2520 Method* InstanceKlass::uncached_lookup_method(const Symbol* name,
2521 const Symbol* signature,
2522 OverpassLookupMode overpass_mode,
2523 PrivateLookupMode private_mode) const {
2524 OverpassLookupMode overpass_local_mode = overpass_mode;
2525 const Klass* klass = this;
2526 while (klass != nullptr) {
2527 Method* const method = InstanceKlass::cast(klass)->find_method_impl(name,
2528 signature,
2529 overpass_local_mode,
2530 StaticLookupMode::find,
2531 private_mode);
2532 if (method != nullptr) {
2533 return method;
2534 }
2535 if (name == vmSymbols::object_initializer_name()) {
2536 break; // <init> is never inherited
2537 }
2538 klass = klass->super();
2539 overpass_local_mode = OverpassLookupMode::skip; // Always ignore overpass methods in superclasses
2540 }
2541 return nullptr;
2542 }
2543
2544 #ifdef ASSERT
2545 // search through class hierarchy and return true if this class or
2546 // one of the superclasses was redefined
2547 bool InstanceKlass::has_redefined_this_or_super() const {
2548 const Klass* klass = this;
2549 while (klass != nullptr) {
2550 if (InstanceKlass::cast(klass)->has_been_redefined()) {
2551 return true;
2552 }
2553 klass = klass->super();
2554 }
2555 return false;
2556 }
2557 #endif
2916 int itable_offset_in_words = (int)(start_of_itable() - (intptr_t*)this);
2917
2918 int nof_interfaces = (method_table_offset_in_words - itable_offset_in_words)
2919 / itableOffsetEntry::size();
2920
2921 for (int i = 0; i < nof_interfaces; i ++, ioe ++) {
2922 if (ioe->interface_klass() != nullptr) {
2923 it->push(ioe->interface_klass_addr());
2924 itableMethodEntry* ime = ioe->first_method_entry(this);
2925 int n = klassItable::method_count_for_interface(ioe->interface_klass());
2926 for (int index = 0; index < n; index ++) {
2927 it->push(ime[index].method_addr());
2928 }
2929 }
2930 }
2931 }
2932
2933 it->push(&_nest_host);
2934 it->push(&_nest_members);
2935 it->push(&_permitted_subclasses);
2936 it->push(&_loadable_descriptors);
2937 it->push(&_record_components);
2938 it->push(&_inline_layout_info_array, MetaspaceClosure::_writable);
2939 }
2940
2941 #if INCLUDE_CDS
2942 void InstanceKlass::remove_unshareable_info() {
2943
2944 if (is_linked()) {
2945 assert(can_be_verified_at_dumptime(), "must be");
2946 // Remember this so we can avoid walking the hierarchy at runtime.
2947 set_verified_at_dump_time();
2948 }
2949
2950 Klass::remove_unshareable_info();
2951
2952 if (SystemDictionaryShared::has_class_failed_verification(this)) {
2953 // Classes are attempted to link during dumping and may fail,
2954 // but these classes are still in the dictionary and class list in CLD.
2955 // If the class has failed verification, there is nothing else to remove.
2956 return;
2957 }
2958
2964
2965 { // Otherwise this needs to take out the Compile_lock.
2966 assert(SafepointSynchronize::is_at_safepoint(), "only called at safepoint");
2967 init_implementor();
2968 }
2969
2970 // Call remove_unshareable_info() on other objects that belong to this class, except
2971 // for constants()->remove_unshareable_info(), which is called in a separate pass in
2972 // ArchiveBuilder::make_klasses_shareable(),
2973
2974 for (int i = 0; i < methods()->length(); i++) {
2975 Method* m = methods()->at(i);
2976 m->remove_unshareable_info();
2977 }
2978
2979 // do array classes also.
2980 if (array_klasses() != nullptr) {
2981 array_klasses()->remove_unshareable_info();
2982 }
2983
2984 // These are not allocated from metaspace. They are safe to set to nullptr.
2985 _source_debug_extension = nullptr;
2986 _dep_context = nullptr;
2987 _osr_nmethods_head = nullptr;
2988 #if INCLUDE_JVMTI
2989 _breakpoints = nullptr;
2990 _previous_versions = nullptr;
2991 _cached_class_file = nullptr;
2992 _jvmti_cached_class_field_map = nullptr;
2993 #endif
2994
2995 _init_thread = nullptr;
2996 _methods_jmethod_ids = nullptr;
2997 _jni_ids = nullptr;
2998 _oop_map_cache = nullptr;
2999 if (CDSConfig::is_dumping_method_handles() && HeapShared::is_lambda_proxy_klass(this)) {
3000 // keep _nest_host
3001 } else {
3002 // clear _nest_host to ensure re-load at runtime
3003 _nest_host = nullptr;
3004 }
3053 void InstanceKlass::compute_has_loops_flag_for_methods() {
3054 Array<Method*>* methods = this->methods();
3055 for (int index = 0; index < methods->length(); ++index) {
3056 Method* m = methods->at(index);
3057 if (!m->is_overpass()) { // work around JDK-8305771
3058 m->compute_has_loops_flag();
3059 }
3060 }
3061 }
3062
3063 void InstanceKlass::restore_unshareable_info(ClassLoaderData* loader_data, Handle protection_domain,
3064 PackageEntry* pkg_entry, TRAPS) {
3065 // InstanceKlass::add_to_hierarchy() sets the init_state to loaded
3066 // before the InstanceKlass is added to the SystemDictionary. Make
3067 // sure the current state is <loaded.
3068 assert(!is_loaded(), "invalid init state");
3069 assert(!shared_loading_failed(), "Must not try to load failed class again");
3070 set_package(loader_data, pkg_entry, CHECK);
3071 Klass::restore_unshareable_info(loader_data, protection_domain, CHECK);
3072
3073 if (is_inline_klass()) {
3074 InlineKlass::cast(this)->initialize_calling_convention(CHECK);
3075 }
3076
3077 Array<Method*>* methods = this->methods();
3078 int num_methods = methods->length();
3079 for (int index = 0; index < num_methods; ++index) {
3080 methods->at(index)->restore_unshareable_info(CHECK);
3081 }
3082 #if INCLUDE_JVMTI
3083 if (JvmtiExport::has_redefined_a_class()) {
3084 // Reinitialize vtable because RedefineClasses may have changed some
3085 // entries in this vtable for super classes so the CDS vtable might
3086 // point to old or obsolete entries. RedefineClasses doesn't fix up
3087 // vtables in the shared system dictionary, only the main one.
3088 // It also redefines the itable too so fix that too.
3089 // First fix any default methods that point to a super class that may
3090 // have been redefined.
3091 bool trace_name_printed = false;
3092 adjust_default_methods(&trace_name_printed);
3093 if (verified_at_dump_time()) {
3094 // Initialize vtable and itable for classes which can be verified at dump time.
3095 // Unlinked classes such as old classes with major version < 50 cannot be verified
3096 // at dump time.
3097 vtable().initialize_vtable();
3098 itable().initialize_itable();
3099 }
3100 }
3101 #endif // INCLUDE_JVMTI
3102
3103 // restore constant pool resolved references
3104 constants()->restore_unshareable_info(CHECK);
3105
3106 if (array_klasses() != nullptr) {
3107 // To get a consistent list of classes we need MultiArray_lock to ensure
3108 // array classes aren't observed while they are being restored.
3109 RecursiveLocker rl(MultiArray_lock, THREAD);
3110 assert(this == ObjArrayKlass::cast(array_klasses())->bottom_klass(), "sanity");
3111 // Array classes have null protection domain.
3112 // --> see ArrayKlass::complete_create_array_klass()
3113 array_klasses()->restore_unshareable_info(class_loader_data(), Handle(), CHECK);
3114 }
3115
3116 // Initialize @ValueBased class annotation if not already set in the archived klass.
3117 if (DiagnoseSyncOnValueBasedClasses && has_value_based_class_annotation() && !is_value_based()) {
3118 set_is_value_based();
3119 }
3120 }
3121
3122 // Check if a class or any of its supertypes has a version older than 50.
3123 // CDS will not perform verification of old classes during dump time because
3124 // without changing the old verifier, the verification constraint cannot be
3125 // retrieved during dump time.
3126 // Verification of archived old classes will be performed during run time.
3127 bool InstanceKlass::can_be_verified_at_dumptime() const {
3128 if (MetaspaceShared::is_in_shared_metaspace(this)) {
3129 // This is a class that was dumped into the base archive, so we know
3130 // it was verified at dump time.
3276 } else {
3277 // Adding one to the attribute length in order to store a null terminator
3278 // character could cause an overflow because the attribute length is
3279 // already coded with an u4 in the classfile, but in practice, it's
3280 // unlikely to happen.
3281 assert((length+1) > length, "Overflow checking");
3282 char* sde = NEW_C_HEAP_ARRAY(char, (length + 1), mtClass);
3283 for (int i = 0; i < length; i++) {
3284 sde[i] = array[i];
3285 }
3286 sde[length] = '\0';
3287 _source_debug_extension = sde;
3288 }
3289 }
3290
3291 Symbol* InstanceKlass::generic_signature() const { return _constants->generic_signature(); }
3292 u2 InstanceKlass::generic_signature_index() const { return _constants->generic_signature_index(); }
3293 void InstanceKlass::set_generic_signature_index(u2 sig_index) { _constants->set_generic_signature_index(sig_index); }
3294
3295 const char* InstanceKlass::signature_name() const {
3296 return signature_name_of_carrier(JVM_SIGNATURE_CLASS);
3297 }
3298
3299 const char* InstanceKlass::signature_name_of_carrier(char c) const {
3300 // Get the internal name as a c string
3301 const char* src = (const char*) (name()->as_C_string());
3302 const int src_length = (int)strlen(src);
3303
3304 char* dest = NEW_RESOURCE_ARRAY(char, src_length + 3);
3305
3306 // Add L or Q as type indicator
3307 int dest_index = 0;
3308 dest[dest_index++] = c;
3309
3310 // Add the actual class name
3311 for (int src_index = 0; src_index < src_length; ) {
3312 dest[dest_index++] = src[src_index++];
3313 }
3314
3315 if (is_hidden()) { // Replace the last '+' with a '.'.
3316 for (int index = (int)src_length; index > 0; index--) {
3317 if (dest[index] == '+') {
3318 dest[index] = JVM_SIGNATURE_DOT;
3319 break;
3320 }
3321 }
3322 }
3323
3324 // Add the semicolon and the null
3325 dest[dest_index++] = JVM_SIGNATURE_ENDCLASS;
3326 dest[dest_index] = '\0';
3327 return dest;
3328 }
3569 bool InstanceKlass::find_inner_classes_attr(int* ooff, int* noff, TRAPS) const {
3570 constantPoolHandle i_cp(THREAD, constants());
3571 for (InnerClassesIterator iter(this); !iter.done(); iter.next()) {
3572 int ioff = iter.inner_class_info_index();
3573 if (ioff != 0) {
3574 // Check to see if the name matches the class we're looking for
3575 // before attempting to find the class.
3576 if (i_cp->klass_name_at_matches(this, ioff)) {
3577 Klass* inner_klass = i_cp->klass_at(ioff, CHECK_false);
3578 if (this == inner_klass) {
3579 *ooff = iter.outer_class_info_index();
3580 *noff = iter.inner_name_index();
3581 return true;
3582 }
3583 }
3584 }
3585 }
3586 return false;
3587 }
3588
3589 void InstanceKlass::check_can_be_annotated_with_NullRestricted(InstanceKlass* type, Symbol* container_klass_name, TRAPS) {
3590 assert(type->is_instance_klass(), "Sanity check");
3591 if (type->is_identity_class()) {
3592 ResourceMark rm(THREAD);
3593 THROW_MSG(vmSymbols::java_lang_IncompatibleClassChangeError(),
3594 err_msg("Class %s expects class %s to be a value class, but it is an identity class",
3595 container_klass_name->as_C_string(),
3596 type->external_name()));
3597 }
3598
3599 if (type->is_abstract()) {
3600 ResourceMark rm(THREAD);
3601 THROW_MSG(vmSymbols::java_lang_IncompatibleClassChangeError(),
3602 err_msg("Class %s expects class %s to be concrete value type, but it is an abstract class",
3603 container_klass_name->as_C_string(),
3604 type->external_name()));
3605 }
3606 }
3607
3608 InstanceKlass* InstanceKlass::compute_enclosing_class(bool* inner_is_member, TRAPS) const {
3609 InstanceKlass* outer_klass = nullptr;
3610 *inner_is_member = false;
3611 int ooff = 0, noff = 0;
3612 bool has_inner_classes_attr = find_inner_classes_attr(&ooff, &noff, THREAD);
3613 if (has_inner_classes_attr) {
3614 constantPoolHandle i_cp(THREAD, constants());
3615 if (ooff != 0) {
3616 Klass* ok = i_cp->klass_at(ooff, CHECK_NULL);
3617 if (!ok->is_instance_klass()) {
3618 // If the outer class is not an instance klass then it cannot have
3619 // declared any inner classes.
3620 ResourceMark rm(THREAD);
3621 // Names are all known to be < 64k so we know this formatted message is not excessively large.
3622 Exceptions::fthrow(
3623 THREAD_AND_LOCATION,
3624 vmSymbols::java_lang_IncompatibleClassChangeError(),
3625 "%s and %s disagree on InnerClasses attribute",
3626 ok->external_name(),
3627 external_name());
3654 u2 InstanceKlass::compute_modifier_flags() const {
3655 u2 access = access_flags().as_unsigned_short();
3656
3657 // But check if it happens to be member class.
3658 InnerClassesIterator iter(this);
3659 for (; !iter.done(); iter.next()) {
3660 int ioff = iter.inner_class_info_index();
3661 // Inner class attribute can be zero, skip it.
3662 // Strange but true: JVM spec. allows null inner class refs.
3663 if (ioff == 0) continue;
3664
3665 // only look at classes that are already loaded
3666 // since we are looking for the flags for our self.
3667 Symbol* inner_name = constants()->klass_name_at(ioff);
3668 if (name() == inner_name) {
3669 // This is really a member class.
3670 access = iter.inner_access_flags();
3671 break;
3672 }
3673 }
3674 return access;
3675 }
3676
3677 jint InstanceKlass::jvmti_class_status() const {
3678 jint result = 0;
3679
3680 if (is_linked()) {
3681 result |= JVMTI_CLASS_STATUS_VERIFIED | JVMTI_CLASS_STATUS_PREPARED;
3682 }
3683
3684 if (is_initialized()) {
3685 assert(is_linked(), "Class status is not consistent");
3686 result |= JVMTI_CLASS_STATUS_INITIALIZED;
3687 }
3688 if (is_in_error_state()) {
3689 result |= JVMTI_CLASS_STATUS_ERROR;
3690 }
3691 return result;
3692 }
3693
3694 Method* InstanceKlass::method_at_itable(InstanceKlass* holder, int index, TRAPS) {
3908 }
3909 osr = osr->osr_link();
3910 }
3911
3912 assert(match_level == false || best == nullptr, "shouldn't pick up anything if match_level is set");
3913 if (best != nullptr && best->comp_level() >= comp_level) {
3914 return best;
3915 }
3916 return nullptr;
3917 }
3918
3919 // -----------------------------------------------------------------------------------------------------
3920 // Printing
3921
3922 #define BULLET " - "
3923
3924 static const char* state_names[] = {
3925 "allocated", "loaded", "linked", "being_initialized", "fully_initialized", "initialization_error"
3926 };
3927
3928 static void print_vtable(address self, intptr_t* start, int len, outputStream* st) {
3929 ResourceMark rm;
3930 int* forward_refs = NEW_RESOURCE_ARRAY(int, len);
3931 for (int i = 0; i < len; i++) forward_refs[i] = 0;
3932 for (int i = 0; i < len; i++) {
3933 intptr_t e = start[i];
3934 st->print("%d : " INTPTR_FORMAT, i, e);
3935 if (forward_refs[i] != 0) {
3936 int from = forward_refs[i];
3937 int off = (int) start[from];
3938 st->print(" (offset %d <= [%d])", off, from);
3939 }
3940 if (MetaspaceObj::is_valid((Metadata*)e)) {
3941 st->print(" ");
3942 ((Metadata*)e)->print_value_on(st);
3943 } else if (self != nullptr && e > 0 && e < 0x10000) {
3944 address location = self + e;
3945 int index = (int)((intptr_t*)location - start);
3946 st->print(" (offset %d => [%d])", (int)e, index);
3947 if (index >= 0 && index < len)
3948 forward_refs[index] = i;
3949 }
3950 st->cr();
3951 }
3952 }
3953
3954 static void print_vtable(vtableEntry* start, int len, outputStream* st) {
3955 return print_vtable(nullptr, reinterpret_cast<intptr_t*>(start), len, st);
3956 }
3957
3958 template<typename T>
3959 static void print_array_on(outputStream* st, Array<T>* array) {
3960 if (array == nullptr) { st->print_cr("nullptr"); return; }
3961 array->print_value_on(st); st->cr();
3962 if (Verbose || WizardMode) {
3963 for (int i = 0; i < array->length(); i++) {
3964 st->print("%d : ", i); array->at(i)->print_value_on(st); st->cr();
3965 }
3966 }
3967 }
3968
3969 static void print_array_on(outputStream* st, Array<int>* array) {
3970 if (array == nullptr) { st->print_cr("nullptr"); return; }
3971 array->print_value_on(st); st->cr();
3972 if (Verbose || WizardMode) {
3973 for (int i = 0; i < array->length(); i++) {
3974 st->print("%d : %d", i, array->at(i)); st->cr();
3975 }
3976 }
3977 }
3978
3979 const char* InstanceKlass::init_state_name() const {
3980 return state_names[init_state()];
3981 }
3982
3983 void InstanceKlass::print_on(outputStream* st) const {
3984 assert(is_klass(), "must be klass");
3985 Klass::print_on(st);
3986
3987 st->print(BULLET"instance size: %d", size_helper()); st->cr();
3988 st->print(BULLET"klass size: %d", size()); st->cr();
3989 st->print(BULLET"access: "); access_flags().print_on(st); st->cr();
3990 st->print(BULLET"flags: "); _misc_flags.print_on(st); st->cr();
3991 st->print(BULLET"state: "); st->print_cr("%s", init_state_name());
3992 st->print(BULLET"name: "); name()->print_value_on(st); st->cr();
3993 st->print(BULLET"super: "); Metadata::print_value_on_maybe_null(st, super()); st->cr();
3994 st->print(BULLET"sub: ");
3995 Klass* sub = subklass();
3996 int n;
3997 for (n = 0; sub != nullptr; n++, sub = sub->next_sibling()) {
3998 if (n < MaxSubklassPrintSize) {
3999 sub->print_value_on(st);
4000 st->print(" ");
4001 }
4002 }
4003 if (n >= MaxSubklassPrintSize) st->print("(%zd more klasses...)", n - MaxSubklassPrintSize);
4004 st->cr();
4005
4006 if (is_interface()) {
4007 st->print_cr(BULLET"nof implementors: %d", nof_implementors());
4008 if (nof_implementors() == 1) {
4009 st->print_cr(BULLET"implementor: ");
4010 st->print(" ");
4011 implementor()->print_value_on(st);
4012 st->cr();
4013 }
4014 }
4015
4016 st->print(BULLET"arrays: "); Metadata::print_value_on_maybe_null(st, array_klasses()); st->cr();
4017 st->print(BULLET"methods: "); print_array_on(st, methods());
4018 st->print(BULLET"method ordering: "); print_array_on(st, method_ordering());
4019 if (default_methods() != nullptr) {
4020 st->print(BULLET"default_methods: "); print_array_on(st, default_methods());
4021 }
4022 print_on_maybe_null(st, BULLET"default vtable indices: ", default_vtable_indices());
4023 st->print(BULLET"local interfaces: "); local_interfaces()->print_value_on(st); st->cr();
4024 st->print(BULLET"trans. interfaces: "); transitive_interfaces()->print_value_on(st); st->cr();
4025
4026 st->print(BULLET"secondary supers: "); secondary_supers()->print_value_on(st); st->cr();
4027
4028 st->print(BULLET"hash_slot: %d", hash_slot()); st->cr();
4029 st->print(BULLET"secondary bitmap: " UINTX_FORMAT_X_0, _secondary_supers_bitmap); st->cr();
4030
4031 if (secondary_supers() != nullptr) {
4032 if (Verbose) {
4033 bool is_hashed = (_secondary_supers_bitmap != SECONDARY_SUPERS_BITMAP_FULL);
4034 st->print_cr(BULLET"---- secondary supers (%d words):", _secondary_supers->length());
4035 for (int i = 0; i < _secondary_supers->length(); i++) {
4036 ResourceMark rm; // for external_name()
4037 Klass* secondary_super = _secondary_supers->at(i);
4038 st->print(BULLET"%2d:", i);
4039 if (is_hashed) {
4040 int home_slot = compute_home_slot(secondary_super, _secondary_supers_bitmap);
4060 print_on_maybe_null(st, BULLET"field type annotations: ", fields_type_annotations());
4061 {
4062 bool have_pv = false;
4063 // previous versions are linked together through the InstanceKlass
4064 for (InstanceKlass* pv_node = previous_versions();
4065 pv_node != nullptr;
4066 pv_node = pv_node->previous_versions()) {
4067 if (!have_pv)
4068 st->print(BULLET"previous version: ");
4069 have_pv = true;
4070 pv_node->constants()->print_value_on(st);
4071 }
4072 if (have_pv) st->cr();
4073 }
4074
4075 print_on_maybe_null(st, BULLET"generic signature: ", generic_signature());
4076 st->print(BULLET"inner classes: "); inner_classes()->print_value_on(st); st->cr();
4077 st->print(BULLET"nest members: "); nest_members()->print_value_on(st); st->cr();
4078 print_on_maybe_null(st, BULLET"record components: ", record_components());
4079 st->print(BULLET"permitted subclasses: "); permitted_subclasses()->print_value_on(st); st->cr();
4080 st->print(BULLET"loadable descriptors: "); loadable_descriptors()->print_value_on(st); st->cr();
4081 if (java_mirror() != nullptr) {
4082 st->print(BULLET"java mirror: ");
4083 java_mirror()->print_value_on(st);
4084 st->cr();
4085 } else {
4086 st->print_cr(BULLET"java mirror: null");
4087 }
4088 st->print(BULLET"vtable length %d (start addr: " PTR_FORMAT ")", vtable_length(), p2i(start_of_vtable())); st->cr();
4089 if (vtable_length() > 0 && (Verbose || WizardMode)) print_vtable(start_of_vtable(), vtable_length(), st);
4090 st->print(BULLET"itable length %d (start addr: " PTR_FORMAT ")", itable_length(), p2i(start_of_itable())); st->cr();
4091 if (itable_length() > 0 && (Verbose || WizardMode)) print_vtable(nullptr, start_of_itable(), itable_length(), st);
4092 st->print_cr(BULLET"---- static fields (%d words):", static_field_size());
4093
4094 FieldPrinter print_static_field(st);
4095 ((InstanceKlass*)this)->do_local_static_fields(&print_static_field);
4096 st->print_cr(BULLET"---- non-static fields (%d words):", nonstatic_field_size());
4097 FieldPrinter print_nonstatic_field(st);
4098 InstanceKlass* ik = const_cast<InstanceKlass*>(this);
4099 ik->print_nonstatic_fields(&print_nonstatic_field);
4100
4101 st->print(BULLET"non-static oop maps (%d entries): ", nonstatic_oop_map_count());
4102 OopMapBlock* map = start_of_nonstatic_oop_maps();
4103 OopMapBlock* end_map = map + nonstatic_oop_map_count();
4104 while (map < end_map) {
4105 st->print("%d-%d ", map->offset(), map->offset() + heapOopSize*(map->count() - 1));
4106 map++;
4107 }
4108 st->cr();
4109 }
4110
4111 void InstanceKlass::print_value_on(outputStream* st) const {
4112 assert(is_klass(), "must be klass");
4113 if (Verbose || WizardMode) access_flags().print_on(st);
4114 name()->print_value_on(st);
4115 }
4116
4117 void FieldPrinter::do_field(fieldDescriptor* fd) {
4118 for (int i = 0; i < _indent; i++) _st->print(" ");
4119 _st->print(BULLET);
4120 if (_obj == nullptr) {
4121 fd->print_on(_st, _base_offset);
4122 _st->cr();
4123 } else {
4124 fd->print_on_for(_st, _obj, _indent, _base_offset);
4125 if (!fd->field_flags().is_flat()) _st->cr();
4126 }
4127 }
4128
4129
4130 void InstanceKlass::oop_print_on(oop obj, outputStream* st, int indent, int base_offset) {
4131 Klass::oop_print_on(obj, st);
4132
4133 if (this == vmClasses::String_klass()) {
4134 typeArrayOop value = java_lang_String::value(obj);
4135 juint length = java_lang_String::length(obj);
4136 if (value != nullptr &&
4137 value->is_typeArray() &&
4138 length <= (juint) value->length()) {
4139 st->print(BULLET"string: ");
4140 java_lang_String::print(obj, st);
4141 st->cr();
4142 }
4143 }
4144
4145 st->print_cr(BULLET"---- fields (total size %zu words):", oop_size(obj));
4146 FieldPrinter print_field(st, obj, indent, base_offset);
4147 print_nonstatic_fields(&print_field);
4148
4149 if (this == vmClasses::Class_klass()) {
4150 st->print(BULLET"signature: ");
4151 java_lang_Class::print_signature(obj, st);
4152 st->cr();
4153 Klass* real_klass = java_lang_Class::as_Klass(obj);
4154 if (real_klass != nullptr && real_klass->is_instance_klass()) {
4155 st->print_cr(BULLET"---- static fields (%d):", java_lang_Class::static_oop_field_count(obj));
4156 InstanceKlass::cast(real_klass)->do_local_static_fields(&print_field);
4157 }
4158 } else if (this == vmClasses::MethodType_klass()) {
4159 st->print(BULLET"signature: ");
4160 java_lang_invoke_MethodType::print_signature(obj, st);
4161 st->cr();
4162 }
4163 }
4164
4165 #ifndef PRODUCT
4166
|